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 errors expected in the test files.
9 // Expected errors are indicated in the test files by putting comments
10 // of the form /* ERROR pattern */ or /* ERRORx pattern */ (or a similar
11 // //-style line comment) immediately following the tokens where errors
12 // are reported. There must be exactly one blank before and after the
13 // ERROR/ERRORx indicator, and the pattern must be a properly quoted Go
16 // The harness will verify that each ERROR pattern is a substring of the
17 // error reported at that source position, and that each ERRORx pattern
18 // is a regular expression matching the respective error.
19 // Consecutive comments may be used to indicate multiple errors reported
20 // at the same position.
22 // For instance, the following test source indicates that an "undeclared"
23 // error should be reported for the undeclared variable x:
27 // _ = x /* ERROR "undeclared" */ + 1
54 haltOnError = flag.Bool("halt", false, "halt on error")
55 verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
58 var fset = token.NewFileSet()
60 func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode parser.Mode) ([]*ast.File, []error) {
63 for i, filename := range filenames {
64 file, err := parser.ParseFile(fset, filename, srcs[i], mode)
66 t.Fatalf("%s: %s", filename, err)
68 files = append(files, file)
70 if list, _ := err.(scanner.ErrorList); len(list) > 0 {
71 for _, err := range list {
72 errlist = append(errlist, err)
75 errlist = append(errlist, err)
82 func unpackError(fset *token.FileSet, err error) (token.Position, string) {
83 switch err := err.(type) {
85 return err.Pos, err.Msg
87 return fset.Position(err.Pos), err.Msg
92 // absDiff returns the absolute difference between x and y.
93 func absDiff(x, y int) int {
100 // parseFlags parses flags from the first line of the given source
101 // (from src if present, or by reading from the file) if the line
102 // starts with "//" (line comment) followed by "-" (possibly with
103 // spaces between). Otherwise the line is ignored.
104 func parseFlags(filename string, src []byte, flags *flag.FlagSet) error {
105 // If there is no src, read from the file.
108 f, err := os.Open(filename)
114 n, err := f.Read(buf[:])
121 // we must have a line comment that starts with a "-"
123 if !bytes.HasPrefix(src, []byte(prefix)) {
124 return nil // first line is not a line comment
126 src = src[len(prefix):]
127 if i := bytes.Index(src, []byte("-")); i < 0 || len(bytes.TrimSpace(src[:i])) != 0 {
128 return nil // comment doesn't start with a "-"
130 end := bytes.Index(src, []byte("\n"))
131 if end < 0 || end > maxLen {
132 return fmt.Errorf("flags comment line too long")
135 return flags.Parse(strings.Fields(string(src[:end])))
138 func testFiles(t *testing.T, sizes Sizes, filenames []string, srcs [][]byte, manual bool, imp Importer) {
139 if len(filenames) == 0 {
140 t.Fatal("no source files")
145 flags := flag.NewFlagSet("", flag.PanicOnError)
146 flags.StringVar(&conf.GoVersion, "lang", "", "")
147 flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
148 flags.BoolVar(boolFieldAddr(&conf, "oldComparableSemantics"), "oldComparableSemantics", false, "")
149 if err := parseFlags(filenames[0], srcs[0], flags); err != nil {
153 files, errlist := parseFiles(t, filenames, srcs, parser.AllErrors)
155 pkgName := "<no package>"
157 pkgName = files[0].Name.Name
160 listErrors := manual && !*verifyErrors
161 if listErrors && len(errlist) > 0 {
162 t.Errorf("--- %s:", pkgName)
163 for _, err := range errlist {
168 // typecheck and collect typechecker errors
169 *boolFieldAddr(&conf, "trace") = manual && testing.Verbose()
171 imp = importer.Default()
174 conf.Error = func(err error) {
182 // Ignore secondary error messages starting with "\t";
183 // they are clarifying messages for a primary error.
184 if !strings.Contains(err.Error(), ": \t") {
185 errlist = append(errlist, err)
188 conf.Check(pkgName, fset, files, nil)
194 // collect expected errors
195 errmap := make(map[string]map[int][]comment)
196 for i, filename := range filenames {
197 if m := commentMap(srcs[i], regexp.MustCompile("^ ERRORx? ")); len(m) > 0 {
202 // match against found errors
203 var indices []int // list indices of matching errors, reused for each error
204 for _, err := range errlist {
205 gotPos, gotMsg := unpackError(fset, err)
207 // find list of errors for the respective error line
208 filename := gotPos.Filename
209 filemap := errmap[filename]
211 var errList []comment
213 errList = filemap[line]
216 // At least one of the errors in errList should match the current error.
217 indices = indices[:0]
218 for i, want := range errList {
219 pattern, substr := strings.CutPrefix(want.text, " ERROR ")
222 pattern, found = strings.CutPrefix(want.text, " ERRORx ")
227 pattern, err := strconv.Unquote(strings.TrimSpace(pattern))
229 t.Errorf("%s:%d:%d: %v", filename, line, want.col, err)
233 if !strings.Contains(gotMsg, pattern) {
237 rx, err := regexp.Compile(pattern)
239 t.Errorf("%s:%d:%d: %v", filename, line, want.col, err)
242 if !rx.MatchString(gotMsg) {
246 indices = append(indices, i)
248 if len(indices) == 0 {
249 t.Errorf("%s: no error expected: %q", gotPos, gotMsg)
254 // If there are multiple matching errors, select the one with the closest column position.
255 index := -1 // index of matching error
257 for _, i := range indices {
258 if d := absDiff(gotPos.Column, errList[i].col); index < 0 || d < delta {
263 // The closest column position must be within expected colDelta.
264 const colDelta = 0 // go/types errors are positioned correctly
265 if delta > colDelta {
266 t.Errorf("%s: got col = %d; want %d", gotPos, gotPos.Column, errList[index].col)
269 // eliminate from errList
270 if n := len(errList) - 1; n > 0 {
271 // not the last entry - slide entries down (don't reorder)
272 copy(errList[index:], errList[index+1:])
273 filemap[line] = errList[:n]
275 // last entry - remove errList from filemap
276 delete(filemap, line)
279 // if filemap is empty, eliminate from errmap
280 if len(filemap) == 0 {
281 delete(errmap, filename)
285 // there should be no expected errors left
287 t.Errorf("--- %s: unreported errors:", pkgName)
288 for filename, filemap := range errmap {
289 for line, errList := range filemap {
290 for _, err := range errList {
291 t.Errorf("%s:%d:%d: %s", filename, line, err.col, err.text)
298 func readCode(err Error) int {
299 v := reflect.ValueOf(err)
300 return int(v.FieldByName("go116code").Int())
303 // boolFieldAddr(conf, name) returns the address of the boolean field conf.<name>.
304 // For accessing unexported fields.
305 func boolFieldAddr(conf *Config, name string) *bool {
306 v := reflect.Indirect(reflect.ValueOf(conf))
307 return (*bool)(v.FieldByName(name).Addr().UnsafePointer())
310 // TestManual is for manual testing of a package - either provided
311 // as a list of filenames belonging to the package, or a directory
312 // name containing the package files - after the test arguments
313 // (and a separating "--"). For instance, to test the package made
314 // of the files foo.go and bar.go, use:
316 // go test -run Manual -- foo.go bar.go
318 // If no source arguments are provided, the file testdata/manual.go
320 // Provide the -verify flag to verify errors against ERROR comments
321 // in the input files rather than having a list of errors reported.
322 // The accepted Go language version can be controlled with the -lang
324 func TestManual(t *testing.T) {
325 testenv.MustHaveGoBuild(t)
327 filenames := flag.Args()
328 if len(filenames) == 0 {
329 filenames = []string{filepath.FromSlash("testdata/manual.go")}
332 info, err := os.Stat(filenames[0])
334 t.Fatalf("TestManual: %v", err)
337 DefPredeclaredTestFuncs()
339 if len(filenames) > 1 {
340 t.Fatal("TestManual: must have only one directory argument")
342 testDir(t, filenames[0], true)
344 testPkg(t, filenames, true)
348 func TestLongConstants(t *testing.T) {
349 format := `package longconst; const _ = %s /* ERROR "constant overflow" */; const _ = %s // ERROR "excessively long constant"`
350 src := fmt.Sprintf(format, strings.Repeat("1", 9999), strings.Repeat("1", 10001))
351 testFiles(t, nil, []string{"longconst.go"}, [][]byte{[]byte(src)}, false, nil)
354 // TestIndexRepresentability tests that constant index operands must
355 // be representable as int even if they already have a type that can
356 // represent larger values.
357 func TestIndexRepresentability(t *testing.T) {
358 const src = `package index; var s []byte; var _ = s[int64 /* ERRORx "int64\\(1\\) << 40 \\(.*\\) overflows int" */ (1) << 40]`
359 testFiles(t, &StdSizes{4, 4}, []string{"index.go"}, [][]byte{[]byte(src)}, false, nil)
362 func TestIssue47243_TypedRHS(t *testing.T) {
363 // The RHS of the shift expression below overflows uint on 32bit platforms,
364 // but this is OK as it is explicitly typed.
365 const src = `package issue47243; var a uint64; var _ = a << uint64(4294967296)` // uint64(1<<32)
366 testFiles(t, &StdSizes{4, 4}, []string{"p.go"}, [][]byte{[]byte(src)}, false, nil)
369 func TestCheck(t *testing.T) {
370 DefPredeclaredTestFuncs()
371 testDirFiles(t, "../../internal/types/testdata/check", false)
373 func TestSpec(t *testing.T) { testDirFiles(t, "../../internal/types/testdata/spec", false) }
374 func TestExamples(t *testing.T) { testDirFiles(t, "../../internal/types/testdata/examples", false) }
375 func TestFixedbugs(t *testing.T) { testDirFiles(t, "../../internal/types/testdata/fixedbugs", false) }
376 func TestLocal(t *testing.T) { testDirFiles(t, "testdata/local", false) }
378 func testDirFiles(t *testing.T, dir string, manual bool) {
379 testenv.MustHaveGoBuild(t)
380 dir = filepath.FromSlash(dir)
382 fis, err := os.ReadDir(dir)
388 for _, fi := range fis {
389 path := filepath.Join(dir, fi.Name())
391 // If fi is a directory, its files make up a single package.
393 testDir(t, path, manual)
395 t.Run(filepath.Base(path), func(t *testing.T) {
396 testPkg(t, []string{path}, manual)
402 func testDir(t *testing.T, dir string, manual bool) {
403 testenv.MustHaveGoBuild(t)
405 fis, err := os.ReadDir(dir)
411 var filenames []string
412 for _, fi := range fis {
413 filenames = append(filenames, filepath.Join(dir, fi.Name()))
416 t.Run(filepath.Base(dir), func(t *testing.T) {
417 testPkg(t, filenames, manual)
421 // TODO(rFindley) reconcile the different test setup in go/types with types2.
422 func testPkg(t *testing.T, filenames []string, manual bool) {
423 srcs := make([][]byte, len(filenames))
424 for i, filename := range filenames {
425 src, err := os.ReadFile(filename)
427 t.Fatalf("could not read %s: %v", filename, err)
431 testFiles(t, nil, filenames, srcs, manual, nil)