This repository has been archived by the owner on Feb 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
d_do_test.d
executable file
·2272 lines (1948 loc) · 78.8 KB
/
d_do_test.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
/**
* D testing tool.
*
* This module implements the test runner for all tests except `unit`.
*
* The general procedure is:
*
* 1. Parse the environment variables (`processEnvironment`)
* 2. Extract test parameters from the source file (`gatherTestParameters`)
* [3. Compile non-D sources (` collectExtraSources`)]
* 4. Compile the test file (`tryMain`)
* 5. Verify the compiler output (`compareOutput`)
* [6. Run the generated executable (`tryMain`) ]
* [5. Verify the executable's output (`compareOutput`) ]
* [7. Run post-test steps (`tryMain`) ]
* 8. Remove intermediate files (`tryMain`)
*
* Optional steps are marked with [...]
*/
module d_do_test;
version (LDC) version (CRuntime_Microsoft) version = LDC_MSVC;
import std.algorithm;
import std.array;
import std.conv;
import std.datetime.stopwatch;
import std.datetime.systime;
import std.exception;
import std.file;
import std.format;
import std.meta : AliasSeq;
import std.process;
import std.random;
import std.range : chain;
import std.regex;
import std.path;
import std.stdio;
import std.string;
import core.sys.posix.sys.wait;
/// Absolute path to the test directory
const dmdTestDir = __FILE_FULL_PATH__.dirName.dirName;
version(Win32)
{
extern(C) int putenv(const char*);
}
/// Prints the `--help` information
void usage()
{
write("d_do_test <test_file>\n"
~ "\n"
~ " Note: this program is normally called through the Makefile, it"
~ " is not meant to be called directly by the user.\n"
~ "\n"
~ " example: d_do_test runnable/pi.d\n"
~ "\n"
~ " relevant environment variables:\n"
~ " ARGS: set to execute all combinations of\n"
~ " REQUIRED_ARGS: arguments always passed to the compiler\n"
~ " DMD: compiler to use, ex: ../src/dmd (required)\n"
~ " CC: C++ compiler to use, ex: dmc, g++\n"
~ " OS: windows, linux, freebsd, osx, netbsd, dragonflybsd\n"
~ " RESULTS_DIR: base directory for test results\n"
~ " MODEL: 32 or 64 (required)\n"
~ " AUTO_UPDATE: set to 1 to auto-update mismatching test output\n"
~ " PRINT_RUNTIME: set to 1 to print test runtime\n"
~ "\n"
~ " windows vs non-windows portability env vars:\n"
~ " DSEP: \\\\ or /\n"
~ " SEP: \\ or / (required)\n"
~ " OBJ: .obj or .o (required)\n"
~ " EXE: .exe or <null> (required)\n");
}
/// Type of test to execute (mapped to the subdirectories)
enum TestMode
{
COMPILE, /// compilable
FAIL_COMPILE, /// fail_compilation
RUN, /// runnable, runnable_cxx
DSHELL, /// dshell
}
/// Test parameters specified in the source file
/// (conditionally expanded depending on the environment)
struct TestArgs
{
TestMode mode; /// Test type based on the directory
bool compileSeparately; /// `COMPILE_SEPARATELY`: compile each source file separately
bool link; /// `LINK`: force linking for `fail_compilation` & `compilable` tests
bool clearDflags; /// `DFLAGS`: whether DFLAGS should be cleared before invoking dmd
string executeArgs; /// `EXECUTE_ARGS`: arguments passed to the compiled executable (for `runnable[_cxx]`)
string cxxflags; /// `CXXFLAGS`: arguments passed to $CC when compiling `EXTRA_CPP_SOURCES`
string[] sources; /// `EXTRA_SOURCES`: additional D sources (+ main source file)
string[] compiledImports; /// `COMPILED_IMPORTS`: files compiled alongside the main source
string[] cppSources; /// `EXTRA_CPP_SOURCES`: additional C++ sources
string[] objcSources; /// `EXTRA_OBJC_SOURCES`: additional Objective-C sources
string permuteArgs; /// `PERMUTE_ARGS`: set of dmd arguments to permute for multiple test runs
string[] argSets; /// `ARG_SETS`: selection of dmd arguments to use in different test runs
string compileOutput; /// `TEST_OUTPUT`: expected output of dmd
string compileOutputFile; /// `TEST_OUTPUT_FILE`: file containing the expected `TEST_OUTPUT`
string runOutput; /// `RUN_OUTPUT`: expected output of the compiled executable
string gdbScript; /// `GDB_SCRIPT`: script executed when running the compiled executable in GDB
string gdbMatch; /// `GDB_MATCH`: regex describing the expected output from executing `GDB_SSCRIPT`
string postScript; /// `POSTSCRIPT`: bash script executed after a successful test
string[] outputFiles; /// generated files appended to the compilation output
string transformOutput; /// Transformations for the compiler output
string requiredArgs; /// `REQUIRED_ARGS`: dmd arguments passed when compiling D sources
string requiredArgsForLink; /// `COMPILE_SEPARATELY`: dmd arguments passed when linking separately compiled objects
string disabledReason; /// `DISABLED`: reason to skip this test or empty, if the test is not disabled
/// Returns: whether this disabled due to some reason
bool isDisabled() const { return disabledReason.length != 0; }
}
/// Test parameters specified in the environment (e.g. target model)
/// which are shared between all tests
struct EnvData
{
string all_args; /// `ARGS`: arguments to test in permutations
string dmd; /// `DMD`: compiler under test
string results_dir; /// `RESULTS_DIR`: directory for temporary files
string sep; /// `SEP`: directory separator (`/` or `\`)
string dsep; /// `DSEP`: double directory separator ( `/` or `\\`)
string obj; /// `OBJ`: object file extension (`.o` or `.obj`)
string exe; /// `EXE`: executable file extension (none or `.exe`)
string os; /// `OS`: host operating system (`linux`, `windows`, ...)
string compiler; /// `HOST_DMD`: host D compiler
string ccompiler; /// `CC`: host C++ compiler
string model; /// `MODEL`: target model (`32` or `64`)
string required_args; /// `REQUIRED_ARGS`: flags added to the tests `REQUIRED_ARGS` parameter
string cxxCompatFlags; /// Additional flags passed to $(compiler) when `EXTRA_CPP_SOURCES` is present
string[] picFlag; /// Compiler flag for PIC (if requested from environment)
bool dobjc; /// `D_OBJC`: run Objective-C tests
bool coverage_build; /// `COVERAGE`: coverage build, skip linking & executing to save time
bool autoUpdate; /// `AUTO_UPDATE`: update `(TEST|RUN)_OUTPUT` on missmatch
bool printRuntime; /// `PRINT_RUNTIME`: Print time spent on a single test
bool usingMicrosoftCompiler; /// Using Visual Studio toolchain
bool tryDisabled; /// `TRY_DISABLED`:Silently try disabled tests (ignore failure and report success)
version (LDC) bool noArchVariant;
}
/++
Creates a new EnvData instance based on the current environment.
Other code should not read from the environment.
Returns: an initialized EnvData instance
++/
immutable(EnvData) processEnvironment()
{
static string envGetRequired(in char[] name)
{
if (auto value = environment.get(name))
return value;
writefln("Error: Missing environment variable '%s', was this called through the Makefile?",
name);
throw new SilentQuit();
}
EnvData envData;
envData.all_args = environment.get("ARGS");
envData.results_dir = envGetRequired("RESULTS_DIR");
envData.sep = envGetRequired ("SEP");
envData.dsep = environment.get("DSEP");
envData.obj = envGetRequired ("OBJ");
envData.exe = envGetRequired ("EXE");
envData.os = environment.get("OS");
envData.dmd = replace(envGetRequired("DMD"), "/", envData.sep);
envData.compiler = "dmd"; //should be replaced for other compilers
envData.ccompiler = environment.get("CC");
envData.model = envGetRequired("MODEL");
envData.required_args = environment.get("REQUIRED_ARGS");
envData.dobjc = environment.get("D_OBJC") == "1";
envData.coverage_build = environment.get("DMD_TEST_COVERAGE") == "1";
envData.autoUpdate = environment.get("AUTO_UPDATE", "") == "1";
envData.printRuntime = environment.get("PRINT_RUNTIME", "") == "1";
envData.tryDisabled = environment.get("TRY_DISABLED") == "1";
version (LDC) envData.noArchVariant = environment.get("NO_ARCH_VARIANT") == "1";
enforce(envData.sep.length == 1,
"Path separator must be a single character, not: `"~envData.sep~"`");
if (envData.ccompiler.empty)
{
if (envData.os != "windows")
envData.ccompiler = "c++";
else version (LDC_MSVC)
envData.ccompiler = "cl.exe";
else if (envData.model == "32omf")
envData.ccompiler = "dmc";
else if (envData.model == "64")
envData.ccompiler = `C:\"Program Files (x86)"\"Microsoft Visual Studio 10.0"\VC\bin\amd64\cl.exe`;
else
{
writeln("Unknown $OS$MODEL combination: ", envData.os, envData.model);
throw new SilentQuit();
}
}
envData.usingMicrosoftCompiler = envData.ccompiler.toLower.endsWith("cl.exe");
version (Windows) {} else
{
version(X86_64)
envData.picFlag = ["-fPIC"];
if (environment.get("PIC", null) == "1")
envData.picFlag = ["-fPIC"];
}
switch (envData.compiler)
{
case "dmd":
case "ldc":
version (CppRuntime_Gcc)
envData.cxxCompatFlags = " -L-lstdc++ -L--no-demangle";
else version (CppRuntime_Clang)
envData.cxxCompatFlags = " -L-lc++ -L--no-demangle";
break;
case "gdc":
envData.cxxCompatFlags = "-Xlinker -lstdc++ -Xlinker --no-demangle";
break;
default:
writeln("Unknown compiler: ", envData.compiler);
throw new SilentQuit();
}
return cast(immutable) envData;
}
/**
* Read the single-line test parameter `token` from the source code which
* might be defined multiple times. All definitions found will be joined
* into a single string using `multilineDelimiter` as a separator.
*
* This will skip conditional parameters declared as `<token>(<environment>)`
* if the specified environment doesn't match the passed `envData`, e.g.
*
* ---
* REQURIRED_ARGS(linux): -ignore
* PERMUTE_ARGS(windows64): -ignore
* ---
*
* Params:
* envData = environment data
* file = source code
* token = test parameter
* result = variable to store the parameter
* multilineDelimiter = separator for multiple declarations
*
* Returns: whether the parameter was found in the source code
*/
bool findTestParameter(const ref EnvData envData, string file, string token, ref string result, string multiLineDelimiter = " ")
{
if (!consumeNextToken(file, token, envData))
return false;
auto lineEndR = std.string.indexOf(file, "\r");
auto lineEndN = std.string.indexOf(file, "\n");
auto lineEnd = lineEndR == -1 ?
(lineEndN == -1 ? file.length : lineEndN) :
(lineEndN == -1 ? lineEndR : min(lineEndR, lineEndN));
result = file[0 .. lineEnd];
const commentStart = std.string.indexOf(result, "//");
if (commentStart != -1)
result = result[0 .. commentStart];
result = strip(result);
string result2;
if (findTestParameter(envData, file[lineEnd .. $], token, result2, multiLineDelimiter))
{
if (result2.length > 0)
{
if (result.length == 0)
result = result2;
else
result ~= multiLineDelimiter ~ result2;
}
}
// fix-up separators
result = result.unifyDirSep(envData.sep);
return true;
}
unittest
{
immutable file = `
/*
Here's a link
FOO: a b
FOO: c
*/
void main() {}
// BAR(windows): all_win
// BAR(windows64): 64_win
int i;
/* REQUIRED_ARGS: -O
* PERMUTE_ARGS:
*/
// COMPILE_SEPARATELY:
import foo.bar;
`;
immutable EnvData win32 = {
os: "windows",
model: "32",
};
immutable EnvData win64 = {
os: "windows",
model: "64",
};
immutable EnvData linux = {
os: "linux",
model: "64",
};
string found;
assert(!findTestParameter(linux, file, "OTHER", found));
assert(found is null);
assert(findTestParameter(win64, file, "FOO", found));
assert(found == "a b c");
found = null;
assert(findTestParameter(win64, file, "FOO", found, ";"));
assert(found == "a b;c");
found = null;
assert(findTestParameter(win64, file, "BAR", found));
assert(found == "all_win 64_win");
found = null;
assert(findTestParameter(win32, file, "BAR", found));
assert(found == "all_win");
found = null;
assert(!findTestParameter(linux, file, "BAR", found));
assert(found is null);
assert(findTestParameter(linux, file, "PERMUTE_ARGS", found));
assert(found == "");
found = null;
assert(findTestParameter(linux, file, "REQUIRED_ARGS", found));
assert(found == "-O");
found = null;
assert(findTestParameter(linux, file, "COMPILE_SEPARATELY", found));
assert(found == "");
}
/**
* Read the multi-line test parameter `token` from the source code and joins
* multiple definitions into a single string.
*
* ```
* TEST_OUTPUT:
* ---
* Hello, World!
* ---
* ```
*
* Params:
* file = source code
* token = test parameter
* result = variable to store the parameter
* envData = environment data
*
* Returns: whether the parameter was found in the source code
*/
bool findOutputParameter(string file, string token, out string result, ref const EnvData envData)
{
bool found = false;
while (consumeNextToken(file, token, envData))
{
found = true;
enum embed_sep = "---";
auto n = std.string.indexOf(file, embed_sep);
enforce(n != -1, "invalid "~token~" format");
n += embed_sep.length;
while (file[n] == '-') ++n;
if (file[n] == '\r') ++n;
if (file[n] == '\n') ++n;
file = file[n .. $];
auto iend = std.string.indexOf(file, embed_sep);
enforce(iend != -1, "invalid TEST_OUTPUT format");
result ~= file[0 .. iend];
while (file[iend] == '-') ++iend;
file = file[iend .. $];
}
if (found)
{
result = std.string.strip(result);
result = result.unifyNewLine().unifyDirSep(envData.sep);
result = result ? result : ""; // keep non-null
}
return found;
}
unittest
{
immutable EnvData linux = { os: "linux", model: "64", sep: "/ " };
immutable file = `
/*
Here's a link
TEST_OUTPUT:
---
Hello, World
---
*/
void main() {}
/*
TEST_OUTPUT(linux):
---
Have a nice day
---
*/
/*
TEST_OUTPUT(linux32):
---
Ignored
---
*/
void foo() {}
/*
MISSING:
*/
/*
INCOMPLETE:
---
*/
`;
string found;
assert(!findOutputParameter(file, "UNKNOWN", found, linux));
assert(found is null);
assert(findOutputParameter(file, "TEST_OUTPUT", found, linux));
assert(found == "Hello, World\nHave a nice day");
found = null;
auto ex = collectException(findOutputParameter(file, "MISSING", found, linux));
assert(ex);
assert(ex.msg == "invalid TEST_OUTPUT format");
assert(found is null);
ex = collectException(findOutputParameter(file, "INCOMPLETE", found, linux));
assert(ex);
assert(ex.msg == "invalid TEST_OUTPUT format");
}
/++
+ Reads the file content to find the next parameter specified by `token`.
+ Ignores conditional parameters that don't apply to the current environment.
+
+ Params:
+ file = file content, will be advanced to the first non-whitespace character
+ of the parameter value - if `token` was found
+ token = requested parameter
+ envData = environment data
+
+ Returns: true if `token` was found
+/
private bool consumeNextToken(ref string file, const string token, ref const EnvData envData)
{
import std.ascii : isWhite;
while (true)
{
const istart = std.string.indexOf(file, token);
if (istart == -1)
return false;
// Examine the preceeding character to avoid false matches
const ch = istart ? file[istart - 1] : ' ';
file = file[istart + token.length .. $];
file = file.stripLeft!(ch => ch == ' '); // Don't read line breaks
// Assume that real test token are preceeded by spaces or comment-related tokens
if (!isWhite(ch) && !among(ch, '/', '*', '+'))
{
debug writeln("Ignoring partial match for token: ", token);
continue;
}
// filter by OS specific setting (os1 os2 ...)
if (file.startsWith("("))
{
auto close = std.string.indexOf(file, ")");
if (close >= 0)
{
// Remove the (<oss>) list from the front of `file``
const oss = split(file[1 .. close], " ");
file = file[close + 1 .. $];
file = file.stripLeft!(ch => ch == ' '); // Don't read line breaks
// Check if the current environment matches an entry in oss, which can either
// be an OS (e.g. "linux") or a combination of OS + MODEL (e.g. "windows32").
// The latter is important on windows because m32 might require other
// parameters than m32mscoff/m64.
if (!oss.canFind!(o => o.skipOver(envData.os) && (o.empty || o == envData.model)))
continue; // Parameter was skipped
}
}
// Skip a trailing colon
if (file.skipOver(":"))
{
file = file.stripLeft!(ch => ch == ' '); // Don't read line breaks
return true;
}
writeln("Test directive `", token,"` must be followed by a `:`");
throw new SilentQuit();
}
}
unittest
{
immutable EnvData linux = { os: "linux", model: "64", sep: "/ " };
immutable file = q{
GOOD: foo
WITH_SPACE : bar
/*
BAD
---
---
*/
//BAD foo
//OPTLINK
// $(TINK foo.bar)
IgnoreSTUFF
IgnoreSTUFF: x
STUFF: someVal
*/
void main() {}
};
string found = file;
assert(!consumeNextToken(found, "UNKNOWN", linux));
assert(found is file);
assert(consumeNextToken(found, "GOOD", linux));
assert(found.startsWith("foo"), found);
found = file;
assert(consumeNextToken(found, "WITH_SPACE", linux));
assert(found.startsWith("bar"), found);
found = file;
assertThrown(consumeNextToken(found, "BAD", linux));
found = file;
assert(!consumeNextToken(found, "LINK", linux));
found = file;
assert(!consumeNextToken(found, "TINK", linux));
found = file;
assert(consumeNextToken(found, "STUFF", linux));
assert(found.startsWith("someVal"), found);
}
/// Replaces the placeholer `${RESULTS_DIR}` with the actual path
/// to `test_results` stored in `envData`.
void replaceResultsDir(ref string arguments, const ref EnvData envData)
{
// Bash would expand this automatically on Posix, but we need to manually
// perform the replacement for Windows compatibility.
arguments = replace(arguments, "${RESULTS_DIR}", envData.results_dir);
}
/// Returns: the reason why this test is disabled or null if it isn't skipped.
string getDisabledReason(string[] disabledPlatforms, const ref EnvData envData)
{
if (disabledPlatforms.length == 0)
return null;
const target = ((envData.os == "windows") ? "win" : envData.os) ~ envData.model;
// allow partial matching, e.g. `win` to disable both win32 and win64
const i = disabledPlatforms.countUntil!(p => target.canFind(p));
if (i != -1)
return "on " ~ disabledPlatforms[i];
version (LDC)
{
version (X86) enum isX86 = true;
else version (X86_64) enum isX86 = true;
else enum isX86 = false;
// additionally support `DISABLED: LDC`
if (disabledPlatforms.canFind("LDC"))
return "for LDC";
// additionally support `DISABLED: LDC_not_x86` (e.g., for tests with DMD-style inline asm)
if (!isX86 && disabledPlatforms.canFind("LDC_not_x86"))
return "for LDC_not_x86";
// additionally support `DISABLED: LDC_<OS>[<model>]`
const j = disabledPlatforms.countUntil!(p => p.startsWith("LDC_") && target.canFind(p[4 .. $]));
if (j != -1)
return "on " ~ disabledPlatforms[j];
}
return null;
}
unittest
{
immutable EnvData win32 = { os: "windows", model: "32", };
immutable EnvData win32mscoff = { os: "windows", model: "32mscoff", };
immutable EnvData win64 = { os: "windows", model: "64", };
assert(getDisabledReason(null, win64) is null);
assert(getDisabledReason([ "linux" ], win64) is null);
assert(getDisabledReason([ "linux", "win" ], win64) == "on win");
assert(getDisabledReason([ "linux", "win64" ], win64) == "on win64");
assert(getDisabledReason([ "linux", "win32" ], win64) is null);
assert(getDisabledReason([ "win32mscoff" ], win32mscoff) == "on win32mscoff");
assert(getDisabledReason([ "win32mscoff" ], win32) is null);
assert(getDisabledReason([ "win32" ], win32mscoff) == "on win32");
assert(getDisabledReason([ "win32" ], win32) == "on win32");
}
/**
* Reads the test configuration from the source code (using `findTestParameter` and
* `findOutputParameter`) and initializes `testArgs` accordingly. Also merges
* configurations/additional parameters specified in the environment, e.g.
* `REQUIRED_ARGS`.
*
* Params:
* testArgs = test configuration object
* input_dir = test directory (e.g. `runnable`)
* input_file = path to the source file
* envData = environment configurations
*
* Returns: whether this test should be executed (true) or skipped (false)
* Throws: Exception if the test configuration is invalid
*/
bool gatherTestParameters(ref TestArgs testArgs, string input_dir, string input_file, const ref EnvData envData)
{
string file = cast(string)std.file.read(input_file);
string dflagsStr;
testArgs.clearDflags = findTestParameter(envData, file, "DFLAGS", dflagsStr);
enforce(dflagsStr.empty, "The DFLAGS test argument must be empty: It is '" ~ dflagsStr ~ "'");
findTestParameter(envData, file, "REQUIRED_ARGS", testArgs.requiredArgs);
if (envData.required_args.length)
{
if (testArgs.requiredArgs.length)
testArgs.requiredArgs ~= " " ~ envData.required_args;
else
testArgs.requiredArgs = envData.required_args;
}
replaceResultsDir(testArgs.requiredArgs, envData);
if (! findTestParameter(envData, file, "PERMUTE_ARGS", testArgs.permuteArgs))
{
if (testArgs.mode == TestMode.RUN)
testArgs.permuteArgs = envData.all_args;
}
replaceResultsDir(testArgs.permuteArgs, envData);
// remove permute args enforced as required anyway
if (testArgs.requiredArgs.length && testArgs.permuteArgs.length)
{
version (LDC)
{
/*
* Additionally exclude some permute args which are uninteresting
* for LDC due to the split in
*
* * dmd-testsuite, requiring `-O`, which basically implies `-inline`
* too (except for a here irrelevant header generation detail), and
* * dmd-testsuite-debug, requiring `-g -link-defaultlib-debug`.
*
* In case the original permute args specify both `-O` and `-g`, only
* 2 of 4 combinations will be tested (`-O` and `-g`), excluding the
* rather uninteresting `-O -g` (which would otherwise be tested twice)
* and `` (which is untestable anyway).
* Similarly, a `-inline` alone without `-O` isn't interesting for
* additional test coverage, as it just controls an LLVM optimization
* pass.
* Ditto for `-fPIC`, which is enabled by default for most targets.
*/
static immutable permuteArgsExcludedByLDC = ["-O", "-inline", "-g", "-fPIC"];
const required = split(testArgs.requiredArgs) ~ permuteArgsExcludedByLDC;
}
else
{
const required = split(testArgs.requiredArgs);
}
const newPermuteArgs = split(testArgs.permuteArgs)
.filter!(a => !required.canFind(a))
.join(" ");
testArgs.permuteArgs = newPermuteArgs;
}
// tests can override -verrors by using REQUIRED_ARGS
if (testArgs.mode == TestMode.FAIL_COMPILE)
testArgs.requiredArgs = "-verrors=0 " ~ testArgs.requiredArgs;
version (LDC)
{
// *.c tests: make sure not to pull in ldc_rt.dso.o for BUILD_SHARED_LIBS=ON builds
// (with implicit -link-defaultlib-shared)
if (input_file.extension() == ".c")
{
if (testArgs.requiredArgs.length)
testArgs.requiredArgs ~= " -defaultlib=";
else
testArgs.requiredArgs = "-defaultlib=";
}
}
{
string argSetsStr;
findTestParameter(envData, file, "ARG_SETS", argSetsStr, ";");
foreach(s; split(argSetsStr, ";"))
{
replaceResultsDir(s, envData);
testArgs.argSets ~= s;
}
}
// win(32|64) doesn't support pic
// -target/-os may compile for non-PIC targets, let the test take care of -fPIC
if (envData.os == "windows" || testArgs.requiredArgs.canFind("-target", "-os"))
{
auto index = std.string.indexOf(testArgs.permuteArgs, "-fPIC");
if (index != -1)
testArgs.permuteArgs = testArgs.permuteArgs[0 .. index] ~ testArgs.permuteArgs[index+5 .. $];
// Remove the first -fPIC when added via the REQUIRED_ARGS environment variable
// This allows test to explicitly set `-fPIC` if necessary
if (envData.required_args.canFind("-fPIC"))
testArgs.requiredArgs = testArgs.requiredArgs.replaceFirst("-fPIC", "").strip();
}
// clean up extra spaces
testArgs.permuteArgs = strip(replace(testArgs.permuteArgs, " ", " "));
if (findTestParameter(envData, file, "EXECUTE_ARGS", testArgs.executeArgs))
replaceResultsDir(testArgs.executeArgs, envData);
// Always run main even if compiled with '-unittest' but let
// tests switch to another behaviour if necessary
if (!testArgs.executeArgs.canFind("--DRT-testmode"))
testArgs.executeArgs ~= " --DRT-testmode=run-main";
string extraSourcesStr;
findTestParameter(envData, file, "EXTRA_SOURCES", extraSourcesStr);
testArgs.sources = [input_file];
// prepend input_dir to each extra source file
foreach(s; split(extraSourcesStr))
testArgs.sources ~= input_dir ~ "/" ~ s;
{
string compiledImports;
findTestParameter(envData, file, "COMPILED_IMPORTS", compiledImports);
foreach(s; split(compiledImports))
testArgs.compiledImports ~= input_dir ~ "/" ~ s;
}
findTestParameter(envData, file, "CXXFLAGS", testArgs.cxxflags);
string extraCppSourcesStr;
findTestParameter(envData, file, "EXTRA_CPP_SOURCES", extraCppSourcesStr);
testArgs.cppSources = split(extraCppSourcesStr);
if (testArgs.cppSources.length)
testArgs.requiredArgs ~= envData.cxxCompatFlags;
string extraObjcSourcesStr;
auto objc = findTestParameter(envData, file, "EXTRA_OBJC_SOURCES", extraObjcSourcesStr);
if (objc && !envData.dobjc)
return false;
testArgs.objcSources = split(extraObjcSourcesStr);
// swap / with $SEP
if (envData.sep && envData.sep != "/")
foreach (ref s; testArgs.sources)
s = replace(s, "/", to!string(envData.sep));
//writeln ("sources: ", testArgs.sources);
{
string throwAway;
testArgs.link = findTestParameter(envData, file, "LINK", throwAway);
}
// COMPILE_SEPARATELY can take optional compiler switches when link .o files
testArgs.compileSeparately = findTestParameter(envData, file, "COMPILE_SEPARATELY", testArgs.requiredArgsForLink);
string disabledPlatformsStr;
findTestParameter(envData, file, "DISABLED", disabledPlatformsStr);
version (DragonFlyBSD)
{
// DragonFlyBSD is x86_64 only, instead of adding DISABLED to a lot of tests, just exclude them from running
if (testArgs.requiredArgs.canFind("-m32"))
testArgs.disabledReason = "on DragonFlyBSD (no -m32)";
}
version (ARM) enum supportsM64 = false;
else version (MIPS32) enum supportsM64 = false;
else version (PPC) enum supportsM64 = false;
else enum supportsM64 = true;
static if (!supportsM64)
{
if (testArgs.requiredArgs.canFind("-m64"))
testArgs.disabledReason = "because target doesn't support -m64";
}
if (!testArgs.isDisabled)
testArgs.disabledReason = getDisabledReason(split(disabledPlatformsStr), envData);
findTestParameter(envData, file, "TEST_OUTPUT_FILE", testArgs.compileOutputFile);
// Only check for TEST_OUTPUT is no file was given because it would
// partially match TEST_OUTPUT_FILE
if (testArgs.compileOutputFile)
{
// Don't require tests to specify the test directory
testArgs.compileOutputFile = input_dir.buildPath(testArgs.compileOutputFile);
testArgs.compileOutput = readText(testArgs.compileOutputFile)
.unifyNewLine() // Avoid CRLF issues
.strip();
// Only sanitize directory separators from file types that support standalone \
if (!testArgs.compileOutputFile.endsWith(".json"))
testArgs.compileOutput = testArgs.compileOutput.unifyDirSep(envData.sep);
}
else
findOutputParameter(file, "TEST_OUTPUT", testArgs.compileOutput, envData);
string outFilesStr;
findTestParameter(envData, file, "OUTPUT_FILES", outFilesStr);
testArgs.outputFiles = outFilesStr.split(';');
findTestParameter(envData, file, "TRANSFORM_OUTPUT", testArgs.transformOutput);
findOutputParameter(file, "RUN_OUTPUT", testArgs.runOutput, envData);
findOutputParameter(file, "GDB_SCRIPT", testArgs.gdbScript, envData);
findTestParameter(envData, file, "GDB_MATCH", testArgs.gdbMatch);
findTestParameter(envData, file, "POST_SCRIPT", testArgs.postScript);
return true;
}
unittest
{
immutable EnvData linux32 = { os: "linux", model: "32", required_args: "-fPIC" };
immutable EnvData linux64 = { os: "linux", model: "64", required_args: "-fPIC" };
immutable EnvData win64 = { os: "windows", model: "64", };
immutable dir = "runnable";
immutable file = ".d_do_test_unittest_target_example.d";
immutable content = q{
/+
https://foo.bar.
REQUIRED_ARGS: -target=x86-unknown-windows-msvc
REQUIRED_ARGS(linux32): -fPIC
+/
};
std.file.write(file, content);
scope (exit) std.file.remove(file);
TestArgs args;
assert(gatherTestParameters(args, dir, file, win64));
assert(args.requiredArgs == "-target=x86-unknown-windows-msvc", args.requiredArgs);
args = TestArgs.init;
assert(gatherTestParameters(args, dir, file, linux64));
assert(args.requiredArgs == "-target=x86-unknown-windows-msvc", args.requiredArgs);
args = TestArgs.init;
assert(gatherTestParameters(args, dir, file, linux32));
assert(args.requiredArgs == "-target=x86-unknown-windows-msvc -fPIC", args.requiredArgs);
std.file.write(file, "REQUIRED_ARGS: -os=windows");
args = TestArgs.init;
assert(gatherTestParameters(args, dir, file, linux64));
assert(args.requiredArgs == "-os=windows", args.requiredArgs);
}
/// Generates all permutations of the space-separated word contained in `argstr`
string[] combinations(string argstr)
{
string[] results;
string[] args = split(argstr);
long combinations = 1 << args.length;
for (size_t i = 0; i < combinations; i++)
{
string r;
bool printed = false;
for (size_t j = 0; j < args.length; j++)
{
if (i & 1 << j)
{
if (printed)
r ~= " ";
r ~= args[j];
printed = true;
}
}
results ~= r;
}
return results;
}
/// Tries to remove the file identified by `filename` and prints warning on failure
void tryRemove(in char[] filename)
{
if (auto ex = std.file.remove(filename).collectException())
debug writeln("WARNING: Failed to remove ", filename);
}
/**
* Executes `command` while logging the invocation and any output produced into f.
*
* Params:
* f = the logfile
* command = the command to execute
* expectPass = whether the command should succeed
*
* Returns: the output produced by `command`
* Throws:
* Exception if `command` returns another exit code than 0/1 (depending on expectPass)
*/
string execute(ref File f, string command, bool expectpass)
{
f.writeln(command);
const result = std.process.executeShell(command);
f.write(result.output);
if (result.status < 0)
{
enforce(false, "caught signal: " ~ to!string(result.status));
}
else
{
const exp = expectpass ? 0 : 1;
enforce(result.status == exp, format("Expected rc == %d, but exited with rc == %d", exp, result.status));
}
return result.output;
}
/// add quotes around the whole string if it contains spaces that are not in quotes
string quoteSpaces(string str)
{