]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/check_test.go
[dev.typeparams] all: merge dev.regabi (7e0a81d) into dev.typeparams
[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", "", "space-separated list of test files")
48 )
49
50 func parseFiles(t *testing.T, filenames []string, mode syntax.Mode) ([]*syntax.File, []error) {
51         var files []*syntax.File
52         var errlist []error
53         errh := func(err error) { errlist = append(errlist, err) }
54         for _, filename := range filenames {
55                 file, err := syntax.ParseFile(filename, errh, nil, mode)
56                 if file == nil {
57                         t.Fatalf("%s: %s", filename, err)
58                 }
59                 files = append(files, file)
60         }
61         return files, errlist
62 }
63
64 func unpackError(err error) syntax.Error {
65         switch err := err.(type) {
66         case syntax.Error:
67                 return err
68         case Error:
69                 return syntax.Error{Pos: err.Pos, Msg: err.Msg}
70         default:
71                 return syntax.Error{Msg: err.Error()}
72         }
73 }
74
75 func delta(x, y uint) uint {
76         switch {
77         case x < y:
78                 return y - x
79         case x > y:
80                 return x - y
81         default:
82                 return 0
83         }
84 }
85
86 func checkFiles(t *testing.T, sources []string, colDelta uint, trace bool) {
87         if len(sources) == 0 {
88                 t.Fatal("no source files")
89         }
90
91         var mode syntax.Mode
92         if strings.HasSuffix(sources[0], ".go2") {
93                 mode |= syntax.AllowGenerics
94         }
95         // parse files and collect parser errors
96         files, errlist := parseFiles(t, sources, mode)
97
98         pkgName := "<no package>"
99         if len(files) > 0 {
100                 pkgName = files[0].PkgName.Value
101         }
102
103         if *listErrors && len(errlist) > 0 {
104                 t.Errorf("--- %s:", pkgName)
105                 for _, err := range errlist {
106                         t.Error(err)
107                 }
108         }
109
110         // typecheck and collect typechecker errors
111         var conf Config
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
117         }
118         conf.Trace = trace
119         conf.Importer = defaultImporter()
120         conf.Error = func(err error) {
121                 if *haltOnError {
122                         defer panic(err)
123                 }
124                 if *listErrors {
125                         t.Error(err)
126                         return
127                 }
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)
132                 }
133         }
134         conf.Check(pkgName, files, nil)
135
136         if *listErrors {
137                 return
138         }
139
140         // collect expected errors
141         errmap := make(map[string]map[uint][]syntax.Error)
142         for _, filename := range sources {
143                 f, err := os.Open(filename)
144                 if err != nil {
145                         t.Error(err)
146                         continue
147                 }
148                 if m := syntax.ErrorMap(f); len(m) > 0 {
149                         errmap[filename] = m
150                 }
151                 f.Close()
152         }
153
154         // match against found errors
155         for _, err := range errlist {
156                 got := unpackError(err)
157
158                 // find list of errors for the respective error line
159                 filename := got.Pos.Base().Filename()
160                 filemap := errmap[filename]
161                 var line uint
162                 var list []syntax.Error
163                 if filemap != nil {
164                         line = got.Pos.Line()
165                         list = filemap[line]
166                 }
167                 // list may be nil
168
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)
173                         if err != nil {
174                                 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
175                                 continue
176                         }
177                         if rx.MatchString(got.Msg) {
178                                 index = i
179                                 break
180                         }
181                 }
182                 if index < 0 {
183                         t.Errorf("%s: no error expected: %q", got.Pos, got.Msg)
184                         continue
185                 }
186
187                 // column position must be within expected colDelta
188                 want := list[index]
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())
191                 }
192
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]
198                 } else {
199                         // last entry - remove list from filemap
200                         delete(filemap, line)
201                 }
202
203                 // if filemap is empty, eliminate from errmap
204                 if len(filemap) == 0 {
205                         delete(errmap, filename)
206                 }
207         }
208
209         // there should be no expected errors left
210         if len(errmap) > 0 {
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)
216                                 }
217                         }
218                 }
219         }
220 }
221
222 // TestCheck is for manual testing of selected input files, provided with -files.
223 func TestCheck(t *testing.T) {
224         if *testFiles == "" {
225                 return
226         }
227         testenv.MustHaveGoBuild(t)
228         DefPredeclaredTestFuncs()
229         checkFiles(t, strings.Split(*testFiles, " "), 0, testing.Verbose())
230 }
231
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") }
235
236 func testDir(t *testing.T, colDelta uint, dir string) {
237         testenv.MustHaveGoBuild(t)
238
239         fis, err := ioutil.ReadDir(dir)
240         if err != nil {
241                 t.Error(err)
242                 return
243         }
244
245         for count, fi := range fis {
246                 path := filepath.Join(dir, fi.Name())
247
248                 // if fi is a directory, its files make up a single package
249                 if fi.IsDir() {
250                         if testing.Verbose() {
251                                 fmt.Printf("%3d %s\n", count, path)
252                         }
253                         fis, err := ioutil.ReadDir(path)
254                         if err != nil {
255                                 t.Error(err)
256                                 continue
257                         }
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])
264                                 }
265                         }
266                         checkFiles(t, files, colDelta, false)
267                         continue
268                 }
269
270                 // otherwise, fi is a stand-alone file
271                 if testing.Verbose() {
272                         fmt.Printf("%3d %s\n", count, path)
273                 }
274                 checkFiles(t, []string{path}, colDelta, false)
275         }
276 }