]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/check_test.go
[dev.typeparams] merge master (2f0da6d) 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", "", "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                 // Ignore secondary error messages starting with "\t";
150                 // they are clarifying messages for a primary error.
151                 if !strings.Contains(err.Error(), ": \t") {
152                         errlist = append(errlist, err)
153                 }
154         }
155         conf.Check(pkgName, files, nil)
156
157         if *listErrors {
158                 return
159         }
160
161         // collect expected errors
162         errmap := make(map[string]map[uint][]syntax.Error)
163         for _, filename := range sources {
164                 f, err := os.Open(filename)
165                 if err != nil {
166                         t.Error(err)
167                         continue
168                 }
169                 if m := syntax.ErrorMap(f); len(m) > 0 {
170                         errmap[filename] = m
171                 }
172                 f.Close()
173         }
174
175         // match against found errors
176         for _, err := range errlist {
177                 got := unpackError(err)
178
179                 // find list of errors for the respective error line
180                 filename := got.Pos.Base().Filename()
181                 filemap := errmap[filename]
182                 var line uint
183                 var list []syntax.Error
184                 if filemap != nil {
185                         line = got.Pos.Line()
186                         list = filemap[line]
187                 }
188                 // list may be nil
189
190                 // one of errors in list should match the current error
191                 index := -1 // list index of matching message, if any
192                 for i, want := range list {
193                         rx, err := regexp.Compile(want.Msg)
194                         if err != nil {
195                                 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
196                                 continue
197                         }
198                         if rx.MatchString(got.Msg) {
199                                 index = i
200                                 break
201                         }
202                 }
203                 if index < 0 {
204                         t.Errorf("%s: no error expected: %q", got.Pos, got.Msg)
205                         continue
206                 }
207
208                 // column position must be within expected colDelta
209                 want := list[index]
210                 if delta(got.Pos.Col(), want.Pos.Col()) > colDelta {
211                         t.Errorf("%s: got col = %d; want %d", got.Pos, got.Pos.Col(), want.Pos.Col())
212                 }
213
214                 // eliminate from list
215                 if n := len(list) - 1; n > 0 {
216                         // not the last entry - swap in last element and shorten list by 1
217                         list[index] = list[n]
218                         filemap[line] = list[:n]
219                 } else {
220                         // last entry - remove list from filemap
221                         delete(filemap, line)
222                 }
223
224                 // if filemap is empty, eliminate from errmap
225                 if len(filemap) == 0 {
226                         delete(errmap, filename)
227                 }
228         }
229
230         // there should be no expected errors left
231         if len(errmap) > 0 {
232                 t.Errorf("--- %s: unreported errors:", pkgName)
233                 for filename, filemap := range errmap {
234                         for line, list := range filemap {
235                                 for _, err := range list {
236                                         t.Errorf("%s:%d:%d: %s", filename, line, err.Pos.Col(), err.Msg)
237                                 }
238                         }
239                 }
240         }
241 }
242
243 // TestCheck is for manual testing of selected input files, provided with -files.
244 // The accepted Go language version can be controlled with the -lang flag.
245 func TestCheck(t *testing.T) {
246         if *testFiles == "" {
247                 return
248         }
249         testenv.MustHaveGoBuild(t)
250         DefPredeclaredTestFuncs()
251         checkFiles(t, strings.Split(*testFiles, ","), *goVersion, 0, testing.Verbose())
252 }
253
254 func TestTestdata(t *testing.T)  { DefPredeclaredTestFuncs(); testDir(t, 75, "testdata") } // TODO(gri) narrow column tolerance
255 func TestExamples(t *testing.T)  { testDir(t, 0, "examples") }
256 func TestFixedbugs(t *testing.T) { testDir(t, 0, "fixedbugs") }
257
258 func testDir(t *testing.T, colDelta uint, dir string) {
259         testenv.MustHaveGoBuild(t)
260
261         fis, err := ioutil.ReadDir(dir)
262         if err != nil {
263                 t.Error(err)
264                 return
265         }
266
267         for count, fi := range fis {
268                 path := filepath.Join(dir, fi.Name())
269
270                 // if fi is a directory, its files make up a single package
271                 if fi.IsDir() {
272                         if testing.Verbose() {
273                                 fmt.Printf("%3d %s\n", count, path)
274                         }
275                         fis, err := ioutil.ReadDir(path)
276                         if err != nil {
277                                 t.Error(err)
278                                 continue
279                         }
280                         files := make([]string, len(fis))
281                         for i, fi := range fis {
282                                 // if fi is a directory, checkFiles below will complain
283                                 files[i] = filepath.Join(path, fi.Name())
284                                 if testing.Verbose() {
285                                         fmt.Printf("\t%s\n", files[i])
286                                 }
287                         }
288                         checkFiles(t, files, "", colDelta, false)
289                         continue
290                 }
291
292                 // otherwise, fi is a stand-alone file
293                 if testing.Verbose() {
294                         fmt.Printf("%3d %s\n", count, path)
295                 }
296                 checkFiles(t, []string{path}, "", colDelta, false)
297         }
298 }