]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/check_test.go
cmd/compile/internal/types2: better error reporting framework (starting point)
[gostls13.git] / src / cmd / compile / internal / types2 / check_test.go
1 // UNREVIEWED
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.
5
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.
9 //
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.
15 //
16 // For instance, the following test file indicates that a "not declared"
17 // error should be reported for the undeclared variable x:
18 //
19 //      package p
20 //      func f() {
21 //              _ = x /* ERROR "not declared" */ + 1
22 //      }
23
24 // TODO(gri) Also collect strict mode errors of the form /* STRICT ... */
25 //           and test against strict mode.
26
27 package types2_test
28
29 import (
30         "cmd/compile/internal/syntax"
31         "flag"
32         "fmt"
33         "internal/testenv"
34         "io/ioutil"
35         "os"
36         "path/filepath"
37         "regexp"
38         "strings"
39         "testing"
40
41         . "cmd/compile/internal/types2"
42 )
43
44 var (
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\"")
49 )
50
51 func parseFiles(t *testing.T, filenames []string, mode syntax.Mode) ([]*syntax.File, []error) {
52         var files []*syntax.File
53         var errlist []error
54         errh := func(err error) { errlist = append(errlist, err) }
55         for _, filename := range filenames {
56                 file, err := syntax.ParseFile(filename, errh, nil, mode)
57                 if file == nil {
58                         t.Fatalf("%s: %s", filename, err)
59                 }
60                 files = append(files, file)
61         }
62         return files, errlist
63 }
64
65 func unpackError(err error) syntax.Error {
66         switch err := err.(type) {
67         case syntax.Error:
68                 return err
69         case Error:
70                 return syntax.Error{Pos: err.Pos, Msg: err.Msg}
71         default:
72                 return syntax.Error{Msg: err.Error()}
73         }
74 }
75
76 func delta(x, y uint) uint {
77         switch {
78         case x < y:
79                 return y - x
80         case x > y:
81                 return x - y
82         default:
83                 return 0
84         }
85 }
86
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]*)$`)
89
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)
97         }
98         return ""
99 }
100
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")
104         }
105
106         var mode syntax.Mode
107         if strings.HasSuffix(sources[0], ".go2") {
108                 mode |= syntax.AllowGenerics
109         }
110         // parse files and collect parser errors
111         files, errlist := parseFiles(t, sources, mode)
112
113         pkgName := "<no package>"
114         if len(files) > 0 {
115                 pkgName = files[0].PkgName.Value
116         }
117
118         // if no Go version is given, consider the package name
119         if goVersion == "" {
120                 goVersion = asGoVersion(pkgName)
121         }
122
123         if *listErrors && len(errlist) > 0 {
124                 t.Errorf("--- %s:", pkgName)
125                 for _, err := range errlist {
126                         t.Error(err)
127                 }
128         }
129
130         // typecheck and collect typechecker errors
131         var conf Config
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
138         }
139         conf.Trace = trace
140         conf.Importer = defaultImporter()
141         conf.Error = func(err error) {
142                 if *haltOnError {
143                         defer panic(err)
144                 }
145                 if *listErrors {
146                         t.Error(err)
147                         return
148                 }
149                 errlist = append(errlist, err)
150         }
151         conf.Check(pkgName, files, nil)
152
153         if *listErrors {
154                 return
155         }
156
157         // collect expected errors
158         errmap := make(map[string]map[uint][]syntax.Error)
159         for _, filename := range sources {
160                 f, err := os.Open(filename)
161                 if err != nil {
162                         t.Error(err)
163                         continue
164                 }
165                 if m := syntax.ErrorMap(f); len(m) > 0 {
166                         errmap[filename] = m
167                 }
168                 f.Close()
169         }
170
171         // match against found errors
172         for _, err := range errlist {
173                 got := unpackError(err)
174
175                 // find list of errors for the respective error line
176                 filename := got.Pos.Base().Filename()
177                 filemap := errmap[filename]
178                 var line uint
179                 var list []syntax.Error
180                 if filemap != nil {
181                         line = got.Pos.Line()
182                         list = filemap[line]
183                 }
184                 // list may be nil
185
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)
190                         if err != nil {
191                                 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
192                                 continue
193                         }
194                         if rx.MatchString(got.Msg) {
195                                 index = i
196                                 break
197                         }
198                 }
199                 if index < 0 {
200                         t.Errorf("%s: no error expected: %q", got.Pos, got.Msg)
201                         continue
202                 }
203
204                 // column position must be within expected colDelta
205                 want := list[index]
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())
208                 }
209
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]
215                 } else {
216                         // last entry - remove list from filemap
217                         delete(filemap, line)
218                 }
219
220                 // if filemap is empty, eliminate from errmap
221                 if len(filemap) == 0 {
222                         delete(errmap, filename)
223                 }
224         }
225
226         // there should be no expected errors left
227         if len(errmap) > 0 {
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)
233                                 }
234                         }
235                 }
236         }
237 }
238
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 == "" {
243                 return
244         }
245         testenv.MustHaveGoBuild(t)
246         DefPredeclaredTestFuncs()
247         checkFiles(t, strings.Split(*testFiles, ","), *goVersion, 0, testing.Verbose())
248 }
249
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") }
253
254 func testDir(t *testing.T, colDelta uint, dir string) {
255         testenv.MustHaveGoBuild(t)
256
257         fis, err := ioutil.ReadDir(dir)
258         if err != nil {
259                 t.Error(err)
260                 return
261         }
262
263         for count, fi := range fis {
264                 path := filepath.Join(dir, fi.Name())
265
266                 // if fi is a directory, its files make up a single package
267                 if fi.IsDir() {
268                         if testing.Verbose() {
269                                 fmt.Printf("%3d %s\n", count, path)
270                         }
271                         fis, err := ioutil.ReadDir(path)
272                         if err != nil {
273                                 t.Error(err)
274                                 continue
275                         }
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])
282                                 }
283                         }
284                         checkFiles(t, files, "", colDelta, false)
285                         continue
286                 }
287
288                 // otherwise, fi is a stand-alone file
289                 if testing.Verbose() {
290                         fmt.Printf("%3d %s\n", count, path)
291                 }
292                 checkFiles(t, []string{path}, "", colDelta, false)
293         }
294 }