github.com/zxy12/golang151_with_comment@v0.0.0-20190507085033-721809559d3c/go/types/resolver.go (about) 1 // Copyright 2013 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 package types 6 7 import ( 8 "fmt" 9 "go/ast" 10 "go/constant" 11 "go/token" 12 pathLib "path" 13 "strconv" 14 "strings" 15 "unicode" 16 ) 17 18 // A declInfo describes a package-level const, type, var, or func declaration. 19 type declInfo struct { 20 file *Scope // scope of file containing this declaration 21 lhs []*Var // lhs of n:1 variable declarations, or nil 22 typ ast.Expr // type, or nil 23 init ast.Expr // init expression, or nil 24 fdecl *ast.FuncDecl // func declaration, or nil 25 26 deps map[Object]bool // type and init dependencies; lazily allocated 27 mark int // for dependency analysis 28 } 29 30 // hasInitializer reports whether the declared object has an initialization 31 // expression or function body. 32 func (d *declInfo) hasInitializer() bool { 33 return d.init != nil || d.fdecl != nil && d.fdecl.Body != nil 34 } 35 36 // addDep adds obj as a dependency to d. 37 func (d *declInfo) addDep(obj Object) { 38 m := d.deps 39 if m == nil { 40 m = make(map[Object]bool) 41 d.deps = m 42 } 43 m[obj] = true 44 } 45 46 // arityMatch checks that the lhs and rhs of a const or var decl 47 // have the appropriate number of names and init exprs. For const 48 // decls, init is the value spec providing the init exprs; for 49 // var decls, init is nil (the init exprs are in s in this case). 50 func (check *Checker) arityMatch(s, init *ast.ValueSpec) { 51 l := len(s.Names) 52 r := len(s.Values) 53 if init != nil { 54 r = len(init.Values) 55 } 56 57 switch { 58 case init == nil && r == 0: 59 // var decl w/o init expr 60 if s.Type == nil { 61 check.errorf(s.Pos(), "missing type or init expr") 62 } 63 case l < r: 64 if l < len(s.Values) { 65 // init exprs from s 66 n := s.Values[l] 67 check.errorf(n.Pos(), "extra init expr %s", n) 68 // TODO(gri) avoid declared but not used error here 69 } else { 70 // init exprs "inherited" 71 check.errorf(s.Pos(), "extra init expr at %s", init.Pos()) 72 // TODO(gri) avoid declared but not used error here 73 } 74 case l > r && (init != nil || r != 1): 75 n := s.Names[r] 76 check.errorf(n.Pos(), "missing init expr for %s", n) 77 } 78 } 79 80 func validatedImportPath(path string) (string, error) { 81 s, err := strconv.Unquote(path) 82 if err != nil { 83 return "", err 84 } 85 if s == "" { 86 return "", fmt.Errorf("empty string") 87 } 88 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD" 89 for _, r := range s { 90 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) { 91 return s, fmt.Errorf("invalid character %#U", r) 92 } 93 } 94 return s, nil 95 } 96 97 // declarePkgObj declares obj in the package scope, records its ident -> obj mapping, 98 // and updates check.objMap. The object must not be a function or method. 99 func (check *Checker) declarePkgObj(ident *ast.Ident, obj Object, d *declInfo) { 100 assert(ident.Name == obj.Name()) 101 102 // spec: "A package-scope or file-scope identifier with name init 103 // may only be declared to be a function with this (func()) signature." 104 if ident.Name == "init" { 105 check.errorf(ident.Pos(), "cannot declare init - must be func") 106 return 107 } 108 109 check.declare(check.pkg.scope, ident, obj, token.NoPos) 110 check.objMap[obj] = d 111 obj.setOrder(uint32(len(check.objMap))) 112 } 113 114 // filename returns a filename suitable for debugging output. 115 func (check *Checker) filename(fileNo int) string { 116 file := check.files[fileNo] 117 if pos := file.Pos(); pos.IsValid() { 118 return check.fset.File(pos).Name() 119 } 120 return fmt.Sprintf("file[%d]", fileNo) 121 } 122 123 // collectObjects collects all file and package objects and inserts them 124 // into their respective scopes. It also performs imports and associates 125 // methods with receiver base type names. 126 func (check *Checker) collectObjects() { 127 pkg := check.pkg 128 129 // pkgImports is the set of packages already imported by any package file seen 130 // so far. Used to avoid duplicate entries in pkg.imports. Allocate and populate 131 // it (pkg.imports may not be empty if we are checking test files incrementally). 132 var pkgImports = make(map[*Package]bool) 133 for _, imp := range pkg.imports { 134 pkgImports[imp] = true 135 } 136 137 for fileNo, file := range check.files { 138 // The package identifier denotes the current package, 139 // but there is no corresponding package object. 140 check.recordDef(file.Name, nil) 141 142 // Use the actual source file extent rather than *ast.File extent since the 143 // latter doesn't include comments which appear at the start or end of the file. 144 // Be conservative and use the *ast.File extent if we don't have a *token.File. 145 pos, end := file.Pos(), file.End() 146 if f := check.fset.File(file.Pos()); f != nil { 147 pos, end = token.Pos(f.Base()), token.Pos(f.Base()+f.Size()) 148 } 149 fileScope := NewScope(check.pkg.scope, pos, end, check.filename(fileNo)) 150 check.recordScope(file, fileScope) 151 152 for _, decl := range file.Decls { 153 switch d := decl.(type) { 154 case *ast.BadDecl: 155 // ignore 156 157 case *ast.GenDecl: 158 var last *ast.ValueSpec // last ValueSpec with type or init exprs seen 159 for iota, spec := range d.Specs { 160 switch s := spec.(type) { 161 case *ast.ImportSpec: 162 // import package 163 var imp *Package 164 path, err := validatedImportPath(s.Path.Value) 165 if err != nil { 166 check.errorf(s.Path.Pos(), "invalid import path (%s)", err) 167 continue 168 } 169 if path == "C" && check.conf.FakeImportC { 170 // TODO(gri) shouldn't create a new one each time 171 imp = NewPackage("C", "C") 172 imp.fake = true 173 } else if path == "unsafe" { 174 // package "unsafe" is known to the language 175 imp = Unsafe 176 } else { 177 if importer := check.conf.Importer; importer != nil { 178 imp, err = importer.Import(path) 179 if imp == nil && err == nil { 180 err = fmt.Errorf("Config.Importer.Import(%s) returned nil but no error", path) 181 } 182 } else { 183 err = fmt.Errorf("Config.Importer not installed") 184 } 185 if err != nil { 186 check.errorf(s.Path.Pos(), "could not import %s (%s)", path, err) 187 continue 188 } 189 } 190 191 // add package to list of explicit imports 192 // (this functionality is provided as a convenience 193 // for clients; it is not needed for type-checking) 194 if !pkgImports[imp] { 195 pkgImports[imp] = true 196 if imp != Unsafe { 197 pkg.imports = append(pkg.imports, imp) 198 } 199 } 200 201 // local name overrides imported package name 202 name := imp.name 203 if s.Name != nil { 204 name = s.Name.Name 205 if name == "init" { 206 check.errorf(s.Name.Pos(), "cannot declare init - must be func") 207 continue 208 } 209 } 210 211 obj := NewPkgName(s.Pos(), pkg, name, imp) 212 if s.Name != nil { 213 // in a dot-import, the dot represents the package 214 check.recordDef(s.Name, obj) 215 } else { 216 check.recordImplicit(s, obj) 217 } 218 219 // add import to file scope 220 if name == "." { 221 // merge imported scope with file scope 222 for _, obj := range imp.scope.elems { 223 // A package scope may contain non-exported objects, 224 // do not import them! 225 if obj.Exported() { 226 // TODO(gri) When we import a package, we create 227 // a new local package object. We should do the 228 // same for each dot-imported object. That way 229 // they can have correct position information. 230 // (We must not modify their existing position 231 // information because the same package - found 232 // via Config.Packages - may be dot-imported in 233 // another package!) 234 check.declare(fileScope, nil, obj, token.NoPos) 235 check.recordImplicit(s, obj) 236 } 237 } 238 // add position to set of dot-import positions for this file 239 // (this is only needed for "imported but not used" errors) 240 check.addUnusedDotImport(fileScope, imp, s.Pos()) 241 } else { 242 // declare imported package object in file scope 243 check.declare(fileScope, nil, obj, token.NoPos) 244 } 245 246 case *ast.ValueSpec: 247 switch d.Tok { 248 case token.CONST: 249 // determine which initialization expressions to use 250 switch { 251 case s.Type != nil || len(s.Values) > 0: 252 last = s 253 case last == nil: 254 last = new(ast.ValueSpec) // make sure last exists 255 } 256 257 // declare all constants 258 for i, name := range s.Names { 259 obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(iota))) 260 261 var init ast.Expr 262 if i < len(last.Values) { 263 init = last.Values[i] 264 } 265 266 d := &declInfo{file: fileScope, typ: last.Type, init: init} 267 check.declarePkgObj(name, obj, d) 268 } 269 270 check.arityMatch(s, last) 271 272 case token.VAR: 273 lhs := make([]*Var, len(s.Names)) 274 // If there's exactly one rhs initializer, use 275 // the same declInfo d1 for all lhs variables 276 // so that each lhs variable depends on the same 277 // rhs initializer (n:1 var declaration). 278 var d1 *declInfo 279 if len(s.Values) == 1 { 280 // The lhs elements are only set up after the for loop below, 281 // but that's ok because declareVar only collects the declInfo 282 // for a later phase. 283 d1 = &declInfo{file: fileScope, lhs: lhs, typ: s.Type, init: s.Values[0]} 284 } 285 286 // declare all variables 287 for i, name := range s.Names { 288 obj := NewVar(name.Pos(), pkg, name.Name, nil) 289 lhs[i] = obj 290 291 d := d1 292 if d == nil { 293 // individual assignments 294 var init ast.Expr 295 if i < len(s.Values) { 296 init = s.Values[i] 297 } 298 d = &declInfo{file: fileScope, typ: s.Type, init: init} 299 } 300 301 check.declarePkgObj(name, obj, d) 302 } 303 304 check.arityMatch(s, nil) 305 306 default: 307 check.invalidAST(s.Pos(), "invalid token %s", d.Tok) 308 } 309 310 case *ast.TypeSpec: 311 obj := NewTypeName(s.Name.Pos(), pkg, s.Name.Name, nil) 312 check.declarePkgObj(s.Name, obj, &declInfo{file: fileScope, typ: s.Type}) 313 314 default: 315 check.invalidAST(s.Pos(), "unknown ast.Spec node %T", s) 316 } 317 } 318 319 case *ast.FuncDecl: 320 name := d.Name.Name 321 obj := NewFunc(d.Name.Pos(), pkg, name, nil) 322 if d.Recv == nil { 323 // regular function 324 if name == "init" { 325 // don't declare init functions in the package scope - they are invisible 326 obj.parent = pkg.scope 327 check.recordDef(d.Name, obj) 328 // init functions must have a body 329 if d.Body == nil { 330 check.softErrorf(obj.pos, "missing function body") 331 } 332 } else { 333 check.declare(pkg.scope, d.Name, obj, token.NoPos) 334 } 335 } else { 336 // method 337 check.recordDef(d.Name, obj) 338 // Associate method with receiver base type name, if possible. 339 // Ignore methods that have an invalid receiver, or a blank _ 340 // receiver name. They will be type-checked later, with regular 341 // functions. 342 if list := d.Recv.List; len(list) > 0 { 343 typ := list[0].Type 344 if ptr, _ := typ.(*ast.StarExpr); ptr != nil { 345 typ = ptr.X 346 } 347 if base, _ := typ.(*ast.Ident); base != nil && base.Name != "_" { 348 check.assocMethod(base.Name, obj) 349 } 350 } 351 } 352 info := &declInfo{file: fileScope, fdecl: d} 353 check.objMap[obj] = info 354 obj.setOrder(uint32(len(check.objMap))) 355 356 default: 357 check.invalidAST(d.Pos(), "unknown ast.Decl node %T", d) 358 } 359 } 360 } 361 362 // verify that objects in package and file scopes have different names 363 for _, scope := range check.pkg.scope.children /* file scopes */ { 364 for _, obj := range scope.elems { 365 if alt := pkg.scope.Lookup(obj.Name()); alt != nil { 366 if pkg, ok := obj.(*PkgName); ok { 367 check.errorf(alt.Pos(), "%s already declared through import of %s", alt.Name(), pkg.Imported()) 368 check.reportAltDecl(pkg) 369 } else { 370 check.errorf(alt.Pos(), "%s already declared through dot-import of %s", alt.Name(), obj.Pkg()) 371 // TODO(gri) dot-imported objects don't have a position; reportAltDecl won't print anything 372 check.reportAltDecl(obj) 373 } 374 } 375 } 376 } 377 } 378 379 // packageObjects typechecks all package objects in objList, but not function bodies. 380 func (check *Checker) packageObjects(objList []Object) { 381 // add new methods to already type-checked types (from a prior Checker.Files call) 382 for _, obj := range objList { 383 if obj, _ := obj.(*TypeName); obj != nil && obj.typ != nil { 384 check.addMethodDecls(obj) 385 } 386 } 387 388 // pre-allocate space for type declaration paths so that the underlying array is reused 389 typePath := make([]*TypeName, 0, 8) 390 391 for _, obj := range objList { 392 check.objDecl(obj, nil, typePath) 393 } 394 395 // At this point we may have a non-empty check.methods map; this means that not all 396 // entries were deleted at the end of typeDecl because the respective receiver base 397 // types were not found. In that case, an error was reported when declaring those 398 // methods. We can now safely discard this map. 399 check.methods = nil 400 } 401 402 // functionBodies typechecks all function bodies. 403 func (check *Checker) functionBodies() { 404 for _, f := range check.funcs { 405 check.funcBody(f.decl, f.name, f.sig, f.body) 406 } 407 } 408 409 // unusedImports checks for unused imports. 410 func (check *Checker) unusedImports() { 411 // if function bodies are not checked, packages' uses are likely missing - don't check 412 if check.conf.IgnoreFuncBodies { 413 return 414 } 415 416 // spec: "It is illegal (...) to directly import a package without referring to 417 // any of its exported identifiers. To import a package solely for its side-effects 418 // (initialization), use the blank identifier as explicit package name." 419 420 // check use of regular imported packages 421 for _, scope := range check.pkg.scope.children /* file scopes */ { 422 for _, obj := range scope.elems { 423 if obj, ok := obj.(*PkgName); ok { 424 // Unused "blank imports" are automatically ignored 425 // since _ identifiers are not entered into scopes. 426 if !obj.used { 427 path := obj.imported.path 428 base := pathLib.Base(path) 429 if obj.name == base { 430 check.softErrorf(obj.pos, "%q imported but not used", path) 431 } else { 432 check.softErrorf(obj.pos, "%q imported but not used as %s", path, obj.name) 433 } 434 } 435 } 436 } 437 } 438 439 // check use of dot-imported packages 440 for _, unusedDotImports := range check.unusedDotImports { 441 for pkg, pos := range unusedDotImports { 442 check.softErrorf(pos, "%q imported but not used", pkg.path) 443 } 444 } 445 }