/
pgen_parser.d
820 lines (637 loc) · 15.3 KB
/
pgen_parser.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
module pgen_parser;
Token[] lex(in string source) pure {
uint col;
uint line;
uint pos;
Token[] result;
// uint[string] intrmap;
char peek(int offset) {
if (pos + offset > source.length - 1) return '\0';
assert(pos + offset <= source.length && pos + offset >= 0);
return source[pos + offset];
}
bool isWhiteSpace(char c) pure {
return (c == ' ' || c == '\t' || c == '\n');
}
bool isIdentifier(char c) pure {
return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '_' && c <= '_'));
}
bool isNumber(char c) pure {
return ((c >= '0' && c <= '9'));
}
TokenType fixedToken(char[3] c) pure {
switch (c[0]) {
// case '\n' :
// return TokenType.newline;
case '/' :
return TokenType.slash;
case '\0' :
return TokenType.eof;
case ']' :
return TokenType.rbracket;
case '{' :
return TokenType.lbrace;
case '}' :
return TokenType.rbrace;
case '(' :
return TokenType.lparen;
case ')' :
return TokenType.rparen;
case ':' :
return TokenType.colon;
case ',' :
return TokenType.comma;
case '@' :
return TokenType.at;
case '[' :
switch (c[1]) {
case ']' :
return TokenType.lrbracket;
default :
return TokenType.lbracket;
}
case '?' :
switch (c[1..$]) {
case "lb" :
return TokenType.lookbehind;
default :
return TokenType.questionmark;
}
default :
return TokenType.INVALID;
}
}
void putDataToken(TokenType ttype, char[] data) {
assert(ttype == TokenType.identifier
|| ttype == TokenType.char_
|| ttype == TokenType.string_
|| ttype == TokenType.number);
uint length = cast(uint) data.length;
if (ttype == TokenType.char_ || ttype == TokenType.string_) {
length += 2;
}
result ~= Token(ttype, line, col, length, data);
col += length;
pos += length;
}
void putToken(TokenType ttype) {
assert(ttype);
assert(ttype != TokenType.identifier
&& ttype != TokenType.char_
&& ttype != TokenType.string_
&& ttype != TokenType.number);
uint length = 1;
switch(ttype) {
case TokenType.lrbracket :
length = 2;
break;
case TokenType.lookbehind :
length = 3;
break;
// case TokenType.newline :
// line++;
// col = -1;
// return;
default :
break;
}
result ~= Token(ttype, line, col, length, null);
col += length;
pos += length;
}
void lexIdentifier() {
char[] identifier;
char p = peek(0);
while (isIdentifier(p)) {
identifier ~= p;
p = peek(cast(uint) identifier.length);
}
assert(identifier.length > 0);
putDataToken(TokenType.identifier, identifier);
}
void lexChar() {
assert(peek(0) == '\'');
char chr = peek(1);
assert(peek(2) == '\'');
putDataToken(TokenType.char_, [chr]);
}
void lexString() {
assert(peek(0) == '"');
char[] string_;
char p = peek(1);
while(p != '"') {
string_ ~= p;
p = peek(cast (uint) string_.length + 1);
}
putDataToken(TokenType.string_, string_);
}
void lexNumber() {
char[] number;
char p = peek(0);
while (isNumber(p)) {
number ~= p;
p = peek(cast(uint) number.length);
}
assert(number.length > 0);
putDataToken(TokenType.number, number);
}
void tokenize() {
// result ~= Token.init;
while (pos<source.length) {
// debug {
// import std.stdio;
// writeln(pos,":",source.length,result[$-1]);
// }
char p = peek(0);
if (isWhiteSpace(p)) {
if(p == '\n') {
line++;
col = 0;
} else {
col++;
}
pos++;
}
if (auto t = fixedToken([p, peek(1), peek(2)])) {
putToken(t);
} else if (isIdentifier(p)) {
lexIdentifier();
} else if (isNumber(p)) {
lexNumber();
} else if (p == '"') {
lexString();
} else if (p == '\'') {
lexChar();
} else {
import std.conv;
//assert("char '" ~to!string(p) ~ "' is not handeled" );
}
}
putToken(TokenType.eof);
return;
}
tokenize();
return result;
}
enum TokenType {
//CharClassTokens:
INVALID = 0,
BOF,
identifier, // [a-zA-Z_]
number, // [0-9]
string_, // "bla"
char_, // 'b'
newline, // \n
lookbehind, // !lb
minus, // -
at, // @
lbracket,// [
rbracket,// ]
lrbracket, // []
lparen, // (
rparen, // )
lbrace, // {
rbrace, // }
slash, // /
singlequote, // '
doublequote, // "
questionmark, // ?
colon, // :
comma, // ,
eof // End of File
}
struct Token {
TokenType type;
uint line;
uint col;
uint length;
char[] data;
}
Group parse(in Token[] tokens) pure {
struct Parser {
pure:
const(Token[]) tokens;
uint pos;
Token lastMatched;
this(const(Token[]) tokens) pure {
this.tokens = tokens;
}
import std.traits;
auto peekParse(F)(F parseFunction)
if(is(F == delegate)) {
auto oldpos = pos;
auto result = parseFunction();
pos = oldpos;
return result;
}
const(Token) peekToken(int offset) {
assert(pos + offset <= tokens.length && pos + offset >= 0);
return tokens[pos + offset];
}
bool peekMatch(TokenType[] arr) {
foreach (uint i,e;arr) {
if(peekToken(i).type != e) {
return false;
}
}
return true;
}
bool opt_match(TokenType t) {
lastMatched = cast(Token) peekToken(0);
if (lastMatched.type == t) {
pos++;
return true;
} else {
lastMatched = Token.init;
return false;
}
}
Token match(TokenType t) {
import std.conv;
import std.exception:enforce;
enforce(opt_match(t), "Expected : " ~ to!string(t) ~ " Got : " ~ to!string(peekToken(0).type));
return lastMatched;
}
bool isGroup() {
return peekMatch([TokenType.identifier, TokenType.lbrace]);
}
bool isAlternativeElement() {
return typeid(peekParse(&parseAlternativeElement)) is typeid(AlternativeElement);
}
bool isRangeElement() {
return peekMatch([TokenType.lbracket]);
}
bool isCharElement() {
return peekMatch([TokenType.char_]);
}
bool isStringElement() {
return peekMatch([TokenType.string_]);
}
bool isLookbehindElement() {
return peekMatch([TokenType.lookbehind]);
}
bool isConstantElement() {
return isRangeElement()
|| isCharElement()
|| isStringElement()
|| isLookbehindElement();
}
bool isOptinalElement() {
return peekMatch([TokenType.questionmark]);
}
bool isNamedElement() {
return peekMatch([TokenType.identifier, TokenType.identifier]);
}
bool isArrayElement() {
return peekMatch([TokenType.identifier, TokenType.lrbracket]);
}
bool isParenElement() {
return peekMatch([TokenType.lparen]);
}
bool isPatternElement() {
return isAlternativeElement()
|| isConstantElement()
|| isNamedElement()
|| isArrayElement()
|| isOptinalElement()
|| isParenElement();
}
Identifier parseIdentifier() {
Token id = match(TokenType.identifier);
return new Identifier(id.data);
}
PatternElement parseAlternativeElement() {
PatternElement[] alternatives;
alternatives ~= parsePatternElement();
while (opt_match(TokenType.slash)) {
alternatives ~= parsePatternElement();
}
if (alternatives.length > 1) {
return new AlternativeElement(alternatives);
} else {
return alternatives[0];
}
}
PatternElement parsePatternElement() {
if (isConstantElement()) {
return parseConstantElement();
} else if (isArrayElement()) {
return parseArrayElement();
} else if (isNamedElement()) {
return parseNamedElement();
} else if (isOptinalElement()) {
return parseOptionalElement();
} else if (isParenElement()) {
return parseParenElement();
} else {
assert(0, "No matching PatternElement");
}
}
ConstantElement parseConstantElement() {
if (isRangeElement()) {
return parseRangeElement();
// } else if (isCharElement()) {
// return parseCharElement();
} else if (isStringElement()) {
return parseStringElement();
} else if (isLookbehindElement()) {
return parseLookBehindElement();
} else {
assert(0, "No matching ConstantElement");
}
}
Group parseGroup() {
Identifier name;
name = parseIdentifier();
match(TokenType.lbrace);
if (isGroup() /*||
peekMatch([TokenType.identifier,TokenType.at, TokenType.identifier, TokenType.lbracket])*/) {
Group[] groups;
while (!opt_match(TokenType.rbrace)) {
groups ~= parseGroup();
}
assert(groups.length > 0);
return new Group(name, groups);
} else if (isPatternElement()) {
PatternElement[] elements;
while (!opt_match(TokenType.rbrace)) {
elements ~= parseAlternativeElement();
opt_match(TokenType.comma);
}
assert(elements.length > 0);
return new Group(name, elements);
} else {
assert(0,"No matching Group");
}
}
CharRange parseCharRange() {
char rangeBegin;
char rangeEnd;
rangeBegin = match(TokenType.char_).data[0];
if (opt_match(TokenType.minus)) {
rangeEnd = match(TokenType.char_).data[0];
} else {
rangeEnd = rangeBegin;
}
return new CharRange(rangeBegin, rangeEnd);
}
RangeElement parseRangeElement() {
CharRange[] ranges;
match(TokenType.lbracket);
while(!opt_match(TokenType.rbracket)) {
ranges ~= parseCharRange();
}
assert(ranges.length > 0);
return new RangeElement(ranges);
}
StringElement parseStringElement() {
return new StringElement(match(TokenType.string_).data);
}
LookBehindElement parseLookBehindElement() {
StringElement str_elm;
match(TokenType.lookbehind);
match(TokenType.lparen);
str_elm = parseStringElement();
assert(str_elm);
match(TokenType.rparen);
return new LookBehindElement(str_elm);
}
ParenElement parseParenElement() {
PatternElement[] elements;
match(TokenType.lparen);
while(opt_match(TokenType.comma)) {
elements ~= parseAlternativeElement();
}
match(TokenType.rparen);
return new ParenElement(elements);
}
NamedElement parseNamedElement() {
auto type = parseIdentifier();
auto name = parseIdentifier();
return new NamedElement(type, name);
}
ArrayElement parseArrayElement() {
auto type = parseIdentifier();
match(TokenType.lrbracket);
auto name = parseIdentifier();
string listSeperator = void;
if (opt_match(TokenType.colon)) {
listSeperator = match(TokenType.string_).data.idup;
}
return new ArrayElement(type, name, listSeperator);
}
OptionalElement parseOptionalElement() {
match(TokenType.questionmark);
auto cond = parseConstantElement();
match(TokenType.colon);
auto elem = parseAlternativeElement();
return new OptionalElement(cond, elem);
}
}
return Parser(tokens).parseGroup();
}
class CharRange {
char rangeBegin;
char rangeEnd;
this(char rangeBegin, char rangeEnd) pure {
this.rangeBegin = rangeBegin;
this.rangeEnd = rangeEnd;
}
}
abstract class Node {}
abstract class Range : Node {}
abstract class PredefinedRange : Range {}
class Identifier : PredefinedRange {
char[] identifier;
this(char[] identifier) pure {
this.identifier = identifier;
}
}
class Group : Node {
Identifier name;
bool hasGroups;
union {
Group[] groups;
PatternElement[] elements;
}
this(Identifier name, Group[] groups) pure {
this.name = name;
this.groups = groups;
this.hasGroups = true;
}
this(Identifier name, PatternElement[] elements) pure {
this.name = name;
this.elements = elements;
}
}
abstract class PatternElement {}
class AlternativeElement : PatternElement {
PatternElement[] alternatives;
this(PatternElement[] alternatives) pure {
this.alternatives = alternatives;
}
}
abstract class ConstantElement : PatternElement {}
class RangeElement : ConstantElement {
CharRange[] ranges;
this(CharRange[] ranges) pure {
this.ranges = ranges;
}
}
class StringElement : ConstantElement {
char[] string_;
this(char[] string_) pure {
this.string_ = string_;
}
}
class LookBehindElement : ConstantElement {
StringElement str_elm;
this(StringElement str_elm) pure {
this.str_elm = str_elm;
}
}
class ParenElement : PatternElement {
PatternElement[] elements;
this(PatternElement[] elements) pure {
this.elements = elements;
}
}
class NamedElement : PatternElement {
Identifier type;
Identifier name;
this(Identifier type, Identifier name) pure {
this.type = type;
this.name = name;
}
}
class ArrayElement : PatternElement {
Identifier type;
Identifier name;
string lst_sep;
this(Identifier type, Identifier name, string lst_sep) pure {
this.type = type;
this.name = name;
this.lst_sep = lst_sep;
}
}
class OptionalElement : PatternElement {
ConstantElement cond;
PatternElement elem;
this(ConstantElement cond, PatternElement elem) pure {
this.cond = cond;
this.elem = elem;
}
}
struct ConstructorVisitor {
import visitor;
uint pos;
uint[] alternativePositions;
bool[] hasConsturctorElement;
string[] alternativeParams;
string[] alternativeBodys;
struct Constructor {
string params;
string _body;
}
Constructor[] constructors;
string visit(ParenElement[] elements) {
string ret;
foreach (element;elements) {
dispatch!((a){return "";})(this, element);
}
foreach(constructor;constructors) {
ret ~= "\tthis(" ~ constructor.params ~ ") {\n" ~
constructor._body ~ "\t}\n";
}
return ret;
}
void visit(AlternativeElement ae) {
alternativePositions ~= pos;
foreach (i,alt;ae.alternatives) {
AlternativeElement cons = visit(alt);
if (cons != Constructor.init) {
}
if (as != "") {
tmp ~= as;
}
}
result ~= "\t\t" ~ str.split("[]").split(" ")[0][0].toUpper ~ ",\n";
}
}
struct PTreeVisitor {
import visitor;
string parent_name;
string visit(Group[] groups) {
string result;
foreach(group;groups) {
result ~= visit(group);
}
return result;
}
string visit(PatternElement pe) {
return dispatch!((a){return "";})(this, pe);
}
string visit(AlternativeElement ae) {
string result;
string[] tmp;
foreach (alt;ae.alternatives) {
auto as = visit(alt);
if (as != "") {
tmp ~= as;
}
}
if (tmp.length > 0) {
result ~="enum {\n";
import std.string;
foreach(str;tmp) {
result ~= "\t\t" ~ str.split("[]").split(" ")[0][0].toUpper ~ ",\n";
}
result ~= "\t}\n";
result ~= "\tunion {\n";
foreach(str;tmp) {
result ~= "\t\t" ~ str;
}
result ~= "\t}\n";
}
return result;
}
string visit(NamedElement ne) {
return cast(string) (ne.type.identifier ~ " " ~ ne.name.identifier ~ ";\n");
}
string visit(OptionalElement oe) {
return dispatch(this, oe.elem);
}
string visit(ArrayElement ae) {
return cast(string) (ae.type.identifier ~ "[] " ~ ae.name.identifier ~ ";\n");
}
string visit(Group group) {
string result;
if (group.hasGroups) {
result ~= "abstract class " ~ group.name.identifier;
if (parent_name) {
result ~= " : " ~ parent_name;
}
result ~= " {}\n\n";
string old_parent = parent_name;
parent_name = cast(string) group.name.identifier;
foreach(group_;group.groups) {
result ~= visit(group_);
}
parent_name = old_parent;
} else {
result ~= "class " ~ group.name.identifier;
if (parent_name) {
result ~= " : " ~ parent_name;
}
result ~= " {\n";
foreach(element;group.elements) {
auto s = visit(element);
result ~= (s != "") ? "\t" ~ s : "";
}
result ~= "\n";
result ~= ConsturctorVisitor().visit(group.elements);
result ~= "}\n";
}
return result;
}
}