github.com/alash3al/go@v0.0.0-20150827002835-d497eeb00540/src/go/types/check_test.go (about) 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 // TODO(gri) Also collect strict mode errors of the form /* STRICT ... */ 24 // and test against strict mode. 25 26 package types_test 27 28 import ( 29 "flag" 30 "go/ast" 31 "go/importer" 32 "go/parser" 33 "go/scanner" 34 "go/token" 35 "internal/testenv" 36 "io/ioutil" 37 "regexp" 38 "strings" 39 "testing" 40 41 . "go/types" 42 ) 43 44 var ( 45 listErrors = flag.Bool("list", false, "list errors") 46 testFiles = flag.String("files", "", "space-separated list of test files") 47 ) 48 49 // The test filenames do not end in .go so that they are invisible 50 // to gofmt since they contain comments that must not change their 51 // positions relative to surrounding tokens. 52 53 // Each tests entry is list of files belonging to the same package. 54 var tests = [][]string{ 55 {"testdata/errors.src"}, 56 {"testdata/importdecl0a.src", "testdata/importdecl0b.src"}, 57 {"testdata/importdecl1a.src", "testdata/importdecl1b.src"}, 58 {"testdata/cycles.src"}, 59 {"testdata/cycles1.src"}, 60 {"testdata/cycles2.src"}, 61 {"testdata/cycles3.src"}, 62 {"testdata/cycles4.src"}, 63 {"testdata/init0.src"}, 64 {"testdata/init1.src"}, 65 {"testdata/init2.src"}, 66 {"testdata/decls0.src"}, 67 {"testdata/decls1.src"}, 68 {"testdata/decls2a.src", "testdata/decls2b.src"}, 69 {"testdata/decls3.src"}, 70 {"testdata/const0.src"}, 71 {"testdata/const1.src"}, 72 {"testdata/constdecl.src"}, 73 {"testdata/vardecl.src"}, 74 {"testdata/expr0.src"}, 75 {"testdata/expr1.src"}, 76 {"testdata/expr2.src"}, 77 {"testdata/expr3.src"}, 78 {"testdata/methodsets.src"}, 79 {"testdata/shifts.src"}, 80 {"testdata/builtins.src"}, 81 {"testdata/conversions.src"}, 82 {"testdata/stmt0.src"}, 83 {"testdata/stmt1.src"}, 84 {"testdata/gotos.src"}, 85 {"testdata/labels.src"}, 86 {"testdata/issues.src"}, 87 {"testdata/blank.src"}, 88 } 89 90 var fset = token.NewFileSet() 91 92 // Positioned errors are of the form filename:line:column: message . 93 var posMsgRx = regexp.MustCompile(`^(.*:[0-9]+:[0-9]+): *(.*)`) 94 95 // splitError splits an error's error message into a position string 96 // and the actual error message. If there's no position information, 97 // pos is the empty string, and msg is the entire error message. 98 // 99 func splitError(err error) (pos, msg string) { 100 msg = err.Error() 101 if m := posMsgRx.FindStringSubmatch(msg); len(m) == 3 { 102 pos = m[1] 103 msg = m[2] 104 } 105 return 106 } 107 108 func parseFiles(t *testing.T, filenames []string) ([]*ast.File, []error) { 109 var files []*ast.File 110 var errlist []error 111 for _, filename := range filenames { 112 file, err := parser.ParseFile(fset, filename, nil, parser.AllErrors) 113 if file == nil { 114 t.Fatalf("%s: %s", filename, err) 115 } 116 files = append(files, file) 117 if err != nil { 118 if list, _ := err.(scanner.ErrorList); len(list) > 0 { 119 for _, err := range list { 120 errlist = append(errlist, err) 121 } 122 } else { 123 errlist = append(errlist, err) 124 } 125 } 126 } 127 return files, errlist 128 } 129 130 // ERROR comments must start with text `ERROR "rx"` or `ERROR rx` where 131 // rx is a regular expression that matches the expected error message. 132 // Space around "rx" or rx is ignored. Use the form `ERROR HERE "rx"` 133 // for error messages that are located immediately after rather than 134 // at a token's position. 135 // 136 var errRx = regexp.MustCompile(`^ *ERROR *(HERE)? *"?([^"]*)"?`) 137 138 // errMap collects the regular expressions of ERROR comments found 139 // in files and returns them as a map of error positions to error messages. 140 // 141 func errMap(t *testing.T, testname string, files []*ast.File) map[string][]string { 142 // map of position strings to lists of error message patterns 143 errmap := make(map[string][]string) 144 145 for _, file := range files { 146 filename := fset.Position(file.Package).Filename 147 src, err := ioutil.ReadFile(filename) 148 if err != nil { 149 t.Fatalf("%s: could not read %s", testname, filename) 150 } 151 152 var s scanner.Scanner 153 s.Init(fset.AddFile(filename, -1, len(src)), src, nil, scanner.ScanComments) 154 var prev token.Pos // position of last non-comment, non-semicolon token 155 var here token.Pos // position immediately after the token at position prev 156 157 scanFile: 158 for { 159 pos, tok, lit := s.Scan() 160 switch tok { 161 case token.EOF: 162 break scanFile 163 case token.COMMENT: 164 if lit[1] == '*' { 165 lit = lit[:len(lit)-2] // strip trailing */ 166 } 167 if s := errRx.FindStringSubmatch(lit[2:]); len(s) == 3 { 168 pos := prev 169 if s[1] == "HERE" { 170 pos = here 171 } 172 p := fset.Position(pos).String() 173 errmap[p] = append(errmap[p], strings.TrimSpace(s[2])) 174 } 175 case token.SEMICOLON: 176 // ignore automatically inserted semicolon 177 if lit == "\n" { 178 continue scanFile 179 } 180 fallthrough 181 default: 182 prev = pos 183 var l int // token length 184 if tok.IsLiteral() { 185 l = len(lit) 186 } else { 187 l = len(tok.String()) 188 } 189 here = prev + token.Pos(l) 190 } 191 } 192 } 193 194 return errmap 195 } 196 197 func eliminate(t *testing.T, errmap map[string][]string, errlist []error) { 198 for _, err := range errlist { 199 pos, gotMsg := splitError(err) 200 list := errmap[pos] 201 index := -1 // list index of matching message, if any 202 // we expect one of the messages in list to match the error at pos 203 for i, wantRx := range list { 204 rx, err := regexp.Compile(wantRx) 205 if err != nil { 206 t.Errorf("%s: %v", pos, err) 207 continue 208 } 209 if rx.MatchString(gotMsg) { 210 index = i 211 break 212 } 213 } 214 if index >= 0 { 215 // eliminate from list 216 if n := len(list) - 1; n > 0 { 217 // not the last entry - swap in last element and shorten list by 1 218 list[index] = list[n] 219 errmap[pos] = list[:n] 220 } else { 221 // last entry - remove list from map 222 delete(errmap, pos) 223 } 224 } else { 225 t.Errorf("%s: no error expected: %q", pos, gotMsg) 226 } 227 } 228 } 229 230 func checkFiles(t *testing.T, testfiles []string) { 231 // parse files and collect parser errors 232 files, errlist := parseFiles(t, testfiles) 233 234 pkgName := "<no package>" 235 if len(files) > 0 { 236 pkgName = files[0].Name.Name 237 } 238 239 if *listErrors && len(errlist) > 0 { 240 t.Errorf("--- %s:", pkgName) 241 for _, err := range errlist { 242 t.Error(err) 243 } 244 } 245 246 // typecheck and collect typechecker errors 247 var conf Config 248 conf.Importer = importer.Default() 249 conf.Error = func(err error) { 250 if *listErrors { 251 t.Error(err) 252 return 253 } 254 // Ignore secondary error messages starting with "\t"; 255 // they are clarifying messages for a primary error. 256 if !strings.Contains(err.Error(), ": \t") { 257 errlist = append(errlist, err) 258 } 259 } 260 conf.Check(pkgName, fset, files, nil) 261 262 if *listErrors { 263 return 264 } 265 266 // match and eliminate errors; 267 // we are expecting the following errors 268 errmap := errMap(t, pkgName, files) 269 eliminate(t, errmap, errlist) 270 271 // there should be no expected errors left 272 if len(errmap) > 0 { 273 t.Errorf("--- %s: %d source positions with expected (but not reported) errors:", pkgName, len(errmap)) 274 for pos, list := range errmap { 275 for _, rx := range list { 276 t.Errorf("%s: %q", pos, rx) 277 } 278 } 279 } 280 } 281 282 func TestCheck(t *testing.T) { 283 testenv.MustHaveGoBuild(t) 284 285 // Declare builtins for testing. 286 DefPredeclaredTestFuncs() 287 288 // If explicit test files are specified, only check those. 289 if files := *testFiles; files != "" { 290 checkFiles(t, strings.Split(files, " ")) 291 return 292 } 293 294 // Otherwise, run all the tests. 295 for _, files := range tests { 296 checkFiles(t, files) 297 } 298 }