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