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 listErrors = flag.Bool("errlist", false, "list errors")
50 testFiles = flag.String("files", "", "comma-separated list of test files")
51 goVersion = flag.String("lang", "", "Go language version (e.g. \"go1.12\"")
54 var fset = token.NewFileSet()
56 // Positioned errors are of the form filename:line:column: message .
57 var posMsgRx = regexp.MustCompile(`^(.*:[0-9]+:[0-9]+): *(.*)`)
59 // splitError splits an error's error message into a position string
60 // and the actual error message. If there's no position information,
61 // pos is the empty string, and msg is the entire error message.
63 func splitError(err error) (pos, msg string) {
65 if m := posMsgRx.FindStringSubmatch(msg); len(m) == 3 {
72 func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode parser.Mode) ([]*ast.File, []error) {
75 for i, filename := range filenames {
76 file, err := parser.ParseFile(fset, filename, srcs[i], mode)
78 t.Fatalf("%s: %s", filename, err)
80 files = append(files, file)
82 if list, _ := err.(scanner.ErrorList); len(list) > 0 {
83 for _, err := range list {
84 errlist = append(errlist, err)
87 errlist = append(errlist, err)
94 // ERROR comments must start with text `ERROR "rx"` or `ERROR rx` where
95 // rx is a regular expression that matches the expected error message.
96 // Space around "rx" or rx is ignored. Use the form `ERROR HERE "rx"`
97 // for error messages that are located immediately after rather than
98 // at a token's position.
100 var errRx = regexp.MustCompile(`^ *ERROR *(HERE)? *"?([^"]*)"?`)
102 // errMap collects the regular expressions of ERROR comments found
103 // in files and returns them as a map of error positions to error messages.
105 // srcs must be a slice of the same length as files, containing the original
106 // source for the parsed AST.
107 func errMap(t *testing.T, files []*ast.File, srcs [][]byte) map[string][]string {
108 // map of position strings to lists of error message patterns
109 errmap := make(map[string][]string)
111 for i, file := range files {
112 tok := fset.File(file.Package)
114 var s scanner.Scanner
115 s.Init(tok, src, nil, scanner.ScanComments)
116 var prev token.Pos // position of last non-comment, non-semicolon token
117 var here token.Pos // position immediately after the token at position prev
121 pos, tok, lit := s.Scan()
127 lit = lit[:len(lit)-2] // strip trailing */
129 if s := errRx.FindStringSubmatch(lit[2:]); len(s) == 3 {
134 p := fset.Position(pos).String()
135 errmap[p] = append(errmap[p], strings.TrimSpace(s[2]))
137 case token.SEMICOLON:
138 // ignore automatically inserted semicolon
145 var l int // token length
149 l = len(tok.String())
151 here = prev + token.Pos(l)
159 func eliminate(t *testing.T, errmap map[string][]string, errlist []error) {
160 for _, err := range errlist {
161 pos, gotMsg := splitError(err)
163 index := -1 // list index of matching message, if any
164 // we expect one of the messages in list to match the error at pos
165 for i, wantRx := range list {
166 rx, err := regexp.Compile(wantRx)
168 t.Errorf("%s: %v", pos, err)
171 if rx.MatchString(gotMsg) {
177 // eliminate from list
178 if n := len(list) - 1; n > 0 {
179 // not the last entry - swap in last element and shorten list by 1
180 list[index] = list[n]
181 errmap[pos] = list[:n]
183 // last entry - remove list from map
187 t.Errorf("%s: no error expected: %q", pos, gotMsg)
192 // goVersionRx matches a Go version string using '_', e.g. "go1_12".
193 var goVersionRx = regexp.MustCompile(`^go[1-9][0-9]*_(0|[1-9][0-9]*)$`)
195 // asGoVersion returns a regular Go language version string
196 // if s is a Go version string using '_' rather than '.' to
197 // separate the major and minor version numbers (e.g. "go1_12").
198 // Otherwise it returns the empty string.
199 func asGoVersion(s string) string {
200 if goVersionRx.MatchString(s) {
201 return strings.Replace(s, "_", ".", 1)
206 func checkFiles(t *testing.T, sizes Sizes, goVersion string, filenames []string, srcs [][]byte) {
207 if len(filenames) == 0 {
208 t.Fatal("no source files")
211 mode := parser.AllErrors
212 if strings.HasSuffix(filenames[0], ".go2") {
213 if !typeparams.Enabled {
214 t.Skip("type params are not enabled")
217 mode |= typeparams.DisallowParsing
220 // parse files and collect parser errors
221 files, errlist := parseFiles(t, filenames, srcs, mode)
223 pkgName := "<no package>"
225 pkgName = files[0].Name.Name
228 // if no Go version is given, consider the package name
230 goVersion = asGoVersion(pkgName)
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 // TestCheck is for manual testing of selected input files, provided with -files.
301 // The accepted Go language version can be controlled with the -lang flag.
302 func TestCheck(t *testing.T) {
303 if *testFiles == "" {
306 testenv.MustHaveGoBuild(t)
307 DefPredeclaredTestFuncs()
308 testPkg(t, strings.Split(*testFiles, ","), *goVersion)
311 func TestLongConstants(t *testing.T) {
312 format := "package longconst\n\nconst _ = %s\nconst _ = %s // ERROR excessively long constant"
313 src := fmt.Sprintf(format, strings.Repeat("1", 9999), strings.Repeat("1", 10001))
314 checkFiles(t, nil, "", []string{"longconst.go"}, [][]byte{[]byte(src)})
317 // TestIndexRepresentability tests that constant index operands must
318 // be representable as int even if they already have a type that can
319 // represent larger values.
320 func TestIndexRepresentability(t *testing.T) {
321 const src = "package index\n\nvar s []byte\nvar _ = s[int64 /* ERROR \"int64\\(1\\) << 40 \\(.*\\) overflows int\" */ (1) << 40]"
322 checkFiles(t, &StdSizes{4, 4}, "", []string{"index.go"}, [][]byte{[]byte(src)})
325 func TestTestdata(t *testing.T) { DefPredeclaredTestFuncs(); testDir(t, "testdata") }
326 func TestExamples(t *testing.T) { testDir(t, "examples") }
327 func TestFixedbugs(t *testing.T) { testDir(t, "fixedbugs") }
329 func testDir(t *testing.T, dir string) {
330 testenv.MustHaveGoBuild(t)
332 fis, err := os.ReadDir(dir)
338 for _, fi := range fis {
339 path := filepath.Join(dir, fi.Name())
341 // if fi is a directory, its files make up a single package
342 var filenames []string
344 fis, err := os.ReadDir(path)
349 for _, fi := range fis {
350 filenames = append(filenames, filepath.Join(path, fi.Name()))
353 filenames = []string{path}
355 t.Run(filepath.Base(path), func(t *testing.T) {
356 testPkg(t, filenames, "")
361 func testPkg(t *testing.T, filenames []string, goVersion string) {
362 srcs := make([][]byte, len(filenames))
363 for i, filename := range filenames {
364 src, err := os.ReadFile(filename)
366 t.Fatalf("could not read %s: %v", filename, err)
370 checkFiles(t, nil, goVersion, filenames, srcs)