forked from Azure/bicep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLexer.cs
1074 lines (921 loc) · 37.9 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
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using Bicep.Core.Diagnostics;
using Bicep.Core.Extensions;
using Bicep.Core.Syntax;
namespace Bicep.Core.Parsing
{
public class Lexer
{
// maps the escape character (that follows the backslash) to its value
private static readonly ImmutableSortedDictionary<char, char> SingleCharacterEscapes = new Dictionary<char, char>
{
{'n', '\n'},
{'r', '\r'},
{'t', '\t'},
{'\\', '\\'},
{'\'', '\''},
{'$', '$'}
}.ToImmutableSortedDictionary();
private static readonly ImmutableArray<string> CharacterEscapeSequences = SingleCharacterEscapes.Keys
.Select(c => $"\\{c}")
.Append("\\u{...}")
.ToImmutableArray();
private const int MultilineStringTerminatingQuoteCount = 3;
// the rules for parsing are slightly different if we are inside an interpolated string (for example, a new line should result in a lex error).
// to handle this, we use a modal lexing pattern with a stack to ensure we're applying the correct set of rules.
private readonly Stack<TokenType> templateStack = new();
private readonly IList<Token> tokens = new List<Token>();
private readonly IDiagnosticWriter diagnosticWriter;
private readonly SlidingTextWindow textWindow;
public Lexer(SlidingTextWindow textWindow, IDiagnosticWriter diagnosticWriter)
{
this.textWindow = textWindow;
this.diagnosticWriter = diagnosticWriter;
}
private void AddDiagnostic(TextSpan span, DiagnosticBuilder.ErrorBuilderDelegate diagnosticFunc)
{
var diagnostic = diagnosticFunc(DiagnosticBuilder.ForPosition(span));
this.diagnosticWriter.Write(diagnostic);
}
private void AddDiagnostic(DiagnosticBuilder.ErrorBuilderDelegate diagnosticFunc)
=> AddDiagnostic(textWindow.GetSpan(), diagnosticFunc);
public void Lex()
{
while (!textWindow.IsAtEnd())
{
LexToken();
}
// make sure we always include an end-of-line
if (!tokens.Any() || tokens.Last().Type != TokenType.EndOfFile)
{
LexToken();
}
}
public ImmutableArray<Token> GetTokens() => tokens.ToImmutableArray();
/// <summary>
/// Converts a set of string literal tokens into their raw values. Returns null if any of the tokens are of the wrong type or malformed.
/// </summary>
/// <param name="stringTokens">the string tokens</param>
public static IEnumerable<string>? TryGetRawStringSegments(IReadOnlyList<Token> stringTokens)
{
var segments = new string[stringTokens.Count];
for (var i = 0; i < stringTokens.Count; i++)
{
var nextSegment = Lexer.TryGetStringValue(stringTokens[i]);
if (nextSegment == null)
{
return null;
}
segments[i] = nextSegment;
}
return segments;
}
public static string? TryGetMultilineStringValue(Token stringToken)
{
var tokenText = stringToken.Text;
if (tokenText.Length < MultilineStringTerminatingQuoteCount * 2)
{
return null;
}
for (var i = 0; i < MultilineStringTerminatingQuoteCount; i++)
{
if (tokenText[i] != '\'')
{
return null;
}
}
for (var i = tokenText.Length - MultilineStringTerminatingQuoteCount; i < tokenText.Length; i++)
{
if (tokenText[i] != '\'')
{
return null;
}
}
var startOffset = MultilineStringTerminatingQuoteCount;
// we strip a leading \r\n or \n
if (tokenText[startOffset] == '\r')
{
startOffset++;
}
if (tokenText[startOffset] == '\n')
{
startOffset++;
}
return tokenText.Substring(startOffset, tokenText.Length - startOffset - MultilineStringTerminatingQuoteCount);
}
/// <summary>
/// Converts string literal text into its value. Returns null if the specified string token is malformed due to lexer error recovery.
/// </summary>
/// <param name="stringToken">the string token</param>
public static string? TryGetStringValue(Token stringToken)
{
var (start, end) = stringToken.Type switch
{
TokenType.StringComplete => (LanguageConstants.StringDelimiter, LanguageConstants.StringDelimiter),
TokenType.StringLeftPiece => (LanguageConstants.StringDelimiter, LanguageConstants.StringHoleOpen),
TokenType.StringMiddlePiece => (LanguageConstants.StringHoleClose, LanguageConstants.StringHoleOpen),
TokenType.StringRightPiece => (LanguageConstants.StringHoleClose, LanguageConstants.StringDelimiter),
_ => (null, null),
};
if (start == null || end == null)
{
return null;
}
if (stringToken.Text.Length < start.Length + end.Length ||
stringToken.Text.Substring(0, start.Length) != start ||
stringToken.Text.Substring(stringToken.Text.Length - end.Length) != end)
{
// any lexer-generated token should not hit this problem as the start & end are already verified
return null;
}
var contents = stringToken.Text.Substring(start.Length, stringToken.Text.Length - start.Length - end.Length);
var window = new SlidingTextWindow(contents);
// the value of the string will be shorter because escapes are longer than the characters they represent
var buffer = new StringBuilder(contents.Length);
while (!window.IsAtEnd())
{
var nextChar = window.Next();
if (nextChar == '\'')
{
return null;
}
if (nextChar == '\\')
{
// escape sequence begins
if (window.IsAtEnd())
{
return null;
}
char escapeChar = window.Next();
if (escapeChar == 'u')
{
// unicode escape
char openCurly = window.Next();
if (openCurly != '{')
{
return null;
}
var codePointText = ScanHexNumber(window);
if (!TryParseCodePoint(codePointText, out uint codePoint))
{
// invalid codepoint
return null;
}
char closeCurly = window.Next();
if (closeCurly != '}')
{
return null;
}
char charOrHighSurrogate = CodepointToString(codePoint, out char lowSurrogate);
buffer.Append(charOrHighSurrogate);
if (lowSurrogate != SlidingTextWindow.InvalidCharacter)
{
// previous char was a high surrogate
// also append the low surrogate
buffer.Append(lowSurrogate);
}
continue;
}
if (SingleCharacterEscapes.TryGetValue(escapeChar, out char escapeCharValue) == false)
{
// invalid escape character
return null;
}
buffer.Append(escapeCharValue);
// continue to next iteration
continue;
}
// regular string char - append to buffer
buffer.Append(nextChar);
}
return buffer.ToString();
}
private static bool TryParseCodePoint(string text, out uint codePoint) => uint.TryParse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint) && codePoint <= 0x10FFFF;
/// <summary>
/// Determines if the specified string is a valid identifier. To be considered a valid identifier, the string must start
/// with the identifier start character and remaining characters must be identifier continuation characters.
/// </summary>
/// <param name="value">The value</param>
public static bool IsValidIdentifier(string value)
{
if (value.Length <= 0)
{
return false;
}
var result = IsIdentifierStart(value[0]);
var index = 1;
while (result && index < value.Length)
{
result = result && IsIdentifierContinuation(value[index]);
index++;
}
return result;
}
private static char CodepointToString(uint codePoint, out char lowSurrogate)
{
if (codePoint < 0x00010000)
{
lowSurrogate = SlidingTextWindow.InvalidCharacter;
return (char)codePoint;
}
Debug.Assert(codePoint > 0x0000FFFF && codePoint <= 0x0010FFFF);
lowSurrogate = (char)((codePoint - 0x00010000) % 0x0400 + 0xDC00);
return (char)((codePoint - 0x00010000) / 0x0400 + 0xD800);
}
private IEnumerable<SyntaxTrivia> ScanTrailingTrivia(bool includeComments)
{
while (true)
{
var next = textWindow.Peek();
if (IsWhiteSpace(next))
{
yield return ScanWhitespace();
}
else if (includeComments && next == '/')
{
var nextNext = textWindow.Peek(1);
if (nextNext == '/')
{
yield return ScanSingleLineComment();
}
else if (nextNext == '*')
{
yield return ScanMultiLineComment();
}
else
{
yield break;
}
}
else
{
yield break;
}
}
}
private IEnumerable<SyntaxTrivia> ScanLeadingTrivia()
{
SyntaxTrivia? current = null;
while (true)
{
if (IsWhiteSpace(textWindow.Peek()))
{
current = ScanWhitespace();
}
else if (textWindow.Peek() == '/' && textWindow.Peek(1) == '/')
{
current = ScanSingleLineComment();
}
else if (textWindow.Peek() == '/' && textWindow.Peek(1) == '*')
{
current = ScanMultiLineComment();
}
else if (
(current is null || !current.IsComment()) &&
textWindow.Peek() == '#' &&
CheckAdjacentText(LanguageConstants.DisableNextLineDiagnosticsKeyword) &&
string.IsNullOrWhiteSpace(textWindow.GetTextBetweenLineStartAndCurrentPosition()))
{
current = ScanDisableNextLineDiagnosticsDirective();
}
else
{
yield break;
}
yield return current;
}
}
private SyntaxTrivia ScanDisableNextLineDiagnosticsDirective()
{
textWindow.Reset();
textWindow.Advance(LanguageConstants.DisableNextLineDiagnosticsKeyword.Length + 1); // Length of disable next statement plus #
var span = textWindow.GetSpan();
int start = span.Position;
int end = span.GetEndPosition();
var sb = new StringBuilder();
sb.Append(textWindow.GetText());
textWindow.Reset();
List<Token> codes = new();
while (!textWindow.IsAtEnd())
{
var nextChar = textWindow.Peek();
if (IsNewLine(nextChar))
{
break;
}
else if (IsIdentifierContinuation(nextChar) || nextChar == '-')
{
switch (textWindow.Peek(1))
{
case ' ':
case '\t':
case '\n':
case '\r':
case char.MaxValue:
textWindow.Advance();
if (GetToken() is { } token)
{
codes.Add(token);
end += token.Span.Length;
sb.Append(token.Text);
continue;
}
break;
default:
textWindow.Advance();
break;
}
}
else if (nextChar == ' ' || nextChar == '\t')
{
textWindow.Advance();
sb.Append(nextChar);
end++;
textWindow.Reset();
}
else
{
// Handle scenario where nextChar is not one of the following: identifier, '-', space, tab
// Eg: '|' in #disable-next-line BCP037|
if (GetToken() is { } token)
{
codes.Add(token);
end += token.Span.Length;
sb.Append(token.Text);
}
break;
}
}
if (codes.Count == 0)
{
AddDiagnostic(b => b.MissingDiagnosticCodes());
}
return GetDisableNextLineDiagnosticsSyntaxTrivia(codes, start, end, sb.ToString());
}
private bool CheckAdjacentText(string text)
{
for (int i = 0; i < text.Length; i++)
{
if (textWindow.Peek(i + 1) == text[i])
{
continue;
}
else
{
return false;
}
}
return true;
}
private DisableNextLineDiagnosticsSyntaxTrivia GetDisableNextLineDiagnosticsSyntaxTrivia(List<Token> codes, int start, int end, string text)
{
if (codes.Any())
{
var lastCodeSpan = codes.Last().Span;
var lastCodeSpanEnd = lastCodeSpan.GetEndPosition();
// There could be whitespace following #disable-next-line directive, in which case we need to adjust the span and text.
// E.g. #disable-next-line BCP226 // test
if (end > lastCodeSpanEnd)
{
var delta = end - lastCodeSpanEnd;
textWindow.Rewind(delta);
return new DisableNextLineDiagnosticsSyntaxTrivia(SyntaxTriviaType.DisableNextLineDiagnosticsDirective, new TextSpan(start, lastCodeSpanEnd - start), text[0..^delta], codes);
}
}
return new DisableNextLineDiagnosticsSyntaxTrivia(SyntaxTriviaType.DisableNextLineDiagnosticsDirective, new TextSpan(start, end - start), text, codes);
}
private Token? GetToken()
{
var text = textWindow.GetText();
if (text.Length > 0)
{
return new FreeformToken(TokenType.StringComplete, textWindow.GetSpan(), text.ToString(), Enumerable.Empty<SyntaxTrivia>(), Enumerable.Empty<SyntaxTrivia>());
}
return null;
}
private void LexToken()
{
textWindow.Reset();
// important to force enum evaluation here via .ToImmutableArray()!
var leadingTrivia = ScanLeadingTrivia().ToImmutableArray();
textWindow.Reset();
var tokenType = ScanToken();
var tokenText = textWindow.GetText();
var tokenSpan = textWindow.GetSpan();
if (tokenType == TokenType.Unrecognized)
{
var text = tokenText.ToString();
if (text == "\"")
{
AddDiagnostic(b => b.DoubleQuoteToken(text));
}
else
{
AddDiagnostic(b => b.UnrecognizedToken(text));
}
}
textWindow.Reset();
// important to force enum evaluation here via .ToImmutableArray()!
var includeComments = SyntaxFacts.GetCommentStickiness(tokenType) >= CommentStickiness.Trailing;
var trailingTrivia = ScanTrailingTrivia(includeComments).ToImmutableArray();
var token = SyntaxFacts.HasFreeFromText(tokenType)
? new FreeformToken(tokenType, tokenSpan, tokenText.ToString(), leadingTrivia, trailingTrivia)
: new Token(tokenType, tokenSpan, leadingTrivia, trailingTrivia);
this.tokens.Add(token);
}
private SyntaxTrivia ScanWhitespace()
{
textWindow.Reset();
while (!textWindow.IsAtEnd())
{
var nextChar = textWindow.Peek();
switch (nextChar)
{
case ' ':
case '\t':
textWindow.Advance();
continue;
}
break;
}
return new SyntaxTrivia(SyntaxTriviaType.Whitespace, textWindow.GetSpan(), textWindow.GetText().ToString());
}
private SyntaxTrivia ScanSingleLineComment()
{
textWindow.Reset();
textWindow.Advance(2);
while (!textWindow.IsAtEnd())
{
var nextChar = textWindow.Peek();
// make sure we don't include the newline in the comment trivia
if (IsNewLine(nextChar))
{
break;
}
textWindow.Advance();
}
return new SyntaxTrivia(SyntaxTriviaType.SingleLineComment, textWindow.GetSpan(), textWindow.GetText().ToString());
}
private SyntaxTrivia ScanMultiLineComment()
{
textWindow.Reset();
textWindow.Advance(2);
while (true)
{
if (textWindow.IsAtEnd())
{
AddDiagnostic(b => b.UnterminatedMultilineComment());
break;
}
var nextChar = textWindow.Peek();
textWindow.Advance();
if (nextChar != '*' || textWindow.Peek() != '/')
{
continue;
}
if (textWindow.IsAtEnd())
{
AddDiagnostic(b => b.UnterminatedMultilineComment());
break;
}
nextChar = textWindow.Peek();
textWindow.Advance();
if (nextChar == '/')
{
break;
}
}
return new SyntaxTrivia(SyntaxTriviaType.MultiLineComment, textWindow.GetSpan(), textWindow.GetText().ToString());
}
private void ScanNewLine()
{
while (true)
{
if (textWindow.IsAtEnd())
{
return;
}
var nextChar = textWindow.Peek();
if (IsNewLine(nextChar) == false)
{
return;
}
textWindow.Advance();
}
}
private TokenType ScanMultilineString()
{
var successiveQuotes = 0;
// we've already scanned the "'''", so get straight to scanning the string contents.
while (!textWindow.IsAtEnd())
{
var nextChar = textWindow.Peek();
textWindow.Advance();
switch (nextChar)
{
case '\'':
successiveQuotes++;
if (successiveQuotes == MultilineStringTerminatingQuoteCount)
{
// we've scanned the terminating "'''". Keep scanning as long as we find more "'" characters;
// it is possible for the verbatim string's last character to be "'", and we should accept this.
while (textWindow.Peek() == '\'')
{
textWindow.Advance();
}
return TokenType.MultilineString;
}
break;
default:
successiveQuotes = 0;
break;
}
}
// We've reached the end of the file without finding terminating quotes.
// We still want to return a string token so that highlighting shows up.
AddDiagnostic(b => b.UnterminatedMultilineString());
return TokenType.MultilineString;
}
private TokenType ScanStringSegment(bool isAtStartOfString)
{
// to handle interpolation, strings are broken down into multiple segments, to detect the portions of string between the 'holes'.
// 'complete' string: a string with no holes (no interpolation), e.g. "'hello'"
// string 'left piece': the portion of an interpolated string up to the first hole, e.g. "'hello$"
// string 'middle piece': the portion of an interpolated string between two holes, e.g. "}hello${"
// string 'right piece': the portion of an interpolated string after the last hole, e.g. "}hello'"
while (true)
{
if (textWindow.IsAtEnd())
{
AddDiagnostic(b => b.UnterminatedString());
return isAtStartOfString ? TokenType.StringComplete : TokenType.StringRightPiece;
}
var nextChar = textWindow.Peek();
if (IsNewLine(nextChar))
{
// do not consume the new line character
AddDiagnostic(b => b.UnterminatedStringWithNewLine());
return isAtStartOfString ? TokenType.StringComplete : TokenType.StringRightPiece;
}
int escapeBeginPosition = textWindow.GetAbsolutePosition();
textWindow.Advance();
if (nextChar == '\'')
{
return isAtStartOfString ? TokenType.StringComplete : TokenType.StringRightPiece;
}
if (nextChar == '$' && !textWindow.IsAtEnd() && textWindow.Peek() == '{')
{
textWindow.Advance();
return isAtStartOfString ? TokenType.StringLeftPiece : TokenType.StringMiddlePiece;
}
if (nextChar != '\\')
{
continue;
}
// an escape sequence was started with \
if (textWindow.IsAtEnd())
{
// the escape was unterminated
AddDiagnostic(b => b.UnterminatedStringEscapeSequenceAtEof());
return isAtStartOfString ? TokenType.StringComplete : TokenType.StringRightPiece;
}
// the escape sequence has a char after the \
// consume it
nextChar = textWindow.Peek();
textWindow.Advance();
if (nextChar == 'u')
{
// unicode escape
if (textWindow.IsAtEnd())
{
// string was prematurely terminated
// reusing the first check in the loop body to produce the diagnostic
continue;
}
nextChar = textWindow.Peek();
if (nextChar != '{')
{
// \u must be followed by {, but it's not
AddDiagnostic(textWindow.GetSpanFromPosition(escapeBeginPosition), b => b.InvalidUnicodeEscape());
continue;
}
textWindow.Advance();
if (textWindow.IsAtEnd())
{
// string was prematurely terminated
// reusing the first check in the loop body to produce the diagnostic
continue;
}
string codePointText = ScanHexNumber(textWindow);
if (textWindow.IsAtEnd())
{
// string was prematurely terminated
// reusing the first check in the loop body to produce the diagnostic
continue;
}
if (string.IsNullOrEmpty(codePointText))
{
// we didn't get any hex digits
AddDiagnostic(textWindow.GetSpanFromPosition(escapeBeginPosition), b => b.InvalidUnicodeEscape());
continue;
}
nextChar = textWindow.Peek();
if (nextChar != '}')
{
// hex digits must be followed by }, but it's not
AddDiagnostic(textWindow.GetSpanFromPosition(escapeBeginPosition), b => b.InvalidUnicodeEscape());
continue;
}
textWindow.Advance();
if (!TryParseCodePoint(codePointText, out _))
{
// code point is not actually valid
AddDiagnostic(textWindow.GetSpanFromPosition(escapeBeginPosition), b => b.InvalidUnicodeEscape());
continue;
}
}
else
{
// not a unicode escape
if (SingleCharacterEscapes.ContainsKey(nextChar) == false)
{
// the span of the error is the incorrect escape sequence
AddDiagnostic(textWindow.GetLookbehindSpan(2), b => b.UnterminatedStringEscapeSequenceUnrecognized(CharacterEscapeSequences));
}
}
}
}
private static string ScanHexNumber(SlidingTextWindow window)
{
var buffer = new StringBuilder();
while (true)
{
if (window.IsAtEnd())
{
return buffer.ToString();
}
char current = window.Peek();
if (!IsHexDigit(current))
{
return buffer.ToString();
}
buffer.Append(current);
window.Advance();
}
}
private void ScanNumber()
{
while (true)
{
if (textWindow.IsAtEnd())
{
return;
}
if (!IsDigit(textWindow.Peek()))
{
return;
}
textWindow.Advance();
}
}
private TokenType GetIdentifierTokenType()
{
var identifier = textWindow.GetText().ToString();
if (LanguageConstants.Keywords.TryGetValue(identifier, out var tokenType))
{
return tokenType;
}
if (identifier.Length > LanguageConstants.MaxIdentifierLength)
{
this.AddDiagnostic(b => b.IdentifierNameExceedsLimit());
}
return TokenType.Identifier;
}
private TokenType ScanIdentifier()
{
while (true)
{
if (textWindow.IsAtEnd())
{
return GetIdentifierTokenType();
}
if (!IsIdentifierContinuation(textWindow.Peek()))
{
return GetIdentifierTokenType();
}
textWindow.Advance();
}
}
private TokenType ScanToken()
{
if (textWindow.IsAtEnd())
{
return TokenType.EndOfFile;
}
var nextChar = textWindow.Peek();
textWindow.Advance();
switch (nextChar)
{
case '{':
if (templateStack.Any())
{
// if we're inside a string interpolation hole, and we find an object open brace,
// push it to the stack, so that we can match it up against an object close brace.
// this allows us to determine whether we're terminating an object or closing an interpolation hole.
templateStack.Push(TokenType.LeftBrace);
}
return TokenType.LeftBrace;
case '}':
if (templateStack.Any())
{
var prevTemplateToken = templateStack.Peek();
if (prevTemplateToken != TokenType.LeftBrace)
{
var stringToken = ScanStringSegment(false);
if (stringToken == TokenType.StringRightPiece)
{
templateStack.Pop();
}
return stringToken;
}
}
return TokenType.RightBrace;
case '(':
return TokenType.LeftParen;
case ')':
return TokenType.RightParen;
case '[':
return TokenType.LeftSquare;
case ']':
return TokenType.RightSquare;
case '@':
return TokenType.At;
case ',':
return TokenType.Comma;
case '.':
return TokenType.Dot;
case '?':
if (!textWindow.IsAtEnd())
{
switch (textWindow.Peek())
{
case '?':
textWindow.Advance();
return TokenType.DoubleQuestion;
}
}
return TokenType.Question;
case ':':
if (!textWindow.IsAtEnd())
{
switch (textWindow.Peek())
{
case ':':
textWindow.Advance();
return TokenType.DoubleColon;
}
}
return TokenType.Colon;
case ';':
return TokenType.Semicolon;
case '+':
return TokenType.Plus;
case '-':
return TokenType.Minus;
case '%':
return TokenType.Modulo;
case '*':
return TokenType.Asterisk;
case '/':
return TokenType.Slash;
case '!':
if (!textWindow.IsAtEnd())
{
switch (textWindow.Peek())
{
case '=':
textWindow.Advance();
return TokenType.NotEquals;
case '~':
textWindow.Advance();
return TokenType.NotEqualsInsensitive;
}
}
return TokenType.Exclamation;
case '<':
if (!textWindow.IsAtEnd())
{
switch (textWindow.Peek())
{
case '=':
textWindow.Advance();
return TokenType.LessThanOrEqual;
}
}
return TokenType.LeftChevron;
case '>':
if (!textWindow.IsAtEnd())
{
switch (textWindow.Peek())
{
case '=':
textWindow.Advance();
return TokenType.GreaterThanOrEqual;
}
}
return TokenType.RightChevron;
case '=':
if (!textWindow.IsAtEnd())
{
switch (textWindow.Peek())
{
case '=':
textWindow.Advance();
return TokenType.Equals;
case '~':
textWindow.Advance();
return TokenType.EqualsInsensitive;
case '>':
textWindow.Advance();
return TokenType.Arrow;
}
}
return TokenType.Assignment;
case '&':
if (!textWindow.IsAtEnd())
{
switch (textWindow.Peek())
{
case '&':
textWindow.Advance();
return TokenType.LogicalAnd;
}
}