]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/check_test.go
go/types, types2: use new type inference algorithm exclusively
[gostls13.git] / src / cmd / compile / internal / types2 / 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 errors expected in the test files.
8 //
9 // Expected errors are indicated in the test files by putting comments
10 // of the form /* ERROR pattern */ or /* ERRORx pattern */ (or a similar
11 // //-style line comment) immediately following the tokens where errors
12 // are reported. There must be exactly one blank before and after the
13 // ERROR/ERRORx indicator, and the pattern must be a properly quoted Go
14 // string.
15 //
16 // The harness will verify that each ERROR pattern is a substring of the
17 // error reported at that source position, and that each ERRORx pattern
18 // is a regular expression matching the respective error.
19 // Consecutive comments may be used to indicate multiple errors reported
20 // at the same position.
21 //
22 // For instance, the following test source indicates that an "undeclared"
23 // error should be reported for the undeclared variable x:
24 //
25 //      package p
26 //      func f() {
27 //              _ = x /* ERROR "undeclared" */ + 1
28 //      }
29
30 package types2_test
31
32 import (
33         "bytes"
34         "cmd/compile/internal/syntax"
35         "flag"
36         "fmt"
37         "internal/testenv"
38         "os"
39         "path/filepath"
40         "regexp"
41         "strconv"
42         "strings"
43         "testing"
44
45         . "cmd/compile/internal/types2"
46 )
47
48 var (
49         haltOnError  = flag.Bool("halt", false, "halt on error")
50         verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
51 )
52
53 func parseFiles(t *testing.T, filenames []string, mode syntax.Mode) ([]*syntax.File, []error) {
54         var files []*syntax.File
55         var errlist []error
56         errh := func(err error) { errlist = append(errlist, err) }
57         for _, filename := range filenames {
58                 file, err := syntax.ParseFile(filename, errh, nil, mode)
59                 if file == nil {
60                         t.Fatalf("%s: %s", filename, err)
61                 }
62                 files = append(files, file)
63         }
64         return files, errlist
65 }
66
67 func unpackError(err error) (syntax.Pos, string) {
68         switch err := err.(type) {
69         case syntax.Error:
70                 return err.Pos, err.Msg
71         case Error:
72                 return err.Pos, err.Msg
73         default:
74                 return nopos, err.Error()
75         }
76 }
77
78 // absDiff returns the absolute difference between x and y.
79 func absDiff(x, y uint) uint {
80         if x < y {
81                 return y - x
82         }
83         return x - y
84 }
85
86 // Note: parseFlags is identical to the version in go/types which is
87 //       why it has a src argument even though here it is always nil.
88
89 // parseFlags parses flags from the first line of the given source
90 // (from src if present, or by reading from the file) if the line
91 // starts with "//" (line comment) followed by "-" (possibly with
92 // spaces between). Otherwise the line is ignored.
93 func parseFlags(filename string, src []byte, flags *flag.FlagSet) error {
94         // If there is no src, read from the file.
95         const maxLen = 256
96         if len(src) == 0 {
97                 f, err := os.Open(filename)
98                 if err != nil {
99                         return err
100                 }
101
102                 var buf [maxLen]byte
103                 n, err := f.Read(buf[:])
104                 if err != nil {
105                         return err
106                 }
107                 src = buf[:n]
108         }
109
110         // we must have a line comment that starts with a "-"
111         const prefix = "//"
112         if !bytes.HasPrefix(src, []byte(prefix)) {
113                 return nil // first line is not a line comment
114         }
115         src = src[len(prefix):]
116         if i := bytes.Index(src, []byte("-")); i < 0 || len(bytes.TrimSpace(src[:i])) != 0 {
117                 return nil // comment doesn't start with a "-"
118         }
119         end := bytes.Index(src, []byte("\n"))
120         if end < 0 || end > maxLen {
121                 return fmt.Errorf("flags comment line too long")
122         }
123
124         return flags.Parse(strings.Fields(string(src[:end])))
125 }
126
127 func testFiles(t *testing.T, filenames []string, colDelta uint, manual bool) {
128         if len(filenames) == 0 {
129                 t.Fatal("no source files")
130         }
131
132         var conf Config
133         flags := flag.NewFlagSet("", flag.PanicOnError)
134         flags.StringVar(&conf.GoVersion, "lang", "", "")
135         flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
136         if err := parseFlags(filenames[0], nil, flags); err != nil {
137                 t.Fatal(err)
138         }
139
140         files, errlist := parseFiles(t, filenames, 0)
141
142         pkgName := "<no package>"
143         if len(files) > 0 {
144                 pkgName = files[0].PkgName.Value
145         }
146
147         listErrors := manual && !*verifyErrors
148         if listErrors && len(errlist) > 0 {
149                 t.Errorf("--- %s:", pkgName)
150                 for _, err := range errlist {
151                         t.Error(err)
152                 }
153         }
154
155         // typecheck and collect typechecker errors
156         conf.Trace = manual && testing.Verbose()
157         conf.Importer = defaultImporter()
158         conf.Error = func(err error) {
159                 if *haltOnError {
160                         defer panic(err)
161                 }
162                 if listErrors {
163                         t.Error(err)
164                         return
165                 }
166                 errlist = append(errlist, err)
167         }
168         conf.Check(pkgName, files, nil)
169
170         if listErrors {
171                 return
172         }
173
174         // collect expected errors
175         errmap := make(map[string]map[uint][]syntax.Error)
176         for _, filename := range filenames {
177                 f, err := os.Open(filename)
178                 if err != nil {
179                         t.Error(err)
180                         continue
181                 }
182                 if m := syntax.CommentMap(f, regexp.MustCompile("^ ERRORx? ")); len(m) > 0 {
183                         errmap[filename] = m
184                 }
185                 f.Close()
186         }
187
188         // match against found errors
189         var indices []int // list indices of matching errors, reused for each error
190         for _, err := range errlist {
191                 gotPos, gotMsg := unpackError(err)
192
193                 // find list of errors for the respective error line
194                 filename := gotPos.Base().Filename()
195                 filemap := errmap[filename]
196                 line := gotPos.Line()
197                 var errList []syntax.Error
198                 if filemap != nil {
199                         errList = filemap[line]
200                 }
201
202                 // At least one of the errors in errList should match the current error.
203                 indices = indices[:0]
204                 for i, want := range errList {
205                         pattern, substr := strings.CutPrefix(want.Msg, " ERROR ")
206                         if !substr {
207                                 var found bool
208                                 pattern, found = strings.CutPrefix(want.Msg, " ERRORx ")
209                                 if !found {
210                                         panic("unreachable")
211                                 }
212                         }
213                         pattern, err := strconv.Unquote(strings.TrimSpace(pattern))
214                         if err != nil {
215                                 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
216                                 continue
217                         }
218                         if substr {
219                                 if !strings.Contains(gotMsg, pattern) {
220                                         continue
221                                 }
222                         } else {
223                                 rx, err := regexp.Compile(pattern)
224                                 if err != nil {
225                                         t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
226                                         continue
227                                 }
228                                 if !rx.MatchString(gotMsg) {
229                                         continue
230                                 }
231                         }
232                         indices = append(indices, i)
233                 }
234                 if len(indices) == 0 {
235                         t.Errorf("%s: no error expected: %q", gotPos, gotMsg)
236                         continue
237                 }
238                 // len(indices) > 0
239
240                 // If there are multiple matching errors, select the one with the closest column position.
241                 index := -1 // index of matching error
242                 var delta uint
243                 for _, i := range indices {
244                         if d := absDiff(gotPos.Col(), errList[i].Pos.Col()); index < 0 || d < delta {
245                                 index, delta = i, d
246                         }
247                 }
248
249                 // The closest column position must be within expected colDelta.
250                 if delta > colDelta {
251                         t.Errorf("%s: got col = %d; want %d", gotPos, gotPos.Col(), errList[index].Pos.Col())
252                 }
253
254                 // eliminate from errList
255                 if n := len(errList) - 1; n > 0 {
256                         // not the last entry - slide entries down (don't reorder)
257                         copy(errList[index:], errList[index+1:])
258                         filemap[line] = errList[:n]
259                 } else {
260                         // last entry - remove errList from filemap
261                         delete(filemap, line)
262                 }
263
264                 // if filemap is empty, eliminate from errmap
265                 if len(filemap) == 0 {
266                         delete(errmap, filename)
267                 }
268         }
269
270         // there should be no expected errors left
271         if len(errmap) > 0 {
272                 t.Errorf("--- %s: unreported errors:", pkgName)
273                 for filename, filemap := range errmap {
274                         for line, errList := range filemap {
275                                 for _, err := range errList {
276                                         t.Errorf("%s:%d:%d: %s", filename, line, err.Pos.Col(), err.Msg)
277                                 }
278                         }
279                 }
280         }
281 }
282
283 // TestManual is for manual testing of a package - either provided
284 // as a list of filenames belonging to the package, or a directory
285 // name containing the package files - after the test arguments
286 // (and a separating "--"). For instance, to test the package made
287 // of the files foo.go and bar.go, use:
288 //
289 //      go test -run Manual -- foo.go bar.go
290 //
291 // If no source arguments are provided, the file testdata/manual.go
292 // is used instead.
293 // Provide the -verify flag to verify errors against ERROR comments
294 // in the input files rather than having a list of errors reported.
295 // The accepted Go language version can be controlled with the -lang
296 // flag.
297 func TestManual(t *testing.T) {
298         testenv.MustHaveGoBuild(t)
299
300         filenames := flag.Args()
301         if len(filenames) == 0 {
302                 filenames = []string{filepath.FromSlash("testdata/manual.go")}
303         }
304
305         info, err := os.Stat(filenames[0])
306         if err != nil {
307                 t.Fatalf("TestManual: %v", err)
308         }
309
310         DefPredeclaredTestFuncs()
311         if info.IsDir() {
312                 if len(filenames) > 1 {
313                         t.Fatal("TestManual: must have only one directory argument")
314                 }
315                 testDir(t, filenames[0], 0, true)
316         } else {
317                 testFiles(t, filenames, 0, true)
318         }
319 }
320
321 // TODO(gri) go/types has extra TestLongConstants and TestIndexRepresentability tests
322
323 func TestCheck(t *testing.T) {
324         DefPredeclaredTestFuncs()
325         testDirFiles(t, "../../../../internal/types/testdata/check", 50, false) // TODO(gri) narrow column tolerance
326 }
327 func TestSpec(t *testing.T) { testDirFiles(t, "../../../../internal/types/testdata/spec", 0, false) }
328 func TestExamples(t *testing.T) {
329         testDirFiles(t, "../../../../internal/types/testdata/examples", 60, false)
330 } // TODO(gri) narrow column tolerance
331 func TestFixedbugs(t *testing.T) {
332         testDirFiles(t, "../../../../internal/types/testdata/fixedbugs", 100, false)
333 }                            // TODO(gri) narrow column tolerance
334 func TestLocal(t *testing.T) { testDirFiles(t, "testdata/local", 0, false) }
335
336 func testDirFiles(t *testing.T, dir string, colDelta uint, manual bool) {
337         testenv.MustHaveGoBuild(t)
338         dir = filepath.FromSlash(dir)
339
340         fis, err := os.ReadDir(dir)
341         if err != nil {
342                 t.Error(err)
343                 return
344         }
345
346         for _, fi := range fis {
347                 path := filepath.Join(dir, fi.Name())
348
349                 // If fi is a directory, its files make up a single package.
350                 if fi.IsDir() {
351                         testDir(t, path, colDelta, manual)
352                 } else {
353                         t.Run(filepath.Base(path), func(t *testing.T) {
354                                 testFiles(t, []string{path}, colDelta, manual)
355                         })
356                 }
357         }
358 }
359
360 func testDir(t *testing.T, dir string, colDelta uint, manual bool) {
361         fis, err := os.ReadDir(dir)
362         if err != nil {
363                 t.Error(err)
364                 return
365         }
366
367         var filenames []string
368         for _, fi := range fis {
369                 filenames = append(filenames, filepath.Join(dir, fi.Name()))
370         }
371
372         t.Run(filepath.Base(dir), func(t *testing.T) {
373                 testFiles(t, filenames, colDelta, manual)
374         })
375 }