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
43 "internal/types/errors"
57 haltOnError = flag.Bool("halt", false, "halt on error")
58 verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
61 var fset = token.NewFileSet()
63 func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode parser.Mode) ([]*ast.File, []error) {
66 for i, filename := range filenames {
67 file, err := parser.ParseFile(fset, filename, srcs[i], mode)
69 t.Fatalf("%s: %s", filename, err)
71 files = append(files, file)
73 if list, _ := err.(scanner.ErrorList); len(list) > 0 {
74 for _, err := range list {
75 errlist = append(errlist, err)
78 errlist = append(errlist, err)
85 func unpackError(fset *token.FileSet, err error) (token.Position, string) {
86 switch err := err.(type) {
88 return err.Pos, err.Msg
90 return fset.Position(err.Pos), err.Msg
95 // absDiff returns the absolute difference between x and y.
96 func absDiff(x, y int) int {
103 // parseFlags parses flags from the first line of the given source if the line
104 // starts with "//" (line comment) followed by "-" (possibly with spaces
105 // between). Otherwise the line is ignored.
106 func parseFlags(src []byte, flags *flag.FlagSet) error {
107 // we must have a line comment that starts with a "-"
109 if !bytes.HasPrefix(src, []byte(prefix)) {
110 return nil // first line is not a line comment
112 src = src[len(prefix):]
113 if i := bytes.Index(src, []byte("-")); i < 0 || len(bytes.TrimSpace(src[:i])) != 0 {
114 return nil // comment doesn't start with a "-"
116 end := bytes.Index(src, []byte("\n"))
118 if end < 0 || end > maxLen {
119 return fmt.Errorf("flags comment line too long")
122 return flags.Parse(strings.Fields(string(src[:end])))
125 // testFiles type-checks the package consisting of the given files, and
126 // compares the resulting errors with the ERROR annotations in the source.
127 // Except for manual tests, each package is type-checked twice, once without
128 // use of Alias types, and once with Alias types.
130 // The srcs slice contains the file content for the files named in the
131 // filenames slice. The colDelta parameter specifies the tolerance for position
132 // mismatch when comparing errors. The manual parameter specifies whether this
133 // is a 'manual' test.
135 // If provided, opts may be used to mutate the Config before type-checking.
136 func testFiles(t *testing.T, filenames []string, srcs [][]byte, manual bool, opts ...func(*Config)) {
137 // Alias types are disabled by default
138 testFilesImpl(t, filenames, srcs, manual, opts...)
140 t.Setenv("GODEBUG", "gotypesalias=1")
141 testFilesImpl(t, filenames, srcs, manual, opts...)
145 func testFilesImpl(t *testing.T, filenames []string, srcs [][]byte, manual bool, opts ...func(*Config)) {
146 if len(filenames) == 0 {
147 t.Fatal("no source files")
151 files, errlist := parseFiles(t, filenames, srcs, parser.AllErrors)
152 pkgName := "<no package>"
154 pkgName = files[0].Name.Name
156 listErrors := manual && !*verifyErrors
157 if listErrors && len(errlist) > 0 {
158 t.Errorf("--- %s:", pkgName)
159 for _, err := range errlist {
164 // set up typechecker
166 *boolFieldAddr(&conf, "_Trace") = manual && testing.Verbose()
167 conf.Importer = importer.Default()
168 conf.Error = func(err error) {
176 // Ignore secondary error messages starting with "\t";
177 // they are clarifying messages for a primary error.
178 if !strings.Contains(err.Error(), ": \t") {
179 errlist = append(errlist, err)
183 // apply custom configuration
184 for _, opt := range opts {
188 // apply flag setting (overrides custom configuration)
189 var goexperiment, gotypesalias string
190 flags := flag.NewFlagSet("", flag.PanicOnError)
191 flags.StringVar(&conf.GoVersion, "lang", "", "")
192 flags.StringVar(&goexperiment, "goexperiment", "", "")
193 flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
194 flags.StringVar(&gotypesalias, "gotypesalias", "", "")
195 if err := parseFlags(srcs[0], flags); err != nil {
199 exp, err := buildcfg.ParseGOEXPERIMENT(runtime.GOOS, runtime.GOARCH, goexperiment)
203 old := buildcfg.Experiment
205 buildcfg.Experiment = old
207 buildcfg.Experiment = *exp
209 // By default, gotypesalias is not set.
210 if gotypesalias != "" {
211 t.Setenv("GODEBUG", "gotypesalias="+gotypesalias)
214 // Provide Config.Info with all maps so that info recording is tested.
216 Types: make(map[ast.Expr]TypeAndValue),
217 Instances: make(map[*ast.Ident]Instance),
218 Defs: make(map[*ast.Ident]Object),
219 Uses: make(map[*ast.Ident]Object),
220 Implicits: make(map[ast.Node]Object),
221 Selections: make(map[*ast.SelectorExpr]*Selection),
222 Scopes: make(map[ast.Node]*Scope),
226 conf.Check(pkgName, fset, files, &info)
231 // collect expected errors
232 errmap := make(map[string]map[int][]comment)
233 for i, filename := range filenames {
234 if m := commentMap(srcs[i], regexp.MustCompile("^ ERRORx? ")); len(m) > 0 {
239 // match against found errors
240 var indices []int // list indices of matching errors, reused for each error
241 for _, err := range errlist {
242 gotPos, gotMsg := unpackError(fset, err)
244 // find list of errors for the respective error line
245 filename := gotPos.Filename
246 filemap := errmap[filename]
248 var errList []comment
250 errList = filemap[line]
253 // At least one of the errors in errList should match the current error.
254 indices = indices[:0]
255 for i, want := range errList {
256 pattern, substr := strings.CutPrefix(want.text, " ERROR ")
259 pattern, found = strings.CutPrefix(want.text, " ERRORx ")
264 pattern, err := strconv.Unquote(strings.TrimSpace(pattern))
266 t.Errorf("%s:%d:%d: %v", filename, line, want.col, err)
270 if !strings.Contains(gotMsg, pattern) {
274 rx, err := regexp.Compile(pattern)
276 t.Errorf("%s:%d:%d: %v", filename, line, want.col, err)
279 if !rx.MatchString(gotMsg) {
283 indices = append(indices, i)
285 if len(indices) == 0 {
286 t.Errorf("%s: no error expected: %q", gotPos, gotMsg)
291 // If there are multiple matching errors, select the one with the closest column position.
292 index := -1 // index of matching error
294 for _, i := range indices {
295 if d := absDiff(gotPos.Column, errList[i].col); index < 0 || d < delta {
300 // The closest column position must be within expected colDelta.
301 const colDelta = 0 // go/types errors are positioned correctly
302 if delta > colDelta {
303 t.Errorf("%s: got col = %d; want %d", gotPos, gotPos.Column, errList[index].col)
306 // eliminate from errList
307 if n := len(errList) - 1; n > 0 {
308 // not the last entry - slide entries down (don't reorder)
309 copy(errList[index:], errList[index+1:])
310 filemap[line] = errList[:n]
312 // last entry - remove errList from filemap
313 delete(filemap, line)
316 // if filemap is empty, eliminate from errmap
317 if len(filemap) == 0 {
318 delete(errmap, filename)
322 // there should be no expected errors left
324 t.Errorf("--- %s: unreported errors:", pkgName)
325 for filename, filemap := range errmap {
326 for line, errList := range filemap {
327 for _, err := range errList {
328 t.Errorf("%s:%d:%d: %s", filename, line, err.col, err.text)
335 func readCode(err Error) errors.Code {
336 v := reflect.ValueOf(err)
337 return errors.Code(v.FieldByName("go116code").Int())
340 // boolFieldAddr(conf, name) returns the address of the boolean field conf.<name>.
341 // For accessing unexported fields.
342 func boolFieldAddr(conf *Config, name string) *bool {
343 v := reflect.Indirect(reflect.ValueOf(conf))
344 return (*bool)(v.FieldByName(name).Addr().UnsafePointer())
347 // stringFieldAddr(conf, name) returns the address of the string field conf.<name>.
348 // For accessing unexported fields.
349 func stringFieldAddr(conf *Config, name string) *string {
350 v := reflect.Indirect(reflect.ValueOf(conf))
351 return (*string)(v.FieldByName(name).Addr().UnsafePointer())
354 // TestManual is for manual testing of a package - either provided
355 // as a list of filenames belonging to the package, or a directory
356 // name containing the package files - after the test arguments
357 // (and a separating "--"). For instance, to test the package made
358 // of the files foo.go and bar.go, use:
360 // go test -run Manual -- foo.go bar.go
362 // If no source arguments are provided, the file testdata/manual.go
364 // Provide the -verify flag to verify errors against ERROR comments
365 // in the input files rather than having a list of errors reported.
366 // The accepted Go language version can be controlled with the -lang
368 func TestManual(t *testing.T) {
369 testenv.MustHaveGoBuild(t)
371 filenames := flag.Args()
372 if len(filenames) == 0 {
373 filenames = []string{filepath.FromSlash("testdata/manual.go")}
376 info, err := os.Stat(filenames[0])
378 t.Fatalf("TestManual: %v", err)
381 DefPredeclaredTestFuncs()
383 if len(filenames) > 1 {
384 t.Fatal("TestManual: must have only one directory argument")
386 testDir(t, filenames[0], true)
388 testPkg(t, filenames, true)
392 func TestLongConstants(t *testing.T) {
393 format := `package longconst; const _ = %s /* ERROR "constant overflow" */; const _ = %s // ERROR "excessively long constant"`
394 src := fmt.Sprintf(format, strings.Repeat("1", 9999), strings.Repeat("1", 10001))
395 testFiles(t, []string{"longconst.go"}, [][]byte{[]byte(src)}, false)
398 func withSizes(sizes Sizes) func(*Config) {
399 return func(cfg *Config) {
404 // TestIndexRepresentability tests that constant index operands must
405 // be representable as int even if they already have a type that can
406 // represent larger values.
407 func TestIndexRepresentability(t *testing.T) {
408 const src = `package index; var s []byte; var _ = s[int64 /* ERRORx "int64\\(1\\) << 40 \\(.*\\) overflows int" */ (1) << 40]`
409 testFiles(t, []string{"index.go"}, [][]byte{[]byte(src)}, false, withSizes(&StdSizes{4, 4}))
412 func TestIssue47243_TypedRHS(t *testing.T) {
413 // The RHS of the shift expression below overflows uint on 32bit platforms,
414 // but this is OK as it is explicitly typed.
415 const src = `package issue47243; var a uint64; var _ = a << uint64(4294967296)` // uint64(1<<32)
416 testFiles(t, []string{"p.go"}, [][]byte{[]byte(src)}, false, withSizes(&StdSizes{4, 4}))
419 func TestCheck(t *testing.T) {
420 old := buildcfg.Experiment.RangeFunc
422 buildcfg.Experiment.RangeFunc = old
424 buildcfg.Experiment.RangeFunc = true
426 DefPredeclaredTestFuncs()
427 testDirFiles(t, "../../internal/types/testdata/check", false)
429 func TestSpec(t *testing.T) { testDirFiles(t, "../../internal/types/testdata/spec", false) }
430 func TestExamples(t *testing.T) { testDirFiles(t, "../../internal/types/testdata/examples", false) }
431 func TestFixedbugs(t *testing.T) { testDirFiles(t, "../../internal/types/testdata/fixedbugs", false) }
432 func TestLocal(t *testing.T) { testDirFiles(t, "testdata/local", false) }
434 func testDirFiles(t *testing.T, dir string, manual bool) {
435 testenv.MustHaveGoBuild(t)
436 dir = filepath.FromSlash(dir)
438 fis, err := os.ReadDir(dir)
444 for _, fi := range fis {
445 path := filepath.Join(dir, fi.Name())
447 // If fi is a directory, its files make up a single package.
449 testDir(t, path, manual)
451 t.Run(filepath.Base(path), func(t *testing.T) {
452 testPkg(t, []string{path}, manual)
458 func testDir(t *testing.T, dir string, manual bool) {
459 testenv.MustHaveGoBuild(t)
461 fis, err := os.ReadDir(dir)
467 var filenames []string
468 for _, fi := range fis {
469 filenames = append(filenames, filepath.Join(dir, fi.Name()))
472 t.Run(filepath.Base(dir), func(t *testing.T) {
473 testPkg(t, filenames, manual)
477 func testPkg(t *testing.T, filenames []string, manual bool) {
478 srcs := make([][]byte, len(filenames))
479 for i, filename := range filenames {
480 src, err := os.ReadFile(filename)
482 t.Fatalf("could not read %s: %v", filename, err)
486 testFiles(t, filenames, srcs, manual)