-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathpeg.d
3751 lines (3101 loc) · 122 KB
/
peg.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
/**
This module contains the engine behind Pegged, the expression templates building blocks to create a top-down
recursive-descent parser.
The terminals and non-terminals described here are meant to be used inside a Pegged grammar.
As such, they are a bit less user-friendly than what's output by pegged.grammar.
For example they take a ParseTree as input, not a string.
See the /docs directory for the full documentation as markdown files.
*/
module pegged.peg;
/*
NOTE:
Do not use the GrammarTester for unittesting in this module. This module needs
to be able to pass its unittests before the GrammarTester is even trustable.
Writing tests the long way is preferred here, as it will avoid the circular
dependency.
*/
import std.algorithm: equal, map, startsWith, max, countUntil, maxElement, filter;
import std.uni : isAlpha, icmp;
import std.array;
import std.conv;
import std.string: strip;
import std.typetuple;
@safe:
// Returns quoted and escaped version of the input, but if the input is null, then return `"end of input"`.
package string stringified(scope string inp) pure
{
import std.format : format;
import std.range : only;
if (inp is null)
return `"end of input"`;
/* TODO: replace `format` with call to substitute!(isASCIIControlChar) that
* only does escaping of control characters to make this `nothrow`. Reuse
* http://mir-algorithm.libmir.org/mir_format.html#.printEscaped. */
// FIXME: referencing local variable on non-scope parameter requires .idup
// to be @safe. Compiler is wrong about scope inference:
// https://issues.dlang.org/show_bug.cgi?id=20674
return inp.idup.only.format!"%(%s%)";
}
unittest // Run- & Compile-time.
{
static bool doTest()
{
const caseSuit1 = [
"" : `""`,
"\0" : `"\0"`,
"\n" : `"\n"`,
"\t" : `"\t"`,
`"` : `"\""`,
"`" : q"("`")",
"'" : `"'"`,
"42" : `"42"`,
"\"some text\"\n" : `"\"some text\"\n"`
];
const caseSuit2 = [cast(string)null : `"end of input"`];
const auto testSuit = [caseSuit1, caseSuit2];
foreach (const ref suit; testSuit)
{
foreach (const ref value, const ref expected; suit)
{
import std.format : format;
const result = value.stringified;
assert(result == expected, "from %s expected %s but got %s".format(value, expected, result));
}
}
return true;
}
// Result is always true, but here, we just force CTFE-mode.
static assert(doTest); // Compile-time.
doTest; // Run-time.
}
version (tracer)
{
import std.logger;
import std.algorithm.comparison : min;
// Function pointers.
private static bool function(string ruleName, const ref ParseTree p) @safe traceConditionFunction;
private static bool delegate(string ruleName, const ref ParseTree p) @safe traceConditionDelegate;
private static int traceLevel;
private static bool traceBlocked;
private static bool logTraceLevel = false;
private void incTraceLevel()
{
if (!__ctfe)
traceLevel++;
}
private void decTraceLevel()
{
if (!__ctfe)
traceLevel--;
}
private bool shouldTrace(string ruleName, const ref ParseTree p)
{
if (__ctfe || traceBlocked)
return false;
if (traceConditionDelegate != null)
return traceConditionDelegate(ruleName, p);
if (traceConditionFunction != null)
return traceConditionFunction(ruleName, p);
return false;
}
static this()
{
traceLevel = 0;
traceNothing();
traceBlocked = false;
}
/++ Supply a function to dynamically switch tracing on and off based on the rule name.
+
+ Example:
+ ---
+ /* Exclude build-in parsers, only trace parsers generated from MyGrammar. */
+ setTraceConditionFunction(ruleName => ruleName.startsWith("MyGrammar"));
+ ---
+/
void setTraceConditionFunction(bool delegate(string ruleName, const ref ParseTree p) @safe condition)
{
traceConditionDelegate = condition;
traceConditionFunction = null;
}
/// ditto
void setTraceConditionFunction(bool function(string ruleName, const ref ParseTree p) @safe condition)
{
traceConditionFunction = condition;
traceConditionDelegate = null;
}
/** Trace all rules.
*
* This can produce a lot of output.
*/
void traceAll()
{
setTraceConditionFunction(function(string ruleName, const ref ParseTree p) {return true;});
}
/** Do not trace any rules. */
void traceNothing()
{
traceConditionFunction = null;
traceConditionDelegate = null;
}
private string traceMsg(ParseTree p, string expression, string name)
{
import std.format;
Position pos = position(p);
enum inputLength = 15;
string result;
for (auto i = 1; i <= traceLevel; i++)
result ~= format("%d|", i);
result ~= format(" (l:%d, c:%d, i:%d)\t", pos.line + 1, pos.col + 1, pos.index) ~
expression.stringified ~ " considering rule " ~ name.stringified ~ " on " ~
p.input[p.end .. min(p.input.length, p.end + inputLength)].stringified ~
(p.end + inputLength > p.input.length ? "" : "...");
return result;
}
private string traceResultMsg(ParseTree p, string name)
{
import std.format;
import std.range: chain;
import std.algorithm.iteration: joiner;
Position pos = position(p);
enum inputLength = 15;
string result;
for (auto i = 1; i <= traceLevel; i++)
result ~= format("%d|", i);
if (p.successful)
{
string consumed;
foreach (match; p.matches)
consumed ~= match;
result ~= format(" (l:%d, c:%d, i:%d)\t", pos.line + 1, pos.col + 1, pos.index) ~ name.stringified ~ " SUCCEEDED on " ~
consumed.stringified;
}
else
result ~= format(" (l:%d, c:%d, i:%d)\t", pos.line + 1, pos.col + 1, pos.index) ~ name.stringified ~ " FAILED on " ~
p.input[p.end .. min(p.input.length, p.end + inputLength)].stringified ~
(p.end + inputLength > p.input.length ? "" : "...");
return result;
}
/**
Overrides FileLogger to remove the time stamp.
Example:
---
sharedLog = cast(shared) new TraceLogger("TraceLog.txt");
---
*/
class TraceLogger : FileLogger
{
this(in string fn) @safe
{
super(fn);
}
import std.concurrency : Tid;
import std.datetime : SysTime;
override protected void beginLogMsg(string file, int line, string funcName,
string prettyFuncName, string moduleName, LogLevel logLevel,
Tid threadId, SysTime timestamp, Logger logger)
@safe
{
}
}
}
/**
CT Switch for testing 'keywords' implementations
*/
enum
{
IFCHAIN,
TRIE
}
enum KEYWORDS = IFCHAIN;
/**
The basic parse tree, as used throughout the project.
You can define your own parse tree node, but respect the basic layout.
*/
struct ParseTree
{
string name; /// The node name
bool successful; /// Indicates whether a parsing was successful or not
string[] matches; /// The matched input's parts. Some expressions match at more than one place, hence matches is an array.
string input; /// The input string that generated the parse tree. Stored here for the parse tree to be passed to other expressions, as input.
size_t begin, end; /// Indices for the matched part from the very beginning of the first match to the last char of the last match.
ParseTree[] children; /// The sub-trees created by sub-rules parsing.
size_t failEnd; // The furthest this tree could match the input (including !successful rules).
ParseTree[] failedChild; /// The !successful child that could still be partially parsed.
/**
Basic toString for easy pretty-printing.
*/
string toString(string tabs = "") const pure
{
string result = name;
string childrenString;
bool allChildrenSuccessful = true;
foreach(i,child; children)
{
childrenString ~= tabs ~ " +-" ~ child.toString(tabs ~ ((i < children.length -1 ) ? " | " : " "));
if (!child.successful) {
allChildrenSuccessful = false;
}
}
result ~= this.toStringThisNode(allChildrenSuccessful);
return result ~ childrenString;
}
/**
* Basic toString of only this node, without the children
*/
private string toStringThisNode(bool allChildrenSuccessful) const pure
{
if (successful) {
return to!string([begin, end]) ~ to!string(matches) ~ "\n";
} else { // some failure info is needed
if (allChildrenSuccessful) { // no one calculated the position yet
return " " ~ this.failMsg ~ "\n";
} else {
return " (failure)\n";
}
}
}
/**
* Generates a generic error when a node fails
*
* @param successMsg String returned when there isn't an error
* @param formatFailMsg Formating delegate function that generates the error message.
*/
string failMsg(string delegate(Position, string, string, const ParseTree) @safe pure formatFailMsg = defaultFormatFailMsg,
string successMsg = "Sucess") const @property pure
{
foreach(i, child; children) {
if (!child.successful) {
return child.failMsg(formatFailMsg, successMsg);
}
}
if (!successful) {
Position pos = position(this);
string left, right;
if (pos.index < 10) {
left = input[0 .. pos.index];
} else {
left = input[pos.index - 10 .. pos.index];
}
if (pos.index + 10 < input.length) {
right = input[pos.index .. pos.index + 10];
} else {
right = input[pos.index .. $];
}
return formatFailMsg(pos, left, right, this);
}
return successMsg;
}
ParseTree dup() const @property pure nothrow
{
ParseTree result;
result.name = name;
result.successful = successful;
result.matches = matches.dup;
result.input = input;
result.begin = begin;
result.end = end;
result.failEnd = failEnd;
result.failedChild = map!(p => p.dup)(failedChild).array();
result.children = map!(p => p.dup)(children).array();
return result;
}
immutable(ParseTree) idup() const @property @trusted pure nothrow
{
return cast(immutable)dup();
}
// Override opIndex operators
ref inout(ParseTree) opIndex(size_t index) inout pure nothrow @nogc {
return children[index];
}
ref inout(ParseTree[]) opIndex() inout return pure {
return children;
}
size_t opDollar(size_t pos)() const pure nothrow @nogc
{
return children.length;
}
inout(ParseTree)[] opSlice(size_t i, size_t j) inout pure nothrow @nogc {
return children[i..j];
}
}
/**
* Default fail message formating function
*/
immutable defaultFormatFailMsg = delegate (Position pos, string left, string right, const ParseTree pt) pure
{
return "Failure at line " ~ to!string(pos.line) ~ ", col " ~ to!string(pos.col) ~ ", "
~ (left.length > 0 ? "after " ~ left.stringified ~ " " : "")
~ "expected " ~ (pt.matches.length > 0 ? pt.matches[$ - 1].stringified : "NO MATCH")
~ `, but got ` ~ right.stringified;
};
unittest // ParseTree testing
{
ParseTree p;
assert(p == p, "Self-identity on null tree.");
p = ParseTree("Name", true, ["abc", "", "def"], "input", 0, 1, null);
assert(p == p, "Self identity on non-null tree.");
ParseTree child = ParseTree("Child", true, ["abc", "", "def"], "input", 0, 1, null);
p.children = [child, child];
assert(p.children[0] == p[0], "override opIndex allows to write less verbose code to navigate the tree");
assert(p.children == p[] );
assert(p.children[0..1] == p[0..1] );
assert(p.children[0..$] == p[0..$] );
ParseTree q = p;
assert(p == q, "Copying creates equal trees.");
assert(p.children == q.children);
p.children = [child, child, child];
assert(q.children != p.children, "Disconnecting children.");
p = ParseTree("Name", true, ["abc", "", "def"], "input", 0, 1, null);
p.children = [child, child];
q = p.dup;
assert(p == q, "Dupping creates equal trees.");
assert(p.children == q.children, "Equal children for dupped trees.");
p.children = null;
assert(q.children != p.children);
immutable iq = p.idup;
q = iq.dup;
assert(p == q, "Dupping to/from immutable creates equal trees.");
q.children = [p,p];
assert(p != q, "Tree with different children are not equal.");
p.children = [p,p];
assert(p == q, "Adding equivalent children is OK.");
p.matches = null;
assert(p != q, "Nulling matches makes trees unequal.");
p.matches = q.matches;
assert(p == q, "Copying matches makes equal trees.");
p.children[0].successful = false;
assert(p.children[0].failMsg == `Failure at line 0, col 1, after "i" expected "def", but got "nput"`);
assert(p.children[1].failMsg == "Sucess");
assert(p.failMsg == `Failure at line 0, col 1, after "i" expected "def", but got "nput"`);
}
/// To compare two trees for content (not bothering with node names)
/// That's useful to compare the results from two different grammars.
bool softCompare(const ParseTree p1, const ParseTree p2)
{
return p1.successful == p2.successful
&& p1.matches == p2.matches
&& p1.begin == p2.begin
&& p1.end == p2.end
&& equal!(softCompare)(p1.children, p2.children); // the same for children
}
unittest // softCompare
{
ParseTree p = ParseTree("Name", true, ["abc", "", "def"], "input", 0, 1, null);
ParseTree child = ParseTree("Child", true, ["abc", "", "def"], "input", 0, 1, null);
p.children = [child, child];
ParseTree q = p;
assert(p == q, "Copy => Equal trees.");
assert(softCompare(p,q), "Copy => Trees equal for softCompare.");
q.name = "Another One";
assert(p != q, "Name change => non-equal trees.");
assert(softCompare(p,q), "Name change => Trees equal for softCompare.");
}
/// To record a position in a text
struct Position
{
size_t line;/// line number (starts at 0)
size_t col;/// column number (starts at 0)
size_t index;/// index (starts at 0)
}
/**
Given an input string, returns the position corresponding to the end of the string.
For example:
---
assert(position("abc") == Position(0,3,3));
assert(position("abc
") == Position(1,0,4));
assert(position("abc
") == Position(2,4,8));
---
*/
Position position(string s) pure nothrow
{
size_t col, line, index, prev_i;
char prev_c;
foreach(i,c; s)
{
if ((c == '\n' && !(i == prev_i + 1 && prev_c == '\r')) || // new line except when directly following a carriage return.
c == '\r')
{
col = 0;
++line;
++index;
prev_i = i;
prev_c = c;
}
else
{
if (c != '\n')
++col;
++index;
}
}
return Position(line,col,index);
}
/**
Same as previous overload, but from the begin of P.input to p.end
*/
Position position(const ParseTree p) pure nothrow
{
return position(p.input[0..p.end]);
}
unittest
{
assert(position("") == Position(0,0,0), "Null string, position 0.");
assert(position("abc") == Position(0,3,3), "length 3 string, no line feed.");
assert(position("abc
") == Position(1,0,4), "One end of line.");
assert(position("abc
----") == Position(2,4,9), "Three lines (second one empty).");
assert(position("abc
----
----") == Position(2,4,13), "Three lines.");
assert(position("
") == Position(3,0,3), "Four lines, all empty.");
assert(position("one\r\ntwo\r\nthree") == Position(2, 5, 15), "Three lines, DOS line endings");
}
string getName(alias expr)() @property @safe
{
static if (is(typeof( { expr(GetName()); })))
return expr(GetName());
else
return __traits(identifier, expr);
}
struct GetName {}
/**
Basic rule, that always fail without consuming.
*/
ParseTree fail(ParseTree p) pure nothrow @nogc
{
return ParseTree("fail", false, [], p.input, p.end, p.end, null);
}
/// ditto
ParseTree fail(string input) pure nothrow @nogc
{
return fail(ParseTree("", false, [], input));
}
string fail(GetName g) pure nothrow @nogc
{
return "fail";
}
unittest // 'fail' unit test
{
ParseTree input = ParseTree("input", true, [], "This is the input string.", 0,0, null);
ParseTree result = fail(input);
assert(result.name == "fail");
assert(!result.successful, "'fail' fails.");
assert(result.matches is null, "'fail' makes no match.");
assert(result.input == input.input, "'fail' does not change the input.");
assert(result.end == input.end, "'fail' puts the index after the previous parse.");
assert(result.children is null, "'fail' has no children.");
result = fail("This is the input string.");
assert(!result.successful, "'fail' fails.");
}
/**
Matches the end of input. Fails if there is any character left.
*/
ParseTree eoi(ParseTree p) pure nothrow
{
if (p.end == p.input.length)
return ParseTree("eoi", true, [], p.input, p.end, p.end);
else
return ParseTree("eoi", false, ["end of input"], p.input, p.end, p.end);
}
/// ditto
ParseTree eoi(string input) pure nothrow
{
return eoi(ParseTree("", false, [], input));
}
string eoi(GetName g) pure nothrow
{
return "eoi";
}
alias eoi endOfInput; /// helper alias.
unittest // 'eoi' unit test
{
ParseTree input = ParseTree("input", true, [], "This is the input string.", 0,0, null);
ParseTree result = eoi(input);
assert(result.name == "eoi");
assert(!result.successful, "'eoi' fails on non-null string.");
assert(result.matches == ["end of input"], "'eoi' error message.");
assert(result.input == input.input, "'eoi' does not change the input.");
assert(result.end == input.end, "'eoi' puts the index after the previous parse.");
assert(result.children is null, "'eoi' has no children.");
input = ParseTree("input", true, [], "", 0,0, null);
result = eoi(input);
assert(result.successful, "'eoi' succeeds on strings of length 0.");
result = eoi("");
assert(result.successful, "'eoi' succeeds on strings of length 0.");
result = eoi(null);
assert(result.successful, "'eoi' succeeds on null strings");
}
/**
Match any character. As long as there is at least a character left in the input, it succeeds.
Conversely, it fails only if called at the end of the input.
*/
ParseTree any(ParseTree p) pure nothrow
{
if (p.end < p.input.length)
return ParseTree("any", true, [p.input[p.end..p.end+1]], p.input, p.end, p.end+1);
else
return ParseTree("any", false, ["any char"], p.input, p.end, p.end);
}
/// ditto
ParseTree any(string input) pure nothrow
{
return any(ParseTree("", false, [], input));
}
string any(GetName g) pure nothrow
{
return "any";
}
unittest // 'any' unit test
{
ParseTree input = ParseTree("input", true, [], "This is the input string.", 0,0, null);
ParseTree result = any(input);
assert(result.name == "any");
assert(result.successful, "'any' succeeds on non-null strings.");
assert(result.matches == ["T"], "'any' matches the first char in an input.");
assert(result.input == input.input, "'any' does not change the input.");
assert(result.end == input.end+1, "'any' advances the index by one position.");
assert(result.children is null, "'any' has no children.");
result = any("a");
assert(result.successful, "'any' matches on strings of length one.");
assert(result.matches == ["a"], "'any' matches the first char in an input.");
assert(result.input == "a", "'any' does not change the input.");
assert(result.end == 1, "'any' advances the index by one position.");
assert(result.children is null, "'any' has no children.");
input = ParseTree("input", true, [], "", 0,0, null);
result = any(input);
assert(!result.successful, "'any' fails on strings of length 0.");
assert(result.matches == ["any char"], "'any' error message on strings of length 0.");
assert(result.end == 0, "'any' does not advance the index.");
result = any("");
assert(!result.successful, "'any' fails on strings of length 0.");
assert(result.matches == ["any char"], "'any' error message on strings of length 0.");
assert(result.end == 0, "'any' does not advance the index.");
result = any(null);
assert(!result.successful, "'any' fails on null strings.");
assert(result.matches == ["any char"], "'any' error message on strings of length 0.");
assert(result.end == 0, "'any' does not advance the index.");
}
/**
Predefined parser: matches word boundaries, as \b for regexes.
*/
ParseTree wordBoundary(ParseTree p) pure // TODO: nothrow?
{
// TODO: I added more indexing guards and now this could probably use
// some simplification. Too tired to write it better. --Chad
bool matched = (p.end == 0 && isAlpha(p.input.front()))
|| (p.end == p.input.length && isAlpha(p.input.back()))
|| (p.end > 0 && isAlpha(p.input[p.end-1]) && p.end < p.input.length && !isAlpha(p.input[p.end]))
|| (p.end > 0 && !isAlpha(p.input[p.end-1]) && p.end < p.input.length && isAlpha(p.input[p.end]));
if (matched)
return ParseTree("wordBoundary", matched, [], p.input, p.end, p.end, null);
else
return ParseTree("wordBoundary", matched, ["word boundary"], p.input, p.end, p.end, null);
}
/// ditto
ParseTree wordBoundary(string input) pure // TODO: nothrow?
{
return ParseTree("wordBoundary", isAlpha(input.front()), [], input, 0,0, null);
}
string wordBoundary(GetName g) pure nothrow
{
return "wordBoundary";
}
unittest // word boundary
{
ParseTree input = ParseTree("", false, [], "This is a word.");
auto wb = [// "This"
cast(size_t)(0):true, 1:false, 2:false, 3:false, 4: true,
// "is"
5: true, 6:false, 7: true,
// "a"
8: true, 9:true,
// "word"
10:true, 11:false, 12:false, 13:false, 14:true,
// "."
15:false
];
foreach(size_t index; 0 .. input.input.length)
{
input.end = index;
ParseTree result = wordBoundary(input);
assert(result.name == "wordBoundary");
assert(result.successful == wb[index]); // true, false, ...
// for errors, there is an error message
assert(result.successful && result.matches is null || !result.successful);
assert(result.begin == input.end);
assert(result.end == input.end);
assert(result.children is null);
}
}
/**
Represents a literal in a PEG, like "abc" or 'abc' (or even '').
It succeeds if a prefix of the input is equal to its template parameter and fails otherwise.
*/
template literal(string s)
{
enum name = "literal!(\""~s~"\")";
ParseTree literal(ParseTree p)
{
enum lit = "\"" ~ s ~ "\"";
if (p.end+s.length <= p.input.length && p.input[p.end..p.end+s.length] == s)
return ParseTree(name, true, [s], p.input, p.end, p.end+s.length);
else {
import std.algorithm : commonPrefix;
import std.utf : byCodeUnit;
auto prefix = p.input[p.end..$].byCodeUnit.commonPrefix(s.byCodeUnit);
return ParseTree(name, false, [lit], p.input, p.end, p.end, null, p.end + prefix.length);
}
}
ParseTree literal(string input)
{
return .literal!(s)(ParseTree("", false, [], input));
}
string literal(GetName g)
{
return name;
}
}
unittest // 'literal' unit test
{
ParseTree input = ParseTree("input", true, [], "abcdef", 0,0, null);
alias literal!"a" a;
alias literal!"abc" abc;
alias literal!"" empty;
ParseTree result = a(input);
assert(result.name == `literal!("a")`, "Literal name test.");
assert(result.successful, "'a' succeeds on inputs beginning with 'a'.");
assert(result.matches == ["a"], "'a' matches the 'a' at the beginning.");
assert(result.input == input.input, "'a' does not change the input.");
assert(result.end == input.end+1, "'a' advances the index by one position.");
assert(result.children is null, "'a' has no children.");
result = a("abcdef");
assert(result.successful, "'a' succeeds on inputs beginning with 'a'.");
assert(result.matches == ["a"], "'a' matches the 'a' at the beginning.");
assert(result.input == input.input, "'a' does not change the input.");
assert(result.end == input.end+1, "'a' advances the index by one position.");
assert(result.children is null, "'a' has no children.");
result = abc(input);
assert(result.name == `literal!("abc")`, "Literal name test.");
assert(result.successful, "'abc' succeeds on inputs beginning with 'abc'.");
assert(result.matches == ["abc"], "'abc' matches 'abc' at the beginning.");
assert(result.input == input.input, "'abc' does not change the input.");
assert(result.end == input.end+3, "'abc' advances the index by 3 positions.");
assert(result.children is null, "'abc' has no children.");
result = abc("abcdef");
assert(result.successful, "'abc' succeeds on inputs beginning with 'abc'.");
assert(result.matches == ["abc"], "'abc' matches 'abc' at the beginning.");
assert(result.input == input.input, "'abc' does not change the input.");
assert(result.end == input.end+3, "'abc' advances the index by 3 positions.");
assert(result.children is null, "'abc' has no children.");
result = empty(input);
assert(result.name == `literal!("")`, "Literal name test.");
assert(result.successful, "'' succeeds on non-null inputs.");
assert(result.matches == [""], "'' matches '' at the beginning.");
assert(result.input == input.input, "'' does not change the input.");
assert(result.end == input.end+0, "'' does not advance the index.");
assert(result.children is null, "'' has no children.");
result = empty("abcdef");
assert(result.successful, "'' succeeds on non-null inputs.");
assert(result.matches == [""], "'' matches '' at the beginning.");
assert(result.input == input.input, "'' does not change the input.");
assert(result.end == input.end+0, "'' does not advance the index.");
assert(result.children is null, "'' has no children.");
input.input = "bcdef";
result = a(input);
assert(!result.successful, "'a' fails on inputs not beginning with 'a'.");
assert(result.matches == ["\"a\""], "'a' makes no match on 'bcdef'.");
assert(result.input == input.input, "'a' does not change the input.");
assert(result.end == input.end, "'a' does not advances the index on 'bcdef'.");
assert(result.children is null, "'a' has no children.");
result = abc(input);
assert(!result.successful, "'abc' fails on inputs not beginning with 'abc'.");
assert(result.matches == ["\"abc\""], "'abc' does no match on 'bcdef'.");
assert(result.input == input.input, "'abc' does not change the input.");
assert(result.end == input.end, "'abc' does not advance the index on 'bcdef'.");
assert(result.children is null, "'abc' has no children.");
result = empty(input);
assert(result.successful, "'' succeeds on non-null inputs.");
assert(result.matches == [""], "'' matches '' at the beginning.");
assert(result.input == input.input, "'' does not change the input.");
assert(result.end == input.end+0, "'' does not advance the index.");
assert(result.children is null, "'' has no children.");
input.input = "";
result = a(input);
assert(!result.successful, "'a' fails on empty strings.");
assert(result.matches == ["\"a\""], "'a' does not match ''.");
assert(result.input == input.input, "'a' does not change the input.");
assert(result.end == input.end, "'a' does not advance the index on 'bcdef'.");
assert(result.children is null, "'a' has no children.");
result = abc(input);
assert(!result.successful, "'abc' fails on empty strings.");
assert(result.matches == ["\"abc\""], "'abc' does not match ''.");
assert(result.input == input.input, "'abc' does not change the input.");
assert(result.end == input.end, "'abc' does not advance the index on 'bcdef'.");
assert(result.children is null, "'abc' has no children.");
result = empty(input);
assert(result.successful, "'' succeeds on empty strings.");
assert(result.matches == [""], "'' matches '' at the beginning, even on empty strings.");
assert(result.input == input.input, "'' does not change the input.");
assert(result.end == input.end+0, "'' does not advance the index.");
assert(result.children is null, "'' has no children.");
}
/**
Represents a case insensitive literal in a PEG, like "abc"i or 'abc'i (or even ''i).
It succeeds if a case insensitive comparison of a prefix of the input and its template
parameter yields no difference and fails otherwise.
*/
template caseInsensitiveLiteral(string s)
{
enum name = "caseInsensitiveLiteral!(\""~s~"\")";
ParseTree caseInsensitiveLiteral(ParseTree p)
{
enum lit = "\"" ~ s ~ "\"";
if (p.end+s.length <= p.input.length && icmp(p.input[p.end..p.end+s.length], s) == 0)
return ParseTree(name, true, [s], p.input, p.end, p.end+s.length);
else
return ParseTree(name, false, [lit], p.input, p.end, p.end);
}
ParseTree caseInsensitiveLiteral(string input)
{
return .caseInsensitiveLiteral!(s)(ParseTree("", false, [], input));
}
string caseInsensitiveLiteral(GetName g)
{
return name;
}
}
unittest // 'caseInsensitiveLiteral' unit test
{
ParseTree input = ParseTree("input", true, [], "AbCdEf", 0,0, null);
alias caseInsensitiveLiteral!"a" a;
alias caseInsensitiveLiteral!"aBC" abc;
alias caseInsensitiveLiteral!"" empty;
ParseTree result = a(input);
assert(result.name == `caseInsensitiveLiteral!("a")`, "caseInsensitiveLiteral name test.");
assert(result.successful, "'a' succeeds on inputs beginning with 'A'.");
assert(result.matches == ["a"], "'a' matches the 'A' at the beginning.");
assert(result.input == input.input, "'a' does not change the input.");
assert(result.end == input.end+1, "'a' advances the index by one position.");
assert(result.children is null, "'a' has no children.");
result = a("AbCdEf");
assert(result.successful, "'a' succeeds on inputs beginning with 'A'.");
assert(result.matches == ["a"], "'a' matches the 'A' at the beginning.");
assert(result.input == input.input, "'a' does not change the input.");
assert(result.end == input.end+1, "'a' advances the index by one position.");
assert(result.children is null, "'a' has no children.");
result = abc(input);
assert(result.name == `caseInsensitiveLiteral!("aBC")`, "caseInsensitiveLiteral name test.");
assert(result.successful, "'aBC' succeeds on inputs beginning with 'AbC'.");
assert(result.matches == ["aBC"], "'AbC' matches 'aBC' at the beginning.");
assert(result.input == input.input, "'aBC' does not change the input.");
assert(result.end == input.end+3, "'aBC' advances the index by 3 positions.");
assert(result.children is null, "'aBC' has no children.");
result = abc("AbCdEf");
assert(result.successful, "'aBC' succeeds on inputs beginning with 'AbC'.");
assert(result.matches == ["aBC"], "'AbC' matches 'aBC' at the beginning.");
assert(result.input == input.input, "'aBC' does not change the input.");
assert(result.end == input.end+3, "'aBC' advances the index by 3 positions.");
assert(result.children is null, "'aBC' has no children.");
result = empty(input);
assert(result.name == `caseInsensitiveLiteral!("")`, "caseInsensitiveLiteral name test.");
assert(result.successful, "'' succeeds on non-null inputs.");
assert(result.matches == [""], "'' matches '' at the beginning.");
assert(result.input == input.input, "'' does not change the input.");
assert(result.end == input.end+0, "'' does not advance the index.");
assert(result.children is null, "'' has no children.");
result = empty("AbCdEf");
assert(result.successful, "'' succeeds on non-null inputs.");
assert(result.matches == [""], "'' matches '' at the beginning.");
assert(result.input == input.input, "'' does not change the input.");
assert(result.end == input.end+0, "'' does not advance the index.");
assert(result.children is null, "'' has no children.");
input.input = "bCdEf";
result = a(input);
assert(!result.successful, "'a' fails on inputs not beginning with 'a' or 'A'.");
assert(result.matches == ["\"a\""], "'a' makes no match on 'bCdEf'.");
assert(result.input == input.input, "'a' does not change the input.");
assert(result.end == input.end, "'a' does not advances the index on 'bCdEf'.");
assert(result.children is null, "'a' has no children.");
result = abc(input);
assert(!result.successful, "'aBC' fails on inputs beginning with 'bCdEf'.");
assert(result.matches == ["\"aBC\""], "'aBC' does no match on 'bCdEf'.");
assert(result.input == input.input, "'aBC' does not change the input.");
assert(result.end == input.end, "'aBC' does not advance the index on 'bCdEf'.");
assert(result.children is null, "'aBC' has no children.");