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