Machine.cpp 20 KB

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