-
Notifications
You must be signed in to change notification settings - Fork 5
/
Rule.cs
784 lines (641 loc) · 23.7 KB
/
Rule.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
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using Ara3D.Utils;
namespace Ara3D.Parakeet
{
/// <summary>
/// Base class of all rules. Matching is performed in a class's override
/// of MatchImplementation.
/// </summary>
public abstract class Rule
{
/// <summary>
/// Attempts to match the parser starting at current state. Returns null
/// if and only if the Rule fails. Otherwise returns a valid ParserState.
/// The ParserState may or may not be different from the previous one.
/// A ParserState is immutable: it never changes.
/// </summary>
protected abstract ParserState MatchImplementation(ParserState state);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ParserState Match(ParserState state)
{
#if DEBUG
// Trace the parsing during debug builds.
if (state.Input.Debugging && this.HasName())
{
Console.WriteLine($"Starting parse - {this.GetName()} {state}");
var r = MatchImplementation(state);
var result = r?.ToString() ?? "FAILED";
Console.WriteLine($"Finished parse - {this.GetName()} {state} - {result}");
return r;
}
#endif
return MatchImplementation(state);
}
public static SequenceRule operator +(Rule left, Rule right)
{
var list = new List<Rule>();
if (left is SequenceRule seq0)
list.AddRange(seq0.Rules);
else
list.Add(left);
if (right is SequenceRule seq1)
list.AddRange(seq1.Rules);
else
list.Add(right);
return new SequenceRule(list.ToArray());
}
public static ChoiceRule operator |(Rule left, Rule right)
{
var list = new List<Rule>();
if (left is ChoiceRule ch0)
list.AddRange(ch0.Rules);
else
list.Add(left);
if (right is ChoiceRule ch1)
list.AddRange(ch1.Rules);
else
list.Add(right);
return new ChoiceRule(list.ToArray());
}
public static NotAtRule operator !(Rule rule)
=> new NotAtRule(rule);
public static implicit operator Rule(string s)
=> s.Length == 1 ? (Rule)s[0] : new StringRule(s);
public static implicit operator Rule(char c)
=> new CharRule(c);
public static implicit operator Rule(int n)
=> new CharRule((char)n);
public static implicit operator Rule(bool b)
=> new BooleanRule(b);
public static implicit operator Rule(char[] cs)
=> cs.Length == 1 ? (Rule)cs[0] : new CharSetRule(cs);
public static implicit operator Rule(string[] strings)
=> strings.Length == 1 ? (Rule)strings[0] : new SequenceRule(strings.Select(s => (Rule)s).ToArray());
public static implicit operator Rule(Func<Rule> f)
=> new RecursiveRule(f);
public static bool operator ==(Rule r1, Rule r2)
=> ReferenceEquals(r1, r2) || (r1?.Equals(r2) ?? false);
public static bool operator !=(Rule r1, Rule r2)
=> !(r1 == r2);
public static int Hash(params object[] objects)
{
var hashCode = -1669597463;
foreach (var o in objects)
{
hashCode = hashCode * -1521134295 + o?.GetHashCode() ?? 0;
}
return hashCode;
}
public override bool Equals(object obj)
=> throw new NotImplementedException();
public override int GetHashCode()
=> throw new NotImplementedException();
public virtual IReadOnlyList<Rule> Children
=> Array.Empty<Rule>();
public override string ToString()
=> $"{this.GetName()} ::= {this.Body().ToDefinition()}";
}
/// <summary>
/// Associates a name with a rule, for the purpose of debugging and pretty-printing grammars.
/// Succeed if and only if the child rule succeeds.
/// Advances if and only if the child rule advances.
/// </summary>
public class NamedRule : Rule
{
public readonly Rule Rule;
public readonly string Name;
public NamedRule(Rule r, string name)
=> (Rule, Name) = (r, name);
protected override ParserState MatchImplementation(ParserState state)
=> Rule.Match(state);
public override bool Equals(object obj)
=> obj is NamedRule other && other.Rule.Equals(Rule) && Name == other.Name;
public override int GetHashCode()
=> Hash(Rule, Name);
public override IReadOnlyList<Rule> Children => new[] { Rule };
}
/// <summary>
/// Used to express recursive relationships between rules.
/// The child rule is retrieved via a function.
/// This is necessary to prevent infinite loops when parsing.
/// This rule matches iff the child rule matches.
/// Advances iff the child rule advances.
/// </summary>
public class RecursiveRule : Rule
{
public Rule Rule
{
get
{
if (CachedRule != null)
return CachedRule;
CachedRule = RuleFunc();
return CachedRule;
}
}
private Rule CachedRule { get; set; }
private Func<Rule> RuleFunc { get; }
public RecursiveRule(Func<Rule> ruleFunc)
=> RuleFunc = ruleFunc;
protected override ParserState MatchImplementation(ParserState state)
=> Rule.Match(state);
public override bool Equals(object obj)
=> obj is RecursiveRule other && other.RuleFunc == RuleFunc;
public override int GetHashCode()
=> Hash(RuleFunc);
}
/// <summary>
/// Matches a specific sequence of characters.
/// Advances the parser when successful.
/// </summary>
public class StringRule : Rule
{
public readonly string Pattern;
public StringRule(string s)
{
if (s.IsNullOrEmpty())
throw new ArgumentException("Pattern must be non-empty", nameof(s));
Pattern = s;
}
protected override ParserState MatchImplementation(ParserState state)
=> state.Match(Pattern);
public override bool Equals(object obj)
=> obj is StringRule smr && smr.Pattern == Pattern;
public override int GetHashCode()
=> Hash(Pattern);
}
/// <summary>
/// Matches a specific sequence of characters ignoring case.
/// Advances the parser when successful.
/// </summary>
public class CaseInvariantStringRule : Rule
{
public readonly string Pattern;
public CaseInvariantStringRule(string s)
{
if (s.IsNullOrEmpty())
throw new ArgumentException("Pattern must be non-empty", nameof(s));
Pattern = s;
}
protected override ParserState MatchImplementation(ParserState state)
=> state.MatchInvariant(Pattern);
public override bool Equals(object obj)
=> obj is CaseInvariantStringRule smr && smr.Pattern == Pattern;
public override int GetHashCode()
=> Hash(Pattern);
}
/// <summary>
/// Matches any character and advances the parser one character unless at the end of the input.
/// </summary>
public class AnyCharRule : Rule
{
protected override ParserState MatchImplementation(ParserState state)
=> state.AdvanceIfNotAtEnd();
public static AnyCharRule Default { get; }
= new AnyCharRule();
public override bool Equals(object obj)
=> obj is AnyCharRule;
public override int GetHashCode()
=> nameof(AnyCharRule).GetHashCode();
}
/// <summary>
/// Matches a character if it is within a specific character range (inclusive).
/// Advances the parser if successful.
/// </summary>
public class CharRangeRule : Rule
{
public readonly char From;
public readonly char To;
public CharRangeRule(char from, char to)
=> (From, To) = (from, to);
protected override ParserState MatchImplementation(ParserState state)
=> state.AdvanceIfWithin(From, To);
public override bool Equals(object obj)
=> obj is CharRangeRule crr && crr.From == From && crr.To == To;
public override int GetHashCode()
=> Hash(From, To);
}
/// <summary>
/// Matches a character if matches one of a set of ASCII characters.
/// Each character must be in the range of 0 to 128 (valid ASCII character set).
/// Uses a table lookup for performance.
/// Advances the parser if successful.
/// </summary>
public class CharSetRule : Rule
{
public static bool[] CharsToTable(IEnumerable<char> chars)
{
var r = new bool[128];
foreach (var c in chars)
{
if (c >= 128) throw new NotSupportedException();
r[c] = true;
}
return r;
}
public readonly bool[] Chars;
public CharSetRule(params char[] chars)
: this(CharsToTable(chars))
{ }
public CharSetRule(bool[] chars)
=> Chars = chars;
protected override ParserState MatchImplementation(ParserState state)
=> state.AtEnd() ? null
: state.GetCurrent() < 128 && Chars[state.GetCurrent()]
? state.Advance()
: null;
public override bool Equals(object obj)
=> obj is CharSetRule csr && Chars.SequenceEqual(csr.Chars);
public override int GetHashCode()
=> Hash(nameof(CharSetRule));
public CharSetRule Union(CharSetRule other)
{
var tmp = Chars.ToArray();
for (var i = 0; i < tmp.Length; i++)
{
if (other.Chars[i])
tmp[i] = true;
}
return new CharSetRule(tmp);
}
public CharSetRule Append(char other)
{
var tmp = Chars.ToArray();
tmp[other] = true;
return new CharSetRule(tmp);
}
public override string ToString()
{
var rangeCount = 0;
var sb = new StringBuilder();
for (var i = 0; i < Chars.Length; ++i)
{
var c = (char)i;
if (Chars[i])
{
rangeCount++;
if (rangeCount == 1)
{
sb.Append(c.EscapeChar());
}
}
else
{
if (i > 0)
{
var prevChar = (char)(i - 1);
if (rangeCount > 2)
{
sb.Append("-");
}
if (rangeCount > 1)
{
sb.Append(prevChar.EscapeChar());
}
}
rangeCount = 0;
}
}
return sb.ToString();
}
}
/// <summary>
/// Matches a specific character.
/// Advances the parser if successful.
/// </summary>
public class CharRule : Rule
{
public readonly char Char;
public CharRule(char ch)
=> Char = ch;
protected override ParserState MatchImplementation(ParserState state)
=> state.AdvanceIf(Char);
public override bool Equals(object obj)
=> obj is CharRule csr && Char == csr.Char;
public override int GetHashCode()
=> Hash(Char);
}
/// <summary>
/// Succeeds iff the parser is at the end of input.
/// Does not advance the parser.
/// </summary>
public class EndOfInputRule : Rule
{
protected override ParserState MatchImplementation(ParserState state)
=> state.AtEnd() ? state : null;
public static EndOfInputRule Default
=> new EndOfInputRule();
public override bool Equals(object obj)
=> obj is EndOfInputRule;
public override int GetHashCode()
=> nameof(EndOfInputRule).GetHashCode();
}
/// <summary>
/// When the child rule matches, it creates a new parse node in the node list.
/// Succeeds iff the child rule is successful.
/// Advances iff the child rules is successful.
/// </summary>
public class NodeRule : NamedRule
{
public NodeRule(Rule rule, string name)
: base(rule, name)
{ }
protected override ParserState MatchImplementation(ParserState state)
=> Rule.Match(state.AddNode(Name, null))?.AddNode(Name, state);
public override bool Equals(object obj)
=> obj is NodeRule nr && Name == nr.Name && Rule.Equals(nr.Rule);
public override int GetHashCode()
=> Hash(Rule, Name);
}
/// <summary>
/// Attempts to match a child rule as many times as possible.
/// Advances if the child rule advances.
/// Child rule must advance, otherwise the parser can get stuck.
/// </summary>
public class ZeroOrMoreRule : Rule
{
public readonly Rule Rule;
public ZeroOrMoreRule(Rule rule) => Rule = rule;
protected override ParserState MatchImplementation(ParserState state)
{
var curr = state;
var next = Rule.Match(curr);
while (next != null)
{
curr = next;
next = Rule.Match(curr);
#if DEBUG
if (next != null)
{
if (next.Position <= curr.Position)
{
throw new ParserException(curr, "Parser is no longer making progress");
}
}
#endif
}
return curr;
}
public override bool Equals(object obj)
=> obj is ZeroOrMoreRule z && z.Rule.Equals(Rule);
public override int GetHashCode()
=> Hash (Rule);
public override IReadOnlyList<Rule> Children => new[] { Rule };
}
/// <summary>
/// Succeeds if the child rule matches at least once
/// </summary>
public class OneOrMoreRule : Rule
{
public readonly Rule Rule;
public OneOrMoreRule(Rule rule) => Rule = rule;
protected override ParserState MatchImplementation(ParserState state)
{
var curr = state;
var next = Rule.Match(curr);
if (next == null)
{
return null;
}
while (next != null)
{
curr = next;
next = Rule.Match(curr);
#if DEBUG
if (next != null)
{
if (next.Position <= curr.Position)
{
throw new ParserException(curr, "Parser is no longer making progress");
}
}
#endif
}
return curr;
}
public override bool Equals(object obj)
=> obj is OneOrMoreRule o && o.Rule.Equals(Rule);
public override int GetHashCode()
=> Hash(Rule);
public override IReadOnlyList<Rule> Children => new[] { Rule };
}
/// <summary>
/// Succeeds if the child rule matches at least "Min" times.
/// Attempts to match the child rule up to "Max" times.
/// Always advances (the child rule must advance).
/// </summary>
public class CountedRule : Rule
{
public readonly int Min;
public readonly int Max;
public readonly Rule Rule;
public CountedRule(Rule rule, int min, int max)
=> (Rule, Min, Max) = (rule, min, max);
protected override ParserState MatchImplementation(ParserState state)
{
var curr = state;
var i = 0;
while (i++ < Min)
{
var next = Rule.Match(curr);
if (next == null)
return null;
curr = next;
}
while (curr != null && i++ < Max)
{
var next = Rule.Match(curr);
#if DEBUG
if (next != null)
{
if (next.Position <= curr.Position)
{
throw new ParserException(curr, "Parser is no longer making progress");
}
}
#endif
if (next == null)
return curr;
curr = next;
}
return curr;
}
public override bool Equals(object obj)
=> obj is CountedRule o && o.Rule.Equals(Rule);
public override int GetHashCode()
=> Hash(Rule);
public override IReadOnlyList<Rule> Children
=> new[] { Rule };
}
/// <summary>
/// Always succeeds.
/// Advances if the child rule advances.
/// </summary>
public class OptionalRule : Rule
{
public readonly Rule Rule;
public OptionalRule(Rule rule)
=> Rule = rule;
protected override ParserState MatchImplementation(ParserState state)
=> Rule.Match(state) ?? state;
public override bool Equals(object obj)
=> obj is OptionalRule opt && opt.Rule.Equals(Rule);
public override int GetHashCode()
=> Hash(Rule);
public override IReadOnlyList<Rule> Children => new[] { Rule };
}
/// <summary>
/// Succeeds only if each of the sequence of rules advances.
/// Advances if all of the rules advance.
/// </summary>
public class SequenceRule : Rule
{
public readonly Rule[] Rules;
public SequenceRule(params Rule[] rules)
{
Rules = rules;
if (Rules.Any(r => r == null))
throw new Exception("One of the rules is null");
}
public int Count
=> Rules.Length;
public Rule this[int index]
=> Rules[index];
protected override ParserState MatchImplementation(ParserState state)
{
var newState = state;
OnFail onFail = null;
foreach (var rule in Rules)
{
if (rule is OnFail)
{
onFail = (OnFail)rule;
}
else
{
var prevState = newState;
newState = rule.Match(prevState);
if (newState == null)
{
if (onFail != null)
{
var error = new ParserError(this, state, rule, prevState, prevState.LastError);
prevState = prevState.WithError(error);
var recovery = onFail.RecoveryRule;
var result = recovery.Match(prevState);
return result;
}
return null;
}
}
}
return newState;
}
public override bool Equals(object obj)
=> obj is SequenceRule seq && Rules.SequenceEqual(seq.Rules);
public override int GetHashCode()
=> Hash(Rules);
public override IReadOnlyList<Rule> Children => Rules;
}
/// <summary>
/// Succeeds if any of the child rules pass.
/// Advances if the passing child rule advances.
/// </summary>
public class ChoiceRule : Rule
{
public readonly Rule[] Rules;
public ChoiceRule(params Rule[] rules)
=> Rules = rules;
public int Count
=> Rules.Count();
public Rule this[int index]
=> Rules[index];
protected override ParserState MatchImplementation(ParserState state)
{
foreach (var rule in Rules)
{
var newState = rule.Match(state);
if (newState != null) return newState;
}
return null;
}
public override bool Equals(object obj)
=> obj is ChoiceRule ch && Rules.SequenceEqual(ch.Rules);
public override int GetHashCode()
=> Hash(Rules);
public override IReadOnlyList<Rule> Children => Rules;
}
/// <summary>
/// Succeed only if the rule matches.
/// Does not advance the parser state.
/// </summary>
public class AtRule : Rule
{
public readonly Rule Rule;
public AtRule(Rule rule)
=> Rule = rule;
protected override ParserState MatchImplementation(ParserState state)
=> Rule.Match(state) != null ? state : null;
public override bool Equals(object obj)
=> obj is AtRule at && Rule.Equals(at.Rule);
public override int GetHashCode()
=> Hash(Rule);
public override IReadOnlyList<Rule> Children => new[] { Rule };
}
/// <summary>
/// Succeed only if the rule does not match.
/// Does not advance the parser state.
/// </summary>
public class NotAtRule : Rule
{
public readonly Rule Rule;
public NotAtRule(Rule rule)
=> (Rule) = (rule);
protected override ParserState MatchImplementation(ParserState state)
=> Rule.Match(state) == null ? state : null;
public override bool Equals(object obj)
=> obj is NotAtRule notAt && Rule.Equals(notAt.Rule);
public override int GetHashCode()
=> Hash(Rule);
public override IReadOnlyList<Rule> Children => new[] { Rule };
}
/// <summary>
/// Used in sequences, to specify what happens if one of the subsequent nodes fails.
/// For example, in a statement you could advance to the end of statement terminator (';').
/// Or you could use results from a structural analysis pass to jump to next code block.
/// Does not advance parser state.
/// </summary>
public class OnFail : Rule
{
public readonly Rule RecoveryRule;
public OnFail(Rule rule)
=> RecoveryRule = rule;
protected override ParserState MatchImplementation(ParserState state)
=> state;
public override bool Equals(object obj)
=> obj is OnFail rec && RecoveryRule.Equals(rec.RecoveryRule);
public override int GetHashCode()
=> Hash(RecoveryRule);
}
/// <summary>
/// Either always succeeds or fails regardless of parser state.
/// Does not advance parser state.
/// </summary>
public class BooleanRule : Rule
{
public readonly bool Value;
public BooleanRule(bool b)
=> Value = b;
protected override ParserState MatchImplementation(ParserState state)
=> Value ? state : null;
public override bool Equals(object obj)
=> obj is BooleanRule br && br.Value == Value;
public override int GetHashCode()
=> Hash(Value);
}
}