/
Lexer.cs
716 lines (655 loc) · 32.5 KB
/
Lexer.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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using static TestLanguage.Terminal;
namespace TestLanguage
{
public partial class Grammar
{
public override LexerBase GetLexer(TextReader reader)
{
return new Lexer(reader);
}
public class Lexer : LexerBase
{
public static Dictionary<string, Terminal> ReservedWords { get; }
= new Dictionary<string, Terminal>
{
{ "asm", Asm }, { "naked", Naked }, { "null", Null }, { "true", True }, { "false", False },
{ "const", Const }, { "object", Terminal.Object }, { "void", Terminal.Void }, { "byte", Terminal.Byte },
{ "bool", Bool }, { "char", Terminal.Char }, { "string", Terminal.String }, { "short", Short },
{ "int", Int }, { "uint", UInt }, { "long", Long }, { "ulong", ULong }, { "float", Float },
{ "double", Terminal.Double }, { "decimal", Terminal.Decimal }, { "using", Using },
{ "namespace", Namespace }, { "public", Public }, { "private", Private }, { "protected", Protected },
{ "static", Static }, { "class", Class }, { "struct", Struct }, { "for", For }, { "while", While },
{ "do", Do }, { "foreach", ForEach }, { "break", Break }, { "continue", Continue }, { "switch", Switch },
{ "default", Default }, { "case", Case }, { "try", Try }, { "catch", Catch }, { "finally", Finally },
{ "throw", Throw }, { "new", New }, { "typeof", Typeof }, { "goto", Goto }, { "return", Return },
{ "virtual", Virtual }, { "interface", Interface }, { "delegate", Terminal.Delegate },
{ "if", If }, { "else", Else }, { "enum", Terminal.Enum }, { "lock", Lock }, { "var", Var },
{ "internal", Internal }, { "abstract", Abstract }
};
public Lexer(TextReader reader) : base(reader) { }
int startline;
int startcol;
int line;
int col;
StringBuilder lexemeBuilder = new StringBuilder();
char read()
{
if (Reader.HasNext())
{
col++;
var c = Reader.Read();
lexemeBuilder.Append(c);
return c;
}
return '\xFFFF';
}
protected override IEnumerable<Token> Lex()
{
return LexWithoutTrivia();
}
private IEnumerable<Token> LexWithoutTrivia()
{
return LexAll().Where(t =>
t.Terminal != Whitespace &&
t.Terminal != Comment
);
}
private IEnumerable<Token> LexAll()
{
line = 1;
col = 1;
// Scan away until there are no characters in the stream!
while (Reader.HasNext())
{
// Set up specific information for this token
startline = line;
startcol = col;
lexemeBuilder.Clear();
Func<Terminal, Token> makeToken = t => new Token(t, lexemeBuilder.ToString());
// Scan whitespace
while (char.IsWhiteSpace(Reader.Peek()))
{
if (!HandleNewline())
{
read();
}
}
if (lexemeBuilder.Length > 0)
{
yield return makeToken(Whitespace);
continue;
}
// Scan division and comments.
if (Reader.Peek() == '/')
{
read();
switch (Reader.Peek())
{
// Single-line comment
case '/':
while (Reader.HasNext() && Reader.Peek() != '\r' && Reader.Peek() != '\n')
{
read();
}
yield return new CommentToken(lexemeBuilder.ToString());
break;
// Multiline comment
case '*':
read();
bool commentClosed = false;
while (Reader.HasNext())
{
HandleNewline();
// Make sure we didn't reach the end of the stream.
if (!Reader.HasNext())
break;
// Scan through and try to find the end of the comment.
var lastc = read();
if (lastc == '*' && Reader.HasNext())
{
if (Reader.Peek() == '/')
{
commentClosed = true;
read();
break;
}
}
}
yield return new CommentToken
(
lexemeBuilder.ToString(),
isMultiline: true,
isClosedProperly: commentClosed
);
break;
// Division assignment
case '=':
read();
yield return makeToken(DivisionAssignment);
break;
// Division
default:
yield return makeToken(Divide);
break;
}
// Scan the next token.
continue;
}
// Recognize identifiers and strings starting with an @ symbol (verbatim specifier).
var verbatim = ('@' == Reader.Peek());
if (verbatim)
{
// Swallow it up
read();
// Make sure it precedes a string or identifier. If not, return our invalid "Verbatim" token.
if (!((Reader.Peek() >= 'a' && Reader.Peek() <= 'z') ||
(Reader.Peek() >= 'A' && Reader.Peek() <= 'Z') ||
Reader.Peek() == '_' ||
Reader.Peek() == '\"'))
{
yield return makeToken(Terminal.Unknown);
continue;
}
}
// Does it start an identifier?
if ((Reader.Peek() >= 'a' && Reader.Peek() <= 'z') || (Reader.Peek() >= 'A' && Reader.Peek() <= 'Z') || Reader.Peek() == '_')
{
var nameBuilder = new StringBuilder();
// Scan it up!
do
{
nameBuilder.Append(read());
}
while (Reader.HasNext() && ((Reader.Peek() >= 'a' && Reader.Peek() <= 'z') || (Reader.Peek() >= 'A' && Reader.Peek() <= 'Z') || (Reader.Peek() >= '0' && Reader.Peek() <= '9') || Reader.Peek() == '_'));
if (verbatim)
{
yield return new IdentifierToken(nameBuilder.ToString(), lexemeBuilder.ToString());
}
else
{
Terminal keyword;
var name = nameBuilder.ToString();
if (!ReservedWords.TryGetValue(name, out keyword))
yield return new IdentifierToken(name);
else
yield return makeToken(keyword);
}
}
// Does it start a number then? (Or is it a dot?)
else if ((Reader.Peek() >= '0' && Reader.Peek() <= '9') || Reader.Peek() == '.')
{
// The type suffix of the number
char typeSuffix = (char)0;
bool fraction = false; // Is this number a floating point number? (Are we ready to start scanning the fractional part?)
bool unsigned = false;
bool typeSpecified = false;
if (Reader.Peek() == '.')
{
read();
// If the next character is not a number, then we just have a dot.
if (Reader.HasNext() || !(Reader.Peek() >= '0' && Reader.Peek() <= '9'))
{
yield return makeToken(Dot);
continue; // Begin scanning the next token.
}
// This is a floating point number; make sure we start by scanning the fractional part.
fraction = true;
}
// Create string builders to keep track of the numeric part of the number.
StringBuilder numberPart = new StringBuilder();
// Now, see if we have a hexadecimal number.
if (!fraction && Reader.Peek() == '0')
{
read();
// See if the next character is an 'x'.
if (Reader.Peek() == 'x' || Reader.Peek() == 'X')
{
read();
// Now, scan all the hexadeximal digits.
while (Reader.HasNext() && ((Reader.Peek() >= '0' && Reader.Peek() <= '9') || (Reader.Peek() >= 'A' && Reader.Peek() <= 'F') || (Reader.Peek() >= 'a' && Reader.Peek() <= 'f')))
{
numberPart.Append(read());
}
// See if it is a type suffix. We can have U, L, UL, or LU (ignoring case). c holds the next character.
for (int i = 0; i < 2; i++)
{
if (!unsigned && (Reader.Peek() == 'u' || Reader.Peek() == 'U'))
{
read();
unsigned = true; // We don't allow "UU"
}
else if (!typeSpecified && (Reader.Peek() == 'l' || Reader.Peek() == 'L'))
{
typeSpecified = true; // We won't allow "LL"
typeSuffix = read();
}
else
{
break;
}
}
// Return the new hexadecimal token.
yield return new NumberToken
(
lexemeBuilder.ToString(),
numberPart: numberPart.ToString(),
isHexadecimal: true,
isFloating: false,
isUnsigned: unsigned,
typeSuffix: typeSuffix,
isTypeSpecified: typeSpecified
);
continue;
}
// If this is not a hexadecimal number but it just starts with 0, scan the rest of the integer part of the number.
// Add the '0' to the number part because this is not a hexadecimal number.
numberPart.Append('0');
while (Reader.HasNext() && (Reader.Peek() >= '0' && Reader.Peek() <= '9'))
{
numberPart.Append(read());
}
}
// Scan the integer part of the number if we are not yet ready to scan the fractional part.
if (!fraction)
{
while (Reader.HasNext() && (Reader.Peek() >= '0' && Reader.Peek() <= '9'))
{
numberPart.Append(read());
}
}
// Signal the OK to scan the fractional part
if (Reader.Peek() == '.')
{
fraction = true;
}
if (fraction)
{
// Yay! We can finally scan the fractional part now.
// Add the dot to our number.
numberPart.Append(read());
// Scan the fractional part.
while (Reader.HasNext() && (Reader.Peek() >= '0' && Reader.Peek() <= '9'))
{
numberPart.Append(read());
}
}
// try to scan the exponent.
if (Reader.Peek() == 'e' || Reader.Peek() == 'E')
{
fraction = true;
numberPart.Append(read());
if (Reader.Peek() == '+' || Reader.Peek() == '-')
{
numberPart.Append(read());
}
while (Reader.HasNext() && (Reader.Peek() >= '0' && Reader.Peek() <= '9'))
{
numberPart.Append(read());
}
}
// Get number suffixes
var lowerc = char.ToLowerInvariant(Reader.Peek());
if (lowerc == 'f' || lowerc == 'd' || lowerc == 'm')
{
typeSpecified = true;
typeSuffix = read();
fraction = true;
}
if (!fraction)
{
// See if it is a type suffix. We can have U, L, UL, or LU (ignoring case). c holds the next character.
for (int i = 0; i < 2; i++)
{
if (!unsigned && (Reader.Peek() == 'u' || Reader.Peek() == 'U'))
{
read();
unsigned = true; // We don't allow "UU"
}
else if (!typeSpecified && (Reader.Peek() == 'l' || Reader.Peek() == 'L'))
{
typeSpecified = true; // We won't allow "LL"
typeSuffix = read();
}
else
{
break;
}
}
}
// Return the token
if (fraction)
{
yield return new NumberToken
(
lexemeBuilder.ToString(),
numberPart: numberPart.ToString(),
isFloating: true,
isTypeSpecified: typeSpecified,
typeSuffix: typeSuffix
);
}
else
{
yield return new NumberToken
(
lexemeBuilder.ToString(),
numberPart: numberPart.ToString(),
isTypeSpecified: typeSpecified,
typeSuffix: typeSuffix,
isUnsigned: unsigned
);
}
}
// Single characters
else if (Reader.Peek() == '\'' || Reader.Peek() == '\"')
{
bool terminated = false;
bool errors = false;
var terminator = read();
StringBuilder str = new StringBuilder();
while (Reader.HasNext() && Reader.Peek() != terminator && (verbatim || (Reader.Peek() != '\r' && Reader.Peek() != '\n')))
{
if (verbatim)
{
if (Reader.Peek() == '\r' || Reader.Peek() == '\n')
{
// Handle \r\n correctly by counting it as a single line ending.
var cr = ('\r' == Reader.Peek());
str.Append(read());
if (cr && (Reader.Peek() == '\n'))
{
str.Append(read());
}
line++;
col = 1;
}
else
{
str.Append(read());
}
}
else
{
if (Reader.Peek() == '\\')
{
read();
if (!Reader.HasNext())
errors = true;
else
{
var c = read();
switch (c)
{
case '\\':
str.Append('\\');
break;
case '\"':
str.Append('\"');
break;
case '\'':
str.Append('\'');
break;
case '\0':
str.Append('\0');
break;
case 'r':
str.Append('\r');
break;
case 'n':
str.Append('\n');
break;
case 'x':
case 'u':
case 'U':
StringBuilder hex = new StringBuilder();
while (Reader.HasNext() && ((Reader.Peek() >= '0' && Reader.Peek() <= '9') || (Reader.Peek() >= 'A' && Reader.Peek() <= 'F') || (Reader.Peek() >= 'a' && Reader.Peek() <= 'f')))
{
hex.Append(read());
if (hex.Length == 8 || (c == 'u' && hex.Length == 4))
break;
}
if (hex.Length == 0 || (c == 'u' && hex.Length != 4) || (c == 'U' && hex.Length != 8))
{
errors = true;
}
else
{
int val;
if (int.TryParse(hex.ToString(), NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out val))
{
try
{
str.Append(char.ConvertFromUtf32(val));
}
catch
{
errors = true;
}
}
else
errors = true;
}
break;
case 'a':
str.Append('\a');
break;
case 'b':
str.Append('\b');
break;
case 't':
str.Append('\t');
break;
case 'f':
str.Append('\f');
break;
case 'v':
str.Append('\v');
break;
default:
errors = true;
break;
}
}
}
else
{
str.Append(read());
}
}
}
if (Reader.Peek() == terminator)
{
terminated = true;
read();
}
if (terminator == '\"')
{
yield return new StringLiteralToken
(
str.ToString(),
lexemeBuilder.ToString(),
isTerminated: terminated,
isWellFormed: !errors
);
}
else
{
yield return new CharLiteralToken
(
str.ToString(),
lexemeBuilder.ToString(),
isTerminated: terminated,
isWellFormed: !errors
);
}
}
// Characters that could also have an = sign (or possibly repeat)
else if (
Reader.Peek() == '!' ||
Reader.Peek() == '%' ||
Reader.Peek() == '*' ||
Reader.Peek() == '^' ||
Reader.Peek() == '&' ||
Reader.Peek() == '|' ||
Reader.Peek() == '+' ||
Reader.Peek() == '-' ||
Reader.Peek() == '=' ||
Reader.Peek() == '<' ||
Reader.Peek() == '>')
{
var c = read();
var doubled = false;
var equalsSign = false;
// All the characters that can be doubled
if (
c == '&' ||
c == '|' ||
c == '+' ||
c == '-' ||
c == '=' ||
c == '<' /*||
c == '>'*/)
{
if (c == Reader.Peek())
{
read();
doubled = true;
}
if (Reader.Peek() == '=' && ((c == '<') /*|| (c == '>')*/))
{
read();
//if (c == '<')
yield return makeToken(ShiftLeftAssignment);
//else
// yield return makeToken(ShiftRightAssignment);
continue;
}
}
// See if an equals sign follows
if (!doubled && (Reader.Peek() == '='))
{
equalsSign = true;
read();
}
// output the correct token
switch (c)
{
case '&':
yield return makeToken(doubled ? LogicalAnd : equalsSign ? AndAssignment : BitwiseAnd);
break;
case '|':
yield return makeToken(doubled ? LogicalOr : equalsSign ? OrAssignment : BitwiseOr);
break;
case '+':
yield return makeToken(doubled ? Increment : equalsSign ? AdditionAssignment : Add);
break;
case '-':
yield return makeToken(doubled ? Decrement : equalsSign ? SubtractionAssignment : Subtract);
break;
case '=':
yield return makeToken(doubled ? Equality : equalsSign ? Equality : Assignment);
break;
case '<':
yield return makeToken(doubled ? ShiftLeft : equalsSign ? LessThanOrEqual : LessThan);
break;
case '>':
yield return makeToken(equalsSign ? GreaterThanOrEqual : GreaterThan);
break;
case '!':
yield return makeToken(equalsSign ? NotEqual : Not);
break;
case '%':
yield return makeToken(equalsSign ? ModAssignment : Mod);
break;
case '*':
yield return makeToken(equalsSign ? MultiplicationAssignment : Multiply);
break;
case '^':
yield return makeToken(equalsSign ? XorAssignment : BitwiseXor);
break;
}
}
// End-of-file
else if (!Reader.HasNext())
{
yield return new Token(Terminal.Eof);
yield break; // That's it
}
// All other single characters
else
{
var c = read();
switch (c)
{
case '~':
yield return makeToken(BitwiseNegate);
break;
case '(':
yield return makeToken(LeftParenthesis);
break;
case ')':
yield return makeToken(RightParenthesis);
break;
case '>':
yield return makeToken(GreaterThan);
break;
case '{':
yield return makeToken(LeftCurlyBrace);
break;
case '}':
yield return makeToken(RightCurlyBrace);
break;
case '[':
yield return makeToken(LeftSquareBracket);
break;
case ']':
yield return makeToken(RightSquareBracket);
break;
case ':':
yield return makeToken(Colon);
break;
case ';':
yield return makeToken(Semicolon);
break;
case ',':
yield return makeToken(Comma);
break;
case '?':
yield return makeToken(QuestionMark);
break;
default:
yield return makeToken(Terminal.Unknown);
break;
}
}
}
yield return new Token(Terminal.Eof);
}
private bool HandleNewline()
{
bool newline = false;
// Handle newlines properly.
if (Reader.Peek() == '\r' || Reader.Peek() == '\n')
{
newline = true;
// Handle \r\n correctly by counting it as a single line ending.
var cr = ('\r' == Reader.Peek());
read();
if (cr && (Reader.Peek() == '\n'))
{
read();
}
line++;
col = 1;
}
return newline;
}
}
}
}