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