1 // Copyright 2011 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.
5 // This file implements a typechecker test harness. The packages specified
6 // in tests are typechecked. Error messages reported by the typechecker are
7 // compared against the error messages expected in the test files.
9 // Expected errors are indicated in the test files by putting a comment
10 // of the form /* ERROR "rx" */ immediately following an offending token.
11 // The harness will verify that an error matching the regular expression
12 // rx is reported at that source position. Consecutive comments may be
13 // used to indicate multiple errors for the same token position.
15 // For instance, the following test file indicates that a "not declared"
16 // error should be reported for the undeclared variable x:
20 // _ = x /* ERROR "not declared" */ + 1
45 haltOnError = flag.Bool("halt", false, "halt on error")
46 verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
47 goVersion = flag.String("lang", "", "Go language version (e.g. \"go1.12\") for TestManual")
50 var fset = token.NewFileSet()
52 // Positioned errors are of the form filename:line:column: message .
53 var posMsgRx = regexp.MustCompile(`^(.*:[0-9]+:[0-9]+): *(?s)(.*)`)
55 // splitError splits an error's error message into a position string
56 // and the actual error message. If there's no position information,
57 // pos is the empty string, and msg is the entire error message.
58 func splitError(err error) (pos, msg string) {
60 if m := posMsgRx.FindStringSubmatch(msg); len(m) == 3 {
67 func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode parser.Mode) ([]*ast.File, []error) {
70 for i, filename := range filenames {
71 file, err := parser.ParseFile(fset, filename, srcs[i], mode)
73 t.Fatalf("%s: %s", filename, err)
75 files = append(files, file)
77 if list, _ := err.(scanner.ErrorList); len(list) > 0 {
78 for _, err := range list {
79 errlist = append(errlist, err)
82 errlist = append(errlist, err)
89 // ERROR comments must start with text `ERROR "rx"` or `ERROR rx` where
90 // rx is a regular expression that matches the expected error message.
91 // Space around "rx" or rx is ignored. Use the form `ERROR HERE "rx"`
92 // for error messages that are located immediately after rather than
93 // at a token's position.
94 var errRx = regexp.MustCompile(`^ *ERROR *(HERE)? *"?([^"]*)"?`)
96 // errMap collects the regular expressions of ERROR comments found
97 // in files and returns them as a map of error positions to error messages.
99 // srcs must be a slice of the same length as files, containing the original
100 // source for the parsed AST.
101 func errMap(t *testing.T, files []*ast.File, srcs [][]byte) map[string][]string {
102 // map of position strings to lists of error message patterns
103 errmap := make(map[string][]string)
105 for i, file := range files {
106 tok := fset.File(file.Package)
108 var s scanner.Scanner
109 s.Init(tok, src, nil, scanner.ScanComments)
110 var prev token.Pos // position of last non-comment, non-semicolon token
111 var here token.Pos // position immediately after the token at position prev
115 pos, tok, lit := s.Scan()
121 lit = lit[:len(lit)-2] // strip trailing */
123 if s := errRx.FindStringSubmatch(lit[2:]); len(s) == 3 {
128 p := fset.Position(pos).String()
129 errmap[p] = append(errmap[p], strings.TrimSpace(s[2]))
131 case token.SEMICOLON:
132 // ignore automatically inserted semicolon
139 var l int // token length
143 l = len(tok.String())
145 here = prev + token.Pos(l)
153 func eliminate(t *testing.T, errmap map[string][]string, errlist []error) {
154 for _, err := range errlist {
155 pos, gotMsg := splitError(err)
157 index := -1 // list index of matching message, if any
158 // we expect one of the messages in list to match the error at pos
159 for i, wantRx := range list {
160 rx, err := regexp.Compile(wantRx)
162 t.Errorf("%s: %v", pos, err)
165 if rx.MatchString(gotMsg) {
171 // eliminate from list
172 if n := len(list) - 1; n > 0 {
173 // not the last entry - swap in last element and shorten list by 1
174 list[index] = list[n]
175 errmap[pos] = list[:n]
177 // last entry - remove list from map
181 t.Errorf("%s: no error expected: %q", pos, gotMsg)
186 // parseFlags parses flags from the first line of the given source
187 // (from src if present, or by reading from the file) if the line
188 // starts with "//" (line comment) followed by "-" (possiby with
189 // spaces between). Otherwise the line is ignored.
190 func parseFlags(filename string, src []byte, flags *flag.FlagSet) error {
191 // If there is no src, read from the file.
194 f, err := os.Open(filename)
200 n, err := f.Read(buf[:])
207 // we must have a line comment that starts with a "-"
209 if !bytes.HasPrefix(src, []byte(prefix)) {
210 return nil // first line is not a line comment
212 src = src[len(prefix):]
213 if i := bytes.Index(src, []byte("-")); i < 0 || len(bytes.TrimSpace(src[:i])) != 0 {
214 return nil // comment doesn't start with a "-"
216 end := bytes.Index(src, []byte("\n"))
217 if end < 0 || end > maxLen {
218 return fmt.Errorf("flags comment line too long")
221 return flags.Parse(strings.Fields(string(src[:end])))
224 func testFiles(t *testing.T, sizes Sizes, filenames []string, srcs [][]byte, manual bool, imp Importer) {
225 if len(filenames) == 0 {
226 t.Fatal("no source files")
231 flags := flag.NewFlagSet("", flag.PanicOnError)
232 flags.StringVar(&conf.GoVersion, "lang", "", "")
233 flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
234 if err := parseFlags(filenames[0], srcs[0], flags); err != nil {
238 if manual && *goVersion != "" {
239 // goVersion overrides -lang for manual tests.
240 conf.GoVersion = *goVersion
243 // TODO(gri) remove this or use flag mechanism to set mode if still needed
244 if strings.HasSuffix(filenames[0], ".go1") {
245 // TODO(rfindley): re-enable this test by using GoVersion.
246 t.Skip("type params are enabled")
249 files, errlist := parseFiles(t, filenames, srcs, parser.AllErrors)
251 pkgName := "<no package>"
253 pkgName = files[0].Name.Name
256 listErrors := manual && !*verifyErrors
257 if listErrors && len(errlist) > 0 {
258 t.Errorf("--- %s:", pkgName)
259 for _, err := range errlist {
264 // typecheck and collect typechecker errors
266 imp = importer.Default()
269 conf.Error = func(err error) {
277 // Ignore secondary error messages starting with "\t";
278 // they are clarifying messages for a primary error.
279 if !strings.Contains(err.Error(), ": \t") {
280 errlist = append(errlist, err)
283 conf.Check(pkgName, fset, files, nil)
289 for _, err := range errlist {
290 err, ok := err.(Error)
294 code := readCode(err)
296 t.Errorf("missing error code: %v", err)
300 // match and eliminate errors;
301 // we are expecting the following errors
302 errmap := errMap(t, files, srcs)
303 eliminate(t, errmap, errlist)
305 // there should be no expected errors left
307 t.Errorf("--- %s: %d source positions with expected (but not reported) errors:", pkgName, len(errmap))
308 for pos, list := range errmap {
309 for _, rx := range list {
310 t.Errorf("%s: %q", pos, rx)
316 // TestManual is for manual testing of a package - either provided
317 // as a list of filenames belonging to the package, or a directory
318 // name containing the package files - after the test arguments
319 // (and a separating "--"). For instance, to test the package made
320 // of the files foo.go and bar.go, use:
322 // go test -run Manual -- foo.go bar.go
324 // If no source arguments are provided, the file testdata/manual.go
326 // Provide the -verify flag to verify errors against ERROR comments
327 // in the input files rather than having a list of errors reported.
328 // The accepted Go language version can be controlled with the -lang
330 func TestManual(t *testing.T) {
331 testenv.MustHaveGoBuild(t)
333 filenames := flag.Args()
334 if len(filenames) == 0 {
335 filenames = []string{filepath.FromSlash("testdata/manual.go")}
338 info, err := os.Stat(filenames[0])
340 t.Fatalf("TestManual: %v", err)
343 DefPredeclaredTestFuncs()
345 if len(filenames) > 1 {
346 t.Fatal("TestManual: must have only one directory argument")
348 testDir(t, filenames[0], true)
350 testPkg(t, filenames, true)
354 func TestLongConstants(t *testing.T) {
355 format := "package longconst\n\nconst _ = %s\nconst _ = %s // ERROR excessively long constant"
356 src := fmt.Sprintf(format, strings.Repeat("1", 9999), strings.Repeat("1", 10001))
357 testFiles(t, nil, []string{"longconst.go"}, [][]byte{[]byte(src)}, false, nil)
360 // TestIndexRepresentability tests that constant index operands must
361 // be representable as int even if they already have a type that can
362 // represent larger values.
363 func TestIndexRepresentability(t *testing.T) {
364 const src = "package index\n\nvar s []byte\nvar _ = s[int64 /* ERROR \"int64\\(1\\) << 40 \\(.*\\) overflows int\" */ (1) << 40]"
365 testFiles(t, &StdSizes{4, 4}, []string{"index.go"}, [][]byte{[]byte(src)}, false, nil)
368 func TestIssue47243_TypedRHS(t *testing.T) {
369 // The RHS of the shift expression below overflows uint on 32bit platforms,
370 // but this is OK as it is explicitly typed.
371 const src = "package issue47243\n\nvar a uint64; var _ = a << uint64(4294967296)" // uint64(1<<32)
372 testFiles(t, &StdSizes{4, 4}, []string{"p.go"}, [][]byte{[]byte(src)}, false, nil)
375 func TestCheck(t *testing.T) { DefPredeclaredTestFuncs(); testDirFiles(t, "testdata/check", false) }
376 func TestSpec(t *testing.T) { testDirFiles(t, "testdata/spec", false) }
377 func TestExamples(t *testing.T) { testDirFiles(t, "testdata/examples", false) }
378 func TestFixedbugs(t *testing.T) { testDirFiles(t, "testdata/fixedbugs", false) }
380 func testDirFiles(t *testing.T, dir string, manual bool) {
381 testenv.MustHaveGoBuild(t)
382 dir = filepath.FromSlash(dir)
384 fis, err := os.ReadDir(dir)
390 for _, fi := range fis {
391 path := filepath.Join(dir, fi.Name())
393 // If fi is a directory, its files make up a single package.
395 testDir(t, path, manual)
397 t.Run(filepath.Base(path), func(t *testing.T) {
398 testPkg(t, []string{path}, manual)
404 func testDir(t *testing.T, dir string, manual bool) {
405 testenv.MustHaveGoBuild(t)
407 fis, err := os.ReadDir(dir)
413 var filenames []string
414 for _, fi := range fis {
415 filenames = append(filenames, filepath.Join(dir, fi.Name()))
418 t.Run(filepath.Base(dir), func(t *testing.T) {
419 testPkg(t, filenames, manual)
423 // TODO(rFindley) reconcile the different test setup in go/types with types2.
424 func testPkg(t *testing.T, filenames []string, manual bool) {
425 srcs := make([][]byte, len(filenames))
426 for i, filename := range filenames {
427 src, err := os.ReadFile(filename)
429 t.Fatalf("could not read %s: %v", filename, err)
433 testFiles(t, nil, filenames, srcs, manual, nil)