generator.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. static int64_t findDependency(ProjectContext &context, const ReadableString& findPath);
  32. static void resolveConnection(Connection &connection);
  33. static void resolveDependency(Dependency &dependency);
  34. static String findSourceFile(const ReadableString& headerPath, bool acceptC, bool acceptCpp);
  35. static void flushToken(List<String> &target, String &currentToken);
  36. static void tokenize(List<String> &target, const ReadableString& line);
  37. static void interpretPreprocessing(ProjectContext &context, int64_t parentIndex, const List<String> &tokens, const ReadableString &parentFolder, int64_t lineNumber);
  38. static void analyzeCode(ProjectContext &context, int64_t parentIndex, String content, const ReadableString &parentFolder);
  39. static int64_t findDependency(ProjectContext &context, const ReadableString& findPath) {
  40. for (int d = 0; d < context.dependencies.length(); d++) {
  41. if (string_match(context.dependencies[d].path, findPath)) {
  42. return d;
  43. }
  44. }
  45. return -1;
  46. }
  47. static void resolveConnection(ProjectContext &context, Connection &connection) {
  48. connection.dependencyIndex = findDependency(context, connection.path);
  49. }
  50. static void resolveDependency(ProjectContext &context, Dependency &dependency) {
  51. for (int l = 0; l < dependency.links.length(); l++) {
  52. resolveConnection(context, dependency.links[l]);
  53. }
  54. for (int i = 0; i < dependency.includes.length(); i++) {
  55. resolveConnection(context, dependency.includes[i]);
  56. }
  57. }
  58. void resolveDependencies(ProjectContext &context) {
  59. for (int d = 0; d < context.dependencies.length(); d++) {
  60. resolveDependency(context, context.dependencies[d]);
  61. }
  62. }
  63. static String findSourceFile(const ReadableString& headerPath, bool acceptC, bool acceptCpp) {
  64. if (file_hasExtension(headerPath)) {
  65. ReadableString extensionlessPath = file_getExtensionless(headerPath);
  66. String cPath = extensionlessPath + U".c";
  67. String cppPath = extensionlessPath + U".cpp";
  68. if (acceptC && file_getEntryType(cPath) == EntryType::File) {
  69. return cPath;
  70. } else if (acceptCpp && file_getEntryType(cppPath) == EntryType::File) {
  71. return cppPath;
  72. }
  73. }
  74. return U"";
  75. }
  76. static void flushToken(List<String> &target, String &currentToken) {
  77. if (string_length(currentToken) > 0) {
  78. target.push(currentToken);
  79. currentToken = U"";
  80. }
  81. }
  82. static void tokenize(List<String> &target, const ReadableString& line) {
  83. String currentToken;
  84. for (int i = 0; i < string_length(line); i++) {
  85. DsrChar c = line[i];
  86. DsrChar nextC = line[i + 1];
  87. if (c == U'#' && nextC == U'#') {
  88. // Appending tokens using ##
  89. i++;
  90. } else if (c == U'#' || c == U'(' || c == U')' || c == U'[' || c == U']' || c == U'{' || c == U'}') {
  91. // Atomic token of a single character
  92. flushToken(target, currentToken);
  93. string_appendChar(currentToken, c);
  94. flushToken(target, currentToken);
  95. } else if (c == U' ' || c == U'\t') {
  96. // Whitespace
  97. flushToken(target, currentToken);
  98. } else {
  99. string_appendChar(currentToken, c);
  100. }
  101. }
  102. flushToken(target, currentToken);
  103. }
  104. static void interpretPreprocessing(ProjectContext &context, int64_t parentIndex, const List<String> &tokens, const ReadableString &parentFolder, int64_t lineNumber) {
  105. if (tokens.length() >= 3) {
  106. if (string_match(tokens[1], U"include")) {
  107. if (tokens[2][0] == U'\"') {
  108. String relativePath = string_unmangleQuote(tokens[2]);
  109. String absolutePath = file_getTheoreticalAbsolutePath(relativePath, parentFolder, LOCAL_PATH_SYNTAX);
  110. context.dependencies[parentIndex].includes.pushConstruct(absolutePath, lineNumber);
  111. analyzeFromFile(context, absolutePath);
  112. }
  113. }
  114. }
  115. }
  116. static void analyzeCode(ProjectContext &context, int64_t parentIndex, String content, const ReadableString &parentFolder) {
  117. List<String> tokens;
  118. bool continuingLine = false;
  119. int64_t lineNumber = 0;
  120. string_split_callback(content, U'\n', true, [&parentIndex, &parentFolder, &tokens, &continuingLine, &lineNumber, &context](ReadableString line) {
  121. lineNumber++;
  122. if (line[0] == U'#' || continuingLine) {
  123. tokenize(tokens, line);
  124. // Continuing pre-processing line using \ at the end.
  125. continuingLine = line[string_length(line) - 1] == U'\\';
  126. } else {
  127. continuingLine = false;
  128. }
  129. if (!continuingLine && tokens.length() > 0) {
  130. interpretPreprocessing(context, parentIndex, tokens, parentFolder, lineNumber);
  131. tokens.clear();
  132. }
  133. });
  134. }
  135. void analyzeFromFile(ProjectContext &context, const ReadableString& absolutePath) {
  136. if (findDependency(context, absolutePath) != -1) {
  137. // Already analyzed the current entry. Abort to prevent duplicate dependencies.
  138. return;
  139. }
  140. int lastDotIndex = string_findLast(absolutePath, U'.');
  141. if (lastDotIndex != -1) {
  142. Extension extension = extensionFromString(string_after(absolutePath, lastDotIndex));
  143. if (extension != Extension::Unknown) {
  144. // The old length will be the new dependency's index.
  145. int64_t parentIndex = context.dependencies.length();
  146. // Get the file's binary content.
  147. Buffer fileBuffer = file_loadBuffer(absolutePath);
  148. // Get the checksum
  149. uint64_t contentChecksum = checksum(fileBuffer);
  150. context.dependencies.pushConstruct(absolutePath, extension, contentChecksum);
  151. if (extension == Extension::H || extension == Extension::Hpp) {
  152. // The current file is a header, so look for an implementation with the corresponding name.
  153. String sourcePath = findSourceFile(absolutePath, extension == Extension::H, true);
  154. // If found:
  155. if (string_length(sourcePath) > 0) {
  156. // Remember that anything using the header will have to link with the implementation.
  157. context.dependencies[parentIndex].links.pushConstruct(sourcePath);
  158. // Look for included headers in the implementation file.
  159. analyzeFromFile(context, sourcePath);
  160. }
  161. }
  162. // Interpret the file's content.
  163. analyzeCode(context, parentIndex, string_loadFromMemory(fileBuffer), file_getRelativeParentFolder(absolutePath));
  164. }
  165. }
  166. }
  167. static void debugPrintDependencyList(const List<Connection> &connnections, const ReadableString verb) {
  168. for (int c = 0; c < connnections.length(); c++) {
  169. int64_t lineNumber = connnections[c].lineNumber;
  170. if (lineNumber != -1) {
  171. printText(U" @", lineNumber, U"\t");
  172. } else {
  173. printText(U" \t");
  174. }
  175. printText(U" ", verb, U" ", file_getPathlessName(connnections[c].path), U"\n");
  176. }
  177. }
  178. void printDependencies(ProjectContext &context) {
  179. for (int d = 0; d < context.dependencies.length(); d++) {
  180. printText(U"* ", file_getPathlessName(context.dependencies[d].path), U"\n");
  181. debugPrintDependencyList(context.dependencies[d].includes, U"including");
  182. debugPrintDependencyList(context.dependencies[d].links, U"linking");
  183. }
  184. }
  185. static void script_printMessage(ScriptTarget &output, const ReadableString message) {
  186. if (output.language == ScriptLanguage::Batch) {
  187. string_append(output.generatedCode, U"echo ", message, U"\n");
  188. } else if (output.language == ScriptLanguage::Bash) {
  189. string_append(output.generatedCode, U"echo ", message, U"\n");
  190. }
  191. }
  192. static void script_executeLocalBinary(ScriptTarget &output, const ReadableString fullPath) {
  193. if (output.language == ScriptLanguage::Batch) {
  194. string_append(output.generatedCode, fullPath, U"\n");
  195. } else if (output.language == ScriptLanguage::Bash) {
  196. string_append(output.generatedCode, fullPath, U";\n");
  197. }
  198. }
  199. static void traverserHeaderChecksums(ProjectContext &context, uint64_t &target, int64_t dependencyIndex) {
  200. // Use checksums from headers
  201. for (int h = 0; h < context.dependencies[dependencyIndex].includes.length(); h++) {
  202. int64_t includedIndex = context.dependencies[dependencyIndex].includes[h].dependencyIndex;
  203. if (!context.dependencies[includedIndex].visited) {
  204. //printText(U" traverserHeaderChecksums(context, ", includedIndex, U") ", context.dependencies[includedIndex].path, "\n");
  205. // Bitwise exclusive or is both order independent and entropy preserving for non-repeated content.
  206. target = target ^ context.dependencies[includedIndex].contentChecksum;
  207. // Just have to make sure that the same checksum is not used twice.
  208. context.dependencies[includedIndex].visited = true;
  209. // Use checksums from headers recursively
  210. traverserHeaderChecksums(context, target, includedIndex);
  211. }
  212. }
  213. }
  214. static uint64_t getCombinedChecksum(ProjectContext &context, int64_t dependencyIndex) {
  215. //printText(U"getCombinedChecksum(context, ", dependencyIndex, U") ", context.dependencies[dependencyIndex].path, "\n");
  216. for (int d = 0; d < context.dependencies.length(); d++) {
  217. context.dependencies[d].visited = false;
  218. }
  219. context.dependencies[dependencyIndex].visited = true;
  220. uint64_t result = context.dependencies[dependencyIndex].contentChecksum;
  221. traverserHeaderChecksums(context, result, dependencyIndex);
  222. return result;
  223. }
  224. struct SourceObject {
  225. uint64_t identityChecksum = 0; // Identification number for the object's name.
  226. uint64_t combinedChecksum = 0; // Combined content of the source file and all included headers recursively.
  227. String sourcePath, objectPath;
  228. SourceObject(ProjectContext &context, const ReadableString& sourcePath, const ReadableString& tempFolder, const ReadableString& identity, int64_t dependencyIndex)
  229. : identityChecksum(checksum(identity)), combinedChecksum(getCombinedChecksum(context, dependencyIndex)), sourcePath(sourcePath) {
  230. // By making the content checksum a part of the name, one can switch back to an older version without having to recompile everything again.
  231. // Just need to clean the temporary folder once in a while because old versions can take a lot of space.
  232. this->objectPath = file_combinePaths(tempFolder, string_combine(U"dfpsr_", this->identityChecksum, U"_", this->combinedChecksum, U".o"));
  233. }
  234. };
  235. void generateCompilationScript(ScriptTarget &output, ProjectContext &context, const Machine &settings, ReadableString programPath) {
  236. // Convert lists of linker and compiler flags into strings.
  237. // TODO: Give a warning if two contradictory flags are used, such as optimization levels and language versions.
  238. // TODO: Make sure that no spaces are inside of the flags, because that can mess up detection of pre-existing and contradictory arguments.
  239. String compilerFlags;
  240. for (int i = 0; i < settings.compilerFlags.length(); i++) {
  241. string_append(compilerFlags, " ", settings.compilerFlags[i]);
  242. }
  243. String linkerFlags;
  244. for (int i = 0; i < settings.linkerFlags.length(); i++) {
  245. string_append(linkerFlags, " -l", settings.linkerFlags[i]);
  246. }
  247. printText(U"Generating build instructions for ", programPath, U" using settings:\n");
  248. printText(U" Compiler flags:", compilerFlags, U"\n");
  249. printText(U" Linker flags:", linkerFlags, U"\n");
  250. for (int v = 0; v < settings.variables.length(); v++) {
  251. printText(U" * ", settings.variables[v].key, U" = ", settings.variables[v].value);
  252. if (settings.variables[v].inherited) {
  253. printText(U" (inherited input)");
  254. }
  255. printText(U"\n");
  256. }
  257. // The compiler is often a global alias, so the user must supply either an alias or an absolute path.
  258. ReadableString compilerName = getFlag(settings, U"Compiler", U"g++"); // Assume g++ as the compiler if not specified.
  259. ReadableString compileFrom = getFlag(settings, U"CompileFrom", U"");
  260. // Check if the build system was asked to run the compiler from a specific folder.
  261. bool changePath = (string_length(compileFrom) > 0);
  262. if (changePath) {
  263. printText(U"Using ", compilerName, " as the compiler executed from ", compileFrom, ".\n");
  264. } else {
  265. printText(U"Using ", compilerName, " as the compiler from the current directory.\n");
  266. }
  267. // TODO: Warn if -DNDEBUG, -DDEBUG, or optimization levels are given directly.
  268. // Using the variables instead is both more flexible by accepting input arguments
  269. // and keeping the same format to better reuse compiled objects.
  270. if (getFlagAsInteger(settings, U"Debug")) {
  271. printText(U"Building with debug mode.\n");
  272. string_append(compilerFlags, " -DDEBUG");
  273. } else {
  274. printText(U"Building with release mode.\n");
  275. string_append(compilerFlags, " -DNDEBUG");
  276. }
  277. if (getFlagAsInteger(settings, U"StaticRuntime")) {
  278. if (getFlagAsInteger(settings, U"Windows")) {
  279. printText(U"Building with static runtime. Your application's binary will be bigger but can run without needing any installer.\n");
  280. string_append(compilerFlags, " -static -static-libgcc -static-libstdc++");
  281. string_append(linkerFlags, " -static -static-libgcc -static-libstdc++");
  282. } else {
  283. printText(U"The target platform does not support static linking of runtime. But don't worry about bundling any runtimes, because it comes with most of the Posix compliant operating systems.\n");
  284. }
  285. } else {
  286. printText(U"Building with dynamic runtime. Don't forget to bundle the C and C++ runtimes for systems that don't have it pre-installed.\n");
  287. }
  288. ReadableString optimizationLevel = getFlag(settings, U"Optimization", U"2");
  289. printText(U"Building with optimization level ", optimizationLevel, U".\n");
  290. string_append(compilerFlags, " -O", optimizationLevel);
  291. List<SourceObject> sourceObjects;
  292. bool hasSourceCode = false;
  293. bool needCppCompiler = false;
  294. for (int d = 0; d < context.dependencies.length(); d++) {
  295. Extension extension = context.dependencies[d].extension;
  296. if (extension == Extension::Cpp) {
  297. needCppCompiler = true;
  298. }
  299. if (extension == Extension::C || extension == Extension::Cpp) {
  300. // Dependency paths are already absolute from the recursive search.
  301. String sourcePath = context.dependencies[d].path;
  302. String identity = string_combine(sourcePath, compilerFlags);
  303. sourceObjects.pushConstruct(context, sourcePath, output.tempPath, identity, d);
  304. if (file_getEntryType(sourcePath) != EntryType::File) {
  305. throwError(U"The source file ", sourcePath, U" could not be found!\n");
  306. } else {
  307. hasSourceCode = true;
  308. }
  309. }
  310. }
  311. if (hasSourceCode) {
  312. // TODO: Give a warning if a known C compiler incapable of handling C++ is given C++ source code when needCppCompiler is true.
  313. if (changePath) {
  314. // Go into the requested folder.
  315. if (output.language == ScriptLanguage::Batch) {
  316. string_append(output.generatedCode, "pushd ", compileFrom, "\n");
  317. } else if (output.language == ScriptLanguage::Bash) {
  318. string_append(output.generatedCode, U"(cd ", compileFrom, ";\n");
  319. }
  320. }
  321. String allObjects;
  322. for (int i = 0; i < sourceObjects.length(); i++) {
  323. if (output.language == ScriptLanguage::Batch) {
  324. string_append(output.generatedCode, U"if exist ", sourceObjects[i].objectPath, U" (\n");
  325. } else if (output.language == ScriptLanguage::Bash) {
  326. string_append(output.generatedCode, U"if [ -e \"", sourceObjects[i].objectPath, U"\" ]; then\n");
  327. }
  328. script_printMessage(output, string_combine(U"Reusing ", sourceObjects[i].sourcePath, U" ID:", sourceObjects[i].identityChecksum, U"."));
  329. if (output.language == ScriptLanguage::Batch) {
  330. string_append(output.generatedCode, U") else (\n");
  331. } else if (output.language == ScriptLanguage::Bash) {
  332. string_append(output.generatedCode, U"else\n");
  333. }
  334. script_printMessage(output, string_combine(U"Compiling ", sourceObjects[i].sourcePath, U" ID:", sourceObjects[i].identityChecksum, U" with \"", compilerFlags, U"\"."));
  335. string_append(output.generatedCode, compilerName, compilerFlags, U" -c ", sourceObjects[i].sourcePath, U" -o ", sourceObjects[i].objectPath, U"\n");
  336. if (output.language == ScriptLanguage::Batch) {
  337. string_append(output.generatedCode, ")\n");
  338. } else if (output.language == ScriptLanguage::Bash) {
  339. string_append(output.generatedCode, U"fi\n");
  340. }
  341. // Remember each object name for linking.
  342. string_append(allObjects, U" ", sourceObjects[i].objectPath);
  343. }
  344. script_printMessage(output, string_combine(U"Linking with \"", linkerFlags, U"\"."));
  345. string_append(output.generatedCode, compilerName, allObjects, linkerFlags, U" -o ", programPath, U"\n");
  346. if (changePath) {
  347. // Get back to the previous folder.
  348. if (output.language == ScriptLanguage::Batch) {
  349. string_append(output.generatedCode, "popd\n");
  350. } else if (output.language == ScriptLanguage::Bash) {
  351. string_append(output.generatedCode, U")\n");
  352. }
  353. }
  354. script_printMessage(output, U"Done building.");
  355. if (getFlagAsInteger(settings, U"Supressed")) {
  356. script_printMessage(output, string_combine(U"Execution of ", programPath, U" was supressed using the Supressed flag."));
  357. } else {
  358. script_printMessage(output, string_combine(U"Starting ", programPath));
  359. script_executeLocalBinary(output, programPath);
  360. script_printMessage(output, U"The program terminated.");
  361. }
  362. } else {
  363. printText("Filed to find any source code to compile.\n");
  364. }
  365. }