generator.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. 
  2. #include "generator.h"
  3. using namespace dsr;
  4. static uint64_t checksum(const ReadableString& text) {
  5. uint64_t a = 0x8C2A03D4;
  6. uint64_t b = 0xF42B1583;
  7. uint64_t c = 0xA6815E74;
  8. uint64_t d = 0;
  9. for (int i = 0; i < string_length(text); i++) {
  10. a = (b * c + ((i * 3756 + 2654) & 58043)) & 0xFFFFFFFF;
  11. b = (231 + text[i] * (a & 154) + c * 867 + 28294061) & 0xFFFFFFFF;
  12. c = (a ^ b ^ (text[i] * 1543217521)) & 0xFFFFFFFF;
  13. d = d ^ (a << 32) ^ b ^ (c << 16);
  14. }
  15. return d;
  16. }
  17. static uint64_t checksum(const Buffer& buffer) {
  18. SafePointer<uint8_t> data = buffer_getSafeData<uint8_t>(buffer, "checksum input buffer");
  19. uint64_t a = 0x8C2A03D4;
  20. uint64_t b = 0xF42B1583;
  21. uint64_t c = 0xA6815E74;
  22. uint64_t d = 0;
  23. for (int i = 0; i < buffer_getSize(buffer); i++) {
  24. a = (b * c + ((i * 3756 + 2654) & 58043)) & 0xFFFFFFFF;
  25. b = (231 + data[i] * (a & 154) + c * 867 + 28294061) & 0xFFFFFFFF;
  26. c = (a ^ b ^ (data[i] * 1543217521)) & 0xFFFFFFFF;
  27. d = d ^ (a << 32) ^ b ^ (c << 16);
  28. }
  29. return d;
  30. }
  31. struct Connection {
  32. String path;
  33. int64_t lineNumber = -1;
  34. int64_t dependencyIndex = -1;
  35. Connection(const ReadableString& path)
  36. : path(path) {}
  37. Connection(const ReadableString& path, int64_t lineNumber)
  38. : path(path), lineNumber(lineNumber) {}
  39. };
  40. enum class Extension {
  41. Unknown, H, Hpp, C, Cpp
  42. };
  43. static Extension extensionFromString(const ReadableString& extensionName) {
  44. String upperName = string_upperCase(string_removeOuterWhiteSpace(extensionName));
  45. Extension result = Extension::Unknown;
  46. if (string_match(upperName, U"H")) {
  47. result = Extension::H;
  48. } else if (string_match(upperName, U"HPP")) {
  49. result = Extension::Hpp;
  50. } else if (string_match(upperName, U"C")) {
  51. result = Extension::C;
  52. } else if (string_match(upperName, U"CPP")) {
  53. result = Extension::Cpp;
  54. }
  55. return result;
  56. }
  57. struct Dependency {
  58. String path;
  59. Extension extension;
  60. uint64_t contentChecksum;
  61. bool visited; // Used to avoid infinite loops while traversing dependencies.
  62. List<Connection> links; // Depends on having these linked after compiling.
  63. List<Connection> includes; // Depends on having these included in pre-processing.
  64. Dependency(const ReadableString& path, Extension extension, uint64_t contentChecksum)
  65. : path(path), extension(extension), contentChecksum(contentChecksum) {}
  66. };
  67. List<Dependency> dependencies;
  68. static int64_t findDependency(const ReadableString& findPath);
  69. static void resolveConnection(Connection &connection);
  70. static void resolveDependency(Dependency &dependency);
  71. static String findSourceFile(const ReadableString& headerPath, bool acceptC, bool acceptCpp);
  72. static void flushToken(List<String> &target, String &currentToken);
  73. static void tokenize(List<String> &target, const ReadableString& line);
  74. static void interpretPreprocessing(int64_t parentIndex, const List<String> &tokens, const ReadableString &parentFolder, int64_t lineNumber);
  75. static void interpretPreprocessing(int64_t parentIndex, const List<String> &tokens, const ReadableString &parentFolder, int64_t lineNumber);
  76. static void analyzeCode(int64_t parentIndex, String content, const ReadableString &parentFolder);
  77. static int64_t findDependency(const ReadableString& findPath) {
  78. for (int d = 0; d < dependencies.length(); d++) {
  79. if (string_match(dependencies[d].path, findPath)) {
  80. return d;
  81. }
  82. }
  83. return -1;
  84. }
  85. static void resolveConnection(Connection &connection) {
  86. connection.dependencyIndex = findDependency(connection.path);
  87. }
  88. static void resolveDependency(Dependency &dependency) {
  89. for (int l = 0; l < dependency.links.length(); l++) {
  90. resolveConnection(dependency.links[l]);
  91. }
  92. for (int i = 0; i < dependency.includes.length(); i++) {
  93. resolveConnection(dependency.includes[i]);
  94. }
  95. }
  96. void resolveDependencies() {
  97. for (int d = 0; d < dependencies.length(); d++) {
  98. resolveDependency(dependencies[d]);
  99. }
  100. }
  101. static String findSourceFile(const ReadableString& headerPath, bool acceptC, bool acceptCpp) {
  102. int lastDotIndex = string_findLast(headerPath, U'.');
  103. if (lastDotIndex != -1) {
  104. ReadableString extensionlessPath = string_removeOuterWhiteSpace(string_before(headerPath, lastDotIndex));
  105. String cPath = extensionlessPath + U".c";
  106. String cppPath = extensionlessPath + U".cpp";
  107. if (acceptC && file_getEntryType(cPath) == EntryType::File) {
  108. return cPath;
  109. } else if (acceptCpp && file_getEntryType(cppPath) == EntryType::File) {
  110. return cppPath;
  111. }
  112. }
  113. return U"";
  114. }
  115. static void flushToken(List<String> &target, String &currentToken) {
  116. if (string_length(currentToken) > 0) {
  117. target.push(currentToken);
  118. currentToken = U"";
  119. }
  120. }
  121. static void tokenize(List<String> &target, const ReadableString& line) {
  122. String currentToken;
  123. for (int i = 0; i < string_length(line); i++) {
  124. DsrChar c = line[i];
  125. DsrChar nextC = line[i + 1];
  126. if (c == U'#' && nextC == U'#') {
  127. // Appending tokens using ##
  128. i++;
  129. } else if (c == U'#' || c == U'(' || c == U')' || c == U'[' || c == U']' || c == U'{' || c == U'}') {
  130. // Atomic token of a single character
  131. flushToken(target, currentToken);
  132. string_appendChar(currentToken, c);
  133. flushToken(target, currentToken);
  134. } else if (c == U' ' || c == U'\t') {
  135. // Whitespace
  136. flushToken(target, currentToken);
  137. } else {
  138. string_appendChar(currentToken, c);
  139. }
  140. }
  141. flushToken(target, currentToken);
  142. }
  143. static void interpretPreprocessing(int64_t parentIndex, const List<String> &tokens, const ReadableString &parentFolder, int64_t lineNumber) {
  144. if (tokens.length() >= 3) {
  145. if (string_match(tokens[1], U"include")) {
  146. if (tokens[2][0] == U'\"') {
  147. String relativePath = string_unmangleQuote(tokens[2]);
  148. String absolutePath = file_getTheoreticalAbsolutePath(relativePath, parentFolder, LOCAL_PATH_SYNTAX);
  149. dependencies[parentIndex].includes.pushConstruct(absolutePath, lineNumber);
  150. analyzeFromFile(absolutePath);
  151. }
  152. }
  153. }
  154. }
  155. static void analyzeCode(int64_t parentIndex, String content, const ReadableString &parentFolder) {
  156. List<String> tokens;
  157. bool continuingLine = false;
  158. int64_t lineNumber = 0;
  159. string_split_callback(content, U'\n', true, [&parentIndex, &parentFolder, &tokens, &continuingLine, &lineNumber](ReadableString line) {
  160. lineNumber++;
  161. if (line[0] == U'#' || continuingLine) {
  162. tokenize(tokens, line);
  163. // Continuing pre-processing line using \ at the end.
  164. continuingLine = line[string_length(line) - 1] == U'\\';
  165. } else {
  166. continuingLine = false;
  167. }
  168. if (!continuingLine && tokens.length() > 0) {
  169. interpretPreprocessing(parentIndex, tokens, parentFolder, lineNumber);
  170. tokens.clear();
  171. }
  172. });
  173. }
  174. void analyzeFromFile(const ReadableString& absolutePath) {
  175. if (findDependency(absolutePath) != -1) {
  176. // Already analyzed the current entry. Abort to prevent duplicate dependencies.
  177. return;
  178. }
  179. int lastDotIndex = string_findLast(absolutePath, U'.');
  180. if (lastDotIndex != -1) {
  181. Extension extension = extensionFromString(string_after(absolutePath, lastDotIndex));
  182. if (extension != Extension::Unknown) {
  183. // The old length will be the new dependency's index.
  184. int64_t parentIndex = dependencies.length();
  185. // Get the file's binary content.
  186. Buffer fileBuffer = file_loadBuffer(absolutePath);
  187. // Get the checksum
  188. uint64_t contentChecksum = checksum(fileBuffer);
  189. dependencies.pushConstruct(absolutePath, extension, contentChecksum);
  190. if (extension == Extension::H || extension == Extension::Hpp) {
  191. // The current file is a header, so look for an implementation with the corresponding name.
  192. String sourcePath = findSourceFile(absolutePath, extension == Extension::H, true);
  193. // If found:
  194. if (string_length(sourcePath) > 0) {
  195. // Remember that anything using the header will have to link with the implementation.
  196. dependencies[parentIndex].links.pushConstruct(sourcePath);
  197. // Look for included headers in the implementation file.
  198. analyzeFromFile(sourcePath);
  199. }
  200. }
  201. // Interpret the file's content.
  202. analyzeCode(parentIndex, string_loadFromMemory(fileBuffer), file_getRelativeParentFolder(absolutePath));
  203. }
  204. }
  205. }
  206. static void debugPrintDependencyList(const List<Connection> &connnections, const ReadableString verb) {
  207. for (int c = 0; c < connnections.length(); c++) {
  208. int64_t lineNumber = connnections[c].lineNumber;
  209. if (lineNumber != -1) {
  210. printText(U" @", lineNumber, U"\t");
  211. } else {
  212. printText(U" \t");
  213. }
  214. printText(U" ", verb, U" ", file_getPathlessName(connnections[c].path), U"\n");
  215. }
  216. }
  217. void printDependencies() {
  218. for (int d = 0; d < dependencies.length(); d++) {
  219. printText(U"* ", file_getPathlessName(dependencies[d].path), U"\n");
  220. debugPrintDependencyList(dependencies[d].includes, U"including");
  221. debugPrintDependencyList(dependencies[d].links, U"linking");
  222. }
  223. }
  224. static ScriptLanguage identifyLanguage(const ReadableString filename) {
  225. String scriptExtension = string_upperCase(file_getExtension(filename));
  226. if (string_match(scriptExtension, U"BAT")) {
  227. return ScriptLanguage::Batch;
  228. } else if (string_match(scriptExtension, U"SH")) {
  229. return ScriptLanguage::Bash;
  230. } else {
  231. throwError(U"Could not identify the scripting language of ", filename, U". Use *.bat or *.sh.\n");
  232. return ScriptLanguage::Unknown;
  233. }
  234. }
  235. static void script_printMessage(String &output, ScriptLanguage language, const ReadableString message) {
  236. if (language == ScriptLanguage::Batch) {
  237. string_append(output, U"echo ", message, U"\n");
  238. } else if (language == ScriptLanguage::Bash) {
  239. string_append(output, U"echo ", message, U"\n");
  240. }
  241. }
  242. static void script_executeLocalBinary(String &output, ScriptLanguage language, const ReadableString code) {
  243. if (language == ScriptLanguage::Batch) {
  244. string_append(output, code, ".exe\n");
  245. } else if (language == ScriptLanguage::Bash) {
  246. string_append(output, file_combinePaths(U".", code), U";\n");
  247. }
  248. }
  249. static void traverserHeaderChecksums(uint64_t &target, int64_t dependencyIndex) {
  250. // Use checksums from headers
  251. for (int h = 0; h < dependencies[dependencyIndex].includes.length(); h++) {
  252. int64_t includedIndex = dependencies[dependencyIndex].includes[h].dependencyIndex;
  253. if (!dependencies[includedIndex].visited) {
  254. //printText(U" traverserHeaderChecksums(", includedIndex, U") ", dependencies[includedIndex].path, "\n");
  255. // Bitwise exclusive or is both order independent and entropy preserving for non-repeated content.
  256. target = target ^ dependencies[includedIndex].contentChecksum;
  257. // Just have to make sure that the same checksum is not used twice.
  258. dependencies[includedIndex].visited = true;
  259. // Use checksums from headers recursively
  260. traverserHeaderChecksums(target, includedIndex);
  261. }
  262. }
  263. }
  264. static uint64_t getCombinedChecksum(int64_t dependencyIndex) {
  265. //printText(U"getCombinedChecksum(", dependencyIndex, U") ", dependencies[dependencyIndex].path, "\n");
  266. for (int d = 0; d < dependencies.length(); d++) {
  267. dependencies[d].visited = false;
  268. }
  269. dependencies[dependencyIndex].visited = true;
  270. uint64_t result = dependencies[dependencyIndex].contentChecksum;
  271. traverserHeaderChecksums(result, dependencyIndex);
  272. return result;
  273. }
  274. struct SourceObject {
  275. uint64_t identityChecksum = 0; // Identification number for the object's name.
  276. uint64_t combinedChecksum = 0; // Combined content of the source file and all included headers recursively.
  277. String sourcePath, objectPath;
  278. SourceObject(const ReadableString& sourcePath, const ReadableString& tempFolder, const ReadableString& identity, int64_t dependencyIndex)
  279. : identityChecksum(checksum(identity)), combinedChecksum(getCombinedChecksum(dependencyIndex)), sourcePath(sourcePath) {
  280. // By making the content checksum a part of the name, one can switch back to an older version without having to recompile everything again.
  281. // Just need to clean the temporary folder once in a while because old versions can take a lot of space.
  282. this->objectPath = file_combinePaths(tempFolder, string_combine(U"dfpsr_", this->identityChecksum, U"_", this->combinedChecksum, U".o"));
  283. }
  284. };
  285. void generateCompilationScript(const Machine &settings, const ReadableString& projectPath) {
  286. ReadableString scriptPath = getFlag(settings, U"ScriptPath", U"");
  287. ReadableString tempFolder = file_getAbsoluteParentFolder(scriptPath);
  288. if (string_length(scriptPath) == 0) {
  289. printText(U"No script path was given, skipping script generation\n");
  290. return;
  291. }
  292. ScriptLanguage language = identifyLanguage(scriptPath);
  293. scriptPath = file_getTheoreticalAbsolutePath(scriptPath, projectPath);
  294. // The compiler is often a global alias, so the user must supply either an alias or an absolute path.
  295. ReadableString compilerName = getFlag(settings, U"Compiler", U"g++"); // Assume g++ as the compiler if not specified.
  296. ReadableString compileFrom = getFlag(settings, U"CompileFrom", U"");
  297. // Check if the build system was asked to run the compiler from a specific folder.
  298. bool changePath = (string_length(compileFrom) > 0);
  299. if (changePath) {
  300. printText(U"Using ", compilerName, " as the compiler executed from ", compileFrom, ".\n");
  301. } else {
  302. printText(U"Using ", compilerName, " as the compiler from the current directory.\n");
  303. }
  304. // Convert lists of linker and compiler flags into strings.
  305. // TODO: Give a warning if two contradictory flags are used, such as optimization levels and language versions.
  306. // TODO: Make sure that no spaces are inside of the flags, because that can mess up detection of pre-existing and contradictory arguments.
  307. String compilerFlags;
  308. for (int i = 0; i < settings.compilerFlags.length(); i++) {
  309. string_append(compilerFlags, " ", settings.compilerFlags[i]);
  310. }
  311. String linkerFlags;
  312. for (int i = 0; i < settings.linkerFlags.length(); i++) {
  313. string_append(linkerFlags, " -l", settings.linkerFlags[i]);
  314. }
  315. // Interpret ProgramPath relative to the project path.
  316. ReadableString binaryPath = getFlag(settings, U"ProgramPath", language == ScriptLanguage::Batch ? U"program.exe" : U"program");
  317. binaryPath = file_getTheoreticalAbsolutePath(binaryPath, projectPath);
  318. String output;
  319. if (language == ScriptLanguage::Batch) {
  320. string_append(output, U"@echo off\n\n");
  321. } else if (language == ScriptLanguage::Bash) {
  322. string_append(output, U"#!/bin/bash\n\n");
  323. } else {
  324. printText(U"The type of script could not be identified for ", scriptPath, U"!\nUse *.bat for Batch or *.sh for Bash.\n");
  325. return;
  326. }
  327. List<SourceObject> sourceObjects;
  328. bool hasSourceCode = false;
  329. bool needCppCompiler = false;
  330. for (int d = 0; d < dependencies.length(); d++) {
  331. Extension extension = dependencies[d].extension;
  332. if (extension == Extension::Cpp) {
  333. needCppCompiler = true;
  334. }
  335. if (extension == Extension::C || extension == Extension::Cpp) {
  336. // Dependency paths are already absolute from the recursive search.
  337. String sourcePath = dependencies[d].path;
  338. String identity = string_combine(sourcePath, compilerFlags, projectPath);
  339. sourceObjects.pushConstruct(sourcePath, tempFolder, identity, d);
  340. if (file_getEntryType(sourcePath) != EntryType::File) {
  341. throwError(U"The source file ", sourcePath, U" could not be found!\n");
  342. } else {
  343. hasSourceCode = true;
  344. }
  345. }
  346. }
  347. if (hasSourceCode) {
  348. // TODO: Give a warning if a known C compiler incapable of handling C++ is given C++ source code when needCppCompiler is true.
  349. if (changePath) {
  350. // Go into the requested folder.
  351. if (language == ScriptLanguage::Batch) {
  352. string_append(output, "pushd ", compileFrom, "\n");
  353. } else if (language == ScriptLanguage::Bash) {
  354. string_append(output, U"(cd ", compileFrom, ";\n");
  355. }
  356. }
  357. String allObjects;
  358. for (int i = 0; i < sourceObjects.length(); i++) {
  359. if (language == ScriptLanguage::Batch) {
  360. string_append(output, U"if exist ", sourceObjects[i].objectPath, U" (\n");
  361. } else if (language == ScriptLanguage::Bash) {
  362. string_append(output, U"if [ -e \"", sourceObjects[i].objectPath, U"\" ]; then\n");
  363. }
  364. script_printMessage(output, language, string_combine(U"Reusing ", sourceObjects[i].sourcePath, U" ID:", sourceObjects[i].identityChecksum, U"."));
  365. if (language == ScriptLanguage::Batch) {
  366. string_append(output, U") else (\n");
  367. } else if (language == ScriptLanguage::Bash) {
  368. string_append(output, U"else\n");
  369. }
  370. script_printMessage(output, language, string_combine(U"Compiling ", sourceObjects[i].sourcePath, U" ID:", sourceObjects[i].identityChecksum, U" with ", compilerFlags, U"."));
  371. string_append(output, compilerName, compilerFlags, U" -c ", sourceObjects[i].sourcePath, U" -o ", sourceObjects[i].objectPath, U"\n");
  372. if (language == ScriptLanguage::Batch) {
  373. string_append(output, ")\n");
  374. } else if (language == ScriptLanguage::Bash) {
  375. string_append(output, U"fi\n");
  376. }
  377. // Remember each object name for linking.
  378. string_append(allObjects, U" ", sourceObjects[i].objectPath);
  379. }
  380. script_printMessage(output, language, string_combine(U"Linking with ", linkerFlags, U"."));
  381. string_append(output, compilerName, allObjects, linkerFlags, U" -o ", binaryPath, U"\n");
  382. if (changePath) {
  383. // Get back to the previous folder.
  384. if (language == ScriptLanguage::Batch) {
  385. string_append(output, "popd\n");
  386. } else if (language == ScriptLanguage::Bash) {
  387. string_append(output, U")\n");
  388. }
  389. }
  390. script_printMessage(output, language, U"Done compiling.");
  391. script_printMessage(output, language, string_combine(U"Starting ", binaryPath));
  392. script_executeLocalBinary(output, language, binaryPath);
  393. script_printMessage(output, language, U"The program terminated.");
  394. if (language == ScriptLanguage::Batch) {
  395. // Windows might close the window before you have time to read the results or error messages of a CLI application, so pause at the end.
  396. string_append(output, U"pause\n");
  397. }
  398. if (language == ScriptLanguage::Batch) {
  399. string_save(scriptPath, output);
  400. } else if (language == ScriptLanguage::Bash) {
  401. string_save(scriptPath, output, CharacterEncoding::BOM_UTF8, LineEncoding::Lf);
  402. }
  403. } else {
  404. printText("Filed to find any source code to compile.\n");
  405. }
  406. }