]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/check_test.go
[dev.typeparams] cmd/compile: re-enable internal/types2 test
[gostls13.git] / src / cmd / compile / internal / types2 / check_test.go
1 // UNREVIEWED
2 // Copyright 2011 The Go Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
5
6 // This file implements a typechecker test harness. The packages specified
7 // in tests are typechecked. Error messages reported by the typechecker are
8 // compared against the error messages expected in the test files.
9 //
10 // Expected errors are indicated in the test files by putting a comment
11 // of the form /* ERROR "rx" */ immediately following an offending token.
12 // The harness will verify that an error matching the regular expression
13 // rx is reported at that source position. Consecutive comments may be
14 // used to indicate multiple errors for the same token position.
15 //
16 // For instance, the following test file indicates that a "not declared"
17 // error should be reported for the undeclared variable x:
18 //
19 //      package p
20 //      func f() {
21 //              _ = x /* ERROR "not declared" */ + 1
22 //      }
23
24 // TODO(gri) Also collect strict mode errors of the form /* STRICT ... */
25 //           and test against strict mode.
26
27 package types2_test
28
29 import (
30         "cmd/compile/internal/syntax"
31         "flag"
32         "fmt"
33         "internal/testenv"
34         "io/ioutil"
35         "os"
36         "path/filepath"
37         "regexp"
38         "strings"
39         "testing"
40
41         . "cmd/compile/internal/types2"
42 )
43
44 var (
45         haltOnError = flag.Bool("halt", false, "halt on error")
46         listErrors  = flag.Bool("errlist", false, "list errors")
47         testFiles   = flag.String("files", "", "space-separated list of test files")
48 )
49
50 func parseFiles(t *testing.T, filenames []string) ([]*syntax.File, []error) {
51         var files []*syntax.File
52         var errlist []error
53         errh := func(err error) { errlist = append(errlist, err) }
54         for _, filename := range filenames {
55                 file, err := syntax.ParseFile(filename, errh, nil, syntax.AllowGenerics)
56                 if file == nil {
57                         t.Fatalf("%s: %s", filename, err)
58                 }
59                 files = append(files, file)
60         }
61         return files, errlist
62 }
63
64 func unpackError(err error) syntax.Error {
65         switch err := err.(type) {
66         case syntax.Error:
67                 return err
68         case Error:
69                 return syntax.Error{Pos: err.Pos, Msg: err.Msg}
70         default:
71                 return syntax.Error{Msg: err.Error()}
72         }
73 }
74
75 func delta(x, y uint) uint {
76         switch {
77         case x < y:
78                 return y - x
79         case x > y:
80                 return x - y
81         default:
82                 return 0
83         }
84 }
85
86 func checkFiles(t *testing.T, sources []string, colDelta uint, trace bool) {
87         // parse files and collect parser errors
88         files, errlist := parseFiles(t, sources)
89
90         pkgName := "<no package>"
91         if len(files) > 0 {
92                 pkgName = files[0].PkgName.Value
93         }
94
95         if *listErrors && len(errlist) > 0 {
96                 t.Errorf("--- %s:", pkgName)
97                 for _, err := range errlist {
98                         t.Error(err)
99                 }
100         }
101
102         // typecheck and collect typechecker errors
103         var conf Config
104         conf.AcceptMethodTypeParams = true
105         conf.InferFromConstraints = true
106         // special case for importC.src
107         if len(sources) == 1 && strings.HasSuffix(sources[0], "importC.src") {
108                 conf.FakeImportC = true
109         }
110         conf.Trace = trace
111         conf.Importer = defaultImporter()
112         conf.Error = func(err error) {
113                 if *haltOnError {
114                         defer panic(err)
115                 }
116                 if *listErrors {
117                         t.Error(err)
118                         return
119                 }
120                 // Ignore secondary error messages starting with "\t";
121                 // they are clarifying messages for a primary error.
122                 if !strings.Contains(err.Error(), ": \t") {
123                         errlist = append(errlist, err)
124                 }
125         }
126         conf.Check(pkgName, files, nil)
127
128         if *listErrors {
129                 return
130         }
131
132         // collect expected errors
133         errmap := make(map[string]map[uint][]syntax.Error)
134         for _, filename := range sources {
135                 f, err := os.Open(filename)
136                 if err != nil {
137                         t.Error(err)
138                         continue
139                 }
140                 if m := syntax.ErrorMap(f); len(m) > 0 {
141                         errmap[filename] = m
142                 }
143                 f.Close()
144         }
145
146         // match against found errors
147         for _, err := range errlist {
148                 got := unpackError(err)
149
150                 // find list of errors for the respective error line
151                 filename := got.Pos.Base().Filename()
152                 filemap := errmap[filename]
153                 var line uint
154                 var list []syntax.Error
155                 if filemap != nil {
156                         line = got.Pos.Line()
157                         list = filemap[line]
158                 }
159                 // list may be nil
160
161                 // one of errors in list should match the current error
162                 index := -1 // list index of matching message, if any
163                 for i, want := range list {
164                         rx, err := regexp.Compile(want.Msg)
165                         if err != nil {
166                                 t.Errorf("%s:%d:%d: %v", filename, line, want.Pos.Col(), err)
167                                 continue
168                         }
169                         if rx.MatchString(got.Msg) {
170                                 index = i
171                                 break
172                         }
173                 }
174                 if index < 0 {
175                         t.Errorf("%s: no error expected: %q", got.Pos, got.Msg)
176                         continue
177                 }
178
179                 // column position must be within expected colDelta
180                 want := list[index]
181                 if delta(got.Pos.Col(), want.Pos.Col()) > colDelta {
182                         t.Errorf("%s: got col = %d; want %d", got.Pos, got.Pos.Col(), want.Pos.Col())
183                 }
184
185                 // eliminate from list
186                 if n := len(list) - 1; n > 0 {
187                         // not the last entry - swap in last element and shorten list by 1
188                         list[index] = list[n]
189                         filemap[line] = list[:n]
190                 } else {
191                         // last entry - remove list from filemap
192                         delete(filemap, line)
193                 }
194
195                 // if filemap is empty, eliminate from errmap
196                 if len(filemap) == 0 {
197                         delete(errmap, filename)
198                 }
199         }
200
201         // there should be no expected errors left
202         if len(errmap) > 0 {
203                 t.Errorf("--- %s: unreported errors:", pkgName)
204                 for filename, filemap := range errmap {
205                         for line, list := range filemap {
206                                 for _, err := range list {
207                                         t.Errorf("%s:%d:%d: %s", filename, line, err.Pos.Col(), err.Msg)
208                                 }
209                         }
210                 }
211         }
212 }
213
214 // TestCheck is for manual testing of selected input files, provided with -files.
215 func TestCheck(t *testing.T) {
216         if *testFiles == "" {
217                 return
218         }
219         testenv.MustHaveGoBuild(t)
220         DefPredeclaredTestFuncs()
221         checkFiles(t, strings.Split(*testFiles, " "), 0, testing.Verbose())
222 }
223
224 func TestTestdata(t *testing.T)  { DefPredeclaredTestFuncs(); testDir(t, 75, "testdata") } // TODO(gri) narrow column tolerance
225 func TestExamples(t *testing.T)  { testDir(t, 0, "examples") }
226 func TestFixedbugs(t *testing.T) { testDir(t, 0, "fixedbugs") }
227
228 func testDir(t *testing.T, colDelta uint, dir string) {
229         testenv.MustHaveGoBuild(t)
230
231         fis, err := ioutil.ReadDir(dir)
232         if err != nil {
233                 t.Error(err)
234                 return
235         }
236
237         for count, fi := range fis {
238                 path := filepath.Join(dir, fi.Name())
239
240                 // if fi is a directory, its files make up a single package
241                 if fi.IsDir() {
242                         if testing.Verbose() {
243                                 fmt.Printf("%3d %s\n", count, path)
244                         }
245                         fis, err := ioutil.ReadDir(path)
246                         if err != nil {
247                                 t.Error(err)
248                                 continue
249                         }
250                         files := make([]string, len(fis))
251                         for i, fi := range fis {
252                                 // if fi is a directory, checkFiles below will complain
253                                 files[i] = filepath.Join(path, fi.Name())
254                                 if testing.Verbose() {
255                                         fmt.Printf("\t%s\n", files[i])
256                                 }
257                         }
258                         checkFiles(t, files, colDelta, false)
259                         continue
260                 }
261
262                 // otherwise, fi is a stand-alone file
263                 if testing.Verbose() {
264                         fmt.Printf("%3d %s\n", count, path)
265                 }
266                 checkFiles(t, []string{path}, colDelta, false)
267         }
268 }