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", "", "space-separated list of test files")
50 func parseFiles(t *testing.T, filenames []string, mode syntax.Mode) ([]*syntax.File, []error) {
51 var files []*syntax.File
53 errh := func(err error) { errlist = append(errlist, err) }
54 for _, filename := range filenames {
55 file, err := syntax.ParseFile(filename, errh, nil, mode)
57 t.Fatalf("%s: %s", filename, err)
59 files = append(files, file)
64 func unpackError(err error) syntax.Error {
65 switch err := err.(type) {
69 return syntax.Error{Pos: err.Pos, Msg: err.Msg}
71 return syntax.Error{Msg: err.Error()}
75 func delta(x, y uint) uint {
86 func checkFiles(t *testing.T, sources []string, colDelta uint, trace bool) {
87 if len(sources) == 0 {
88 t.Fatal("no source files")
92 if strings.HasSuffix(sources[0], ".go2") {
93 mode |= syntax.AllowGenerics
95 // parse files and collect parser errors
96 files, errlist := parseFiles(t, sources, mode)
98 pkgName := "<no package>"
100 pkgName = files[0].PkgName.Value
103 if *listErrors && len(errlist) > 0 {
104 t.Errorf("--- %s:", pkgName)
105 for _, err := range errlist {
110 // typecheck and collect typechecker errors
112 conf.AcceptMethodTypeParams = true
113 conf.InferFromConstraints = true
114 // special case for importC.src
115 if len(sources) == 1 && strings.HasSuffix(sources[0], "importC.src") {
116 conf.FakeImportC = true
119 conf.Importer = defaultImporter()
120 conf.Error = func(err error) {
128 // Ignore secondary error messages starting with "\t";
129 // they are clarifying messages for a primary error.
130 if !strings.Contains(err.Error(), ": \t") {
131 errlist = append(errlist, err)
134 conf.Check(pkgName, files, nil)
140 // collect expected errors
141 errmap := make(map[string]map[uint][]syntax.Error)
142 for _, filename := range sources {
143 f, err := os.Open(filename)
148 if m := syntax.ErrorMap(f); len(m) > 0 {
154 // match against found errors
155 for _, err := range errlist {
156 got := unpackError(err)
158 // find list of errors for the respective error line
159 filename := got.Pos.Base().Filename()
160 filemap := errmap[filename]
162 var list []syntax.Error
164 line = got.Pos.Line()
169 // one of errors in list should match the current error
170 index := -1 // list index of matching message, if any
171 for i, want := range list {
172 rx, err := regexp.Compile(want.Msg)
174 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
177 if rx.MatchString(got.Msg) {
183 t.Errorf("%s: no error expected: %q", got.Pos, got.Msg)
187 // column position must be within expected colDelta
189 if delta(got.Pos.Col(), want.Pos.Col()) > colDelta {
190 t.Errorf("%s: got col = %d; want %d", got.Pos, got.Pos.Col(), want.Pos.Col())
193 // eliminate from list
194 if n := len(list) - 1; n > 0 {
195 // not the last entry - swap in last element and shorten list by 1
196 list[index] = list[n]
197 filemap[line] = list[:n]
199 // last entry - remove list from filemap
200 delete(filemap, line)
203 // if filemap is empty, eliminate from errmap
204 if len(filemap) == 0 {
205 delete(errmap, filename)
209 // there should be no expected errors left
211 t.Errorf("--- %s: unreported errors:", pkgName)
212 for filename, filemap := range errmap {
213 for line, list := range filemap {
214 for _, err := range list {
215 t.Errorf("%s:%d:%d: %s", filename, line, err.Pos.Col(), err.Msg)
222 // TestCheck is for manual testing of selected input files, provided with -files.
223 func TestCheck(t *testing.T) {
224 if *testFiles == "" {
227 testenv.MustHaveGoBuild(t)
228 DefPredeclaredTestFuncs()
229 checkFiles(t, strings.Split(*testFiles, " "), 0, testing.Verbose())
232 func TestTestdata(t *testing.T) { DefPredeclaredTestFuncs(); testDir(t, 75, "testdata") } // TODO(gri) narrow column tolerance
233 func TestExamples(t *testing.T) { testDir(t, 0, "examples") }
234 func TestFixedbugs(t *testing.T) { testDir(t, 0, "fixedbugs") }
236 func testDir(t *testing.T, colDelta uint, dir string) {
237 testenv.MustHaveGoBuild(t)
239 fis, err := ioutil.ReadDir(dir)
245 for count, fi := range fis {
246 path := filepath.Join(dir, fi.Name())
248 // if fi is a directory, its files make up a single package
250 if testing.Verbose() {
251 fmt.Printf("%3d %s\n", count, path)
253 fis, err := ioutil.ReadDir(path)
258 files := make([]string, len(fis))
259 for i, fi := range fis {
260 // if fi is a directory, checkFiles below will complain
261 files[i] = filepath.Join(path, fi.Name())
262 if testing.Verbose() {
263 fmt.Printf("\t%s\n", files[i])
266 checkFiles(t, files, colDelta, false)
270 // otherwise, fi is a stand-alone file
271 if testing.Verbose() {
272 fmt.Printf("%3d %s\n", count, path)
274 checkFiles(t, []string{path}, colDelta, false)