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 errlist = append(errlist, err)
151 conf.Check(pkgName, files, nil)
157 // collect expected errors
158 errmap := make(map[string]map[uint][]syntax.Error)
159 for _, filename := range sources {
160 f, err := os.Open(filename)
165 if m := syntax.ErrorMap(f); len(m) > 0 {
171 // match against found errors
172 for _, err := range errlist {
173 got := unpackError(err)
175 // find list of errors for the respective error line
176 filename := got.Pos.Base().Filename()
177 filemap := errmap[filename]
179 var list []syntax.Error
181 line = got.Pos.Line()
186 // one of errors in list should match the current error
187 index := -1 // list index of matching message, if any
188 for i, want := range list {
189 rx, err := regexp.Compile(want.Msg)
191 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
194 if rx.MatchString(got.Msg) {
200 t.Errorf("%s: no error expected: %q", got.Pos, got.Msg)
204 // column position must be within expected colDelta
206 if delta(got.Pos.Col(), want.Pos.Col()) > colDelta {
207 t.Errorf("%s: got col = %d; want %d", got.Pos, got.Pos.Col(), want.Pos.Col())
210 // eliminate from list
211 if n := len(list) - 1; n > 0 {
212 // not the last entry - swap in last element and shorten list by 1
213 list[index] = list[n]
214 filemap[line] = list[:n]
216 // last entry - remove list from filemap
217 delete(filemap, line)
220 // if filemap is empty, eliminate from errmap
221 if len(filemap) == 0 {
222 delete(errmap, filename)
226 // there should be no expected errors left
228 t.Errorf("--- %s: unreported errors:", pkgName)
229 for filename, filemap := range errmap {
230 for line, list := range filemap {
231 for _, err := range list {
232 t.Errorf("%s:%d:%d: %s", filename, line, err.Pos.Col(), err.Msg)
239 // TestCheck is for manual testing of selected input files, provided with -files.
240 // The accepted Go language version can be controlled with the -lang flag.
241 func TestCheck(t *testing.T) {
242 if *testFiles == "" {
245 testenv.MustHaveGoBuild(t)
246 DefPredeclaredTestFuncs()
247 checkFiles(t, strings.Split(*testFiles, ","), *goVersion, 0, testing.Verbose())
250 func TestTestdata(t *testing.T) { DefPredeclaredTestFuncs(); testDir(t, 75, "testdata") } // TODO(gri) narrow column tolerance
251 func TestExamples(t *testing.T) { testDir(t, 0, "examples") }
252 func TestFixedbugs(t *testing.T) { testDir(t, 0, "fixedbugs") }
254 func testDir(t *testing.T, colDelta uint, dir string) {
255 testenv.MustHaveGoBuild(t)
257 fis, err := ioutil.ReadDir(dir)
263 for count, fi := range fis {
264 path := filepath.Join(dir, fi.Name())
266 // if fi is a directory, its files make up a single package
268 if testing.Verbose() {
269 fmt.Printf("%3d %s\n", count, path)
271 fis, err := ioutil.ReadDir(path)
276 files := make([]string, len(fis))
277 for i, fi := range fis {
278 // if fi is a directory, checkFiles below will complain
279 files[i] = filepath.Join(path, fi.Name())
280 if testing.Verbose() {
281 fmt.Printf("\t%s\n", files[i])
284 checkFiles(t, files, "", colDelta, false)
288 // otherwise, fi is a stand-alone file
289 if testing.Verbose() {
290 fmt.Printf("%3d %s\n", count, path)
292 checkFiles(t, []string{path}, "", colDelta, false)