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
42 "internal/types/errors"
55 haltOnError = flag.Bool("halt", false, "halt on error")
56 verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
59 var fset = token.NewFileSet()
61 func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode parser.Mode) ([]*ast.File, []error) {
64 for i, filename := range filenames {
65 file, err := parser.ParseFile(fset, filename, srcs[i], mode)
67 t.Fatalf("%s: %s", filename, err)
69 files = append(files, file)
71 if list, _ := err.(scanner.ErrorList); len(list) > 0 {
72 for _, err := range list {
73 errlist = append(errlist, err)
76 errlist = append(errlist, err)
83 func unpackError(fset *token.FileSet, err error) (token.Position, string) {
84 switch err := err.(type) {
86 return err.Pos, err.Msg
88 return fset.Position(err.Pos), err.Msg
93 // absDiff returns the absolute difference between x and y.
94 func absDiff(x, y int) int {
101 // parseFlags parses flags from the first line of the given source if the line
102 // starts with "//" (line comment) followed by "-" (possibly with spaces
103 // between). Otherwise the line is ignored.
104 func parseFlags(src []byte, flags *flag.FlagSet) error {
105 // we must have a line comment that starts with a "-"
107 if !bytes.HasPrefix(src, []byte(prefix)) {
108 return nil // first line is not a line comment
110 src = src[len(prefix):]
111 if i := bytes.Index(src, []byte("-")); i < 0 || len(bytes.TrimSpace(src[:i])) != 0 {
112 return nil // comment doesn't start with a "-"
114 end := bytes.Index(src, []byte("\n"))
116 if end < 0 || end > maxLen {
117 return fmt.Errorf("flags comment line too long")
120 return flags.Parse(strings.Fields(string(src[:end])))
123 // testFiles type-checks the package consisting of the given files, and
124 // compares the resulting errors with the ERROR annotations in the source.
126 // The srcs slice contains the file content for the files named in the
127 // filenames slice. The manual parameter specifies whether this is a 'manual'
130 // If provided, opts may be used to mutate the Config before type-checking.
131 func testFiles(t *testing.T, filenames []string, srcs [][]byte, manual bool, opts ...func(*Config)) {
132 if len(filenames) == 0 {
133 t.Fatal("no source files")
137 flags := flag.NewFlagSet("", flag.PanicOnError)
138 flags.StringVar(&conf.GoVersion, "lang", "", "")
139 flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
140 flags.BoolVar(boolFieldAddr(&conf, "_EnableInterfaceInference"), "EnableInterfaceInference", false, "")
141 if err := parseFlags(srcs[0], flags); err != nil {
145 files, errlist := parseFiles(t, filenames, srcs, parser.AllErrors)
147 pkgName := "<no package>"
149 pkgName = files[0].Name.Name
152 listErrors := manual && !*verifyErrors
153 if listErrors && len(errlist) > 0 {
154 t.Errorf("--- %s:", pkgName)
155 for _, err := range errlist {
160 // typecheck and collect typechecker errors
161 *boolFieldAddr(&conf, "_Trace") = manual && testing.Verbose()
162 conf.Importer = importer.Default()
163 conf.Error = func(err error) {
171 // Ignore secondary error messages starting with "\t";
172 // they are clarifying messages for a primary error.
173 if !strings.Contains(err.Error(), ": \t") {
174 errlist = append(errlist, err)
178 for _, opt := range opts {
182 conf.Check(pkgName, fset, files, nil)
188 // collect expected errors
189 errmap := make(map[string]map[int][]comment)
190 for i, filename := range filenames {
191 if m := commentMap(srcs[i], regexp.MustCompile("^ ERRORx? ")); len(m) > 0 {
196 // match against found errors
197 var indices []int // list indices of matching errors, reused for each error
198 for _, err := range errlist {
199 gotPos, gotMsg := unpackError(fset, err)
201 // find list of errors for the respective error line
202 filename := gotPos.Filename
203 filemap := errmap[filename]
205 var errList []comment
207 errList = filemap[line]
210 // At least one of the errors in errList should match the current error.
211 indices = indices[:0]
212 for i, want := range errList {
213 pattern, substr := strings.CutPrefix(want.text, " ERROR ")
216 pattern, found = strings.CutPrefix(want.text, " ERRORx ")
221 pattern, err := strconv.Unquote(strings.TrimSpace(pattern))
223 t.Errorf("%s:%d:%d: %v", filename, line, want.col, err)
227 if !strings.Contains(gotMsg, pattern) {
231 rx, err := regexp.Compile(pattern)
233 t.Errorf("%s:%d:%d: %v", filename, line, want.col, err)
236 if !rx.MatchString(gotMsg) {
240 indices = append(indices, i)
242 if len(indices) == 0 {
243 t.Errorf("%s: no error expected: %q", gotPos, gotMsg)
248 // If there are multiple matching errors, select the one with the closest column position.
249 index := -1 // index of matching error
251 for _, i := range indices {
252 if d := absDiff(gotPos.Column, errList[i].col); index < 0 || d < delta {
257 // The closest column position must be within expected colDelta.
258 const colDelta = 0 // go/types errors are positioned correctly
259 if delta > colDelta {
260 t.Errorf("%s: got col = %d; want %d", gotPos, gotPos.Column, errList[index].col)
263 // eliminate from errList
264 if n := len(errList) - 1; n > 0 {
265 // not the last entry - slide entries down (don't reorder)
266 copy(errList[index:], errList[index+1:])
267 filemap[line] = errList[:n]
269 // last entry - remove errList from filemap
270 delete(filemap, line)
273 // if filemap is empty, eliminate from errmap
274 if len(filemap) == 0 {
275 delete(errmap, filename)
279 // there should be no expected errors left
281 t.Errorf("--- %s: unreported errors:", pkgName)
282 for filename, filemap := range errmap {
283 for line, errList := range filemap {
284 for _, err := range errList {
285 t.Errorf("%s:%d:%d: %s", filename, line, err.col, err.text)
292 func readCode(err Error) errors.Code {
293 v := reflect.ValueOf(err)
294 return errors.Code(v.FieldByName("go116code").Int())
297 // boolFieldAddr(conf, name) returns the address of the boolean field conf.<name>.
298 // For accessing unexported fields.
299 func boolFieldAddr(conf *Config, name string) *bool {
300 v := reflect.Indirect(reflect.ValueOf(conf))
301 return (*bool)(v.FieldByName(name).Addr().UnsafePointer())
304 // TestManual is for manual testing of a package - either provided
305 // as a list of filenames belonging to the package, or a directory
306 // name containing the package files - after the test arguments
307 // (and a separating "--"). For instance, to test the package made
308 // of the files foo.go and bar.go, use:
310 // go test -run Manual -- foo.go bar.go
312 // If no source arguments are provided, the file testdata/manual.go
314 // Provide the -verify flag to verify errors against ERROR comments
315 // in the input files rather than having a list of errors reported.
316 // The accepted Go language version can be controlled with the -lang
318 func TestManual(t *testing.T) {
319 testenv.MustHaveGoBuild(t)
321 filenames := flag.Args()
322 if len(filenames) == 0 {
323 filenames = []string{filepath.FromSlash("testdata/manual.go")}
326 info, err := os.Stat(filenames[0])
328 t.Fatalf("TestManual: %v", err)
331 DefPredeclaredTestFuncs()
333 if len(filenames) > 1 {
334 t.Fatal("TestManual: must have only one directory argument")
336 testDir(t, filenames[0], true)
338 testPkg(t, filenames, true)
342 func TestLongConstants(t *testing.T) {
343 format := `package longconst; const _ = %s /* ERROR "constant overflow" */; const _ = %s // ERROR "excessively long constant"`
344 src := fmt.Sprintf(format, strings.Repeat("1", 9999), strings.Repeat("1", 10001))
345 testFiles(t, []string{"longconst.go"}, [][]byte{[]byte(src)}, false)
348 func withSizes(sizes Sizes) func(*Config) {
349 return func(cfg *Config) {
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, []string{"index.go"}, [][]byte{[]byte(src)}, false, withSizes(&StdSizes{4, 4}))
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, []string{"p.go"}, [][]byte{[]byte(src)}, false, withSizes(&StdSizes{4, 4}))
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 func testPkg(t *testing.T, filenames []string, manual bool) {
422 srcs := make([][]byte, len(filenames))
423 for i, filename := range filenames {
424 src, err := os.ReadFile(filename)
426 t.Fatalf("could not read %s: %v", filename, err)
430 testFiles(t, filenames, srcs, manual)