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
26 "cmd/compile/internal/syntax"
36 . "cmd/compile/internal/types2"
40 haltOnError = flag.Bool("halt", false, "halt on error")
41 verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
42 goVersion = flag.String("lang", "", "Go language version (e.g. \"go1.12\")")
45 func parseFiles(t *testing.T, filenames []string, mode syntax.Mode) ([]*syntax.File, []error) {
46 var files []*syntax.File
48 errh := func(err error) { errlist = append(errlist, err) }
49 for _, filename := range filenames {
50 file, err := syntax.ParseFile(filename, errh, nil, mode)
52 t.Fatalf("%s: %s", filename, err)
54 files = append(files, file)
59 func unpackError(err error) syntax.Error {
60 switch err := err.(type) {
64 return syntax.Error{Pos: err.Pos, Msg: err.Msg}
66 return syntax.Error{Msg: err.Error()}
70 // delta returns the absolute difference between x and y.
71 func delta(x, y uint) uint {
82 // goVersionRx matches a Go version string using '_', e.g. "go1_12".
83 var goVersionRx = regexp.MustCompile(`^go[1-9][0-9]*_(0|[1-9][0-9]*)$`)
85 // asGoVersion returns a regular Go language version string
86 // if s is a Go version string using '_' rather than '.' to
87 // separate the major and minor version numbers (e.g. "go1_12").
88 // Otherwise it returns the empty string.
89 func asGoVersion(s string) string {
90 if goVersionRx.MatchString(s) {
91 return strings.Replace(s, "_", ".", 1)
96 func testFiles(t *testing.T, filenames []string, colDelta uint, manual bool) {
97 if len(filenames) == 0 {
98 t.Fatal("no source files")
102 if strings.HasSuffix(filenames[0], ".go2") {
103 mode |= syntax.AllowGenerics | syntax.AllowTypeSets | syntax.AllowTypeLists
105 // parse files and collect parser errors
106 files, errlist := parseFiles(t, filenames, mode)
108 pkgName := "<no package>"
110 pkgName = files[0].PkgName.Value
113 // if no Go version is given, consider the package name
114 goVersion := *goVersion
116 goVersion = asGoVersion(pkgName)
119 listErrors := manual && !*verifyErrors
120 if listErrors && len(errlist) > 0 {
121 t.Errorf("--- %s:", pkgName)
122 for _, err := range errlist {
127 // typecheck and collect typechecker errors
129 conf.GoVersion = goVersion
130 // special case for importC.src
131 if len(filenames) == 1 && strings.HasSuffix(filenames[0], "importC.src") {
132 conf.FakeImportC = true
134 conf.Trace = manual && testing.Verbose()
135 conf.Importer = defaultImporter()
136 conf.Error = func(err error) {
144 errlist = append(errlist, err)
146 conf.Check(pkgName, files, nil)
152 // sort errlist in source order
153 sort.Slice(errlist, func(i, j int) bool {
154 pi := unpackError(errlist[i]).Pos
155 pj := unpackError(errlist[j]).Pos
156 return pi.Cmp(pj) < 0
159 // collect expected errors
160 errmap := make(map[string]map[uint][]syntax.Error)
161 for _, filename := range filenames {
162 f, err := os.Open(filename)
167 if m := syntax.ErrorMap(f); len(m) > 0 {
173 // match against found errors
174 for _, err := range errlist {
175 got := unpackError(err)
177 // find list of errors for the respective error line
178 filename := got.Pos.Base().Filename()
179 filemap := errmap[filename]
180 line := got.Pos.Line()
181 var list []syntax.Error
187 // one of errors in list should match the current error
188 index := -1 // list index of matching message, if any
189 for i, want := range list {
190 rx, err := regexp.Compile(want.Msg)
192 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
195 if rx.MatchString(got.Msg) {
201 t.Errorf("%s: no error expected: %q", got.Pos, got.Msg)
205 // column position must be within expected colDelta
207 if delta(got.Pos.Col(), want.Pos.Col()) > colDelta {
208 t.Errorf("%s: got col = %d; want %d", got.Pos, got.Pos.Col(), want.Pos.Col())
211 // eliminate from list
212 if n := len(list) - 1; n > 0 {
213 // not the last entry - slide entries down (don't reorder)
214 copy(list[index:], list[index+1:])
215 filemap[line] = list[:n]
217 // last entry - remove list from filemap
218 delete(filemap, line)
221 // if filemap is empty, eliminate from errmap
222 if len(filemap) == 0 {
223 delete(errmap, filename)
227 // there should be no expected errors left
229 t.Errorf("--- %s: unreported errors:", pkgName)
230 for filename, filemap := range errmap {
231 for line, list := range filemap {
232 for _, err := range list {
233 t.Errorf("%s:%d:%d: %s", filename, line, err.Pos.Col(), err.Msg)
240 // TestManual is for manual testing of a package - either provided
241 // as a list of filenames belonging to the package, or a directory
242 // name containing the package files - after the test arguments
243 // (and a separating "--"). For instance, to test the package made
244 // of the files foo.go and bar.go, use:
246 // go test -run Manual -- foo.go bar.go
248 // If no source arguments are provided, the file testdata/manual.go2
250 // Provide the -verify flag to verify errors against ERROR comments
251 // in the input files rather than having a list of errors reported.
252 // The accepted Go language version can be controlled with the -lang
254 func TestManual(t *testing.T) {
255 testenv.MustHaveGoBuild(t)
257 filenames := flag.Args()
258 if len(filenames) == 0 {
259 filenames = []string{filepath.FromSlash("testdata/manual.go2")}
262 info, err := os.Stat(filenames[0])
264 t.Fatalf("TestManual: %v", err)
267 DefPredeclaredTestFuncs()
269 if len(filenames) > 1 {
270 t.Fatal("TestManual: must have only one directory argument")
272 testDir(t, filenames[0], 0, true)
274 testFiles(t, filenames, 0, true)
278 // TODO(gri) go/types has extra TestLongConstants and TestIndexRepresentability tests
280 func TestCheck(t *testing.T) { DefPredeclaredTestFuncs(); testDirFiles(t, "testdata/check", 75, false) } // TODO(gri) narrow column tolerance
281 func TestExamples(t *testing.T) { testDirFiles(t, "testdata/examples", 0, false) }
282 func TestFixedbugs(t *testing.T) { testDirFiles(t, "testdata/fixedbugs", 0, false) }
284 func testDirFiles(t *testing.T, dir string, colDelta uint, manual bool) {
285 testenv.MustHaveGoBuild(t)
286 dir = filepath.FromSlash(dir)
288 fis, err := os.ReadDir(dir)
294 for _, fi := range fis {
295 path := filepath.Join(dir, fi.Name())
297 // If fi is a directory, its files make up a single package.
299 testDir(t, path, colDelta, manual)
301 t.Run(filepath.Base(path), func(t *testing.T) {
302 testFiles(t, []string{path}, colDelta, manual)
308 func testDir(t *testing.T, dir string, colDelta uint, manual bool) {
309 fis, err := os.ReadDir(dir)
315 var filenames []string
316 for _, fi := range fis {
317 filenames = append(filenames, filepath.Join(dir, fi.Name()))
320 t.Run(filepath.Base(dir), func(t *testing.T) {
321 testFiles(t, filenames, colDelta, manual)