Machine.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. 
  2. #include "Machine.h"
  3. #include "generator.h"
  4. #include "../../DFPSR/api/fileAPI.h"
  5. using namespace dsr;
  6. int64_t findFlag(const Machine &target, const dsr::ReadableString &key) {
  7. for (int64_t f = 0; f < target.variables.length(); f++) {
  8. if (string_caseInsensitiveMatch(key, target.variables[f].key)) {
  9. return f;
  10. }
  11. }
  12. return -1;
  13. }
  14. ReadableString getFlag(const Machine &target, const dsr::ReadableString &key, const dsr::ReadableString &defaultValue) {
  15. int64_t existingIndex = findFlag(target, key);
  16. if (existingIndex == -1) {
  17. return defaultValue;
  18. } else {
  19. return target.variables[existingIndex].value;
  20. }
  21. }
  22. int64_t getFlagAsInteger(const Machine &target, const dsr::ReadableString &key, int64_t defaultValue) {
  23. int64_t existingIndex = findFlag(target, key);
  24. if (existingIndex == -1) {
  25. return defaultValue;
  26. } else {
  27. return string_toInteger(target.variables[existingIndex].value);
  28. }
  29. }
  30. static String unwrapIfNeeded(const dsr::ReadableString &value) {
  31. if (value[0] == U'\"') {
  32. return string_unmangleQuote(value);
  33. } else {
  34. return value;
  35. }
  36. }
  37. void assignValue(Machine &target, const dsr::ReadableString &key, const dsr::ReadableString &value) {
  38. int64_t existingIndex = findFlag(target, key);
  39. if (existingIndex == -1) {
  40. target.variables.pushConstruct(string_upperCase(key), unwrapIfNeeded(value));
  41. } else {
  42. target.variables[existingIndex].value = unwrapIfNeeded(value);
  43. }
  44. }
  45. static void flushToken(List<String> &targetTokens, String &currentToken) {
  46. if (string_length(currentToken) > 0) {
  47. targetTokens.push(currentToken);
  48. currentToken = U"";
  49. }
  50. }
  51. // Safe access for easy pattern matching.
  52. static ReadableString getToken(List<String> &tokens, int index) {
  53. if (0 <= index && index < tokens.length()) {
  54. return tokens[index];
  55. } else {
  56. return U"";
  57. }
  58. }
  59. static int64_t interpretAsInteger(const dsr::ReadableString &value) {
  60. if (string_length(value) == 0) {
  61. return 0;
  62. } else {
  63. return string_toInteger(value);
  64. }
  65. }
  66. #define STRING_EXPR(FIRST_TOKEN, LAST_TOKEN) evaluateExpression(target, tokens, FIRST_TOKEN, LAST_TOKEN)
  67. #define STRING_LEFT STRING_EXPR(startTokenIndex, opIndex - 1)
  68. #define STRING_RIGHT STRING_EXPR(opIndex + 1, endTokenIndex)
  69. #define INTEGER_EXPR(FIRST_TOKEN, LAST_TOKEN) interpretAsInteger(STRING_EXPR(FIRST_TOKEN, LAST_TOKEN))
  70. #define INTEGER_LEFT INTEGER_EXPR(startTokenIndex, opIndex - 1)
  71. #define INTEGER_RIGHT INTEGER_EXPR(opIndex + 1, endTokenIndex)
  72. #define PATH_EXPR(FIRST_TOKEN, LAST_TOKEN) file_getTheoreticalAbsolutePath(STRING_EXPR(FIRST_TOKEN, LAST_TOKEN), fromPath)
  73. #define MATCH_CIS(TOKEN) string_caseInsensitiveMatch(currentToken, TOKEN)
  74. #define MATCH_CS(TOKEN) string_match(currentToken, TOKEN)
  75. static String evaluateExpression(Machine &target, List<String> &tokens, int64_t startTokenIndex, int64_t endTokenIndex) {
  76. if (startTokenIndex == endTokenIndex) {
  77. ReadableString first = getToken(tokens, startTokenIndex);
  78. if (string_isInteger(first)) {
  79. return first;
  80. } else if (first[0] == U'\"') {
  81. return string_unmangleQuote(first);
  82. } else {
  83. // Identifier defaulting to empty.
  84. return getFlag(target, first, U"");
  85. }
  86. } else {
  87. int64_t depth = 0;
  88. for (int64_t opIndex = 0; opIndex < tokens.length(); opIndex++) {
  89. String currentToken = tokens[opIndex];
  90. if (MATCH_CS(U"(")) {
  91. depth++;
  92. } else if (MATCH_CS(U")")) {
  93. depth--;
  94. if (depth < 0) throwError(U"Negative expression depth!\n");
  95. } else if (MATCH_CIS(U"and")) {
  96. return string_combine(INTEGER_LEFT && INTEGER_RIGHT);
  97. } else if (MATCH_CIS(U"or")) {
  98. return string_combine(INTEGER_LEFT || INTEGER_RIGHT);
  99. } else if (MATCH_CIS(U"xor")) {
  100. return string_combine((!INTEGER_LEFT) != (!INTEGER_RIGHT));
  101. } else if (MATCH_CS(U"+")) {
  102. return string_combine(INTEGER_LEFT + INTEGER_RIGHT);
  103. } else if (MATCH_CS(U"-")) {
  104. return string_combine(INTEGER_LEFT - INTEGER_RIGHT);
  105. } else if (MATCH_CS(U"*")) {
  106. return string_combine(INTEGER_LEFT * INTEGER_RIGHT);
  107. } else if (MATCH_CS(U"/")) {
  108. return string_combine(INTEGER_LEFT / INTEGER_RIGHT);
  109. } else if (MATCH_CS(U"<")) {
  110. return string_combine(INTEGER_LEFT < INTEGER_RIGHT);
  111. } else if (MATCH_CS(U">")) {
  112. return string_combine(INTEGER_LEFT > INTEGER_RIGHT);
  113. } else if (MATCH_CS(U">=")) {
  114. return string_combine(INTEGER_LEFT >= INTEGER_RIGHT);
  115. } else if (MATCH_CS(U"<=")) {
  116. return string_combine(INTEGER_LEFT <= INTEGER_RIGHT);
  117. } else if (MATCH_CS(U"==")) {
  118. return string_combine(INTEGER_LEFT == INTEGER_RIGHT);
  119. } else if (MATCH_CS(U"!=")) {
  120. return string_combine(INTEGER_LEFT != INTEGER_RIGHT);
  121. } else if (MATCH_CS(U"&")) {
  122. return string_combine(STRING_LEFT, STRING_RIGHT);
  123. }
  124. }
  125. if (depth != 0) throwError(U"Unbalanced expression depth!\n");
  126. if (string_match(tokens[startTokenIndex], U"(") && string_match(tokens[endTokenIndex], U")")) {
  127. return evaluateExpression(target, tokens, startTokenIndex + 1, endTokenIndex - 1);
  128. }
  129. }
  130. throwError(U"Failed to evaluate expression!\n");
  131. return U"?";
  132. }
  133. static void analyzeSource(const dsr::ReadableString &absolutePath) {
  134. EntryType pathType = file_getEntryType(absolutePath);
  135. if (pathType == EntryType::File) {
  136. printText(U" Using source from ", absolutePath, U".\n");
  137. analyzeFromFile(absolutePath);
  138. } else if (pathType == EntryType::Folder) {
  139. // TODO: Being analyzing from each source file in the folder recursively.
  140. // Each file that is already included will quickly be ignored.
  141. // The difficult part is that exploring a folder returns files in non-deterministic order and GNU's compiler is order dependent.
  142. printText(U" Searching for source code from the folder ", absolutePath, U" is not yet supported due to order dependent linking!\n");
  143. } else if (pathType == EntryType::SymbolicLink) {
  144. // Symbolic links can point to both files and folder, so we need to follow it and find out what it really is.
  145. analyzeSource(file_followSymbolicLink(absolutePath));
  146. }
  147. }
  148. static void interpretLine(Machine &target, List<String> &tokens, const dsr::ReadableString &fromPath) {
  149. if (tokens.length() > 0) {
  150. bool activeLine = target.activeStackDepth >= target.currentStackDepth;
  151. /*
  152. printText(activeLine ? U"interpret:" : U"ignore:");
  153. for (int t = 0; t < tokens.length(); t++) {
  154. printText(U" [", tokens[t], U"]");
  155. }
  156. printText(U"\n");
  157. */
  158. ReadableString first = getToken(tokens, 0);
  159. ReadableString second = getToken(tokens, 1);
  160. if (activeLine) {
  161. // TODO: Implement elseif and else cases using a list as a virtual stack,
  162. // to remember at which layer the else cases have already been consumed by a true evaluation.
  163. // 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.
  164. if (string_caseInsensitiveMatch(first, U"import")) {
  165. // Get path relative to importing script's path.
  166. String importPath = PATH_EXPR(1, tokens.length() - 1);
  167. evaluateScript(target, importPath);
  168. if (tokens.length() > 2) { printText(U"Unused tokens after import!\n");}
  169. } else if (string_caseInsensitiveMatch(first, U"if")) {
  170. // Being if statement
  171. bool active = INTEGER_EXPR(1, tokens.length() - 1);
  172. if (active) {
  173. target.activeStackDepth++;
  174. }
  175. target.currentStackDepth++;
  176. } else if (string_caseInsensitiveMatch(first, U"end")) {
  177. // End if statement
  178. target.currentStackDepth--;
  179. target.activeStackDepth = target.currentStackDepth;
  180. } else if (string_caseInsensitiveMatch(first, U"compile")) {
  181. // The right hand expression is evaluated into a path relative to the build script and used as the root for searching for source code.
  182. analyzeSource(PATH_EXPR(1, tokens.length() - 1));
  183. } else if (string_caseInsensitiveMatch(first, U"linkerflag")) {
  184. target.linkerFlags.push(STRING_EXPR(1, tokens.length() - 1));
  185. } else if (string_caseInsensitiveMatch(first, U"compilerflag")) {
  186. target.compilerFlags.push(STRING_EXPR(1, tokens.length() - 1));
  187. } else if (string_caseInsensitiveMatch(first, U"message")) {
  188. // Print a message while evaluating the build script.
  189. // This is not done while actually compiling, so it will not know if compilation and linking worked or not.
  190. printText(STRING_EXPR(1, tokens.length() - 1));
  191. } else {
  192. if (tokens.length() == 1) {
  193. // Mentioning an identifier without assigning anything will assign it to one as a boolean flag.
  194. assignValue(target, first, U"1");
  195. } else if (string_match(second, U"=")) {
  196. // TODO: Create in-place math and string operations with different types of assignments.
  197. // Maybe use a different syntax beginning with a keyword?
  198. // TODO: Look for the assignment operator dynamically if references to collection elements are allowed as l-value expressions.
  199. // Using an equality sign replaces any previous value of the variable.
  200. assignValue(target, first, STRING_EXPR(2, tokens.length() - 1));
  201. } else {
  202. // TODO: Give better error messages.
  203. printText(U" Ignored unrecognized statement!\n");
  204. }
  205. }
  206. } else {
  207. if (string_caseInsensitiveMatch(first, U"if")) {
  208. target.currentStackDepth++;
  209. } else if (string_caseInsensitiveMatch(first, U"end")) {
  210. target.currentStackDepth--;
  211. }
  212. }
  213. }
  214. tokens.clear();
  215. }
  216. void evaluateScript(Machine &target, const ReadableString &scriptPath) {
  217. if (file_getEntryType(scriptPath) != EntryType::File) {
  218. printText(U"The script path ", scriptPath, U" does not exist!\n");
  219. }
  220. String projectContent = string_load(scriptPath);
  221. // Each new script being imported will have its own simulated current path for accessing files and such.
  222. String projectFolderPath = file_getAbsoluteParentFolder(scriptPath);
  223. String currentToken;
  224. List<String> currentLine; // Keep it fast and simple by only remembering tokens for the current line.
  225. bool quoted = false;
  226. bool commented = false;
  227. for (int i = 0; i <= string_length(projectContent); i++) {
  228. DsrChar c = projectContent[i];
  229. // The null terminator does not really exist in projectContent,
  230. // but dsr::String returns a null character safely when requesting a character out of bound,
  231. // which allow interpreting the last line without duplicating code.
  232. if (c == U'\n' || c == U'\0') {
  233. // Comment removing everything else.
  234. flushToken(currentLine, currentToken);
  235. interpretLine(target, currentLine, projectFolderPath);
  236. commented = false; // Automatically end comments at end of line.
  237. quoted = false; // Automatically end quotes at end of line.
  238. } else if (c == U'\"') {
  239. quoted = !quoted;
  240. string_appendChar(currentToken, c);
  241. } else if (c == U'#') {
  242. // Comment removing everything else until a new line comes.
  243. flushToken(currentLine, currentToken);
  244. interpretLine(target, currentLine, projectFolderPath);
  245. commented = true;
  246. } else if (!commented) {
  247. if (quoted) {
  248. // Insert character into quote.
  249. string_appendChar(currentToken, c);
  250. } else {
  251. if (c == U'(' || c == U')' || c == U'[' || c == U']' || c == U'{' || c == U'}' || c == U'=') {
  252. // Atomic token of a single character
  253. flushToken(currentLine, currentToken);
  254. string_appendChar(currentToken, c);
  255. flushToken(currentLine, currentToken);
  256. } else if (c == U' ' || c == U'\t') {
  257. // Whitespace
  258. flushToken(currentLine, currentToken);
  259. } else {
  260. // Insert unquoted character into token.
  261. string_appendChar(currentToken, c);
  262. }
  263. }
  264. }
  265. }
  266. }