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