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