]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/check_test.go
go/types, types2: reverse inference of function type arguments
[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         flags.BoolVar(&conf.EnableReverseTypeInference, "reverseTypeInference", false, "")
137         if err := parseFlags(filenames[0], nil, flags); err != nil {
138                 t.Fatal(err)
139         }
140
141         files, errlist := parseFiles(t, filenames, 0)
142
143         pkgName := "<no package>"
144         if len(files) > 0 {
145                 pkgName = files[0].PkgName.Value
146         }
147
148         listErrors := manual && !*verifyErrors
149         if listErrors && len(errlist) > 0 {
150                 t.Errorf("--- %s:", pkgName)
151                 for _, err := range errlist {
152                         t.Error(err)
153                 }
154         }
155
156         // typecheck and collect typechecker errors
157         conf.Trace = manual && testing.Verbose()
158         conf.Importer = defaultImporter()
159         conf.Error = func(err error) {
160                 if *haltOnError {
161                         defer panic(err)
162                 }
163                 if listErrors {
164                         t.Error(err)
165                         return
166                 }
167                 errlist = append(errlist, err)
168         }
169         conf.Check(pkgName, files, nil)
170
171         if listErrors {
172                 return
173         }
174
175         // collect expected errors
176         errmap := make(map[string]map[uint][]syntax.Error)
177         for _, filename := range filenames {
178                 f, err := os.Open(filename)
179                 if err != nil {
180                         t.Error(err)
181                         continue
182                 }
183                 if m := syntax.CommentMap(f, regexp.MustCompile("^ ERRORx? ")); len(m) > 0 {
184                         errmap[filename] = m
185                 }
186                 f.Close()
187         }
188
189         // match against found errors
190         var indices []int // list indices of matching errors, reused for each error
191         for _, err := range errlist {
192                 gotPos, gotMsg := unpackError(err)
193
194                 // find list of errors for the respective error line
195                 filename := gotPos.Base().Filename()
196                 filemap := errmap[filename]
197                 line := gotPos.Line()
198                 var errList []syntax.Error
199                 if filemap != nil {
200                         errList = filemap[line]
201                 }
202
203                 // At least one of the errors in errList should match the current error.
204                 indices = indices[:0]
205                 for i, want := range errList {
206                         pattern, substr := strings.CutPrefix(want.Msg, " ERROR ")
207                         if !substr {
208                                 var found bool
209                                 pattern, found = strings.CutPrefix(want.Msg, " ERRORx ")
210                                 if !found {
211                                         panic("unreachable")
212                                 }
213                         }
214                         pattern, err := strconv.Unquote(strings.TrimSpace(pattern))
215                         if err != nil {
216                                 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
217                                 continue
218                         }
219                         if substr {
220                                 if !strings.Contains(gotMsg, pattern) {
221                                         continue
222                                 }
223                         } else {
224                                 rx, err := regexp.Compile(pattern)
225                                 if err != nil {
226                                         t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
227                                         continue
228                                 }
229                                 if !rx.MatchString(gotMsg) {
230                                         continue
231                                 }
232                         }
233                         indices = append(indices, i)
234                 }
235                 if len(indices) == 0 {
236                         t.Errorf("%s: no error expected: %q", gotPos, gotMsg)
237                         continue
238                 }
239                 // len(indices) > 0
240
241                 // If there are multiple matching errors, select the one with the closest column position.
242                 index := -1 // index of matching error
243                 var delta uint
244                 for _, i := range indices {
245                         if d := absDiff(gotPos.Col(), errList[i].Pos.Col()); index < 0 || d < delta {
246                                 index, delta = i, d
247                         }
248                 }
249
250                 // The closest column position must be within expected colDelta.
251                 if delta > colDelta {
252                         t.Errorf("%s: got col = %d; want %d", gotPos, gotPos.Col(), errList[index].Pos.Col())
253                 }
254
255                 // eliminate from errList
256                 if n := len(errList) - 1; n > 0 {
257                         // not the last entry - slide entries down (don't reorder)
258                         copy(errList[index:], errList[index+1:])
259                         filemap[line] = errList[:n]
260                 } else {
261                         // last entry - remove errList from filemap
262                         delete(filemap, line)
263                 }
264
265                 // if filemap is empty, eliminate from errmap
266                 if len(filemap) == 0 {
267                         delete(errmap, filename)
268                 }
269         }
270
271         // there should be no expected errors left
272         if len(errmap) > 0 {
273                 t.Errorf("--- %s: unreported errors:", pkgName)
274                 for filename, filemap := range errmap {
275                         for line, errList := range filemap {
276                                 for _, err := range errList {
277                                         t.Errorf("%s:%d:%d: %s", filename, line, err.Pos.Col(), err.Msg)
278                                 }
279                         }
280                 }
281         }
282 }
283
284 // TestManual is for manual testing of a package - either provided
285 // as a list of filenames belonging to the package, or a directory
286 // name containing the package files - after the test arguments
287 // (and a separating "--"). For instance, to test the package made
288 // of the files foo.go and bar.go, use:
289 //
290 //      go test -run Manual -- foo.go bar.go
291 //
292 // If no source arguments are provided, the file testdata/manual.go
293 // is used instead.
294 // Provide the -verify flag to verify errors against ERROR comments
295 // in the input files rather than having a list of errors reported.
296 // The accepted Go language version can be controlled with the -lang
297 // flag.
298 func TestManual(t *testing.T) {
299         testenv.MustHaveGoBuild(t)
300
301         filenames := flag.Args()
302         if len(filenames) == 0 {
303                 filenames = []string{filepath.FromSlash("testdata/manual.go")}
304         }
305
306         info, err := os.Stat(filenames[0])
307         if err != nil {
308                 t.Fatalf("TestManual: %v", err)
309         }
310
311         DefPredeclaredTestFuncs()
312         if info.IsDir() {
313                 if len(filenames) > 1 {
314                         t.Fatal("TestManual: must have only one directory argument")
315                 }
316                 testDir(t, filenames[0], 0, true)
317         } else {
318                 testFiles(t, filenames, 0, true)
319         }
320 }
321
322 // TODO(gri) go/types has extra TestLongConstants and TestIndexRepresentability tests
323
324 func TestCheck(t *testing.T) {
325         DefPredeclaredTestFuncs()
326         testDirFiles(t, "../../../../internal/types/testdata/check", 50, false) // TODO(gri) narrow column tolerance
327 }
328 func TestSpec(t *testing.T) { testDirFiles(t, "../../../../internal/types/testdata/spec", 0, false) }
329 func TestExamples(t *testing.T) {
330         testDirFiles(t, "../../../../internal/types/testdata/examples", 125, false)
331 } // TODO(gri) narrow column tolerance
332 func TestFixedbugs(t *testing.T) {
333         testDirFiles(t, "../../../../internal/types/testdata/fixedbugs", 100, false)
334 }                            // TODO(gri) narrow column tolerance
335 func TestLocal(t *testing.T) { testDirFiles(t, "testdata/local", 0, false) }
336
337 func testDirFiles(t *testing.T, dir string, colDelta uint, manual bool) {
338         testenv.MustHaveGoBuild(t)
339         dir = filepath.FromSlash(dir)
340
341         fis, err := os.ReadDir(dir)
342         if err != nil {
343                 t.Error(err)
344                 return
345         }
346
347         for _, fi := range fis {
348                 path := filepath.Join(dir, fi.Name())
349
350                 // If fi is a directory, its files make up a single package.
351                 if fi.IsDir() {
352                         testDir(t, path, colDelta, manual)
353                 } else {
354                         t.Run(filepath.Base(path), func(t *testing.T) {
355                                 testFiles(t, []string{path}, colDelta, manual)
356                         })
357                 }
358         }
359 }
360
361 func testDir(t *testing.T, dir string, colDelta uint, manual bool) {
362         fis, err := os.ReadDir(dir)
363         if err != nil {
364                 t.Error(err)
365                 return
366         }
367
368         var filenames []string
369         for _, fi := range fis {
370                 filenames = append(filenames, filepath.Join(dir, fi.Name()))
371         }
372
373         t.Run(filepath.Base(dir), func(t *testing.T) {
374                 testFiles(t, filenames, colDelta, manual)
375         })
376 }