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"
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]+): *(.*)`)
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.
59 func splitError(err error) (pos, msg string) {
61 if m := posMsgRx.FindStringSubmatch(msg); len(m) == 3 {
68 func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode parser.Mode) ([]*ast.File, []error) {
71 for i, filename := range filenames {
72 file, err := parser.ParseFile(fset, filename, srcs[i], mode)
74 t.Fatalf("%s: %s", filename, err)
76 files = append(files, file)
78 if list, _ := err.(scanner.ErrorList); len(list) > 0 {
79 for _, err := range list {
80 errlist = append(errlist, err)
83 errlist = append(errlist, err)
90 // ERROR comments must start with text `ERROR "rx"` or `ERROR rx` where
91 // rx is a regular expression that matches the expected error message.
92 // Space around "rx" or rx is ignored. Use the form `ERROR HERE "rx"`
93 // for error messages that are located immediately after rather than
94 // at a token's position.
96 var errRx = regexp.MustCompile(`^ *ERROR *(HERE)? *"?([^"]*)"?`)
98 // errMap collects the regular expressions of ERROR comments found
99 // in files and returns them as a map of error positions to error messages.
101 // srcs must be a slice of the same length as files, containing the original
102 // source for the parsed AST.
103 func errMap(t *testing.T, files []*ast.File, srcs [][]byte) map[string][]string {
104 // map of position strings to lists of error message patterns
105 errmap := make(map[string][]string)
107 for i, file := range files {
108 tok := fset.File(file.Package)
110 var s scanner.Scanner
111 s.Init(tok, src, nil, scanner.ScanComments)
112 var prev token.Pos // position of last non-comment, non-semicolon token
113 var here token.Pos // position immediately after the token at position prev
117 pos, tok, lit := s.Scan()
123 lit = lit[:len(lit)-2] // strip trailing */
125 if s := errRx.FindStringSubmatch(lit[2:]); len(s) == 3 {
130 p := fset.Position(pos).String()
131 errmap[p] = append(errmap[p], strings.TrimSpace(s[2]))
133 case token.SEMICOLON:
134 // ignore automatically inserted semicolon
141 var l int // token length
145 l = len(tok.String())
147 here = prev + token.Pos(l)
155 func eliminate(t *testing.T, errmap map[string][]string, errlist []error) {
156 for _, err := range errlist {
157 pos, gotMsg := splitError(err)
159 index := -1 // list index of matching message, if any
160 // we expect one of the messages in list to match the error at pos
161 for i, wantRx := range list {
162 rx, err := regexp.Compile(wantRx)
164 t.Errorf("%s: %v", pos, err)
167 if rx.MatchString(gotMsg) {
173 // eliminate from list
174 if n := len(list) - 1; n > 0 {
175 // not the last entry - swap in last element and shorten list by 1
176 list[index] = list[n]
177 errmap[pos] = list[:n]
179 // last entry - remove list from map
183 t.Errorf("%s: no error expected: %q", pos, gotMsg)
188 // goVersionRx matches a Go version string using '_', e.g. "go1_12".
189 var goVersionRx = regexp.MustCompile(`^go[1-9][0-9]*_(0|[1-9][0-9]*)$`)
191 // asGoVersion returns a regular Go language version string
192 // if s is a Go version string using '_' rather than '.' to
193 // separate the major and minor version numbers (e.g. "go1_12").
194 // Otherwise it returns the empty string.
195 func asGoVersion(s string) string {
196 if goVersionRx.MatchString(s) {
197 return strings.Replace(s, "_", ".", 1)
202 func testFiles(t *testing.T, sizes Sizes, filenames []string, srcs [][]byte, manual bool, imp Importer) {
203 if len(filenames) == 0 {
204 t.Fatal("no source files")
207 if strings.HasSuffix(filenames[0], ".go1") {
208 // TODO(rfindley): re-enable this test by using GoVersion.
209 t.Skip("type params are enabled")
212 mode := parser.AllErrors
213 if !strings.HasSuffix(filenames[0], ".go2") && !manual {
214 mode |= typeparams.DisallowParsing
217 // parse files and collect parser errors
218 files, errlist := parseFiles(t, filenames, srcs, mode)
220 pkgName := "<no package>"
222 pkgName = files[0].Name.Name
225 // if no Go version is given, consider the package name
226 goVersion := *goVersion
228 goVersion = asGoVersion(pkgName)
231 listErrors := manual && !*verifyErrors
232 if listErrors && len(errlist) > 0 {
233 t.Errorf("--- %s:", pkgName)
234 for _, err := range errlist {
239 // typecheck and collect typechecker errors
242 conf.GoVersion = goVersion
244 // special case for importC.src
245 if len(filenames) == 1 {
246 if strings.HasSuffix(filenames[0], "importC.src") {
247 conf.FakeImportC = true
253 conf.Importer = importer.Default()
255 conf.Error = func(err error) {
263 // Ignore secondary error messages starting with "\t";
264 // they are clarifying messages for a primary error.
265 if !strings.Contains(err.Error(), ": \t") {
266 errlist = append(errlist, err)
269 conf.Check(pkgName, fset, files, nil)
275 for _, err := range errlist {
276 err, ok := err.(Error)
280 code := readCode(err)
282 t.Errorf("missing error code: %v", err)
286 // match and eliminate errors;
287 // we are expecting the following errors
288 errmap := errMap(t, files, srcs)
289 eliminate(t, errmap, errlist)
291 // there should be no expected errors left
293 t.Errorf("--- %s: %d source positions with expected (but not reported) errors:", pkgName, len(errmap))
294 for pos, list := range errmap {
295 for _, rx := range list {
296 t.Errorf("%s: %q", pos, rx)
302 // TestManual is for manual testing of a package - either provided
303 // as a list of filenames belonging to the package, or a directory
304 // name containing the package files - after the test arguments
305 // (and a separating "--"). For instance, to test the package made
306 // of the files foo.go and bar.go, use:
308 // go test -run Manual -- foo.go bar.go
310 // If no source arguments are provided, the file testdata/manual.go2
312 // Provide the -verify flag to verify errors against ERROR comments
313 // in the input files rather than having a list of errors reported.
314 // The accepted Go language version can be controlled with the -lang
316 func TestManual(t *testing.T) {
317 testenv.MustHaveGoBuild(t)
319 filenames := flag.Args()
320 if len(filenames) == 0 {
321 filenames = []string{filepath.FromSlash("testdata/manual.go2")}
324 info, err := os.Stat(filenames[0])
326 t.Fatalf("TestManual: %v", err)
329 DefPredeclaredTestFuncs()
331 if len(filenames) > 1 {
332 t.Fatal("TestManual: must have only one directory argument")
334 testDir(t, filenames[0], true)
336 testPkg(t, filenames, true)
340 func TestLongConstants(t *testing.T) {
341 format := "package longconst\n\nconst _ = %s\nconst _ = %s // ERROR excessively long constant"
342 src := fmt.Sprintf(format, strings.Repeat("1", 9999), strings.Repeat("1", 10001))
343 testFiles(t, nil, []string{"longconst.go"}, [][]byte{[]byte(src)}, false, nil)
346 // TestIndexRepresentability tests that constant index operands must
347 // be representable as int even if they already have a type that can
348 // represent larger values.
349 func TestIndexRepresentability(t *testing.T) {
350 const src = "package index\n\nvar s []byte\nvar _ = s[int64 /* ERROR \"int64\\(1\\) << 40 \\(.*\\) overflows int\" */ (1) << 40]"
351 testFiles(t, &StdSizes{4, 4}, []string{"index.go"}, [][]byte{[]byte(src)}, false, nil)
354 func TestIssue47243_TypedRHS(t *testing.T) {
355 // The RHS of the shift expression below overflows uint on 32bit platforms,
356 // but this is OK as it is explicitly typed.
357 const src = "package issue47243\n\nvar a uint64; var _ = a << uint64(4294967296)" // uint64(1<<32)
358 testFiles(t, &StdSizes{4, 4}, []string{"p.go"}, [][]byte{[]byte(src)}, false, nil)
361 func TestCheck(t *testing.T) { DefPredeclaredTestFuncs(); testDirFiles(t, "testdata/check", false) }
362 func TestExamples(t *testing.T) { testDirFiles(t, "testdata/examples", false) }
363 func TestFixedbugs(t *testing.T) { testDirFiles(t, "testdata/fixedbugs", false) }
365 func testDirFiles(t *testing.T, dir string, manual bool) {
366 testenv.MustHaveGoBuild(t)
367 dir = filepath.FromSlash(dir)
369 fis, err := os.ReadDir(dir)
375 for _, fi := range fis {
376 path := filepath.Join(dir, fi.Name())
378 // If fi is a directory, its files make up a single package.
380 testDir(t, path, manual)
382 t.Run(filepath.Base(path), func(t *testing.T) {
383 testPkg(t, []string{path}, manual)
389 func testDir(t *testing.T, dir string, manual bool) {
390 testenv.MustHaveGoBuild(t)
392 fis, err := os.ReadDir(dir)
398 var filenames []string
399 for _, fi := range fis {
400 filenames = append(filenames, filepath.Join(dir, fi.Name()))
403 t.Run(filepath.Base(dir), func(t *testing.T) {
404 testPkg(t, filenames, manual)
408 // TODO(rFindley) reconcile the different test setup in go/types with types2.
409 func testPkg(t *testing.T, filenames []string, manual bool) {
410 srcs := make([][]byte, len(filenames))
411 for i, filename := range filenames {
412 src, err := os.ReadFile(filename)
414 t.Fatalf("could not read %s: %v", filename, err)
418 testFiles(t, nil, filenames, srcs, manual, nil)