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"
46 . "cmd/compile/internal/types2"
50 haltOnError = flag.Bool("halt", false, "halt on error")
51 verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
54 func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode syntax.Mode) ([]*syntax.File, []error) {
55 var files []*syntax.File
57 errh := func(err error) { errlist = append(errlist, err) }
58 for i, filename := range filenames {
59 base := syntax.NewFileBase(filename)
60 r := bytes.NewReader(srcs[i])
61 file, err := syntax.Parse(base, r, errh, nil, mode)
63 t.Fatalf("%s: %s", filename, err)
65 files = append(files, file)
70 func unpackError(err error) (syntax.Pos, string) {
71 switch err := err.(type) {
73 return err.Pos, err.Msg
75 return err.Pos, err.Msg
77 return nopos, err.Error()
81 // absDiff returns the absolute difference between x and y.
82 func absDiff(x, y uint) uint {
89 // parseFlags parses flags from the first line of the given source if the line
90 // starts with "//" (line comment) followed by "-" (possibly with spaces
91 // between). Otherwise the line is ignored.
92 func parseFlags(src []byte, flags *flag.FlagSet) error {
93 // we must have a line comment that starts with a "-"
95 if !bytes.HasPrefix(src, []byte(prefix)) {
96 return nil // first line is not a line comment
98 src = src[len(prefix):]
99 if i := bytes.Index(src, []byte("-")); i < 0 || len(bytes.TrimSpace(src[:i])) != 0 {
100 return nil // comment doesn't start with a "-"
102 end := bytes.Index(src, []byte("\n"))
104 if end < 0 || end > maxLen {
105 return fmt.Errorf("flags comment line too long")
108 return flags.Parse(strings.Fields(string(src[:end])))
111 // testFiles type-checks the package consisting of the given files, and
112 // compares the resulting errors with the ERROR annotations in the source.
114 // The srcs slice contains the file content for the files named in the
115 // filenames slice. The colDelta parameter specifies the tolerance for position
116 // mismatch when comparing errors. The manual parameter specifies whether this
117 // is a 'manual' test.
119 // If provided, opts may be used to mutate the Config before type-checking.
120 func testFiles(t *testing.T, filenames []string, srcs [][]byte, colDelta uint, manual bool, opts ...func(*Config)) {
121 if len(filenames) == 0 {
122 t.Fatal("no source files")
126 flags := flag.NewFlagSet("", flag.PanicOnError)
127 flags.StringVar(&conf.GoVersion, "lang", "", "")
128 flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
129 if err := parseFlags(srcs[0], flags); err != nil {
133 files, errlist := parseFiles(t, filenames, srcs, 0)
135 pkgName := "<no package>"
137 pkgName = files[0].PkgName.Value
140 listErrors := manual && !*verifyErrors
141 if listErrors && len(errlist) > 0 {
142 t.Errorf("--- %s:", pkgName)
143 for _, err := range errlist {
148 // typecheck and collect typechecker errors
149 conf.Trace = manual && testing.Verbose()
150 conf.Importer = defaultImporter()
151 conf.Error = func(err error) {
159 errlist = append(errlist, err)
162 for _, opt := range opts {
166 conf.Check(pkgName, files, nil)
172 // collect expected errors
173 errmap := make(map[string]map[uint][]syntax.Error)
174 for i, filename := range filenames {
175 if m := syntax.CommentMap(bytes.NewReader(srcs[i]), regexp.MustCompile("^ ERRORx? ")); len(m) > 0 {
180 // match against found errors
181 var indices []int // list indices of matching errors, reused for each error
182 for _, err := range errlist {
183 gotPos, gotMsg := unpackError(err)
185 // find list of errors for the respective error line
186 filename := gotPos.Base().Filename()
187 filemap := errmap[filename]
188 line := gotPos.Line()
189 var errList []syntax.Error
191 errList = filemap[line]
194 // At least one of the errors in errList should match the current error.
195 indices = indices[:0]
196 for i, want := range errList {
197 pattern, substr := strings.CutPrefix(want.Msg, " ERROR ")
200 pattern, found = strings.CutPrefix(want.Msg, " ERRORx ")
205 pattern, err := strconv.Unquote(strings.TrimSpace(pattern))
207 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
211 if !strings.Contains(gotMsg, pattern) {
215 rx, err := regexp.Compile(pattern)
217 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
220 if !rx.MatchString(gotMsg) {
224 indices = append(indices, i)
226 if len(indices) == 0 {
227 t.Errorf("%s: no error expected: %q", gotPos, gotMsg)
232 // If there are multiple matching errors, select the one with the closest column position.
233 index := -1 // index of matching error
235 for _, i := range indices {
236 if d := absDiff(gotPos.Col(), errList[i].Pos.Col()); index < 0 || d < delta {
241 // The closest column position must be within expected colDelta.
242 if delta > colDelta {
243 t.Errorf("%s: got col = %d; want %d", gotPos, gotPos.Col(), errList[index].Pos.Col())
246 // eliminate from errList
247 if n := len(errList) - 1; n > 0 {
248 // not the last entry - slide entries down (don't reorder)
249 copy(errList[index:], errList[index+1:])
250 filemap[line] = errList[:n]
252 // last entry - remove errList from filemap
253 delete(filemap, line)
256 // if filemap is empty, eliminate from errmap
257 if len(filemap) == 0 {
258 delete(errmap, filename)
262 // there should be no expected errors left
264 t.Errorf("--- %s: unreported errors:", pkgName)
265 for filename, filemap := range errmap {
266 for line, errList := range filemap {
267 for _, err := range errList {
268 t.Errorf("%s:%d:%d: %s", filename, line, err.Pos.Col(), err.Msg)
275 // boolFieldAddr(conf, name) returns the address of the boolean field conf.<name>.
276 // For accessing unexported fields.
277 func boolFieldAddr(conf *Config, name string) *bool {
278 v := reflect.Indirect(reflect.ValueOf(conf))
279 return (*bool)(v.FieldByName(name).Addr().UnsafePointer())
282 // TestManual is for manual testing of a package - either provided
283 // as a list of filenames belonging to the package, or a directory
284 // name containing the package files - after the test arguments
285 // (and a separating "--"). For instance, to test the package made
286 // of the files foo.go and bar.go, use:
288 // go test -run Manual -- foo.go bar.go
290 // If no source arguments are provided, the file testdata/manual.go
292 // Provide the -verify flag to verify errors against ERROR comments
293 // in the input files rather than having a list of errors reported.
294 // The accepted Go language version can be controlled with the -lang
296 func TestManual(t *testing.T) {
297 testenv.MustHaveGoBuild(t)
299 filenames := flag.Args()
300 if len(filenames) == 0 {
301 filenames = []string{filepath.FromSlash("testdata/manual.go")}
304 info, err := os.Stat(filenames[0])
306 t.Fatalf("TestManual: %v", err)
309 DefPredeclaredTestFuncs()
311 if len(filenames) > 1 {
312 t.Fatal("TestManual: must have only one directory argument")
314 testDir(t, filenames[0], 0, true)
316 testPkg(t, filenames, 0, true)
320 // TODO(gri) go/types has extra TestLongConstants and TestIndexRepresentability tests
322 func TestCheck(t *testing.T) {
323 DefPredeclaredTestFuncs()
324 testDirFiles(t, "../../../../internal/types/testdata/check", 50, false) // TODO(gri) narrow column tolerance
326 func TestSpec(t *testing.T) { testDirFiles(t, "../../../../internal/types/testdata/spec", 0, false) }
327 func TestExamples(t *testing.T) {
328 testDirFiles(t, "../../../../internal/types/testdata/examples", 125, false)
329 } // TODO(gri) narrow column tolerance
330 func TestFixedbugs(t *testing.T) {
331 testDirFiles(t, "../../../../internal/types/testdata/fixedbugs", 100, false)
332 } // TODO(gri) narrow column tolerance
333 func TestLocal(t *testing.T) { testDirFiles(t, "testdata/local", 0, false) }
335 func testDirFiles(t *testing.T, dir string, colDelta uint, manual bool) {
336 testenv.MustHaveGoBuild(t)
337 dir = filepath.FromSlash(dir)
339 fis, err := os.ReadDir(dir)
345 for _, fi := range fis {
346 path := filepath.Join(dir, fi.Name())
348 // If fi is a directory, its files make up a single package.
350 testDir(t, path, colDelta, manual)
352 t.Run(filepath.Base(path), func(t *testing.T) {
353 testPkg(t, []string{path}, colDelta, manual)
359 func testDir(t *testing.T, dir string, colDelta uint, manual bool) {
360 fis, err := os.ReadDir(dir)
366 var filenames []string
367 for _, fi := range fis {
368 filenames = append(filenames, filepath.Join(dir, fi.Name()))
371 t.Run(filepath.Base(dir), func(t *testing.T) {
372 testPkg(t, filenames, colDelta, manual)
376 func testPkg(t *testing.T, filenames []string, colDelta uint, manual bool) {
377 srcs := make([][]byte, len(filenames))
378 for i, filename := range filenames {
379 src, err := os.ReadFile(filename)
381 t.Fatalf("could not read %s: %v", filename, err)
385 testFiles(t, filenames, srcs, colDelta, manual)