Debian Codegraph @

js/lex_test.go

raw
1 package js
2
3 import (
4 "fmt"
5 "io"
6 "strings"
7 "testing"
8
9 "github.com/tdewolff/parse/v2"
10 "github.com/tdewolff/test"
11 )
12
13 type TTs []TokenType
14
15 func TestTokens(t *testing.T) {
16 var tokenTests = []struct {
17 js string
18 expected []TokenType
19 }{
20 {" \t\v\f\u00A0\uFEFF\u2000", TTs{}}, // WhitespaceToken
21 {"\n\r\r\n\u2028\u2029", TTs{LineTerminatorToken}},
22 {"5.2 .04 1. 2.e3 0x0F 5e99", TTs{DecimalToken, DecimalToken, DecimalToken, DecimalToken, HexadecimalToken, DecimalToken}},
23 {"2_3 5_4.1_2 1_1n 0o2_3 0b1_1 0xF_F", TTs{IntegerToken, DecimalToken, IntegerToken, OctalToken, BinaryToken, HexadecimalToken}},
24 {"0o22 0b11", TTs{OctalToken, BinaryToken}},
25 {"0n 2345n 0o5n 0b1n 0x5n 435.333n", TTs{IntegerToken, IntegerToken, OctalToken, BinaryToken, HexadecimalToken, DecimalToken, ErrorToken}},
26 {"a = 'string'", TTs{IdentifierToken, EqToken, StringToken}},
27 {"/*comment*/ //comment", TTs{CommentToken, CommentToken}},
28 {"{ } ( ) [ ]", TTs{OpenBraceToken, CloseBraceToken, OpenParenToken, CloseParenToken, OpenBracketToken, CloseBracketToken}},
29 {". ; , < > <= ...", TTs{DotToken, SemicolonToken, CommaToken, LtToken, GtToken, LtEqToken, EllipsisToken}},
30 {">= == != === !==", TTs{GtEqToken, EqEqToken, NotEqToken, EqEqEqToken, NotEqEqToken}},
31 {"+ - * / % ** ++ --", TTs{AddToken, SubToken, MulToken, DivToken, ModToken, ExpToken, IncrToken, DecrToken}},
32 {"<< >> >>> & | ^", TTs{LtLtToken, GtGtToken, GtGtGtToken, BitAndToken, BitOrToken, BitXorToken}},
33 {"! ~ && || ? : ?? ?.", TTs{NotToken, BitNotToken, AndToken, OrToken, QuestionToken, ColonToken, NullishToken, OptChainToken}},
34 {"= += -= *= **= /= %= <<=", TTs{EqToken, AddEqToken, SubEqToken, MulEqToken, ExpEqToken, DivEqToken, ModEqToken, LtLtEqToken}},
35 {">>= >>>= &= |= ^= =>", TTs{GtGtEqToken, GtGtGtEqToken, BitAndEqToken, BitOrEqToken, BitXorEqToken, ArrowToken}},
36 {"&&= ||= ??=", TTs{AndEqToken, OrEqToken, NullishEqToken}},
37 {"?.5", TTs{QuestionToken, DecimalToken}},
38 {"?.a", TTs{OptChainToken, IdentifierToken}},
39 {"await break case catch class const continue", TTs{AwaitToken, BreakToken, CaseToken, CatchToken, ClassToken, ConstToken, ContinueToken}},
40 {"debugger default delete do else enum export extends", TTs{DebuggerToken, DefaultToken, DeleteToken, DoToken, ElseToken, EnumToken, ExportToken, ExtendsToken}},
41 {"false finally for function if import in instanceof", TTs{FalseToken, FinallyToken, ForToken, FunctionToken, IfToken, ImportToken, InToken, InstanceofToken}},
42 {"new null return super switch this throw true", TTs{NewToken, NullToken, ReturnToken, SuperToken, SwitchToken, ThisToken, ThrowToken, TrueToken}},
43 {"try typeof var void while with yield", TTs{TryToken, TypeofToken, VarToken, VoidToken, WhileToken, WithToken, YieldToken}},
44 {"implements interface let package private protected public static", TTs{ImplementsToken, InterfaceToken, LetToken, PackageToken, PrivateToken, ProtectedToken, PublicToken, StaticToken}},
45 {"as async from get meta of set target", TTs{AsToken, AsyncToken, FromToken, GetToken, MetaToken, OfToken, SetToken, TargetToken}},
46 {"#ident", TTs{PrivateIdentifierToken}},
47
48 {"/*co\nm\u2028m/*ent*/ //co//mment\u2029//comment", TTs{CommentLineTerminatorToken, CommentToken, LineTerminatorToken, CommentToken}},
49 {"<!-", TTs{LtToken, NotToken, SubToken}},
50 {"1<!--2\n", TTs{IntegerToken, CommentToken, LineTerminatorToken}},
51 {"x=y-->10\n", TTs{IdentifierToken, EqToken, IdentifierToken, DecrToken, GtToken, IntegerToken, LineTerminatorToken}},
52 {" /*comment*/ -->nothing\n", TTs{CommentToken, DecrToken, GtToken, IdentifierToken, LineTerminatorToken}},
53 {"1 /*comment\nmultiline*/ -->nothing\n", TTs{IntegerToken, CommentLineTerminatorToken, CommentToken, LineTerminatorToken}},
54 {"$ _\u200C \\u2000 _\\u200C \u200C", TTs{IdentifierToken, IdentifierToken, IdentifierToken, IdentifierToken, ErrorToken}},
55 {">>>=>>>>=", TTs{GtGtGtEqToken, GtGtGtToken, GtEqToken}},
56 {"1/", TTs{IntegerToken, DivToken}},
57 {"1/=", TTs{IntegerToken, DivEqToken}},
58 {"'str\\i\\'ng'", TTs{StringToken}},
59 {"'str\\\\'abc", TTs{StringToken, IdentifierToken}},
60 {"'str\\\ni\\\\u00A0ng'", TTs{StringToken}},
61 {"'str\u2028\u2029ing'", TTs{StringToken}},
62
63 {"0b0101 0o0707 0b17", TTs{BinaryToken, OctalToken, BinaryToken, IntegerToken}},
64 {"`template`", TTs{TemplateToken}},
65 {"`a${x+y}b`", TTs{TemplateStartToken, IdentifierToken, AddToken, IdentifierToken, TemplateEndToken}},
66 {"`tmpl${x}tmpl${x}`", TTs{TemplateStartToken, IdentifierToken, TemplateMiddleToken, IdentifierToken, TemplateEndToken}},
67 {"`temp\nlate`", TTs{TemplateToken}},
68 {"`outer${{x: 10}}bar${ raw`nested${2}endnest` }end`", TTs{TemplateStartToken, OpenBraceToken, IdentifierToken, ColonToken, IntegerToken, CloseBraceToken, TemplateMiddleToken, IdentifierToken, TemplateStartToken, IntegerToken, TemplateEndToken, TemplateEndToken}},
69 {"`tmpl ${ a ? '' : `tmpl2 ${b ? 'b' : 'c'}` }`", TTs{TemplateStartToken, IdentifierToken, QuestionToken, StringToken, ColonToken, TemplateStartToken, IdentifierToken, QuestionToken, StringToken, ColonToken, StringToken, TemplateEndToken, TemplateEndToken}},
70
71 // early endings
72 {"'string", TTs{ErrorToken}},
73 {"'\n", TTs{ErrorToken}},
74 {"'\u2028", TTs{ErrorToken}},
75 {"'str\\\U00100000ing\\0'", TTs{StringToken}},
76 {"'strin\\00g'", TTs{StringToken}},
77 {"/*comment", TTs{ErrorToken}},
78 {"a=/regexp", TTs{IdentifierToken, EqToken, DivToken, IdentifierToken}},
79 {"\\u002", TTs{ErrorToken}},
80 {"`template", TTs{ErrorToken}},
81 {"`template${x}template", TTs{TemplateStartToken, IdentifierToken, ErrorToken}},
82 {"a++=1", TTs{IdentifierToken, IncrToken, EqToken, IntegerToken}},
83 {"a++==1", TTs{IdentifierToken, IncrToken, EqEqToken, IntegerToken}},
84 {"a++===1", TTs{IdentifierToken, IncrToken, EqEqEqToken, IntegerToken}},
85
86 // null characters
87 {"'string\x00'return", TTs{StringToken, ReturnToken}},
88 {"//comment\x00comment\nreturn", TTs{CommentToken, LineTerminatorToken, ReturnToken}},
89 {"/*comment\x00*/return", TTs{CommentToken, ReturnToken}},
90 {"`template\x00`return", TTs{TemplateToken, ReturnToken}},
91 {"`template\\\x00`return", TTs{TemplateToken, ReturnToken}},
92
93 // numbers
94 {"0xg", TTs{IntegerToken, ErrorToken}},
95 {"0bg", TTs{IntegerToken, ErrorToken}},
96 {"0og", TTs{IntegerToken, ErrorToken}},
97 {"010", TTs{ErrorToken}}, // Decimal(0) Decimal(10) Identifier(xF)
98 {"50e+-0", TTs{ErrorToken}},
99 {"5.a", TTs{DecimalToken, ErrorToken}},
100 {"5..a", TTs{DecimalToken, DotToken, IdentifierToken}},
101
102 // coverage
103 {"Ø a〉", TTs{IdentifierToken, IdentifierToken, ErrorToken}},
104 {"\u00A0\uFEFF\u2000", TTs{}},
105 {"\u2028\u2029", TTs{LineTerminatorToken}},
106 {"\\u0029ident", TTs{IdentifierToken}},
107 {"\\u{0029FEF}ident", TTs{IdentifierToken}},
108 {"\\u{}", TTs{ErrorToken}},
109 {"\\ugident", TTs{ErrorToken}},
110 {"'str\ring'", TTs{ErrorToken}},
111 {"a=/\\\n", TTs{IdentifierToken, EqToken, DivToken, ErrorToken}},
112 {"a=/x\n", TTs{IdentifierToken, EqToken, DivToken, IdentifierToken, LineTerminatorToken}},
113 {"`\\``", TTs{TemplateToken}},
114 {"`\\${ 1 }`", TTs{TemplateToken}},
115 {"`\\\r\n`", TTs{TemplateToken}},
116
117 // go fuzz
118 {"`", TTs{ErrorToken}},
119
120 // issues
121 {"_\u00bare_unicode_escape_identifier", TTs{IdentifierToken}}, // tdewolff/minify#449
122 }
123
124 for _, tt := range tokenTests {
125 t.Run(tt.js, func(t *testing.T) {
126 l := NewLexer(parse.NewInputString(tt.js))
127 i := 0
128 tokens := []TokenType{}
129 for {
130 token, _ := l.Next()
131 if token == ErrorToken {
132 if l.Err() != io.EOF {
133 tokens = append(tokens, token)
134 }
135 break
136 } else if token == WhitespaceToken {
137 continue
138 }
139 tokens = append(tokens, token)
140 i++
141 }
142 test.T(t, tokens, tt.expected, "token types must match")
143 })
144 }
145
146 // coverage
147 for _, start := range []int{0, 0x0100, 0x0200, 0x0600, 0x0800} {
148 for i := start; ; i++ {
149 if TokenType(i).String() == fmt.Sprintf("Invalid(%d)", i) {
150 break
151 }
152 }
153 }
154
155 test.That(t, IsPunctuator(CommaToken))
156 test.That(t, IsPunctuator(GtGtEqToken))
157 test.That(t, !IsPunctuator(WhileToken))
158 test.That(t, !IsOperator(CommaToken))
159 test.That(t, IsOperator(GtGtEqToken))
160 test.That(t, !IsOperator(WhileToken))
161 test.That(t, !IsIdentifier(CommaToken))
162 test.That(t, !IsIdentifier(GtGtEqToken))
163 test.That(t, IsReservedWord(WhileToken))
164 test.That(t, IsIdentifier(AsyncToken))
165 test.That(t, IsIdentifierName(WhileToken))
166 test.That(t, IsIdentifierName(AsToken))
167
168 test.That(t, IsIdentifierStart([]byte("a")))
169 test.That(t, !IsIdentifierStart([]byte("6")))
170 test.That(t, !IsIdentifierStart([]byte("[")))
171 test.That(t, IsIdentifierContinue([]byte("a")))
172 test.That(t, IsIdentifierContinue([]byte("6")))
173 test.That(t, !IsIdentifierContinue([]byte("[")))
174 test.That(t, IsIdentifierEnd([]byte(".a")))
175 test.That(t, IsIdentifierEnd([]byte(".6")))
176 test.That(t, !IsIdentifierEnd([]byte(".[")))
177 }
178
179 func TestRegExp(t *testing.T) {
180 var tokenTests = []struct {
181 js string
182 expected []TokenType
183 }{
184 {"a = /[a-z/]/g", TTs{IdentifierToken, EqToken, RegExpToken}},
185 {"a=/=/g1", TTs{IdentifierToken, EqToken, RegExpToken}},
186 {"a = /'\\\\/\n", TTs{IdentifierToken, EqToken, RegExpToken, LineTerminatorToken}},
187 {"a=/\\//g1", TTs{IdentifierToken, EqToken, RegExpToken}},
188 {"new RegExp(a + /\\d{1,2}/.source)", TTs{NewToken, IdentifierToken, OpenParenToken, IdentifierToken, AddToken, RegExpToken, DotToken, IdentifierToken, CloseParenToken}},
189 {"a=/regexp\x00/;return", TTs{IdentifierToken, EqToken, RegExpToken, SemicolonToken, ReturnToken}},
190 {"a=/regexp\\\x00/;return", TTs{IdentifierToken, EqToken, RegExpToken, SemicolonToken, ReturnToken}},
191 {"a=/x/\u200C\u3009", TTs{IdentifierToken, EqToken, RegExpToken, ErrorToken}},
192 {"a=/end", TTs{IdentifierToken, EqToken, ErrorToken}},
193 {"a=/\\\nend", TTs{IdentifierToken, EqToken, ErrorToken}},
194 {"a=/\\\u2028", TTs{IdentifierToken, EqToken, ErrorToken}},
195 {"a=/regexp/Ø", TTs{IdentifierToken, EqToken, RegExpToken}},
196 }
197
198 for _, tt := range tokenTests {
199 t.Run(tt.js, func(t *testing.T) {
200 l := NewLexer(parse.NewInputString(tt.js))
201 i := 0
202 tokens := []TokenType{}
203 for {
204 token, _ := l.Next()
205 if token == DivToken || token == DivEqToken {
206 token, _ = l.RegExp()
207 }
208 if token == ErrorToken {
209 if l.Err() != io.EOF {
210 tokens = append(tokens, token)
211 }
212 break
213 } else if token == WhitespaceToken {
214 continue
215 }
216 tokens = append(tokens, token)
217 i++
218 }
219 test.T(t, tokens, tt.expected, "token types must match")
220 })
221 }
222
223 token, _ := NewLexer(parse.NewInputString("")).RegExp()
224 test.T(t, token, ErrorToken)
225 }
226
227 func TestOffset(t *testing.T) {
228 z := parse.NewInputString(`var i=5;`)
229 l := NewLexer(z)
230 test.T(t, z.Offset(), 0)
231 _, _ = l.Next()
232 test.T(t, z.Offset(), 3) // var
233 _, _ = l.Next()
234 test.T(t, z.Offset(), 4) // ws
235 _, _ = l.Next()
236 test.T(t, z.Offset(), 5) // i
237 _, _ = l.Next()
238 test.T(t, z.Offset(), 6) // =
239 _, _ = l.Next()
240 test.T(t, z.Offset(), 7) // 5
241 _, _ = l.Next()
242 test.T(t, z.Offset(), 8) // ;
243 }
244
245 func TestLexerErrors(t *testing.T) {
246 var tests = []struct {
247 js string
248 err string
249 }{
250 {"@", "unexpected @"},
251 {"\x00", "unexpected 0x00"},
252 {"\x7f", "unexpected 0x7F"},
253 {"\u200F", "unexpected U+200F"},
254 {"\u2010", "unexpected \u2010"},
255 {".0E", "invalid number"},
256 {`"a`, "unterminated string literal"},
257 {"'a\nb'", "unterminated string literal"},
258 {"`", "unterminated template literal"},
259 }
260
261 for _, tt := range tests {
262 t.Run(tt.js, func(t *testing.T) {
263 l := NewLexer(parse.NewInputString(tt.js))
264 for l.Err() == nil {
265 l.Next()
266 }
267 test.T(t, l.Err().(*parse.Error).Message, tt.err)
268 })
269 }
270
271 l := NewLexer(parse.NewInputString(""))
272 l.RegExp()
273 test.T(t, l.Err().(*parse.Error).Message, "expected / or /=")
274
275 l = NewLexer(parse.NewInputString("/"))
276 l.Next()
277 l.RegExp()
278 test.T(t, l.Err().(*parse.Error).Message, "unexpected EOF or newline")
279
280 // see #118
281 l = NewLexer(parse.NewInputString("\uFFFDa"))
282 tt, data := l.Next()
283 test.T(t, tt, ErrorToken)
284 test.T(t, string(data), "�")
285 test.T(t, l.Err().(*parse.Error).Message, "unexpected �")
286 tt, data = l.Next()
287 test.T(t, tt, IdentifierToken)
288 test.T(t, string(data), "a")
289 }
290
291 ////////////////////////////////////////////////////////////////
292
293 func ExampleNewLexer() {
294 l := NewLexer(parse.NewInputString("var x = 'lorem ipsum';"))
295 var out strings.Builder
296 for {
297 tt, data := l.Next()
298 if tt == ErrorToken {
299 break
300 }
301 out.WriteString(string(data))
302 }
303 fmt.Println(out.String())
304 // Output: var x = 'lorem ipsum';
305 }