generator.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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(String &output, ScriptLanguage language, const ReadableString message) {
  186. if (language == ScriptLanguage::Batch) {
  187. string_append(output, U"echo ", message, U"\n");
  188. } else if (language == ScriptLanguage::Bash) {
  189. string_append(output, U"echo ", message, U"\n");
  190. }
  191. }
  192. static void traverserHeaderChecksums(ProjectContext &context, uint64_t &target, int64_t dependencyIndex) {
  193. // Use checksums from headers
  194. for (int h = 0; h < context.dependencies[dependencyIndex].includes.length(); h++) {
  195. int64_t includedIndex = context.dependencies[dependencyIndex].includes[h].dependencyIndex;
  196. if (!context.dependencies[includedIndex].visited) {
  197. //printText(U" traverserHeaderChecksums(context, ", includedIndex, U") ", context.dependencies[includedIndex].path, "\n");
  198. // Bitwise exclusive or is both order independent and entropy preserving for non-repeated content.
  199. target = target ^ context.dependencies[includedIndex].contentChecksum;
  200. // Just have to make sure that the same checksum is not used twice.
  201. context.dependencies[includedIndex].visited = true;
  202. // Use checksums from headers recursively
  203. traverserHeaderChecksums(context, target, includedIndex);
  204. }
  205. }
  206. }
  207. static uint64_t getCombinedChecksum(ProjectContext &context, int64_t dependencyIndex) {
  208. //printText(U"getCombinedChecksum(context, ", dependencyIndex, U") ", context.dependencies[dependencyIndex].path, "\n");
  209. for (int d = 0; d < context.dependencies.length(); d++) {
  210. context.dependencies[d].visited = false;
  211. }
  212. context.dependencies[dependencyIndex].visited = true;
  213. uint64_t result = context.dependencies[dependencyIndex].contentChecksum;
  214. traverserHeaderChecksums(context, result, dependencyIndex);
  215. return result;
  216. }
  217. static int64_t findObject(SessionContext &source, uint64_t identityChecksum) {
  218. for (int64_t o = 0; o < source.sourceObjects.length(); o++) {
  219. if (source.sourceObjects[o].identityChecksum == identityChecksum) {
  220. return o;
  221. }
  222. }
  223. return -1;
  224. }
  225. void gatherBuildInstructions(SessionContext &output, ProjectContext &context, Machine &settings, ReadableString programPath) {
  226. // The compiler is often a global alias, so the user must supply either an alias or an absolute path.
  227. ReadableString compilerName = getFlag(settings, U"Compiler", U"g++"); // Assume g++ as the compiler if not specified.
  228. ReadableString compileFrom = getFlag(settings, U"CompileFrom", U"");
  229. // Check if the build system was asked to run the compiler from a specific folder.
  230. bool changePath = (string_length(compileFrom) > 0);
  231. if (changePath) {
  232. printText(U"Using ", compilerName, " as the compiler executed from ", compileFrom, ".\n");
  233. } else {
  234. printText(U"Using ", compilerName, " as the compiler from the current directory.\n");
  235. }
  236. // TODO: Warn if -DNDEBUG, -DDEBUG, or optimization levels are given directly.
  237. // Using the variables instead is both more flexible by accepting input arguments
  238. // and keeping the same format to better reuse compiled objects.
  239. if (getFlagAsInteger(settings, U"Debug")) {
  240. printText(U"Building with debug mode.\n");
  241. settings.compilerFlags.push(U"-DDEBUG");
  242. } else {
  243. printText(U"Building with release mode.\n");
  244. settings.compilerFlags.push(U"-DNDEBUG");
  245. }
  246. if (getFlagAsInteger(settings, U"StaticRuntime")) {
  247. if (getFlagAsInteger(settings, U"Windows")) {
  248. printText(U"Building with static runtime. Your application's binary will be bigger but can run without needing any installer.\n");
  249. settings.compilerFlags.push(U"-static");
  250. settings.compilerFlags.push(U"-static-libgcc");
  251. settings.compilerFlags.push(U"-static-libstdc++");
  252. settings.linkerFlags.push(U"-static");
  253. settings.linkerFlags.push(U"-static-libgcc");
  254. settings.linkerFlags.push(U"-static-libstdc++");
  255. } else {
  256. 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");
  257. }
  258. } else {
  259. 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");
  260. }
  261. ReadableString optimizationLevel = getFlag(settings, U"Optimization", U"2");
  262. printText(U"Building with optimization level ", optimizationLevel, U".\n");
  263. settings.compilerFlags.push(string_combine(U"-O", optimizationLevel));
  264. // Convert lists of linker and compiler flags into strings.
  265. // TODO: Give a warning if two contradictory flags are used, such as optimization levels and language versions.
  266. // TODO: Make sure that no spaces are inside of the flags, because that can mess up detection of pre-existing and contradictory arguments.
  267. // TODO: Use groups of compiler flags, so that they can be generated in the last step.
  268. // This would allow calling the compiler directly when given a folder path for temporary files instead of a script path.
  269. String generatedCompilerFlags;
  270. for (int i = 0; i < settings.compilerFlags.length(); i++) {
  271. string_append(generatedCompilerFlags, " ", settings.compilerFlags[i]);
  272. }
  273. String linkerFlags;
  274. for (int i = 0; i < settings.linkerFlags.length(); i++) {
  275. string_append(linkerFlags, " -l", settings.linkerFlags[i]);
  276. }
  277. printText(U"Generating build instructions for ", programPath, U" using settings:\n");
  278. printText(U" Compiler flags:", generatedCompilerFlags, U"\n");
  279. printText(U" Linker flags:", linkerFlags, U"\n");
  280. for (int v = 0; v < settings.variables.length(); v++) {
  281. printText(U" * ", settings.variables[v].key, U" = ", settings.variables[v].value);
  282. if (settings.variables[v].inherited) {
  283. printText(U" (inherited input)");
  284. }
  285. printText(U"\n");
  286. }
  287. printText(U"Listing source files to compile in the current session.\n");
  288. // The current project's global indices to objects shared between all projects being built during the session.
  289. List<int64_t> sourceObjectIndices;
  290. bool hasSourceCode = false;
  291. for (int d = 0; d < context.dependencies.length(); d++) {
  292. Extension extension = context.dependencies[d].extension;
  293. if (extension == Extension::C || extension == Extension::Cpp) {
  294. // Dependency paths are already absolute from the recursive search.
  295. String sourcePath = context.dependencies[d].path;
  296. String identity = string_combine(sourcePath, generatedCompilerFlags);
  297. uint64_t identityChecksum = checksum(identity);
  298. int64_t previousIndex = findObject(output, identityChecksum);
  299. if (previousIndex == -1) {
  300. // Content checksums were created while scanning for source code, so now we just combine each source file's content checksum with all its headers to get the combined checksum.
  301. // The combined checksum represents the state after all headers are included recursively and given as input for compilation unit generating an object.
  302. uint64_t combinedChecksum = getCombinedChecksum(context, d);
  303. String objectPath = file_combinePaths(output.tempPath, string_combine(U"dfpsr_", identityChecksum, U"_", combinedChecksum, U".o"));
  304. sourceObjectIndices.push(output.sourceObjects.length());
  305. output.sourceObjects.pushConstruct(identityChecksum, combinedChecksum, sourcePath, objectPath, generatedCompilerFlags, compilerName, compileFrom);
  306. } else {
  307. // Link to this pre-existing source file.
  308. sourceObjectIndices.push(previousIndex);
  309. }
  310. hasSourceCode = true;
  311. }
  312. }
  313. if (hasSourceCode) {
  314. printText(U"Listing target executable ", programPath, " in the current session.\n");
  315. bool executeResult = getFlagAsInteger(settings, U"Supressed") == 0;
  316. output.linkerSteps.pushConstruct(compilerName, compileFrom, programPath, settings.linkerFlags, sourceObjectIndices, executeResult);
  317. } else {
  318. printText(U"Filed to find any source code to compile when building ", programPath, U".\n");
  319. }
  320. }
  321. static ScriptLanguage identifyLanguage(const ReadableString &filename) {
  322. String scriptExtension = string_upperCase(file_getExtension(filename));
  323. if (string_match(scriptExtension, U"BAT")) {
  324. return ScriptLanguage::Batch;
  325. } else if (string_match(scriptExtension, U"SH")) {
  326. return ScriptLanguage::Bash;
  327. } else {
  328. throwError(U"Could not identify the scripting language of ", filename, U". Use *.bat or *.sh.\n");
  329. return ScriptLanguage::Unknown;
  330. }
  331. }
  332. void setCompilationFolder(String &generatedCode, ScriptLanguage language, String &currentPath, const ReadableString &newPath) {
  333. if (!string_match(currentPath, newPath)) {
  334. if (string_length(currentPath) > 0) {
  335. if (language == ScriptLanguage::Batch) {
  336. string_append(generatedCode, "popd\n");
  337. } else if (language == ScriptLanguage::Bash) {
  338. string_append(generatedCode, U")\n");
  339. }
  340. }
  341. if (string_length(newPath) > 0) {
  342. if (language == ScriptLanguage::Batch) {
  343. string_append(generatedCode, "pushd ", newPath, "\n");
  344. } else if (language == ScriptLanguage::Bash) {
  345. string_append(generatedCode, U"(cd ", newPath, ";\n");
  346. }
  347. }
  348. }
  349. }
  350. void generateCompilationScript(SessionContext &input, const ReadableString &scriptPath) {
  351. printText(U"Generating build script\n");
  352. String generatedCode;
  353. ScriptLanguage language = identifyLanguage(scriptPath);
  354. if (language == ScriptLanguage::Batch) {
  355. string_append(generatedCode, U"@echo off\n\n");
  356. } else if (language == ScriptLanguage::Bash) {
  357. string_append(generatedCode, U"#!/bin/bash\n\n");
  358. }
  359. // Keep track of the current path, so that it only changes when needed.
  360. String currentPath;
  361. // Generate code for compiling source code into objects.
  362. printText(U"Generating code for compiling ", input.sourceObjects.length(), U" objects.\n");
  363. for (int o = 0; o < input.sourceObjects.length(); o++) {
  364. SourceObject *sourceObject = &(input.sourceObjects[o]);
  365. printText(U"\t* ", sourceObject->sourcePath, U"\n");
  366. setCompilationFolder(generatedCode, language, currentPath, sourceObject->compileFrom);
  367. if (language == ScriptLanguage::Batch) {
  368. string_append(generatedCode, U"if exist ", sourceObject->objectPath, U" (\n");
  369. } else if (language == ScriptLanguage::Bash) {
  370. string_append(generatedCode, U"if [ -e \"", sourceObject->objectPath, U"\" ]; then\n");
  371. }
  372. script_printMessage(generatedCode, language, string_combine(U"Reusing ", sourceObject->sourcePath, U" ID:", sourceObject->identityChecksum, U"."));
  373. if (language == ScriptLanguage::Batch) {
  374. string_append(generatedCode, U") else (\n");
  375. } else if (language == ScriptLanguage::Bash) {
  376. string_append(generatedCode, U"else\n");
  377. }
  378. String compilerFlags = sourceObject->generatedCompilerFlags;
  379. script_printMessage(generatedCode, language, string_combine(U"Compiling ", sourceObject->sourcePath, U" ID:", sourceObject->identityChecksum, U" with ", compilerFlags, U"."));
  380. string_append(generatedCode, sourceObject->compilerName, compilerFlags, U" -c ", sourceObject->sourcePath, U" -o ", sourceObject->objectPath, U"\n");
  381. if (language == ScriptLanguage::Batch) {
  382. string_append(generatedCode, ")\n");
  383. } else if (language == ScriptLanguage::Bash) {
  384. string_append(generatedCode, U"fi\n");
  385. }
  386. }
  387. // Generate code for linking objects into executables.
  388. printText(U"Generating code for linking ", input.linkerSteps.length(), U" executables:\n");
  389. for (int l = 0; l < input.linkerSteps.length(); l++) {
  390. LinkingStep *linkingStep = &(input.linkerSteps[l]);
  391. String programPath = linkingStep->binaryName;
  392. printText(U"\tGenerating code for linking ", programPath, U" of :\n");
  393. setCompilationFolder(generatedCode, language, currentPath, linkingStep->compileFrom);
  394. String linkerFlags;
  395. for (int lib = 0; lib < linkingStep->linkerFlags.length(); lib++) {
  396. String library = linkingStep->linkerFlags[lib];
  397. string_append(linkerFlags, " -l", library);
  398. printText(U"\t\t* ", library, U" library\n");
  399. }
  400. // Generate a list of object paths from indices.
  401. String allObjects;
  402. for (int i = 0; i < linkingStep->sourceObjectIndices.length(); i++) {
  403. int64_t objectIndex = linkingStep->sourceObjectIndices[i];
  404. SourceObject *sourceObject = &(input.sourceObjects[objectIndex]);
  405. if (objectIndex >= 0 || objectIndex < input.sourceObjects.length()) {
  406. printText(U"\t\t* ", sourceObject->sourcePath, U"\n");
  407. string_append(allObjects, U" ", sourceObject->objectPath);
  408. } else {
  409. throwError(U"Object index ", objectIndex, U" is out of bound ", 0, U"..", (input.sourceObjects.length() - 1), U"\n");
  410. }
  411. }
  412. // Generate the code for building.
  413. if (string_length(linkerFlags) > 0) {
  414. script_printMessage(generatedCode, language, string_combine(U"Linking ", programPath, U" with", linkerFlags, U"."));
  415. } else {
  416. script_printMessage(generatedCode, language, string_combine(U"Linking ", programPath, U"."));
  417. }
  418. string_append(generatedCode, linkingStep->compilerName, allObjects, linkerFlags, U" -o ", programPath, U"\n");
  419. if (linkingStep->executeResult) {
  420. script_printMessage(generatedCode, language, string_combine(U"Starting ", programPath));
  421. string_append(generatedCode, programPath, U"\n");
  422. script_printMessage(generatedCode, language, U"The program terminated.");
  423. }
  424. }
  425. setCompilationFolder(generatedCode, language, currentPath, U"");
  426. script_printMessage(generatedCode, language, U"Done building.");
  427. // Save the script.
  428. printText(U"Saving script to ", scriptPath, "\n");
  429. if (language == ScriptLanguage::Batch) {
  430. string_save(scriptPath, generatedCode);
  431. } else if (language == ScriptLanguage::Bash) {
  432. string_save(scriptPath, generatedCode, CharacterEncoding::BOM_UTF8, LineEncoding::Lf);
  433. }
  434. }