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
30 "go/internal/typeparams"
46 haltOnError = flag.Bool("halt", false, "halt on error")
47 verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
48 goVersion = flag.String("lang", "", "Go language version (e.g. \"go1.12\") for TestManual")
51 var fset = token.NewFileSet()
53 // Positioned errors are of the form filename:line:column: message .
54 var posMsgRx = regexp.MustCompile(`^(.*:[0-9]+:[0-9]+): *(.*)`)
56 // splitError splits an error's error message into a position string
57 // and the actual error message. If there's no position information,
58 // pos is the empty string, and msg is the entire error message.
60 func splitError(err error) (pos, msg string) {
62 if m := posMsgRx.FindStringSubmatch(msg); len(m) == 3 {
69 func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode parser.Mode) ([]*ast.File, []error) {
72 for i, filename := range filenames {
73 file, err := parser.ParseFile(fset, filename, srcs[i], mode)
75 t.Fatalf("%s: %s", filename, err)
77 files = append(files, file)
79 if list, _ := err.(scanner.ErrorList); len(list) > 0 {
80 for _, err := range list {
81 errlist = append(errlist, err)
84 errlist = append(errlist, err)
91 // ERROR comments must start with text `ERROR "rx"` or `ERROR rx` where
92 // rx is a regular expression that matches the expected error message.
93 // Space around "rx" or rx is ignored. Use the form `ERROR HERE "rx"`
94 // for error messages that are located immediately after rather than
95 // at a token's position.
97 var errRx = regexp.MustCompile(`^ *ERROR *(HERE)? *"?([^"]*)"?`)
99 // errMap collects the regular expressions of ERROR comments found
100 // in files and returns them as a map of error positions to error messages.
102 // srcs must be a slice of the same length as files, containing the original
103 // source for the parsed AST.
104 func errMap(t *testing.T, files []*ast.File, srcs [][]byte) map[string][]string {
105 // map of position strings to lists of error message patterns
106 errmap := make(map[string][]string)
108 for i, file := range files {
109 tok := fset.File(file.Package)
111 var s scanner.Scanner
112 s.Init(tok, src, nil, scanner.ScanComments)
113 var prev token.Pos // position of last non-comment, non-semicolon token
114 var here token.Pos // position immediately after the token at position prev
118 pos, tok, lit := s.Scan()
124 lit = lit[:len(lit)-2] // strip trailing */
126 if s := errRx.FindStringSubmatch(lit[2:]); len(s) == 3 {
131 p := fset.Position(pos).String()
132 errmap[p] = append(errmap[p], strings.TrimSpace(s[2]))
134 case token.SEMICOLON:
135 // ignore automatically inserted semicolon
142 var l int // token length
146 l = len(tok.String())
148 here = prev + token.Pos(l)
156 func eliminate(t *testing.T, errmap map[string][]string, errlist []error) {
157 for _, err := range errlist {
158 pos, gotMsg := splitError(err)
160 index := -1 // list index of matching message, if any
161 // we expect one of the messages in list to match the error at pos
162 for i, wantRx := range list {
163 rx, err := regexp.Compile(wantRx)
165 t.Errorf("%s: %v", pos, err)
168 if rx.MatchString(gotMsg) {
174 // eliminate from list
175 if n := len(list) - 1; n > 0 {
176 // not the last entry - swap in last element and shorten list by 1
177 list[index] = list[n]
178 errmap[pos] = list[:n]
180 // last entry - remove list from map
184 t.Errorf("%s: no error expected: %q", pos, gotMsg)
189 // goVersionRx matches a Go version string using '_', e.g. "go1_12".
190 var goVersionRx = regexp.MustCompile(`^go[1-9][0-9]*_(0|[1-9][0-9]*)$`)
192 // asGoVersion returns a regular Go language version string
193 // if s is a Go version string using '_' rather than '.' to
194 // separate the major and minor version numbers (e.g. "go1_12").
195 // Otherwise it returns the empty string.
196 func asGoVersion(s string) string {
197 if goVersionRx.MatchString(s) {
198 return strings.Replace(s, "_", ".", 1)
203 // excludedForUnifiedBuild lists files that cannot be tested
204 // when using the unified build's export data.
205 // TODO(gri) enable as soon as the unified build supports this.
206 var excludedForUnifiedBuild = map[string]bool{
207 "issue47818.go2": true,
208 "issue49705.go2": true,
211 func testFiles(t *testing.T, sizes Sizes, filenames []string, srcs [][]byte, manual bool, imp Importer) {
212 if len(filenames) == 0 {
213 t.Fatal("no source files")
216 if buildcfg.Experiment.Unified {
217 for _, f := range filenames {
218 if excludedForUnifiedBuild[filepath.Base(f)] {
219 t.Logf("%s cannot be tested with unified build - skipped", f)
225 if strings.HasSuffix(filenames[0], ".go1") {
226 // TODO(rfindley): re-enable this test by using GoVersion.
227 t.Skip("type params are enabled")
230 mode := parser.AllErrors
231 if !strings.HasSuffix(filenames[0], ".go2") && !manual {
232 mode |= typeparams.DisallowParsing
235 // parse files and collect parser errors
236 files, errlist := parseFiles(t, filenames, srcs, mode)
238 pkgName := "<no package>"
240 pkgName = files[0].Name.Name
243 // if no Go version is given, consider the package name
244 goVersion := *goVersion
246 goVersion = asGoVersion(pkgName)
249 listErrors := manual && !*verifyErrors
250 if listErrors && len(errlist) > 0 {
251 t.Errorf("--- %s:", pkgName)
252 for _, err := range errlist {
257 // typecheck and collect typechecker errors
260 conf.GoVersion = goVersion
262 // special case for importC.src
263 if len(filenames) == 1 {
264 if strings.HasSuffix(filenames[0], "importC.src") {
265 conf.FakeImportC = true
271 conf.Importer = importer.Default()
273 conf.Error = func(err error) {
281 // Ignore secondary error messages starting with "\t";
282 // they are clarifying messages for a primary error.
283 if !strings.Contains(err.Error(), ": \t") {
284 errlist = append(errlist, err)
287 conf.Check(pkgName, fset, files, nil)
293 for _, err := range errlist {
294 err, ok := err.(Error)
298 code := readCode(err)
300 t.Errorf("missing error code: %v", err)
304 // match and eliminate errors;
305 // we are expecting the following errors
306 errmap := errMap(t, files, srcs)
307 eliminate(t, errmap, errlist)
309 // there should be no expected errors left
311 t.Errorf("--- %s: %d source positions with expected (but not reported) errors:", pkgName, len(errmap))
312 for pos, list := range errmap {
313 for _, rx := range list {
314 t.Errorf("%s: %q", pos, rx)
320 // TestManual is for manual testing of a package - either provided
321 // as a list of filenames belonging to the package, or a directory
322 // name containing the package files - after the test arguments
323 // (and a separating "--"). For instance, to test the package made
324 // of the files foo.go and bar.go, use:
326 // go test -run Manual -- foo.go bar.go
328 // If no source arguments are provided, the file testdata/manual.go2
330 // Provide the -verify flag to verify errors against ERROR comments
331 // in the input files rather than having a list of errors reported.
332 // The accepted Go language version can be controlled with the -lang
334 func TestManual(t *testing.T) {
335 testenv.MustHaveGoBuild(t)
337 filenames := flag.Args()
338 if len(filenames) == 0 {
339 filenames = []string{filepath.FromSlash("testdata/manual.go2")}
342 info, err := os.Stat(filenames[0])
344 t.Fatalf("TestManual: %v", err)
347 DefPredeclaredTestFuncs()
349 if len(filenames) > 1 {
350 t.Fatal("TestManual: must have only one directory argument")
352 testDir(t, filenames[0], true)
354 testPkg(t, filenames, true)
358 func TestLongConstants(t *testing.T) {
359 format := "package longconst\n\nconst _ = %s\nconst _ = %s // ERROR excessively long constant"
360 src := fmt.Sprintf(format, strings.Repeat("1", 9999), strings.Repeat("1", 10001))
361 testFiles(t, nil, []string{"longconst.go"}, [][]byte{[]byte(src)}, false, nil)
364 // TestIndexRepresentability tests that constant index operands must
365 // be representable as int even if they already have a type that can
366 // represent larger values.
367 func TestIndexRepresentability(t *testing.T) {
368 const src = "package index\n\nvar s []byte\nvar _ = s[int64 /* ERROR \"int64\\(1\\) << 40 \\(.*\\) overflows int\" */ (1) << 40]"
369 testFiles(t, &StdSizes{4, 4}, []string{"index.go"}, [][]byte{[]byte(src)}, false, nil)
372 func TestIssue47243_TypedRHS(t *testing.T) {
373 // The RHS of the shift expression below overflows uint on 32bit platforms,
374 // but this is OK as it is explicitly typed.
375 const src = "package issue47243\n\nvar a uint64; var _ = a << uint64(4294967296)" // uint64(1<<32)
376 testFiles(t, &StdSizes{4, 4}, []string{"p.go"}, [][]byte{[]byte(src)}, false, nil)
379 func TestCheck(t *testing.T) { DefPredeclaredTestFuncs(); testDirFiles(t, "testdata/check", false) }
380 func TestSpec(t *testing.T) { DefPredeclaredTestFuncs(); testDirFiles(t, "testdata/spec", false) }
381 func TestExamples(t *testing.T) { testDirFiles(t, "testdata/examples", false) }
382 func TestFixedbugs(t *testing.T) { testDirFiles(t, "testdata/fixedbugs", false) }
384 func testDirFiles(t *testing.T, dir string, manual bool) {
385 testenv.MustHaveGoBuild(t)
386 dir = filepath.FromSlash(dir)
388 fis, err := os.ReadDir(dir)
394 for _, fi := range fis {
395 path := filepath.Join(dir, fi.Name())
397 // If fi is a directory, its files make up a single package.
399 testDir(t, path, manual)
401 t.Run(filepath.Base(path), func(t *testing.T) {
402 testPkg(t, []string{path}, manual)
408 func testDir(t *testing.T, dir string, manual bool) {
409 testenv.MustHaveGoBuild(t)
411 fis, err := os.ReadDir(dir)
417 var filenames []string
418 for _, fi := range fis {
419 filenames = append(filenames, filepath.Join(dir, fi.Name()))
422 t.Run(filepath.Base(dir), func(t *testing.T) {
423 testPkg(t, filenames, manual)
427 // TODO(rFindley) reconcile the different test setup in go/types with types2.
428 func testPkg(t *testing.T, filenames []string, manual bool) {
429 srcs := make([][]byte, len(filenames))
430 for i, filename := range filenames {
431 src, err := os.ReadFile(filename)
433 t.Fatalf("could not read %s: %v", filename, err)
437 testFiles(t, nil, filenames, srcs, manual, nil)