Source file
src/go/scanner/scanner_test.go
1
2
3
4
5 package scanner
6
7 import (
8 "go/token"
9 "os"
10 "path/filepath"
11 "runtime"
12 "strings"
13 "testing"
14 )
15
16 var fset = token.NewFileSet()
17
18 const (
19 special = iota
20 literal
21 operator
22 keyword
23 )
24
25 func tokenclass(tok token.Token) int {
26 switch {
27 case tok.IsLiteral():
28 return literal
29 case tok.IsOperator():
30 return operator
31 case tok.IsKeyword():
32 return keyword
33 }
34 return special
35 }
36
37 type elt struct {
38 tok token.Token
39 lit string
40 class int
41 }
42
43 var tokens = []elt{
44
45 {token.COMMENT, "/* a comment */", special},
46 {token.COMMENT, "// a comment \n", special},
47 {token.COMMENT, "/*\r*/", special},
48 {token.COMMENT, "/**\r/*/", special},
49 {token.COMMENT, "/**\r\r/*/", special},
50 {token.COMMENT, "//\r\n", special},
51
52
53 {token.IDENT, "foobar", literal},
54 {token.IDENT, "a۰۱۸", literal},
55 {token.IDENT, "foo६४", literal},
56 {token.IDENT, "bar9876", literal},
57 {token.IDENT, "ŝ", literal},
58 {token.IDENT, "ŝfoo", literal},
59 {token.INT, "0", literal},
60 {token.INT, "1", literal},
61 {token.INT, "123456789012345678890", literal},
62 {token.INT, "01234567", literal},
63 {token.INT, "0xcafebabe", literal},
64 {token.FLOAT, "0.", literal},
65 {token.FLOAT, ".0", literal},
66 {token.FLOAT, "3.14159265", literal},
67 {token.FLOAT, "1e0", literal},
68 {token.FLOAT, "1e+100", literal},
69 {token.FLOAT, "1e-100", literal},
70 {token.FLOAT, "2.71828e-1000", literal},
71 {token.IMAG, "0i", literal},
72 {token.IMAG, "1i", literal},
73 {token.IMAG, "012345678901234567889i", literal},
74 {token.IMAG, "123456789012345678890i", literal},
75 {token.IMAG, "0.i", literal},
76 {token.IMAG, ".0i", literal},
77 {token.IMAG, "3.14159265i", literal},
78 {token.IMAG, "1e0i", literal},
79 {token.IMAG, "1e+100i", literal},
80 {token.IMAG, "1e-100i", literal},
81 {token.IMAG, "2.71828e-1000i", literal},
82 {token.CHAR, "'a'", literal},
83 {token.CHAR, "'\\000'", literal},
84 {token.CHAR, "'\\xFF'", literal},
85 {token.CHAR, "'\\uff16'", literal},
86 {token.CHAR, "'\\U0000ff16'", literal},
87 {token.STRING, "`foobar`", literal},
88 {token.STRING, "`" + `foo
89 bar` +
90 "`",
91 literal,
92 },
93 {token.STRING, "`\r`", literal},
94 {token.STRING, "`foo\r\nbar`", literal},
95
96
97 {token.ADD, "+", operator},
98 {token.SUB, "-", operator},
99 {token.MUL, "*", operator},
100 {token.QUO, "/", operator},
101 {token.REM, "%", operator},
102
103 {token.AND, "&", operator},
104 {token.OR, "|", operator},
105 {token.XOR, "^", operator},
106 {token.SHL, "<<", operator},
107 {token.SHR, ">>", operator},
108 {token.AND_NOT, "&^", operator},
109
110 {token.ADD_ASSIGN, "+=", operator},
111 {token.SUB_ASSIGN, "-=", operator},
112 {token.MUL_ASSIGN, "*=", operator},
113 {token.QUO_ASSIGN, "/=", operator},
114 {token.REM_ASSIGN, "%=", operator},
115
116 {token.AND_ASSIGN, "&=", operator},
117 {token.OR_ASSIGN, "|=", operator},
118 {token.XOR_ASSIGN, "^=", operator},
119 {token.SHL_ASSIGN, "<<=", operator},
120 {token.SHR_ASSIGN, ">>=", operator},
121 {token.AND_NOT_ASSIGN, "&^=", operator},
122
123 {token.LAND, "&&", operator},
124 {token.LOR, "||", operator},
125 {token.ARROW, "<-", operator},
126 {token.INC, "++", operator},
127 {token.DEC, "--", operator},
128
129 {token.EQL, "==", operator},
130 {token.LSS, "<", operator},
131 {token.GTR, ">", operator},
132 {token.ASSIGN, "=", operator},
133 {token.NOT, "!", operator},
134
135 {token.NEQ, "!=", operator},
136 {token.LEQ, "<=", operator},
137 {token.GEQ, ">=", operator},
138 {token.DEFINE, ":=", operator},
139 {token.ELLIPSIS, "...", operator},
140
141 {token.LPAREN, "(", operator},
142 {token.LBRACK, "[", operator},
143 {token.LBRACE, "{", operator},
144 {token.COMMA, ",", operator},
145 {token.PERIOD, ".", operator},
146
147 {token.RPAREN, ")", operator},
148 {token.RBRACK, "]", operator},
149 {token.RBRACE, "}", operator},
150 {token.SEMICOLON, ";", operator},
151 {token.COLON, ":", operator},
152 {token.TILDE, "~", operator},
153
154
155 {token.BREAK, "break", keyword},
156 {token.CASE, "case", keyword},
157 {token.CHAN, "chan", keyword},
158 {token.CONST, "const", keyword},
159 {token.CONTINUE, "continue", keyword},
160
161 {token.DEFAULT, "default", keyword},
162 {token.DEFER, "defer", keyword},
163 {token.ELSE, "else", keyword},
164 {token.FALLTHROUGH, "fallthrough", keyword},
165 {token.FOR, "for", keyword},
166
167 {token.FUNC, "func", keyword},
168 {token.GO, "go", keyword},
169 {token.GOTO, "goto", keyword},
170 {token.IF, "if", keyword},
171 {token.IMPORT, "import", keyword},
172
173 {token.INTERFACE, "interface", keyword},
174 {token.MAP, "map", keyword},
175 {token.PACKAGE, "package", keyword},
176 {token.RANGE, "range", keyword},
177 {token.RETURN, "return", keyword},
178
179 {token.SELECT, "select", keyword},
180 {token.STRUCT, "struct", keyword},
181 {token.SWITCH, "switch", keyword},
182 {token.TYPE, "type", keyword},
183 {token.VAR, "var", keyword},
184 }
185
186 const whitespace = " \t \n\n\n"
187
188 var source = func() []byte {
189 var src []byte
190 for _, t := range tokens {
191 src = append(src, t.lit...)
192 src = append(src, whitespace...)
193 }
194 return src
195 }()
196
197 func newlineCount(s string) int {
198 n := 0
199 for i := 0; i < len(s); i++ {
200 if s[i] == '\n' {
201 n++
202 }
203 }
204 return n
205 }
206
207 func checkPos(t *testing.T, lit string, p token.Pos, expected token.Position) {
208 pos := fset.Position(p)
209
210
211 if pos.Filename != expected.Filename && filepath.Clean(pos.Filename) != filepath.Clean(expected.Filename) {
212 t.Errorf("bad filename for %q: got %s, expected %s", lit, pos.Filename, expected.Filename)
213 }
214 if pos.Offset != expected.Offset {
215 t.Errorf("bad position for %q: got %d, expected %d", lit, pos.Offset, expected.Offset)
216 }
217 if pos.Line != expected.Line {
218 t.Errorf("bad line for %q: got %d, expected %d", lit, pos.Line, expected.Line)
219 }
220 if pos.Column != expected.Column {
221 t.Errorf("bad column for %q: got %d, expected %d", lit, pos.Column, expected.Column)
222 }
223 }
224
225
226 func TestScan(t *testing.T) {
227 whitespace_linecount := newlineCount(whitespace)
228
229
230 eh := func(_ token.Position, msg string) {
231 t.Errorf("error handler called (msg = %s)", msg)
232 }
233
234
235 var s Scanner
236 s.Init(fset.AddFile("", fset.Base(), len(source)), source, eh, ScanComments|dontInsertSemis)
237
238
239 epos := token.Position{
240 Filename: "",
241 Offset: 0,
242 Line: 1,
243 Column: 1,
244 }
245
246 index := 0
247 for {
248 pos, tok, lit := s.Scan()
249
250
251 if tok == token.EOF {
252
253 epos.Line = newlineCount(string(source))
254 epos.Column = 2
255 }
256 checkPos(t, lit, pos, epos)
257
258
259 e := elt{token.EOF, "", special}
260 if index < len(tokens) {
261 e = tokens[index]
262 index++
263 }
264 if tok != e.tok {
265 t.Errorf("bad token for %q: got %s, expected %s", lit, tok, e.tok)
266 }
267
268
269 if tokenclass(tok) != e.class {
270 t.Errorf("bad class for %q: got %d, expected %d", lit, tokenclass(tok), e.class)
271 }
272
273
274 elit := ""
275 switch e.tok {
276 case token.COMMENT:
277
278 elit = string(stripCR([]byte(e.lit), e.lit[1] == '*'))
279
280 if elit[1] == '/' {
281 elit = elit[0 : len(elit)-1]
282 }
283 case token.IDENT:
284 elit = e.lit
285 case token.SEMICOLON:
286 elit = ";"
287 default:
288 if e.tok.IsLiteral() {
289
290 elit = e.lit
291 if elit[0] == '`' {
292 elit = string(stripCR([]byte(elit), false))
293 }
294 } else if e.tok.IsKeyword() {
295 elit = e.lit
296 }
297 }
298 if lit != elit {
299 t.Errorf("bad literal for %q: got %q, expected %q", lit, lit, elit)
300 }
301
302 if tok == token.EOF {
303 break
304 }
305
306
307 epos.Offset += len(e.lit) + len(whitespace)
308 epos.Line += newlineCount(e.lit) + whitespace_linecount
309
310 }
311
312 if s.ErrorCount != 0 {
313 t.Errorf("found %d errors", s.ErrorCount)
314 }
315 }
316
317 func TestStripCR(t *testing.T) {
318 for _, test := range []struct{ have, want string }{
319 {"//\n", "//\n"},
320 {"//\r\n", "//\n"},
321 {"//\r\r\r\n", "//\n"},
322 {"//\r*\r/\r\n", "//*/\n"},
323 {"/**/", "/**/"},
324 {"/*\r/*/", "/*/*/"},
325 {"/*\r*/", "/**/"},
326 {"/**\r/*/", "/**\r/*/"},
327 {"/*\r/\r*\r/*/", "/*/*\r/*/"},
328 {"/*\r\r\r\r*/", "/**/"},
329 } {
330 got := string(stripCR([]byte(test.have), len(test.have) >= 2 && test.have[1] == '*'))
331 if got != test.want {
332 t.Errorf("stripCR(%q) = %q; want %q", test.have, got, test.want)
333 }
334 }
335 }
336
337 func checkSemi(t *testing.T, line string, mode Mode) {
338 var S Scanner
339 file := fset.AddFile("TestSemis", fset.Base(), len(line))
340 S.Init(file, []byte(line), nil, mode)
341 pos, tok, lit := S.Scan()
342 for tok != token.EOF {
343 if tok == token.ILLEGAL {
344
345
346 semiLit := "\n"
347 if lit[0] == '#' {
348 semiLit = ";"
349 }
350
351 semiPos := file.Position(pos)
352 semiPos.Offset++
353 semiPos.Column++
354 pos, tok, lit = S.Scan()
355 if tok == token.SEMICOLON {
356 if lit != semiLit {
357 t.Errorf(`bad literal for %q: got %q, expected %q`, line, lit, semiLit)
358 }
359 checkPos(t, line, pos, semiPos)
360 } else {
361 t.Errorf("bad token for %q: got %s, expected ;", line, tok)
362 }
363 } else if tok == token.SEMICOLON {
364 t.Errorf("bad token for %q: got ;, expected no ;", line)
365 }
366 pos, tok, lit = S.Scan()
367 }
368 }
369
370 var lines = []string{
371
372
373 "",
374 "\ufeff#;",
375 "#;",
376 "foo$\n",
377 "123$\n",
378 "1.2$\n",
379 "'x'$\n",
380 `"x"` + "$\n",
381 "`x`$\n",
382
383 "+\n",
384 "-\n",
385 "*\n",
386 "/\n",
387 "%\n",
388
389 "&\n",
390 "|\n",
391 "^\n",
392 "<<\n",
393 ">>\n",
394 "&^\n",
395
396 "+=\n",
397 "-=\n",
398 "*=\n",
399 "/=\n",
400 "%=\n",
401
402 "&=\n",
403 "|=\n",
404 "^=\n",
405 "<<=\n",
406 ">>=\n",
407 "&^=\n",
408
409 "&&\n",
410 "||\n",
411 "<-\n",
412 "++$\n",
413 "--$\n",
414
415 "==\n",
416 "<\n",
417 ">\n",
418 "=\n",
419 "!\n",
420
421 "!=\n",
422 "<=\n",
423 ">=\n",
424 ":=\n",
425 "...\n",
426
427 "(\n",
428 "[\n",
429 "{\n",
430 ",\n",
431 ".\n",
432
433 ")$\n",
434 "]$\n",
435 "}$\n",
436 "#;\n",
437 ":\n",
438
439 "break$\n",
440 "case\n",
441 "chan\n",
442 "const\n",
443 "continue$\n",
444
445 "default\n",
446 "defer\n",
447 "else\n",
448 "fallthrough$\n",
449 "for\n",
450
451 "func\n",
452 "go\n",
453 "goto\n",
454 "if\n",
455 "import\n",
456
457 "interface\n",
458 "map\n",
459 "package\n",
460 "range\n",
461 "return$\n",
462
463 "select\n",
464 "struct\n",
465 "switch\n",
466 "type\n",
467 "var\n",
468
469 "foo$//comment\n",
470 "foo$//comment",
471 "foo$/*comment*/\n",
472 "foo$/*\n*/",
473 "foo$/*comment*/ \n",
474 "foo$/*\n*/ ",
475
476 "foo $// comment\n",
477 "foo $// comment",
478 "foo $/*comment*/\n",
479 "foo $/*\n*/",
480 "foo $/* */ /* \n */ bar$/**/\n",
481 "foo $/*0*/ /*1*/ /*2*/\n",
482
483 "foo $/*comment*/ \n",
484 "foo $/*0*/ /*1*/ /*2*/ \n",
485 "foo $/**/ /*-------------*/ /*----\n*/bar $/* \n*/baa$\n",
486 "foo $/* an EOF terminates a line */",
487 "foo $/* an EOF terminates a line */ /*",
488 "foo $/* an EOF terminates a line */ //",
489
490 "package main$\n\nfunc main() {\n\tif {\n\t\treturn /* */ }$\n}$\n",
491 "package main$",
492 }
493
494 func TestSemis(t *testing.T) {
495 for _, line := range lines {
496 checkSemi(t, line, 0)
497 checkSemi(t, line, ScanComments)
498
499
500
501 for i := len(line) - 1; i >= 0 && line[i] == '\n'; i-- {
502 checkSemi(t, line[0:i], 0)
503 checkSemi(t, line[0:i], ScanComments)
504 }
505 }
506 }
507
508 type segment struct {
509 srcline string
510 filename string
511 line, column int
512 }
513
514 var segments = []segment{
515
516 {" line1", "TestLineDirectives", 1, 3},
517 {"\nline2", "TestLineDirectives", 2, 1},
518 {"\nline3 //line File1.go:100", "TestLineDirectives", 3, 1},
519 {"\nline4", "TestLineDirectives", 4, 1},
520 {"\n//line File1.go:100\n line100", "File1.go", 100, 0},
521 {"\n//line \t :42\n line1", " \t ", 42, 0},
522 {"\n//line File2.go:200\n line200", "File2.go", 200, 0},
523 {"\n//line foo\t:42\n line42", "foo\t", 42, 0},
524 {"\n //line foo:42\n line43", "foo\t", 44, 0},
525 {"\n//line foo 42\n line44", "foo\t", 46, 0},
526 {"\n//line /bar:42\n line45", "/bar", 42, 0},
527 {"\n//line ./foo:42\n line46", "foo", 42, 0},
528 {"\n//line a/b/c/File1.go:100\n line100", "a/b/c/File1.go", 100, 0},
529 {"\n//line c:\\bar:42\n line200", "c:\\bar", 42, 0},
530 {"\n//line c:\\dir\\File1.go:100\n line201", "c:\\dir\\File1.go", 100, 0},
531
532
533 {"\n//line :100\na1", "", 100, 0},
534 {"\n//line bar:100\nb1", "bar", 100, 0},
535 {"\n//line :100:10\nc1", "bar", 100, 10},
536 {"\n//line foo:100:10\nd1", "foo", 100, 10},
537
538 {"\n/*line :100*/a2", "", 100, 0},
539 {"\n/*line bar:100*/b2", "bar", 100, 0},
540 {"\n/*line :100:10*/c2", "bar", 100, 10},
541 {"\n/*line foo:100:10*/d2", "foo", 100, 10},
542 {"\n/*line foo:100:10*/ e2", "foo", 100, 14},
543 {"\n/*line foo:100:10*/\n\nf2", "foo", 102, 1},
544 }
545
546 var dirsegments = []segment{
547
548 {" line1", "TestLineDir/TestLineDirectives", 1, 3},
549 {"\n//line File1.go:100\n line100", "TestLineDir/File1.go", 100, 0},
550 }
551
552 var dirUnixSegments = []segment{
553 {"\n//line /bar:42\n line42", "/bar", 42, 0},
554 }
555
556 var dirWindowsSegments = []segment{
557 {"\n//line c:\\bar:42\n line42", "c:\\bar", 42, 0},
558 }
559
560
561 func TestLineDirectives(t *testing.T) {
562 testSegments(t, segments, "TestLineDirectives")
563 testSegments(t, dirsegments, "TestLineDir/TestLineDirectives")
564 if runtime.GOOS == "windows" {
565 testSegments(t, dirWindowsSegments, "TestLineDir/TestLineDirectives")
566 } else {
567 testSegments(t, dirUnixSegments, "TestLineDir/TestLineDirectives")
568 }
569 }
570
571 func testSegments(t *testing.T, segments []segment, filename string) {
572 var src string
573 for _, e := range segments {
574 src += e.srcline
575 }
576
577
578 var S Scanner
579 file := fset.AddFile(filename, fset.Base(), len(src))
580 S.Init(file, []byte(src), func(pos token.Position, msg string) { t.Error(Error{pos, msg}) }, dontInsertSemis)
581 for _, s := range segments {
582 p, _, lit := S.Scan()
583 pos := file.Position(p)
584 checkPos(t, lit, p, token.Position{
585 Filename: s.filename,
586 Offset: pos.Offset,
587 Line: s.line,
588 Column: s.column,
589 })
590 }
591
592 if S.ErrorCount != 0 {
593 t.Errorf("got %d errors", S.ErrorCount)
594 }
595 }
596
597
598
599 var invalidSegments = []segment{
600 {"\n//line :1:1\n//line foo:42 extra text\ndummy", "invalid line number: 42 extra text", 1, 12},
601 {"\n//line :2:1\n//line foobar:\ndummy", "invalid line number: ", 2, 15},
602 {"\n//line :5:1\n//line :0\ndummy", "invalid line number: 0", 5, 9},
603 {"\n//line :10:1\n//line :1:0\ndummy", "invalid column number: 0", 10, 11},
604 {"\n//line :1:1\n//line :foo:0\ndummy", "invalid line number: 0", 1, 13},
605 }
606
607
608 func TestInvalidLineDirectives(t *testing.T) {
609
610 var src string
611 for _, e := range invalidSegments {
612 src += e.srcline
613 }
614
615
616 var S Scanner
617 var s segment
618 file := fset.AddFile(filepath.Join("dir", "TestInvalidLineDirectives"), fset.Base(), len(src))
619 S.Init(file, []byte(src), func(pos token.Position, msg string) {
620 if msg != s.filename {
621 t.Errorf("got error %q; want %q", msg, s.filename)
622 }
623 if pos.Line != s.line || pos.Column != s.column {
624 t.Errorf("got position %d:%d; want %d:%d", pos.Line, pos.Column, s.line, s.column)
625 }
626 }, dontInsertSemis)
627 for _, s = range invalidSegments {
628 S.Scan()
629 }
630
631 if S.ErrorCount != len(invalidSegments) {
632 t.Errorf("got %d errors; want %d", S.ErrorCount, len(invalidSegments))
633 }
634 }
635
636
637 func TestInit(t *testing.T) {
638 var s Scanner
639
640
641 src1 := "if true { }"
642 f1 := fset.AddFile("src1", fset.Base(), len(src1))
643 s.Init(f1, []byte(src1), nil, dontInsertSemis)
644 if f1.Size() != len(src1) {
645 t.Errorf("bad file size: got %d, expected %d", f1.Size(), len(src1))
646 }
647 s.Scan()
648 s.Scan()
649 _, tok, _ := s.Scan()
650 if tok != token.LBRACE {
651 t.Errorf("bad token: got %s, expected %s", tok, token.LBRACE)
652 }
653
654
655 src2 := "go true { ]"
656 f2 := fset.AddFile("src2", fset.Base(), len(src2))
657 s.Init(f2, []byte(src2), nil, dontInsertSemis)
658 if f2.Size() != len(src2) {
659 t.Errorf("bad file size: got %d, expected %d", f2.Size(), len(src2))
660 }
661 _, tok, _ = s.Scan()
662 if tok != token.GO {
663 t.Errorf("bad token: got %s, expected %s", tok, token.GO)
664 }
665
666 if s.ErrorCount != 0 {
667 t.Errorf("found %d errors", s.ErrorCount)
668 }
669 }
670
671 func TestStdErrorHander(t *testing.T) {
672 const src = "@\n" +
673 "@ @\n" +
674 "//line File2:20\n" +
675 "@\n" +
676 "//line File2:1\n" +
677 "@ @\n" +
678 "//line File1:1\n" +
679 "@ @ @"
680
681 var list ErrorList
682 eh := func(pos token.Position, msg string) { list.Add(pos, msg) }
683
684 var s Scanner
685 s.Init(fset.AddFile("File1", fset.Base(), len(src)), []byte(src), eh, dontInsertSemis)
686 for {
687 if _, tok, _ := s.Scan(); tok == token.EOF {
688 break
689 }
690 }
691
692 if len(list) != s.ErrorCount {
693 t.Errorf("found %d errors, expected %d", len(list), s.ErrorCount)
694 }
695
696 if len(list) != 9 {
697 t.Errorf("found %d raw errors, expected 9", len(list))
698 PrintError(os.Stderr, list)
699 }
700
701 list.Sort()
702 if len(list) != 9 {
703 t.Errorf("found %d sorted errors, expected 9", len(list))
704 PrintError(os.Stderr, list)
705 }
706
707 list.RemoveMultiples()
708 if len(list) != 4 {
709 t.Errorf("found %d one-per-line errors, expected 4", len(list))
710 PrintError(os.Stderr, list)
711 }
712 }
713
714 type errorCollector struct {
715 cnt int
716 msg string
717 pos token.Position
718 }
719
720 func checkError(t *testing.T, src string, tok token.Token, pos int, lit, err string) {
721 var s Scanner
722 var h errorCollector
723 eh := func(pos token.Position, msg string) {
724 h.cnt++
725 h.msg = msg
726 h.pos = pos
727 }
728 s.Init(fset.AddFile("", fset.Base(), len(src)), []byte(src), eh, ScanComments|dontInsertSemis)
729 _, tok0, lit0 := s.Scan()
730 if tok0 != tok {
731 t.Errorf("%q: got %s, expected %s", src, tok0, tok)
732 }
733 if tok0 != token.ILLEGAL && lit0 != lit {
734 t.Errorf("%q: got literal %q, expected %q", src, lit0, lit)
735 }
736 cnt := 0
737 if err != "" {
738 cnt = 1
739 }
740 if h.cnt != cnt {
741 t.Errorf("%q: got cnt %d, expected %d", src, h.cnt, cnt)
742 }
743 if h.msg != err {
744 t.Errorf("%q: got msg %q, expected %q", src, h.msg, err)
745 }
746 if h.pos.Offset != pos {
747 t.Errorf("%q: got offset %d, expected %d", src, h.pos.Offset, pos)
748 }
749 }
750
751 var errors = []struct {
752 src string
753 tok token.Token
754 pos int
755 lit string
756 err string
757 }{
758 {"\a", token.ILLEGAL, 0, "", "illegal character U+0007"},
759 {`#`, token.ILLEGAL, 0, "", "illegal character U+0023 '#'"},
760 {`…`, token.ILLEGAL, 0, "", "illegal character U+2026 '…'"},
761 {"..", token.PERIOD, 0, "", ""},
762 {`' '`, token.CHAR, 0, `' '`, ""},
763 {`''`, token.CHAR, 0, `''`, "illegal rune literal"},
764 {`'12'`, token.CHAR, 0, `'12'`, "illegal rune literal"},
765 {`'123'`, token.CHAR, 0, `'123'`, "illegal rune literal"},
766 {`'\0'`, token.CHAR, 3, `'\0'`, "illegal character U+0027 ''' in escape sequence"},
767 {`'\07'`, token.CHAR, 4, `'\07'`, "illegal character U+0027 ''' in escape sequence"},
768 {`'\8'`, token.CHAR, 2, `'\8'`, "unknown escape sequence"},
769 {`'\08'`, token.CHAR, 3, `'\08'`, "illegal character U+0038 '8' in escape sequence"},
770 {`'\x'`, token.CHAR, 3, `'\x'`, "illegal character U+0027 ''' in escape sequence"},
771 {`'\x0'`, token.CHAR, 4, `'\x0'`, "illegal character U+0027 ''' in escape sequence"},
772 {`'\x0g'`, token.CHAR, 4, `'\x0g'`, "illegal character U+0067 'g' in escape sequence"},
773 {`'\u'`, token.CHAR, 3, `'\u'`, "illegal character U+0027 ''' in escape sequence"},
774 {`'\u0'`, token.CHAR, 4, `'\u0'`, "illegal character U+0027 ''' in escape sequence"},
775 {`'\u00'`, token.CHAR, 5, `'\u00'`, "illegal character U+0027 ''' in escape sequence"},
776 {`'\u000'`, token.CHAR, 6, `'\u000'`, "illegal character U+0027 ''' in escape sequence"},
777 {`'\u000`, token.CHAR, 6, `'\u000`, "escape sequence not terminated"},
778 {`'\u0000'`, token.CHAR, 0, `'\u0000'`, ""},
779 {`'\U'`, token.CHAR, 3, `'\U'`, "illegal character U+0027 ''' in escape sequence"},
780 {`'\U0'`, token.CHAR, 4, `'\U0'`, "illegal character U+0027 ''' in escape sequence"},
781 {`'\U00'`, token.CHAR, 5, `'\U00'`, "illegal character U+0027 ''' in escape sequence"},
782 {`'\U000'`, token.CHAR, 6, `'\U000'`, "illegal character U+0027 ''' in escape sequence"},
783 {`'\U0000'`, token.CHAR, 7, `'\U0000'`, "illegal character U+0027 ''' in escape sequence"},
784 {`'\U00000'`, token.CHAR, 8, `'\U00000'`, "illegal character U+0027 ''' in escape sequence"},
785 {`'\U000000'`, token.CHAR, 9, `'\U000000'`, "illegal character U+0027 ''' in escape sequence"},
786 {`'\U0000000'`, token.CHAR, 10, `'\U0000000'`, "illegal character U+0027 ''' in escape sequence"},
787 {`'\U0000000`, token.CHAR, 10, `'\U0000000`, "escape sequence not terminated"},
788 {`'\U00000000'`, token.CHAR, 0, `'\U00000000'`, ""},
789 {`'\Uffffffff'`, token.CHAR, 2, `'\Uffffffff'`, "escape sequence is invalid Unicode code point"},
790 {`'`, token.CHAR, 0, `'`, "rune literal not terminated"},
791 {`'\`, token.CHAR, 2, `'\`, "escape sequence not terminated"},
792 {"'\n", token.CHAR, 0, "'", "rune literal not terminated"},
793 {"'\n ", token.CHAR, 0, "'", "rune literal not terminated"},
794 {`""`, token.STRING, 0, `""`, ""},
795 {`"abc`, token.STRING, 0, `"abc`, "string literal not terminated"},
796 {"\"abc\n", token.STRING, 0, `"abc`, "string literal not terminated"},
797 {"\"abc\n ", token.STRING, 0, `"abc`, "string literal not terminated"},
798 {"``", token.STRING, 0, "``", ""},
799 {"`", token.STRING, 0, "`", "raw string literal not terminated"},
800 {"/**/", token.COMMENT, 0, "/**/", ""},
801 {"/*", token.COMMENT, 0, "/*", "comment not terminated"},
802 {"077", token.INT, 0, "077", ""},
803 {"078.", token.FLOAT, 0, "078.", ""},
804 {"07801234567.", token.FLOAT, 0, "07801234567.", ""},
805 {"078e0", token.FLOAT, 0, "078e0", ""},
806 {"0E", token.FLOAT, 2, "0E", "exponent has no digits"},
807 {"078", token.INT, 2, "078", "invalid digit '8' in octal literal"},
808 {"07090000008", token.INT, 3, "07090000008", "invalid digit '9' in octal literal"},
809 {"0x", token.INT, 2, "0x", "hexadecimal literal has no digits"},
810 {"\"abc\x00def\"", token.STRING, 4, "\"abc\x00def\"", "illegal character NUL"},
811 {"\"abc\x80def\"", token.STRING, 4, "\"abc\x80def\"", "illegal UTF-8 encoding"},
812 {"\ufeff\ufeff", token.ILLEGAL, 3, "\ufeff\ufeff", "illegal byte order mark"},
813 {"//\ufeff", token.COMMENT, 2, "//\ufeff", "illegal byte order mark"},
814 {"'\ufeff" + `'`, token.CHAR, 1, "'\ufeff" + `'`, "illegal byte order mark"},
815 {`"` + "abc\ufeffdef" + `"`, token.STRING, 4, `"` + "abc\ufeffdef" + `"`, "illegal byte order mark"},
816 {"abc\x00def", token.IDENT, 3, "abc", "illegal character NUL"},
817 {"abc\x00", token.IDENT, 3, "abc", "illegal character NUL"},
818 }
819
820 func TestScanErrors(t *testing.T) {
821 for _, e := range errors {
822 checkError(t, e.src, e.tok, e.pos, e.lit, e.err)
823 }
824 }
825
826
827 func TestIssue10213(t *testing.T) {
828 const src = `
829 var (
830 A = 1 // foo
831 )
832
833 var (
834 B = 2
835 // foo
836 )
837
838 var C = 3 // foo
839
840 var D = 4
841 // foo
842
843 func anycode() {
844 // foo
845 }
846 `
847 var s Scanner
848 s.Init(fset.AddFile("", fset.Base(), len(src)), []byte(src), nil, 0)
849 for {
850 pos, tok, lit := s.Scan()
851 class := tokenclass(tok)
852 if lit != "" && class != keyword && class != literal && tok != token.SEMICOLON {
853 t.Errorf("%s: tok = %s, lit = %q", fset.Position(pos), tok, lit)
854 }
855 if tok <= token.EOF {
856 break
857 }
858 }
859 }
860
861 func TestIssue28112(t *testing.T) {
862 const src = "... .. 0.. .."
863 tokens := []token.Token{token.ELLIPSIS, token.PERIOD, token.PERIOD, token.FLOAT, token.PERIOD, token.PERIOD, token.PERIOD, token.EOF}
864 var s Scanner
865 s.Init(fset.AddFile("", fset.Base(), len(src)), []byte(src), nil, 0)
866 for _, want := range tokens {
867 pos, got, lit := s.Scan()
868 if got != want {
869 t.Errorf("%s: got %s, want %s", fset.Position(pos), got, want)
870 }
871
872 if tokenclass(got) == literal && lit == "" {
873 t.Errorf("%s: for %s got empty literal string", fset.Position(pos), got)
874 }
875 }
876 }
877
878 func BenchmarkScan(b *testing.B) {
879 b.StopTimer()
880 fset := token.NewFileSet()
881 file := fset.AddFile("", fset.Base(), len(source))
882 var s Scanner
883 b.StartTimer()
884 for i := 0; i < b.N; i++ {
885 s.Init(file, source, nil, ScanComments)
886 for {
887 _, tok, _ := s.Scan()
888 if tok == token.EOF {
889 break
890 }
891 }
892 }
893 }
894
895 func BenchmarkScanFiles(b *testing.B) {
896
897
898 for _, p := range []string{
899 "go/types/expr.go",
900 "go/parser/parser.go",
901 "net/http/server.go",
902 "go/scanner/errors.go",
903 } {
904 b.Run(p, func(b *testing.B) {
905 b.StopTimer()
906 filename := filepath.Join("..", "..", filepath.FromSlash(p))
907 src, err := os.ReadFile(filename)
908 if err != nil {
909 b.Fatal(err)
910 }
911 fset := token.NewFileSet()
912 file := fset.AddFile(filename, fset.Base(), len(src))
913 b.SetBytes(int64(len(src)))
914 var s Scanner
915 b.StartTimer()
916 for i := 0; i < b.N; i++ {
917 s.Init(file, src, nil, ScanComments)
918 for {
919 _, tok, _ := s.Scan()
920 if tok == token.EOF {
921 break
922 }
923 }
924 }
925 })
926 }
927 }
928
929 func TestNumbers(t *testing.T) {
930 for _, test := range []struct {
931 tok token.Token
932 src, tokens, err string
933 }{
934
935 {token.INT, "0b0", "0b0", ""},
936 {token.INT, "0b1010", "0b1010", ""},
937 {token.INT, "0B1110", "0B1110", ""},
938
939 {token.INT, "0b", "0b", "binary literal has no digits"},
940 {token.INT, "0b0190", "0b0190", "invalid digit '9' in binary literal"},
941 {token.INT, "0b01a0", "0b01 a0", ""},
942
943 {token.FLOAT, "0b.", "0b.", "invalid radix point in binary literal"},
944 {token.FLOAT, "0b.1", "0b.1", "invalid radix point in binary literal"},
945 {token.FLOAT, "0b1.0", "0b1.0", "invalid radix point in binary literal"},
946 {token.FLOAT, "0b1e10", "0b1e10", "'e' exponent requires decimal mantissa"},
947 {token.FLOAT, "0b1P-1", "0b1P-1", "'P' exponent requires hexadecimal mantissa"},
948
949 {token.IMAG, "0b10i", "0b10i", ""},
950 {token.IMAG, "0b10.0i", "0b10.0i", "invalid radix point in binary literal"},
951
952
953 {token.INT, "0o0", "0o0", ""},
954 {token.INT, "0o1234", "0o1234", ""},
955 {token.INT, "0O1234", "0O1234", ""},
956
957 {token.INT, "0o", "0o", "octal literal has no digits"},
958 {token.INT, "0o8123", "0o8123", "invalid digit '8' in octal literal"},
959 {token.INT, "0o1293", "0o1293", "invalid digit '9' in octal literal"},
960 {token.INT, "0o12a3", "0o12 a3", ""},
961
962 {token.FLOAT, "0o.", "0o.", "invalid radix point in octal literal"},
963 {token.FLOAT, "0o.2", "0o.2", "invalid radix point in octal literal"},
964 {token.FLOAT, "0o1.2", "0o1.2", "invalid radix point in octal literal"},
965 {token.FLOAT, "0o1E+2", "0o1E+2", "'E' exponent requires decimal mantissa"},
966 {token.FLOAT, "0o1p10", "0o1p10", "'p' exponent requires hexadecimal mantissa"},
967
968 {token.IMAG, "0o10i", "0o10i", ""},
969 {token.IMAG, "0o10e0i", "0o10e0i", "'e' exponent requires decimal mantissa"},
970
971
972 {token.INT, "0", "0", ""},
973 {token.INT, "0123", "0123", ""},
974
975 {token.INT, "08123", "08123", "invalid digit '8' in octal literal"},
976 {token.INT, "01293", "01293", "invalid digit '9' in octal literal"},
977 {token.INT, "0F.", "0 F .", ""},
978 {token.INT, "0123F.", "0123 F .", ""},
979 {token.INT, "0123456x", "0123456 x", ""},
980
981
982 {token.INT, "1", "1", ""},
983 {token.INT, "1234", "1234", ""},
984
985 {token.INT, "1f", "1 f", ""},
986
987 {token.IMAG, "0i", "0i", ""},
988 {token.IMAG, "0678i", "0678i", ""},
989
990
991 {token.FLOAT, "0.", "0.", ""},
992 {token.FLOAT, "123.", "123.", ""},
993 {token.FLOAT, "0123.", "0123.", ""},
994
995 {token.FLOAT, ".0", ".0", ""},
996 {token.FLOAT, ".123", ".123", ""},
997 {token.FLOAT, ".0123", ".0123", ""},
998
999 {token.FLOAT, "0.0", "0.0", ""},
1000 {token.FLOAT, "123.123", "123.123", ""},
1001 {token.FLOAT, "0123.0123", "0123.0123", ""},
1002
1003 {token.FLOAT, "0e0", "0e0", ""},
1004 {token.FLOAT, "123e+0", "123e+0", ""},
1005 {token.FLOAT, "0123E-1", "0123E-1", ""},
1006
1007 {token.FLOAT, "0.e+1", "0.e+1", ""},
1008 {token.FLOAT, "123.E-10", "123.E-10", ""},
1009 {token.FLOAT, "0123.e123", "0123.e123", ""},
1010
1011 {token.FLOAT, ".0e-1", ".0e-1", ""},
1012 {token.FLOAT, ".123E+10", ".123E+10", ""},
1013 {token.FLOAT, ".0123E123", ".0123E123", ""},
1014
1015 {token.FLOAT, "0.0e1", "0.0e1", ""},
1016 {token.FLOAT, "123.123E-10", "123.123E-10", ""},
1017 {token.FLOAT, "0123.0123e+456", "0123.0123e+456", ""},
1018
1019 {token.FLOAT, "0e", "0e", "exponent has no digits"},
1020 {token.FLOAT, "0E+", "0E+", "exponent has no digits"},
1021 {token.FLOAT, "1e+f", "1e+ f", "exponent has no digits"},
1022 {token.FLOAT, "0p0", "0p0", "'p' exponent requires hexadecimal mantissa"},
1023 {token.FLOAT, "1.0P-1", "1.0P-1", "'P' exponent requires hexadecimal mantissa"},
1024
1025 {token.IMAG, "0.i", "0.i", ""},
1026 {token.IMAG, ".123i", ".123i", ""},
1027 {token.IMAG, "123.123i", "123.123i", ""},
1028 {token.IMAG, "123e+0i", "123e+0i", ""},
1029 {token.IMAG, "123.E-10i", "123.E-10i", ""},
1030 {token.IMAG, ".123E+10i", ".123E+10i", ""},
1031
1032
1033 {token.INT, "0x0", "0x0", ""},
1034 {token.INT, "0x1234", "0x1234", ""},
1035 {token.INT, "0xcafef00d", "0xcafef00d", ""},
1036 {token.INT, "0XCAFEF00D", "0XCAFEF00D", ""},
1037
1038 {token.INT, "0x", "0x", "hexadecimal literal has no digits"},
1039 {token.INT, "0x1g", "0x1 g", ""},
1040
1041 {token.IMAG, "0xf00i", "0xf00i", ""},
1042
1043
1044 {token.FLOAT, "0x0p0", "0x0p0", ""},
1045 {token.FLOAT, "0x12efp-123", "0x12efp-123", ""},
1046 {token.FLOAT, "0xABCD.p+0", "0xABCD.p+0", ""},
1047 {token.FLOAT, "0x.0189P-0", "0x.0189P-0", ""},
1048 {token.FLOAT, "0x1.ffffp+1023", "0x1.ffffp+1023", ""},
1049
1050 {token.FLOAT, "0x.", "0x.", "hexadecimal literal has no digits"},
1051 {token.FLOAT, "0x0.", "0x0.", "hexadecimal mantissa requires a 'p' exponent"},
1052 {token.FLOAT, "0x.0", "0x.0", "hexadecimal mantissa requires a 'p' exponent"},
1053 {token.FLOAT, "0x1.1", "0x1.1", "hexadecimal mantissa requires a 'p' exponent"},
1054 {token.FLOAT, "0x1.1e0", "0x1.1e0", "hexadecimal mantissa requires a 'p' exponent"},
1055 {token.FLOAT, "0x1.2gp1a", "0x1.2 gp1a", "hexadecimal mantissa requires a 'p' exponent"},
1056 {token.FLOAT, "0x0p", "0x0p", "exponent has no digits"},
1057 {token.FLOAT, "0xeP-", "0xeP-", "exponent has no digits"},
1058 {token.FLOAT, "0x1234PAB", "0x1234P AB", "exponent has no digits"},
1059 {token.FLOAT, "0x1.2p1a", "0x1.2p1 a", ""},
1060
1061 {token.IMAG, "0xf00.bap+12i", "0xf00.bap+12i", ""},
1062
1063
1064 {token.INT, "0b_1000_0001", "0b_1000_0001", ""},
1065 {token.INT, "0o_600", "0o_600", ""},
1066 {token.INT, "0_466", "0_466", ""},
1067 {token.INT, "1_000", "1_000", ""},
1068 {token.FLOAT, "1_000.000_1", "1_000.000_1", ""},
1069 {token.IMAG, "10e+1_2_3i", "10e+1_2_3i", ""},
1070 {token.INT, "0x_f00d", "0x_f00d", ""},
1071 {token.FLOAT, "0x_f00d.0p1_2", "0x_f00d.0p1_2", ""},
1072
1073 {token.INT, "0b__1000", "0b__1000", "'_' must separate successive digits"},
1074 {token.INT, "0o60___0", "0o60___0", "'_' must separate successive digits"},
1075 {token.INT, "0466_", "0466_", "'_' must separate successive digits"},
1076 {token.FLOAT, "1_.", "1_.", "'_' must separate successive digits"},
1077 {token.FLOAT, "0._1", "0._1", "'_' must separate successive digits"},
1078 {token.FLOAT, "2.7_e0", "2.7_e0", "'_' must separate successive digits"},
1079 {token.IMAG, "10e+12_i", "10e+12_i", "'_' must separate successive digits"},
1080 {token.INT, "0x___0", "0x___0", "'_' must separate successive digits"},
1081 {token.FLOAT, "0x1.0_p0", "0x1.0_p0", "'_' must separate successive digits"},
1082 } {
1083 var s Scanner
1084 var err string
1085 s.Init(fset.AddFile("", fset.Base(), len(test.src)), []byte(test.src), func(_ token.Position, msg string) {
1086 if err == "" {
1087 err = msg
1088 }
1089 }, 0)
1090 for i, want := range strings.Split(test.tokens, " ") {
1091 err = ""
1092 _, tok, lit := s.Scan()
1093
1094
1095 switch tok {
1096 case token.PERIOD:
1097 lit = "."
1098 case token.ADD:
1099 lit = "+"
1100 case token.SUB:
1101 lit = "-"
1102 }
1103
1104 if i == 0 {
1105 if tok != test.tok {
1106 t.Errorf("%q: got token %s; want %s", test.src, tok, test.tok)
1107 }
1108 if err != test.err {
1109 t.Errorf("%q: got error %q; want %q", test.src, err, test.err)
1110 }
1111 }
1112
1113 if lit != want {
1114 t.Errorf("%q: got literal %q (%s); want %s", test.src, lit, tok, want)
1115 }
1116 }
1117
1118
1119 _, tok, _ := s.Scan()
1120 if tok == token.SEMICOLON {
1121 _, tok, _ = s.Scan()
1122 }
1123 if tok != token.EOF {
1124 t.Errorf("%q: got %s; want EOF", test.src, tok)
1125 }
1126 }
1127 }
1128
View as plain text