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
23 // TODO(gri) Also collect strict mode errors of the form /* STRICT ... */
24 // and test against strict mode.
33 "go/internal/typeparams"
48 haltOnError = flag.Bool("halt", false, "halt on error")
49 verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
50 goVersion = flag.String("lang", "", "Go language version (e.g. \"go1.12\") for TestManual")
53 var fset = token.NewFileSet()
55 // Positioned errors are of the form filename:line:column: message .
56 var posMsgRx = regexp.MustCompile(`^(.*:[0-9]+:[0-9]+): *(.*)`)
58 // splitError splits an error's error message into a position string
59 // and the actual error message. If there's no position information,
60 // pos is the empty string, and msg is the entire error message.
62 func splitError(err error) (pos, msg string) {
64 if m := posMsgRx.FindStringSubmatch(msg); len(m) == 3 {
71 func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode parser.Mode) ([]*ast.File, []error) {
74 for i, filename := range filenames {
75 file, err := parser.ParseFile(fset, filename, srcs[i], mode)
77 t.Fatalf("%s: %s", filename, err)
79 files = append(files, file)
81 if list, _ := err.(scanner.ErrorList); len(list) > 0 {
82 for _, err := range list {
83 errlist = append(errlist, err)
86 errlist = append(errlist, err)
93 // ERROR comments must start with text `ERROR "rx"` or `ERROR rx` where
94 // rx is a regular expression that matches the expected error message.
95 // Space around "rx" or rx is ignored. Use the form `ERROR HERE "rx"`
96 // for error messages that are located immediately after rather than
97 // at a token's position.
99 var errRx = regexp.MustCompile(`^ *ERROR *(HERE)? *"?([^"]*)"?`)
101 // errMap collects the regular expressions of ERROR comments found
102 // in files and returns them as a map of error positions to error messages.
104 // srcs must be a slice of the same length as files, containing the original
105 // source for the parsed AST.
106 func errMap(t *testing.T, files []*ast.File, srcs [][]byte) map[string][]string {
107 // map of position strings to lists of error message patterns
108 errmap := make(map[string][]string)
110 for i, file := range files {
111 tok := fset.File(file.Package)
113 var s scanner.Scanner
114 s.Init(tok, src, nil, scanner.ScanComments)
115 var prev token.Pos // position of last non-comment, non-semicolon token
116 var here token.Pos // position immediately after the token at position prev
120 pos, tok, lit := s.Scan()
126 lit = lit[:len(lit)-2] // strip trailing */
128 if s := errRx.FindStringSubmatch(lit[2:]); len(s) == 3 {
133 p := fset.Position(pos).String()
134 errmap[p] = append(errmap[p], strings.TrimSpace(s[2]))
136 case token.SEMICOLON:
137 // ignore automatically inserted semicolon
144 var l int // token length
148 l = len(tok.String())
150 here = prev + token.Pos(l)
158 func eliminate(t *testing.T, errmap map[string][]string, errlist []error) {
159 for _, err := range errlist {
160 pos, gotMsg := splitError(err)
162 index := -1 // list index of matching message, if any
163 // we expect one of the messages in list to match the error at pos
164 for i, wantRx := range list {
165 rx, err := regexp.Compile(wantRx)
167 t.Errorf("%s: %v", pos, err)
170 if rx.MatchString(gotMsg) {
176 // eliminate from list
177 if n := len(list) - 1; n > 0 {
178 // not the last entry - swap in last element and shorten list by 1
179 list[index] = list[n]
180 errmap[pos] = list[:n]
182 // last entry - remove list from map
186 t.Errorf("%s: no error expected: %q", pos, gotMsg)
191 // goVersionRx matches a Go version string using '_', e.g. "go1_12".
192 var goVersionRx = regexp.MustCompile(`^go[1-9][0-9]*_(0|[1-9][0-9]*)$`)
194 // asGoVersion returns a regular Go language version string
195 // if s is a Go version string using '_' rather than '.' to
196 // separate the major and minor version numbers (e.g. "go1_12").
197 // Otherwise it returns the empty string.
198 func asGoVersion(s string) string {
199 if goVersionRx.MatchString(s) {
200 return strings.Replace(s, "_", ".", 1)
205 func checkFiles(t *testing.T, sizes Sizes, goVersion string, filenames []string, srcs [][]byte, manual bool) {
206 if len(filenames) == 0 {
207 t.Fatal("no source files")
210 mode := parser.AllErrors
211 if strings.HasSuffix(filenames[0], ".go2") {
212 if !typeparams.Enabled {
213 t.Skip("type params are not enabled")
216 mode |= typeparams.DisallowParsing
219 // parse files and collect parser errors
220 files, errlist := parseFiles(t, filenames, srcs, mode)
222 pkgName := "<no package>"
224 pkgName = files[0].Name.Name
227 // if no Go version is given, consider the package name
229 goVersion = asGoVersion(pkgName)
232 listErrors := manual && !*verifyErrors
233 if listErrors && len(errlist) > 0 {
234 t.Errorf("--- %s:", pkgName)
235 for _, err := range errlist {
240 // typecheck and collect typechecker errors
243 conf.GoVersion = goVersion
245 // special case for importC.src
246 if len(filenames) == 1 {
247 if strings.HasSuffix(filenames[0], "importC.src") {
248 conf.FakeImportC = true
252 conf.Importer = importer.Default()
253 conf.Error = func(err error) {
261 // Ignore secondary error messages starting with "\t";
262 // they are clarifying messages for a primary error.
263 if !strings.Contains(err.Error(), ": \t") {
264 errlist = append(errlist, err)
267 conf.Check(pkgName, fset, files, nil)
273 for _, err := range errlist {
274 err, ok := err.(Error)
278 code := readCode(err)
280 t.Errorf("missing error code: %v", err)
284 // match and eliminate errors;
285 // we are expecting the following errors
286 errmap := errMap(t, files, srcs)
287 eliminate(t, errmap, errlist)
289 // there should be no expected errors left
291 t.Errorf("--- %s: %d source positions with expected (but not reported) errors:", pkgName, len(errmap))
292 for pos, list := range errmap {
293 for _, rx := range list {
294 t.Errorf("%s: %q", pos, rx)
300 // TestManual is for manual testing of input files, provided as a list
301 // of arguments after the test arguments (and a separating "--"). For
302 // instance, to check the files foo.go and bar.go, use:
304 // go test -run Manual -- foo.go bar.go
306 // Provide the -verify flag to verify errors against ERROR comments in
307 // the input files rather than having a list of errors reported.
308 // The accepted Go language version can be controlled with the -lang flag.
309 func TestManual(t *testing.T) {
310 filenames := flag.Args()
311 if len(filenames) == 0 {
314 testenv.MustHaveGoBuild(t)
315 DefPredeclaredTestFuncs()
316 testPkg(t, filenames, *goVersion, true)
319 func TestLongConstants(t *testing.T) {
320 format := "package longconst\n\nconst _ = %s\nconst _ = %s // ERROR excessively long constant"
321 src := fmt.Sprintf(format, strings.Repeat("1", 9999), strings.Repeat("1", 10001))
322 checkFiles(t, nil, "", []string{"longconst.go"}, [][]byte{[]byte(src)}, false)
325 // TestIndexRepresentability tests that constant index operands must
326 // be representable as int even if they already have a type that can
327 // represent larger values.
328 func TestIndexRepresentability(t *testing.T) {
329 const src = "package index\n\nvar s []byte\nvar _ = s[int64 /* ERROR \"int64\\(1\\) << 40 \\(.*\\) overflows int\" */ (1) << 40]"
330 checkFiles(t, &StdSizes{4, 4}, "", []string{"index.go"}, [][]byte{[]byte(src)}, false)
333 func TestCheck(t *testing.T) { DefPredeclaredTestFuncs(); testDir(t, "check") }
334 func TestExamples(t *testing.T) { testDir(t, "examples") }
335 func TestFixedbugs(t *testing.T) { testDir(t, "fixedbugs") }
337 func testDir(t *testing.T, dir string) {
338 testenv.MustHaveGoBuild(t)
340 dir = filepath.Join("testdata", dir)
341 fis, err := os.ReadDir(dir)
347 for _, fi := range fis {
348 path := filepath.Join(dir, fi.Name())
350 // if fi is a directory, its files make up a single package
351 var filenames []string
353 fis, err := os.ReadDir(path)
358 for _, fi := range fis {
359 filenames = append(filenames, filepath.Join(path, fi.Name()))
362 filenames = []string{path}
364 t.Run(filepath.Base(path), func(t *testing.T) {
365 testPkg(t, filenames, "", false)
370 // TODO(rFindley) reconcile the different test setup in go/types with types2.
371 func testPkg(t *testing.T, filenames []string, goVersion string, manual bool) {
372 srcs := make([][]byte, len(filenames))
373 for i, filename := range filenames {
374 src, err := os.ReadFile(filename)
376 t.Fatalf("could not read %s: %v", filename, err)
380 checkFiles(t, nil, goVersion, filenames, srcs, manual)