Machine.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. 
  2. #include "Machine.h"
  3. #include "expression.h"
  4. #include "../../../DFPSR/api/fileAPI.h"
  5. using namespace dsr;
  6. #define STRING_EXPR(FIRST_TOKEN, LAST_TOKEN) evaluateExpression(target, tokens, FIRST_TOKEN, LAST_TOKEN)
  7. #define INTEGER_EXPR(FIRST_TOKEN, LAST_TOKEN) expression_interpretAsInteger(STRING_EXPR(FIRST_TOKEN, LAST_TOKEN))
  8. #define PATH_EXPR(FIRST_TOKEN, LAST_TOKEN) file_getTheoreticalAbsolutePath(STRING_EXPR(FIRST_TOKEN, LAST_TOKEN), fromPath)
  9. int64_t findFlag(const Machine &target, const dsr::ReadableString &key) {
  10. for (int64_t f = 0; f < target.variables.length(); f++) {
  11. if (string_caseInsensitiveMatch(key, target.variables[f].key)) {
  12. return f;
  13. }
  14. }
  15. return -1;
  16. }
  17. ReadableString getFlag(const Machine &target, const dsr::ReadableString &key, const dsr::ReadableString &defaultValue) {
  18. int64_t existingIndex = findFlag(target, key);
  19. if (existingIndex == -1) {
  20. return defaultValue;
  21. } else {
  22. return target.variables[existingIndex].value;
  23. }
  24. }
  25. int64_t getFlagAsInteger(const Machine &target, const dsr::ReadableString &key, int64_t defaultValue) {
  26. int64_t existingIndex = findFlag(target, key);
  27. if (existingIndex == -1) {
  28. return defaultValue;
  29. } else {
  30. return string_toInteger(target.variables[existingIndex].value);
  31. }
  32. }
  33. void assignValue(Machine &target, const dsr::ReadableString &key, const dsr::ReadableString &value, bool inherited) {
  34. int64_t existingIndex = findFlag(target, key);
  35. if (existingIndex == -1) {
  36. target.variables.pushConstruct(string_upperCase(key), expression_unwrapIfNeeded(value), inherited);
  37. } else {
  38. target.variables[existingIndex].value = expression_unwrapIfNeeded(value);
  39. if (inherited) {
  40. target.variables[existingIndex].inherited = true;
  41. }
  42. }
  43. }
  44. static void flushToken(List<String> &targetTokens, String &currentToken) {
  45. if (string_length(currentToken) > 0) {
  46. targetTokens.push(currentToken);
  47. currentToken = U"";
  48. }
  49. }
  50. static String evaluateExpression(Machine &target, List<String> &tokens, int64_t startTokenIndex, int64_t endTokenIndex) {
  51. return expression_evaluate(tokens, startTokenIndex, endTokenIndex, [&target](ReadableString identifier) -> String {
  52. return getFlag(target, identifier, U"");
  53. });
  54. }
  55. // Copy inherited variables from parent to child.
  56. static void inheritMachine(Machine &child, const Machine &parent) {
  57. for (int64_t v = 0; v < parent.variables.length(); v++) {
  58. String key = string_upperCase(parent.variables[v].key);
  59. if (parent.variables[v].inherited) {
  60. child.variables.push(parent.variables[v]);
  61. }
  62. }
  63. }
  64. static void interpretLine(SessionContext &output, Machine &target, List<String> &tokens, const dsr::ReadableString &fromPath) {
  65. if (tokens.length() > 0) {
  66. bool activeLine = target.activeStackDepth >= target.currentStackDepth;
  67. /*
  68. printText(activeLine ? U"interpret:" : U"ignore:");
  69. for (int64_t t = 0; t < tokens.length(); t++) {
  70. printText(U" [", tokens[t], U"]");
  71. }
  72. printText(U"\n");
  73. */
  74. ReadableString first = expression_getToken(tokens, 0);
  75. ReadableString second = expression_getToken(tokens, 1);
  76. if (activeLine) {
  77. // TODO: Implement elseif and else cases using a list as a virtual stack,
  78. // to remember at which layer the else cases have already been consumed by a true evaluation.
  79. // TODO: Remember at which depth the script entered, so that importing something can't leave the rest inside of a dangling if or else by accident.
  80. if (string_caseInsensitiveMatch(first, U"import")) {
  81. // Get path relative to importing script's path.
  82. String importPath = PATH_EXPR(1, tokens.length() - 1);
  83. evaluateScript(output, target, importPath);
  84. if (tokens.length() > 2) { printText(U"Unused tokens after import!\n");}
  85. } else if (string_caseInsensitiveMatch(first, U"if")) {
  86. // Being if statement
  87. bool active = INTEGER_EXPR(1, tokens.length() - 1);
  88. if (active) {
  89. target.activeStackDepth++;
  90. }
  91. target.currentStackDepth++;
  92. } else if (string_caseInsensitiveMatch(first, U"end") && string_caseInsensitiveMatch(second, U"if")) {
  93. // End if statement
  94. target.currentStackDepth--;
  95. target.activeStackDepth = target.currentStackDepth;
  96. } else if (string_caseInsensitiveMatch(first, U"crawl")) {
  97. // The right hand expression is evaluated into a path relative to the build script and used as the root for searching for source code.
  98. target.crawlOrigins.push(PATH_EXPR(1, tokens.length() - 1));
  99. } else if (string_caseInsensitiveMatch(first, U"build")) {
  100. // Build one or more other projects from a project file or folder path, as dependencies.
  101. // Having the same external project built twice during the same session is not allowed.
  102. // Evaluate arguments recursively, but let the analyzer do the work.
  103. Machine childSettings;
  104. inheritMachine(childSettings, target);
  105. String projectPath = file_getTheoreticalAbsolutePath(expression_unwrapIfNeeded(second), fromPath); // Use the second token as the folder path.
  106. argumentsToSettings(childSettings, tokens, 2); // Send all tokens after the second token as input arguments to buildProjects.
  107. printText("Building ", second, " from ", fromPath, " which is ", projectPath, "\n");
  108. target.otherProjectPaths.push(projectPath);
  109. target.otherProjectSettings.push(childSettings);
  110. } else if (string_caseInsensitiveMatch(first, U"link")) {
  111. // Only the path name itself is needed, so any redundant -l prefixes will be stripped away.
  112. String libraryName = STRING_EXPR(1, tokens.length() - 1);
  113. if (libraryName[0] == U'-' && (libraryName[1] == U'l' || libraryName[1] == U'L')) {
  114. libraryName = string_after(libraryName, 2);
  115. }
  116. target.linkerFlags.push(libraryName);
  117. } else if (string_caseInsensitiveMatch(first, U"compilerflag")) {
  118. target.compilerFlags.push(STRING_EXPR(1, tokens.length() - 1));
  119. } else if (string_caseInsensitiveMatch(first, U"message")) {
  120. // Print a message while evaluating the build script.
  121. // This is not done while actually compiling, so it will not know if compilation and linking worked or not.
  122. printText(STRING_EXPR(1, tokens.length() - 1));
  123. } else {
  124. if (tokens.length() == 1) {
  125. // Mentioning an identifier without assigning anything will assign it to one as a boolean flag.
  126. assignValue(target, first, U"1", false);
  127. } else if (string_match(second, U"=")) {
  128. // TODO: Create in-place math and string operations with different types of assignments.
  129. // Maybe use a different syntax beginning with a keyword?
  130. // TODO: Look for the assignment operator dynamically if references to collection elements are allowed as l-value expressions.
  131. // Using an equality sign replaces any previous value of the variable.
  132. assignValue(target, first, STRING_EXPR(2, tokens.length() - 1), false);
  133. } else {
  134. // TODO: Give better error messages.
  135. printText(U" Ignored unrecognized statement!\n");
  136. }
  137. }
  138. } else {
  139. if (string_caseInsensitiveMatch(first, U"if")) {
  140. target.currentStackDepth++;
  141. } else if (string_caseInsensitiveMatch(first, U"end") && string_caseInsensitiveMatch(second, U"if")) {
  142. target.currentStackDepth--;
  143. }
  144. }
  145. }
  146. tokens.clear();
  147. }
  148. void evaluateScript(SessionContext &output, Machine &target, const ReadableString &scriptPath) {
  149. if (file_getEntryType(scriptPath) != EntryType::File) {
  150. printText(U"The script path ", scriptPath, U" does not exist!\n");
  151. }
  152. String projectContent = string_load(scriptPath);
  153. // Each new script being imported will have its own simulated current path for accessing files and such.
  154. String projectFolderPath = file_getAbsoluteParentFolder(scriptPath);
  155. String currentToken;
  156. List<String> currentLine; // Keep it fast and simple by only remembering tokens for the current line.
  157. bool quoted = false;
  158. bool commented = false;
  159. for (int64_t i = 0; i <= string_length(projectContent); i++) {
  160. DsrChar c = projectContent[i];
  161. // Treat end of file as a linebreak to simplify tokenization rules.
  162. if (c == U'\0') c == U'\n';
  163. // The null terminator does not really exist in projectContent,
  164. // but dsr::String returns a null character safely when requesting a character out of bound,
  165. // which allow interpreting the last line without duplicating code.
  166. if (c == U'\n' || c == U'\0') {
  167. // Comment removing everything else.
  168. flushToken(currentLine, currentToken);
  169. interpretLine(output, target, currentLine, projectFolderPath);
  170. commented = false; // Automatically end comments at end of line.
  171. quoted = false; // Automatically end quotes at end of line.
  172. } else if (c == U'\"') {
  173. quoted = !quoted;
  174. string_appendChar(currentToken, c);
  175. } else if (c == U'#') {
  176. // Comment removing everything else until a new line comes.
  177. flushToken(currentLine, currentToken);
  178. interpretLine(output, target, currentLine, projectFolderPath);
  179. commented = true;
  180. } else if (!commented) {
  181. if (quoted) {
  182. // Insert character into quote.
  183. string_appendChar(currentToken, c);
  184. } else {
  185. // TODO: Do the tokenization in the expression module to get the correct symbols.
  186. if (c == U'(' || c == U')' || c == U'[' || c == U']' || c == U'{' || c == U'}' || c == U'=' || c == U'.' || c == U',' || c == U'|' || c == U'!' || c == U'&' || c == U'+' || c == U'-' || c == U'*' || c == U'/' || c == U'\\') {
  187. // Atomic token of a single character
  188. flushToken(currentLine, currentToken);
  189. string_appendChar(currentToken, c);
  190. flushToken(currentLine, currentToken);
  191. } else if (c == U' ' || c == U'\t') {
  192. // Whitespace
  193. flushToken(currentLine, currentToken);
  194. } else {
  195. // Insert unquoted character into token.
  196. string_appendChar(currentToken, c);
  197. }
  198. }
  199. }
  200. }
  201. }
  202. void argumentsToSettings(Machine &settings, const List<String> &arguments, int64_t firstArgument) {
  203. for (int64_t a = firstArgument; a < arguments.length(); a++) {
  204. String argument = arguments[a];
  205. int64_t assignmentIndex = string_findFirst(argument, U'=');
  206. if (assignmentIndex == -1) {
  207. assignValue(settings, argument, U"1", true);
  208. printText(U"Assigning ", argument, U" to 1 from input argument.\n");
  209. } else {
  210. String key = string_removeOuterWhiteSpace(string_before(argument, assignmentIndex));
  211. String value = string_removeOuterWhiteSpace(string_after(argument, assignmentIndex));
  212. assignValue(settings, key, value, true);
  213. printText(U"Assigning ", key, U" to ", value, U" from input argument.\n");
  214. }
  215. }
  216. }