-
-
Notifications
You must be signed in to change notification settings - Fork 607
/
build.d
executable file
·2388 lines (2110 loc) · 80.1 KB
/
build.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env rdmd
/**
DMD builder
Usage:
./build.d dmd
See `--help` for targets.
detab, tolf, install targets - require the D Language Tools (detab.exe, tolf.exe)
https://github.com/dlang/tools.
zip target - requires Info-ZIP or equivalent (zip32.exe)
http://www.info-zip.org/Zip.html#Downloads
*/
version(CoreDdoc) {} else:
import std.algorithm, std.conv, std.datetime, std.exception, std.file, std.format, std.functional,
std.getopt, std.path, std.process, std.range, std.stdio, std.string, std.traits;
import std.parallelism : TaskPool, totalCPUs;
const thisBuildScript = __FILE_FULL_PATH__.buildNormalizedPath;
const srcDir = thisBuildScript.dirName;
const compilerDir = srcDir.dirName;
const dmdRepo = compilerDir.dirName;
const testDir = compilerDir.buildPath("test");
shared bool verbose; // output verbose logging
shared bool force; // always build everything (ignores timestamp checking)
shared bool dryRun; /// dont execute targets, just print command to be executed
__gshared int jobs; // Number of jobs to run in parallel
__gshared string[string] env;
__gshared string[][string] flags;
__gshared typeof(sourceFiles()) sources;
__gshared TaskPool taskPool;
/// Array of build rules through which all other build rules can be reached
immutable rootRules = [
&dmdDefault,
&dmdPGO,
&runDmdUnittest,
&clean,
&checkwhitespace,
&runTests,
&buildFrontendHeaders,
&runCxxHeadersTest,
&runCxxUnittest,
&detab,
&tolf,
&zip,
&html,
&toolchainInfo,
&style,
&man,
&installCopy,
];
int main(string[] args)
{
try
{
runMain(args);
return 0;
}
catch (BuildException e)
{
writeln(e.msg);
if (e.details)
{
writeln("DETAILS:\n");
writeln(e.details);
}
return 1;
}
}
void runMain(string[] args)
{
jobs = totalCPUs;
bool calledFromMake = false;
auto res = getopt(args,
"j|jobs", "Specifies the number of jobs (commands) to run simultaneously (default: %d)".format(totalCPUs), &jobs,
"v|verbose", "Verbose command output", cast(bool*) &verbose,
"f|force", "Force run (ignore timestamps and always run all tests)", cast(bool*) &force,
"d|dry-run", "Print commands instead of executing them", cast(bool*) &dryRun,
"called-from-make", "Calling the build script from the Makefile", &calledFromMake
);
void showHelp()
{
defaultGetoptPrinter(`./build.d <targets>...
Examples
--------
./build.d dmd # build DMD
./build.d unittest # runs internal unittests
./build.d clean # remove all generated files
./build.d generated/linux/release/64/dmd.conf
./build.d dmd-pgo # builds dmd with PGO data, currently only LDC is supported
Important variables:
--------------------
HOST_DMD: Host D compiler to use for bootstrapping
AUTO_BOOTSTRAP: Enable auto-boostrapping by downloading a stable DMD binary
MODEL: Target architecture to build for (32,64) - defaults to the host architecture
Build modes:
------------
BUILD: release (default) | debug (enabled a build with debug instructions)
Opt-in build features:
ENABLE_RELEASE: Optimized release build
ENABLE_DEBUG: Add debug instructions and symbols (set if ENABLE_RELEASE isn't set)
ENABLE_ASSERTS: Don't use -release if ENABLE_RELEASE is set
ENABLE_LTO: Enable link-time optimizations
ENABLE_UNITTEST: Build dmd with unittests (sets ENABLE_COVERAGE=1)
ENABLE_PROFILE: Build dmd with a profiling recorder (D)
ENABLE_COVERAGE Build dmd with coverage counting
ENABLE_SANITIZERS Build dmd with sanitizer (e.g. ENABLE_SANITIZERS=address,undefined)
Targets
-------
` ~ targetsHelp ~ `
The generated files will be in generated/$(OS)/$(BUILD)/$(MODEL) (` ~ env["G"] ~ `)
Command-line parameters
-----------------------
`, res.options);
return;
}
// workaround issue https://issues.dlang.org/show_bug.cgi?id=13727
version (CRuntime_DigitalMars)
{
pragma(msg, "Warning: Parallel builds disabled because of Issue 13727!");
jobs = min(jobs, 1); // Fall back to a sequential build
}
if (jobs <= 0)
abortBuild("Invalid number of jobs: %d".format(jobs));
taskPool = new TaskPool(jobs - 1); // Main thread is active too
scope (exit) taskPool.finish();
scope (failure) taskPool.stop();
// parse arguments
args.popFront;
args2Environment(args);
parseEnvironment;
processEnvironment;
processEnvironmentCxx;
sources = sourceFiles;
if (res.helpWanted)
return showHelp;
// Since we're ultimately outputting to a TTY, force colored output
// A more proper solution would be to redirect DMD's output to this script's
// output using `std.process`', but it's more involved and the following
// "just works"
version(Posix) // UPDATE: only when ANSII color codes are supported, that is. Don't do this on Windows.
if (!flags["DFLAGS"].canFind("-color=off") &&
[env["HOST_DMD_RUN"], "-color=on", "-h"].tryRun().status == 0)
flags["DFLAGS"] ~= "-color=on";
// default target
if (!args.length)
args = ["dmd"];
auto targets = predefinedTargets(args); // preprocess
if (targets.length == 0)
return showHelp;
if (verbose)
{
log("================================================================================");
foreach (key, value; env)
log("%s=%s", key, value);
foreach (key, value; flags)
log("%s=%-(%s %)", key, value);
log("================================================================================");
}
{
File lockFile;
if (calledFromMake)
{
// If called from make, use an interprocess lock so that parallel builds don't stomp on each other
lockFile = File(env["GENERATED"].buildPath("build.lock"), "w");
lockFile.lock();
}
scope (exit)
{
if (calledFromMake)
{
lockFile.unlock();
lockFile.close();
}
}
Scheduler.build(targets);
}
writeln("Success");
}
/// Generate list of targets for use in the help message
string targetsHelp()
{
string result = "";
foreach (rule; BuildRuleRange(rootRules.map!(a => a()).array))
{
if (rule.name)
{
enum defaultPrefix = "\n ";
result ~= rule.name;
string prefix = defaultPrefix[1 + rule.name.length .. $];
void add(string msg)
{
result ~= format("%s%s", prefix, msg);
prefix = defaultPrefix;
}
if (rule.description)
add(rule.description);
else if (rule.targets)
{
foreach (target; rule.targets)
{
add(target.relativePath);
}
}
result ~= "\n";
}
}
return result;
}
/**
D build rules
====================
The strategy of this script is to emulate what the Makefile is doing.
Below all individual rules of DMD are defined.
They have a target path, sources paths and an optional name.
When a rule is needed either its command or custom commandFunction is executed.
A rule will be skipped if all targets are older than all sources.
This script is by default part of the sources and thus any change to the build script,
will trigger a full rebuild.
*/
/// Returns: the rule that builds the lexer object file
alias lexer = makeRuleWithArgs!((MethodInitializer!BuildRule builder, BuildRule rule,
string suffix, string[] extraFlags)
=> builder
.name("lexer")
.target(env["G"].buildPath("lexer" ~ suffix).objName)
.sources(sources.lexer)
.deps([
versionFile,
sysconfDirFile,
common(suffix, extraFlags)
])
.msg("(DC) LEXER" ~ suffix)
.command([env["HOST_DMD_RUN"],
"-c",
"-of" ~ rule.target,
"-vtls",
"-J" ~ env["RES"]]
.chain(flags["DFLAGS"],
extraFlags,
// source files need to have relative paths in order for the code coverage
// .lst files to be named properly for CodeCov to find them
rule.sources.map!(e => e.relativePath(compilerDir))
).array
)
);
/// Returns: the rule that generates the dmd.conf/sc.ini file in the output folder
alias dmdConf = makeRule!((builder, rule) {
string exportDynamic;
version(OSX) {} else
exportDynamic = " -L--export-dynamic";
version (Windows)
{
enum confFile = "sc.ini";
enum conf = `[Environment]
DFLAGS="-I%@P%\..\..\..\..\druntime\import" "-I%@P%\..\..\..\..\..\phobos"
LIB="%@P%\..\..\..\..\..\phobos"
[Environment32]
DFLAGS=%DFLAGS% -L/OPT:NOICF
[Environment64]
DFLAGS=%DFLAGS% -L/OPT:NOICF
`;
}
else
{
enum confFile = "dmd.conf";
enum conf = `[Environment32]
DFLAGS=-I%@P%/../../../../druntime/import -I%@P%/../../../../../phobos -L-L%@P%/../../../../../phobos/generated/{OS}/{BUILD}/32{exportDynamic} -fPIC
[Environment64]
DFLAGS=-I%@P%/../../../../druntime/import -I%@P%/../../../../../phobos -L-L%@P%/../../../../../phobos/generated/{OS}/{BUILD}/64{exportDynamic} -fPIC
`;
}
builder
.name("dmdconf")
.target(env["G"].buildPath(confFile))
.msg("(TX) DMD_CONF")
.commandFunction(() {
const expConf = conf
.replace("{exportDynamic}", exportDynamic)
.replace("{BUILD}", env["BUILD"])
.replace("{OS}", env["OS"]);
writeText(rule.target, expConf);
});
});
/// Returns: the rule that builds the common object file
alias common = makeRuleWithArgs!((MethodInitializer!BuildRule builder, BuildRule rule,
string suffix, string[] extraFlags) => builder
.name("common")
.target(env["G"].buildPath("common" ~ suffix).objName)
.sources(sources.common)
.msg("(DC) COMMON" ~ suffix)
.command([
env["HOST_DMD_RUN"],
"-c",
"-of" ~ rule.target,
]
.chain(
flags["DFLAGS"], extraFlags,
// source files need to have relative paths in order for the code coverage
// .lst files to be named properly for CodeCov to find them
rule.sources.map!(e => e.relativePath(compilerDir))
).array)
);
alias validateCommonBetterC = makeRule!((builder, rule) => builder
.name("common-betterc")
.description("Verify that common is -betterC compatible")
.deps([ common("-betterc", ["-betterC"]) ])
);
/// Returns: the rule that builds the backend object file
alias backend = makeRuleWithArgs!((MethodInitializer!BuildRule builder, BuildRule rule,
string suffix, string[] extraFlags) => builder
.name("backend")
.target(env["G"].buildPath("backend" ~ suffix).objName)
.sources(sources.backend)
.deps([
common(suffix, extraFlags)
])
.msg("(DC) BACKEND" ~ suffix)
.command([
env["HOST_DMD_RUN"],
"-c",
"-of" ~ rule.target,
]
.chain(
flags["DFLAGS"], extraFlags,
// source files need to have relative paths in order for the code coverage
// .lst files to be named properly for CodeCov to find them
rule.sources.map!(e => e.relativePath(compilerDir))
).array)
);
/// Returns: the rules that generate required string files: VERSION and SYSCONFDIR.imp
alias versionFile = makeRule!((builder, rule) {
alias contents = memoize!(() {
if (dmdRepo.buildPath(".git").exists)
{
bool validVersionNumber(string version_)
{
// ensure tag has initial 'v'
if (!version_.length || !version_[0] == 'v')
return false;
size_t i = 1;
// validate full major version number
for (; i < version_.length; i++)
{
if ('0' <= version_[i] && version_[i] <= '9')
continue;
else if (version_[i] == '.')
break;
return false;
}
// ensure tag has point
if (i >= version_.length || version_[i++] != '.')
return false;
// only validate first digit of minor version number
if ('0' > version_[i] || version_[i] > '9')
return false;
return true;
}
auto gitResult = tryRun([env["GIT"], "describe", "--dirty"]);
if (gitResult.status == 0 && validVersionNumber(gitResult.output))
return gitResult.output.strip;
}
// version fallback
return dmdRepo.buildPath("VERSION").readText;
});
builder
.target(env["G"].buildPath("VERSION"))
.condition(() => !rule.target.exists || rule.target.readText != contents)
.msg("(TX) VERSION")
.commandFunction(() => writeText(rule.target, contents));
});
alias sysconfDirFile = makeRule!((builder, rule) => builder
.target(env["G"].buildPath("SYSCONFDIR.imp"))
.condition(() => !rule.target.exists || rule.target.readText != env["SYSCONFDIR"])
.msg("(TX) SYSCONFDIR")
.commandFunction(() => writeText(rule.target, env["SYSCONFDIR"]))
);
/// BuildRule to create a directory if it doesn't exist.
alias directoryRule = makeRuleWithArgs!((MethodInitializer!BuildRule builder, BuildRule rule, string dir) => builder
.target(dir)
.condition(() => !exists(dir))
.msg("mkdirRecurse '%s'".format(dir))
.commandFunction(() => mkdirRecurse(dir))
);
alias dmdSymlink = makeRule!((builder, rule) => builder
.commandFunction((){
import std.process;
version(Windows)
{
}
else
{
spawnProcess(["ln", "-sf", env["DMD_PATH"], "./dmd"]);
}
})
);
/**
BuildRule for the DMD executable.
Params:
extra_flags = Flags to apply to the main build but not the rules
*/
alias dmdExe = makeRuleWithArgs!((MethodInitializer!BuildRule builder, BuildRule rule,
string targetSuffix, string[] extraFlags, string[] depFlags) {
const dmdSources = sources.dmd.all.chain(sources.root).array;
string[] platformArgs;
version (Windows)
platformArgs = ["-L/STACK:16777216"];
auto lexer = lexer(targetSuffix, depFlags);
auto backend = backend(targetSuffix, depFlags);
auto common = common(targetSuffix, depFlags);
builder
// include lexer.o, common.o, and backend.o
.sources(dmdSources.chain(lexer.targets, backend.targets, common.targets).array)
.target(env["DMD_PATH"] ~ targetSuffix)
.msg("(DC) DMD" ~ targetSuffix)
.deps([versionFile, sysconfDirFile, lexer, backend, common])
.command([
env["HOST_DMD_RUN"],
"-of" ~ rule.target,
"-vtls",
"-J" ~ env["RES"],
].chain(extraFlags, platformArgs, flags["DFLAGS"],
// source files need to have relative paths in order for the code coverage
// .lst files to be named properly for CodeCov to find them
rule.sources.map!(e => e.relativePath(compilerDir))
).array);
});
alias dmdDefault = makeRule!((builder, rule) => builder
.name("dmd")
.description("Build dmd")
.deps([dmdExe(null, null, null), dmdConf])
);
struct PGOState
{
//Does the host compiler actually support PGO, if not print a message
static bool checkPGO(string x)
{
switch (env["HOST_DMD_KIND"])
{
case "dmd":
abortBuild(`DMD does not support PGO!`);
break;
case "ldc":
return true;
break;
case "gdc":
abortBuild(`PGO (or AutoFDO) builds are not yet supported for gdc`);
break;
default:
assert(false, "Unknown host compiler kind: " ~ env["HOST_DMD_KIND"]);
}
assert(0);
}
this(string set)
{
hostKind = set;
profDirPath = buildPath(env["G"], "dmd_profdata");
mkdirRecurse(profDirPath);
}
string profDirPath;
string hostKind;
string[] pgoGenerateFlags() const
{
switch(hostKind)
{
case "ldc":
return ["-fprofile-instr-generate=" ~ pgoDataPath ~ "/data.%p.raw"];
default:
return [""];
}
}
string[] pgoUseFlags() const
{
switch(hostKind)
{
case "ldc":
return ["-fprofile-instr-use=" ~ buildPath(pgoDataPath(), "merged.data")];
default:
return [""];
}
}
string pgoDataPath() const
{
return profDirPath;
}
}
// Compiles the test runner
alias testRunner = methodInit!(BuildRule, (rundBuilder, rundRule) => rundBuilder
.msg("(DC) RUN.D")
.sources([ testDir.buildPath( "run.d") ])
.target(env["GENERATED"].buildPath("run".exeName))
.command([ env["HOST_DMD_RUN"], "-of=" ~ rundRule.target, "-i", "-I" ~ testDir] ~ rundRule.sources));
alias dmdPGO = makeRule!((builder, rule) {
const dmdKind = env["HOST_DMD_KIND"];
PGOState pgoState = PGOState(dmdKind);
alias buildInstrumentedDmd = methodInit!(BuildRule, (rundBuilder, rundRule) => rundBuilder
.msg("Built dmd with PGO instrumentation")
.deps([dmdExe(null, pgoState.pgoGenerateFlags(), pgoState.pgoGenerateFlags()), dmdConf]));
alias genDmdData = methodInit!(BuildRule, (rundBuilder, rundRule) => rundBuilder
.msg("Compiling dmd testsuite to generate PGO data")
.sources([ testDir.buildPath( "run.d") ])
.deps([buildInstrumentedDmd, testRunner])
.commandFunction({
// Run dmd test suite to get data
const scope cmd = [ testRunner.targets[0], "compilable", "-j" ~ jobs.to!string ];
log("%-(%s %)", cmd);
if (spawnProcess(cmd, null, Config.init, testDir).wait())
stderr.writeln("dmd tests failed! This will not end the PGO build because some data may have been gathered");
}));
alias genPhobosData = methodInit!(BuildRule, (rundBuilder, rundRule) => rundBuilder
.msg("Compiling phobos testsuite to generate PGO data")
.deps([buildInstrumentedDmd])
.commandFunction({
// Run phobos unittests
//TODO makefiles
//generated/linux/release/64/unittest/test_runner builds the unittests without running them.
const scope cmd = ["make", "-C", "../phobos", "-j" ~ jobs.to!string, "generated/linux/release/64/unittest/test_runner", "DMD_DIR="~compilerDir];
log("%-(%s %)", cmd);
if (spawnProcess(cmd, null, Config.init, compilerDir).wait())
stderr.writeln("Phobos Tests failed! This will not end the PGO build because some data may have been gathered");
}));
alias finalDataMerge = methodInit!(BuildRule, (rundBuilder, rundRule) => rundBuilder
.msg("Merging PGO data")
.deps([genDmdData])
.commandFunction({
// Run dmd test suite to get data
scope cmd = ["ldc-profdata", "merge", "--output=merged.data"];
import std.file : dirEntries;
auto files = dirEntries(pgoState.pgoDataPath, "*.raw", SpanMode.shallow).map!(f => f.name);
// Use a separate file to work around the windows command limit
version (Windows)
{{
const listFile = buildPath(env["G"], "pgo_file_list.txt");
File list = File(listFile, "w");
foreach (file; files)
list.writeln(file);
cmd ~= [ "--input-files=" ~ listFile ];
}}
else
cmd = chain(cmd, files).array;
log("%-(%s %)", cmd);
if (spawnProcess(cmd, null, Config.init, pgoState.pgoDataPath).wait())
abortBuild("Merge failed");
files.each!(f => remove(f));
}));
builder
.name("dmd-pgo")
.description("Build dmd with PGO data collected from the dmd and phobos testsuites")
.msg("Build with collected PGO data")
.condition(() => PGOState.checkPGO(dmdKind))
.deps([finalDataMerge])
.commandFunction({
const extraFlags = pgoState.pgoUseFlags ~ "-wi";
const scope cmd = [thisExePath, "HOST_DMD="~env["HOST_DMD_RUN"],
"ENABLE_RELEASE=1", "ENABLE_LTO=1", "DFLAGS="~extraFlags.join(" "),
"--force", "-j"~jobs.to!string];
log("%-(%s %)", cmd);
if (spawnProcess(cmd, null, Config.init).wait())
abortBuild("PGO Compilation failed");
});
}
);
/// Run's the test suite (unittests & `run.d`)
alias runTests = makeRule!((testBuilder, testRule)
{
// Reference header assumes Linux64
auto headerCheck = env["OS"] == "linux" && env["MODEL"] == "64"
? [ runCxxHeadersTest ] : null;
testBuilder
.name("test")
.description("Run the test suite using test/run.d")
.msg("(RUN) TEST")
.deps([dmdDefault, runDmdUnittest, testRunner] ~ headerCheck)
.commandFunction({
// Use spawnProcess to avoid output redirection for `command`s
const scope cmd = [ testRunner.targets[0], "-j" ~ jobs.to!string ];
log("%-(%s %)", cmd);
if (spawnProcess(cmd, null, Config.init, testDir).wait())
abortBuild("Tests failed!");
});
});
/// BuildRule to run the DMD unittest executable.
alias runDmdUnittest = makeRule!((builder, rule) {
auto dmdUnittestExe = dmdExe("-unittest", ["-version=NoMain", "-unittest", env["HOST_DMD_KIND"] == "gdc" ? "-fmain" : "-main"], ["-unittest"]);
builder
.name("unittest")
.description("Run the dmd unittests")
.msg("(RUN) DMD-UNITTEST")
.deps([dmdUnittestExe])
.command(dmdUnittestExe.targets);
});
/**
BuildRule to run the DMD frontend header generation
For debugging, use `./build.d cxx-headers DFLAGS="-debug=Debug_DtoH"` (clean before)
*/
alias buildFrontendHeaders = makeRule!((builder, rule) {
const dmdSources = sources.dmd.frontend ~ sources.root ~ sources.common ~ sources.lexer;
const dmdExeFile = dmdDefault.deps[0].target;
builder
.name("cxx-headers")
.description("Build the C++ frontend headers ")
.msg("(DMD) CXX-HEADERS")
.deps([dmdDefault])
.target(env["G"].buildPath("frontend.h"))
.command([dmdExeFile] ~
flags["DFLAGS"]
.filter!(f => startsWith(f, "-debug=", "-version=", "-I", "-J")).array ~
["-J" ~ env["RES"], "-c", "-o-", "-HCf="~rule.target,
// Enforce the expected target architecture
"-m64", "-os=linux",
] ~ dmdSources ~
// Set druntime up to be imported explicitly,
// so that druntime doesn't have to be built to run the updating of c++ headers.
["-I../druntime/src"]);
});
alias runCxxHeadersTest = makeRule!((builder, rule) {
builder
.name("cxx-headers-test")
.description("Check that the C++ interface matches `src/dmd/frontend.h`")
.msg("(TEST) CXX-HEADERS")
.deps([buildFrontendHeaders])
.commandFunction(() {
const cxxHeaderGeneratedPath = buildFrontendHeaders.target;
const cxxHeaderReferencePath = env["D"].buildPath("frontend.h");
log("Comparing referenceHeader(%s) <-> generatedHeader(%s)",
cxxHeaderReferencePath, cxxHeaderGeneratedPath);
auto generatedHeader = cxxHeaderGeneratedPath.readText;
auto referenceHeader = cxxHeaderReferencePath.readText;
// Ignore carriage return to unify the expected newlines
version (Windows)
{
generatedHeader = generatedHeader.replace("\r\n", "\n"); // \r added by OutBuffer
referenceHeader = referenceHeader.replace("\r\n", "\n"); // \r added by Git's if autocrlf is enabled
}
if (generatedHeader != referenceHeader) {
if (env.getNumberedBool("AUTO_UPDATE"))
{
generatedHeader.toFile(cxxHeaderReferencePath);
writeln("NOTICE: Reference header file (" ~ cxxHeaderReferencePath ~
") has been auto-updated.");
}
else
{
import core.runtime : Runtime;
string message = "ERROR: Newly generated header file (" ~ cxxHeaderGeneratedPath ~
") doesn't match with the reference header file (" ~
cxxHeaderReferencePath ~ ")\n";
auto diff = tryRun(["git", "diff", "--no-index", cxxHeaderReferencePath, cxxHeaderGeneratedPath], runDir).output;
diff ~= "\n===============
The file `src/dmd/frontend.h` seems to be out of sync. This is likely because
changes were made which affect the C++ interface used by GDC and LDC.
Make sure that those changes have been properly reflected in the relevant header
files (e.g. `src/dmd/scope.h` for changes in `src/dmd/dscope.d`).
To update `frontend.h` and fix this error, run the following command:
`" ~ Runtime.args[0] ~ " cxx-headers-test AUTO_UPDATE=1`
Note that the generated code need not be valid, as the header generator
(`src/dmd/dtoh.d`) is still under development.
To read more about `frontend.h` and its usage, see src/README.md#cxx-headers-test
";
abortBuild(message, diff);
}
}
});
});
/// Runs the C++ unittest executable
alias runCxxUnittest = makeRule!((runCxxBuilder, runCxxRule) {
/// Compiles the C++ frontend test files
alias cxxFrontend = methodInit!(BuildRule, (frontendBuilder, frontendRule) => frontendBuilder
.name("cxx-frontend")
.description("Build the C++ frontend")
.msg("(CXX) CXX-FRONTEND")
.sources(srcDir.buildPath("tests", "cxxfrontend.cc") ~ .sources.frontendHeaders ~ .sources.commonHeaders ~ .sources.rootHeaders /* Andrei ~ .sources.dmd.driver ~ .sources.dmd.frontend ~ .sources.root*/)
.target(env["G"].buildPath("cxxfrontend").objName)
// No explicit if since CXX_KIND will always be either g++ or clang++
.command([ env["CXX"], "-xc++", "-std=c++11",
"-c", frontendRule.sources[0], "-o" ~ frontendRule.target, "-I" ~ env["D"] ] ~ flags["CXXFLAGS"])
);
alias cxxUnittestExe = methodInit!(BuildRule, (exeBuilder, exeRule) => exeBuilder
.name("cxx-unittest")
.description("Build the C++ unittests")
.msg("(DC) CXX-UNITTEST")
.deps([lexer(null, null), cxxFrontend])
.sources(sources.dmd.driver ~ sources.dmd.frontend ~ sources.root ~ sources.common ~ env["D"].buildPath("cxxfrontend.d"))
.target(env["G"].buildPath("cxx-unittest").exeName)
.command([ env["HOST_DMD_RUN"], "-of=" ~ exeRule.target, "-vtls", "-J" ~ env["RES"],
"-L-lstdc++", "-version=NoMain", "-version=NoBackend"
].chain(
flags["DFLAGS"], exeRule.sources, exeRule.deps.map!(d => d.target)
).array)
);
runCxxBuilder
.name("cxx-unittest")
.description("Run the C++ unittests")
.msg("(RUN) CXX-UNITTEST");
version (Windows) runCxxBuilder
.commandFunction({ abortBuild("Running the C++ unittests is not supported on Windows yet"); });
else runCxxBuilder
.deps([cxxUnittestExe])
.command([cxxUnittestExe.target]);
});
/// BuildRule that removes all generated files
alias clean = makeRule!((builder, rule) => builder
.name("clean")
.description("Remove the generated directory")
.msg("(RM) " ~ env["G"])
.commandFunction(delegate() {
if (env["G"].exists)
env["G"].rmdirRecurse;
})
);
alias toolsRepo = makeRule!((builder, rule) => builder
.target(env["TOOLS_DIR"])
.msg("(GIT) DLANG/TOOLS")
.condition(() => !exists(rule.target))
.commandFunction(delegate() {
auto toolsDir = env["TOOLS_DIR"];
version(Win32)
// Win32-git seems to confuse C:\... as a relative path
toolsDir = toolsDir.relativePath(compilerDir);
run([env["GIT"], "clone", "--depth=1", env["GIT_HOME"] ~ "/tools", toolsDir]);
})
);
alias checkwhitespace = makeRule!((builder, rule) => builder
.name("checkwhitespace")
.description("Check for trailing whitespace and tabs")
.msg("(RUN) checkwhitespace")
.deps([toolsRepo])
.sources(allRepoSources)
.commandFunction(delegate() {
const cmdPrefix = [env["HOST_DMD_RUN"], "-run", env["TOOLS_DIR"].buildPath("checkwhitespace.d")];
auto chunkLength = allRepoSources.length;
version (Win32)
chunkLength = 80; // avoid command-line limit on win32
foreach (nextSources; taskPool.parallel(allRepoSources.chunks(chunkLength), 1))
{
const nextCommand = cmdPrefix ~ nextSources;
run(nextCommand);
}
})
);
alias style = makeRule!((builder, rule)
{
const dscannerDir = env["GENERATED"].buildPath("dscanner");
alias dscannerRepo = methodInit!(BuildRule, (repoBuilder, repoRule) => repoBuilder
.msg("(GIT) DScanner")
.target(dscannerDir)
.condition(() => !exists(dscannerDir))
.command([
// FIXME: Omitted --shallow-submodules because it requires a more recent
// git version which is not available on buildkite
env["GIT"], "clone", "--depth=1", "--recurse-submodules",
"--branch=v0.14.0",
"https://github.com/dlang-community/D-Scanner", dscannerDir
])
);
alias dscanner = methodInit!(BuildRule, (dscannerBuilder, dscannerRule) {
dscannerBuilder
.name("dscanner")
.description("Build custom DScanner")
.deps([dscannerRepo]);
version (Windows) dscannerBuilder
.msg("(CMD) DScanner")
.target(dscannerDir.buildPath("bin", "dscanner".exeName))
.commandFunction(()
{
// The build script expects to be run inside dscannerDir
run([dscannerDir.buildPath("build.bat")], dscannerDir);
});
else dscannerBuilder
.msg("(MAKE) DScanner")
.target(dscannerDir.buildPath("dsc".exeName))
.command([
// debug build is faster but disable trace output
env["MAKE"], "-C", dscannerDir, "debug",
"DEBUG_VERSIONS=-version=StdLoggerDisableWarning"
]);
});
builder
.name("style")
.description("Check for style errors using D-Scanner")
.msg("(DSCANNER) dmd")
.deps([dscanner])
// Disabled because we need to build a patched dscanner version
// .command([
// "dub", "-q", "run", "-y", "dscanner", "--", "--styleCheck", "--config",
// srcDir.buildPath(".dscanner.ini"), srcDir.buildPath("dmd"), "-I" ~ srcDir
// ])
.command([
dscanner.target, "--styleCheck", "--config", srcDir.buildPath(".dscanner.ini"),
srcDir.buildPath("dmd"), "-I" ~ srcDir
]);
});
/// BuildRule to generate man pages
alias man = makeRule!((builder, rule) {
alias genMan = methodInit!(BuildRule, (genManBuilder, genManRule) => genManBuilder
.target(env["G"].buildPath("gen_man"))
.sources([
compilerDir.buildPath("docs", "gen_man.d"),
env["D"].buildPath("cli.d")])
.command([
env["HOST_DMD_RUN"],
"-I" ~ srcDir,
"-of" ~ genManRule.target]
~ flags["DFLAGS"]
~ genManRule.sources)
.msg(genManRule.command.join(" "))
);
const genManDir = env["GENERATED"].buildPath("docs", "man");
alias dmdMan = methodInit!(BuildRule, (dmdManBuilder, dmdManRule) => dmdManBuilder
.target(genManDir.buildPath("man1", "dmd.1"))
.deps([genMan, directoryRule(dmdManRule.target.dirName)])
.msg("(GEN_MAN) " ~ dmdManRule.target)
.commandFunction(() {
writeText(dmdManRule.target, genMan.target.execute.output);
})
);
builder
.name("man")
.description("Generate and prepare man files")
.deps([dmdMan].chain(
"man1/dumpobj.1 man1/obj2asm.1 man5/dmd.conf.5".split
.map!(e => methodInit!(BuildRule, (manFileBuilder, manFileRule) => manFileBuilder
.target(genManDir.buildPath(e))
.sources([compilerDir.buildPath("docs", "man", e)])
.deps([directoryRule(manFileRule.target.dirName)])
.commandFunction(() => copyAndTouch(manFileRule.sources[0], manFileRule.target))
.msg("copy '%s' to '%s'".format(manFileRule.sources[0], manFileRule.target))
))
).array);
});
alias detab = makeRule!((builder, rule) => builder
.name("detab")
.description("Replace hard tabs with spaces")
.command([env["DETAB"]] ~ allRepoSources)
.msg("(DETAB) DMD")
);
alias tolf = makeRule!((builder, rule) => builder
.name("tolf")
.description("Convert to Unix line endings")
.command([env["TOLF"]] ~ allRepoSources)
.msg("(TOLF) DMD")
);
alias zip = makeRule!((builder, rule) => builder
.name("zip")
.target(srcDir.buildPath("dmdsrc.zip"))
.description("Archive all source files")
.sources(allBuildSources)
.msg("ZIP " ~ rule.target)
.commandFunction(() {
if (exists(rule.target))
remove(rule.target);
run([env["ZIP"], rule.target, thisBuildScript] ~ rule.sources);
})
);
alias html = makeRule!((htmlBuilder, htmlRule) {
htmlBuilder
.name("html")
.description("Generate html docs, requires DMD and STDDOC to be set");
static string d2html(string sourceFile)
{
const ext = sourceFile.extension();
assert(ext == ".d" || ext == ".di", sourceFile);
const htmlFilePrefix = (sourceFile.baseName == "package.d") ?
sourceFile[0 .. $ - "package.d".length - 1] :
sourceFile[0 .. $ - ext.length];
return htmlFilePrefix ~ ".html";
}
const stddocs = env.get("STDDOC", "").split();
auto docSources = .sources.common ~ .sources.root ~ .sources.lexer ~ .sources.dmd.all ~ env["D"].buildPath("frontend.d");
htmlBuilder.deps(docSources.chunks(1).map!(sourceArray =>
methodInit!(BuildRule, (docBuilder, docRule) {
const source = sourceArray[0];
docBuilder
.sources(sourceArray)
.target(env["DOC_OUTPUT_DIR"].buildPath(d2html(source)[srcDir.length + 1..$]
.replace(dirSeparator, "_")))
.deps([dmdDefault, versionFile, sysconfDirFile])
.command([
dmdDefault.deps[0].target,
"-o-",
"-c",
"-Dd" ~ env["DOCSRC"],
"-J" ~ env["RES"],
"-I" ~ env["D"],
srcDir.buildPath("project.ddoc")
] ~ stddocs ~ [
"-Df" ~ docRule.target,
// Need to use a short relative path to make sure ddoc links are correct
source.relativePath(runDir)
] ~ flags["DFLAGS"])
.msg("(DDOC) " ~ source);
})
).array);
});
alias toolchainInfo = makeRule!((builder, rule) => builder
.name("toolchain-info")
.description("Show informations about used tools")
.commandFunction(() {
scope Appender!(char[]) app;
void show(string what, string[] cmd)
{
const res = tryRun(cmd);
const output = res.status != -1
? res.output
: "<Not available>";