2 // Copyright 2011 The Go Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
6 // This file implements a typechecker test harness. The packages specified
7 // in tests are typechecked. Error messages reported by the typechecker are
8 // compared against the error messages expected in the test files.
10 // Expected errors are indicated in the test files by putting a comment
11 // of the form /* ERROR "rx" */ immediately following an offending token.
12 // The harness will verify that an error matching the regular expression
13 // rx is reported at that source position. Consecutive comments may be
14 // used to indicate multiple errors for the same token position.
16 // For instance, the following test file indicates that a "not declared"
17 // error should be reported for the undeclared variable x:
21 // _ = x /* ERROR "not declared" */ + 1
24 // TODO(gri) Also collect strict mode errors of the form /* STRICT ... */
25 // and test against strict mode.
30 "cmd/compile/internal/syntax"
41 . "cmd/compile/internal/types2"
45 haltOnError = flag.Bool("halt", false, "halt on error")
46 listErrors = flag.Bool("errlist", false, "list errors")
47 testFiles = flag.String("files", "", "comma-separated list of test files")
48 goVersion = flag.String("lang", "", "Go language version (e.g. \"go1.12\"")
51 func parseFiles(t *testing.T, filenames []string, mode syntax.Mode) ([]*syntax.File, []error) {
52 var files []*syntax.File
54 errh := func(err error) { errlist = append(errlist, err) }
55 for _, filename := range filenames {
56 file, err := syntax.ParseFile(filename, errh, nil, mode)
58 t.Fatalf("%s: %s", filename, err)
60 files = append(files, file)
65 func unpackError(err error) syntax.Error {
66 switch err := err.(type) {
70 return syntax.Error{Pos: err.Pos, Msg: err.Msg}
72 return syntax.Error{Msg: err.Error()}
76 func delta(x, y uint) uint {
87 // goVersionRx matches a Go version string using '_', e.g. "go1_12".
88 var goVersionRx = regexp.MustCompile(`^go[1-9][0-9]*_(0|[1-9][0-9]*)$`)
90 // asGoVersion returns a regular Go language version string
91 // if s is a Go version string using '_' rather than '.' to
92 // separate the major and minor version numbers (e.g. "go1_12").
93 // Otherwise it returns the empty string.
94 func asGoVersion(s string) string {
95 if goVersionRx.MatchString(s) {
96 return strings.Replace(s, "_", ".", 1)
101 func checkFiles(t *testing.T, sources []string, goVersion string, colDelta uint, trace bool) {
102 if len(sources) == 0 {
103 t.Fatal("no source files")
107 if strings.HasSuffix(sources[0], ".go2") {
108 mode |= syntax.AllowGenerics
110 // parse files and collect parser errors
111 files, errlist := parseFiles(t, sources, mode)
113 pkgName := "<no package>"
115 pkgName = files[0].PkgName.Value
118 // if no Go version is given, consider the package name
120 goVersion = asGoVersion(pkgName)
123 if *listErrors && len(errlist) > 0 {
124 t.Errorf("--- %s:", pkgName)
125 for _, err := range errlist {
130 // typecheck and collect typechecker errors
132 conf.GoVersion = goVersion
133 conf.AcceptMethodTypeParams = true
134 conf.InferFromConstraints = true
135 // special case for importC.src
136 if len(sources) == 1 && strings.HasSuffix(sources[0], "importC.src") {
137 conf.FakeImportC = true
140 conf.Importer = defaultImporter()
141 conf.Error = func(err error) {
149 // Ignore secondary error messages starting with "\t";
150 // they are clarifying messages for a primary error.
151 if !strings.Contains(err.Error(), ": \t") {
152 errlist = append(errlist, err)
155 conf.Check(pkgName, files, nil)
161 // collect expected errors
162 errmap := make(map[string]map[uint][]syntax.Error)
163 for _, filename := range sources {
164 f, err := os.Open(filename)
169 if m := syntax.ErrorMap(f); len(m) > 0 {
175 // match against found errors
176 for _, err := range errlist {
177 got := unpackError(err)
179 // find list of errors for the respective error line
180 filename := got.Pos.Base().Filename()
181 filemap := errmap[filename]
183 var list []syntax.Error
185 line = got.Pos.Line()
190 // one of errors in list should match the current error
191 index := -1 // list index of matching message, if any
192 for i, want := range list {
193 rx, err := regexp.Compile(want.Msg)
195 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
198 if rx.MatchString(got.Msg) {
204 t.Errorf("%s: no error expected: %q", got.Pos, got.Msg)
208 // column position must be within expected colDelta
210 if delta(got.Pos.Col(), want.Pos.Col()) > colDelta {
211 t.Errorf("%s: got col = %d; want %d", got.Pos, got.Pos.Col(), want.Pos.Col())
214 // eliminate from list
215 if n := len(list) - 1; n > 0 {
216 // not the last entry - swap in last element and shorten list by 1
217 list[index] = list[n]
218 filemap[line] = list[:n]
220 // last entry - remove list from filemap
221 delete(filemap, line)
224 // if filemap is empty, eliminate from errmap
225 if len(filemap) == 0 {
226 delete(errmap, filename)
230 // there should be no expected errors left
232 t.Errorf("--- %s: unreported errors:", pkgName)
233 for filename, filemap := range errmap {
234 for line, list := range filemap {
235 for _, err := range list {
236 t.Errorf("%s:%d:%d: %s", filename, line, err.Pos.Col(), err.Msg)
243 // TestCheck is for manual testing of selected input files, provided with -files.
244 // The accepted Go language version can be controlled with the -lang flag.
245 func TestCheck(t *testing.T) {
246 if *testFiles == "" {
249 testenv.MustHaveGoBuild(t)
250 DefPredeclaredTestFuncs()
251 checkFiles(t, strings.Split(*testFiles, ","), *goVersion, 0, testing.Verbose())
254 func TestTestdata(t *testing.T) { DefPredeclaredTestFuncs(); testDir(t, 75, "testdata") } // TODO(gri) narrow column tolerance
255 func TestExamples(t *testing.T) { testDir(t, 0, "examples") }
256 func TestFixedbugs(t *testing.T) { testDir(t, 0, "fixedbugs") }
258 func testDir(t *testing.T, colDelta uint, dir string) {
259 testenv.MustHaveGoBuild(t)
261 fis, err := ioutil.ReadDir(dir)
267 for count, fi := range fis {
268 path := filepath.Join(dir, fi.Name())
270 // if fi is a directory, its files make up a single package
272 if testing.Verbose() {
273 fmt.Printf("%3d %s\n", count, path)
275 fis, err := ioutil.ReadDir(path)
280 files := make([]string, len(fis))
281 for i, fi := range fis {
282 // if fi is a directory, checkFiles below will complain
283 files[i] = filepath.Join(path, fi.Name())
284 if testing.Verbose() {
285 fmt.Printf("\t%s\n", files[i])
288 checkFiles(t, files, "", colDelta, false)
292 // otherwise, fi is a stand-alone file
293 if testing.Verbose() {
294 fmt.Printf("%3d %s\n", count, path)
296 checkFiles(t, []string{path}, "", colDelta, false)