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