1 /** 2 Code to make the executable do what it does at runtime. 3 */ 4 module dpp.runtime.app; 5 6 import dpp.from; 7 8 /** 9 The "real" main 10 */ 11 void run(in from!"dpp.runtime.options".Options options) @safe { 12 import std.stdio: File; 13 import std.exception: enforce; 14 import std.process: execute; 15 import std.array: join; 16 import std.file: remove; 17 18 foreach(dppFileName; options.dppFileNames) 19 preprocess(options, dppFileName, options.toDFileName(dppFileName)); 20 21 if(options.preprocessOnly) return; 22 23 // See #102. We need some C++ boilerplate to link to the application. 24 scope(exit) if(options.cppStdLib) remove(CppBoilerplateCode.objFileName); 25 if(options.cppStdLib) CppBoilerplateCode.generate; 26 const cppExtraArgs = options.cppStdLib ? [CppBoilerplateCode.objFileName] : []; 27 28 const args = options.dlangCompiler ~ options.dlangCompilerArgs ~ cppExtraArgs; 29 const res = execute(args); 30 enforce(res.status == 0, "Could not execute `" ~ args.join(" ") ~ "`:\n" ~ res.output); 31 32 if(!options.keepDlangFiles) { 33 foreach(fileName; options.dFileNames) 34 remove(fileName); 35 } 36 } 37 38 39 // See #102. We need some C++ boilerplate to link to the application. 40 private struct CppBoilerplateCode { 41 42 enum baseFileName = "cpp_boilerplate"; 43 enum srcFileName = baseFileName ~ ".cpp"; 44 version(Windows) 45 enum objFileName = baseFileName ~ ".obj"; 46 else 47 enum objFileName = baseFileName ~ ".o"; 48 49 50 static void generate() @safe { 51 52 import std.stdio: File; 53 import std.file: remove; 54 55 writeSrcFile; 56 scope(exit) remove(srcFileName); 57 compileSrcFile; 58 } 59 60 ~this() @safe { 61 import std.file: remove; 62 remove(objFileName); 63 } 64 65 static void writeSrcFile() @safe { 66 import std.stdio: File; 67 68 auto file = File(srcFileName, "w"); 69 file.writeln(`#include <vector>`); 70 file.writeln(`void cpp_stdlib_boilerplate_dpp() {`); 71 file.writeln(` std::vector<bool> v;`); 72 file.writeln(` (void) (v[0] == v[0]);`); 73 file.writeln(` (void) (v.begin() == v.begin());`); 74 file.writeln(`}`); 75 } 76 77 static void compileSrcFile() @safe { 78 import std.process: execute; 79 import std.file: exists; 80 import std.exception: enforce; 81 82 const args = ["-c", srcFileName]; 83 const gccArgs = "g++" ~ args; 84 const clangArgs = "clang++" ~ args; 85 86 scope(success) enforce(objFileName.exists, objFileName ~ " was expected to exist but did not"); 87 88 const gccRet = execute(gccArgs); 89 if(gccRet.status == 0) return; 90 91 const clangRet = execute(clangArgs); 92 if(clangRet.status != 0) 93 throw new Exception("Could not compile C++ boilerplate with either gcc or clang"); 94 } 95 } 96 97 98 /** 99 Preprocesses a .dpp file, expanding #include directives inline while 100 translating all definitions, and redefines any macros defined therein. 101 102 The output is a valid D file that can be compiled. 103 104 Params: 105 options = The runtime options. 106 inputFileName = the name of the file to read 107 outputFileName = the name of the file to write 108 */ 109 private void preprocess(in from!"dpp.runtime.options".Options options, 110 in string inputFileName, 111 in string outputFileName) 112 @safe 113 { 114 import std.file: remove, exists, mkdirRecurse, copy; 115 import std.stdio: File; 116 import std.path: dirName; 117 118 const outputPath = outputFileName.dirName; 119 if(!outputPath.exists) mkdirRecurse(outputPath); 120 121 const tmpFileName = outputFileName ~ ".tmp"; 122 scope(exit) if(!options.keepPreCppFiles) remove(tmpFileName); 123 124 { 125 auto outputFile = File(tmpFileName, "w"); 126 127 const translationText = translationText(options, inputFileName); 128 129 writeUndefLines(inputFileName, outputFile); 130 131 outputFile.writeln(translationText.moduleDeclaration); 132 outputFile.writeln(preamble(options.ignoreMacros)); 133 outputFile.writeln(translationText.dlangDeclarations); 134 135 // write original D code 136 writeDlangLines(inputFileName, outputFile); 137 } 138 139 if(options.ignoreMacros) 140 copy(tmpFileName, outputFileName); 141 else 142 runCPreProcessor(options.cppPath, tmpFileName, outputFileName); 143 } 144 145 private struct TranslationText { 146 string moduleDeclaration; 147 string dlangDeclarations; 148 } 149 150 // the translated D code from all #included files 151 private TranslationText translationText(in from!"dpp.runtime.options".Options options, 152 in string inputFileName) 153 @safe 154 { 155 156 import dpp.runtime.context: Context, Language; 157 version(dpp2) 158 import dpp2.expansion: expand, isCppHeader, getHeaderName; 159 else 160 import dpp.expansion: expand, isCppHeader, getHeaderName; 161 import clang.util: getTempFileName; 162 163 import std.algorithm: map, filter; 164 import std.string: fromStringz; 165 import std.path: dirName; 166 import std.array: array, join; 167 import std.stdio: File; 168 169 auto inputFile = File(inputFileName); 170 const lines = () @trusted { return inputFile.byLine.map!(a => a.idup).array; }(); 171 auto moduleLines = () @trusted { return lines.filter!isModuleLine.array; }(); 172 auto nonModuleLines = lines.filter!(a => !isModuleLine(a)); 173 const includePaths = options.includePaths ~ inputFileName.dirName; 174 auto includes = nonModuleLines 175 .map!(a => getHeaderName(a, inputFileName, includePaths)) 176 .filter!(a => a != "") 177 ; 178 const includesFileName = getTempFileName(); 179 auto language = Language.C; 180 // write a temporary file with all #included files in it 181 () @trusted { 182 auto includesFile = File(includesFileName, "w"); 183 foreach(include; includes) { 184 includesFile.writeln(`#include "`, include, `"`); 185 if(isCppHeader(options, include)) language = Language.Cpp; 186 } 187 }(); 188 189 /** 190 We remember the cursors already seen so as to not try and define 191 something twice (legal in C, illegal in D). 192 */ 193 auto context = Context(options.dup, language); 194 195 // parse all #includes at once and populate context with 196 // D definitions 197 expand(includesFileName, context, includePaths); 198 199 context.fixNames; 200 201 return TranslationText(moduleLines.join("\n"), context.translation); 202 } 203 204 // write the original D code that doesn't need translating 205 private void writeUndefLines(in string inputFileName, ref from!"std.stdio".File outputFile) 206 @trusted 207 { 208 import std.stdio: File; 209 import std.algorithm: filter, canFind; 210 211 auto lines = File(inputFileName).byLine.filter!(l => l.canFind("#undef")); 212 foreach(line; lines) { 213 outputFile.writeln(line); 214 } 215 } 216 217 218 // write the original D code that doesn't need translating 219 private void writeDlangLines(in string inputFileName, ref from!"std.stdio".File outputFile) 220 @trusted 221 { 222 223 import dpp.expansion: getHeaderName; 224 import std.stdio: File; 225 import std.algorithm: filter; 226 227 foreach(line; File(inputFileName).byLine.filter!(a => !isModuleLine(a))) { 228 if(getHeaderName(line) == "") { 229 // not an #include directive, just pass through 230 outputFile.writeln(line); 231 } // otherwise do nothing 232 } 233 } 234 235 private bool isModuleLine(in const(char)[] line) @safe pure { 236 import std.string: stripLeft; 237 import std.algorithm: startsWith; 238 return line.stripLeft.startsWith("module "); 239 } 240 241 private void runCPreProcessor(in string cppPath, in string tmpFileName, in string outputFileName) @safe { 242 243 import std.exception: enforce; 244 import std.process: execute, Config; 245 import std.conv: text; 246 import std.string: join, splitLines; 247 import std.stdio: File; 248 import std.algorithm: filter, startsWith; 249 250 version (Windows) 251 enum cppDefault = "clang-cpp"; 252 else 253 enum cppDefault = "cpp"; 254 255 const cpp = cppPath == "" ? cppDefault : cppPath; 256 257 const cppArgs = [cpp, "-w", "--comments", tmpFileName]; 258 const ret = () { 259 try { 260 string[string] env; 261 return execute(cppArgs, env, Config.stderrPassThrough); 262 } catch (Exception e) 263 { 264 import std.typecons : Tuple; 265 return Tuple!(int, "status", string, "output")(-1, e.msg); 266 } 267 }(); 268 enforce(ret.status == 0, text("Could not run `", cppArgs.join(" "), "`:\n", ret.output)); 269 270 { 271 auto outputFile = File(outputFileName, "w"); 272 auto lines = ret. 273 output 274 .splitLines 275 .filter!(a => !a.startsWith("#")) 276 ; 277 278 foreach(line; lines) { 279 outputFile.writeln(line); 280 } 281 } 282 } 283 284 285 string preamble(bool ignoreMacros) @safe pure { 286 import std.array: replace, join; 287 import std.algorithm: map, filter; 288 import std.string: splitLines; 289 290 const vaArgs = ignoreMacros 291 ? "" 292 : " #define __gnuc_va_list va_list\n\n" ~ 293 " #define __is_empty(_Type) dpp.isEmpty!(_Type)\n"; 294 295 return q{ 296 297 import core.stdc.config; 298 import core.stdc.stdarg: va_list; 299 static import core.simd; 300 static import std.conv; 301 302 struct Int128 { long lower; long upper; } 303 struct UInt128 { ulong lower; ulong upper; } 304 305 struct __locale_data { int dummy; } // FIXME 306 } ~ 307 vaArgs ~ 308 309 q{ 310 alias _Bool = bool; 311 312 struct dpp { 313 314 static struct Opaque(int N) { 315 void[N] bytes; 316 } 317 318 // Replacement for the gcc/clang intrinsic 319 static bool isEmpty(T)() { 320 return T.tupleof.length == 0; 321 } 322 323 static struct Move(T) { 324 T* ptr; 325 } 326 327 // dmd bug causes a crash if T is passed by value. 328 // Works fine with ldc. 329 static auto move(T)(ref T value) { 330 return Move!T(&value); 331 } 332 333 mixin template EnumD(string name, T, string prefix) if(is(T == enum)) { 334 335 private static string _memberMixinStr(string member) { 336 import std.conv: text; 337 import std.array: replace; 338 return text(` `, member.replace(prefix, ""), ` = `, T.stringof, `.`, member, `,`); 339 } 340 341 private static string _enumMixinStr() { 342 import std.array: join; 343 344 string[] ret; 345 346 ret ~= "enum " ~ name ~ "{"; 347 348 static foreach(member; __traits(allMembers, T)) { 349 ret ~= _memberMixinStr(member); 350 } 351 352 ret ~= "}"; 353 354 return ret.join("\n"); 355 } 356 357 mixin(_enumMixinStr()); 358 } 359 } 360 } 361 .splitLines 362 .filter!(a => a != "") 363 .map!(a => a.length >= 8 ? a[8 .. $] : a) // get rid of leading spaces 364 .join("\n"); 365 }