Machine.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. static bool isUnique(const List<String> &list) {
  10. for (int i = 0; i < list.length() - 1; i++) {
  11. for (int j = i + 1; j < list.length(); j++) {
  12. if (string_match(list[i], list[j])) {
  13. return false;
  14. }
  15. }
  16. }
  17. return true;
  18. }
  19. static bool isUnique(const List<Flag> &list) {
  20. for (int i = 0; i < list.length() - 1; i++) {
  21. for (int j = i + 1; j < list.length(); j++) {
  22. if (string_match(list[i].key, list[j].key)) {
  23. return false;
  24. }
  25. }
  26. }
  27. return true;
  28. }
  29. void printSettings(const Machine &settings) {
  30. printText(U" Project name: ", settings.projectName, U"\n");
  31. for (int64_t i = 0; i < settings.compilerFlags.length(); i++) {
  32. printText(U" Compiler flag ", settings.compilerFlags[i], U"\n");
  33. }
  34. for (int64_t i = 0; i < settings.linkerFlags.length(); i++) {
  35. printText(U" Linker flag ", settings.linkerFlags[i], U"\n");
  36. }
  37. for (int64_t i = 0; i < settings.variables.length(); i++) {
  38. printText(U" Variable ", settings.variables[i].key, U" = ", settings.variables[i].value, U"\n");
  39. }
  40. }
  41. void validateSettings(const Machine &settings, const dsr::ReadableString &eventDescription) {
  42. if (!isUnique(settings.compilerFlags)) {
  43. printText(U"Duplicate compiler flags:\n");
  44. printSettings(settings);
  45. throwError(U"Found duplicate compiler flags ", eventDescription, U"!\n");
  46. };
  47. if (!isUnique(settings.linkerFlags)) {
  48. printText(U"Duplicate linker flags:\n");
  49. printSettings(settings);
  50. throwError(U"Found duplicate linker flags ", eventDescription, U"!\n");
  51. };
  52. if (!isUnique(settings.variables)) {
  53. printText(U"Duplicate variables:\n");
  54. printSettings(settings);
  55. throwError(U"Found duplicate variables ", eventDescription, U"!\n");
  56. };
  57. }
  58. int64_t findFlag(const Machine &target, const dsr::ReadableString &key) {
  59. for (int64_t f = 0; f < target.variables.length(); f++) {
  60. if (string_caseInsensitiveMatch(key, target.variables[f].key)) {
  61. return f;
  62. }
  63. }
  64. return -1;
  65. }
  66. ReadableString getFlag(const Machine &target, const dsr::ReadableString &key, const dsr::ReadableString &defaultValue) {
  67. int64_t existingIndex = findFlag(target, key);
  68. if (existingIndex == -1) {
  69. return defaultValue;
  70. } else {
  71. return target.variables[existingIndex].value;
  72. }
  73. }
  74. int64_t getFlagAsInteger(const Machine &target, const dsr::ReadableString &key, int64_t defaultValue) {
  75. int64_t existingIndex = findFlag(target, key);
  76. if (existingIndex == -1) {
  77. return defaultValue;
  78. } else {
  79. return string_toInteger(target.variables[existingIndex].value);
  80. }
  81. }
  82. void assignValue(Machine &target, const dsr::ReadableString &key, const dsr::ReadableString &value, bool inherited) {
  83. int64_t existingIndex = findFlag(target, key);
  84. if (existingIndex == -1) {
  85. target.variables.pushConstruct(string_upperCase(key), expression_unwrapIfNeeded(value), inherited);
  86. } else {
  87. target.variables[existingIndex].value = expression_unwrapIfNeeded(value);
  88. if (inherited) {
  89. target.variables[existingIndex].inherited = true;
  90. }
  91. }
  92. }
  93. static String evaluateExpression(Machine &target, const List<String> &tokens, int64_t startTokenIndex, int64_t endTokenIndex) {
  94. for (int64_t t = startTokenIndex; t <= endTokenIndex; t++) {
  95. if (string_match(tokens[t], U"\n")) {
  96. throwError(U"Found a linebreak inside of an expression!");
  97. }
  98. }
  99. return expression_evaluate(tokens, startTokenIndex, endTokenIndex, [&target](ReadableString identifier) -> String {
  100. return getFlag(target, identifier, U"");
  101. });
  102. }
  103. // Copy inherited variables from parent to child.
  104. void inheritMachine(Machine &child, const Machine &parent) {
  105. for (int64_t v = 0; v < parent.variables.length(); v++) {
  106. String key = string_upperCase(parent.variables[v].key);
  107. if (parent.variables[v].inherited) {
  108. child.variables.push(parent.variables[v]);
  109. }
  110. }
  111. }
  112. static bool validIdentifier(const dsr::ReadableString &identifier) {
  113. DsrChar first = identifier[0];
  114. if (!((U'a' <= first && first <= U'z') || (U'A' <= first && first <= U'Z'))) {
  115. return false;
  116. }
  117. for (int i = 1; i < string_length(identifier); i++) {
  118. DsrChar current = identifier[i];
  119. if (!((U'a' <= current && current <= U'z') || (U'A' <= current && current <= U'Z') || (U'0' <= current && current <= U'9'))) {
  120. return false;
  121. }
  122. }
  123. return true;
  124. }
  125. static void interpretLine(Machine &target, const List<String> &tokens, int64_t startTokenIndex, int64_t endTokenIndex, const dsr::ReadableString &fromPath) {
  126. // Automatically clamp to safe bounds.
  127. if (startTokenIndex < 0) startTokenIndex = 0;
  128. if (endTokenIndex >= tokens.length()) endTokenIndex = tokens.length() - 1;
  129. int64_t tokenCount = endTokenIndex - startTokenIndex + 1;
  130. if (tokenCount > 0) {
  131. bool activeLine = target.activeStackDepth >= target.currentStackDepth;
  132. /*
  133. printText(activeLine ? U"interpret:" : U"ignore:");
  134. for (int64_t t = startTokenIndex; t <= endTokenIndex; t++) {
  135. printText(U" [", tokens[t], U"]");
  136. }
  137. printText(U"\n");
  138. */
  139. ReadableString first = expression_getToken(tokens, startTokenIndex, U"");
  140. ReadableString second = expression_getToken(tokens, startTokenIndex + 1, U"");
  141. if (activeLine) {
  142. // TODO: Implement elseif and else cases using a list as a virtual stack,
  143. // to remember at which layer the else cases have already been consumed by a true evaluation.
  144. // 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.
  145. if (string_caseInsensitiveMatch(first, U"import")) {
  146. // Get path relative to importing script's path.
  147. String importPath = PATH_EXPR(startTokenIndex + 1, endTokenIndex);
  148. evaluateScript(target, importPath);
  149. validateSettings(target, U"in target after importing a project head\n");
  150. } else if (string_caseInsensitiveMatch(first, U"if")) {
  151. // Being if statement
  152. bool active = INTEGER_EXPR(startTokenIndex + 1, endTokenIndex);
  153. if (active) {
  154. target.activeStackDepth++;
  155. }
  156. target.currentStackDepth++;
  157. } else if (string_caseInsensitiveMatch(first, U"end") && string_caseInsensitiveMatch(second, U"if")) {
  158. // End if statement
  159. target.currentStackDepth--;
  160. target.activeStackDepth = target.currentStackDepth;
  161. } else if (string_caseInsensitiveMatch(first, U"crawl")) {
  162. // The right hand expression is evaluated into a path relative to the build script and used as the root for searching for source code.
  163. target.crawlOrigins.push(PATH_EXPR(startTokenIndex + 1, endTokenIndex));
  164. validateSettings(target, U"in target after listing a crawl origin\n");
  165. } else if (string_caseInsensitiveMatch(first, U"build")) {
  166. // Build one or more other projects from a project file or folder path, as dependencies.
  167. // Having the same external project built twice during the same session is not allowed.
  168. // Evaluate arguments recursively, but let the analyzer do the work.
  169. String projectPath = file_getTheoreticalAbsolutePath(expression_unwrapIfNeeded(second), fromPath); // Use the second token as the folder path.
  170. // The arguments may be for a whole folder of projects, so each project still need to clone its own settings.
  171. Machine sharedInputFlags(file_getPathlessName(projectPath));
  172. validateSettings(target, U"in the parent about to build a child project (build in interpretLine)");
  173. inheritMachine(sharedInputFlags, target);
  174. validateSettings(sharedInputFlags, U"in the parent after inheriting settings for a build child (build in interpretLine)");
  175. validateSettings(sharedInputFlags, U"in the child after inheriting settings as a build child (build in interpretLine)");
  176. argumentsToSettings(sharedInputFlags, tokens, startTokenIndex + 2, endTokenIndex); // Send all tokens after the second token as input arguments to buildProjects.
  177. validateSettings(sharedInputFlags, U"in the child after parsing arguments (build in interpretLine)");
  178. printText(U"Building ", second, U" from ", fromPath, U" which is ", projectPath, U"\n");
  179. target.otherProjectPaths.push(projectPath);
  180. target.otherProjectSettings.push(sharedInputFlags);
  181. validateSettings(target, U"in target after listing a child project\n");
  182. } else if (string_caseInsensitiveMatch(first, U"link")) {
  183. // Only the library name itself is needed, because the -l prefix can be added automatically.
  184. String libraryName = STRING_EXPR(startTokenIndex + 1, endTokenIndex);
  185. if (libraryName[0] == U'-' && (libraryName[1] == U'l' || libraryName[1] == U'L')) {
  186. target.linkerFlags.push(libraryName);
  187. } else {
  188. target.linkerFlags.push(string_combine(U"-l", libraryName));
  189. }
  190. validateSettings(target, U"in target after adding a linker flag\n");
  191. } else if (string_caseInsensitiveMatch(first, U"linkerflag")) {
  192. // For linker flags that are not used to
  193. target.linkerFlags.push(STRING_EXPR(startTokenIndex + 1, endTokenIndex));
  194. validateSettings(target, U"in target after adding a linker flag\n");
  195. } else if (string_caseInsensitiveMatch(first, U"compilerflag")) {
  196. target.compilerFlags.push(STRING_EXPR(startTokenIndex + 1, endTokenIndex));
  197. validateSettings(target, U"in target after adding a compiler flag\n");
  198. } else if (string_caseInsensitiveMatch(first, U"message")) {
  199. // Print a message while evaluating the build script.
  200. // This is not done while actually compiling, so it will not know if compilation and linking worked or not.
  201. printText(STRING_EXPR(startTokenIndex + 1, endTokenIndex));
  202. } else {
  203. if (tokenCount == 1) {
  204. // Mentioning an identifier without assigning anything will assign it to one as a boolean flag.
  205. if (validIdentifier(first)) {
  206. assignValue(target, first, U"1", false);
  207. } else {
  208. throwError(U"The token ", first, U" is not a valid identifier for implicit assignment to one.\n");
  209. }
  210. validateSettings(target, U"in target after implicitly assigning a value to a variable\n");
  211. } else if (string_match(second, U"=")) {
  212. // TODO: Create in-place math and string operations with different types of assignments.
  213. // Maybe use a different syntax beginning with a keyword?
  214. // TODO: Look for the assignment operator dynamically if references to collection elements are allowed as l-value expressions.
  215. // Using an equality sign replaces any previous value of the variable.
  216. if (validIdentifier(first)) {
  217. assignValue(target, first, STRING_EXPR(startTokenIndex + 2, endTokenIndex), false);
  218. } else {
  219. throwError(U"The token ", first, U" is not a valid identifier for assignments.\n");
  220. }
  221. validateSettings(target, U"in target after explicitly assigning a value to a variable\n");
  222. } else {
  223. String errorMessage = U"Failed to parse statement: ";
  224. printText(U"Failed to parse statement of tokens: ");
  225. for (int64_t t = startTokenIndex; t <= endTokenIndex; t++) {
  226. string_append(errorMessage, U" ", string_mangleQuote(tokens[t]));
  227. }
  228. string_append(errorMessage, U"\n");
  229. throwError(errorMessage);
  230. }
  231. }
  232. } else {
  233. if (string_caseInsensitiveMatch(first, U"if")) {
  234. target.currentStackDepth++;
  235. } else if (string_caseInsensitiveMatch(first, U"end") && string_caseInsensitiveMatch(second, U"if")) {
  236. target.currentStackDepth--;
  237. }
  238. }
  239. }
  240. }
  241. void evaluateScript(Machine &target, const ReadableString &scriptPath) {
  242. //printText(U"Evaluating script at ", scriptPath, U"\n");
  243. //printSettings(target);
  244. if (file_getEntryType(scriptPath) != EntryType::File) {
  245. printText(U"The script path ", scriptPath, U" does not exist!\n");
  246. }
  247. // Each new script being imported will have its own simulated current path for accessing files and such.
  248. String projectFolderPath = file_getAbsoluteParentFolder(scriptPath);
  249. // Tokenize the document to handle string literals.
  250. String projectContent = string_load(scriptPath);
  251. List<String> tokens;
  252. expression_tokenize(tokens, projectContent);
  253. // Insert an extra linebreak at the end to avoid special cases for the last line.
  254. tokens.push(U"\n");
  255. // Segment tokens into logical lines and interpret one at a time.
  256. int64_t startTokenIndex = 0;
  257. for (int64_t t = 0; t < tokens.length(); t++) {
  258. if (string_match(tokens[t], U"\n")) {
  259. interpretLine(target, tokens, startTokenIndex, t - 1, projectFolderPath);
  260. startTokenIndex = t + 1;
  261. }
  262. }
  263. //printText(U"Evaluated script at ", scriptPath, U"\n");
  264. //printSettings(target);
  265. }
  266. void argumentsToSettings(Machine &settings, const List<String> &arguments, int64_t firstArgument, int64_t lastArgument) {
  267. //printText(U"argumentsToSettings:");
  268. //for (int64_t a = firstArgument; a <= lastArgument; a++) {
  269. // printText(U" ", arguments[a]);
  270. //}
  271. //printText(U"\n");
  272. for (int64_t a = firstArgument; a <= lastArgument; a++) {
  273. String argument = arguments[a];
  274. int64_t assignmentIndex = string_findFirst(argument, U'=');
  275. if (assignmentIndex == -1) {
  276. assignValue(settings, argument, U"1", true);
  277. printText(U"Assigning ", argument, U" to 1 from input argument.\n");
  278. } else {
  279. String key = string_removeOuterWhiteSpace(string_before(argument, assignmentIndex));
  280. String value = string_removeOuterWhiteSpace(string_after(argument, assignmentIndex));
  281. assignValue(settings, key, value, true);
  282. printText(U"Assigning ", key, U" to ", value, U" from input argument.\n");
  283. }
  284. }
  285. }