/
Tokenizer.cs
1284 lines (1115 loc) · 26 KB
/
Tokenizer.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
//
// MiniME - http://www.toptensoftware.com/minime
//
// The contents of this file are subject to the license terms as
// specified at the web address above.
//
// Software distributed under the License is distributed on an
// "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
// implied. See the License for the specific language governing
// rights and limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MiniME
{
class Bookmark
{
public Bookmark(StringScanner file, int position, Token token, bool warnings)
{
this.file = file;
this.position = position;
this.token = token;
this.warnings = warnings;
}
public StringScanner file;
public int position;
public Token token;
public bool warnings;
public override string ToString()
{
int offset;
int line = file.LineNumberFromOffset(position, out offset);
return String.Format("{0}({1},{2})", file.FileName, line + 1, offset + 1);
}
}
enum Token
{
eof, // End of file
comment, // C or C++ style comment (filtered out internally to tokenizer)
literal,
identifier,
directive_private, // Comment of form /* private */
directive_public, // Comment of form /* public */
directive_comment, // Comment of form //! or /*!
// Operators
assign,
addAssign,
subtractAssign,
multiplyAssign,
divideAssign,
modulusAssign,
shlAssign,
shrAssign,
shrzAssign,
bitwiseXorAssign,
bitwiseOrAssign,
bitwiseAndAssign,
increment,
decrement,
add,
subtract,
multiply,
divide,
modulus,
shl,
shr,
shrz,
compareEQ,
compareNE,
compareLT,
compareLE,
compareGT,
compareGE,
compareEQStrict,
compareNEStrict,
bitwiseXor,
bitwiseOr,
bitwiseAnd,
bitwiseNot,
logicalNot,
logicalOr,
logicalAnd,
// Special symbols
question, // ?
colon, // :
semicolon, // ;
comma, // ,
openRound,
closeRound,
openBrace,
closeBrace,
openSquare,
closeSquare,
period,
// Keywords
kw_void,
kw_delete,
kw_new,
kw_in,
kw_instanceof,
kw_typeof,
kw_var,
kw_return,
kw_if,
kw_switch,
kw_case,
kw_default,
kw_break,
kw_continue,
kw_fallthrough,
kw_else,
kw_for,
kw_do,
kw_while,
kw_with,
kw_throw,
kw_try,
kw_catch,
kw_finally,
kw_function,
kw_class,
kw_debugger,
}
// Simple class to store a double value and it's original
// string representation. Used to pass through doubles without
// changing precision.
public class DoubleLiteral
{
public double Value;
public string Original;
}
// Tokenizer
// - a fairly standard approach to input stream tokenization
// - tokenizes all Javascript tokens
// - special case for regex:
// - parser must know when a regex is allowed, check for Token.divide
// and then call ParseRegex, which simply returns the entire regex
// as a string
// - uses a StringScanner for maintaining position in input
class Tokenizer
{
static Tokenizer()
{
// Build a map of keyword identifiers to token enums
BuildKeywordMap();
}
// Constructor
public Tokenizer(Compiler Compiler, string str, string strFileName, bool bWarnings)
{
this.Compiler=Compiler;
// Prep the string scanner
p = new StringScanner();
p.Reset(str);
p.FileName = strFileName;
m_bWarnings = bWarnings;
// Used to detect line breaks between tokens for automatic
// semicolon insertion
m_bPreceededByLineBreak = true;
// Queue up the first token
m_prevToken = Token.eof;
Next();
}
public Compiler Compiler
{
get;
private set;
}
public void OpenIncludeFile(string text, string fileName)
{
// Register the included file
Compiler.RegisterIncludedFile(fileName);
// Save the current string parser
m_IncludeStack.Push(p);
// Prep the string scanner
p = new StringScanner();
p.Reset(text);
p.FileName = fileName;
// Used to detect line breaks between tokens for automatic
// semicolon insertion
m_bPreceededByLineBreak = true;
m_prevTokenEnd = 0;
}
public Bookmark GetBookmark()
{
return new Bookmark(p, m_tokenStart, this.token, m_bWarnings);
}
public bool Warnings
{
get
{
return m_bWarnings;
}
}
// Rewind the tokenizer to a previously marked position
public void Rewind(Bookmark bmk)
{
System.Diagnostics.Debug.Assert(bmk.file == this.p);
p.position = bmk.position;
Next();
}
// Helper to convert a token back to it's original form
public static string FormatToken(Token token)
{
switch (token)
{
case Token.eof: return "end-of-file";
case Token.assign: return "=";
case Token.add: return "+";
case Token.subtract: return "-";
case Token.multiply: return "*";
case Token.divide: return "/";
case Token.modulus: return "%";
case Token.shl: return "<<";
case Token.shr: return ">>";
case Token.shrz: return ">>>";
case Token.addAssign: return "+=";
case Token.subtractAssign: return "-=";
case Token.multiplyAssign: return "*=";
case Token.divideAssign: return "/=";
case Token.modulusAssign: return "%=";
case Token.shlAssign: return "<<=";
case Token.shrAssign: return ">>=";
case Token.shrzAssign: return ">>>=";
case Token.increment:return "++";
case Token.decrement: return "--";
case Token.compareEQ: return "==";
case Token.compareNE: return "!=";
case Token.compareLT: return "<";
case Token.compareLE: return "<=";
case Token.compareGT: return ">";
case Token.compareGE:return ">=";
case Token.compareEQStrict:return "===";
case Token.compareNEStrict:return "!==";
case Token.bitwiseXor:return "^";
case Token.bitwiseOr:return "|";
case Token.bitwiseAnd:return "&";
case Token.bitwiseNot:return "~";
case Token.bitwiseXorAssign: return "^=";
case Token.bitwiseOrAssign:return "|=";
case Token.bitwiseAndAssign:return "&=";
case Token.logicalNot:return "!";
case Token.logicalOr:return "||";
case Token.logicalAnd:return "&&";
case Token.question:return "?";
case Token.colon:return ":";
case Token.semicolon: return ";";
case Token.comma:return ",";
case Token.openRound:return "(";
case Token.closeRound:return ")";
case Token.openBrace:return "{";
case Token.closeBrace:return "}";
case Token.openSquare:return "[";
case Token.closeSquare:return "]";
case Token.period:return ".";
}
var s=token.ToString();
if (s.StartsWith("kw_"))
return s.Substring(3);
return s;
}
// Get a text representation of the current token
// - typically used for descriptive error messages
public string DescribeCurrentToken()
{
switch (token)
{
case Token.identifier:
case Token.literal:
return string.Format("{0} - `{1}`", FormatToken(token), RawToken);
}
return string.Format("`{0}`", FormatToken(token));
}
// The current token
public Token token
{
get
{
return m_currentToken;
}
}
// Check if more input is available
public bool more
{
get
{
return m_currentToken != Token.eof && m_IncludeStack.Count==0;
}
}
// Get the offset of the current token
public int currentOffset
{
get
{
return m_tokenStart;
}
}
// Get the line number of the current token
public int currentLine
{
get
{
int unused;
return p.LineNumberFromOffset(m_tokenStart, out unused);
}
}
// Get the line offset of the current token
public int currentLinePosition
{
get
{
int chpos;
p.LineNumberFromOffset(m_tokenStart, out chpos);
return chpos;
}
}
public int LineNumberFromOffset(int position, out int lineoffset)
{
return p.LineNumberFromOffset(position, out lineoffset);
}
// Get the raw text from which the current token was parsed
public string RawToken
{
get
{
return p.Substring(m_tokenStart, m_tokenEnd - m_tokenStart);
}
}
// Get the value of a literal token
public object literal
{
get
{
System.Diagnostics.Debug.Assert(token == Token.literal);
return m_literal;
}
}
// Get the name of an identifier token
public string identifier
{
get
{
return m_strIdentifier;
}
}
// Check for cases where a semicolon is optional
// - end of file
// - immediately before a brace
// - before a line break
public bool IsAutoSemicolon()
{
if (p.eof || token == Token.closeBrace || m_bPreceededByLineBreak)
{
if (m_prevToken!=Token.closeBrace)
{
if (m_bWarnings)
{
var b = new Bookmark(p, m_prevTokenEnd, token, m_bWarnings);
b.file = this.p;
b.position = this.m_prevTokenEnd;
b.token = this.token;
Compiler.RecordWarning(b, "missing semicolon");
}
}
return true;
}
return false;
}
// Check for an optional token, skipping it if found
public bool SkipOptional(Token t)
{
if (token != t)
{
// Automatic semicolons?
if (t == Token.semicolon && IsAutoSemicolon())
{
return true;
}
return false;
}
Next();
return true;
}
// Check for a required token, skipping it if found, raising an
// error if not found
public void SkipRequired(Token t)
{
// Automatic semicolons?
if (t == Token.semicolon && token != Token.semicolon)
{
if (IsAutoSemicolon())
return;
}
Require(t);
Next();
}
// Raise an error if the current token isn't of the specified type
public void Require(Token t)
{
if (token != t)
{
throw new CompileError(string.Format("Syntax error - expected {0} but found {1}", FormatToken(t), DescribeCurrentToken()), this);
}
}
// Parse a regex string
public string ParseRegEx()
{
// Rewind to start of the current token
p.position = m_tokenStart;
// Must start with a slash
System.Diagnostics.Debug.Assert(p.current=='/');
// Mark the position and skip the opening slash
p.Mark();
p.SkipForward(1);
// Find the end
while (!p.eol)
{
if (p.current == '/')
break;
if (p.current=='\\')
p.SkipForward(2);
else
p.SkipForward(1);
}
// Check end found
if (p.current != '/')
{
p.position=m_tokenStart;
throw new CompileError("Syntax error - unterminated regular expression", this);
}
// Closing slash
p.SkipForward(1);
// Flags
while (p.current=='g' || p.current=='i' || p.current=='m' || p.current=='y')
p.SkipForward(1);
// Check no more characters
if (IsIdentifierChar(p.current))
{
p.position = m_tokenStart;
throw new CompileError(string.Format("Syntax error - unexpected character `{0}` after regular expression", p.current), this);
}
// Get the regex verbatim
string regex = p.Extract();
// Scan the next token
Next();
// Done
return regex;
}
// Get the next token, skipping comments as we go
public Token Next()
{
m_prevToken = m_currentToken;
do
{
m_currentToken = ParseToken();
if (m_currentToken == Token.eof && m_IncludeStack.Count > 0)
{
// Pop include stack
p = m_IncludeStack.Pop();
m_prevTokenEnd = p.position;
return Next();
}
// Check for directive comments
if (m_currentToken == Token.comment)
{
if (m_strIdentifier.StartsWith("!"))
{
m_currentToken = Token.directive_comment;
break;
}
string str = m_strIdentifier.Trim();
if (str=="fall through")
{
m_currentToken=Token.kw_fallthrough;
break;
}
if (str == "warnings:on")
{
m_bWarnings = true;
}
if (str == "warnings:off")
{
m_bWarnings = false;
}
if (str == "warnings:push:on")
{
Compiler.WarningsEnabledStack.Push(m_bWarnings);
m_bWarnings = true;
}
if (str == "warnings:push:off")
{
Compiler.WarningsEnabledStack.Push(m_bWarnings);
m_bWarnings = false;
}
if (str == "warnings:pop")
{
if (Compiler.WarningsEnabledStack.Count > 0)
{
m_bWarnings = Compiler.WarningsEnabledStack.Pop();
}
else
{
m_bWarnings = true;
Compiler.RecordWarning(GetBookmark(), "can't pop warning state.");
}
}
if (str.StartsWith("private:"))
{
m_currentToken = Token.directive_private;
m_strIdentifier = str.Substring(8);
break;
}
if (str.StartsWith("public:"))
{
m_currentToken = Token.directive_public;
m_strIdentifier = str.Substring(7);
break;
}
if (str.StartsWith("include:"))
{
// Get file name
string strFile = str.Substring(8).Trim();
// Work out fully qualified name, relative to current file being processed
string strDir = System.IO.Path.GetDirectoryName(p.FileName);
string strOldDir = System.IO.Directory.GetCurrentDirectory();
System.IO.Directory.SetCurrentDirectory(strDir);
strFile = System.IO.Path.GetFullPath(strFile);
System.IO.Directory.SetCurrentDirectory(strOldDir);
// Open the include file
OpenIncludeFile(System.IO.File.ReadAllText(strFile), strFile);
// Recurse
return Next();
}
}
} while (m_currentToken == Token.comment);
m_prevTokenEnd = m_tokenEnd;
m_tokenEnd = p.position;
return m_currentToken;
}
// Main token parser
public Token ParseToken()
{
// Skip whitespace, but remember if there were any line breaks
bool bOldPreceededByLineBreak = m_bPreceededByLineBreak;
m_bPreceededByLineBreak = false;
while (char.IsWhiteSpace(p.current))
{
if (p.eol)
m_bPreceededByLineBreak = true;
p.SkipForward(1);
}
// check for eof
if (p.eof)
{
return Token.eof;
}
// Save current position
m_tokenStart = p.position;
char ch=p.current;
// Digit?
if (ch >= '0' && ch <= '9')
{
return ParseNumber();
}
// Identifier?
if (IsIdentifierLeadChar(ch))
{
ParseIdentifier();
return MapIdentifierToKeyword();
}
// Characters...
switch (ch)
{
case '.':
// Decimal point without leading digits
p.SkipForward(1);
if (p.current >= '0' && p.current <= '9')
{
p.SkipForward(-1);
return ParseNumber();
}
return Token.period;
case '/':
p.SkipForward(1);
switch (p.current)
{
case '*':
p.SkipForward(1);
p.Mark();
if (!p.Find("*/"))
{
p.position = m_tokenStart;
throw new CompileError("Syntax error - unterminated C-style comment", this);
}
m_strIdentifier = p.Extract();
p.SkipForward(2);
m_bPreceededByLineBreak = bOldPreceededByLineBreak;
return Token.comment;
case '/':
p.SkipForward(1);
p.Mark();
p.SkipToEol();
m_strIdentifier = p.Extract();
return Token.comment;
case '=':
p.SkipForward(1);
return Token.divideAssign;
}
return Token.divide;
case '+':
p.SkipForward(1);
if (p.current == '=')
{
p.SkipForward(1);
return Token.addAssign;
}
if (p.current == '+')
{
p.SkipForward(1);
return Token.increment;
}
return Token.add;
case '-':
p.SkipForward(1);
if (p.current == '=')
{
p.SkipForward(1);
return Token.subtractAssign;
}
if (p.current == '-')
{
p.SkipForward(1);
return Token.decrement;
}
return Token.subtract;
case '*':
p.SkipForward(1);
if (p.current == '=')
{
p.SkipForward(1);
return Token.multiplyAssign;
}
return Token.multiply;
case '%':
p.SkipForward(1);
if (p.current == '=')
{
p.SkipForward(1);
return Token.modulusAssign;
}
return Token.modulus;
case '<':
p.SkipForward(1);
if (p.current == '<')
{
// <<
p.SkipForward(1);
if (p.current == '=')
{
// <<=
p.SkipForward(1);
return Token.shlAssign;
}
return Token.shl;
}
if (p.current == '=')
{
// <=
p.SkipForward(1);
return Token.compareLE;
}
// <
return Token.compareLT;
case '>':
p.SkipForward(1);
if (p.current == '>')
{
// >>
p.SkipForward(1);
if (p.current == '>')
{
// >>>
p.SkipForward(1);
if (p.current == '=')
{
// >>>=
p.SkipForward(1);
return Token.shrzAssign;
}
return Token.shrz;
}
if (p.current == '=')
{
p.SkipForward(1);
return Token.shrAssign;
}
return Token.shr;
}
if (p.current == '=')
{
// >=
p.SkipForward(1);
return Token.compareGE;
}
return Token.compareGT;
case '{':
p.SkipForward(1);
return Token.openBrace;
case '}':
p.SkipForward(1);
return Token.closeBrace;
case '[':
p.SkipForward(1);
return Token.openSquare;
case ']':
p.SkipForward(1);
return Token.closeSquare;
case '(':
p.SkipForward(1);
return Token.openRound;
case ')':
p.SkipForward(1);
return Token.closeRound;
case '&':
p.SkipForward(1);
if (p.current == '&')
{
p.SkipForward(1);
return Token.logicalAnd;
}
if (p.current == '=')
{
p.SkipForward(1);
return Token.bitwiseAndAssign;
}
return Token.bitwiseAnd;
case '|':
p.SkipForward(1);
if (p.current == '|')
{
p.SkipForward(1);
return Token.logicalOr;
}
if (p.current == '=')
{
p.SkipForward(1);
return Token.bitwiseOrAssign;
}
return Token.bitwiseOr;
case '~':
p.SkipForward(1);
return Token.bitwiseNot;
case '!':
p.SkipForward(1);
if (p.current == '=')
{
p.SkipForward(1);
if (p.current == '=')
{
p.SkipForward(1);
return Token.compareNEStrict;
}
return Token.compareNE;
}
return Token.logicalNot;
case '^':
p.SkipForward(1);
if (p.current == '=')
{
p.SkipForward(1);
return Token.bitwiseXorAssign;
}
return Token.bitwiseXor;
case '=':
p.SkipForward(1);
if (p.current == '=')
{
p.SkipForward(1);
if (p.current == '=')
{
p.SkipForward(1);
return Token.compareEQStrict;
}
return Token.compareEQ;
}
return Token.assign;
case '?':
p.SkipForward(1);
return Token.question;
case ':':
p.SkipForward(1);
return Token.colon;
case ',':
p.SkipForward(1);
return Token.comma;
case ';':
p.SkipForward(1);
return Token.semicolon;
case '\'':
case '\"':
return ParseString();
}
throw new CompileError(string.Format("Syntax error - unrecognized character: `{0}`", p.current), this);
}
// Parse a string literal
Token ParseString()
{
char chTerminator = p.current;
p.SkipForward(1);
sb.Length = 0;
while (!p.eol)
{
var ch = p.current;
if (ch == chTerminator)
break;
if (ch == '\\')
{
p.SkipForward(1);
if (OctalDigit(p.current) >= 0)
{
// Up to three octal digits
int val = 0;
for (int i = 0; i < 3; i++)
{
int digit = OctalDigit(p.current);
if (digit < 0)
break;
val = val * 8 + digit;
p.SkipForward(1);
}
sb.Append((char)val);
}
else
{
switch (p.current)
{
case 'b':
sb.Append('\b');
break;
case 'f':
sb.Append('\f');
break;
case 'n':
sb.Append('\n');
break;
case 'r':
sb.Append('\r');
break;
case 't':
sb.Append('\t');
break;
case 'x':
{
p.SkipForward(1);
// Need two hex digits
int val = 0;
for (int i = 0; i < 2; i++)
{
int digit = HexDigit(p.current);
if (digit < 0)
{
throw new CompileError(string.Format("Syntax error - invalid character `{0}` in string literal", p.current), this);
}
val = val * 16 + digit;
p.SkipForward(1);
}
sb.Append((char)val);
continue;
}