-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPegGrammar.cs
More file actions
643 lines (546 loc) · 18.2 KB
/
Copy pathPegGrammar.cs
File metadata and controls
643 lines (546 loc) · 18.2 KB
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
using DotPython.Language.Syntax;
namespace DotPython.ParserGenerator.Generation;
internal sealed class PegGrammar
{
private static readonly HashSet<string> ReservedKeywords =
[
"False",
"None",
"True",
"and",
"as",
"assert",
"async",
"await",
"break",
"class",
"continue",
"def",
"del",
"elif",
"else",
"except",
"finally",
"for",
"from",
"global",
"if",
"import",
"in",
"is",
"lambda",
"nonlocal",
"not",
"or",
"pass",
"raise",
"return",
"try",
"while",
"with",
"yield",
];
private readonly Dictionary<string, PegExpression> _rules;
private PegGrammar(Dictionary<string, PegExpression> rules)
{
_rules = rules;
}
internal int RuleCount => _rules.Count;
internal static PegGrammar Parse(string source)
{
ArgumentNullException.ThrowIfNull(source);
var rules = new Dictionary<string, PegExpression>(StringComparer.Ordinal);
foreach (var line in NormalizeRuleSource(source).Split('\n'))
{
if (line.Length == 0)
{
continue;
}
var colonIndex = line.IndexOf(':', StringComparison.Ordinal);
if (colonIndex <= 0)
{
throw new InvalidDataException($"Invalid PEG rule: '{line}'.");
}
var name = line[..colonIndex].Trim();
if (!IsIdentifier(name))
{
throw new InvalidDataException($"Invalid PEG rule name '{name}'.");
}
var expression = new ExpressionParser(line[(colonIndex + 1)..]).Parse();
if (!rules.TryAdd(name, expression))
{
throw new InvalidDataException($"Duplicate PEG rule '{name}'.");
}
}
if (!rules.ContainsKey("file"))
{
throw new InvalidDataException("The PEG grammar must define a 'file' rule.");
}
ValidateReferences(rules);
return new PegGrammar(rules);
}
internal static string NormalizeRuleSource(string source)
{
ArgumentNullException.ThrowIfNull(source);
var lines = source
.ReplaceLineEndings("\n")
.Split('\n')
.Select(line => RemoveComment(line).Trim())
.Where(line => line.Length != 0);
return string.Join('\n', lines);
}
internal PegMatchResult Match(SyntaxToken[] tokens)
{
ArgumentNullException.ThrowIfNull(tokens);
var matcher = new Matcher(_rules, tokens);
var position = 0;
var success = matcher.MatchRule("file", ref position) && position == tokens.Length;
return new PegMatchResult(success, matcher.FurthestPosition);
}
private static void ValidateReferences(IReadOnlyDictionary<string, PegExpression> rules)
{
foreach (var (ruleName, expression) in rules)
{
foreach (var reference in EnumerateReferences(expression))
{
if (!IsTokenName(reference) && !rules.ContainsKey(reference))
{
throw new InvalidDataException(
$"PEG rule '{ruleName}' references unknown rule or token '{reference}'."
);
}
}
}
}
private static IEnumerable<string> EnumerateReferences(PegExpression expression)
{
switch (expression)
{
case PegName name:
yield return name.Value;
break;
case PegSequence sequence:
foreach (var item in sequence.Items)
{
foreach (var reference in EnumerateReferences(item))
{
yield return reference;
}
}
break;
case PegChoice choice:
foreach (var alternative in choice.Alternatives)
{
foreach (var reference in EnumerateReferences(alternative))
{
yield return reference;
}
}
break;
case PegOptional optional:
foreach (var reference in EnumerateReferences(optional.Expression))
{
yield return reference;
}
break;
case PegRepeat repeat:
foreach (var reference in EnumerateReferences(repeat.Expression))
{
yield return reference;
}
break;
case PegGather gather:
foreach (var reference in EnumerateReferences(gather.Separator))
{
yield return reference;
}
foreach (var reference in EnumerateReferences(gather.Expression))
{
yield return reference;
}
break;
}
}
private static bool IsTokenName(string value) =>
value is "NAME" or "NUMBER" or "STRING" or "NEWLINE" or "INDENT" or "DEDENT" or "ENDMARKER";
private static bool IsIdentifier(string value)
{
if (value.Length == 0 || !(char.IsAsciiLetter(value[0]) || value[0] == '_'))
{
return false;
}
for (var index = 1; index < value.Length; index++)
{
if (!(char.IsAsciiLetterOrDigit(value[index]) || value[index] == '_'))
{
return false;
}
}
return true;
}
private static string RemoveComment(string line)
{
var quote = '\0';
for (var index = 0; index < line.Length; index++)
{
var character = line[index];
if (quote != '\0')
{
if (character == '\\')
{
index++;
}
else if (character == quote)
{
quote = '\0';
}
continue;
}
if (character is '\'' or '"')
{
quote = character;
}
else if (character == '#')
{
return line[..index];
}
}
return line;
}
private sealed class Matcher(
IReadOnlyDictionary<string, PegExpression> rules,
SyntaxToken[] tokens
)
{
private readonly Dictionary<(string Name, int Position), MemoizedMatch> _memoized = [];
private readonly HashSet<(string Name, int Position)> _pending = [];
internal int FurthestPosition { get; private set; }
internal bool MatchRule(string name, ref int position)
{
var start = position;
var key = (name, start);
if (_memoized.TryGetValue(key, out var memoized))
{
position = memoized.EndPosition;
return memoized.Success;
}
if (!_pending.Add(key))
{
throw new InvalidDataException(
$"Left recursion in PEG rule '{name}' is not supported yet."
);
}
var success = MatchExpression(rules[name], ref position);
_pending.Remove(key);
if (!success)
{
position = start;
}
_memoized.Add(key, new MemoizedMatch(success, position));
return success;
}
private bool MatchExpression(PegExpression expression, ref int position)
{
FurthestPosition = Math.Max(FurthestPosition, position);
switch (expression)
{
case PegLiteral literal:
return MatchLiteral(literal.Value, ref position);
case PegName name:
return MatchName(name.Value, ref position);
case PegSequence sequence:
return MatchSequence(sequence, ref position);
case PegChoice choice:
return MatchChoice(choice, ref position);
case PegOptional optional:
MatchExpression(optional.Expression, ref position);
return true;
case PegRepeat repeat:
return MatchRepeat(repeat, ref position);
case PegGather gather:
return MatchGather(gather, ref position);
default:
throw new InvalidOperationException(
$"Unknown PEG expression '{expression.GetType().Name}'."
);
}
}
private bool MatchLiteral(string value, ref int position)
{
if (
position >= tokens.Length
|| !string.Equals(tokens[position].Text, value, StringComparison.Ordinal)
)
{
return false;
}
position++;
return true;
}
private bool MatchName(string name, ref int position)
{
if (!IsTokenName(name))
{
return MatchRule(name, ref position);
}
if (position >= tokens.Length || !MatchesToken(name, tokens[position]))
{
return false;
}
position++;
return true;
}
private bool MatchSequence(PegSequence sequence, ref int position)
{
var start = position;
foreach (var item in sequence.Items)
{
if (!MatchExpression(item, ref position))
{
position = start;
return false;
}
}
return true;
}
private bool MatchChoice(PegChoice choice, ref int position)
{
foreach (var alternative in choice.Alternatives)
{
var start = position;
if (MatchExpression(alternative, ref position))
{
return true;
}
position = start;
}
return false;
}
private bool MatchRepeat(PegRepeat repeat, ref int position)
{
var matches = 0;
while (true)
{
var start = position;
if (!MatchExpression(repeat.Expression, ref position))
{
position = start;
break;
}
if (position == start)
{
throw new InvalidDataException("A repeated PEG expression matched no input.");
}
matches++;
}
return matches >= repeat.Minimum;
}
private bool MatchGather(PegGather gather, ref int position)
{
var start = position;
if (!MatchExpression(gather.Expression, ref position))
{
position = start;
return false;
}
while (true)
{
var separatorStart = position;
if (
!MatchExpression(gather.Separator, ref position)
|| !MatchExpression(gather.Expression, ref position)
)
{
position = separatorStart;
break;
}
}
return true;
}
private static bool MatchesToken(string name, SyntaxToken token) =>
name switch
{
"NAME" => token.Kind == SyntaxTokenKind.Identifier
&& !ReservedKeywords.Contains(token.Text),
"NUMBER" => token.Kind
is SyntaxTokenKind.IntegerLiteral
or SyntaxTokenKind.FloatLiteral
or SyntaxTokenKind.ImaginaryLiteral,
"STRING" => token.Kind
is SyntaxTokenKind.StringLiteral
or SyntaxTokenKind.BytesLiteral
or SyntaxTokenKind.FormattedStringLiteral
or SyntaxTokenKind.TemplateStringLiteral,
"NEWLINE" => token.Kind == SyntaxTokenKind.NewLine,
"INDENT" => token.Kind == SyntaxTokenKind.Indent,
"DEDENT" => token.Kind == SyntaxTokenKind.Dedent,
"ENDMARKER" => token.Kind == SyntaxTokenKind.EndOfFile,
_ => false,
};
private readonly record struct MemoizedMatch(bool Success, int EndPosition);
}
private sealed class ExpressionParser(string source)
{
private int _position;
internal PegExpression Parse()
{
var expression = ParseChoice();
SkipWhitespace();
if (_position != source.Length)
{
throw Error($"Unexpected character '{source[_position]}'.");
}
return expression;
}
private PegExpression ParseChoice()
{
var alternatives = new List<PegExpression> { ParseSequence() };
while (Match('|'))
{
alternatives.Add(ParseSequence());
}
return alternatives.Count == 1
? alternatives[0]
: new PegChoice(alternatives.ToArray());
}
private PegExpression ParseSequence()
{
var items = new List<PegExpression>();
while (CanStartPrimary())
{
items.Add(ParseItem());
}
return items.Count switch
{
0 => throw Error("Expected a PEG expression."),
1 => items[0],
_ => new PegSequence(items.ToArray()),
};
}
private PegExpression ParseItem()
{
var expression = ParsePrimary();
if (Match('.'))
{
var item = ParsePrimary();
if (!Match('+'))
{
throw Error("A PEG gather must end with '+'.");
}
return new PegGather(expression, item);
}
if (Match('*'))
{
return new PegRepeat(expression, 0);
}
return Match('+') ? new PegRepeat(expression, 1) : expression;
}
private PegExpression ParsePrimary()
{
SkipWhitespace();
if (_position >= source.Length)
{
throw Error("Expected a PEG primary expression.");
}
if (Match('['))
{
var expression = ParseChoice();
Expect(']');
return new PegOptional(expression);
}
if (Match('('))
{
var expression = ParseChoice();
Expect(')');
return expression;
}
if (source[_position] is '\'' or '"')
{
return new PegLiteral(ParseString());
}
return new PegName(ParseIdentifier());
}
private string ParseIdentifier()
{
SkipWhitespace();
var start = _position;
while (
_position < source.Length
&& (char.IsAsciiLetterOrDigit(source[_position]) || source[_position] == '_')
)
{
_position++;
}
var value = source[start.._position];
if (!IsIdentifier(value))
{
throw Error("Expected a PEG identifier.");
}
return value;
}
private string ParseString()
{
var quote = source[_position++];
var builder = new System.Text.StringBuilder();
while (_position < source.Length)
{
var character = source[_position++];
if (character == quote)
{
return builder.ToString();
}
if (character == '\\')
{
if (_position == source.Length)
{
break;
}
character = source[_position++];
}
builder.Append(character);
}
throw Error("Unterminated PEG string literal.");
}
private bool CanStartPrimary()
{
SkipWhitespace();
return _position < source.Length && source[_position] is not ('|' or ')' or ']');
}
private bool Match(char character)
{
SkipWhitespace();
if (_position >= source.Length || source[_position] != character)
{
return false;
}
_position++;
return true;
}
private void Expect(char character)
{
if (!Match(character))
{
throw Error($"Expected '{character}'.");
}
}
private void SkipWhitespace()
{
while (_position < source.Length && char.IsWhiteSpace(source[_position]))
{
_position++;
}
}
private InvalidDataException Error(string message) =>
new($"{message} (column {_position + 1} in '{source}').");
}
private abstract record PegExpression;
private sealed record PegLiteral(string Value) : PegExpression;
private sealed record PegName(string Value) : PegExpression;
private sealed record PegSequence(PegExpression[] Items) : PegExpression;
private sealed record PegChoice(PegExpression[] Alternatives) : PegExpression;
private sealed record PegOptional(PegExpression Expression) : PegExpression;
private sealed record PegRepeat(PegExpression Expression, int Minimum) : PegExpression;
private sealed record PegGather(PegExpression Separator, PegExpression Expression)
: PegExpression;
}
internal readonly record struct PegMatchResult(bool Success, int FurthestTokenIndex);