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