-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parser.cs
759 lines (669 loc) · 25.1 KB
/
Parser.cs
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
using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using Parser.AST;
namespace Parser
{
class Parser
{
public delegate ParserResult<T> IParser<T>(InputReader input);
public class InputReader
{
private string _input;
private int _offset;
public InputReader(string input)
{
_input = input;
_offset = 0;
}
public char Read()
{
if (_offset >= _input.Length)
{
return '\0';
}
return _input[_offset++];
}
public int GetPosition()
{
return _offset;
}
public void Seek(int position)
{
_offset = position;
}
public bool EOF()
{
return _offset >= _input.Length;
}
}
public class ParserResult<T>
{
public bool IsSuccess {get; set;}
public T Value {get; set;}
public string ErrorMessage { get; set;}
public static ParserResult<T> Success(T value)
{
var result = new ParserResult<T>();
result.IsSuccess = true;
result.Value = value;
return result;
}
public static ParserResult<T> Failure(string message)
{
var result = new ParserResult<T>();
result.IsSuccess = false;
result.ErrorMessage = message;
return result;
}
}
public Parser()
{
var parsePrimaryExpression = Debug(ParsePrimaryExpression(), "ParsePrimaryExpression");
var parsePostfixExpression = ParsePostfixExpression(parsePrimaryExpression);
parseExpression = ChainR(parsePostfixExpression, Debug(BinaryOps("^"), "Looking OP ^"));
parseExpression = ParseUniaryExpression(parseExpression, UniaryOps("+", "-", "!"));
parseExpression = ChainL(parseExpression, Debug(BinaryOps("*", "/", "%"), "Looking OP *, /, %"));
parseExpression = ChainL(parseExpression, Debug(BinaryOps("+", "-"), "Looking OP +, -"));
parseExpression = ChainL(parseExpression, Debug(BinaryOps("==", "!="), "Looking OP ==, !="));
parseExpression = ChainL(parseExpression, Debug(BinaryOps(">=", ">", "<=", "<"), "Looking OP <=, <, >=, >"));
parseExpression = ChainL(parseExpression, Debug(BinaryOps("&&"), "Looking OP &&"));
parseExpression = ChainL(parseExpression, Debug(BinaryOps("||"), "Looking OP ||"));
parseExpression = ChainL(parseExpression, Debug(BinaryOps("??"), "Looking OP ??"));
}
private static Dictionary<string, SyntaxKind> opTable = new Dictionary<string, SyntaxKind>()
{
{"+", SyntaxKind.PlusExpression},
{"-", SyntaxKind.MinusExpression},
{"*", SyntaxKind.MulExpression},
{"/", SyntaxKind.DivExpression},
{"%", SyntaxKind.PercentExpression},
{"^", SyntaxKind.BitXorExpression},
{"==", SyntaxKind.EqualExpression},
{"!=", SyntaxKind.NotEqualExpression},
{">", SyntaxKind.GreaterThanExpression},
{">=", SyntaxKind.GreaterOrEqualExpression},
{"<", SyntaxKind.LessThanExpression},
{"<=", SyntaxKind.LessOrEqualExpression},
{"&&", SyntaxKind.LogicalAndExpression},
{"||", SyntaxKind.LogicalOrExpression},
{"??", SyntaxKind.NullCoalescExpression},
{"!", SyntaxKind.NotExpression}
};
private IParser<SyntaxNode> ParsePrimaryExpression()
{
var ID = Concat(Opt(Or(All("@@"), Str(Any("_#$@%")))), Str(Any(Letter())), Many(Any(Letter() + Digit() + "_")));
var manyDigits = Many1(Any(Digit()));
var NUM = Concat(manyDigits, Opt(Concat(Str(Char('.')), manyDigits)));
var escapeChar = Concat(Str(Char('\\')), Str(Not("")));
var stringLiteral1 = Concat(Str(Char('"')), Concat(Many(Or(Many1(Not("\\\"")), escapeChar))), Str(Char('"')));
var stringLiteral2 = Concat(Str(Char('\'')), Concat(Many(Or(Many1(Not("\\'")), escapeChar))), Str(Char('\'')));
//var stringLiteral = Or(stringLiteral1, stringLiteral2);
parseID = Terminal(ID, SyntaxKind.IdentiferToken);
var parseNUM = Terminal(NUM, SyntaxKind.NumToken);
//var parseSTRING = Terminal(stringLiteral, SyntaxKind.StringToken);
var parseArgList = SquareBracketed(SepBy(Spaced(LazyParseExpression()), Char(',')));
var parseArrayCreation = Select(parseArgList, argList => { return new SyntaxNode(SyntaxKind.ArrayCreationExpression, argList.ToArray());});
var lookAhead = LookAhead();
var brackedExpression = Bracketed(Spaced(LazyParseExpression()));
return (input) =>
{
var next = lookAhead(input);
if (!next.IsSuccess)
{
return ParserResult<SyntaxNode>.Failure(next.ErrorMessage);
}
switch (next.Value)
{
case '(':
return brackedExpression(input);
case '[':
return parseArrayCreation(input);
case '"':
return Terminal(stringLiteral1, SyntaxKind.StringToken)(input);
case '\'':
return Terminal(stringLiteral2, SyntaxKind.StringToken)(input);
default:
if (Digit().Contains(next.Value))
{
return parseNUM(input);
}
if ((Letter()+"$#_@%").Contains(next.Value))
{
return parseID(input);
}
break;
}
return ParserResult<SyntaxNode>.Failure($"Can't parse out a primary expression, unexpected char {next.Value}");
};
}
private IParser<char> LookAhead()
{
return (input) =>
{
var pos = input.GetPosition();
var result = Any()(input);
input.Seek(pos);
return result;
};
}
private IParser<SyntaxNode> ParsePostfixExpression(IParser<SyntaxNode> parser)
{
var parseProperty = Before(Char('.'), LazyParseID());
var parseIndex = SquareBracketed(Spaced(LazyParseExpression()));
var parseArgList = Bracketed(SepBy(Spaced(LazyParseExpression()), Char(',')));
var lookAhead = LookAhead();
return (input) =>
{
var primary = parser(input);
if (!primary.IsSuccess)
{
return ParserResult<SyntaxNode>.Failure(primary.ErrorMessage);
}
while(true)
{
var next = lookAhead(input);
if (!next.IsSuccess)
{
break;
}
var matched = true;
switch (next.Value)
{
case '.':
var property = parseProperty(input);
if (!property.IsSuccess)
{
return ParserResult<SyntaxNode>.Failure("Can't get an identifer after .");
}
primary.Value = new SyntaxNode(SyntaxKind.AccessExpression, primary.Value, property.Value);
break;
case '[':
var index = parseIndex(input);
if (!index.IsSuccess)
{
return ParserResult<SyntaxNode>.Failure("Can't get an expression after [");
}
primary.Value = new SyntaxNode(SyntaxKind.ElementExpression, primary.Value, index.Value);
break;
case '(':
var argList = parseArgList(input);
if (!argList.IsSuccess)
{
return ParserResult<SyntaxNode>.Failure("Can't get arg list after (");
}
primary.Value = new SyntaxNode(SyntaxKind.InvokeExpression, primary.Value);
primary.Value.Children = primary.Value.Children.Concat(argList.Value).ToArray();
break;
default:
matched = false;
break;
}
if (!matched)
{
break;
}
}
return primary;
};
}
private IParser<SyntaxNode> ParseUniaryExpression(IParser<SyntaxNode> parser,IParser<Func<SyntaxNode, SyntaxNode>> op)
{
return (input) =>
{
var ops = Many(op)(input);
var right = parser(input);
if (!right.IsSuccess)
{
return ParserResult<SyntaxNode>.Failure(right.ErrorMessage);
}
foreach (var op in ops.Value.Reverse())
{
right.Value = op(right.Value);
}
return right;
};
}
private IParser<Func<SyntaxNode, SyntaxNode, SyntaxNode>> BinaryOps(params string[] opStr)
{
var opParsers = opStr.Select(x => All(x)).ToArray();
return Select<string, Func<SyntaxNode, SyntaxNode, SyntaxNode>>(Between(Or(opParsers), Spaces()), op =>
(left, right) => new SyntaxNode(opTable[op], left, right)
);
}
private IParser<Func<SyntaxNode, SyntaxNode>> UniaryOps(params string[] opStr)
{
var opParsers = opStr.Select(x => All(x)).ToArray();
return Select<string, Func<SyntaxNode, SyntaxNode>>(Or(opParsers), op =>
right => new SyntaxNode(opTable[op], right)
);
}
private IParser<char> Any()
{
return (input) =>
{
if (input.EOF())
{
return ParserResult<char>.Failure($"Unexpected end of file");
}
var ch = input.Read();
return ParserResult<char>.Success(ch);
};
}
private IParser<T> Where<T>(IParser<T> parser, Func<T, bool> predicate, Func<T, string> predicateFailMessage = null)
{
return (input) =>
{
var result = parser(input);
if (!result.IsSuccess)
{
return ParserResult<T>.Failure(result.ErrorMessage);
}
if(!predicate(result.Value))
{
var message = predicateFailMessage != null ? predicateFailMessage(result.Value) : "Condition not meet";
return ParserResult<T>.Failure(message);
}
return ParserResult<T>.Success(result.Value);
};
}
private IParser<char> Char(char c)
{
return Where(Any(), ch => ch == c, ch => $"Input {ch} is expected value {c}.");
}
private IParser<string> All(string str)
{
return (input) =>
{
foreach (char c in str)
{
var ch = input.Read();
if (ch != c)
{
return ParserResult<string>.Failure($"Unexpected input, expecting {c}, actual {ch}");
}
};
return ParserResult<string>.Success(str);
};
}
private IParser<char> Not(string str)
{
return Where(Any(), c => !str.Contains(c), c => $"Input {c} should not in {str}.");
}
private IParser<char> Any(string str)
{
return Where(Any(), c => str.Contains(c), c => $"Input {c} is not in {str}.");
}
private IParser<string> Str<T>(IParser<T> parser)
{
return Select<T, string>(parser, v => v.ToString());
}
private IParser<T> Try<T>(IParser<T> parser)
{
return (input) =>
{
var position = input.GetPosition();
var result = parser(input);
if (!result.IsSuccess)
{
input.Seek(position);
}
return result;
};
}
private IParser<T> Or<T>(params IParser<T>[] parsers)
{
return (input) =>
{
var messages = new List<string>();
foreach (var parser in parsers)
{
var result = Try<T>(parser)(input);
if (result.IsSuccess)
{
return result;
}
messages.Add(result.ErrorMessage);
}
return ParserResult<T>.Failure(string.Join("<AND>", messages));
};
}
private IParser<T> Opt<T>(IParser<T> parser, T defaultValue = default(T))
{
return (input) =>
{
var result = Try<T>(parser)(input);
return result.IsSuccess ? result : ParserResult<T>.Success(defaultValue);
};
}
private IParser<U> Select<T, U>(IParser<T> parser, Func<T, U> func)
{
return (input) =>
{
var result = parser(input);
if (result.IsSuccess)
{
return ParserResult<U>.Success(func(result.Value));
}
else
{
return ParserResult<U>.Failure(result.ErrorMessage);
}
};
}
private IParser<IEnumerable<T>> Many<T>(IParser<T> parser)
{
return (input) =>
{
var result = new List<T>(){};
while(true)
{
var part = Try<T>(parser)(input);
if (part.IsSuccess)
{
result.Add(part.Value);
}
else
{
break;
}
}
return ParserResult<IEnumerable<T>>.Success(result);
};
}
private IParser<string> Many(IParser<char> parser)
{
return (input) =>
{
var builder = new StringBuilder();
while(true)
{
var part = Try<char>(parser)(input);
if (part.IsSuccess)
{
builder.Append(part.Value);
}
else
{
break;
}
}
return ParserResult<string>.Success(builder.ToString());
};
}
private IParser<IEnumerable<T>> Many1<T>(IParser<T> parser)
{
return (input) =>
{
var result = new List<T>(){};
var item0 = parser(input);
if (item0.IsSuccess)
{
result.Add(item0.Value);
}
else
{
return ParserResult<IEnumerable<T>>.Failure(item0.ErrorMessage);
}
var rest = Many<T>(parser)(input);
result.AddRange(rest.Value);
return ParserResult<IEnumerable<T>>.Success(result);
};
}
private IParser<string> Many1(IParser<char> parser)
{
return (input) =>
{
var item0 = parser(input);
if (!item0.IsSuccess)
{
return ParserResult<string>.Failure(item0.ErrorMessage);
}
var rest = Many(parser)(input);
return ParserResult<string>.Success(item0.Value.ToString() + rest.Value);
};
}
private IParser<IEnumerable<T>> Seq<T>(params IParser<T>[] parsers)
{
return (input) =>
{
var result = new List<T>(){};
foreach (var parser in parsers)
{
var part = parser(input);
if (part.IsSuccess)
{
result.Add(part.Value);
}
else
{
return ParserResult<IEnumerable<T>>.Failure(part.ErrorMessage);
}
}
return ParserResult<IEnumerable<T>>.Success(result);
};
}
private IParser<T> Aggregate<T>(IParser<T>[] parsers, Func<T, T, T> func)
{
return (input) =>
{
var result = Seq(parsers)(input);
if (result.IsSuccess)
{
var finalValue = result.Value.Aggregate(func);
return ParserResult<T>.Success(finalValue);
}
else
{
return ParserResult<T>.Failure(result.ErrorMessage);
}
};
}
private IParser<IEnumerable<T>> SepBy<T, U>(IParser<T> parser, IParser<U> sep)
{
return (input) =>
{
var result = new List<T>(){};
var first = Try(parser)(input);
if (first.IsSuccess)
{
result.Add(first.Value);
var rest = Many(Before(sep, parser))(input);
result.AddRange(rest.Value);
}
return ParserResult<IEnumerable<T>>.Success(result);
};
}
private IParser<string> Concat(params IParser<string>[] parsers)
{
return Aggregate(parsers, (x, y) => x + y);
}
private IParser<string> Concat(IParser<IEnumerable<string>> parser)
{
return Select<IEnumerable<string>, string>(parser, x => x.Aggregate(string.Empty, (a, b) => a + b));
}
private IParser<T> Between<T, U>(IParser<T> parser, IParser<U> sep)
{
return After(Before(sep, parser), sep);
}
private IParser<T> Between<T, U, V>(IParser<T> parser, IParser<U> sep1, IParser<V> sep2)
{
return After(Before(sep1, parser), sep2);
}
private IParser<U> Before<T, U>(IParser<T> parser1, IParser<U> parser2)
{
return (input) =>
{
var result1 = parser1(input);
if (!result1.IsSuccess)
{
return ParserResult<U>.Failure(result1.ErrorMessage);
}
return parser2(input);
};
}
private IParser<T> After<T, U>(IParser<T> parser1, IParser<U> parser2)
{
return (input) =>
{
var result1 = parser1(input);
if (!result1.IsSuccess)
{
return ParserResult<T>.Failure(result1.ErrorMessage);
}
var result2 = parser2(input);
if (!result2.IsSuccess)
{
return ParserResult<T>.Failure(result2.ErrorMessage);
}
return result1;
};
}
private IParser<T> ChainL<T>(IParser<T> parser, IParser<Func<T, T, T>> op)
{
return (input) =>
{
var result = parser(input);
if (!result.IsSuccess)
{
return ParserResult<T>.Failure(result.ErrorMessage);
}
while (true)
{
var opResult = Try(op)(input);
if (!opResult.IsSuccess)
{
break;
}
var result2 = parser(input);
if (!result2.IsSuccess)
{
return ParserResult<T>.Failure(result2.ErrorMessage);
}
result.Value = opResult.Value(result.Value, result2.Value);
}
return result;
};
}
private IParser<T> ChainR<T>(IParser<T> parser, IParser<Func<T, T, T>> op)
{
IParser<T> right = null;
right = (input) =>
{
var result = parser(input);
if (!result.IsSuccess)
{
return ParserResult<T>.Failure(result.ErrorMessage);
}
var opResult = Try(op)(input);
if (opResult.IsSuccess)
{
var rightResult = right(input);
if (!rightResult.IsSuccess)
{
return ParserResult<T>.Failure(rightResult.ErrorMessage);
}
result.Value = opResult.Value(result.Value, rightResult.Value);
}
return result;
};
return right;
}
private IParser<SyntaxNode> Terminal(IParser<string> parser, SyntaxKind kind)
{
return Select(parser, str => (SyntaxNode)new Terminal(kind, str));
}
private IParser<T> Spaced<T>(IParser<T> parser)
{
return Between(parser, Spaces());
}
private IParser<T> Bracketed<T>(IParser<T> parser)
{
return Between(parser, Char('('), Char(')'));
}
private IParser<T> SquareBracketed<T>(IParser<T> parser)
{
return Between(parser, Char('['), Char(']'));
}
private IParser<T> CurlyBracketed<T>(IParser<T> parser)
{
return Between(parser, Char('{'), Char('}'));
}
public ParserResult<SyntaxNode> Parse(string input)
{
var inputReader = new InputReader(input);
return parseExpression(inputReader);
}
private string Letter()
{
return "abcdefghijklmnopqrstuvwxyzABCEDEFGHIJKLMNOPQRSTUVWXYZ";
}
private string Digit()
{
return "0123456789";
}
private string Space()
{
return " \t\r\n";
}
private IParser<string> Spaces()
{
return (input) =>
{
var builder = new StringBuilder();
while (true)
{
var c = input.Read();
if (!" \t\r\n".Contains(c))
{
input.Seek(input.GetPosition()-1);
break;
}
builder.Append(c);
}
return ParserResult<string>.Success(builder.ToString());
};
}
private IParser<SyntaxNode> LazyParseExpression()
{
return (input) =>
{
return parseExpression(input);
};
}
private IParser<SyntaxNode> LazyParseID()
{
return (input) =>
{
return parseID(input);
};
}
private IParser<T> Debug<T>(IParser<T> parser, string label)
{
return (input) =>
{
if (debug)
{
var indent = string.Concat(Enumerable.Repeat(" ", debugLevel));
Console.WriteLine($"{indent}Enter {label}. <POS:{input.GetPosition()}>");
debugLevel++;
}
var result = parser(input);
if (debug)
{
debugLevel--;
var indent = string.Concat(Enumerable.Repeat(" ", debugLevel));
Console.Write($"{indent}Leave {label}. ");
Console.Write(result.IsSuccess ? "<Success>":"<Failure>");
Console.WriteLine($" <POS:{input.GetPosition()}>");
}
return result;
};
}
private IParser<SyntaxNode> parseExpression;
private IParser<SyntaxNode> parseID;
private bool debug = false;
private int debugLevel = 0;
}
}