-
Notifications
You must be signed in to change notification settings - Fork 16
/
splitter.d
1865 lines (1660 loc) · 42.3 KB
/
splitter.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
/// Simple source code splitter
/// Written by Vladimir Panteleev <[email protected]>
/// License: Boost Software License, Version 1.0
module splitter;
import std.ascii;
import std.algorithm;
import std.array;
import std.conv;
import std.datetime.systime;
import std.exception;
import std.file;
import std.functional;
import std.path;
import std.range;
import std.stdio : File, stdin;
import std.string;
import std.traits;
import std.stdio : stderr;
import std.typecons;
import std.utf : byChar;
import polyhash;
/// Represents an Entity's position within a program tree.
struct Address
{
Address* parent; /// Upper node's Address. If null, then this is the root node (and index should be 0).
size_t index; /// Index within the parent's children array
size_t depth; /// Distance from the root address
Address*[] children; /// Used to keep a global cached tree of addresses.
ref Address* child(size_t index) const
{
auto mutableThis = cast(Address*)&this; // Break const for caching
if (mutableThis.children.length < index + 1)
mutableThis.children.length = index + 1;
if (!mutableThis.children[index])
mutableThis.children[index] = new Address(mutableThis, index, depth+1);
return mutableThis.children[index];
}
}
struct EntityRef /// Reference to another Entity in the same tree
{
Entity entity; /// Pointer - only valid during splitting / optimizing
const(Address)* address; /// Address - assigned after splitting / optimizing
}
enum largest64bitPrime = 18446744073709551557UL; // 0xFFFFFFFF_FFFFFFC5
// static if (is(ModQ!(ulong, largest64bitPrime)))
static if (modQSupported) // https://issues.dlang.org/show_bug.cgi?id=20677
alias EntityHash = PolynomialHash!(ModQ!(ulong, largest64bitPrime));
else
{
pragma(msg,
"64-bit long multiplication/division is not supported on this platform.\n" ~
"Falling back to working in modulo 2^^64.\n" ~
"Hashing / cache accuracy may be impaired.\n" ~
"---------------------------------------------------------------------");
alias EntityHash = PolynomialHash!ulong;
}
/// Represents a slice of the original code.
final class Entity
{
string head; /// This node's "head", e.g. "{" for a statement block.
Entity[] children; /// This node's children nodes, e.g. the statements of the statement block.
string tail; /// This node's "tail", e.g. "}" for a statement block.
string contents;
struct FileProperties
{
string name; /// Relative to the reduction root
Nullable!uint mode; /// OS-specific (std.file.getAttributes)
Nullable!(SysTime[2]) times; /// Access and modification times
}
FileProperties* file; /// If non-null, this node represents a file
bool isPair; /// Internal hint for --dump output
bool noRemove; /// Don't try removing this entity (children OK)
bool clean; /// Computed fields are up-to-date
bool dead; /// Tombstone or redirect
EntityRef[] dependents;/// If this entity is removed, so should all these entities.
Address* redirect; /// If moved, this is where this entity is now
int id; /// For diagnostics
size_t descendants; /// [Computed] For progress display
EntityHash hash; /// [Computed] Hashed value of this entity's content (as if it were saved to disk).
const(Address)*[] allDependents; /// [Computed] External dependents of this and child nodes
string deadContents; /// [Computed] For --white-out - all of this node's contents, with non-whitespace replaced by whitespace
EntityHash deadHash; /// [Computed] Hash of deadContents
this(string head = null, Entity[] children = null, string tail = null)
{
this.head = head;
this.children = children;
this.tail = tail;
}
@property string comment()
{
string[] result;
debug result = comments;
if (isPair)
{
assert(token == DSplitter.Token.none);
result ~= "Pair";
}
if (token && DSplitter.tokenText[token])
result ~= DSplitter.tokenText[token];
return result.length ? result.join(" / ") : null;
}
override string toString() const
{
return "%(%s%) %s %(%s%)".format([head], children, [tail]);
}
Entity dup() /// Creates a shallow copy
{
auto result = new Entity;
foreach (i, item; this.tupleof)
result.tupleof[i] = this.tupleof[i];
result.children = result.children.dup;
return result;
}
void kill() /// Convert to tombstone/redirect
{
dependents = null;
isPair = false;
descendants = 0;
allDependents = null;
dead = true;
}
private: // Used during parsing only
DSplitter.Token token; /// Used internally
debug string[] comments; /// Used to debug the splitter
}
enum Splitter
{
files, /// Load entire files only
lines, /// Split by line ends
null_, /// Split by the \0 (NUL) character
words, /// Split by whitespace
D, /// Parse D source code
diff, /// Unified diffs
indent, /// Indentation (Python, YAML...)
lisp, /// Lisp and similar languages
}
immutable string[] splitterNames = [EnumMembers!Splitter].map!(e => e.text().toLower().chomp("_")).array();
struct ParseRule
{
string pattern;
Splitter splitter;
}
struct ParseOptions
{
enum Mode
{
source,
words, /// split identifiers, for obfuscation
json,
}
bool stripComments;
ParseRule[] rules;
Mode mode;
uint tabWidth;
}
version (Posix) {} else
{
// Non-POSIX symlink stubs
string readLink(const(char)[]) { throw new Exception("Sorry, symbolic links are only supported on POSIX systems"); }
void symlink(const(char)[], const(char)[]) { throw new Exception("Sorry, symbolic links are only supported on POSIX systems"); }
}
/// Parse the given file/directory.
/// For files, modifies `path` to be the base name for .test / .reduced directories.
Entity loadFiles(ref string path, ParseOptions options)
{
if (path != "-" && !path.isSymlink && path.exists && path.isDir)
{
auto set = new Entity();
foreach (string entry; dirEntries(path, SpanMode.breadth, /*followSymlink:*/false).array.sort!((a, b) => a.name < b.name))
if (isSymlink(entry) || isFile(entry) || isDir(entry))
{
assert(entry.startsWith(path));
auto name = entry[path.length+1..$];
set.children ~= loadFile(name, entry, options);
}
return set;
}
else
{
auto realPath = path;
string name; // For Entity.filename
if (path == "-" || path == "/dev/stdin")
name = path = "stdin";
else
name = realPath.baseName();
return loadFile(name, realPath, options);
}
}
enum BIN_SIZE = 2;
void optimizeUntil(alias stop)(Entity set)
{
static Entity group(Entity[] children)
{
if (children.length == 1)
return children[0];
auto e = new Entity(null, children, null);
e.noRemove = children.any!(c => c.noRemove)();
return e;
}
static void clusterBy(ref Entity[] set, size_t binSize)
{
while (set.length > binSize)
{
auto size = set.length >= binSize*2 ? binSize : (set.length+1) / 2;
//auto size = binSize;
set = set.chunks(size).map!group.array;
}
}
void doOptimize(Entity e)
{
if (stop(e))
return;
foreach (c; e.children)
doOptimize(c);
clusterBy(e.children, BIN_SIZE);
}
doOptimize(set);
}
alias optimize = optimizeUntil!((Entity e) => false);
private:
/// Override std.string nonsense, which does UTF-8 decoding
bool startsWith(in char[] big, in char[] small) { return big.length >= small.length && big[0..small.length] == small; }
bool startsWith(in char[] big, char c) { return big.length && big[0] == c; }
string strip(string s) { while (s.length && isWhite(s[0])) s = s[1..$]; while (s.length && isWhite(s[$-1])) s = s[0..$-1]; return s; }
immutable ParseRule[] defaultRules =
[
{ "*.d" , Splitter.D },
{ "*.di" , Splitter.D },
{ "*.diff" , Splitter.diff },
{ "*.patch", Splitter.diff },
{ "*.lisp" , Splitter.lisp },
{ "*.cl" , Splitter.lisp },
{ "*.lsp" , Splitter.lisp },
{ "*.el" , Splitter.lisp },
{ "*" , Splitter.files },
];
void[] readFile(File f)
{
import std.range.primitives : put;
auto result = appender!(ubyte[]);
auto size = f.size;
if (size <= uint.max)
result.reserve(cast(size_t)size);
put(result, f.byChunk(64 * 1024));
return result.data;
}
Entity loadFile(string name, string path, ParseOptions options)
{
auto base = name.baseName();
Splitter splitterType = chain(options.rules, defaultRules).find!(rule => base.globMatch(rule.pattern)).front.splitter;
Nullable!uint mode;
if (path != "-")
{
mode = getLinkAttributes(path);
if (attrIsSymlink(mode.get()) || attrIsDir(mode.get()))
splitterType = Splitter.files;
}
stderr.writeln("Loading ", path, " [", splitterType, "]");
auto contents =
attrIsSymlink(mode.get(0)) ? path.readLink() :
attrIsDir(mode.get(0)) ? null :
cast(string)readFile(path == "-" ? stdin : File(path, "rb"));
if (options.mode == ParseOptions.Mode.json)
return loadJson(contents);
auto result = new Entity();
result.file = new Entity.FileProperties;
result.file.name = name.replace(dirSeparator, `/`);
result.file.mode = mode;
if (!mode.isNull() && !attrIsSymlink(mode.get()) && path != "-")
{
SysTime accessTime, modificationTime;
getTimes(path, accessTime, modificationTime);
result.file.times = [accessTime, modificationTime];
}
result.contents = contents;
final switch (splitterType)
{
case Splitter.files:
result.children = [new Entity(result.contents, null, null)];
break;
case Splitter.lines:
result.children = parseToLines(result.contents);
break;
case Splitter.words:
result.children = parseToWords(result.contents);
break;
case Splitter.null_:
result.children = parseToNull(result.contents);
break;
case Splitter.D:
if (result.contents.startsWith("Ddoc"))
goto case Splitter.files;
DSplitter splitter;
if (options.stripComments)
result.contents = splitter.stripComments(result.contents);
final switch (options.mode)
{
case ParseOptions.Mode.json:
assert(false);
case ParseOptions.Mode.source:
result.children = splitter.parse(result.contents);
break;
case ParseOptions.Mode.words:
result.children = splitter.parseToWords(result.contents);
break;
}
break;
case Splitter.diff:
result.children = parseDiff(result.contents);
break;
case Splitter.indent:
result.children = parseIndent(result.contents, options.tabWidth);
break;
case Splitter.lisp:
result.children = parseLisp(result.contents);
break;
}
debug
{
string resultContents;
void walk(Entity[] entities) { foreach (e; entities) { resultContents ~= e.head; walk(e.children); resultContents ~= e.tail; }}
walk(result.children);
assert(result.contents == resultContents, "Contents mismatch after splitting:\n" ~ resultContents);
}
return result;
}
// *****************************************************************************************************************************************************************************
/// A simple, error-tolerant D source code splitter.
struct DSplitter
{
struct Pair { string start, end; }
static const Pair[] pairs =
[
{ "{", "}" },
{ "[", "]" },
{ "(", ")" },
];
static immutable string[] blockKeywords = ["try", "catch", "finally", "while", "do", "in", "out", "body", "if", "static if", "else", "for", "foreach"];
static immutable string[] parenKeywords = ["catch", "while", "if", "static if", "for", "foreach"];
/// The order dictates the splitting priority of the separators.
static immutable string[][] separators =
[
[";", "{"] ~ blockKeywords,
["import"],
// From http://wiki.dlang.org/Operator_precedence
// Some items are listed twice, DustMite does not distinguish binary/prefix/postfix operators
[".."],
[","],
["=>"],
["=", "-=", "+=", "<<=", ">>=", ">>>=", "=", "*=", "%=", "^=", "^^=", "~="],
["?", ":"],
["||"],
["&&"],
["|"],
["^"],
["&"],
["==", "!=", ">", "<", ">=", "<=", "!>", "!<", "!>=", "!<=", "<>", "!<>", "<>=", "!<>=", "in", "!in", "is", "!is"],
["<<", ">>", ">>>"],
["+", "-", "~"],
["*", "/", "%"],
["&", "++", "--", "*", "+", "-", /*"!",*/ "~"],
["^^"],
[".", "++", "--" /*, "(", "["*/],
// "=>",
["!"],
["(", "["]
];
enum Token : int
{
none,
end, /// end of stream
whitespace, /// spaces, tabs, newlines
comment, /// all forms of comments
other, /// identifiers, literals and misc. keywords
generated0, /// First value of generated tokens (see below)
max = tokenText.length
}
static immutable string[] tokenText =
{
auto result = new string[Token.generated0];
Token[string] lookup;
Token add(string s)
{
auto p = s in lookup;
if (p)
return *p;
Token t = cast(Token)result.length;
result ~= s;
lookup[s] = t;
return t;
}
foreach (pair; pairs)
{
add(pair.start);
add(pair.end );
}
foreach (i, synonyms; separators)
foreach (sep; synonyms)
add(sep);
return result;
}();
static Token lookupToken(string s)
{
if (!__ctfe) assert(false, "Don't use at runtime");
foreach (t; Token.generated0 .. Token.max)
if (s == tokenText[t])
return t;
assert(false, "No such token: " ~ s);
}
enum Token tokenLookup(string s) = lookupToken(s);
struct TokenPair { Token start, end; }
static TokenPair makeTokenPair(Pair pair) { return TokenPair(lookupToken(pair.start), lookupToken(pair.end)); }
alias lookupTokens = arrayMap!(lookupToken, const string);
static immutable TokenPair[] pairTokens = pairs .arrayMap!makeTokenPair();
static immutable Token[][] separatorTokens = separators.arrayMap!lookupTokens ();
static immutable Token[] blockKeywordTokens = blockKeywords.arrayMap!lookupToken();
static immutable Token[] parenKeywordTokens = parenKeywords.arrayMap!lookupToken();
enum SeparatorType
{
none,
pair,
prefix,
postfix,
binary, /// infers dependency
}
static SeparatorType getSeparatorType(Token t)
{
switch (t)
{
case tokenLookup!";":
return SeparatorType.postfix;
case tokenLookup!"import":
return SeparatorType.prefix;
case tokenLookup!"else":
return SeparatorType.binary;
default:
if (pairTokens.any!(pair => pair.start == t))
return SeparatorType.pair;
if (blockKeywordTokens.canFind(t))
return SeparatorType.prefix;
if (separatorTokens.any!(row => row.canFind(t)))
return SeparatorType.binary;
return SeparatorType.none;
}
}
// ************************************************************************
string s; /// Source code we are splitting
size_t i; /// Cursor
/// Making the end of an input stream a throwable greatly simplifies control flow.
class EndOfInput : Throwable { this() { super(null); } }
/// Are we at the end of the stream?
@property bool eos() { return i >= s.length; }
/// Advances i by n bytes. Throws EndOfInput if there are not enough.
string advance(size_t n)
{
auto e = i + n;
if (e > s.length)
{
i = s.length;
throw new EndOfInput;
}
auto result = s[i..e];
i = e;
return result;
}
/// ditto
char advance() { return advance(1)[0]; }
/// If pre comes next, advance i through pre and return it.
/// Otherwise, return null.
string consume(string pre)
{
if (s[i..$].startsWith(pre))
return advance(pre.length);
else
return null;
}
/// ditto
char consume(char pre)
{
assert(pre);
if (s[i..$].startsWith(pre))
return advance();
else
return 0;
}
/// Peeks at the next n characters.
string peek(size_t n)
{
if (i+n > s.length)
throw new EndOfInput;
return s[i..i+n];
}
/// ditto
char peek() { return peek(1)[0]; }
/// Advances i through one token (whether it's a comment,
/// a series of whitespace characters, or something else).
/// Returns the token type.
Token skipTokenOrWS()
{
if (eos)
return Token.end;
Token result = Token.other;
try
{
auto c = advance();
switch (c)
{
case '\'':
result = Token.other;
if (consume('\\'))
advance();
while (advance() != '\'')
continue;
break;
case '\\': // D1 naked escaped string
result = Token.other;
advance();
break;
case '"':
result = Token.other;
while (peek() != '"')
{
if (advance() == '\\')
advance();
}
advance();
break;
case 'r':
if (consume(`"`))
{
result = Token.other;
while (advance() != '"')
continue;
break;
}
else
goto default;
case '`':
result = Token.other;
while (advance() != '`')
continue;
break;
case '/':
if (consume('/'))
{
result = Token.comment;
while (peek() != '\r' && peek() != '\n')
advance();
}
else
if (consume('*'))
{
result = Token.comment;
while (!consume("*/"))
advance();
}
else
if (consume('+'))
{
result = Token.comment;
int commentLevel = 1;
while (commentLevel)
{
if (consume("/+"))
commentLevel++;
else
if (consume("+/"))
commentLevel--;
else
advance();
}
}
else
goto default;
break;
case '@':
if (consume("disable")
|| consume("property")
|| consume("safe")
|| consume("trusted")
|| consume("system")
)
return Token.other;
goto default;
case '#':
result = Token.other;
do
{
c = advance();
if (c == '\\')
c = advance();
}
while (c != '\n');
break;
default:
{
i--;
Token best;
size_t bestLength;
foreach (Token t; Token.init..Token.max)
{
auto text = tokenText[t];
if (!text)
continue;
if (!s[i..$].startsWith(text))
continue;
if (text[$-1].isAlphaNum() && s.length > i + text.length && s[i + text.length].isAlphaNum())
continue; // if the token is a word, it must end at a word boundary
if (text.length <= bestLength)
continue;
best = t;
bestLength = text.length;
}
if (bestLength)
{
auto consumed = consume(tokenText[best]);
assert(consumed);
return best;
}
i++;
}
if (c.isWhite())
{
result = Token.whitespace;
while (peek().isWhite())
advance();
}
else
if (isWordChar(c))
{
result = Token.other;
while (isWordChar(peek()))
advance();
}
else
result = Token.other;
}
}
catch (EndOfInput)
i = s.length;
return result;
}
/// Skips leading and trailing whitespace/comments, too.
/// Never returns Token.whitespace or Token.comment.
void readToken(out Token type, out string span)
{
size_t spanStart = i;
do
type = skipTokenOrWS();
while (type == Token.whitespace || type == Token.comment);
skipToEOL();
span = s[spanStart..i];
if (type == Token.end && span.length)
type = Token.whitespace;
}
/// Moves i forward over first series of EOL characters,
/// or until first non-whitespace character, whichever comes first.
void skipToEOL()
{
try
while (true)
{
auto c = peek();
if (c == '\r' || c == '\n')
{
do
advance(), c = peek();
while (c == '\r' || c == '\n');
return;
}
else
if (c.isWhite())
i++;
else
if (peek(2) == "//")
{
auto t = skipTokenOrWS();
assert(t == Token.comment);
}
else
break;
}
catch (EndOfInput)
i = s.length;
}
static bool isWordChar(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
}
void reset(string code)
{
s = code;
i = 0;
}
void parseScope(Entity result, Token scopeEnd)
{
enum Level : int
{
zero,
separator0,
separatorMax = separator0 + separators.length - 1,
text,
max
}
Entity[][Level.max] splitterQueue;
Entity[] terminateLevel(Level level)
{
level++;
if (level == Level.max)
return null;
auto r = splitterQueue[level] ~ group(terminateLevel(level));
splitterQueue[level] = null;
return r;
}
while (true)
{
Token token;
string span;
readToken(token, span);
if (token == Token.end)
{
assert(span.empty);
break;
}
if (token == scopeEnd)
{
result.tail = span;
break;
}
auto e = new Entity();
e.token = token;
auto level = Level.text;
Entity after;
foreach (n, synonyms; separatorTokens)
foreach (sep; synonyms)
if (token == sep)
{
level = cast(Level)(Level.separator0 + n);
e.children = terminateLevel(level);
auto type = getSeparatorType(token);
if (type == SeparatorType.prefix || type == SeparatorType.pair)
{
Entity empty = e;
if (e.children.length)
{
e.token = Token.none;
after = empty = new Entity(span);
after.token = token;
}
else
e.head = span;
if (type == SeparatorType.pair)
parseScope(empty, pairTokens.find!(pair => pair.start == token).front.end);
}
else
e.tail = span;
goto handled;
}
e.head = span;
handled:
splitterQueue[level] ~= e;
if (after)
splitterQueue[level] ~= after;
}
result.children ~= terminateLevel(Level.zero);
}
Entity[] parse(string code)
{
reset(code);
auto entity = new Entity;
parseScope(entity, Token.none);
assert(!entity.head && !entity.tail);
postProcess(entity.children);
return [entity];
}
Entity[] parseToWords(string code)
{
reset(code);
Entity[] result;
while (!eos)
{
auto start = i;
auto token = skipTokenOrWS();
auto span = s[start..i];
if (token == Token.other)
result ~= new Entity(span);
else
{
if (!result.length)
result ~= new Entity();
if (!result[$-1].tail)
result[$-1].tail = span;
else
{
start = result[$-1].tail.ptr - s.ptr;
result[$-1].tail = s[start..i];
}
}
}
return result;
}
string stripComments(string code)
{
reset(code);
auto result = appender!string();
while (!eos)
{
auto start = i;
Token t = skipTokenOrWS();
if (t != Token.comment)
result.put(s[start..i]);
}
return result.data;
}
static Entity[] group(Entity[] entities)
{
if (entities.length <= 1)
return entities;
return [new Entity(null, entities, null)];
}
static void postProcessSimplify(ref Entity[] entities)
{
for (size_t i=0; i<entities.length;)
{
auto e = entities[i];
if (e.head.empty && e.tail.empty && e.dependents.empty)
{
assert(e.token == Token.none);
if (e.children.length == 0)
{
entities = entities.remove(i);
continue;
}
else
if (e.children.length == 1)
{
entities[i] = e.children[0];
continue;
}
}
i++;
}
}
// Join together module names. We should not attempt to reduce "import std.stdio" to "import std" (or "import stdio").
static void postProcessImports(ref Entity[] entities)
{
if (entities.length && entities[0].head.strip == "import" && !entities[0].children.length && !entities[0].tail.length)
foreach (entity; entities[1 .. $])
{
static void visit(Entity entity)
{
static bool isValidModuleName(string s) { return s.byChar.all!(c => isWordChar(c) || isWhite(c) || c == '.'); }
static bool canBeMerged(Entity entity)
{
return
isValidModuleName(entity.head) &&
entity.children.all!(child => canBeMerged(child)) &&
isValidModuleName(entity.tail);
}
if (canBeMerged(entity))
{
auto root = entity;
// Link all ancestors to the root, and in reverse, therefore making them inextricable.
void link(Entity entity)
{
entity.dependents ~= EntityRef(root);
// root.dependents ~= EntityRef(entity);
foreach (child; entity.children)
link(child);
}
foreach (child; entity.children)
link(child);
}
else
{
foreach (child; entity.children)
visit(child);
}
}
foreach (child; entity.children)
visit(child);
}
}
static void postProcessDependency(ref Entity[] entities)
{
if (entities.length < 2)
{
foreach (e; entities)
postProcessDependency(e.children);
return;
}
size_t[] points;