-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbob.d
More file actions
2768 lines (2389 loc) · 94.5 KB
/
bob.d
File metadata and controls
2768 lines (2389 loc) · 94.5 KB
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
/**
* Copyright 2012, Graham St Jack.
*
* This file is part of bob, a software build tool.
*
* Bob is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Bob is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
import std.stdio;
import std.ascii;
import std.string;
import std.format;
import std.algorithm;
import std.range;
import std.file;
import std.path;
import std.conv;
import std.datetime;
import std.getopt;
import std.concurrency;
import std.functional;
import std.exception;
import std.process;
import core.sys.posix.signal;
import core.sys.posix.sys.wait;
import core.stdc.errno;
import core.sys.posix.unistd;
import core.sys.posix.stdlib;
import core.sys.posix.fcntl;
// TODO:
// * Fix problem re spwned processes getting stuck in sleeping state.
// * Conditional Bobfile statements.
// * Add a mechanism to scrape the names of additional output filenames from
// a source file using (say) a regex.
// * Generation of documentation from the code.
// * public-lib rule that auto-copies public headers. A dynamic lib incorporating
// a public static lib has to only contain public static libs. A public-lib
// that is not incorporated into a dynamic lib is also copied into dist/lib.
// * Improve correctness of scanning for imports and includes.
// * Support code coverage analysis for test-exe.
/*
A build tool suitable for C/C++ and D code, written in D.
Objectives of this build tool are:
* Easy to write and maintain build scripts (Bobfiles):
- Simple syntax.
- Automatic determination of which in-project libraries to link.
* Auto execution and evaluation of unit tests.
* Enforcement of dependency rules.
* Support for building source code from multiple repositories.
* Support for C/C++ and D.
* Support for code generation:
- A source file isn't scanned for imports/includes until after it is up to date.
- Dependencies inferred from these imports are automatically applied.
Refer to README and INSTRUCTIONS and examples for details on how to use bob.
Dependency rules
----------------
Files and their owning packages are arranged in a tree with cross-linking
dependencies. Each node in the tree can be public or protected. The root of the
tree contains its children publicly.
The dependency rules are:
* A protected node can only be referred to by sibling nodes or nodes contained
by those siblings.
* A node can only refer to another node if its parent transitively refers to or
transitively contains that other node.
* Circular dependencies are not allowed.
An object file can only be used once - either in a library or an executable.
Dynamic libraries don't count as a use - they are just a repackaging.
A dynamic library cannot contain the same static library as another dynamic library.
Search paths
------------
Compilers are told to look in 'src' and 'obj' directories for input files.
The src directory contains links to each top-level package in all the
repositories that comprise the project.
Therefore, include directives have to include the path starting from
the top-level package names, which must be unique.
This namespacing avoids problems of duplicate filenames
at the cost of the compiler being able to find everything, even files
that should not be accessible. Bob therefore enforces all visibility
rules before invoking the compiler.
The build process
-----------------
Bob reads the project Bobfile, transiting into
other-package Bobfiles as packages are mentioned.
Bob assumes that new packages, libraries, etc
are mentioned in dependency order. That is, when each thing is
mentioned, everything it depends on, including dependencies inferred by
include/import statements in source code, has already been mentioned.
Exception: a Bobfile can refer to previously-unknown top-level packages.
The planner scans the Bobfiles, binding files to specific
locations in the filesystem as it goes, and builds the dependency graph.
The file state sequence is:
initial
dependencies_clean skipped if no dependencies
building skipped if no build action
up-to-date
scanning_for_includes
includes_known
clean
As files become buildable, actions are passed to workers.
Results cause the dependency graph to be updated, allowing more actions to
be issued. Specifically, generated source files are scanned for import/include
after they are up to date, and the dependency graph and action commands are
adjusted accordingly.
*/
//-----------------------------------------------------------------------------------------
// PriorityQueue - insert items in any order, and remove largest-first
// (or smallest-first if "a > b" is passed for less).
//
// It is a simple input range (empty(), front() and popFront()).
//
// Notes from Wikipedia article on Binary Heap:
// * Tree is concocted using index arithetic on underlying array, as follows:
// First layer is 0. Second is 1,2. Third is 3,4,5,6, etc.
// Therefore parent of index i is (i-1)/2 and children of index i are 2*i+1 and 2*i+2
// * Tree is balanced, with incomplete population to right of bottom layer.
// * A parent is !less all its children.
// * Insert:
// - Append to array.
// - Swap new element with parent until parent !less child.
// * Remove:
// - Replace root with the last element and reduce the length of the array.
// - If moved element is less than a child, swap with largest child.
//-----------------------------------------------------------------------------------------
struct PriorityQueue(T, alias less = "a < b") {
private:
T[] _store; // underlying store, whose length is the queue's capacity
size_t _used; // the used length of _store
alias binaryFun!(less) comp;
public:
@property size_t length() const nothrow { return _used; }
@property size_t capacity() const nothrow { return _store.length; }
@property bool empty() const nothrow { return !length; }
@property const(T) front() const { enforce(!empty); return _store[0]; }
// Insert a value into the queue
size_t insert(T value)
{
// put the new element at the back of the store
if ( length == capacity) {
_store.length = (capacity + 1) * 2;
}
_store[_used] = value;
// percolate-up the new element
for (size_t n = _used; n; )
{
auto parent = (n - 1) / 2;
if (!comp(_store[parent], _store[n])) break;
swap(_store[parent], _store[n]);
n = parent;
}
++_used;
return 1;
}
void popFront()
{
enforce(!empty);
// replace the front element with the back one
if (_used > 1) {
_store[0] = _store[_used-1];
}
--_used;
// percolate-down the front element (which used to be at the back)
size_t parent = 0;
for (;;)
{
auto left = parent * 2 + 1, right = left + 1;
if (right > _used) {
// no children - done
break;
}
if (right == _used) {
// no right child - possibly swap parent with left, then done
if (comp(_store[parent], _store[left])) swap(_store[parent], _store[left]);
break;
}
// both left and right children - swap parent with largest of itself and left or right
auto largest = comp(_store[parent], _store[left])
? (comp(_store[left], _store[right]) ? right : left)
: (comp(_store[parent], _store[right]) ? right : parent);
if (largest == parent) break;
swap(_store[parent], _store[largest]);
parent = largest;
}
}
}
//------------------------------------------------------------------------------
// Synchronized object that launches external processes in the background
// and keeps track of their PIDs. A one-shot bail() method kills all those
// launched processes and prevents any more from being launched.
//
// bail() is called by the error() functions, which then throw an exception.
//
// We also install a signal handler to bail on receipt of various signals.
//------------------------------------------------------------------------------
class BailException : Exception {
this() {
super("Bail");
}
}
class Launcher {
private {
bool bailed;
int[string] children; // by worker name
}
// launch a process if we haven't bailed
int launch(string worker, string command, string resultsPath, string tmpPath) {
synchronized(this) {
if (bailed) {
throw new BailException();
}
}
command = "TMP_PATH=" ~ tmpPath ~ " " ~ command ~ " > " ~ resultsPath ~ " 2>&1";
int child = spawnvp(P_NOWAIT, "/bin/bash", ["bash", "-c", command]);
/+ This code occasionally blocks in the child for reasons unknown.
say("%s forking", worker);
auto child = fork();
if (child == -1) fatal("%s failed to spawn new process: %s", worker, command);
if (child == 0)
{
// Child process
execvp();
// Open resultsPath for use as stdout and stderr and /dev/zero for stdin
auto inFd = core.sys.posix.fcntl.open(toStringz("/dev/zero"), O_RDONLY);
auto outFd = core.sys.posix.fcntl.open(toStringz(resultsPath), O_WRONLY | O_CREAT | O_TRUNC, octal!644);
auto errFd = dup(outFd);
assert(inFd != -1, "Failed to open /dev/zero");
assert(outFd != -1, format("Failed to open %s", resultsPath));
// Redirect streams and close the old file descriptors.
dup2(inFd, STDIN_FILENO); close(inFd);
dup2(outFd, STDOUT_FILENO); close(outFd);
dup2(errFd, STDERR_FILENO); close(errFd);
// Set up nul-terminated arguments array
string[] args = split(command);
auto argz = new const(char)*[](args.length+1);
foreach (i, arg; args) {
argz[i] = toStringz(arg);
}
argz[$-1] = null;
if (tmpPath.length) {
// Add TMP_PATH to environment
setenv(toStringz("TMP_PATH"), toStringz(tmpPath), 1);
}
// Execute program
execvp(argz[0], argz.ptr);
// If we get here, exec has failed.
assert(0, format("%s failed to exec: %s", worker, command));
}
else
{
// Parent process
synchronized(this) {
say("%s spawned child process %s", worker, child);
children[worker] = child;
return child;
}
}
+/
synchronized(this) {
children[worker] = child;
return child;
}
}
// a child has been finished with
void completed(string worker) {
synchronized(this) {
//say("%s child process completed", worker);
children.remove(worker);
}
}
// bail, doing nothing if we had already bailed
bool bail() {
synchronized(this) {
if (!bailed) {
bailed = true;
foreach (worker, child; children) {
say("killing %s child process %s", worker, child);
kill(child, SIGTERM);
}
return false;
}
else {
return true;
}
}
}
}
__gshared Launcher launcher;
__gshared Tid bailerTid;
void doBailer() {
//say("bailer starting");
void bail(int sig) {
say("Got signal %s", sig);
launcher.bail();
}
bool done;
while (!done) {
receive( (int sig) { bail(sig); },
(string dummy) { done = true; }
);
}
//say("bailer terminating");
}
extern (C) void mySignalHandler(int sig) nothrow {
try {
send(bailerTid, sig);
}
catch (Exception ex) { assert(0, format("Unexpected exception: %s", ex)); }
}
shared static this() {
// set up Launcher and signal handling
launcher = new Launcher();
signal(SIGINT, &mySignalHandler);
signal(SIGHUP, &mySignalHandler);
}
//------------------------------------------------------------------------------
// printing utility functions
//------------------------------------------------------------------------------
// where something originated from
struct Origin {
string path;
uint line;
}
private void sayNoNewline(A...)(string fmt, A a) {
auto w = appender!(char[])();
formattedWrite(w, fmt, a);
stderr.write(w.data);
}
void say(A...)(string fmt, A a) {
auto w = appender!(char[])();
formattedWrite(w, fmt, a);
stderr.writeln(w.data);
stderr.flush;
}
void fatal(A...)(string fmt, A a) {
say(fmt, a);
launcher.bail;
throw new BailException();
}
void error(A...)(ref Origin origin, string fmt, A a) {
sayNoNewline("%s|%s| ERROR: ", origin.path, origin.line);
fatal(fmt, a);
}
void errorUnless(A...)(bool condition, Origin origin, lazy string fmt, lazy A a) {
if (!condition) {
error(origin, fmt, a);
}
}
//-------------------------------------------------------------------------
// path/filesystem utility functions
//-------------------------------------------------------------------------
//
// Ensure that the parent dir of path exists
//
void ensureParent(string path) {
static bool[string] doesExist;
string dir = dirName(path);
if (dir !in doesExist) {
if (!exists(dir)) {
ensureParent(dir);
say("%-15s %s", "Mkdir", dir);
mkdir(dir);
}
else if (!isDir(dir)) {
error(Origin(), "%s is not a directory!", dir);
}
doesExist[path] = true;
}
}
//
// return the modification time of the file at path
// Note: A zero-length target file is treated as if it doesn't exist.
//
long modifiedTime(string path, bool isTarget) {
if (!exists(path) || (isTarget && getSize(path) == 0)) {
return 0;
}
SysTime fileAccessTime, fileModificationTime;
getTimes(path, fileAccessTime, fileModificationTime);
return fileModificationTime.stdTime;
}
//
// return the privacy implied by args
//
Privacy privacyOf(ref Origin origin, string[] args) {
if (!args.length ) return Privacy.PUBLIC;
else if (args[0] == "protected") return Privacy.PROTECTED;
else if (args[0] == "semi-protected") return Privacy.SEMI_PROTECTED;
else if (args[0] == "private") return Privacy.PRIVATE;
else if (args[0] == "public") return Privacy.PUBLIC;
else error(origin, "privacy must be one of public, semi-protected, protected or private");
assert(0);
}
//
// Return true if the given suffix implies a scannable file.
//
bool isScannable(string suffix) {
string ext = extension(suffix);
if (ext is null) ext = suffix;
return
ext == ".c" ||
ext == ".h" ||
ext == ".cc" ||
ext == ".cxx" ||
ext == ".cpp" ||
ext == ".hpp" ||
ext == ".hh" ||
ext == ".d";
}
//
// Return true if str starts with any of the given prefixes
//
bool startsWith(string str, string[] prefixes) {
foreach (prefix; prefixes) {
size_t len = prefix.length;
if (str.length >= len && str[0..len] == prefix)
{
return true;
}
}
return false;
}
//------------------------------------------------------------------------
// File parsing
//------------------------------------------------------------------------
//
// Options read from Boboptions file
//
// General variables
string[string] options;
// Commmands to compile a source file into an object file
struct CompileCommand {
string command;
}
CompileCommand[string] compileCommands; // keyed on input extension
// Commands to generate files other than reserved extensions
struct GenerateCommand {
string[] suffixes;
string command;
}
GenerateCommand[string] generateCommands; // keyed on input extension
// Commands that work with object files
struct LinkCommand {
string staticLib;
string dynamicLib;
string executable;
}
LinkCommand[string] linkCommands; // keyed on source extension
bool[string] reservedExts;
static this() {
reservedExts = [".obj":true, ".slib":true, ".dlib":true, ".exe":true];
}
//
// Read an options file, populating option lines
// Format is: key = value
// value can contain '='
//
void readOptions() {
string path = "Boboptions";
Origin origin = Origin(path, 1);
errorUnless(exists(path) && isFile(path), origin, "can't read Boboptions %s", path);
string content = readText(path);
foreach (line; splitLines(content)) {
string[] tokens = split(line, " = ");
if (tokens.length == 2) {
string key = strip(tokens[0]);
string value = strip(tokens[1]);
if (key[0] == '.') {
// A command of some sort
string[] extensions = split(key);
if (extensions.length < 2) {
fatal("Commands require at least two extensions: %s", line);
}
string input = extensions[0];
string[] outputs = extensions[1..$];
errorUnless(input !in reservedExts, origin,
"Cannot use %s as source ext in commands", input);
if (outputs.length == 1 && (outputs[0] == ".slib" ||
outputs[0] == ".dlib" ||
outputs[0] == ".exe")) {
// A link command
if (input !in linkCommands) {
linkCommands[input] = LinkCommand("", "", "");
}
LinkCommand *linkCommand = input in linkCommands;
if (outputs[0] == ".slib") linkCommand.staticLib = value;
if (outputs[0] == ".dlib") linkCommand.dynamicLib = value;
if (outputs[0] == ".exe") linkCommand.executable = value;
}
else if (outputs.length == 1 && outputs[0] == ".obj") {
// A compile command
errorUnless(input !in compileCommands && input !in generateCommands,
origin, "Multiple compile/generate commands using %s", input);
compileCommands[input] = CompileCommand(value);
}
else {
// A generate command
errorUnless(input !in compileCommands && input !in generateCommands,
origin, "Multiple compile/generate commands using %s", input);
foreach (ext; outputs) {
errorUnless(ext !in reservedExts, origin,
"Cannot use %s in a generate command: %s", ext, line);
}
generateCommands[input] = GenerateCommand(outputs, value);
}
}
else if (key.length > 7 && key[0..7] == "syslib ") {
// syslib declaration
SysLib.create(split(key[7..$]), split(value));
}
else {
// A variable
options[key] = value;
}
}
else {
fatal("Invalid Boboptions line: %s", line);
}
}
}
string getOption(string key) {
auto value = key in options;
if (value) {
return *value;
}
else {
return "";
}
}
//
// Scan file for includes, returning an array of included trails
// # include "trail"
//
// All of the files found should have trails relative to "src" (if source)
// or "obj" (if generated). All system includes must use angle-brackets,
// and are not returned from a scan.
//
struct Include {
string trail;
uint line;
bool quoted;
}
Include[] scanForIncludes(string path) {
Include[] result;
Origin origin = Origin(path, 1);
enum Phase { START, HASH, WORD, INCLUDE, QUOTE, ANGLE, NEXT }
if (exists(path) && isFile(path)) {
string content = readText(path);
int anchor = 0;
Phase phase = Phase.START;
foreach (int i, char ch; content) {
if (ch == '\n') {
phase = Phase.START;
++origin.line;
}
else {
switch (phase) {
case Phase.START:
if (ch == '#') {
phase = Phase.HASH;
}
else if (!isWhite(ch)) {
phase = Phase.NEXT;
}
break;
case Phase.HASH:
if (!isWhite(ch)) {
phase = Phase.WORD;
anchor = i;
}
break;
case Phase.WORD:
if (isWhite(ch)) {
if (content[anchor..i] == "include") {
phase = Phase.INCLUDE;
}
else {
phase = Phase.NEXT;
}
}
break;
case Phase.INCLUDE:
if (ch == '"') {
phase = Phase.QUOTE;
anchor = i+1;
}
else if (ch == '<') {
phase = Phase.ANGLE;
anchor = i+1;
}
else if (isWhite(ch)) {
phase = Phase.NEXT;
}
break;
case Phase.QUOTE:
if (ch == '"') {
result ~= Include(content[anchor..i].idup, origin.line, true);
phase = Phase.NEXT;
//say("%s: found quoted include of %s", path, content[anchor..i]);
}
else if (isWhite(ch)) {
phase = Phase.NEXT;
}
break;
case Phase.ANGLE:
if (ch == '>') {
result ~= Include(content[anchor..i].idup, origin.line, false);
phase = Phase.NEXT;
//say("%s: found system include of %s", path, content[anchor..i]);
}
else if (isWhite(ch)) {
phase = Phase.NEXT;
}
break;
case Phase.NEXT:
break;
default:
error(origin, "invalid phase");
}
}
}
}
return result;
}
//
// Scan a D source file for imports.
//
// The parser is simple and fast, but can't deal with version
// statements or mixins. This is ok for now because it only needs
// to work for source we have control over.
//
// The approach is:
// * Scan for a line starting with "static", "public", "private" or ""
// followed by "import".
// * Then look for:
// ':' - module is previous word, and then skip to next ';'.
// ',' - module is previous word.
// ';' - module is previous word.
// The import is terminated by a ';'.
//
Include[] scanForImports(string path) {
Include[] result;
string content = readText(path);
string word;
int anchor, line=1;
bool inWord, inImport, ignoring;
string[] externals = [ "core", "std" ];
foreach (int pos, char ch; content) {
if (ch == '\n') {
line++;
}
if (ignoring) {
if (ch == ';' || ch == '\n') {
// resume looking for imports
ignoring = false;
inWord = false;
inImport = false;
}
else {
// ignore
}
}
else {
// we are not ignoring
if (inWord && (isWhite(ch) || ch == ':' || ch == ',' || ch == ';')) {
inWord = false;
word = content[anchor..pos];
if (!inImport) {
if (isWhite(ch)) {
if (word == "import") {
inImport = true;
}
else if (word != "public" && word != "private" && word != "static") {
ignoring = true;
}
}
else {
ignoring = true;
}
}
}
if (inImport && word && (ch == ':' || ch == ',' || ch == ';')) {
// previous word is a module name
string trail = std.array.replace(word, ".", dirSeparator) ~ ".d";
bool ignored = false;
foreach (external; externals) {
string ignoreStr = external ~ dirSeparator;
if (trail.length >= ignoreStr.length &&
trail[0..ignoreStr.length] == ignoreStr)
{
ignored = true;
break;
}
}
if (!ignored) {
result ~= Include(trail, line, true);
}
word = null;
if (ch == ':') ignoring = true;
else if (ch == ';') inImport = false;
}
if (!inWord && !(isWhite(ch) || ch == ':' || ch == ',' || ch == ';')) {
inWord = true;
anchor = pos;
}
}
}
return result;
}
//
// read a Bobfile, returning all its statements
//
// // a simple statement
// rulename targets... : arg1... : arg2... : arg3...; // can expand Boboptions variable with ${var-name}
//
struct Statement {
Origin origin;
int phase; // 0==>empty, 1==>rule populated, 2==rule,targets populated, etc
string rule;
string[] targets;
string[] arg1;
string[] arg2;
string[] arg3;
string toString() const {
string result;
if (phase >= 1) result ~= rule;
if (phase >= 2) result ~= format(" : %s", targets);
if (phase >= 3) result ~= format(" : %s", arg1);
if (phase >= 4) result ~= format(" : %s", arg2);
if (phase >= 5) result ~= format(" : %s", arg3);
return result;
}
}
Statement[] readBobfile(string path) {
Statement[] statements;
Origin origin = Origin(path, 1);
errorUnless(exists(path) && isFile(path), origin, "can't read Bobfile %s", path);
string content = readText(path);
int anchor;
bool inWord;
bool inComment;
Statement statement;
foreach (int pos, char ch ; content) {
if (ch == '\n') {
++origin.line;
}
if (ch == '#') {
inComment = true;
inWord = false;
}
if (inComment) {
if (ch == '\n') {
inComment = false;
anchor = pos;
}
}
else if ((isWhite(ch) || ch == ':' || ch == ';')) {
if (inWord) {
inWord = false;
string word = content[anchor..pos];
// should be a word in a statement
string[] words = [word];
if (word.length > 3 && word[0..2] == "${" && word[$-1] == '}') {
// macro substitution
words = split(getOption(word[2..$-1]));
}
if (word.length > 0) {
if (statement.phase == 0) {
statement.origin = origin;
statement.rule = words[0];
++statement.phase;
}
else if (statement.phase == 1) {
statement.targets ~= words;
}
else if (statement.phase == 2) {
statement.arg1 ~= words;
}
else if (statement.phase == 3) {
statement.arg2 ~= words;
}
else if (statement.phase == 4) {
statement.arg3 ~= words;
}
else {
error(origin, "Too many arguments in %s", path);
}
}
}
if (ch == ':' || ch == ';') {
++statement.phase;
if (ch == ';') {
if (statement.phase > 1) {
statements ~= statement;
}
statement = statement.init;
}
}
}
else if (!inWord) {
inWord = true;
anchor = pos;
}
}
errorUnless(statement.phase == 0, origin, "%s ends in unterminated statement", path);
return statements;
}
//-------------------------------------------------------------------------
// Planner
//
// Planner reads Bobfiles, understands what they mean, builds
// a tree of packages, etc, understands what it all means, enforces rules,
// binds everything to filenames, discovers modification times, scans for
// includes, and schedules actions for processing by the worker.
//
// Also receives results of successful actions from the Worker,
// does additional scanning for includes, updates modification
// times and schedules more work.
//
// A critical feature is that scans for includes are deferred until
// a file is up-to-date.
//-------------------------------------------------------------------------
// some thread-local "globals" to make things easier
bool g_print_rules;
bool g_print_deps;
bool g_print_details;
//
// Action - specifies how to build some files, and what they depend on
//
final class Action {
static Action[string] byName;
static int nextNumber;
static PriorityQueue!Action queue;
string name; // the name of the action
string command; // the action command-string
int number; // influences build order
File[] inputs; // files the action directly relies on
File[] builds; // files that this action builds
File[] depends; // files that the action's targets depend on
bool finalised; // true if the action command has been finalised
bool issued; // true if the action has been issued to a worker
this(ref Origin origin, Pkg pkg, string name_, string command_, File[] builds_, File[] depends_) {
name = name_;
command = command_;
number = nextNumber++;
inputs = depends_;
builds = builds_;
depends = depends_;
errorUnless(!(name in byName), origin, "Duplicate command name=%s", name);
byName[name] = this;
// All the files built by this action depend on the Bobfile
depends ~= pkg.bobfile;