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