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