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
34 "cmd/compile/internal/syntax"
48 . "cmd/compile/internal/types2"
52 haltOnError = flag.Bool("halt", false, "halt on error")
53 verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
54 enableAlias = flag.Bool("alias", false, "set Config._EnableAlias for tests")
57 func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode syntax.Mode) ([]*syntax.File, []error) {
58 var files []*syntax.File
60 errh := func(err error) { errlist = append(errlist, err) }
61 for i, filename := range filenames {
62 base := syntax.NewFileBase(filename)
63 r := bytes.NewReader(srcs[i])
64 file, err := syntax.Parse(base, r, errh, nil, mode)
66 t.Fatalf("%s: %s", filename, err)
68 files = append(files, file)
73 func unpackError(err error) (syntax.Pos, string) {
74 switch err := err.(type) {
76 return err.Pos, err.Msg
78 return err.Pos, err.Msg
80 return nopos, err.Error()
84 // absDiff returns the absolute difference between x and y.
85 func absDiff(x, y uint) uint {
92 // parseFlags parses flags from the first line of the given source if the line
93 // starts with "//" (line comment) followed by "-" (possibly with spaces
94 // between). Otherwise the line is ignored.
95 func parseFlags(src []byte, flags *flag.FlagSet) error {
96 // we must have a line comment that starts with a "-"
98 if !bytes.HasPrefix(src, []byte(prefix)) {
99 return nil // first line is not a line comment
101 src = src[len(prefix):]
102 if i := bytes.Index(src, []byte("-")); i < 0 || len(bytes.TrimSpace(src[:i])) != 0 {
103 return nil // comment doesn't start with a "-"
105 end := bytes.Index(src, []byte("\n"))
107 if end < 0 || end > maxLen {
108 return fmt.Errorf("flags comment line too long")
111 return flags.Parse(strings.Fields(string(src[:end])))
114 // testFiles type-checks the package consisting of the given files, and
115 // compares the resulting errors with the ERROR annotations in the source.
117 // The srcs slice contains the file content for the files named in the
118 // filenames slice. The colDelta parameter specifies the tolerance for position
119 // mismatch when comparing errors. The manual parameter specifies whether this
120 // is a 'manual' test.
122 // If provided, opts may be used to mutate the Config before type-checking.
123 func testFiles(t *testing.T, filenames []string, srcs [][]byte, colDelta uint, manual bool, opts ...func(*Config)) {
124 if len(filenames) == 0 {
125 t.Fatal("no source files")
129 var goexperiment string
130 flags := flag.NewFlagSet("", flag.PanicOnError)
131 flags.StringVar(&conf.GoVersion, "lang", "", "")
132 flags.StringVar(&goexperiment, "goexperiment", "", "")
133 flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
134 flags.BoolVar(boolFieldAddr(&conf, "_EnableAlias"), "alias", *enableAlias, "")
135 if err := parseFlags(srcs[0], flags); err != nil {
138 exp, err := buildcfg.ParseGOEXPERIMENT(runtime.GOOS, runtime.GOARCH, goexperiment)
142 old := buildcfg.Experiment
144 buildcfg.Experiment = old
146 buildcfg.Experiment = *exp
148 files, errlist := parseFiles(t, filenames, srcs, 0)
150 pkgName := "<no package>"
152 pkgName = files[0].PkgName.Value
155 listErrors := manual && !*verifyErrors
156 if listErrors && len(errlist) > 0 {
157 t.Errorf("--- %s:", pkgName)
158 for _, err := range errlist {
163 // typecheck and collect typechecker errors
164 conf.Trace = manual && testing.Verbose()
165 conf.Importer = defaultImporter()
166 conf.Error = func(err error) {
174 errlist = append(errlist, err)
177 for _, opt := range opts {
181 // Provide Config.Info with all maps so that info recording is tested.
183 Types: make(map[syntax.Expr]TypeAndValue),
184 Instances: make(map[*syntax.Name]Instance),
185 Defs: make(map[*syntax.Name]Object),
186 Uses: make(map[*syntax.Name]Object),
187 Implicits: make(map[syntax.Node]Object),
188 Selections: make(map[*syntax.SelectorExpr]*Selection),
189 Scopes: make(map[syntax.Node]*Scope),
191 conf.Check(pkgName, files, &info)
197 // collect expected errors
198 errmap := make(map[string]map[uint][]syntax.Error)
199 for i, filename := range filenames {
200 if m := syntax.CommentMap(bytes.NewReader(srcs[i]), regexp.MustCompile("^ ERRORx? ")); len(m) > 0 {
205 // match against found errors
206 var indices []int // list indices of matching errors, reused for each error
207 for _, err := range errlist {
208 gotPos, gotMsg := unpackError(err)
210 // find list of errors for the respective error line
211 filename := gotPos.Base().Filename()
212 filemap := errmap[filename]
213 line := gotPos.Line()
214 var errList []syntax.Error
216 errList = filemap[line]
219 // At least one of the errors in errList should match the current error.
220 indices = indices[:0]
221 for i, want := range errList {
222 pattern, substr := strings.CutPrefix(want.Msg, " ERROR ")
225 pattern, found = strings.CutPrefix(want.Msg, " ERRORx ")
230 pattern, err := strconv.Unquote(strings.TrimSpace(pattern))
232 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
236 if !strings.Contains(gotMsg, pattern) {
240 rx, err := regexp.Compile(pattern)
242 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
245 if !rx.MatchString(gotMsg) {
249 indices = append(indices, i)
251 if len(indices) == 0 {
252 t.Errorf("%s: no error expected: %q", gotPos, gotMsg)
257 // If there are multiple matching errors, select the one with the closest column position.
258 index := -1 // index of matching error
260 for _, i := range indices {
261 if d := absDiff(gotPos.Col(), errList[i].Pos.Col()); index < 0 || d < delta {
266 // The closest column position must be within expected colDelta.
267 if delta > colDelta {
268 t.Errorf("%s: got col = %d; want %d", gotPos, gotPos.Col(), errList[index].Pos.Col())
271 // eliminate from errList
272 if n := len(errList) - 1; n > 0 {
273 // not the last entry - slide entries down (don't reorder)
274 copy(errList[index:], errList[index+1:])
275 filemap[line] = errList[:n]
277 // last entry - remove errList from filemap
278 delete(filemap, line)
281 // if filemap is empty, eliminate from errmap
282 if len(filemap) == 0 {
283 delete(errmap, filename)
287 // there should be no expected errors left
289 t.Errorf("--- %s: unreported errors:", pkgName)
290 for filename, filemap := range errmap {
291 for line, errList := range filemap {
292 for _, err := range errList {
293 t.Errorf("%s:%d:%d: %s", filename, line, err.Pos.Col(), err.Msg)
300 // boolFieldAddr(conf, name) returns the address of the boolean field conf.<name>.
301 // For accessing unexported fields.
302 func boolFieldAddr(conf *Config, name string) *bool {
303 v := reflect.Indirect(reflect.ValueOf(conf))
304 return (*bool)(v.FieldByName(name).Addr().UnsafePointer())
307 // TestManual is for manual testing of a package - either provided
308 // as a list of filenames belonging to the package, or a directory
309 // name containing the package files - after the test arguments
310 // (and a separating "--"). For instance, to test the package made
311 // of the files foo.go and bar.go, use:
313 // go test -run Manual -- foo.go bar.go
315 // If no source arguments are provided, the file testdata/manual.go
317 // Provide the -verify flag to verify errors against ERROR comments
318 // in the input files rather than having a list of errors reported.
319 // The accepted Go language version can be controlled with the -lang
321 func TestManual(t *testing.T) {
322 testenv.MustHaveGoBuild(t)
324 filenames := flag.Args()
325 if len(filenames) == 0 {
326 filenames = []string{filepath.FromSlash("testdata/manual.go")}
329 info, err := os.Stat(filenames[0])
331 t.Fatalf("TestManual: %v", err)
334 DefPredeclaredTestFuncs()
336 if len(filenames) > 1 {
337 t.Fatal("TestManual: must have only one directory argument")
339 testDir(t, filenames[0], 0, true)
341 testPkg(t, filenames, 0, true)
345 func TestLongConstants(t *testing.T) {
346 format := `package longconst; const _ = %s /* ERROR "constant overflow" */; const _ = %s // ERROR "excessively long constant"`
347 src := fmt.Sprintf(format, strings.Repeat("1", 9999), strings.Repeat("1", 10001))
348 testFiles(t, []string{"longconst.go"}, [][]byte{[]byte(src)}, 0, false)
351 func withSizes(sizes Sizes) func(*Config) {
352 return func(cfg *Config) {
357 // TestIndexRepresentability tests that constant index operands must
358 // be representable as int even if they already have a type that can
359 // represent larger values.
360 func TestIndexRepresentability(t *testing.T) {
361 const src = `package index; var s []byte; var _ = s[int64 /* ERRORx "int64\\(1\\) << 40 \\(.*\\) overflows int" */ (1) << 40]`
362 testFiles(t, []string{"index.go"}, [][]byte{[]byte(src)}, 0, false, withSizes(&StdSizes{4, 4}))
365 func TestIssue47243_TypedRHS(t *testing.T) {
366 // The RHS of the shift expression below overflows uint on 32bit platforms,
367 // but this is OK as it is explicitly typed.
368 const src = `package issue47243; var a uint64; var _ = a << uint64(4294967296)` // uint64(1<<32)
369 testFiles(t, []string{"p.go"}, [][]byte{[]byte(src)}, 0, false, withSizes(&StdSizes{4, 4}))
372 func TestCheck(t *testing.T) {
373 old := buildcfg.Experiment.RangeFunc
375 buildcfg.Experiment.RangeFunc = old
377 buildcfg.Experiment.RangeFunc = true
379 DefPredeclaredTestFuncs()
380 testDirFiles(t, "../../../../internal/types/testdata/check", 50, false) // TODO(gri) narrow column tolerance
382 func TestSpec(t *testing.T) { testDirFiles(t, "../../../../internal/types/testdata/spec", 0, false) }
383 func TestExamples(t *testing.T) {
384 testDirFiles(t, "../../../../internal/types/testdata/examples", 125, false)
385 } // TODO(gri) narrow column tolerance
386 func TestFixedbugs(t *testing.T) {
387 testDirFiles(t, "../../../../internal/types/testdata/fixedbugs", 100, false)
388 } // TODO(gri) narrow column tolerance
389 func TestLocal(t *testing.T) { testDirFiles(t, "testdata/local", 0, false) }
391 func testDirFiles(t *testing.T, dir string, colDelta uint, manual bool) {
392 testenv.MustHaveGoBuild(t)
393 dir = filepath.FromSlash(dir)
395 fis, err := os.ReadDir(dir)
401 for _, fi := range fis {
402 path := filepath.Join(dir, fi.Name())
404 // If fi is a directory, its files make up a single package.
406 testDir(t, path, colDelta, manual)
408 t.Run(filepath.Base(path), func(t *testing.T) {
409 testPkg(t, []string{path}, colDelta, manual)
415 func testDir(t *testing.T, dir string, colDelta uint, manual bool) {
416 fis, err := os.ReadDir(dir)
422 var filenames []string
423 for _, fi := range fis {
424 filenames = append(filenames, filepath.Join(dir, fi.Name()))
427 t.Run(filepath.Base(dir), func(t *testing.T) {
428 testPkg(t, filenames, colDelta, manual)
432 func testPkg(t *testing.T, filenames []string, colDelta uint, manual bool) {
433 srcs := make([][]byte, len(filenames))
434 for i, filename := range filenames {
435 src, err := os.ReadFile(filename)
437 t.Fatalf("could not read %s: %v", filename, err)
441 testFiles(t, filenames, srcs, colDelta, manual)