]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/check_test.go
go/types, types2: make the new comparable semantics the default
[gostls13.git] / src / go / types / 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 error messages expected in the test files.
8 //
9 // Expected errors are indicated in the test files by putting a comment
10 // of the form /* ERROR "rx" */ immediately following an offending token.
11 // The harness will verify that an error matching the regular expression
12 // rx is reported at that source position. Consecutive comments may be
13 // used to indicate multiple errors for the same token position.
14 //
15 // For instance, the following test file indicates that a "not declared"
16 // error should be reported for the undeclared variable x:
17 //
18 //      package p
19 //      func f() {
20 //              _ = x /* ERROR "not declared" */ + 1
21 //      }
22
23 package types_test
24
25 import (
26         "bytes"
27         "flag"
28         "fmt"
29         "go/ast"
30         "go/importer"
31         "go/parser"
32         "go/scanner"
33         "go/token"
34         "internal/testenv"
35         "os"
36         "path/filepath"
37         "reflect"
38         "regexp"
39         "strings"
40         "testing"
41
42         . "go/types"
43 )
44
45 var (
46         haltOnError  = flag.Bool("halt", false, "halt on error")
47         verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
48 )
49
50 var fset = token.NewFileSet()
51
52 // Positioned errors are of the form filename:line:column: message .
53 var posMsgRx = regexp.MustCompile(`^(.*:\d+:\d+): *(?s)(.*)`)
54
55 // splitError splits an error's error message into a position string
56 // and the actual error message. If there's no position information,
57 // pos is the empty string, and msg is the entire error message.
58 func splitError(err error) (pos, msg string) {
59         msg = err.Error()
60         if m := posMsgRx.FindStringSubmatch(msg); len(m) == 3 {
61                 pos = m[1]
62                 msg = m[2]
63         }
64         return
65 }
66
67 func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode parser.Mode) ([]*ast.File, []error) {
68         var files []*ast.File
69         var errlist []error
70         for i, filename := range filenames {
71                 file, err := parser.ParseFile(fset, filename, srcs[i], mode)
72                 if file == nil {
73                         t.Fatalf("%s: %s", filename, err)
74                 }
75                 files = append(files, file)
76                 if err != nil {
77                         if list, _ := err.(scanner.ErrorList); len(list) > 0 {
78                                 for _, err := range list {
79                                         errlist = append(errlist, err)
80                                 }
81                         } else {
82                                 errlist = append(errlist, err)
83                         }
84                 }
85         }
86         return files, errlist
87 }
88
89 // ERROR comments must start with text `ERROR "rx"` or `ERROR rx` where
90 // rx is a regular expression that matches the expected error message.
91 // Space around "rx" or rx is ignored.
92 var errRx = regexp.MustCompile(`^ *ERROR *"?([^"]*)"?`)
93
94 // errMap collects the regular expressions of ERROR comments found
95 // in files and returns them as a map of error positions to error messages.
96 //
97 // srcs must be a slice of the same length as files, containing the original
98 // source for the parsed AST.
99 func errMap(t *testing.T, files []*ast.File, srcs [][]byte) map[string][]string {
100         // map of position strings to lists of error message patterns
101         errmap := make(map[string][]string)
102
103         for i, file := range files {
104                 tok := fset.File(file.Package)
105                 src := srcs[i]
106                 var s scanner.Scanner
107                 s.Init(tok, src, nil, scanner.ScanComments)
108                 var prev token.Pos // position of last non-comment, non-semicolon token
109
110         scanFile:
111                 for {
112                         pos, tok, lit := s.Scan()
113                         switch tok {
114                         case token.EOF:
115                                 break scanFile
116                         case token.COMMENT:
117                                 if lit[1] == '*' {
118                                         lit = lit[:len(lit)-2] // strip trailing */
119                                 }
120                                 if s := errRx.FindStringSubmatch(lit[2:]); len(s) == 2 {
121                                         p := fset.Position(prev).String()
122                                         errmap[p] = append(errmap[p], strings.TrimSpace(s[1]))
123                                 }
124                         case token.SEMICOLON:
125                                 // ignore automatically inserted semicolon
126                                 if lit == "\n" {
127                                         continue scanFile
128                                 }
129                                 fallthrough
130                         default:
131                                 prev = pos
132                         }
133                 }
134         }
135
136         return errmap
137 }
138
139 func eliminate(t *testing.T, errmap map[string][]string, errlist []error) {
140         for _, err := range errlist {
141                 pos, gotMsg := splitError(err)
142                 list := errmap[pos]
143                 index := -1 // list index of matching message, if any
144                 // we expect one of the messages in list to match the error at pos
145                 for i, wantRx := range list {
146                         rx, err := regexp.Compile(wantRx)
147                         if err != nil {
148                                 t.Errorf("%s: %v", pos, err)
149                                 continue
150                         }
151                         if rx.MatchString(gotMsg) {
152                                 index = i
153                                 break
154                         }
155                 }
156                 if index >= 0 {
157                         // eliminate from list
158                         if n := len(list) - 1; n > 0 {
159                                 // not the last entry - swap in last element and shorten list by 1
160                                 list[index] = list[n]
161                                 errmap[pos] = list[:n]
162                         } else {
163                                 // last entry - remove list from map
164                                 delete(errmap, pos)
165                         }
166                 } else {
167                         t.Errorf("%s: no error expected: %q", pos, gotMsg)
168                 }
169         }
170 }
171
172 // parseFlags parses flags from the first line of the given source
173 // (from src if present, or by reading from the file) if the line
174 // starts with "//" (line comment) followed by "-" (possibly with
175 // spaces between). Otherwise the line is ignored.
176 func parseFlags(filename string, src []byte, flags *flag.FlagSet) error {
177         // If there is no src, read from the file.
178         const maxLen = 256
179         if len(src) == 0 {
180                 f, err := os.Open(filename)
181                 if err != nil {
182                         return err
183                 }
184
185                 var buf [maxLen]byte
186                 n, err := f.Read(buf[:])
187                 if err != nil {
188                         return err
189                 }
190                 src = buf[:n]
191         }
192
193         // we must have a line comment that starts with a "-"
194         const prefix = "//"
195         if !bytes.HasPrefix(src, []byte(prefix)) {
196                 return nil // first line is not a line comment
197         }
198         src = src[len(prefix):]
199         if i := bytes.Index(src, []byte("-")); i < 0 || len(bytes.TrimSpace(src[:i])) != 0 {
200                 return nil // comment doesn't start with a "-"
201         }
202         end := bytes.Index(src, []byte("\n"))
203         if end < 0 || end > maxLen {
204                 return fmt.Errorf("flags comment line too long")
205         }
206
207         return flags.Parse(strings.Fields(string(src[:end])))
208 }
209
210 func testFiles(t *testing.T, sizes Sizes, filenames []string, srcs [][]byte, manual bool, imp Importer) {
211         if len(filenames) == 0 {
212                 t.Fatal("no source files")
213         }
214
215         var conf Config
216         conf.Sizes = sizes
217         flags := flag.NewFlagSet("", flag.PanicOnError)
218         flags.StringVar(&conf.GoVersion, "lang", "", "")
219         flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
220         flags.BoolVar(addrOldComparableSemantics(&conf), "oldComparableSemantics", false, "")
221         if err := parseFlags(filenames[0], srcs[0], flags); err != nil {
222                 t.Fatal(err)
223         }
224
225         files, errlist := parseFiles(t, filenames, srcs, parser.AllErrors)
226
227         pkgName := "<no package>"
228         if len(files) > 0 {
229                 pkgName = files[0].Name.Name
230         }
231
232         listErrors := manual && !*verifyErrors
233         if listErrors && len(errlist) > 0 {
234                 t.Errorf("--- %s:", pkgName)
235                 for _, err := range errlist {
236                         t.Error(err)
237                 }
238         }
239
240         // typecheck and collect typechecker errors
241         if imp == nil {
242                 imp = importer.Default()
243         }
244         conf.Importer = imp
245         conf.Error = func(err error) {
246                 if *haltOnError {
247                         defer panic(err)
248                 }
249                 if listErrors {
250                         t.Error(err)
251                         return
252                 }
253                 // Ignore secondary error messages starting with "\t";
254                 // they are clarifying messages for a primary error.
255                 if !strings.Contains(err.Error(), ": \t") {
256                         errlist = append(errlist, err)
257                 }
258         }
259         conf.Check(pkgName, fset, files, nil)
260
261         if listErrors {
262                 return
263         }
264
265         for _, err := range errlist {
266                 err, ok := err.(Error)
267                 if !ok {
268                         continue
269                 }
270                 code := readCode(err)
271                 if code == 0 {
272                         t.Errorf("missing error code: %v", err)
273                 }
274         }
275
276         // match and eliminate errors;
277         // we are expecting the following errors
278         errmap := errMap(t, files, srcs)
279         eliminate(t, errmap, errlist)
280
281         // there should be no expected errors left
282         if len(errmap) > 0 {
283                 t.Errorf("--- %s: %d source positions with expected (but not reported) errors:", pkgName, len(errmap))
284                 for pos, list := range errmap {
285                         for _, rx := range list {
286                                 t.Errorf("%s: %q", pos, rx)
287                         }
288                 }
289         }
290 }
291
292 func readCode(err Error) int {
293         v := reflect.ValueOf(err)
294         return int(v.FieldByName("go116code").Int())
295 }
296
297 // addrOldComparableSemantics(conf) returns &conf.oldComparableSemantics (unexported field).
298 func addrOldComparableSemantics(conf *Config) *bool {
299         v := reflect.Indirect(reflect.ValueOf(conf))
300         return (*bool)(v.FieldByName("oldComparableSemantics").Addr().UnsafePointer())
301 }
302
303 // TestManual is for manual testing of a package - either provided
304 // as a list of filenames belonging to the package, or a directory
305 // name containing the package files - after the test arguments
306 // (and a separating "--"). For instance, to test the package made
307 // of the files foo.go and bar.go, use:
308 //
309 //      go test -run Manual -- foo.go bar.go
310 //
311 // If no source arguments are provided, the file testdata/manual.go
312 // is used instead.
313 // Provide the -verify flag to verify errors against ERROR comments
314 // in the input files rather than having a list of errors reported.
315 // The accepted Go language version can be controlled with the -lang
316 // flag.
317 func TestManual(t *testing.T) {
318         testenv.MustHaveGoBuild(t)
319
320         filenames := flag.Args()
321         if len(filenames) == 0 {
322                 filenames = []string{filepath.FromSlash("testdata/manual.go")}
323         }
324
325         info, err := os.Stat(filenames[0])
326         if err != nil {
327                 t.Fatalf("TestManual: %v", err)
328         }
329
330         DefPredeclaredTestFuncs()
331         if info.IsDir() {
332                 if len(filenames) > 1 {
333                         t.Fatal("TestManual: must have only one directory argument")
334                 }
335                 testDir(t, filenames[0], true)
336         } else {
337                 testPkg(t, filenames, true)
338         }
339 }
340
341 func TestLongConstants(t *testing.T) {
342         format := "package longconst\n\nconst _ = %s /* ERROR constant overflow */ \nconst _ = %s // ERROR excessively long constant"
343         src := fmt.Sprintf(format, strings.Repeat("1", 9999), strings.Repeat("1", 10001))
344         testFiles(t, nil, []string{"longconst.go"}, [][]byte{[]byte(src)}, false, nil)
345 }
346
347 // TestIndexRepresentability tests that constant index operands must
348 // be representable as int even if they already have a type that can
349 // represent larger values.
350 func TestIndexRepresentability(t *testing.T) {
351         const src = "package index\n\nvar s []byte\nvar _ = s[int64 /* ERROR \"int64\\(1\\) << 40 \\(.*\\) overflows int\" */ (1) << 40]"
352         testFiles(t, &StdSizes{4, 4}, []string{"index.go"}, [][]byte{[]byte(src)}, false, nil)
353 }
354
355 func TestIssue47243_TypedRHS(t *testing.T) {
356         // The RHS of the shift expression below overflows uint on 32bit platforms,
357         // but this is OK as it is explicitly typed.
358         const src = "package issue47243\n\nvar a uint64; var _ = a << uint64(4294967296)" // uint64(1<<32)
359         testFiles(t, &StdSizes{4, 4}, []string{"p.go"}, [][]byte{[]byte(src)}, false, nil)
360 }
361
362 func TestCheck(t *testing.T) {
363         DefPredeclaredTestFuncs()
364         testDirFiles(t, "../../internal/types/testdata/check", false)
365 }
366 func TestSpec(t *testing.T)      { testDirFiles(t, "../../internal/types/testdata/spec", false) }
367 func TestExamples(t *testing.T)  { testDirFiles(t, "../../internal/types/testdata/examples", false) }
368 func TestFixedbugs(t *testing.T) { testDirFiles(t, "../../internal/types/testdata/fixedbugs", false) }
369 func TestLocal(t *testing.T)     { testDirFiles(t, "testdata/local", false) }
370
371 func testDirFiles(t *testing.T, dir string, manual bool) {
372         testenv.MustHaveGoBuild(t)
373         dir = filepath.FromSlash(dir)
374
375         fis, err := os.ReadDir(dir)
376         if err != nil {
377                 t.Error(err)
378                 return
379         }
380
381         for _, fi := range fis {
382                 path := filepath.Join(dir, fi.Name())
383
384                 // If fi is a directory, its files make up a single package.
385                 if fi.IsDir() {
386                         testDir(t, path, manual)
387                 } else {
388                         t.Run(filepath.Base(path), func(t *testing.T) {
389                                 testPkg(t, []string{path}, manual)
390                         })
391                 }
392         }
393 }
394
395 func testDir(t *testing.T, dir string, manual bool) {
396         testenv.MustHaveGoBuild(t)
397
398         fis, err := os.ReadDir(dir)
399         if err != nil {
400                 t.Error(err)
401                 return
402         }
403
404         var filenames []string
405         for _, fi := range fis {
406                 filenames = append(filenames, filepath.Join(dir, fi.Name()))
407         }
408
409         t.Run(filepath.Base(dir), func(t *testing.T) {
410                 testPkg(t, filenames, manual)
411         })
412 }
413
414 // TODO(rFindley) reconcile the different test setup in go/types with types2.
415 func testPkg(t *testing.T, filenames []string, manual bool) {
416         srcs := make([][]byte, len(filenames))
417         for i, filename := range filenames {
418                 src, err := os.ReadFile(filename)
419                 if err != nil {
420                         t.Fatalf("could not read %s: %v", filename, err)
421                 }
422                 srcs[i] = src
423         }
424         testFiles(t, nil, filenames, srcs, manual, nil)
425 }