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 error messages expected in the test files.
9 // Expected errors are indicated in the test files by putting a comment
10 // of the form /* ERROR "rx" */ immediately following an offending token.
11 // The harness will verify that an error matching the regular expression
12 // rx is reported at that source position. Consecutive comments may be
13 // used to indicate multiple errors for the same token position.
15 // For instance, the following test file indicates that a "not declared"
16 // error should be reported for the undeclared variable x:
20 // _ = x /* ERROR "not declared" */ + 1
27 "cmd/compile/internal/syntax"
38 . "cmd/compile/internal/types2"
42 haltOnError = flag.Bool("halt", false, "halt on error")
43 verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
46 func parseFiles(t *testing.T, filenames []string, mode syntax.Mode) ([]*syntax.File, []error) {
47 var files []*syntax.File
49 errh := func(err error) { errlist = append(errlist, err) }
50 for _, filename := range filenames {
51 file, err := syntax.ParseFile(filename, errh, nil, mode)
53 t.Fatalf("%s: %s", filename, err)
55 files = append(files, file)
60 func unpackError(err error) syntax.Error {
61 switch err := err.(type) {
65 return syntax.Error{Pos: err.Pos, Msg: err.Msg}
67 return syntax.Error{Msg: err.Error()}
71 // delta returns the absolute difference between x and y.
72 func delta(x, y uint) uint {
83 // Note: parseFlags is identical to the version in go/types which is
84 // why it has a src argument even though here it is always nil.
86 // parseFlags parses flags from the first line of the given source
87 // (from src if present, or by reading from the file) if the line
88 // starts with "//" (line comment) followed by "-" (possibly with
89 // spaces between). Otherwise the line is ignored.
90 func parseFlags(filename string, src []byte, flags *flag.FlagSet) error {
91 // If there is no src, read from the file.
94 f, err := os.Open(filename)
100 n, err := f.Read(buf[:])
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"))
117 if end < 0 || end > maxLen {
118 return fmt.Errorf("flags comment line too long")
121 return flags.Parse(strings.Fields(string(src[:end])))
124 func testFiles(t *testing.T, filenames []string, colDelta uint, manual bool) {
125 if len(filenames) == 0 {
126 t.Fatal("no source files")
130 flags := flag.NewFlagSet("", flag.PanicOnError)
131 flags.StringVar(&conf.GoVersion, "lang", "", "")
132 flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
133 if err := parseFlags(filenames[0], nil, flags); err != nil {
137 files, errlist := parseFiles(t, filenames, 0)
139 pkgName := "<no package>"
141 pkgName = files[0].PkgName.Value
144 listErrors := manual && !*verifyErrors
145 if listErrors && len(errlist) > 0 {
146 t.Errorf("--- %s:", pkgName)
147 for _, err := range errlist {
152 // typecheck and collect typechecker errors
153 conf.Trace = manual && testing.Verbose()
154 conf.Importer = defaultImporter()
155 conf.Error = func(err error) {
163 errlist = append(errlist, err)
165 conf.Check(pkgName, files, nil)
171 // sort errlist in source order
172 sort.Slice(errlist, func(i, j int) bool {
173 pi := unpackError(errlist[i]).Pos
174 pj := unpackError(errlist[j]).Pos
175 return pi.Cmp(pj) < 0
178 // collect expected errors
179 errmap := make(map[string]map[uint][]syntax.Error)
180 for _, filename := range filenames {
181 f, err := os.Open(filename)
186 if m := syntax.ErrorMap(f); len(m) > 0 {
192 // match against found errors
193 for _, err := range errlist {
194 got := unpackError(err)
196 // find list of errors for the respective error line
197 filename := got.Pos.Base().Filename()
198 filemap := errmap[filename]
199 line := got.Pos.Line()
200 var list []syntax.Error
206 // one of errors in list should match the current error
207 index := -1 // list index of matching message, if any
208 for i, want := range list {
209 rx, err := regexp.Compile(want.Msg)
211 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
214 if rx.MatchString(got.Msg) {
220 t.Errorf("%s: no error expected: %q", got.Pos, got.Msg)
224 // column position must be within expected colDelta
226 if delta(got.Pos.Col(), want.Pos.Col()) > colDelta {
227 t.Errorf("%s: got col = %d; want %d", got.Pos, got.Pos.Col(), want.Pos.Col())
230 // eliminate from list
231 if n := len(list) - 1; n > 0 {
232 // not the last entry - slide entries down (don't reorder)
233 copy(list[index:], list[index+1:])
234 filemap[line] = list[:n]
236 // last entry - remove list from filemap
237 delete(filemap, line)
240 // if filemap is empty, eliminate from errmap
241 if len(filemap) == 0 {
242 delete(errmap, filename)
246 // there should be no expected errors left
248 t.Errorf("--- %s: unreported errors:", pkgName)
249 for filename, filemap := range errmap {
250 for line, list := range filemap {
251 for _, err := range list {
252 t.Errorf("%s:%d:%d: %s", filename, line, err.Pos.Col(), err.Msg)
259 // TestManual is for manual testing of a package - either provided
260 // as a list of filenames belonging to the package, or a directory
261 // name containing the package files - after the test arguments
262 // (and a separating "--"). For instance, to test the package made
263 // of the files foo.go and bar.go, use:
265 // go test -run Manual -- foo.go bar.go
267 // If no source arguments are provided, the file testdata/manual.go
269 // Provide the -verify flag to verify errors against ERROR comments
270 // in the input files rather than having a list of errors reported.
271 // The accepted Go language version can be controlled with the -lang
273 func TestManual(t *testing.T) {
274 testenv.MustHaveGoBuild(t)
276 filenames := flag.Args()
277 if len(filenames) == 0 {
278 filenames = []string{filepath.FromSlash("testdata/manual.go")}
281 info, err := os.Stat(filenames[0])
283 t.Fatalf("TestManual: %v", err)
286 DefPredeclaredTestFuncs()
288 if len(filenames) > 1 {
289 t.Fatal("TestManual: must have only one directory argument")
291 testDir(t, filenames[0], 0, true)
293 testFiles(t, filenames, 0, true)
297 // TODO(gri) go/types has extra TestLongConstants and TestIndexRepresentability tests
299 func TestCheck(t *testing.T) {
300 DefPredeclaredTestFuncs()
301 testDirFiles(t, "../../../../internal/types/testdata/check", 50, false) // TODO(gri) narrow column tolerance
303 func TestSpec(t *testing.T) { testDirFiles(t, "../../../../internal/types/testdata/spec", 0, false) }
304 func TestExamples(t *testing.T) {
305 testDirFiles(t, "../../../../internal/types/testdata/examples", 45, false)
306 } // TODO(gri) narrow column tolerance
307 func TestFixedbugs(t *testing.T) {
308 testDirFiles(t, "../../../../internal/types/testdata/fixedbugs", 100, false)
309 } // TODO(gri) narrow column tolerance
310 func TestLocal(t *testing.T) { testDirFiles(t, "testdata/local", 0, false) }
312 func testDirFiles(t *testing.T, dir string, colDelta uint, manual bool) {
313 testenv.MustHaveGoBuild(t)
314 dir = filepath.FromSlash(dir)
316 fis, err := os.ReadDir(dir)
322 for _, fi := range fis {
323 path := filepath.Join(dir, fi.Name())
325 // If fi is a directory, its files make up a single package.
327 testDir(t, path, colDelta, manual)
329 t.Run(filepath.Base(path), func(t *testing.T) {
330 testFiles(t, []string{path}, colDelta, manual)
336 func testDir(t *testing.T, dir string, colDelta uint, manual bool) {
337 fis, err := os.ReadDir(dir)
343 var filenames []string
344 for _, fi := range fis {
345 filenames = append(filenames, filepath.Join(dir, fi.Name()))
348 t.Run(filepath.Base(dir), func(t *testing.T) {
349 testFiles(t, filenames, colDelta, manual)