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")
44 goVersion = flag.String("lang", "", "Go language version (e.g. \"go1.12\")")
47 func parseFiles(t *testing.T, filenames []string, mode syntax.Mode) ([]*syntax.File, []error) {
48 var files []*syntax.File
50 errh := func(err error) { errlist = append(errlist, err) }
51 for _, filename := range filenames {
52 file, err := syntax.ParseFile(filename, errh, nil, mode)
54 t.Fatalf("%s: %s", filename, err)
56 files = append(files, file)
61 func unpackError(err error) syntax.Error {
62 switch err := err.(type) {
66 return syntax.Error{Pos: err.Pos, Msg: err.Msg}
68 return syntax.Error{Msg: err.Error()}
72 // delta returns the absolute difference between x and y.
73 func delta(x, y uint) uint {
84 // Note: parseFlags is identical to the version in go/types which is
85 // why it has a src argument even though here it is always nil.
87 // parseFlags parses flags from the first line of the given source
88 // (from src if present, or by reading from the file) if the line
89 // starts with "//" (line comment) followed by "-" (possiby with
90 // spaces between). Otherwise the line is ignored.
91 func parseFlags(filename string, src []byte, flags *flag.FlagSet) error {
92 // If there is no src, read from the file.
95 f, err := os.Open(filename)
101 n, err := f.Read(buf[:])
108 // we must have a line comment that starts with a "-"
110 if !bytes.HasPrefix(src, []byte(prefix)) {
111 return nil // first line is not a line comment
113 src = src[len(prefix):]
114 if i := bytes.Index(src, []byte("-")); i < 0 || len(bytes.TrimSpace(src[:i])) != 0 {
115 return nil // comment doesn't start with a "-"
117 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 func testFiles(t *testing.T, filenames []string, colDelta uint, manual bool) {
126 if len(filenames) == 0 {
127 t.Fatal("no source files")
131 flags := flag.NewFlagSet("", flag.PanicOnError)
132 flags.StringVar(&conf.GoVersion, "lang", "", "")
133 flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
134 if err := parseFlags(filenames[0], nil, flags); err != nil {
138 files, errlist := parseFiles(t, filenames, syntax.AllowGenerics|syntax.AllowMethodTypeParams)
140 pkgName := "<no package>"
142 pkgName = files[0].PkgName.Value
145 listErrors := manual && !*verifyErrors
146 if listErrors && len(errlist) > 0 {
147 t.Errorf("--- %s:", pkgName)
148 for _, err := range errlist {
153 // typecheck and collect typechecker errors
154 conf.Trace = manual && testing.Verbose()
155 conf.Importer = defaultImporter()
156 conf.Error = func(err error) {
164 errlist = append(errlist, err)
166 conf.Check(pkgName, files, nil)
172 // sort errlist in source order
173 sort.Slice(errlist, func(i, j int) bool {
174 pi := unpackError(errlist[i]).Pos
175 pj := unpackError(errlist[j]).Pos
176 return pi.Cmp(pj) < 0
179 // collect expected errors
180 errmap := make(map[string]map[uint][]syntax.Error)
181 for _, filename := range filenames {
182 f, err := os.Open(filename)
187 if m := syntax.ErrorMap(f); len(m) > 0 {
193 // match against found errors
194 for _, err := range errlist {
195 got := unpackError(err)
197 // find list of errors for the respective error line
198 filename := got.Pos.Base().Filename()
199 filemap := errmap[filename]
200 line := got.Pos.Line()
201 var list []syntax.Error
207 // one of errors in list should match the current error
208 index := -1 // list index of matching message, if any
209 for i, want := range list {
210 rx, err := regexp.Compile(want.Msg)
212 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
215 if rx.MatchString(got.Msg) {
221 t.Errorf("%s: no error expected: %q", got.Pos, got.Msg)
225 // column position must be within expected colDelta
227 if delta(got.Pos.Col(), want.Pos.Col()) > colDelta {
228 t.Errorf("%s: got col = %d; want %d", got.Pos, got.Pos.Col(), want.Pos.Col())
231 // eliminate from list
232 if n := len(list) - 1; n > 0 {
233 // not the last entry - slide entries down (don't reorder)
234 copy(list[index:], list[index+1:])
235 filemap[line] = list[:n]
237 // last entry - remove list from filemap
238 delete(filemap, line)
241 // if filemap is empty, eliminate from errmap
242 if len(filemap) == 0 {
243 delete(errmap, filename)
247 // there should be no expected errors left
249 t.Errorf("--- %s: unreported errors:", pkgName)
250 for filename, filemap := range errmap {
251 for line, list := range filemap {
252 for _, err := range list {
253 t.Errorf("%s:%d:%d: %s", filename, line, err.Pos.Col(), err.Msg)
260 // TestManual is for manual testing of a package - either provided
261 // as a list of filenames belonging to the package, or a directory
262 // name containing the package files - after the test arguments
263 // (and a separating "--"). For instance, to test the package made
264 // of the files foo.go and bar.go, use:
266 // go test -run Manual -- foo.go bar.go
268 // If no source arguments are provided, the file testdata/manual.go
270 // Provide the -verify flag to verify errors against ERROR comments
271 // in the input files rather than having a list of errors reported.
272 // The accepted Go language version can be controlled with the -lang
274 func TestManual(t *testing.T) {
275 testenv.MustHaveGoBuild(t)
277 filenames := flag.Args()
278 if len(filenames) == 0 {
279 filenames = []string{filepath.FromSlash("testdata/manual.go")}
282 info, err := os.Stat(filenames[0])
284 t.Fatalf("TestManual: %v", err)
287 DefPredeclaredTestFuncs()
289 if len(filenames) > 1 {
290 t.Fatal("TestManual: must have only one directory argument")
292 testDir(t, filenames[0], 0, true)
294 testFiles(t, filenames, 0, true)
298 // TODO(gri) go/types has extra TestLongConstants and TestIndexRepresentability tests
300 func TestCheck(t *testing.T) { testDirFiles(t, "testdata/check", 55, false) } // TODO(gri) narrow column tolerance
301 func TestSpec(t *testing.T) { testDirFiles(t, "testdata/spec", 0, false) }
302 func TestExamples(t *testing.T) { testDirFiles(t, "testdata/examples", 0, false) }
303 func TestFixedbugs(t *testing.T) { testDirFiles(t, "testdata/fixedbugs", 0, false) }
305 func testDirFiles(t *testing.T, dir string, colDelta uint, manual bool) {
306 testenv.MustHaveGoBuild(t)
307 dir = filepath.FromSlash(dir)
309 fis, err := os.ReadDir(dir)
315 for _, fi := range fis {
316 path := filepath.Join(dir, fi.Name())
318 // If fi is a directory, its files make up a single package.
320 testDir(t, path, colDelta, manual)
322 t.Run(filepath.Base(path), func(t *testing.T) {
323 testFiles(t, []string{path}, colDelta, manual)
329 func testDir(t *testing.T, dir string, colDelta uint, manual bool) {
330 fis, err := os.ReadDir(dir)
336 var filenames []string
337 for _, fi := range fis {
338 filenames = append(filenames, filepath.Join(dir, fi.Name()))
341 t.Run(filepath.Base(dir), func(t *testing.T) {
342 testFiles(t, filenames, colDelta, manual)