2
0

Machine.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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.crawlOrigins.length(); i++) {
  32. printText(U" Crawl origins ", settings.crawlOrigins[i], U"\n");
  33. }
  34. for (int64_t i = 0; i < settings.compilerFlags.length(); i++) {
  35. printText(U" Compiler flag ", settings.compilerFlags[i], U"\n");
  36. }
  37. for (int64_t i = 0; i < settings.linkerFlags.length(); i++) {
  38. printText(U" Linker flag ", settings.linkerFlags[i], U"\n");
  39. }
  40. for (int64_t i = 0; i < settings.variables.length(); i++) {
  41. printText(U" Variable ", settings.variables[i].key, U" = ", settings.variables[i].value, U"\n");
  42. }
  43. }
  44. void validateSettings(const Machine &settings, const dsr::ReadableString &eventDescription) {
  45. if (!isUnique(settings.compilerFlags)) {
  46. printText(U"Duplicate compiler flags:\n");
  47. printSettings(settings);
  48. throwError(U"Found duplicate compiler flags ", eventDescription, U"!\n");
  49. };
  50. if (!isUnique(settings.linkerFlags)) {
  51. printText(U"Duplicate linker flags:\n");
  52. printSettings(settings);
  53. throwError(U"Found duplicate linker flags ", eventDescription, U"!\n");
  54. };
  55. if (!isUnique(settings.variables)) {
  56. printText(U"Duplicate variables:\n");
  57. printSettings(settings);
  58. throwError(U"Found duplicate variables ", eventDescription, U"!\n");
  59. };
  60. }
  61. int64_t findFlag(const Machine &target, const dsr::ReadableString &key) {
  62. for (int64_t f = 0; f < target.variables.length(); f++) {
  63. if (string_caseInsensitiveMatch(key, target.variables[f].key)) {
  64. return f;
  65. }
  66. }
  67. return -1;
  68. }
  69. ReadableString getFlag(const Machine &target, const dsr::ReadableString &key, const dsr::ReadableString &defaultValue) {
  70. int64_t existingIndex = findFlag(target, key);
  71. if (existingIndex == -1) {
  72. return defaultValue;
  73. } else {
  74. return target.variables[existingIndex].value;
  75. }
  76. }
  77. int64_t getFlagAsInteger(const Machine &target, const dsr::ReadableString &key, int64_t defaultValue) {
  78. int64_t existingIndex = findFlag(target, key);
  79. if (existingIndex == -1) {
  80. return defaultValue;
  81. } else {
  82. return string_toInteger(target.variables[existingIndex].value);
  83. }
  84. }
  85. void assignValue(Machine &target, const dsr::ReadableString &key, const dsr::ReadableString &value, bool inherited) {
  86. int64_t existingIndex = findFlag(target, key);
  87. if (existingIndex == -1) {
  88. target.variables.pushConstruct(string_upperCase(key), expression_unwrapIfNeeded(value), inherited);
  89. } else {
  90. target.variables[existingIndex].value = expression_unwrapIfNeeded(value);
  91. if (inherited) {
  92. target.variables[existingIndex].inherited = true;
  93. }
  94. }
  95. }
  96. static String evaluateExpression(Machine &target, const List<String> &tokens, int64_t startTokenIndex, int64_t endTokenIndex) {
  97. for (int64_t t = startTokenIndex; t <= endTokenIndex; t++) {
  98. if (string_match(tokens[t], U"\n")) {
  99. throwError(U"Found a linebreak inside of an expression!");
  100. }
  101. }
  102. return expression_evaluate(tokens, startTokenIndex, endTokenIndex, [&target](ReadableString identifier) -> String {
  103. return getFlag(target, identifier, U"");
  104. });
  105. }
  106. // Copy inherited variables from parent to child.
  107. void inheritMachine(Machine &child, const Machine &parent) {
  108. // Only take selected variables, such as the target platform's name.
  109. for (int64_t v = 0; v < parent.variables.length(); v++) {
  110. if (parent.variables[v].inherited) {
  111. child.variables.push(parent.variables[v]);
  112. }
  113. }
  114. }
  115. void cloneMachine(Machine &child, const Machine &parent) {
  116. // Inherit everything.
  117. for (int64_t v = 0; v < parent.variables.length(); v++) {
  118. child.variables.push(parent.variables[v]);
  119. }
  120. for (int64_t v = 0; v < parent.compilerFlags.length(); v++) {
  121. child.compilerFlags.push(parent.compilerFlags[v]);
  122. }
  123. for (int64_t v = 0; v < parent.linkerFlags.length(); v++) {
  124. child.linkerFlags.push(parent.linkerFlags[v]);
  125. }
  126. for (int64_t v = 0; v < parent.crawlOrigins.length(); v++) {
  127. child.crawlOrigins.push(parent.crawlOrigins[v]);
  128. }
  129. }
  130. static bool validIdentifier(const dsr::ReadableString &identifier) {
  131. DsrChar first = identifier[0];
  132. if (!((U'a' <= first && first <= U'z') || (U'A' <= first && first <= U'Z'))) {
  133. return false;
  134. }
  135. for (int i = 1; i < string_length(identifier); i++) {
  136. DsrChar current = identifier[i];
  137. if (!((U'a' <= current && current <= U'z') || (U'A' <= current && current <= U'Z') || (U'0' <= current && current <= U'9'))) {
  138. return false;
  139. }
  140. }
  141. return true;
  142. }
  143. using NameFilter = std::function<bool(const ReadableString &filename)>;
  144. static NameFilter generateFilterFromPattern(const dsr::ReadableString &pattern) {
  145. int64_t firstStar = string_findFirst(pattern, U'*');
  146. int64_t lastStar = string_findLast(pattern, U'*');
  147. if (firstStar == -1) {
  148. return [pattern](const ReadableString &filename) -> bool {
  149. return string_caseInsensitiveMatch(filename, pattern);
  150. };
  151. } else if (firstStar == lastStar) {
  152. String prefix = string_before(pattern, firstStar);
  153. String postfix = string_after(pattern, lastStar);
  154. int64_t preLength = string_length(prefix);
  155. int64_t postLength = string_length(postfix);
  156. int64_t minimumLength = preLength + postLength;
  157. return [prefix, postfix, preLength, postLength, minimumLength](const ReadableString &filename) -> bool {
  158. int64_t nameLength = string_length(filename);
  159. if (nameLength < minimumLength) {
  160. return false;
  161. } else {
  162. ReadableString foundPrefix = string_before(filename, preLength);
  163. ReadableString foundPostfix = string_from(filename, nameLength - postLength);
  164. return string_caseInsensitiveMatch(foundPrefix, prefix) && string_caseInsensitiveMatch(foundPostfix, postfix);
  165. }
  166. };
  167. } else {
  168. throwError(U"Can not use '", pattern, "' as a name pattern, because the matching expression may not use more than one '*' character!\n");
  169. return [](const ReadableString &filename) -> bool {
  170. return false;
  171. };
  172. }
  173. }
  174. static void findFiles(const dsr::ReadableString &inPath, NameFilter filter, std::function<void(const ReadableString &path)> action) {
  175. if (!file_getFolderContent(inPath, [&filter, &action](const ReadableString& entryPath, const ReadableString& entryName, EntryType entryType) {
  176. if (entryType == EntryType::File) {
  177. if (filter(entryName)) {
  178. action(entryPath);
  179. }
  180. } else if (entryType == EntryType::Folder) {
  181. findFiles(entryPath, filter, action);
  182. }
  183. })) {
  184. printText("Failed to look for files in '", inPath, "'\n");
  185. }
  186. }
  187. static void findFilesAsProjects(Machine &target, const dsr::ReadableString &inPath, const dsr::ReadableString &fromPattern) {
  188. printText(U"findFilesAsProjects: Looking for ", fromPattern, U" in ", inPath, U".\n");
  189. validateSettings(target, U"in the parent about to create projects from files");
  190. findFiles(inPath, generateFilterFromPattern(fromPattern), [&target](const ReadableString &path) {
  191. printText(U"Creating a temporary project for ", path, U"\n");
  192. // List the file as a project.
  193. target.projectFromSourceFilenames.push(path);
  194. Machine allInputFlags(file_getPathlessName(path));
  195. cloneMachine(allInputFlags, target);
  196. target.projectFromSourceSettings.push(allInputFlags);
  197. });
  198. }
  199. // TODO: Improve error messages with line numbers and quoted content instead of just throwing errors.
  200. static void interpretLine(Machine &target, const List<String> &tokens, int64_t startTokenIndex, int64_t endTokenIndex, const dsr::ReadableString &fromPath) {
  201. // Automatically clamp to safe bounds.
  202. if (startTokenIndex < 0) startTokenIndex = 0;
  203. if (endTokenIndex >= tokens.length()) endTokenIndex = tokens.length() - 1;
  204. int64_t tokenCount = endTokenIndex - startTokenIndex + 1;
  205. if (tokenCount > 0) {
  206. bool activeLine = target.activeStackDepth >= target.currentStackDepth;
  207. /*
  208. printText(activeLine ? U"interpret:" : U"ignore:");
  209. for (int64_t t = startTokenIndex; t <= endTokenIndex; t++) {
  210. printText(U" [", tokens[t], U"]");
  211. }
  212. printText(U"\n");
  213. */
  214. ReadableString first = expression_getToken(tokens, startTokenIndex, U"");
  215. ReadableString second = expression_getToken(tokens, startTokenIndex + 1, U"");
  216. if (activeLine) {
  217. // TODO: Implement elseif and else cases using a list as a virtual stack,
  218. // to remember at which layer the else cases have already been consumed by a true evaluation.
  219. // 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.
  220. if (string_caseInsensitiveMatch(first, U"import")) {
  221. // Get path relative to importing script's path.
  222. String importPath = PATH_EXPR(startTokenIndex + 1, endTokenIndex);
  223. evaluateScript(target, importPath);
  224. validateSettings(target, U"in target after importing a project head\n");
  225. } else if (string_caseInsensitiveMatch(first, U"if")) {
  226. // Being if statement
  227. bool active = INTEGER_EXPR(startTokenIndex + 1, endTokenIndex);
  228. if (active) {
  229. target.activeStackDepth++;
  230. }
  231. target.currentStackDepth++;
  232. } else if (string_caseInsensitiveMatch(first, U"end") && string_caseInsensitiveMatch(second, U"if")) {
  233. // End if statement
  234. target.currentStackDepth--;
  235. target.activeStackDepth = target.currentStackDepth;
  236. } else if (string_caseInsensitiveMatch(first, U"crawl")) {
  237. // The right hand expression is evaluated into a path relative to the build script and used as the root for searching for source code.
  238. target.crawlOrigins.push(PATH_EXPR(startTokenIndex + 1, endTokenIndex));
  239. validateSettings(target, U"in target after listing a crawl origin\n");
  240. } else if (string_caseInsensitiveMatch(first, U"projects")) {
  241. // TODO: Should it be possible to give the string content of variables as patterns and paths?
  242. //Projects from "*Test.cpp" in "tests"
  243. int currentTokenIndex = startTokenIndex + 1;
  244. String arg_from;
  245. String arg_in;
  246. while (currentTokenIndex < endTokenIndex) {
  247. ReadableString key = expression_getToken(tokens, currentTokenIndex, U"");
  248. ReadableString value = expression_getToken(tokens, currentTokenIndex + 1, U"");
  249. if (string_caseInsensitiveMatch(key, U"from")) {
  250. if (string_length(value) == 0) {
  251. throwError(U"Missing folder path after 'from' keyword in 'projects' command!\n");
  252. } else {
  253. printText(U"Using ", value, U" as the 'from' argument.\n");
  254. arg_from = string_unmangleQuote(value);
  255. // Consume both key and value.
  256. currentTokenIndex += 2;
  257. }
  258. } else if (string_caseInsensitiveMatch(key, U"in")) {
  259. if (string_length(value) == 0) {
  260. throwError(U"Missing file name pattern after 'in' keyword in 'projects' command!\n");
  261. } else {
  262. printText(U"Using ", value, U" as the 'in' argument.\n");
  263. arg_in = string_unmangleQuote(value);
  264. // Consume both key and value.
  265. currentTokenIndex += 2;
  266. }
  267. } else {
  268. throwError(U"Unexpected key '", key, "' in 'projects' command!\n");
  269. }
  270. }
  271. if (string_length(arg_from) == 0 && string_length(arg_in) == 0) {
  272. throwError(U"Need 'from' and 'in' keywords in 'projects' command!\n");
  273. } else if (string_length(arg_from) == 0) {
  274. throwError(U"Missing 'from' keyword in 'projects' command!\n");
  275. } else if (string_length(arg_in) == 0) {
  276. throwError(U"Missing 'in' keywords in 'projects' command!\n");
  277. } else {
  278. findFilesAsProjects(target, file_combinePaths(fromPath, arg_in), arg_from);
  279. }
  280. } else if (string_caseInsensitiveMatch(first, U"build")) {
  281. // Build one or more other projects from a project file or folder path, as dependencies.
  282. // Having the same external project built twice during the same session is not allowed.
  283. // Evaluate arguments recursively, but let the analyzer do the work.
  284. String projectPath = file_getTheoreticalAbsolutePath(expression_unwrapIfNeeded(second), fromPath); // Use the second token as the folder path.
  285. // The arguments may be for a whole folder of projects, so each project still need to clone its own settings.
  286. Machine sharedInputFlags(file_getPathlessName(projectPath));
  287. validateSettings(target, U"in the parent about to build a child project (build in interpretLine)");
  288. inheritMachine(sharedInputFlags, target);
  289. validateSettings(sharedInputFlags, U"in the parent after inheriting settings for a build child (build in interpretLine)");
  290. validateSettings(sharedInputFlags, U"in the child after inheriting settings as a build child (build in interpretLine)");
  291. argumentsToSettings(sharedInputFlags, tokens, startTokenIndex + 2, endTokenIndex); // Send all tokens after the second token as input arguments to buildProjects.
  292. validateSettings(sharedInputFlags, U"in the child after parsing arguments (build in interpretLine)");
  293. printText(U"Building ", second, U" from ", fromPath, U" which is ", projectPath, U"\n");
  294. target.otherProjectPaths.push(projectPath);
  295. target.otherProjectSettings.push(sharedInputFlags);
  296. validateSettings(target, U"in target after listing a child project\n");
  297. } else if (string_caseInsensitiveMatch(first, U"link")) {
  298. // Only the library name itself is needed, because the -l prefix can be added automatically.
  299. String libraryName = STRING_EXPR(startTokenIndex + 1, endTokenIndex);
  300. if (libraryName[0] == U'-' && (libraryName[1] == U'l' || libraryName[1] == U'L')) {
  301. target.linkerFlags.push(libraryName);
  302. } else {
  303. target.linkerFlags.push(string_combine(U"-l", libraryName));
  304. }
  305. validateSettings(target, U"in target after adding a linker flag\n");
  306. } else if (string_caseInsensitiveMatch(first, U"linkerflag")) {
  307. // For linker flags that are not used to
  308. target.linkerFlags.push(STRING_EXPR(startTokenIndex + 1, endTokenIndex));
  309. validateSettings(target, U"in target after adding a linker flag\n");
  310. } else if (string_caseInsensitiveMatch(first, U"compilerflag")) {
  311. target.compilerFlags.push(STRING_EXPR(startTokenIndex + 1, endTokenIndex));
  312. validateSettings(target, U"in target after adding a compiler flag\n");
  313. } else if (string_caseInsensitiveMatch(first, U"message")) {
  314. // Print a message while evaluating the build script.
  315. // This is not done while actually compiling, so it will not know if compilation and linking worked or not.
  316. printText(STRING_EXPR(startTokenIndex + 1, endTokenIndex));
  317. } else {
  318. if (tokenCount == 1) {
  319. // Mentioning an identifier without assigning anything will assign it to one as a boolean flag.
  320. if (validIdentifier(first)) {
  321. assignValue(target, first, U"1", false);
  322. } else {
  323. throwError(U"The token ", first, U" is not a valid identifier for implicit assignment to one.\n");
  324. }
  325. validateSettings(target, U"in target after implicitly assigning a value to a variable\n");
  326. } else if (string_match(second, U"=")) {
  327. // TODO: Create in-place math and string operations with different types of assignments.
  328. // Maybe use a different syntax beginning with a keyword?
  329. // TODO: Look for the assignment operator dynamically if references to collection elements are allowed as l-value expressions.
  330. // Using an equality sign replaces any previous value of the variable.
  331. if (validIdentifier(first)) {
  332. assignValue(target, first, STRING_EXPR(startTokenIndex + 2, endTokenIndex), false);
  333. } else {
  334. throwError(U"The token ", first, U" is not a valid identifier for assignments.\n");
  335. }
  336. validateSettings(target, U"in target after explicitly assigning a value to a variable\n");
  337. } else {
  338. String errorMessage = U"Failed to parse statement: ";
  339. for (int64_t t = startTokenIndex; t <= endTokenIndex; t++) {
  340. string_append(errorMessage, U" ", string_mangleQuote(tokens[t]));
  341. }
  342. string_append(errorMessage, U"\n");
  343. throwError(errorMessage);
  344. }
  345. }
  346. } else {
  347. if (string_caseInsensitiveMatch(first, U"if")) {
  348. target.currentStackDepth++;
  349. } else if (string_caseInsensitiveMatch(first, U"end") && string_caseInsensitiveMatch(second, U"if")) {
  350. target.currentStackDepth--;
  351. }
  352. }
  353. }
  354. }
  355. void evaluateScript(Machine &target, const ReadableString &scriptPath) {
  356. //printText(U"Evaluating script at ", scriptPath, U"\n");
  357. //printSettings(target);
  358. if (file_getEntryType(scriptPath) != EntryType::File) {
  359. printText(U"The script path ", scriptPath, U" does not exist!\n");
  360. }
  361. // Each new script being imported will have its own simulated current path for accessing files and such.
  362. String projectFolderPath = file_getAbsoluteParentFolder(scriptPath);
  363. // Tokenize the document to handle string literals.
  364. String projectContent = string_load(scriptPath);
  365. List<String> tokens;
  366. expression_tokenize(tokens, projectContent);
  367. // Insert an extra linebreak at the end to avoid special cases for the last line.
  368. tokens.push(U"\n");
  369. // Segment tokens into logical lines and interpret one at a time.
  370. int64_t startTokenIndex = 0;
  371. for (int64_t t = 0; t < tokens.length(); t++) {
  372. if (string_match(tokens[t], U"\n")) {
  373. interpretLine(target, tokens, startTokenIndex, t - 1, projectFolderPath);
  374. startTokenIndex = t + 1;
  375. }
  376. }
  377. //printText(U"Evaluated script at ", scriptPath, U"\n");
  378. //printSettings(target);
  379. }
  380. void argumentsToSettings(Machine &settings, const List<String> &arguments, int64_t firstArgument, int64_t lastArgument) {
  381. //printText(U"argumentsToSettings:");
  382. //for (int64_t a = firstArgument; a <= lastArgument; a++) {
  383. // printText(U" ", arguments[a]);
  384. //}
  385. //printText(U"\n");
  386. for (int64_t a = firstArgument; a <= lastArgument; a++) {
  387. String argument = arguments[a];
  388. int64_t assignmentIndex = string_findFirst(argument, U'=');
  389. if (assignmentIndex == -1) {
  390. assignValue(settings, argument, U"1", true);
  391. printText(U"Assigning ", argument, U" to 1 from input argument.\n");
  392. } else {
  393. String key = string_removeOuterWhiteSpace(string_before(argument, assignmentIndex));
  394. String value = string_removeOuterWhiteSpace(string_after(argument, assignmentIndex));
  395. assignValue(settings, key, value, true);
  396. printText(U"Assigning ", key, U" to ", value, U" from input argument.\n");
  397. }
  398. }
  399. }