-
Notifications
You must be signed in to change notification settings - Fork 16
/
dustmite.d
3040 lines (2656 loc) · 71.6 KB
/
dustmite.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
/// DustMite, a general-purpose data reduction tool
/// Written by Vladimir Panteleev <[email protected]>
/// License: Boost Software License, Version 1.0
module dustmite;
import core.atomic;
import core.thread;
import std.algorithm;
import std.array;
import std.ascii;
import std.container.rbtree;
import std.conv;
import std.datetime;
import std.datetime.stopwatch : StopWatch;
import std.exception;
import std.file;
import std.getopt;
import std.math : nextPow2;
import std.path;
import std.parallelism : totalCPUs;
import std.process;
import std.random;
import std.range;
import std.regex;
import std.stdio : stdout, stderr, File;
import std.string;
import std.typecons;
import splitter;
alias Splitter = splitter.Splitter;
// Issue 314 workarounds
alias join = std.string.join;
alias startsWith = std.algorithm.searching.startsWith;
string dir, resultDir, tmpDir, tester, globalCache;
string dirSuffix(string suffix, Flag!q{temp} temp)
{
return (
(temp && tmpDir ? tmpDir.buildPath(dir.baseName) : dir)
.absolutePath().buildNormalizedPath() ~ "." ~ suffix
).relativePath();
}
size_t maxBreadth;
size_t origDescendants;
int tests, maxSteps = -1; bool foundAnything;
bool noSave, trace, noRedirect, doDump, whiteout;
RemoveRule[] rejectRules;
string strategy = "inbreadth";
struct Times { StopWatch total, load, testSave, resultSave, apply, lookaheadApply, lookaheadWaitThread, lookaheadWaitProcess, test, clean, globalCache, misc; }
Times times;
static this() { times.total.start(); times.misc.start(); }
T measure(string what, T)(scope T delegate() p)
{
times.misc.stop(); mixin("times."~what~".start();");
scope(exit) { mixin("times."~what~".stop();"); times.misc.start(); }
return p();
}
struct Reduction
{
enum Type { None, Remove, Unwrap, Concat, ReplaceWord, Swap }
Type type;
Entity root;
// Remove / Unwrap / Concat / Swap
const(Address)* address;
// Swap
const(Address)* address2;
// ReplaceWord
string from, to;
size_t index, total;
string toString()
{
string name = .to!string(type);
final switch (type)
{
case Reduction.Type.None:
return name;
case Reduction.Type.ReplaceWord:
return format(`%s [%d/%d: %s -> %s]`, name, index+1, total, from, to);
case Reduction.Type.Remove:
case Reduction.Type.Unwrap:
case Reduction.Type.Concat:
{
auto address = addressToArr(this.address);
string[] segments = new string[address.length];
Entity e = root;
size_t progress;
bool binary = maxBreadth == 2;
foreach (i, a; address)
{
auto p = a;
foreach (c; e.children[0..a])
if (c.dead)
p--;
segments[i] = binary ? text(p) : format("%d/%d", e.children.length-a, e.children.length);
foreach (c; e.children[0..a])
progress += c.descendants;
progress++; // account for this node
e = e.children[a];
}
progress += e.descendants;
auto progressPM = (origDescendants-progress) * 1000 / origDescendants; // per-mille
return format("[%2d.%d%%] %s [%s]", progressPM/10, progressPM%10, name, segments.join(binary ? "" : ", "));
}
case Reduction.Type.Swap:
{
static string addressToString(Entity root, const(Address)* addressPtr)
{
auto address = addressToArr(findEntityEx(root, addressPtr).address);
string[] segments = new string[address.length];
bool binary = maxBreadth == 2;
Entity e = root;
foreach (i, a; address)
{
auto p = a;
foreach (c; e.children[0..a])
if (c.dead)
p--;
segments[i] = binary ? text(p) : format("%d/%d", e.children.length-a, e.children.length);
e = e.children[a];
}
return segments.join(binary ? "" : ", ");
}
return format("[%s] <-> [%s]",
addressToString(root, address),
addressToString(root, address2));
}
}
}
}
Address rootAddress;
auto nullReduction = Reduction(Reduction.Type.None);
struct RemoveRule { Regex!char regexp; string shellGlob; bool remove; }
int main(string[] args)
{
bool force, dumpHtml, dumpJson, readJson, showTimes, stripComments, obfuscate, fuzz, keepLength, showHelp, openWiki, showVersion, noOptimize, inPlace;
string coverageDir;
RemoveRule[] removeRules;
string[] splitRules;
uint lookaheadCount, tabWidth = 8;
args = args
.filter!((string arg) {
if (arg.skipOver("-j"))
{
lookaheadCount = arg.length ? arg.to!uint : totalCPUs;
return false;
}
return true;
})
// Work around getopt's inability to handle "-" in 2.080.0
.map!((string arg) => arg == "-" ? "\0" ~ arg : arg)
.array();
getopt(args,
"force", &force,
"reduceonly|reduce-only", (string opt, string value) { removeRules ~= RemoveRule(Regex!char.init, value, true); },
"remove" , (string opt, string value) { removeRules ~= RemoveRule(regex(value, "mg"), null, true); },
"noremove|no-remove" , (string opt, string value) { removeRules ~= RemoveRule(regex(value, "mg"), null, false); },
"reject" , (string opt, string value) { rejectRules ~= RemoveRule(regex(value, "mg"), null, true); },
"strip-comments", &stripComments,
"whiteout|white-out", &whiteout,
"coverage", &coverageDir,
"obfuscate", &obfuscate,
"fuzz", &fuzz,
"keep-length", &keepLength,
"strategy", &strategy,
"split", &splitRules,
"dump", &doDump,
"dump-html", &dumpHtml,
"dump-json", &dumpJson,
"times", &showTimes,
"noredirect|no-redirect", &noRedirect,
"cache", &globalCache, // for research
"trace", &trace, // for debugging
"nosave|no-save", &noSave, // for research
"nooptimize|no-optimize", &noOptimize, // for research
"tab-width", &tabWidth,
"temp-dir", &tmpDir,
"max-steps", &maxSteps, // for research / benchmarking
"i|in-place", &inPlace,
"json", &readJson,
"h|help", &showHelp,
"man", &openWiki,
"V|version", &showVersion,
);
foreach (ref arg; args)
arg.skipOver("\0"); // Undo getopt hack
if (showVersion)
{
version (Dlang_Tools)
enum source = "dlang/tools";
else
version (Dustmite_CustomSource) // Packaging Dustmite separately for a distribution?
enum source = import("source");
else
enum source = "upstream";
stdout.writeln("DustMite build ", __DATE__, " (", source, "), built with ", __VENDOR__, " ", __VERSION__);
if (args.length == 1)
return 0;
}
if (openWiki)
{
browse("https://github.com/CyberShadow/DustMite/wiki");
if (args.length == 1)
return 0;
}
if (showHelp || args.length == 1 || args.length>3)
{
stderr.writef(q"EOS
Usage: %s [OPTION]... PATH TESTER
PATH should contain a clean copy of the file-set to reduce.
TESTER should be a shell command which returns 0 for a correct reduction,
and anything else otherwise.
Supported options:
--force Force reduction of unusual files
--reduce-only MASK Only reduce paths glob-matching MASK
(may be used multiple times)
--remove REGEXP Only reduce blocks covered by REGEXP
(may be used multiple times)
--no-remove REGEXP Do not reduce blocks containing REGEXP
(may be used multiple times)
--reject REGEXP Reject reductions which cause REGEXP to occur in output
(may be used multiple times)
--strip-comments Attempt to remove comments from source code
--white-out Replace deleted text with spaces to preserve line numbers
--coverage DIR Load .lst files corresponding to source files from DIR
--fuzz Instead of reducing, fuzz the input by performing random
changes until TESTER returns 0
--obfuscate Instead of reducing, obfuscate the input by replacing
words with random substitutions
--keep-length Preserve word length when obfuscating
--split MASK:MODE Parse and reduce files specified by MASK using the given
splitter. Can be repeated. MODE must be one of:
%-(%s, %)
--json Load PATH as a JSON file (same syntax as --dump-json)
--no-redirect Don't redirect stdout/stderr streams of test command
--temp-dir Write and run reduction candidates in this directory
-j[N] Use N look-ahead processes (%d by default)
EOS", args[0], splitterNames, totalCPUs);
if (!showHelp)
{
stderr.write(q"EOS
-h, --help Show this message and some less interesting options
EOS");
}
else
{
stderr.write(q"EOS
-h, --help Show this message
Less interesting options:
--man Launch the project wiki web page in a web browser
-V, --version Show program version
--strategy STRAT Set strategy (careful/lookback/pingpong/indepth/inbreadth)
--dump Dump parsed tree to PATH.dump file
--dump-html Dump parsed tree to PATH.html file
--dump-json Dump parsed tree to PATH.json file
--times Display verbose spent time breakdown
--cache DIR Use DIR as persistent disk cache
(in addition to memory cache)
--trace Save all attempted reductions to DIR.trace
-i, --in-place Overwrite input with results
--no-save Disable saving in-progress results
--no-optimize Disable tree optimization step
(may be useful with --dump)
--max-steps N Perform no more than N steps when reducing
--tab-width N How many spaces one tab is equivalent to
(for the "indent" split mode)
EOS");
}
stderr.write(q"EOS
Full documentation can be found on the GitHub wiki:
https://github.com/CyberShadow/DustMite/wiki
EOS");
return showHelp ? 0 : 64; // EX_USAGE
}
enforce(!(stripComments && coverageDir), "Sorry, --strip-comments is not compatible with --coverage");
dir = args[1];
if (isDirSeparator(dir[$-1]))
dir = dir[0..$-1];
if (args.length>=3)
tester = args[2];
bool isDotName(string fn) { return fn.startsWith(".") && !(fn=="." || fn==".."); }
if (!readJson && !force && dir.exists && dir.isDir())
{
bool suspiciousFilesFound;
foreach (string path; dirEntries(dir, SpanMode.breadth))
if (isDotName(baseName(path)) || isDotName(baseName(dirName(path))) || extension(path)==".o" || extension(path)==".obj" || extension(path)==".exe")
{
stderr.writeln("Warning: Suspicious file found: ", path);
suspiciousFilesFound = true;
}
if (suspiciousFilesFound)
stderr.writeln("You should use a clean copy of the source tree.\nIf it was your intention to include this file in the file-set to be reduced,\nyou can use --force to silence this message.");
}
ParseRule parseSplitRule(string rule)
{
auto p = rule.lastIndexOf(':');
string pattern, splitterName;
if (p < 0)
{
pattern = "*";
splitterName = rule;
}
else
{
enforce(p > 0, "Invalid parse rule: " ~ rule);
pattern = rule[0 .. p];
splitterName = rule[p + 1 .. $];
}
auto splitterIndex = splitterNames.countUntil(splitterName);
enforce(splitterIndex >= 0, "Unknown splitter: " ~ splitterName);
return ParseRule(pattern, cast(Splitter)splitterIndex);
}
Entity root;
ParseOptions parseOptions;
parseOptions.stripComments = stripComments;
parseOptions.mode =
readJson ? ParseOptions.Mode.json :
obfuscate ? ParseOptions.Mode.words :
ParseOptions.Mode.source;
parseOptions.rules = splitRules.map!parseSplitRule().array();
parseOptions.tabWidth = tabWidth;
measure!"load"({root = loadFiles(dir, parseOptions);});
enforce(root.children.length, "No files in specified directory");
applyNoRemoveMagic(root);
applyNoRemoveRules(root, removeRules);
applyNoRemoveDeps(root);
if (coverageDir)
loadCoverage(root, coverageDir);
if (!obfuscate && !noOptimize)
optimize(root);
maxBreadth = getMaxBreadth(root);
assignID(root);
convertRefs(root);
recalculate(root);
resetProgress(root);
if (doDump)
dumpSet(root, dirSuffix("dump", No.temp));
if (dumpHtml)
dumpToHtml(root, dirSuffix("html", No.temp));
if (dumpJson)
dumpToJson(root, dirSuffix("json", No.temp));
if (tester is null)
{
stderr.writeln("No tester specified, exiting");
return 0;
}
if (inPlace)
resultDir = dir;
else
{
resultDir = dirSuffix("reduced", No.temp);
if (resultDir.exists)
{
stderr.writeln("Hint: read https://github.com/CyberShadow/DustMite/wiki#result-directory-already-exists");
throw new Exception("Result directory already exists");
}
}
if (!fuzz)
{
auto nullResult = test(root, [nullReduction]);
if (!nullResult.success)
{
auto testerFile = dir.buildNormalizedPath(tester);
version (Posix)
{
if (testerFile.exists && (testerFile.getAttributes() & octal!111) == 0)
stderr.writeln("Hint: test program seems to be a non-executable file, try: chmod +x " ~ testerFile.escapeShellFileName());
}
if (!testerFile.exists && tester.exists)
stderr.writeln("Hint: test program path should be relative to the source directory, try " ~
tester.absolutePath.relativePath(dir.absolutePath).escapeShellFileName() ~
" instead of " ~ tester.escapeShellFileName());
if (!noRedirect)
stderr.writeln("Hint: use --no-redirect to see test script output");
stderr.writeln("Hint: read https://github.com/CyberShadow/DustMite/wiki#initial-test-fails");
throw new Exception("Initial test fails: " ~ nullResult.reason);
}
}
lookaheadProcessSlots = new LookaheadSlot[lookaheadCount];
foundAnything = false;
string resultAdjective;
if (obfuscate)
{
resultAdjective = "obfuscated";
.obfuscate(root, keepLength);
}
else
if (fuzz)
{
resultAdjective = "fuzzed";
.fuzz(root);
}
else
{
resultAdjective = "reduced";
reduce(root);
}
auto duration = times.total.peek();
duration = dur!"msecs"(duration.total!"msecs"); // truncate anything below ms, users aren't interested in that
if (foundAnything)
{
if (!root.dead)
{
if (noSave)
measure!"resultSave"({safeSave(root, resultDir);});
stderr.writefln("Done in %s tests and %s; %s version is in %s", tests, duration, resultAdjective, resultDir);
}
else
{
stderr.writeln("Hint: read https://github.com/CyberShadow/DustMite/wiki#reduced-to-empty-set");
stderr.writefln("Done in %s tests and %s; %s to empty set", tests, duration, resultAdjective);
}
}
else
stderr.writefln("Done in %s tests and %s; no reductions found", tests, duration);
if (showTimes)
foreach (i, t; times.tupleof)
stderr.writefln("%s: %s", times.tupleof[i].stringof, times.tupleof[i].peek());
return 0;
}
size_t getMaxBreadth(Entity e)
{
size_t breadth = e.children.length;
foreach (child; e.children)
{
auto childBreadth = getMaxBreadth(child);
if (breadth < childBreadth)
breadth = childBreadth;
}
return breadth;
}
/// An output range which only allocates a new copy on the first write
/// that's different from a given original copy.
auto cowRange(E)(E[] arr)
{
static struct Range
{
void put(ref E item)
{
if (pos != size_t.max)
{
if (pos == arr.length || item != arr[pos])
{
arr = arr[0 .. pos];
pos = size_t.max;
// continue to append (appending to a slice will copy)
}
else
{
pos++;
return;
}
}
arr ~= item;
}
E[] get() { return pos == size_t.max ? arr : arr[0 .. pos]; }
private:
E[] arr;
size_t pos; // if size_t.max, then the copy has occurred
}
return Range(arr);
}
/// Update computed fields for dirty nodes
void recalculate(Entity root)
{
// Pass 1 - length + hash (and some other calculated fields)
{
bool pass1(Entity e, Address *addr)
{
if (e.clean)
return false;
auto allDependents = e.allDependents.cowRange();
e.descendants = 1;
e.hash = e.deadHash = EntityHash.init;
e.contents = e.deadContents = null;
void putString(string s)
{
e.hash.put(s);
// There is a circular dependency here.
// Calculating the whited-out string efficiently
// requires the total length of all children,
// which is conveniently included in the hash.
// However, calculating the hash requires knowing
// the whited-out string that will be written.
// Break the cycle by calculating the hash of the
// redundantly whited-out string explicitly here.
if (whiteout)
foreach (c; s)
e.deadHash.put(c.isWhite ? c : ' ');
}
if (e.file)
putString(e.file.name);
putString(e.head);
void addDependents(R)(R range, bool fresh)
{
if (e.dead)
return;
auto oldDependents = allDependents.get();
dependentLoop:
foreach (const(Address)* d; range)
{
if (!fresh)
{
d = findEntity(root, d).address;
if (!d)
continue; // Gone
}
if (d.startsWith(addr))
continue; // Internal
// Deduplicate
foreach (o; oldDependents)
if (equal(d, o))
continue dependentLoop;
allDependents.put(d);
}
}
if (e.dead)
assert(!e.dependents);
else
{
// Update dependents' addresses
auto dependents = cowRange(e.dependents);
foreach (d; e.dependents)
{
d.address = findEntity(root, d.address).address;
if (d.address)
dependents.put(d);
}
e.dependents = dependents.get();
}
addDependents(e.dependents.map!(d => d.address), true);
foreach (i, c; e.children)
{
bool fresh = pass1(c, addr.child(i));
e.descendants += c.descendants;
e.hash.put(c.hash);
e.deadHash.put(c.deadHash);
addDependents(c.allDependents, fresh);
}
putString(e.tail);
e.allDependents = allDependents.get();
assert(e.deadHash.length == (whiteout ? e.hash.length : 0));
if (e.dead)
{
e.descendants = 0;
// Switch to the "dead" variant of this subtree's hash at this point.
// This is irreversible (in child nodes).
e.hash = e.deadHash;
}
return true;
}
pass1(root, &rootAddress);
}
// --white-out pass - calculate deadContents
if (whiteout)
{
// At the top-most dirty node, start a contiguous buffer
// which contains the concatenation of all child nodes.
char[] buf;
size_t pos;
void putString(string s)
{
foreach (char c; s)
{
if (!isWhite(c))
c = ' ';
buf[pos++] = c;
}
}
void putWhite(string s)
{
foreach (c; s)
buf[pos++] = c;
}
// This needs to run in a second pass because we
// need to know the total length of nodes first.
void passWO(Entity e, bool inFile)
{
if (e.clean)
{
if (buf)
putWhite(e.deadContents);
return;
}
inFile |= e.file !is null;
assert(e.hash.length == e.deadHash.length);
bool bufStarted;
// We start a buffer even when outside of a file,
// for efficiency (use one buffer across many files).
if (!buf && e.deadHash.length)
{
buf = new char[e.deadHash.length];
pos = 0;
bufStarted = true;
}
auto start = pos;
if (e.file)
putString(e.file.name);
putString(e.head);
foreach (c; e.children)
passWO(c, inFile);
putString(e.tail);
assert(e.deadHash.length == e.hash.length);
e.deadContents = cast(string)buf[start .. pos];
if (bufStarted)
{
assert(pos == buf.length);
buf = null;
pos = 0;
}
if (inFile)
e.contents = e.deadContents;
}
passWO(root, false);
}
{
void passFinal(Entity e)
{
if (e.clean)
return;
foreach (c; e.children)
passFinal(c);
e.clean = true;
}
passFinal(root);
}
}
size_t checkDescendants(Entity e)
{
if (e.dead)
return 0;
size_t n = e.dead ? 0 : 1;
foreach (c; e.children)
n += checkDescendants(c);
assert(e.descendants == n, "Wrong descendant count: expected %d, found %d".format(e.descendants, n));
return n;
}
bool addressDead(Entity root, size_t[] address) // TODO: this function shouldn't exist
{
if (root.dead)
return true;
if (!address.length)
return false;
return addressDead(root.children[address[0]], address[1..$]);
}
struct ReductionIterator
{
Strategy strategy;
bool done = false;
Reduction.Type type = Reduction.Type.None;
Entity e;
this(Strategy strategy)
{
this.strategy = strategy;
next(false);
}
this(this)
{
strategy = strategy.dup;
}
@property ref Entity root() { return strategy.root; }
@property Reduction front() { return Reduction(type, root, strategy.front.addressFromArr); }
void nextEntity(bool success) /// Iterate strategy until the next non-dead node
{
strategy.next(success);
while (!strategy.done && root.addressDead(strategy.front))
strategy.next(false);
}
void reset()
{
strategy.reset();
type = Reduction.Type.None;
}
void next(bool success)
{
if (success && type == Reduction.Type.Concat)
reset(); // Significant changes across the tree
while (true)
{
final switch (type)
{
case Reduction.Type.None:
if (strategy.done)
{
done = true;
return;
}
e = root.entityAt(strategy.front);
if (e.noRemove)
{
nextEntity(false);
continue;
}
if (e is root && !root.children.length)
{
nextEntity(false);
continue;
}
// Try next reduction type
type = Reduction.Type.Remove;
return;
case Reduction.Type.Remove:
if (success)
{
// Next node
type = Reduction.Type.None;
nextEntity(true);
continue;
}
// Try next reduction type
type = Reduction.Type.Unwrap;
if (e.head.length && e.tail.length)
return; // Try this
else
{
success = false; // Skip
continue;
}
case Reduction.Type.Unwrap:
if (success)
{
// Next node
type = Reduction.Type.None;
nextEntity(true);
continue;
}
// Try next reduction type
type = Reduction.Type.Concat;
if (e.file)
return; // Try this
else
{
success = false; // Skip
continue;
}
case Reduction.Type.Concat:
// Next node
type = Reduction.Type.None;
nextEntity(success);
continue;
case Reduction.Type.ReplaceWord:
case Reduction.Type.Swap:
assert(false);
}
}
}
}
void resetProgress(Entity root)
{
origDescendants = root.descendants;
}
abstract class Strategy
{
Entity root;
uint progressGeneration = 0;
bool done = false;
void copy(Strategy result) const
{
result.root = cast()root;
result.progressGeneration = this.progressGeneration;
result.done = this.done;
}
abstract @property size_t[] front();
abstract void next(bool success);
abstract void reset(); /// Invoked by ReductionIterator for significant tree changes
int getIteration() { return -1; }
int getDepth() { return -1; }
final Strategy dup()
{
auto result = cast(Strategy)this.classinfo.create();
copy(result);
return result;
}
}
class SimpleStrategy : Strategy
{
size_t[] address;
override void copy(Strategy target) const
{
super.copy(target);
auto result = cast(SimpleStrategy)target;
result.address = this.address.dup;
}
override @property size_t[] front()
{
assert(!done, "Done");
return address;
}
override void next(bool success)
{
assert(!done, "Done");
}
}
class IterativeStrategy : SimpleStrategy
{
int iteration = 0;
bool iterationChanged;
override int getIteration() { return iteration; }
override void copy(Strategy target) const
{
super.copy(target);
auto result = cast(IterativeStrategy)target;
result.iteration = this.iteration;
result.iterationChanged = this.iterationChanged;
}
override void next(bool success)
{
super.next(success);
iterationChanged |= success;
}
void nextIteration()
{
assert(iterationChanged, "Starting new iteration after no changes");
reset();
}
override void reset()
{
iteration++;
iterationChanged = false;
address = null;
progressGeneration++;
}
}
/// Find the first address at the depth of address.length,
/// and populate address[] accordingly.
/// Return false if no address at that level could be found.
bool findAddressAtLevel(size_t[] address, Entity root)
{
if (root.dead)
return false;
if (!address.length)
return true;
foreach_reverse (i, child; root.children)
{
if (findAddressAtLevel(address[1..$], child))
{
address[0] = i;
return true;
}
}
return false;
}
/// Find the next address at the depth of address.length,
/// and update address[] accordingly.
/// Return false if no more addresses at that level could be found.
bool nextAddressInLevel(size_t[] address, Entity root)
{
if (!address.length || root.dead)
return false;
if (nextAddressInLevel(address[1..$], root.children[address[0]]))
return true;
if (!address[0])
return false;
foreach_reverse (i; 0..address[0])
{
if (findAddressAtLevel(address[1..$], root.children[i]))
{
address[0] = i;
return true;
}
}
return false;
}
/// Find the next address, starting from the given one
/// (going depth-first). Update address accordingly.
/// If descend is false, then skip addresses under the given one.
/// Return false if no more addresses could be found.
bool nextAddress(ref size_t[] address, Entity root, bool descend)
{
if (root.dead)
return false;
if (!address.length)
{
if (descend && root.children.length)
{
address ~= [root.children.length-1];
return true;
}
return false;
}