-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathgrammar.d
2941 lines (2549 loc) · 108 KB
/
grammar.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
/**
Parser generation module for Pegged.
The Pegged parser itself is in pegged.parser, generated from pegged.examples.peggedgrammar.
The documentation is in the /docs directory.
*/
module pegged.grammar;
import std.algorithm: startsWith;
import std.conv: to;
import std.functional: toDelegate;
import std.stdio;
public import pegged.peg;
import pegged.parser;
@safe:
/**
Option enum to get internal memoization (parse results storing).
*/
enum Memoization { no, yes }
/**
This function takes a (future) module name, a (future) file name and a grammar as a string or a file.
It writes the corresponding parser inside a module with the given name.
*/
void asModule(Memoization withMemo = Memoization.yes)(string moduleName, string fileName, string grammarString, string optHeader = "")
{
import std.stdio;
auto f = File(fileName ~ ".d","w");
f.write("/+ DO NOT EDIT BY HAND!\n",
"This module was automatically generated from the following grammar:\n\n");
f.write(grammarString);
f.write("\n\n+/\n");
f.write("module " ~ moduleName ~ ";\n\n");
if (optHeader.length > 0)
f.write(optHeader ~ "\n\n");
f.write("public import pegged.peg;\n");
f.write("import std.algorithm: startsWith;\n");
f.write("import std.functional: toDelegate;\n\n");
f.write(grammar!(withMemo)(grammarString));
}
/// ditto
void asModule(Memoization withMemo = Memoization.yes)(string moduleName, File file, string optHeader = "")
{
string grammarDefinition;
foreach(line; file.byLine)
{
grammarDefinition ~= line ~ '\n';
}
asModule!(withMemo)(moduleName, grammarDefinition, optHeader);
}
// Helper to insert 'Spacing' before and after Primaries
ParseTree spaceArrow(ParseTree input)
{
ParseTree wrapInSpaces(ParseTree p)
{
ParseTree spacer =
ParseTree("Pegged.Prefix", true, null, null, 0,0, [
ParseTree("Pegged.Suffix", true, null, null, 0, 0, [
ParseTree("Pegged.Primary", true, null, null, 0, 0, [
ParseTree("Pegged.RhsName", true, null, null, 0,0, [
ParseTree("Pegged.Identifier", true, ["Spacing"])
])
])
])
]);
ParseTree result = ParseTree("Pegged.WrapAround", true, p.matches, p.input, p.begin, p.end, p.children);
result.children = spacer ~ result.children ~ spacer;
return result;
}
return modify!( p => p.name == "Pegged.Primary",
wrapInSpaces)(input);
}
/**
Generate a parser from a PEG definition.
The parser is a string containing D code, to be mixed in or written in a file.
----
enum string def = "
Gram:
A <- 'a' B*
B <- 'b' / 'c'
";
mixin(grammar(def));
ParseTree p = Gram("abcbccbcd");
----
*/
string grammar(Memoization withMemo = Memoization.yes)(string definition)
{
ParseTree defAsParseTree = Pegged(definition);
if (!defAsParseTree.successful)
{
// To work around a strange bug with ParseTree printing at compile time
string result = "static assert(false, `" ~ defAsParseTree.toString("") ~ "`);";
return result;
}
return grammar!(withMemo)(defAsParseTree);
}
/// ditto
string grammar(Memoization withMemo = Memoization.yes)(ParseTree defAsParseTree)
{
string[] composedGrammars;
// Grammar analysis in support of left-recursion.
import pegged.introspection;
import std.algorithm : canFind;
GrammarInfo grammarInfo = grammarInfo(defAsParseTree.children[0]);
string[] stoppers; // Keys are the rules that stop left-recursion and the
// values are arrays of strings containing the corresponding
// rules for which memoization needs to be blocked.
/*
I once considered that if two left-recursive cycles intersect, unbounded left-recursion
would be prevented in both cycles if only the intersection rule would be a stopper. Although
true, it causes other problems, as documented in the "Mutual left-recursion" unittest below.
Therefore, we simply make the first rule in every left-recursive cycle a stopper.
Also, one might think that it suffices to prevent ordinary memoization in just the rules
that are part of the cycle. However, some larger input files for pegged/examples/extended_pascal
would fail to parse. So memoization for all left-recursive rules is disabled during
left-recursion.
*/
string[] allLeftRecursiveRules;
foreach (cycle; grammarInfo.leftRecursiveCycles)
foreach (rule; cycle)
if (!canFind(allLeftRecursiveRules, rule))
allLeftRecursiveRules ~= rule;
foreach (cycle; grammarInfo.leftRecursiveCycles)
if (!stoppers.canFind(cycle[0]))
stoppers ~= cycle[0];
// Prints comment showing detected left-recursive cycles.
string printLeftRecursiveCycles()
{
string result;
foreach (cycle; grammarInfo.leftRecursiveCycles)
{
result ~= cycle[0];
foreach (rule; cycle[1..$])
result ~= " <- " ~ rule;
result ~= "\n";
}
return result.length > 0 ? "/** Left-recursive cycles:\n" ~ result ~ "*/\n\n" : "";
}
// Prints comment showing rules that stop left-recursive cycles and rules for which memoization is blocked during recursion.
string printLeftRecursionStoppers()
{
import std.array: join;
string result;
foreach (stopper; stoppers)
result ~= stopper ~ ": " ~ allLeftRecursiveRules.join(", ") ~ "\n";
return result.length > 0 ?
"/** Rules that stop left-recursive cycles, followed by rules for which\n"
~ " * memoization is blocked during recursion:\n" ~ result ~ "*/\n\n" : "";
}
// Analysis completed.
string generateForgetMemo()
{
string result;
result ~= "
static void forgetMemo()
{";
if (withMemo == Memoization.yes)
result ~= "
memo = null;";
if (composedGrammars.length > 0)
result ~= "
import std.traits;";
foreach (composed; composedGrammars)
result ~= "
static if (is(typeof(" ~ composed ~ ".forgetMemo)))
" ~ composed ~ ".forgetMemo();";
result ~= "
}\n";
return result;
}
string generateCode(ParseTree p, string propagatedName = "")
{
string result;
switch (p.name)
{
case "Pegged":
result = generateCode(p.children[0]);
break;
case "Pegged.Grammar":
string grammarName = generateCode(p.children[0]);
string shortGrammarName = p.children[0].matches[0];
//string invokedGrammarName = generateCode(transformName(p.children[0]));
string firstRuleName = generateCode(p.children[1].children[0]);
result =
"@safe struct Generic" ~ shortGrammarName ~ "(TParseTree)
{
import std.functional : toDelegate;
import pegged.dynamic.grammar;
static import pegged.peg;
struct " ~ grammarName ~ "\n {
enum name = \"" ~ shortGrammarName ~ "\";
static ParseTree delegate(ParseTree) @safe [string] before;
static ParseTree delegate(ParseTree) @safe [string] after;
static ParseTree delegate(ParseTree) @safe [string] rules;";
if (withMemo == Memoization.yes) {
result ~= "
import std.typecons:Tuple, tuple;
static TParseTree[Tuple!(string, size_t)] memo;";
if (grammarInfo.leftRecursiveCycles.length > 0)
result ~= "
import std.algorithm: canFind, countUntil, remove;
static size_t[] blockMemoAtPos;";
}
result ~= "
static this() @trusted\n {\n";
ParseTree[] definitions = p.children[1 .. $];
bool userDefinedSpacing;
foreach(i,def; definitions)
{
if (def.children[0].children.length == 1) // Non-parameterized ruleName
result ~= " rules[\"" ~ def.matches[0] ~ "\"] = toDelegate(&" ~ def.matches[0] ~ ");\n";
if (def.matches[0] == "Spacing") // user-defined spacing
{
userDefinedSpacing = true;
break;
}
}
if(!userDefinedSpacing)
result ~= " rules[\"Spacing\"] = toDelegate(&Spacing);\n";
result ~=
" }
template hooked(alias r, string name)
{
static ParseTree hooked(ParseTree p) @safe
{
ParseTree result;
if (name in before)
{
result = before[name](p);
if (result.successful)
return result;
}
result = r(p);
if (result.successful || name !in after)
return result;
result = after[name](p);
return result;
}
static ParseTree hooked(string input) @safe
{
return hooked!(r, name)(ParseTree(\"\",false,[],input));
}
}
static void addRuleBefore(string parentRule, string ruleSyntax) @safe
{
// enum name is the current grammar name
DynamicGrammar dg = pegged.dynamic.grammar.grammar(name ~ \": \" ~ ruleSyntax, rules);
foreach(ruleName,rule; dg.rules)
if (ruleName != \"Spacing\") // Keep the local Spacing rule, do not overwrite it
rules[ruleName] = rule;
before[parentRule] = rules[dg.startingRule];
}
static void addRuleAfter(string parentRule, string ruleSyntax) @safe
{
// enum name is the current grammar named
DynamicGrammar dg = pegged.dynamic.grammar.grammar(name ~ \": \" ~ ruleSyntax, rules);
foreach(ruleName,rule; dg.rules)
{
if (ruleName != \"Spacing\")
rules[ruleName] = rule;
}
after[parentRule] = rules[dg.startingRule];
}
static bool isRule(string s) pure nothrow @nogc
{
import std.algorithm : startsWith;
return s.startsWith(\"" ~ shortGrammarName ~ ".\");
}
";
/+
~ " switch(s)\n"
~ " {\n";
bool[string] ruleNames; // to avoid duplicates, when using parameterized rules
string parameterizedRulesSpecialCode; // because param rules need to be put in the 'default' part of the switch
string paramRuleHandler(string target)
{
return "if (s.length >= "~to!string(shortGrammarName.length + target.length + 3)
~" && s[0.."~to!string(shortGrammarName.length + target.length + 3)~"] == \""
~shortGrammarName ~ "." ~ target~"!(\") return true;";
}
foreach(i,def; definitions)
{
/*
if (def.matches[0] !in ruleNames)
{
ruleNames[def.matches[0]] = true;
if (def.children[0].children.length > 1) // Parameterized rule
parameterizedRulesSpecialCode ~= " " ~ paramRuleHandler(def.matches[0])~ "\n";
else
result ~= " case \"" ~ shortGrammarName ~ "." ~ def.matches[0] ~ "\":\n";
}
*/
if (def.matches[0] == "Spacing") // user-defined spacing
{
userDefinedSpacing = true;
break;
}
}
result ~= " return true;\n"
~ " default:\n"
~ parameterizedRulesSpecialCode
~ " return false;\n }\n }\n";
+/
result ~= " mixin decimateTree;\n\n";
// If the grammar provides a Spacing rule, then this will be used.
// else, the predefined 'spacing' rule is used.
result ~= userDefinedSpacing ? "" : " alias spacing Spacing;\n\n";
// Creating the inner functions, each corresponding to a grammar rule
foreach(def; definitions)
result ~= generateCode(def, shortGrammarName);
// if the first rule is parameterized (a template), it's impossible to get an opCall
// because we don't know with which template arguments it should be called.
// So no opCall is generated in this case.
if (p.children[1].children[0].children.length == 1)
{
// General calling interface
result ~= " static TParseTree opCall(TParseTree p)\n"
~ " {\n"
~ " TParseTree result = decimateTree(" ~ firstRuleName ~ "(p));\n"
~ " result.children = [result];\n"
~ " result.name = \"" ~ shortGrammarName ~ "\";\n"
~ " return result;\n"
~ " }\n\n"
~ " static TParseTree opCall(string input)\n"
~ " {\n";
if (withMemo == Memoization.no)
result ~= " forgetMemo();\n"
~ " return " ~ shortGrammarName ~ "(TParseTree(``, false, [], input, 0, 0));\n"
~ " }\n";
else
result ~= " if(__ctfe)\n"
~ " {\n"
~ " return " ~ shortGrammarName ~ "(TParseTree(``, false, [], input, 0, 0));\n"
~ " }\n"
~ " else\n"
~ " {\n"
~ " forgetMemo();\n"
~ " return " ~ shortGrammarName ~ "(TParseTree(``, false, [], input, 0, 0));\n"
~ " }\n"
~ " }\n";
result ~= " static string opCall(GetName g)\n"
~ " {\n"
~ " return \"" ~ shortGrammarName ~ "\";\n"
~ " }\n\n";
}
result ~= generateForgetMemo();
result ~= " }\n" // end of grammar struct definition
~ "}\n\n" // end of template definition
~ "alias Generic" ~ shortGrammarName ~ "!(ParseTree)."
~ shortGrammarName ~ " " ~ shortGrammarName ~ ";\n\n";
break;
case "Pegged.Definition":
// children[0]: name
// children[1]: arrow (arrow type as first child)
// children[2]: description
string code;
switch(p.children[1].children[0].name)
{
case "Pegged.LEFTARROW":
code ~= generateCode(p.children[2]);
break;
case "Pegged.FUSEARROW":
code ~= "pegged.peg.fuse!(" ~ generateCode(p.children[2]) ~ ")";
break;
case "Pegged.DISCARDARROW":
code ~= "pegged.peg.discard!(" ~ generateCode(p.children[2]) ~ ")";
break;
case "Pegged.KEEPARROW":
code ~= "pegged.peg.keep!("~ generateCode(p.children[2]) ~ ")";
break;
case "Pegged.DROPARROW":
code ~= "pegged.peg.drop!("~ generateCode(p.children[2]) ~ ")";
break;
case "Pegged.PROPAGATEARROW":
code ~= "pegged.peg.propagate!("~ generateCode(p.children[2]) ~ ")";
break;
case "Pegged.SPACEARROW":
ParseTree modified = spaceArrow(p.children[2]);
code ~= generateCode(modified);
break;
case "Pegged.ACTIONARROW":
auto actionResult = generateCode(p.children[2]);
foreach(action; p.children[1].matches[1..$])
actionResult = "pegged.peg.action!(" ~ actionResult ~ ", " ~ action ~ ")";
code ~= actionResult;
break;
default:
break;
}
bool parameterizedRule = p.children[0].children.length > 1;
string completeName = generateCode(p.children[0]);
string shortName = p.matches[0];
string innerName;
string hookedName = p.matches[0];
if (parameterizedRule)
{
result = " template " ~ completeName ~ "\n"
~ " {\n";
innerName ~= "\"" ~ shortName ~ "!(\" ~ ";
hookedName ~= "_" ~ to!string(p.children[0].children[1].children.length);
foreach(i,param; p.children[0].children[1].children)
innerName ~= "pegged.peg.getName!("~ param.children[0].matches[0]
~ (i<p.children[0].children[1].children.length-1 ? ")() ~ \", \" ~ "
: ")");
innerName ~= " ~ \")\"";
}
else
{
innerName ~= "`" ~ completeName ~ "`";
}
string ctfeCode = " pegged.peg.defined!(" ~ code ~ ", \"" ~ propagatedName ~ "." ~ innerName[1..$-1] ~ "\")";
code = "hooked!(pegged.peg.defined!(" ~ code ~ ", \"" ~ propagatedName ~ "." ~ innerName[1..$-1] ~ "\"), \"" ~ hookedName ~ "\")";
if (withMemo == Memoization.no)
result ~= " static TParseTree " ~ shortName ~ "(TParseTree p)\n"
~ " {\n"
~ " if(__ctfe)\n"
~ " {\n"
~ (stoppers.canFind(shortName) ?
" assert(false, \"" ~ shortName ~ " is left-recursive, which is not supported "
~ "at compile-time. Consider using asModule().\");\n"
:
" return " ~ ctfeCode ~ "(p);\n"
)
~ " }\n"
~ " else\n"
~ " {\n"
~ (stoppers.canFind(shortName) ?
// This rule needs to prevent infinite left-recursion.
" static TParseTree[size_t /*position*/] seed;\n"
~ " if (auto s = p.end in seed)\n"
~ " return *s;\n"
~ " auto current = fail(p);\n"
~ " seed[p.end] = current;\n"
~ " while(true)\n"
~ " {\n"
~ " auto result = " ~ code ~ "(p);\n"
~ (grammarInfo.ruleInfo[shortName].nullMatch == NullMatch.no ?
" if (result.end > current.end)\n"
:
" if (result.end > current.end ||\n"
~ " (!current.successful && result.successful) /* null-match */)\n"
)
~ " {\n"
~ " current = result;\n"
~ " seed[p.end] = current;\n"
~ " } else {\n"
~ " seed.remove(p.end);\n"
~ " return current;\n"
~ " }\n"
~ " }\n"
:
// Possibly left-recursive rule, but infinite recursion is already prevented by another rule in the same cycle.
" return " ~ code ~ "(p);\n"
)
~ " }\n"
~ " }\n"
~ " static TParseTree " ~ shortName ~ "(string s)\n"
~ " {\n"
~ " if(__ctfe)\n"
~ " return " ~ ctfeCode ~ "(TParseTree(\"\", false,[], s));\n"
~ " else\n"
~ " {\n"
~ " forgetMemo();\n"
~ " return " ~ code ~ "(TParseTree(\"\", false,[], s));\n"
~ " }\n"
~ " }\n";
else // Memoization.yes
result ~= " static TParseTree " ~ shortName ~ "(TParseTree p)\n"
~ " {\n"
~ " if(__ctfe)\n"
~ " {\n"
~ (stoppers.canFind(shortName) ?
" assert(false, \"" ~ shortName ~ " is left-recursive, which is not supported "
~ "at compile-time. Consider using asModule().\");\n"
:
" return " ~ ctfeCode ~ "(p);\n"
)
~ " }\n"
~ " else\n"
~ " {\n"
~ (stoppers.canFind(shortName) ?
// This rule needs to prevent infinite left-recursion.
" static TParseTree[size_t /*position*/] seed;\n"
~ " if (auto s = p.end in seed)\n"
~ " return *s;\n"
~ " if (!blockMemoAtPos.canFind(p.end))\n"
~ " if (auto m = tuple(" ~ innerName ~ ", p.end) in memo)\n"
~ " return *m;\n"
~ " auto current = fail(p);\n"
~ " seed[p.end] = current;\n"
~ " blockMemoAtPos ~= p.end;\n"
~ " while (true)\n"
~ " {\n"
~ " auto result = " ~ code ~ "(p);\n"
~ (grammarInfo.ruleInfo[shortName].nullMatch == NullMatch.no ?
" if (result.end > current.end)\n"
:
" if (result.end > current.end ||\n"
~ " (!current.successful && result.successful) /* null-match */)\n"
)
~ " {\n"
~ " current = result;\n"
~ " seed[p.end] = current;\n"
~ " } else {\n"
// Since seed is local, it cannot be reset between parses the way memo is reset.
// We can get away with this by removing elements from it, done below, so that
// seed is empty again when left-recursion has ended and all recursive calls have
// returned. The advantage of a local seed is that it remains small and fast. The
// disadvantage is that seed doesn't memoize the final result, so that must be taken
// care of by memo. Note that p.end remains constant for the course of recursion,
// and the length of seed only grows when nested recursion occurs.
~ " seed.remove(p.end);\n"
// TODO investigate if p.end is always the last element of blockMemoAtPos.
~ " assert(blockMemoAtPos.canFind(p.end));\n"
~ " blockMemoAtPos = blockMemoAtPos.remove(countUntil(blockMemoAtPos, p.end));\n"
~ " memo[tuple(" ~ innerName ~ ", p.end)] = current;\n"
~ " return current;\n"
~ " }\n"
~ " }\n"
:
// Possibly left-recursive rule, but infinite recursion is already prevented by another rule in the same cycle.
(allLeftRecursiveRules.canFind(shortName) ?
" if (blockMemoAtPos.canFind(p.end))\n"
~ " return " ~ code ~ "(p);\n"
: ""
)
~ " if (auto m = tuple(" ~ innerName ~ ", p.end) in memo)\n"
~ " return *m;\n"
~ " else\n"
~ " {\n"
~ " TParseTree result = " ~ code ~ "(p);\n"
~ " memo[tuple(" ~ innerName ~ ", p.end)] = result;\n"
~ " return result;\n"
~ " }\n"
)
~ " }\n"
~ " }\n\n"
~ " static TParseTree " ~ shortName ~ "(string s)\n"
~ " {\n"
~ " if(__ctfe)\n"
~ " {\n"
~ " return " ~ ctfeCode ~ "(TParseTree(\"\", false,[], s));\n"
~ " }\n"
~ " else\n"
~ " {\n"
~ " forgetMemo();\n"
~ " return " ~ code ~ "(TParseTree(\"\", false,[], s));\n"
~ " }\n"
~ " }\n";
result ~= " static string " ~ shortName ~ "(GetName g)\n"
~ " {\n"
~ " return \"" ~ propagatedName ~ "." ~ innerName[1..$-1] ~ "\";\n"
~ " }\n\n";
if (parameterizedRule)
result ~= " }\n";
break;
case "Pegged.GrammarName":
result = generateCode(p.children[0]);
if (p.children.length == 2)
result ~= generateCode(p.children[1]);
break;
case "Pegged.LhsName":
result = generateCode(p.children[0]);
if (p.children.length == 2)
result ~= generateCode(p.children[1]);
break;
case "Pegged.ParamList":
result = "(";
foreach(i,child; p.children)
result ~= generateCode(child) ~ ", ";
result = result[0..$-2] ~ ")";
break;
case "Pegged.Param":
result = "alias " ~ generateCode(p.children[0]);
break;
case "Pegged.SingleParam":
result = p.matches[0];
break;
case "Pegged.DefaultParam":
result = p.matches[0] ~ " = " ~ generateCode(p.children[1]);
break;
case "Pegged.Expression":
result ~= generateCode(p.children[0]);
break;
case "Pegged.FirstExpression",
"Pegged.LongestExpression":
if (p.children.length > 1) // [LONGEST_]OR expression
{
// Keyword list detection: "abstract"/"alias"/...
bool isLiteral(ParseTree p)
{
return ( p.name == "Pegged.Sequence"
&& p.children.length == 1
&& p.children[0].children.length == 1
&& p.children[0].children[0].children.length == 1
&& p.children[0].children[0].children[0].children.length == 1
&& p.children[0].children[0].children[0].children[0].name == "Pegged.Literal");
}
bool keywordList = true;
foreach(child;p.children)
if (!isLiteral(child))
{
keywordList = false;
break;
}
if (keywordList)
{
result = "pegged.peg.keywords!(";
foreach(seq; p.children)
result ~= "\"" ~ (seq.matches.length == 3 ? seq.matches[1] : "") ~ "\", ";
result = result[0..$-2] ~ ")";
}
else
{
result = p.name == "Pegged.FirstExpression" ? "pegged.peg.or!(" : "pegged.peg.longest_match!(";
foreach(seq; p.children)
result ~= generateCode(seq) ~ ", ";
result = result[0..$-2] ~ ")";
}
}
else // One child -> just a sequence, no need for an or!( , )
{
result = generateCode(p.children[0]);
}
break;
case "Pegged.Sequence":
if (p.children.length > 1) // real sequence
{
result = "pegged.peg.and!(";
foreach(seq; p.children)
{
string elementCode = generateCode(seq);
// flattening inner sequences
if (elementCode.length > 6 && elementCode[0..5] == "pegged.peg.and!(")
elementCode = elementCode[5..$-1]; // cutting 'and!(' and ')'
result ~= elementCode ~ ", ";
}
result = result[0..$-2] ~ ")";
}
else // One child -> just a Suffix, no need for a and!( , )
{
result = generateCode(p.children[0]);
}
break;
case "Pegged.Prefix":
result = generateCode(p.children[$-1]);
foreach(child; p.children[0..$-1])
result = generateCode(child) ~ result ~ ")";
break;
case "Pegged.Suffix":
result = generateCode(p.children[0]);
foreach(child; p.children[1..$])
{
switch (child.name)
{
case "Pegged.OPTION":
result = "pegged.peg.option!(" ~ result ~ ")";
break;
case "Pegged.ZEROORMORE":
result = "pegged.peg.zeroOrMore!(" ~ result ~ ")";
break;
case "Pegged.ONEORMORE":
result = "pegged.peg.oneOrMore!(" ~ result ~ ")";
break;
case "Pegged.Action":
foreach(action; child.matches)
result = "pegged.peg.action!(" ~ result ~ ", " ~ action ~ ")";
break;
default:
break;
}
}
break;
case "Pegged.Primary":
result = generateCode(p.children[0]);
break;
case "Pegged.RhsName":
result = "";
string composedGrammar = "";
foreach(child; p.children)
{
result ~= generateCode(child);
if (child.name == "Pegged.NAMESEP")
composedGrammar = p.input[p.begin .. child.begin];
}
if (composedGrammar.length > 0 && !composedGrammars.canFind(composedGrammar))
composedGrammars ~= composedGrammar;
break;
case "Pegged.ArgList":
result = "!(";
foreach(child; p.children)
result ~= generateCode(child) ~ ", "; // Allow A <- List('A'*,',')
result = result[0..$-2] ~ ")";
break;
case "Pegged.Identifier":
result = p.matches[0];
break;
case "Pegged.NAMESEP":
result = ".";
break;
case "Pegged.Literal":
if(p.matches.length == 3) // standard case
result = "pegged.peg.literal!(\"" ~ p.matches[1] ~ "\")";
else // only two children -> empty literal
result = "pegged.peg.literal!(``)";
break;
case "Pegged.CILiteral":
if(p.matches.length == 3) // standard case
result = "pegged.peg.caseInsensitiveLiteral!(\"" ~ p.matches[1] ~ "\")";
else // only two children -> empty literal
result = "pegged.peg.caseInsensitiveLiteral!(``)";
break;
case "Pegged.CharClass":
if (p.children.length > 1)
{
result = "pegged.peg.or!(";
foreach(seq; p.children)
result ~= generateCode(seq) ~ ", ";
result = result[0..$-2] ~ ")";
}
else // One child -> just a sequence, no need for an or!( , )
{
result = generateCode(p.children[0]);
}
break;
case "Pegged.CharRange":
/// Make the generation at the Char level: directly what is needed, be it `` or "" or whatever
if (p.children.length > 1) // a-b range
{
result = "pegged.peg.charRange!('" ~ generateCode(p.children[0])
~ "', '"
~ generateCode(p.children[1])
~ "')";
}
else // lone char
{
result = "pegged.peg.literal!(";
string ch = p.matches[0];
switch (ch)
{
case "\\[":
case "\\]":
case "\\-":
result ~= "\"" ~ ch[1..$] ~ "\")";
break;
case "\\\'":
result ~= "\"'\")";
break;
case "\\`":
result ~= q{"`")};
break;
case "\\":
case "\\\\":
result ~= "`\\`)";
break;
case "\"":
case "\\\"":
result ~= "`\"`)";
break;
case "\n":
case "\r":
case "\t":
result ~= "\"" ~ to!string(to!dchar(ch)) ~ "\")";
break;
default:
result ~= "\"" ~ ch ~ "\")";
}
}
break;
case "Pegged.Char":
string ch = p.matches[0];
switch (ch)
{
case "\\[":
case "\\]":
case "\\-":
case "\\\'":
case "\\\"":
case "\\`":
case "\\\\":
result = ch[1..$];
break;
case "\n":
case "\r":
case "\t":
result = to!string(to!dchar(ch));
break;
default:
result = ch;
}
break;
case "Pegged.POS":
result = "pegged.peg.posLookahead!(";
break;
case "Pegged.NEG":
result = "pegged.peg.negLookahead!(";
break;
case "Pegged.FUSE":
result = "pegged.peg.fuse!(";
break;
case "Pegged.DISCARD":
result = "pegged.peg.discard!(";
break;
//case "Pegged.CUT":
// result = "discardChildren!(";
// break;
case "Pegged.KEEP":
result = "pegged.peg.keep!(";
break;
case "Pegged.DROP":
result = "pegged.peg.drop!(";
break;
case "Pegged.PROPAGATE":
result = "pegged.peg.propagate!(";
break;
case "Pegged.OPTION":
result = "pegged.peg.option!(";
break;
case "Pegged.ZEROORMORE":
result = "pegged.peg.zeroOrMore!(";
break;
case "Pegged.ONEORMORE":
result = "pegged.peg.oneOrMore!(";
break;
case "Pegged.Action":
result = generateCode(p.children[0]);
foreach(action; p.matches[1..$])
result = "pegged.peg.action!(" ~ result ~ ", " ~ action ~ ")";
break;
case "Pegged.ANY":
result = "pegged.peg.any";
break;
case "Pegged.WrapAround":
result = "pegged.peg.wrapAround!(" ~ generateCode(p.children[0]) ~ ", "
~ generateCode(p.children[1]) ~ ", "
~ generateCode(p.children[2]) ~ ")";
break;
default:
result = "Bad tree: " ~ p.toString();
break;
}
return result;
}
return printLeftRecursiveCycles() ~ printLeftRecursionStoppers() ~ generateCode(defAsParseTree);
}
/**
Mixin to get what a failed rule expected as input.
Not used by Pegged yet.
*/
mixin template expected()
{
string expected(ParseTree p)
{
switch(p.name)
{
case "Pegged.Expression":
string expectation;
foreach(i, child; p.children)
expectation ~= "(" ~ expected(child) ~ ")" ~ (i < p.children.length -1 ? " or " : "");
return expectation;
case "Pegged.Sequence":
string expectation;
foreach(i, expr; p.children)
expectation ~= "(" ~ expected(expr) ~ ")" ~ (i < p.children.length -1 ? " followed by " : "");
return expectation;
case "Pegged.Prefix":
return expected(p.children[$-1]);
case "Pegged.Suffix":
string expectation;
string end;
foreach(prefix; p.children[1..$])
switch(prefix.name)
{
case "Pegged.ZEROORMORE":
expectation ~= "zero or more times (";
end ~= ")";
break;
case "Pegged.ONEORMORE":
expectation ~= "one or more times (";
end ~= ")";
break;
case "Pegged.OPTION":
expectation ~= "optionally (";
end ~= ")";
break;
case "Pegged.Action":
break;
default:
break;
}
return expectation ~ expected(p.children[0]) ~ end;
case "Pegged.Primary":
return expected(p.children[0]);
//case "Pegged.RhsName":
// return "RhsName, not implemented.";
case "Pegged.Literal":
return "the literal `" ~ p.matches[0] ~ "`";
case "Pegged.CharClass":
string expectation;
foreach(i, child; p.children)
expectation ~= expected(child) ~ (i < p.children.length -1 ? " or " : "");
return expectation;
case "Pegged.CharRange":
if (p.children.length == 1)
return expected(p.children[0]);
else
return "any character between '" ~ p.matches[0] ~ "' and '" ~ p.matches[2] ~ "'";
case "Pegged.Char":
return "the character '" ~ p.matches[0] ~ "'";
case "Pegged.ANY":
return "any character";
default:
return "unknow rule (" ~ p.matches[0] ~ ")";
}
}
}
unittest // 'grammar' unit test: low-level functionalities
{
mixin(grammar(`
Test1:
Rule1 <- 'a'
Rule2 <- 'b'
`));
assert(is(Test1 == struct), "A struct name Test1 is created.");
assert(is(typeof(Test1("a"))), "Test1 is callable with a string arg");
assert(__traits(hasMember, Test1, "Rule1"), "Test1 has a member named Rule1.");
assert(__traits(hasMember, Test1, "Rule2"), "Test1 has a member named Rule2.");
assert(is(typeof(Test1.Rule1("a"))), "Test1.Rule1 is callable with a string arg");
assert(is(typeof(Test1.Rule2("a"))), "Test1.Rule2 is callable with a string arg");
assert(__traits(hasMember, Test1, "decimateTree"), "Test1 has a member named decimateTree.");
assert(__traits(hasMember, Test1, "name"), "Test1 has a member named name.");
assert(__traits(hasMember, Test1, "isRule"), "Test1 has a member named isRule.");
}
unittest // 'grammar' unit test: PEG syntax