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
37 // The test filenames do not end in .go so that they are invisible
38 // to gofmt since they contain comments that must not change their
39 // positions relative to surrounding tokens.
41 var tests = []struct {
45 {"test0", []string{"testdata/test0.src"}},
48 var fset = token.NewFileSet()
50 // TODO(gri) This functionality should be in token.Fileset.
51 func getFile(filename string) *token.File {
52 for f := range fset.Files() {
53 if f.Name() == filename {
60 // TODO(gri) This functionality should be in token.Fileset.
61 func getPos(filename string, offset int) token.Pos {
62 if f := getFile(filename); f != nil {
68 // TODO(gri) Need to revisit parser interface. We should be able to use parser.ParseFiles
69 // or a similar function instead.
70 func parseFiles(t *testing.T, testname string, filenames []string) (map[string]*ast.File, error) {
71 files := make(map[string]*ast.File)
72 var errors scanner.ErrorList
73 for _, filename := range filenames {
74 if _, exists := files[filename]; exists {
75 t.Fatalf("%s: duplicate file %s", testname, filename)
77 file, err := parser.ParseFile(fset, filename, nil, parser.DeclarationErrors)
79 t.Fatalf("%s: could not parse file %s", testname, filename)
81 files[filename] = file
83 // if the parser returns a non-scanner.ErrorList error
84 // the file couldn't be read in the first place and
85 // file == nil; in that case we shouldn't reach here
86 errors = append(errors, err.(scanner.ErrorList)...)
93 // ERROR comments must be of the form /* ERROR "rx" */ and rx is
94 // a regular expression that matches the expected error message.
96 var errRx = regexp.MustCompile(`^/\* *ERROR *"([^"]*)" *\*/$`)
98 // expectedErrors collects the regular expressions of ERROR comments found
99 // in files and returns them as a map of error positions to error messages.
101 func expectedErrors(t *testing.T, testname string, files map[string]*ast.File) map[token.Pos]string {
102 errors := make(map[token.Pos]string)
103 for filename := range files {
104 src, err := ioutil.ReadFile(filename)
106 t.Fatalf("%s: could not read %s", testname, filename)
109 var s scanner.Scanner
110 // file was parsed already - do not add it again to the file
111 // set otherwise the position information returned here will
112 // not match the position information collected by the parser
113 s.Init(getFile(filename), src, nil, scanner.ScanComments)
114 var prev token.Pos // position of last non-comment, non-semicolon token
118 pos, tok, lit := s.Scan()
123 s := errRx.FindStringSubmatch(lit)
125 errors[prev] = string(s[1])
127 case token.SEMICOLON:
128 // ignore automatically inserted semicolon
141 func eliminate(t *testing.T, expected map[token.Pos]string, errors error) {
145 for _, error := range errors.(scanner.ErrorList) {
146 // error.Pos is a token.Position, but we want
147 // a token.Pos so we can do a map lookup
148 // TODO(gri) Need to move scanner.Errors over
149 // to use token.Pos and file set info.
150 pos := getPos(error.Pos.Filename, error.Pos.Offset)
151 if msg, found := expected[pos]; found {
152 // we expect a message at pos; check if it matches
153 rx, err := regexp.Compile(msg)
155 t.Errorf("%s: %v", error.Pos, err)
158 if match := rx.MatchString(error.Msg); !match {
159 t.Errorf("%s: %q does not match %q", error.Pos, error.Msg, msg)
162 // we have a match - eliminate this error
163 delete(expected, pos)
165 // To keep in mind when analyzing failed test output:
166 // If the same error position occurs multiple times in errors,
167 // this message will be triggered (because the first error at
168 // the position removes this position from the expected errors).
169 t.Errorf("%s: no (multiple?) error expected, but found: %s", error.Pos, error.Msg)
174 func check(t *testing.T, testname string, testfiles []string) {
175 // TODO(gri) Eventually all these different phases should be
176 // subsumed into a single function call that takes
177 // a set of files and creates a fully resolved and
180 files, err := parseFiles(t, testname, testfiles)
182 // we are expecting the following errors
183 // (collect these after parsing the files so that
184 // they are found in the file set)
185 errors := expectedErrors(t, testname, files)
187 // verify errors returned by the parser
188 eliminate(t, errors, err)
190 // verify errors returned after resolving identifiers
191 pkg, err := ast.NewPackage(fset, files, GcImporter, Universe)
192 eliminate(t, errors, err)
194 // verify errors returned by the typechecker
195 _, err = Check(fset, pkg)
196 eliminate(t, errors, err)
198 // there should be no expected errors left
200 t.Errorf("%s: %d errors not reported:", testname, len(errors))
201 for pos, msg := range errors {
202 t.Errorf("%s: %s\n", fset.Position(pos), msg)
207 func TestCheck(t *testing.T) {
208 // For easy debugging w/o changing the testing code,
209 // if there is a local test file, only test that file.
210 const testfile = "test.go"
211 if fi, err := os.Stat(testfile); err == nil && !fi.IsDir() {
212 fmt.Printf("WARNING: Testing only %s (remove it to run all tests)\n", testfile)
213 check(t, testfile, []string{testfile})
217 // Otherwise, run all the tests.
218 for _, test := range tests {
219 check(t, test.name, test.files)