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"
45 . "cmd/compile/internal/types2"
49 haltOnError = flag.Bool("halt", false, "halt on error")
50 verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
53 func parseFiles(t *testing.T, filenames []string, mode syntax.Mode) ([]*syntax.File, []error) {
54 var files []*syntax.File
56 errh := func(err error) { errlist = append(errlist, err) }
57 for _, filename := range filenames {
58 file, err := syntax.ParseFile(filename, errh, nil, mode)
60 t.Fatalf("%s: %s", filename, err)
62 files = append(files, file)
67 func unpackError(err error) (syntax.Pos, string) {
68 switch err := err.(type) {
70 return err.Pos, err.Msg
72 return err.Pos, err.Msg
74 return nopos, err.Error()
78 // absDiff returns the absolute difference between x and y.
79 func absDiff(x, y uint) uint {
86 // Note: parseFlags is identical to the version in go/types which is
87 // why it has a src argument even though here it is always nil.
89 // parseFlags parses flags from the first line of the given source
90 // (from src if present, or by reading from the file) if the line
91 // starts with "//" (line comment) followed by "-" (possibly with
92 // spaces between). Otherwise the line is ignored.
93 func parseFlags(filename string, src []byte, flags *flag.FlagSet) error {
94 // If there is no src, read from the file.
97 f, err := os.Open(filename)
103 n, err := f.Read(buf[:])
110 // we must have a line comment that starts with a "-"
112 if !bytes.HasPrefix(src, []byte(prefix)) {
113 return nil // first line is not a line comment
115 src = src[len(prefix):]
116 if i := bytes.Index(src, []byte("-")); i < 0 || len(bytes.TrimSpace(src[:i])) != 0 {
117 return nil // comment doesn't start with a "-"
119 end := bytes.Index(src, []byte("\n"))
120 if end < 0 || end > maxLen {
121 return fmt.Errorf("flags comment line too long")
124 return flags.Parse(strings.Fields(string(src[:end])))
127 func testFiles(t *testing.T, filenames []string, colDelta uint, manual bool) {
128 if len(filenames) == 0 {
129 t.Fatal("no source files")
133 flags := flag.NewFlagSet("", flag.PanicOnError)
134 flags.StringVar(&conf.GoVersion, "lang", "", "")
135 flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
136 if err := parseFlags(filenames[0], nil, flags); err != nil {
140 files, errlist := parseFiles(t, filenames, 0)
142 pkgName := "<no package>"
144 pkgName = files[0].PkgName.Value
147 listErrors := manual && !*verifyErrors
148 if listErrors && len(errlist) > 0 {
149 t.Errorf("--- %s:", pkgName)
150 for _, err := range errlist {
155 // typecheck and collect typechecker errors
156 conf.Trace = manual && testing.Verbose()
157 conf.Importer = defaultImporter()
158 conf.Error = func(err error) {
166 errlist = append(errlist, err)
168 conf.Check(pkgName, files, nil)
174 // collect expected errors
175 errmap := make(map[string]map[uint][]syntax.Error)
176 for _, filename := range filenames {
177 f, err := os.Open(filename)
182 if m := syntax.CommentMap(f, regexp.MustCompile("^ ERRORx? ")); len(m) > 0 {
188 // match against found errors
189 var indices []int // list indices of matching errors, reused for each error
190 for _, err := range errlist {
191 gotPos, gotMsg := unpackError(err)
193 // find list of errors for the respective error line
194 filename := gotPos.Base().Filename()
195 filemap := errmap[filename]
196 line := gotPos.Line()
197 var errList []syntax.Error
199 errList = filemap[line]
202 // At least one of the errors in errList should match the current error.
203 indices = indices[:0]
204 for i, want := range errList {
205 pattern, substr := strings.CutPrefix(want.Msg, " ERROR ")
208 pattern, found = strings.CutPrefix(want.Msg, " ERRORx ")
213 pattern, err := strconv.Unquote(strings.TrimSpace(pattern))
215 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
219 if !strings.Contains(gotMsg, pattern) {
223 rx, err := regexp.Compile(pattern)
225 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
228 if !rx.MatchString(gotMsg) {
232 indices = append(indices, i)
234 if len(indices) == 0 {
235 t.Errorf("%s: no error expected: %q", gotPos, gotMsg)
240 // If there are multiple matching errors, select the one with the closest column position.
241 index := -1 // index of matching error
243 for _, i := range indices {
244 if d := absDiff(gotPos.Col(), errList[i].Pos.Col()); index < 0 || d < delta {
249 // The closest column position must be within expected colDelta.
250 if delta > colDelta {
251 t.Errorf("%s: got col = %d; want %d", gotPos, gotPos.Col(), errList[index].Pos.Col())
254 // eliminate from errList
255 if n := len(errList) - 1; n > 0 {
256 // not the last entry - slide entries down (don't reorder)
257 copy(errList[index:], errList[index+1:])
258 filemap[line] = errList[:n]
260 // last entry - remove errList from filemap
261 delete(filemap, line)
264 // if filemap is empty, eliminate from errmap
265 if len(filemap) == 0 {
266 delete(errmap, filename)
270 // there should be no expected errors left
272 t.Errorf("--- %s: unreported errors:", pkgName)
273 for filename, filemap := range errmap {
274 for line, errList := range filemap {
275 for _, err := range errList {
276 t.Errorf("%s:%d:%d: %s", filename, line, err.Pos.Col(), err.Msg)
283 // TestManual is for manual testing of a package - either provided
284 // as a list of filenames belonging to the package, or a directory
285 // name containing the package files - after the test arguments
286 // (and a separating "--"). For instance, to test the package made
287 // of the files foo.go and bar.go, use:
289 // go test -run Manual -- foo.go bar.go
291 // If no source arguments are provided, the file testdata/manual.go
293 // Provide the -verify flag to verify errors against ERROR comments
294 // in the input files rather than having a list of errors reported.
295 // The accepted Go language version can be controlled with the -lang
297 func TestManual(t *testing.T) {
298 testenv.MustHaveGoBuild(t)
300 filenames := flag.Args()
301 if len(filenames) == 0 {
302 filenames = []string{filepath.FromSlash("testdata/manual.go")}
305 info, err := os.Stat(filenames[0])
307 t.Fatalf("TestManual: %v", err)
310 DefPredeclaredTestFuncs()
312 if len(filenames) > 1 {
313 t.Fatal("TestManual: must have only one directory argument")
315 testDir(t, filenames[0], 0, true)
317 testFiles(t, filenames, 0, true)
321 // TODO(gri) go/types has extra TestLongConstants and TestIndexRepresentability tests
323 func TestCheck(t *testing.T) {
324 DefPredeclaredTestFuncs()
325 testDirFiles(t, "../../../../internal/types/testdata/check", 50, false) // TODO(gri) narrow column tolerance
327 func TestSpec(t *testing.T) { testDirFiles(t, "../../../../internal/types/testdata/spec", 0, false) }
328 func TestExamples(t *testing.T) {
329 testDirFiles(t, "../../../../internal/types/testdata/examples", 60, false)
330 } // TODO(gri) narrow column tolerance
331 func TestFixedbugs(t *testing.T) {
332 testDirFiles(t, "../../../../internal/types/testdata/fixedbugs", 100, false)
333 } // TODO(gri) narrow column tolerance
334 func TestLocal(t *testing.T) { testDirFiles(t, "testdata/local", 0, false) }
336 func testDirFiles(t *testing.T, dir string, colDelta uint, manual bool) {
337 testenv.MustHaveGoBuild(t)
338 dir = filepath.FromSlash(dir)
340 fis, err := os.ReadDir(dir)
346 for _, fi := range fis {
347 path := filepath.Join(dir, fi.Name())
349 // If fi is a directory, its files make up a single package.
351 testDir(t, path, colDelta, manual)
353 t.Run(filepath.Base(path), func(t *testing.T) {
354 testFiles(t, []string{path}, colDelta, manual)
360 func testDir(t *testing.T, dir string, colDelta uint, manual bool) {
361 fis, err := os.ReadDir(dir)
367 var filenames []string
368 for _, fi := range fis {
369 filenames = append(filenames, filepath.Join(dir, fi.Name()))
372 t.Run(filepath.Base(dir), func(t *testing.T) {
373 testFiles(t, filenames, colDelta, manual)