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