Source file
src/go/types/check_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 package types_test
31
32 import (
33 "bytes"
34 "flag"
35 "fmt"
36 "go/ast"
37 "go/build"
38 "go/build/constraint"
39 "go/parser"
40 "go/scanner"
41 "go/token"
42 "internal/buildcfg"
43 "internal/testenv"
44 "internal/types/errors"
45 "os"
46 "path/filepath"
47 "reflect"
48 "regexp"
49 "runtime"
50 "slices"
51 "strconv"
52 "strings"
53 "testing"
54
55 . "go/types"
56 )
57
58 var (
59 haltOnError = flag.Bool("halt", false, "halt on error")
60 verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
61 )
62
63 var fset = token.NewFileSet()
64
65 func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode parser.Mode) ([]*ast.File, []error) {
66 var files []*ast.File
67 var errlist []error
68 for i, filename := range filenames {
69 file, err := parser.ParseFile(fset, filename, srcs[i], mode)
70 if file == nil {
71 t.Fatalf("%s: %s", filename, err)
72 }
73 files = append(files, file)
74 if err != nil {
75 if list, _ := err.(scanner.ErrorList); len(list) > 0 {
76 for _, err := range list {
77 errlist = append(errlist, err)
78 }
79 } else {
80 errlist = append(errlist, err)
81 }
82 }
83 }
84 return files, errlist
85 }
86
87 func unpackError(fset *token.FileSet, err error) (token.Position, string) {
88 switch err := err.(type) {
89 case *scanner.Error:
90 return err.Pos, err.Msg
91 case Error:
92 return fset.Position(err.Pos), err.Msg
93 }
94 panic("unreachable")
95 }
96
97
98 func absDiff(x, y int) int {
99 if x < y {
100 return y - x
101 }
102 return x - y
103 }
104
105
106
107
108 func parseFlags(src []byte, flags *flag.FlagSet) error {
109
110 const prefix = "//"
111 if !bytes.HasPrefix(src, []byte(prefix)) {
112 return nil
113 }
114 src = src[len(prefix):]
115 if i := bytes.Index(src, []byte("-")); i < 0 || len(bytes.TrimSpace(src[:i])) != 0 {
116 return nil
117 }
118 end := bytes.Index(src, []byte("\n"))
119 const maxLen = 256
120 if end < 0 || end > maxLen {
121 return fmt.Errorf("flags comment line too long")
122 }
123
124 return flags.Parse(strings.Fields(string(src[:end])))
125 }
126
127
128
129
130
131
132
133
134
135
136 func testFiles(t *testing.T, filenames []string, srcs [][]byte, manual bool, opts ...func(*Config)) {
137 if len(filenames) == 0 {
138 t.Fatal("no source files")
139 }
140
141
142 files, errlist := parseFiles(t, filenames, srcs, parser.AllErrors|parser.SkipObjectResolution)
143 pkgName := "<no package>"
144 if len(files) > 0 {
145 pkgName = files[0].Name.Name
146 }
147 listErrors := manual && !*verifyErrors
148 if listErrors && len(errlist) > 0 {
149 t.Errorf("--- %s:", pkgName)
150 for _, err := range errlist {
151 t.Error(err)
152 }
153 }
154
155
156 var conf Config
157 *boolFieldAddr(&conf, "_Trace") = manual && testing.Verbose()
158 conf.Importer = defaultImporter(fset)
159 conf.Error = func(err error) {
160 if *haltOnError {
161 defer panic(err)
162 }
163 if listErrors {
164 t.Error(err)
165 return
166 }
167
168
169 if !strings.Contains(err.Error(), ": \t") {
170 errlist = append(errlist, err)
171 }
172 }
173
174
175 for _, opt := range opts {
176 opt(&conf)
177 }
178
179
180 var goexperiment string
181 flags := flag.NewFlagSet("", flag.PanicOnError)
182 flags.StringVar(&conf.GoVersion, "lang", "", "")
183 flags.StringVar(&goexperiment, "goexperiment", "", "")
184 flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
185 if err := parseFlags(srcs[0], flags); err != nil {
186 t.Fatal(err)
187 }
188
189 if goexperiment != "" {
190 revert := setGOEXPERIMENT(goexperiment)
191 defer revert()
192 }
193
194
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 FileVersions: make(map[*ast.File]string),
204 }
205
206
207 conf.Check(pkgName, fset, files, &info)
208 if listErrors {
209 return
210 }
211
212
213 errmap := make(map[string]map[int][]comment)
214 for i, filename := range filenames {
215 if m := commentMap(srcs[i], regexp.MustCompile("^ ERRORx? ")); len(m) > 0 {
216 errmap[filename] = m
217 }
218 }
219
220
221 var indices []int
222 for _, err := range errlist {
223 gotPos, gotMsg := unpackError(fset, err)
224
225
226 filename := gotPos.Filename
227 filemap := errmap[filename]
228 line := gotPos.Line
229 var errList []comment
230 if filemap != nil {
231 errList = filemap[line]
232 }
233
234
235 indices = indices[:0]
236 for i, want := range errList {
237 pattern, substr := strings.CutPrefix(want.text, " ERROR ")
238 if !substr {
239 var found bool
240 pattern, found = strings.CutPrefix(want.text, " ERRORx ")
241 if !found {
242 panic("unreachable")
243 }
244 }
245 unquoted, err := strconv.Unquote(strings.TrimSpace(pattern))
246 if err != nil {
247 t.Errorf("%s:%d:%d: invalid ERROR pattern (cannot unquote %s)", filename, line, want.col, pattern)
248 continue
249 }
250 if substr {
251 if !strings.Contains(gotMsg, unquoted) {
252 continue
253 }
254 } else {
255 rx, err := regexp.Compile(unquoted)
256 if err != nil {
257 t.Errorf("%s:%d:%d: %v", filename, line, want.col, err)
258 continue
259 }
260 if !rx.MatchString(gotMsg) {
261 continue
262 }
263 }
264 indices = append(indices, i)
265 }
266 if len(indices) == 0 {
267 t.Errorf("%s: no error expected: %q", gotPos, gotMsg)
268 continue
269 }
270
271
272
273 index := -1
274 var delta int
275 for _, i := range indices {
276 if d := absDiff(gotPos.Column, errList[i].col); index < 0 || d < delta {
277 index, delta = i, d
278 }
279 }
280
281
282 const colDelta = 0
283 if delta > colDelta {
284 t.Errorf("%s: got col = %d; want %d", gotPos, gotPos.Column, errList[index].col)
285 }
286
287
288 if n := len(errList) - 1; n > 0 {
289
290 copy(errList[index:], errList[index+1:])
291 filemap[line] = errList[:n]
292 } else {
293
294 delete(filemap, line)
295 }
296
297
298 if len(filemap) == 0 {
299 delete(errmap, filename)
300 }
301 }
302
303
304 if len(errmap) > 0 {
305 t.Errorf("--- %s: unreported errors:", pkgName)
306 for filename, filemap := range errmap {
307 for line, errList := range filemap {
308 for _, err := range errList {
309 t.Errorf("%s:%d:%d: %s", filename, line, err.col, err.text)
310 }
311 }
312 }
313 }
314 }
315
316 func readCode(err Error) errors.Code {
317 v := reflect.ValueOf(err)
318 return errors.Code(v.FieldByName("go116code").Int())
319 }
320
321
322
323 func boolFieldAddr(conf *Config, name string) *bool {
324 v := reflect.Indirect(reflect.ValueOf(conf))
325 return (*bool)(v.FieldByName(name).Addr().UnsafePointer())
326 }
327
328
329
330 func stringFieldAddr(conf *Config, name string) *string {
331 v := reflect.Indirect(reflect.ValueOf(conf))
332 return (*string)(v.FieldByName(name).Addr().UnsafePointer())
333 }
334
335
336
337
338
339 func setGOEXPERIMENT(goexperiment string) func() {
340 exp, err := buildcfg.ParseGOEXPERIMENT(runtime.GOOS, runtime.GOARCH, goexperiment)
341 if err != nil {
342 panic(err)
343 }
344 old := buildcfg.Experiment
345 buildcfg.Experiment = *exp
346 return func() { buildcfg.Experiment = old }
347 }
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363 func TestManual(t *testing.T) {
364 testenv.MustHaveGoBuild(t)
365
366 filenames := flag.Args()
367 if len(filenames) == 0 {
368 filenames = []string{filepath.FromSlash("testdata/manual.go")}
369 }
370
371 info, err := os.Stat(filenames[0])
372 if err != nil {
373 t.Fatalf("TestManual: %v", err)
374 }
375
376 DefPredeclaredTestFuncs()
377 if info.IsDir() {
378 if len(filenames) > 1 {
379 t.Fatal("TestManual: must have only one directory argument")
380 }
381 testDir(t, filenames[0], true)
382 } else {
383 testPkg(t, filenames, true)
384 }
385 }
386
387 func TestLongConstants(t *testing.T) {
388 format := `package longconst; const _ = %s /* ERROR "constant overflow" */; const _ = %s // ERROR "excessively long constant"`
389 src := fmt.Sprintf(format, strings.Repeat("1", 9999), strings.Repeat("1", 10001))
390 testFiles(t, []string{"longconst.go"}, [][]byte{[]byte(src)}, false)
391 }
392
393 func withSizes(sizes Sizes) func(*Config) {
394 return func(cfg *Config) {
395 cfg.Sizes = sizes
396 }
397 }
398
399
400
401
402 func TestIndexRepresentability(t *testing.T) {
403 const src = `package index; var s []byte; var _ = s[int64 /* ERRORx "int64\\(1\\) << 40 \\(.*\\) overflows int" */ (1) << 40]`
404 testFiles(t, []string{"index.go"}, [][]byte{[]byte(src)}, false, withSizes(&StdSizes{4, 4}))
405 }
406
407 func TestIssue47243_TypedRHS(t *testing.T) {
408
409
410 const src = `package issue47243; var a uint64; var _ = a << uint64(4294967296)`
411 testFiles(t, []string{"p.go"}, [][]byte{[]byte(src)}, false, withSizes(&StdSizes{4, 4}))
412 }
413
414 func TestCheck(t *testing.T) {
415 DefPredeclaredTestFuncs()
416 testDirFiles(t, "../../internal/types/testdata/check", false)
417 }
418 func TestSpec(t *testing.T) { testDirFiles(t, "../../internal/types/testdata/spec", false) }
419 func TestExamples(t *testing.T) { testDirFiles(t, "../../internal/types/testdata/examples", false) }
420 func TestFixedbugs(t *testing.T) { testDirFiles(t, "../../internal/types/testdata/fixedbugs", false) }
421 func TestLocal(t *testing.T) { testDirFiles(t, "testdata/local", false) }
422
423 func testDirFiles(t *testing.T, dir string, manual bool) {
424 testenv.MustHaveGoBuild(t)
425 dir = filepath.FromSlash(dir)
426
427 fis, err := os.ReadDir(dir)
428 if err != nil {
429 t.Error(err)
430 return
431 }
432
433 for _, fi := range fis {
434 path := filepath.Join(dir, fi.Name())
435
436
437 if fi.IsDir() {
438 testDir(t, path, manual)
439 } else {
440 t.Run(filepath.Base(path), func(t *testing.T) {
441 testPkg(t, []string{path}, manual)
442 })
443 }
444 }
445 }
446
447 func testDir(t *testing.T, dir string, manual bool) {
448 testenv.MustHaveGoBuild(t)
449
450 fis, err := os.ReadDir(dir)
451 if err != nil {
452 t.Error(err)
453 return
454 }
455
456 var filenames []string
457 for _, fi := range fis {
458 filenames = append(filenames, filepath.Join(dir, fi.Name()))
459 }
460
461 t.Run(filepath.Base(dir), func(t *testing.T) {
462 testPkg(t, filenames, manual)
463 })
464 }
465
466 func testPkg(t *testing.T, filenames []string, manual bool) {
467 fs := filenames[:0]
468 srcs := make([][]byte, 0, len(filenames))
469 for _, filename := range filenames {
470 src, err := os.ReadFile(filename)
471 if err != nil {
472 t.Fatalf("could not read %s: %v", filename, err)
473 }
474 if !shouldTest(src) {
475 continue
476 }
477 fs = append(fs, filename)
478 srcs = append(srcs, src)
479 }
480 if len(fs) == 0 {
481 t.Skip("all files skipped by build tags")
482 }
483 testFiles(t, fs, srcs, manual)
484 }
485
486
487
488 func shouldTest(src []byte) bool {
489 match := func(tag string) bool {
490
491 if slices.Contains(build.Default.ReleaseTags, tag) {
492 return true
493 }
494 return tag == runtime.GOOS || tag == runtime.GOARCH
495 }
496 for line := range strings.SplitSeq(string(src), "\n") {
497 if strings.HasPrefix(line, "package ") {
498 break
499 }
500 if expr, err := constraint.Parse(line); err == nil {
501 return expr.Eval(match)
502 }
503 }
504 return true
505 }
506
View as plain text