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