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