Source file src/go/scanner/scanner_test.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     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 /* class */ (
    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  	// Special tokens
    45  	{token.COMMENT, "/* a comment */", special},
    46  	{token.COMMENT, "// a comment \n", special},
    47  	{token.COMMENT, "/*\r*/", special},
    48  	{token.COMMENT, "/**\r/*/", special}, // issue 11151
    49  	{token.COMMENT, "/**\r\r/*/", special},
    50  	{token.COMMENT, "//\r\n", special},
    51  
    52  	// Identifiers and basic type literals
    53  	{token.IDENT, "foobar", literal},
    54  	{token.IDENT, "a۰۱۸", literal},
    55  	{token.IDENT, "foo६४", literal},
    56  	{token.IDENT, "bar9876", literal},
    57  	{token.IDENT, "ŝ", literal},    // was bug (issue 4000)
    58  	{token.IDENT, "ŝfoo", literal}, // was bug (issue 4000)
    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  	// Operators and delimiters
    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  	// Keywords
   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" // to separate tokens
   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  	// Check cleaned filenames so that we don't have to worry about
   210  	// different os.PathSeparator values.
   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  // Verify that calling Scan() provides the correct results.
   226  func TestScan(t *testing.T) {
   227  	whitespace_linecount := newlineCount(whitespace)
   228  
   229  	// error handler
   230  	eh := func(_ token.Position, msg string) {
   231  		t.Errorf("error handler called (msg = %s)", msg)
   232  	}
   233  
   234  	// verify scan
   235  	var s Scanner
   236  	s.Init(fset.AddFile("", fset.Base(), len(source)), source, eh, ScanComments|dontInsertSemis)
   237  
   238  	// set up expected position
   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  		// check position
   251  		if tok == token.EOF {
   252  			// correction for EOF
   253  			epos.Line = newlineCount(string(source))
   254  			epos.Column = 2
   255  		}
   256  		checkPos(t, lit, pos, epos)
   257  
   258  		// check token
   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  		// check token class
   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  		// check literal
   274  		elit := ""
   275  		switch e.tok {
   276  		case token.COMMENT:
   277  			// no CRs in comments
   278  			elit = string(stripCR([]byte(e.lit), e.lit[1] == '*'))
   279  			//-style comment literal doesn't contain newline
   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  				// no CRs in raw string literals
   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  		// update position
   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, input, want string, mode Mode) {
   338  	if mode&ScanComments == 0 {
   339  		want = strings.ReplaceAll(want, "COMMENT ", "")
   340  		want = strings.ReplaceAll(want, " COMMENT", "") // if at end
   341  		want = strings.ReplaceAll(want, "COMMENT", "")  // if sole token
   342  	}
   343  
   344  	file := fset.AddFile("TestSemis", fset.Base(), len(input))
   345  	var scan Scanner
   346  	scan.Init(file, []byte(input), nil, mode)
   347  	var tokens []string
   348  	for {
   349  		pos, tok, lit := scan.Scan()
   350  		if tok == token.EOF {
   351  			break
   352  		}
   353  		if tok == token.SEMICOLON && lit != ";" {
   354  			// Artificial semicolon:
   355  			// assert that position is EOF or that of a newline.
   356  			off := file.Offset(pos)
   357  			if off != len(input) && input[off] != '\n' {
   358  				t.Errorf("scanning <<%s>>, got SEMICOLON at offset %d, want newline or EOF", input, off)
   359  			}
   360  		}
   361  		lit = tok.String() // "\n" => ";"
   362  		tokens = append(tokens, lit)
   363  	}
   364  	if got := strings.Join(tokens, " "); got != want {
   365  		t.Errorf("scanning <<%s>>, got [%s], want [%s]", input, got, want)
   366  	}
   367  }
   368  
   369  var semicolonTests = [...]struct{ input, want string }{
   370  	{"", ""},
   371  	{"\ufeff;", ";"}, // first BOM is ignored
   372  	{";", ";"},
   373  	{"foo\n", "IDENT ;"},
   374  	{"123\n", "INT ;"},
   375  	{"1.2\n", "FLOAT ;"},
   376  	{"'x'\n", "CHAR ;"},
   377  	{`"x"` + "\n", "STRING ;"},
   378  	{"`x`\n", "STRING ;"},
   379  
   380  	{"+\n", "+"},
   381  	{"-\n", "-"},
   382  	{"*\n", "*"},
   383  	{"/\n", "/"},
   384  	{"%\n", "%"},
   385  
   386  	{"&\n", "&"},
   387  	{"|\n", "|"},
   388  	{"^\n", "^"},
   389  	{"<<\n", "<<"},
   390  	{">>\n", ">>"},
   391  	{"&^\n", "&^"},
   392  
   393  	{"+=\n", "+="},
   394  	{"-=\n", "-="},
   395  	{"*=\n", "*="},
   396  	{"/=\n", "/="},
   397  	{"%=\n", "%="},
   398  
   399  	{"&=\n", "&="},
   400  	{"|=\n", "|="},
   401  	{"^=\n", "^="},
   402  	{"<<=\n", "<<="},
   403  	{">>=\n", ">>="},
   404  	{"&^=\n", "&^="},
   405  
   406  	{"&&\n", "&&"},
   407  	{"||\n", "||"},
   408  	{"<-\n", "<-"},
   409  	{"++\n", "++ ;"},
   410  	{"--\n", "-- ;"},
   411  
   412  	{"==\n", "=="},
   413  	{"<\n", "<"},
   414  	{">\n", ">"},
   415  	{"=\n", "="},
   416  	{"!\n", "!"},
   417  
   418  	{"!=\n", "!="},
   419  	{"<=\n", "<="},
   420  	{">=\n", ">="},
   421  	{":=\n", ":="},
   422  	{"...\n", "..."},
   423  
   424  	{"(\n", "("},
   425  	{"[\n", "["},
   426  	{"{\n", "{"},
   427  	{",\n", ","},
   428  	{".\n", "."},
   429  
   430  	{")\n", ") ;"},
   431  	{"]\n", "] ;"},
   432  	{"}\n", "} ;"},
   433  	{";\n", ";"},
   434  	{":\n", ":"},
   435  
   436  	{"break\n", "break ;"},
   437  	{"case\n", "case"},
   438  	{"chan\n", "chan"},
   439  	{"const\n", "const"},
   440  	{"continue\n", "continue ;"},
   441  
   442  	{"default\n", "default"},
   443  	{"defer\n", "defer"},
   444  	{"else\n", "else"},
   445  	{"fallthrough\n", "fallthrough ;"},
   446  	{"for\n", "for"},
   447  
   448  	{"func\n", "func"},
   449  	{"go\n", "go"},
   450  	{"goto\n", "goto"},
   451  	{"if\n", "if"},
   452  	{"import\n", "import"},
   453  
   454  	{"interface\n", "interface"},
   455  	{"map\n", "map"},
   456  	{"package\n", "package"},
   457  	{"range\n", "range"},
   458  	{"return\n", "return ;"},
   459  
   460  	{"select\n", "select"},
   461  	{"struct\n", "struct"},
   462  	{"switch\n", "switch"},
   463  	{"type\n", "type"},
   464  	{"var\n", "var"},
   465  
   466  	{"foo//comment\n", "IDENT COMMENT ;"},
   467  	{"foo//comment", "IDENT COMMENT ;"},
   468  	{"foo/*comment*/\n", "IDENT COMMENT ;"},
   469  	{"foo/*\n*/", "IDENT COMMENT ;"},
   470  	{"foo/*comment*/    \n", "IDENT COMMENT ;"},
   471  	{"foo/*\n*/    ", "IDENT COMMENT ;"},
   472  
   473  	{"foo    // comment\n", "IDENT COMMENT ;"},
   474  	{"foo    // comment", "IDENT COMMENT ;"},
   475  	{"foo    /*comment*/\n", "IDENT COMMENT ;"},
   476  	{"foo    /*\n*/", "IDENT COMMENT ;"},
   477  	{"foo    /*  */ /* \n */ bar/**/\n", "IDENT COMMENT COMMENT ; IDENT COMMENT ;"},
   478  	{"foo    /*0*/ /*1*/ /*2*/\n", "IDENT COMMENT COMMENT COMMENT ;"},
   479  
   480  	{"foo    /*comment*/    \n", "IDENT COMMENT ;"},
   481  	{"foo    /*0*/ /*1*/ /*2*/    \n", "IDENT COMMENT COMMENT COMMENT ;"},
   482  	{"foo	/**/ /*-------------*/       /*----\n*/bar       /*  \n*/baa\n", "IDENT COMMENT COMMENT COMMENT ; IDENT COMMENT ; IDENT ;"},
   483  	{"foo    /* an EOF terminates a line */", "IDENT COMMENT ;"},
   484  	{"foo    /* an EOF terminates a line */ /*", "IDENT COMMENT COMMENT ;"},
   485  	{"foo    /* an EOF terminates a line */ //", "IDENT COMMENT COMMENT ;"},
   486  
   487  	{"package main\n\nfunc main() {\n\tif {\n\t\treturn /* */ }\n}\n", "package IDENT ; func IDENT ( ) { if { return COMMENT } ; } ;"},
   488  	{"package main", "package IDENT ;"},
   489  }
   490  
   491  func TestSemicolons(t *testing.T) {
   492  	for _, test := range semicolonTests {
   493  		input, want := test.input, test.want
   494  		checkSemi(t, input, want, 0)
   495  		checkSemi(t, input, want, ScanComments)
   496  
   497  		// if the input ended in newlines, the input must tokenize the
   498  		// same with or without those newlines
   499  		for i := len(input) - 1; i >= 0 && input[i] == '\n'; i-- {
   500  			checkSemi(t, input[0:i], want, 0)
   501  			checkSemi(t, input[0:i], want, ScanComments)
   502  		}
   503  	}
   504  }
   505  
   506  type segment struct {
   507  	srcline      string // a line of source text
   508  	filename     string // filename for current token; error message for invalid line directives
   509  	line, column int    // line and column for current token; error position for invalid line directives
   510  }
   511  
   512  var segments = []segment{
   513  	// exactly one token per line since the test consumes one token per segment
   514  	{"  line1", "TestLineDirectives", 1, 3},
   515  	{"\nline2", "TestLineDirectives", 2, 1},
   516  	{"\nline3  //line File1.go:100", "TestLineDirectives", 3, 1}, // bad line comment, ignored
   517  	{"\nline4", "TestLineDirectives", 4, 1},
   518  	{"\n//line File1.go:100\n  line100", "File1.go", 100, 0},
   519  	{"\n//line  \t :42\n  line1", " \t ", 42, 0},
   520  	{"\n//line File2.go:200\n  line200", "File2.go", 200, 0},
   521  	{"\n//line foo\t:42\n  line42", "foo\t", 42, 0},
   522  	{"\n //line foo:42\n  line43", "foo\t", 44, 0}, // bad line comment, ignored (use existing, prior filename)
   523  	{"\n//line foo 42\n  line44", "foo\t", 46, 0},  // bad line comment, ignored (use existing, prior filename)
   524  	{"\n//line /bar:42\n  line45", "/bar", 42, 0},
   525  	{"\n//line ./foo:42\n  line46", "foo", 42, 0},
   526  	{"\n//line a/b/c/File1.go:100\n  line100", "a/b/c/File1.go", 100, 0},
   527  	{"\n//line c:\\bar:42\n  line200", "c:\\bar", 42, 0},
   528  	{"\n//line c:\\dir\\File1.go:100\n  line201", "c:\\dir\\File1.go", 100, 0},
   529  
   530  	// tests for new line directive syntax
   531  	{"\n//line :100\na1", "", 100, 0}, // missing filename means empty filename
   532  	{"\n//line bar:100\nb1", "bar", 100, 0},
   533  	{"\n//line :100:10\nc1", "bar", 100, 10}, // missing filename means current filename
   534  	{"\n//line foo:100:10\nd1", "foo", 100, 10},
   535  
   536  	{"\n/*line :100*/a2", "", 100, 0}, // missing filename means empty filename
   537  	{"\n/*line bar:100*/b2", "bar", 100, 0},
   538  	{"\n/*line :100:10*/c2", "bar", 100, 10}, // missing filename means current filename
   539  	{"\n/*line foo:100:10*/d2", "foo", 100, 10},
   540  	{"\n/*line foo:100:10*/    e2", "foo", 100, 14}, // line-directive relative column
   541  	{"\n/*line foo:100:10*/\n\nf2", "foo", 102, 1},  // absolute column since on new line
   542  }
   543  
   544  var dirsegments = []segment{
   545  	// exactly one token per line since the test consumes one token per segment
   546  	{"  line1", "TestLineDir/TestLineDirectives", 1, 3},
   547  	{"\n//line File1.go:100\n  line100", "TestLineDir/File1.go", 100, 0},
   548  }
   549  
   550  var dirUnixSegments = []segment{
   551  	{"\n//line /bar:42\n  line42", "/bar", 42, 0},
   552  }
   553  
   554  var dirWindowsSegments = []segment{
   555  	{"\n//line c:\\bar:42\n  line42", "c:\\bar", 42, 0},
   556  }
   557  
   558  // Verify that line directives are interpreted correctly.
   559  func TestLineDirectives(t *testing.T) {
   560  	testSegments(t, segments, "TestLineDirectives")
   561  	testSegments(t, dirsegments, "TestLineDir/TestLineDirectives")
   562  	if runtime.GOOS == "windows" {
   563  		testSegments(t, dirWindowsSegments, "TestLineDir/TestLineDirectives")
   564  	} else {
   565  		testSegments(t, dirUnixSegments, "TestLineDir/TestLineDirectives")
   566  	}
   567  }
   568  
   569  func testSegments(t *testing.T, segments []segment, filename string) {
   570  	var src string
   571  	for _, e := range segments {
   572  		src += e.srcline
   573  	}
   574  
   575  	// verify scan
   576  	var S Scanner
   577  	file := fset.AddFile(filename, fset.Base(), len(src))
   578  	S.Init(file, []byte(src), func(pos token.Position, msg string) { t.Error(Error{pos, msg}) }, dontInsertSemis)
   579  	for _, s := range segments {
   580  		p, _, lit := S.Scan()
   581  		pos := file.Position(p)
   582  		checkPos(t, lit, p, token.Position{
   583  			Filename: s.filename,
   584  			Offset:   pos.Offset,
   585  			Line:     s.line,
   586  			Column:   s.column,
   587  		})
   588  	}
   589  
   590  	if S.ErrorCount != 0 {
   591  		t.Errorf("got %d errors", S.ErrorCount)
   592  	}
   593  }
   594  
   595  // The filename is used for the error message in these test cases.
   596  // The first line directive is valid and used to control the expected error line.
   597  var invalidSegments = []segment{
   598  	{"\n//line :1:1\n//line foo:42 extra text\ndummy", "invalid line number: 42 extra text", 1, 12},
   599  	{"\n//line :2:1\n//line foobar:\ndummy", "invalid line number: ", 2, 15},
   600  	{"\n//line :5:1\n//line :0\ndummy", "invalid line number: 0", 5, 9},
   601  	{"\n//line :10:1\n//line :1:0\ndummy", "invalid column number: 0", 10, 11},
   602  	{"\n//line :1:1\n//line :foo:0\ndummy", "invalid line number: 0", 1, 13}, // foo is considered part of the filename
   603  }
   604  
   605  // Verify that invalid line directives get the correct error message.
   606  func TestInvalidLineDirectives(t *testing.T) {
   607  	// make source
   608  	var src string
   609  	for _, e := range invalidSegments {
   610  		src += e.srcline
   611  	}
   612  
   613  	// verify scan
   614  	var S Scanner
   615  	var s segment // current segment
   616  	file := fset.AddFile(filepath.Join("dir", "TestInvalidLineDirectives"), fset.Base(), len(src))
   617  	S.Init(file, []byte(src), func(pos token.Position, msg string) {
   618  		if msg != s.filename {
   619  			t.Errorf("got error %q; want %q", msg, s.filename)
   620  		}
   621  		if pos.Line != s.line || pos.Column != s.column {
   622  			t.Errorf("got position %d:%d; want %d:%d", pos.Line, pos.Column, s.line, s.column)
   623  		}
   624  	}, dontInsertSemis)
   625  	for _, s = range invalidSegments {
   626  		S.Scan()
   627  	}
   628  
   629  	if S.ErrorCount != len(invalidSegments) {
   630  		t.Errorf("got %d errors; want %d", S.ErrorCount, len(invalidSegments))
   631  	}
   632  }
   633  
   634  // Verify that initializing the same scanner more than once works correctly.
   635  func TestInit(t *testing.T) {
   636  	var s Scanner
   637  
   638  	// 1st init
   639  	src1 := "if true { }"
   640  	f1 := fset.AddFile("src1", fset.Base(), len(src1))
   641  	s.Init(f1, []byte(src1), nil, dontInsertSemis)
   642  	if f1.Size() != len(src1) {
   643  		t.Errorf("bad file size: got %d, expected %d", f1.Size(), len(src1))
   644  	}
   645  	s.Scan()              // if
   646  	s.Scan()              // true
   647  	_, tok, _ := s.Scan() // {
   648  	if tok != token.LBRACE {
   649  		t.Errorf("bad token: got %s, expected %s", tok, token.LBRACE)
   650  	}
   651  
   652  	// 2nd init
   653  	src2 := "go true { ]"
   654  	f2 := fset.AddFile("src2", fset.Base(), len(src2))
   655  	s.Init(f2, []byte(src2), nil, dontInsertSemis)
   656  	if f2.Size() != len(src2) {
   657  		t.Errorf("bad file size: got %d, expected %d", f2.Size(), len(src2))
   658  	}
   659  	_, tok, _ = s.Scan() // go
   660  	if tok != token.GO {
   661  		t.Errorf("bad token: got %s, expected %s", tok, token.GO)
   662  	}
   663  
   664  	if s.ErrorCount != 0 {
   665  		t.Errorf("found %d errors", s.ErrorCount)
   666  	}
   667  }
   668  
   669  func TestStdErrorHandler(t *testing.T) {
   670  	const src = "@\n" + // illegal character, cause an error
   671  		"@ @\n" + // two errors on the same line
   672  		"//line File2:20\n" +
   673  		"@\n" + // different file, but same line
   674  		"//line File2:1\n" +
   675  		"@ @\n" + // same file, decreasing line number
   676  		"//line File1:1\n" +
   677  		"@ @ @" // original file, line 1 again
   678  
   679  	var list ErrorList
   680  	eh := func(pos token.Position, msg string) { list.Add(pos, msg) }
   681  
   682  	var s Scanner
   683  	s.Init(fset.AddFile("File1", fset.Base(), len(src)), []byte(src), eh, dontInsertSemis)
   684  	for {
   685  		if _, tok, _ := s.Scan(); tok == token.EOF {
   686  			break
   687  		}
   688  	}
   689  
   690  	if len(list) != s.ErrorCount {
   691  		t.Errorf("found %d errors, expected %d", len(list), s.ErrorCount)
   692  	}
   693  
   694  	if len(list) != 9 {
   695  		t.Errorf("found %d raw errors, expected 9", len(list))
   696  		PrintError(os.Stderr, list)
   697  	}
   698  
   699  	list.Sort()
   700  	if len(list) != 9 {
   701  		t.Errorf("found %d sorted errors, expected 9", len(list))
   702  		PrintError(os.Stderr, list)
   703  	}
   704  
   705  	list.RemoveMultiples()
   706  	if len(list) != 4 {
   707  		t.Errorf("found %d one-per-line errors, expected 4", len(list))
   708  		PrintError(os.Stderr, list)
   709  	}
   710  }
   711  
   712  type errorCollector struct {
   713  	cnt int            // number of errors encountered
   714  	msg string         // last error message encountered
   715  	pos token.Position // last error position encountered
   716  }
   717  
   718  func checkError(t *testing.T, src string, tok token.Token, pos int, lit, err string) {
   719  	var s Scanner
   720  	var h errorCollector
   721  	eh := func(pos token.Position, msg string) {
   722  		h.cnt++
   723  		h.msg = msg
   724  		h.pos = pos
   725  	}
   726  	s.Init(fset.AddFile("", fset.Base(), len(src)), []byte(src), eh, ScanComments|dontInsertSemis)
   727  	_, tok0, lit0 := s.Scan()
   728  	if tok0 != tok {
   729  		t.Errorf("%q: got %s, expected %s", src, tok0, tok)
   730  	}
   731  	if tok0 != token.ILLEGAL && lit0 != lit {
   732  		t.Errorf("%q: got literal %q, expected %q", src, lit0, lit)
   733  	}
   734  	cnt := 0
   735  	if err != "" {
   736  		cnt = 1
   737  	}
   738  	if h.cnt != cnt {
   739  		t.Errorf("%q: got cnt %d, expected %d", src, h.cnt, cnt)
   740  	}
   741  	if h.msg != err {
   742  		t.Errorf("%q: got msg %q, expected %q", src, h.msg, err)
   743  	}
   744  	if h.pos.Offset != pos {
   745  		t.Errorf("%q: got offset %d, expected %d", src, h.pos.Offset, pos)
   746  	}
   747  }
   748  
   749  var errors = []struct {
   750  	src string
   751  	tok token.Token
   752  	pos int
   753  	lit string
   754  	err string
   755  }{
   756  	{"\a", token.ILLEGAL, 0, "", "illegal character U+0007"},
   757  	{`#`, token.ILLEGAL, 0, "", "illegal character U+0023 '#'"},
   758  	{`…`, token.ILLEGAL, 0, "", "illegal character U+2026 '…'"},
   759  	{"..", token.PERIOD, 0, "", ""}, // two periods, not invalid token (issue #28112)
   760  	{`' '`, token.CHAR, 0, `' '`, ""},
   761  	{`''`, token.CHAR, 0, `''`, "illegal rune literal"},
   762  	{`'12'`, token.CHAR, 0, `'12'`, "illegal rune literal"},
   763  	{`'123'`, token.CHAR, 0, `'123'`, "illegal rune literal"},
   764  	{`'\0'`, token.CHAR, 3, `'\0'`, "illegal character U+0027 ''' in escape sequence"},
   765  	{`'\07'`, token.CHAR, 4, `'\07'`, "illegal character U+0027 ''' in escape sequence"},
   766  	{`'\8'`, token.CHAR, 2, `'\8'`, "unknown escape sequence"},
   767  	{`'\08'`, token.CHAR, 3, `'\08'`, "illegal character U+0038 '8' in escape sequence"},
   768  	{`'\x'`, token.CHAR, 3, `'\x'`, "illegal character U+0027 ''' in escape sequence"},
   769  	{`'\x0'`, token.CHAR, 4, `'\x0'`, "illegal character U+0027 ''' in escape sequence"},
   770  	{`'\x0g'`, token.CHAR, 4, `'\x0g'`, "illegal character U+0067 'g' in escape sequence"},
   771  	{`'\u'`, token.CHAR, 3, `'\u'`, "illegal character U+0027 ''' in escape sequence"},
   772  	{`'\u0'`, token.CHAR, 4, `'\u0'`, "illegal character U+0027 ''' in escape sequence"},
   773  	{`'\u00'`, token.CHAR, 5, `'\u00'`, "illegal character U+0027 ''' in escape sequence"},
   774  	{`'\u000'`, token.CHAR, 6, `'\u000'`, "illegal character U+0027 ''' in escape sequence"},
   775  	{`'\u000`, token.CHAR, 6, `'\u000`, "escape sequence not terminated"},
   776  	{`'\u0000'`, token.CHAR, 0, `'\u0000'`, ""},
   777  	{`'\U'`, token.CHAR, 3, `'\U'`, "illegal character U+0027 ''' in escape sequence"},
   778  	{`'\U0'`, token.CHAR, 4, `'\U0'`, "illegal character U+0027 ''' in escape sequence"},
   779  	{`'\U00'`, token.CHAR, 5, `'\U00'`, "illegal character U+0027 ''' in escape sequence"},
   780  	{`'\U000'`, token.CHAR, 6, `'\U000'`, "illegal character U+0027 ''' in escape sequence"},
   781  	{`'\U0000'`, token.CHAR, 7, `'\U0000'`, "illegal character U+0027 ''' in escape sequence"},
   782  	{`'\U00000'`, token.CHAR, 8, `'\U00000'`, "illegal character U+0027 ''' in escape sequence"},
   783  	{`'\U000000'`, token.CHAR, 9, `'\U000000'`, "illegal character U+0027 ''' in escape sequence"},
   784  	{`'\U0000000'`, token.CHAR, 10, `'\U0000000'`, "illegal character U+0027 ''' in escape sequence"},
   785  	{`'\U0000000`, token.CHAR, 10, `'\U0000000`, "escape sequence not terminated"},
   786  	{`'\U00000000'`, token.CHAR, 0, `'\U00000000'`, ""},
   787  	{`'\Uffffffff'`, token.CHAR, 2, `'\Uffffffff'`, "escape sequence is invalid Unicode code point"},
   788  	{`'`, token.CHAR, 0, `'`, "rune literal not terminated"},
   789  	{`'\`, token.CHAR, 2, `'\`, "escape sequence not terminated"},
   790  	{"'\n", token.CHAR, 0, "'", "rune literal not terminated"},
   791  	{"'\n   ", token.CHAR, 0, "'", "rune literal not terminated"},
   792  	{`""`, token.STRING, 0, `""`, ""},
   793  	{`"abc`, token.STRING, 0, `"abc`, "string literal not terminated"},
   794  	{"\"abc\n", token.STRING, 0, `"abc`, "string literal not terminated"},
   795  	{"\"abc\n   ", token.STRING, 0, `"abc`, "string literal not terminated"},
   796  	{"``", token.STRING, 0, "``", ""},
   797  	{"`", token.STRING, 0, "`", "raw string literal not terminated"},
   798  	{"/**/", token.COMMENT, 0, "/**/", ""},
   799  	{"/*", token.COMMENT, 0, "/*", "comment not terminated"},
   800  	{"077", token.INT, 0, "077", ""},
   801  	{"078.", token.FLOAT, 0, "078.", ""},
   802  	{"07801234567.", token.FLOAT, 0, "07801234567.", ""},
   803  	{"078e0", token.FLOAT, 0, "078e0", ""},
   804  	{"0E", token.FLOAT, 2, "0E", "exponent has no digits"}, // issue 17621
   805  	{"078", token.INT, 2, "078", "invalid digit '8' in octal literal"},
   806  	{"07090000008", token.INT, 3, "07090000008", "invalid digit '9' in octal literal"},
   807  	{"0x", token.INT, 2, "0x", "hexadecimal literal has no digits"},
   808  	{"\"abc\x00def\"", token.STRING, 4, "\"abc\x00def\"", "illegal character NUL"},
   809  	{"\"abc\x80def\"", token.STRING, 4, "\"abc\x80def\"", "illegal UTF-8 encoding"},
   810  	{"\ufeff\ufeff", token.ILLEGAL, 3, "\ufeff\ufeff", "illegal byte order mark"},                        // only first BOM is ignored
   811  	{"//\ufeff", token.COMMENT, 2, "//\ufeff", "illegal byte order mark"},                                // only first BOM is ignored
   812  	{"'\ufeff" + `'`, token.CHAR, 1, "'\ufeff" + `'`, "illegal byte order mark"},                         // only first BOM is ignored
   813  	{`"` + "abc\ufeffdef" + `"`, token.STRING, 4, `"` + "abc\ufeffdef" + `"`, "illegal byte order mark"}, // only first BOM is ignored
   814  	{"abc\x00def", token.IDENT, 3, "abc", "illegal character NUL"},
   815  	{"abc\x00", token.IDENT, 3, "abc", "illegal character NUL"},
   816  	{"“abc”", token.ILLEGAL, 0, "abc", `curly quotation mark '“' (use neutral '"')`},
   817  }
   818  
   819  func TestScanErrors(t *testing.T) {
   820  	for _, e := range errors {
   821  		checkError(t, e.src, e.tok, e.pos, e.lit, e.err)
   822  	}
   823  }
   824  
   825  // Verify that no comments show up as literal values when skipping comments.
   826  func TestIssue10213(t *testing.T) {
   827  	const src = `
   828  		var (
   829  			A = 1 // foo
   830  		)
   831  
   832  		var (
   833  			B = 2
   834  			// foo
   835  		)
   836  
   837  		var C = 3 // foo
   838  
   839  		var D = 4
   840  		// foo
   841  
   842  		func anycode() {
   843  		// foo
   844  		}
   845  	`
   846  	var s Scanner
   847  	s.Init(fset.AddFile("", fset.Base(), len(src)), []byte(src), nil, 0)
   848  	for {
   849  		pos, tok, lit := s.Scan()
   850  		class := tokenclass(tok)
   851  		if lit != "" && class != keyword && class != literal && tok != token.SEMICOLON {
   852  			t.Errorf("%s: tok = %s, lit = %q", fset.Position(pos), tok, lit)
   853  		}
   854  		if tok <= token.EOF {
   855  			break
   856  		}
   857  	}
   858  }
   859  
   860  func TestIssue28112(t *testing.T) {
   861  	const src = "... .. 0.. .." // make sure to have stand-alone ".." immediately before EOF to test EOF behavior
   862  	tokens := []token.Token{token.ELLIPSIS, token.PERIOD, token.PERIOD, token.FLOAT, token.PERIOD, token.PERIOD, token.PERIOD, token.EOF}
   863  	var s Scanner
   864  	s.Init(fset.AddFile("", fset.Base(), len(src)), []byte(src), nil, 0)
   865  	for _, want := range tokens {
   866  		pos, got, lit := s.Scan()
   867  		if got != want {
   868  			t.Errorf("%s: got %s, want %s", fset.Position(pos), got, want)
   869  		}
   870  		// literals expect to have a (non-empty) literal string and we don't care about other tokens for this test
   871  		if tokenclass(got) == literal && lit == "" {
   872  			t.Errorf("%s: for %s got empty literal string", fset.Position(pos), got)
   873  		}
   874  	}
   875  }
   876  
   877  func BenchmarkScan(b *testing.B) {
   878  	b.StopTimer()
   879  	fset := token.NewFileSet()
   880  	file := fset.AddFile("", fset.Base(), len(source))
   881  	var s Scanner
   882  	b.StartTimer()
   883  	for i := 0; i < b.N; i++ {
   884  		s.Init(file, source, nil, ScanComments)
   885  		for {
   886  			_, tok, _ := s.Scan()
   887  			if tok == token.EOF {
   888  				break
   889  			}
   890  		}
   891  	}
   892  }
   893  
   894  func BenchmarkScanFiles(b *testing.B) {
   895  	// Scan a few arbitrary large files, and one small one, to provide some
   896  	// variety in benchmarks.
   897  	for _, p := range []string{
   898  		"go/types/expr.go",
   899  		"go/parser/parser.go",
   900  		"net/http/server.go",
   901  		"go/scanner/errors.go",
   902  	} {
   903  		b.Run(p, func(b *testing.B) {
   904  			b.StopTimer()
   905  			filename := filepath.Join("..", "..", filepath.FromSlash(p))
   906  			src, err := os.ReadFile(filename)
   907  			if err != nil {
   908  				b.Fatal(err)
   909  			}
   910  			fset := token.NewFileSet()
   911  			file := fset.AddFile(filename, fset.Base(), len(src))
   912  			b.SetBytes(int64(len(src)))
   913  			var s Scanner
   914  			b.StartTimer()
   915  			for i := 0; i < b.N; i++ {
   916  				s.Init(file, src, nil, ScanComments)
   917  				for {
   918  					_, tok, _ := s.Scan()
   919  					if tok == token.EOF {
   920  						break
   921  					}
   922  				}
   923  			}
   924  		})
   925  	}
   926  }
   927  
   928  func TestNumbers(t *testing.T) {
   929  	for _, test := range []struct {
   930  		tok              token.Token
   931  		src, tokens, err string
   932  	}{
   933  		// binaries
   934  		{token.INT, "0b0", "0b0", ""},
   935  		{token.INT, "0b1010", "0b1010", ""},
   936  		{token.INT, "0B1110", "0B1110", ""},
   937  
   938  		{token.INT, "0b", "0b", "binary literal has no digits"},
   939  		{token.INT, "0b0190", "0b0190", "invalid digit '9' in binary literal"},
   940  		{token.INT, "0b01a0", "0b01 a0", ""}, // only accept 0-9
   941  
   942  		{token.FLOAT, "0b.", "0b.", "invalid radix point in binary literal"},
   943  		{token.FLOAT, "0b.1", "0b.1", "invalid radix point in binary literal"},
   944  		{token.FLOAT, "0b1.0", "0b1.0", "invalid radix point in binary literal"},
   945  		{token.FLOAT, "0b1e10", "0b1e10", "'e' exponent requires decimal mantissa"},
   946  		{token.FLOAT, "0b1P-1", "0b1P-1", "'P' exponent requires hexadecimal mantissa"},
   947  
   948  		{token.IMAG, "0b10i", "0b10i", ""},
   949  		{token.IMAG, "0b10.0i", "0b10.0i", "invalid radix point in binary literal"},
   950  
   951  		// octals
   952  		{token.INT, "0o0", "0o0", ""},
   953  		{token.INT, "0o1234", "0o1234", ""},
   954  		{token.INT, "0O1234", "0O1234", ""},
   955  
   956  		{token.INT, "0o", "0o", "octal literal has no digits"},
   957  		{token.INT, "0o8123", "0o8123", "invalid digit '8' in octal literal"},
   958  		{token.INT, "0o1293", "0o1293", "invalid digit '9' in octal literal"},
   959  		{token.INT, "0o12a3", "0o12 a3", ""}, // only accept 0-9
   960  
   961  		{token.FLOAT, "0o.", "0o.", "invalid radix point in octal literal"},
   962  		{token.FLOAT, "0o.2", "0o.2", "invalid radix point in octal literal"},
   963  		{token.FLOAT, "0o1.2", "0o1.2", "invalid radix point in octal literal"},
   964  		{token.FLOAT, "0o1E+2", "0o1E+2", "'E' exponent requires decimal mantissa"},
   965  		{token.FLOAT, "0o1p10", "0o1p10", "'p' exponent requires hexadecimal mantissa"},
   966  
   967  		{token.IMAG, "0o10i", "0o10i", ""},
   968  		{token.IMAG, "0o10e0i", "0o10e0i", "'e' exponent requires decimal mantissa"},
   969  
   970  		// 0-octals
   971  		{token.INT, "0", "0", ""},
   972  		{token.INT, "0123", "0123", ""},
   973  
   974  		{token.INT, "08123", "08123", "invalid digit '8' in octal literal"},
   975  		{token.INT, "01293", "01293", "invalid digit '9' in octal literal"},
   976  		{token.INT, "0F.", "0 F .", ""}, // only accept 0-9
   977  		{token.INT, "0123F.", "0123 F .", ""},
   978  		{token.INT, "0123456x", "0123456 x", ""},
   979  
   980  		// decimals
   981  		{token.INT, "1", "1", ""},
   982  		{token.INT, "1234", "1234", ""},
   983  
   984  		{token.INT, "1f", "1 f", ""}, // only accept 0-9
   985  
   986  		{token.IMAG, "0i", "0i", ""},
   987  		{token.IMAG, "0678i", "0678i", ""},
   988  
   989  		// decimal floats
   990  		{token.FLOAT, "0.", "0.", ""},
   991  		{token.FLOAT, "123.", "123.", ""},
   992  		{token.FLOAT, "0123.", "0123.", ""},
   993  
   994  		{token.FLOAT, ".0", ".0", ""},
   995  		{token.FLOAT, ".123", ".123", ""},
   996  		{token.FLOAT, ".0123", ".0123", ""},
   997  
   998  		{token.FLOAT, "0.0", "0.0", ""},
   999  		{token.FLOAT, "123.123", "123.123", ""},
  1000  		{token.FLOAT, "0123.0123", "0123.0123", ""},
  1001  
  1002  		{token.FLOAT, "0e0", "0e0", ""},
  1003  		{token.FLOAT, "123e+0", "123e+0", ""},
  1004  		{token.FLOAT, "0123E-1", "0123E-1", ""},
  1005  
  1006  		{token.FLOAT, "0.e+1", "0.e+1", ""},
  1007  		{token.FLOAT, "123.E-10", "123.E-10", ""},
  1008  		{token.FLOAT, "0123.e123", "0123.e123", ""},
  1009  
  1010  		{token.FLOAT, ".0e-1", ".0e-1", ""},
  1011  		{token.FLOAT, ".123E+10", ".123E+10", ""},
  1012  		{token.FLOAT, ".0123E123", ".0123E123", ""},
  1013  
  1014  		{token.FLOAT, "0.0e1", "0.0e1", ""},
  1015  		{token.FLOAT, "123.123E-10", "123.123E-10", ""},
  1016  		{token.FLOAT, "0123.0123e+456", "0123.0123e+456", ""},
  1017  
  1018  		{token.FLOAT, "0e", "0e", "exponent has no digits"},
  1019  		{token.FLOAT, "0E+", "0E+", "exponent has no digits"},
  1020  		{token.FLOAT, "1e+f", "1e+ f", "exponent has no digits"},
  1021  		{token.FLOAT, "0p0", "0p0", "'p' exponent requires hexadecimal mantissa"},
  1022  		{token.FLOAT, "1.0P-1", "1.0P-1", "'P' exponent requires hexadecimal mantissa"},
  1023  
  1024  		{token.IMAG, "0.i", "0.i", ""},
  1025  		{token.IMAG, ".123i", ".123i", ""},
  1026  		{token.IMAG, "123.123i", "123.123i", ""},
  1027  		{token.IMAG, "123e+0i", "123e+0i", ""},
  1028  		{token.IMAG, "123.E-10i", "123.E-10i", ""},
  1029  		{token.IMAG, ".123E+10i", ".123E+10i", ""},
  1030  
  1031  		// hexadecimals
  1032  		{token.INT, "0x0", "0x0", ""},
  1033  		{token.INT, "0x1234", "0x1234", ""},
  1034  		{token.INT, "0xcafef00d", "0xcafef00d", ""},
  1035  		{token.INT, "0XCAFEF00D", "0XCAFEF00D", ""},
  1036  
  1037  		{token.INT, "0x", "0x", "hexadecimal literal has no digits"},
  1038  		{token.INT, "0x1g", "0x1 g", ""},
  1039  
  1040  		{token.IMAG, "0xf00i", "0xf00i", ""},
  1041  
  1042  		// hexadecimal floats
  1043  		{token.FLOAT, "0x0p0", "0x0p0", ""},
  1044  		{token.FLOAT, "0x12efp-123", "0x12efp-123", ""},
  1045  		{token.FLOAT, "0xABCD.p+0", "0xABCD.p+0", ""},
  1046  		{token.FLOAT, "0x.0189P-0", "0x.0189P-0", ""},
  1047  		{token.FLOAT, "0x1.ffffp+1023", "0x1.ffffp+1023", ""},
  1048  
  1049  		{token.FLOAT, "0x.", "0x.", "hexadecimal literal has no digits"},
  1050  		{token.FLOAT, "0x0.", "0x0.", "hexadecimal mantissa requires a 'p' exponent"},
  1051  		{token.FLOAT, "0x.0", "0x.0", "hexadecimal mantissa requires a 'p' exponent"},
  1052  		{token.FLOAT, "0x1.1", "0x1.1", "hexadecimal mantissa requires a 'p' exponent"},
  1053  		{token.FLOAT, "0x1.1e0", "0x1.1e0", "hexadecimal mantissa requires a 'p' exponent"},
  1054  		{token.FLOAT, "0x1.2gp1a", "0x1.2 gp1a", "hexadecimal mantissa requires a 'p' exponent"},
  1055  		{token.FLOAT, "0x0p", "0x0p", "exponent has no digits"},
  1056  		{token.FLOAT, "0xeP-", "0xeP-", "exponent has no digits"},
  1057  		{token.FLOAT, "0x1234PAB", "0x1234P AB", "exponent has no digits"},
  1058  		{token.FLOAT, "0x1.2p1a", "0x1.2p1 a", ""},
  1059  
  1060  		{token.IMAG, "0xf00.bap+12i", "0xf00.bap+12i", ""},
  1061  
  1062  		// separators
  1063  		{token.INT, "0b_1000_0001", "0b_1000_0001", ""},
  1064  		{token.INT, "0o_600", "0o_600", ""},
  1065  		{token.INT, "0_466", "0_466", ""},
  1066  		{token.INT, "1_000", "1_000", ""},
  1067  		{token.FLOAT, "1_000.000_1", "1_000.000_1", ""},
  1068  		{token.IMAG, "10e+1_2_3i", "10e+1_2_3i", ""},
  1069  		{token.INT, "0x_f00d", "0x_f00d", ""},
  1070  		{token.FLOAT, "0x_f00d.0p1_2", "0x_f00d.0p1_2", ""},
  1071  
  1072  		{token.INT, "0b__1000", "0b__1000", "'_' must separate successive digits"},
  1073  		{token.INT, "0o60___0", "0o60___0", "'_' must separate successive digits"},
  1074  		{token.INT, "0466_", "0466_", "'_' must separate successive digits"},
  1075  		{token.FLOAT, "1_.", "1_.", "'_' must separate successive digits"},
  1076  		{token.FLOAT, "0._1", "0._1", "'_' must separate successive digits"},
  1077  		{token.FLOAT, "2.7_e0", "2.7_e0", "'_' must separate successive digits"},
  1078  		{token.IMAG, "10e+12_i", "10e+12_i", "'_' must separate successive digits"},
  1079  		{token.INT, "0x___0", "0x___0", "'_' must separate successive digits"},
  1080  		{token.FLOAT, "0x1.0_p0", "0x1.0_p0", "'_' must separate successive digits"},
  1081  	} {
  1082  		var s Scanner
  1083  		var err string
  1084  		s.Init(fset.AddFile("", fset.Base(), len(test.src)), []byte(test.src), func(_ token.Position, msg string) {
  1085  			if err == "" {
  1086  				err = msg
  1087  			}
  1088  		}, 0)
  1089  		for i, want := range strings.Split(test.tokens, " ") {
  1090  			err = ""
  1091  			_, tok, lit := s.Scan()
  1092  
  1093  			// compute lit where for tokens where lit is not defined
  1094  			switch tok {
  1095  			case token.PERIOD:
  1096  				lit = "."
  1097  			case token.ADD:
  1098  				lit = "+"
  1099  			case token.SUB:
  1100  				lit = "-"
  1101  			}
  1102  
  1103  			if i == 0 {
  1104  				if tok != test.tok {
  1105  					t.Errorf("%q: got token %s; want %s", test.src, tok, test.tok)
  1106  				}
  1107  				if err != test.err {
  1108  					t.Errorf("%q: got error %q; want %q", test.src, err, test.err)
  1109  				}
  1110  			}
  1111  
  1112  			if lit != want {
  1113  				t.Errorf("%q: got literal %q (%s); want %s", test.src, lit, tok, want)
  1114  			}
  1115  		}
  1116  
  1117  		// make sure we read all
  1118  		_, tok, _ := s.Scan()
  1119  		if tok == token.SEMICOLON {
  1120  			_, tok, _ = s.Scan()
  1121  		}
  1122  		if tok != token.EOF {
  1123  			t.Errorf("%q: got %s; want EOF", test.src, tok)
  1124  		}
  1125  	}
  1126  }
  1127  

View as plain text