]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/check_test.go
go/types, types2: consider shared methods when unifying against interfaces
[gostls13.git] / src / go / types / check_test.go
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.
4
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 errors expected in the test files.
8 //
9 // Expected errors are indicated in the test files by putting comments
10 // of the form /* ERROR pattern */ or /* ERRORx pattern */ (or a similar
11 // //-style line comment) immediately following the tokens where errors
12 // are reported. There must be exactly one blank before and after the
13 // ERROR/ERRORx indicator, and the pattern must be a properly quoted Go
14 // string.
15 //
16 // The harness will verify that each ERROR pattern is a substring of the
17 // error reported at that source position, and that each ERRORx pattern
18 // is a regular expression matching the respective error.
19 // Consecutive comments may be used to indicate multiple errors reported
20 // at the same position.
21 //
22 // For instance, the following test source indicates that an "undeclared"
23 // error should be reported for the undeclared variable x:
24 //
25 //      package p
26 //      func f() {
27 //              _ = x /* ERROR "undeclared" */ + 1
28 //      }
29
30 package types_test
31
32 import (
33         "bytes"
34         "flag"
35         "fmt"
36         "go/ast"
37         "go/importer"
38         "go/parser"
39         "go/scanner"
40         "go/token"
41         "internal/testenv"
42         "internal/types/errors"
43         "os"
44         "path/filepath"
45         "reflect"
46         "regexp"
47         "strconv"
48         "strings"
49         "testing"
50
51         . "go/types"
52 )
53
54 var (
55         haltOnError  = flag.Bool("halt", false, "halt on error")
56         verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
57 )
58
59 var fset = token.NewFileSet()
60
61 func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode parser.Mode) ([]*ast.File, []error) {
62         var files []*ast.File
63         var errlist []error
64         for i, filename := range filenames {
65                 file, err := parser.ParseFile(fset, filename, srcs[i], mode)
66                 if file == nil {
67                         t.Fatalf("%s: %s", filename, err)
68                 }
69                 files = append(files, file)
70                 if err != nil {
71                         if list, _ := err.(scanner.ErrorList); len(list) > 0 {
72                                 for _, err := range list {
73                                         errlist = append(errlist, err)
74                                 }
75                         } else {
76                                 errlist = append(errlist, err)
77                         }
78                 }
79         }
80         return files, errlist
81 }
82
83 func unpackError(fset *token.FileSet, err error) (token.Position, string) {
84         switch err := err.(type) {
85         case *scanner.Error:
86                 return err.Pos, err.Msg
87         case Error:
88                 return fset.Position(err.Pos), err.Msg
89         }
90         panic("unreachable")
91 }
92
93 // absDiff returns the absolute difference between x and y.
94 func absDiff(x, y int) int {
95         if x < y {
96                 return y - x
97         }
98         return x - y
99 }
100
101 // parseFlags parses flags from the first line of the given source if the line
102 // starts with "//" (line comment) followed by "-" (possibly with spaces
103 // between). Otherwise the line is ignored.
104 func parseFlags(src []byte, flags *flag.FlagSet) error {
105         // we must have a line comment that starts with a "-"
106         const prefix = "//"
107         if !bytes.HasPrefix(src, []byte(prefix)) {
108                 return nil // first line is not a line comment
109         }
110         src = src[len(prefix):]
111         if i := bytes.Index(src, []byte("-")); i < 0 || len(bytes.TrimSpace(src[:i])) != 0 {
112                 return nil // comment doesn't start with a "-"
113         }
114         end := bytes.Index(src, []byte("\n"))
115         const maxLen = 256
116         if end < 0 || end > maxLen {
117                 return fmt.Errorf("flags comment line too long")
118         }
119
120         return flags.Parse(strings.Fields(string(src[:end])))
121 }
122
123 // testFiles type-checks the package consisting of the given files, and
124 // compares the resulting errors with the ERROR annotations in the source.
125 //
126 // The srcs slice contains the file content for the files named in the
127 // filenames slice. The manual parameter specifies whether this is a 'manual'
128 // test.
129 //
130 // If provided, opts may be used to mutate the Config before type-checking.
131 func testFiles(t *testing.T, filenames []string, srcs [][]byte, manual bool, opts ...func(*Config)) {
132         if len(filenames) == 0 {
133                 t.Fatal("no source files")
134         }
135
136         var conf Config
137         flags := flag.NewFlagSet("", flag.PanicOnError)
138         flags.StringVar(&conf.GoVersion, "lang", "", "")
139         flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
140         flags.BoolVar(boolFieldAddr(&conf, "_EnableInterfaceInference"), "EnableInterfaceInference", false, "")
141         if err := parseFlags(srcs[0], flags); err != nil {
142                 t.Fatal(err)
143         }
144
145         files, errlist := parseFiles(t, filenames, srcs, parser.AllErrors)
146
147         pkgName := "<no package>"
148         if len(files) > 0 {
149                 pkgName = files[0].Name.Name
150         }
151
152         listErrors := manual && !*verifyErrors
153         if listErrors && len(errlist) > 0 {
154                 t.Errorf("--- %s:", pkgName)
155                 for _, err := range errlist {
156                         t.Error(err)
157                 }
158         }
159
160         // typecheck and collect typechecker errors
161         *boolFieldAddr(&conf, "_Trace") = manual && testing.Verbose()
162         conf.Importer = importer.Default()
163         conf.Error = func(err error) {
164                 if *haltOnError {
165                         defer panic(err)
166                 }
167                 if listErrors {
168                         t.Error(err)
169                         return
170                 }
171                 // Ignore secondary error messages starting with "\t";
172                 // they are clarifying messages for a primary error.
173                 if !strings.Contains(err.Error(), ": \t") {
174                         errlist = append(errlist, err)
175                 }
176         }
177
178         for _, opt := range opts {
179                 opt(&conf)
180         }
181
182         conf.Check(pkgName, fset, files, nil)
183
184         if listErrors {
185                 return
186         }
187
188         // collect expected errors
189         errmap := make(map[string]map[int][]comment)
190         for i, filename := range filenames {
191                 if m := commentMap(srcs[i], regexp.MustCompile("^ ERRORx? ")); len(m) > 0 {
192                         errmap[filename] = m
193                 }
194         }
195
196         // match against found errors
197         var indices []int // list indices of matching errors, reused for each error
198         for _, err := range errlist {
199                 gotPos, gotMsg := unpackError(fset, err)
200
201                 // find list of errors for the respective error line
202                 filename := gotPos.Filename
203                 filemap := errmap[filename]
204                 line := gotPos.Line
205                 var errList []comment
206                 if filemap != nil {
207                         errList = filemap[line]
208                 }
209
210                 // At least one of the errors in errList should match the current error.
211                 indices = indices[:0]
212                 for i, want := range errList {
213                         pattern, substr := strings.CutPrefix(want.text, " ERROR ")
214                         if !substr {
215                                 var found bool
216                                 pattern, found = strings.CutPrefix(want.text, " ERRORx ")
217                                 if !found {
218                                         panic("unreachable")
219                                 }
220                         }
221                         pattern, err := strconv.Unquote(strings.TrimSpace(pattern))
222                         if err != nil {
223                                 t.Errorf("%s:%d:%d: %v", filename, line, want.col, err)
224                                 continue
225                         }
226                         if substr {
227                                 if !strings.Contains(gotMsg, pattern) {
228                                         continue
229                                 }
230                         } else {
231                                 rx, err := regexp.Compile(pattern)
232                                 if err != nil {
233                                         t.Errorf("%s:%d:%d: %v", filename, line, want.col, err)
234                                         continue
235                                 }
236                                 if !rx.MatchString(gotMsg) {
237                                         continue
238                                 }
239                         }
240                         indices = append(indices, i)
241                 }
242                 if len(indices) == 0 {
243                         t.Errorf("%s: no error expected: %q", gotPos, gotMsg)
244                         continue
245                 }
246                 // len(indices) > 0
247
248                 // If there are multiple matching errors, select the one with the closest column position.
249                 index := -1 // index of matching error
250                 var delta int
251                 for _, i := range indices {
252                         if d := absDiff(gotPos.Column, errList[i].col); index < 0 || d < delta {
253                                 index, delta = i, d
254                         }
255                 }
256
257                 // The closest column position must be within expected colDelta.
258                 const colDelta = 0 // go/types errors are positioned correctly
259                 if delta > colDelta {
260                         t.Errorf("%s: got col = %d; want %d", gotPos, gotPos.Column, errList[index].col)
261                 }
262
263                 // eliminate from errList
264                 if n := len(errList) - 1; n > 0 {
265                         // not the last entry - slide entries down (don't reorder)
266                         copy(errList[index:], errList[index+1:])
267                         filemap[line] = errList[:n]
268                 } else {
269                         // last entry - remove errList from filemap
270                         delete(filemap, line)
271                 }
272
273                 // if filemap is empty, eliminate from errmap
274                 if len(filemap) == 0 {
275                         delete(errmap, filename)
276                 }
277         }
278
279         // there should be no expected errors left
280         if len(errmap) > 0 {
281                 t.Errorf("--- %s: unreported errors:", pkgName)
282                 for filename, filemap := range errmap {
283                         for line, errList := range filemap {
284                                 for _, err := range errList {
285                                         t.Errorf("%s:%d:%d: %s", filename, line, err.col, err.text)
286                                 }
287                         }
288                 }
289         }
290 }
291
292 func readCode(err Error) errors.Code {
293         v := reflect.ValueOf(err)
294         return errors.Code(v.FieldByName("go116code").Int())
295 }
296
297 // boolFieldAddr(conf, name) returns the address of the boolean field conf.<name>.
298 // For accessing unexported fields.
299 func boolFieldAddr(conf *Config, name string) *bool {
300         v := reflect.Indirect(reflect.ValueOf(conf))
301         return (*bool)(v.FieldByName(name).Addr().UnsafePointer())
302 }
303
304 // TestManual is for manual testing of a package - either provided
305 // as a list of filenames belonging to the package, or a directory
306 // name containing the package files - after the test arguments
307 // (and a separating "--"). For instance, to test the package made
308 // of the files foo.go and bar.go, use:
309 //
310 //      go test -run Manual -- foo.go bar.go
311 //
312 // If no source arguments are provided, the file testdata/manual.go
313 // is used instead.
314 // Provide the -verify flag to verify errors against ERROR comments
315 // in the input files rather than having a list of errors reported.
316 // The accepted Go language version can be controlled with the -lang
317 // flag.
318 func TestManual(t *testing.T) {
319         testenv.MustHaveGoBuild(t)
320
321         filenames := flag.Args()
322         if len(filenames) == 0 {
323                 filenames = []string{filepath.FromSlash("testdata/manual.go")}
324         }
325
326         info, err := os.Stat(filenames[0])
327         if err != nil {
328                 t.Fatalf("TestManual: %v", err)
329         }
330
331         DefPredeclaredTestFuncs()
332         if info.IsDir() {
333                 if len(filenames) > 1 {
334                         t.Fatal("TestManual: must have only one directory argument")
335                 }
336                 testDir(t, filenames[0], true)
337         } else {
338                 testPkg(t, filenames, true)
339         }
340 }
341
342 func TestLongConstants(t *testing.T) {
343         format := `package longconst; const _ = %s /* ERROR "constant overflow" */; const _ = %s // ERROR "excessively long constant"`
344         src := fmt.Sprintf(format, strings.Repeat("1", 9999), strings.Repeat("1", 10001))
345         testFiles(t, []string{"longconst.go"}, [][]byte{[]byte(src)}, false)
346 }
347
348 func withSizes(sizes Sizes) func(*Config) {
349         return func(cfg *Config) {
350                 cfg.Sizes = sizes
351         }
352 }
353
354 // TestIndexRepresentability tests that constant index operands must
355 // be representable as int even if they already have a type that can
356 // represent larger values.
357 func TestIndexRepresentability(t *testing.T) {
358         const src = `package index; var s []byte; var _ = s[int64 /* ERRORx "int64\\(1\\) << 40 \\(.*\\) overflows int" */ (1) << 40]`
359         testFiles(t, []string{"index.go"}, [][]byte{[]byte(src)}, false, withSizes(&StdSizes{4, 4}))
360 }
361
362 func TestIssue47243_TypedRHS(t *testing.T) {
363         // The RHS of the shift expression below overflows uint on 32bit platforms,
364         // but this is OK as it is explicitly typed.
365         const src = `package issue47243; var a uint64; var _ = a << uint64(4294967296)` // uint64(1<<32)
366         testFiles(t, []string{"p.go"}, [][]byte{[]byte(src)}, false, withSizes(&StdSizes{4, 4}))
367 }
368
369 func TestCheck(t *testing.T) {
370         DefPredeclaredTestFuncs()
371         testDirFiles(t, "../../internal/types/testdata/check", false)
372 }
373 func TestSpec(t *testing.T)      { testDirFiles(t, "../../internal/types/testdata/spec", false) }
374 func TestExamples(t *testing.T)  { testDirFiles(t, "../../internal/types/testdata/examples", false) }
375 func TestFixedbugs(t *testing.T) { testDirFiles(t, "../../internal/types/testdata/fixedbugs", false) }
376 func TestLocal(t *testing.T)     { testDirFiles(t, "testdata/local", false) }
377
378 func testDirFiles(t *testing.T, dir string, manual bool) {
379         testenv.MustHaveGoBuild(t)
380         dir = filepath.FromSlash(dir)
381
382         fis, err := os.ReadDir(dir)
383         if err != nil {
384                 t.Error(err)
385                 return
386         }
387
388         for _, fi := range fis {
389                 path := filepath.Join(dir, fi.Name())
390
391                 // If fi is a directory, its files make up a single package.
392                 if fi.IsDir() {
393                         testDir(t, path, manual)
394                 } else {
395                         t.Run(filepath.Base(path), func(t *testing.T) {
396                                 testPkg(t, []string{path}, manual)
397                         })
398                 }
399         }
400 }
401
402 func testDir(t *testing.T, dir string, manual bool) {
403         testenv.MustHaveGoBuild(t)
404
405         fis, err := os.ReadDir(dir)
406         if err != nil {
407                 t.Error(err)
408                 return
409         }
410
411         var filenames []string
412         for _, fi := range fis {
413                 filenames = append(filenames, filepath.Join(dir, fi.Name()))
414         }
415
416         t.Run(filepath.Base(dir), func(t *testing.T) {
417                 testPkg(t, filenames, manual)
418         })
419 }
420
421 func testPkg(t *testing.T, filenames []string, manual bool) {
422         srcs := make([][]byte, len(filenames))
423         for i, filename := range filenames {
424                 src, err := os.ReadFile(filename)
425                 if err != nil {
426                         t.Fatalf("could not read %s: %v", filename, err)
427                 }
428                 srcs[i] = src
429         }
430         testFiles(t, filenames, srcs, manual)
431 }