github.com/euank/go@v0.0.0-20160829210321-495514729181/src/go/types/decl.go (about) 1 // Copyright 2014 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 "go/ast" 9 "go/constant" 10 "go/token" 11 ) 12 13 func (check *Checker) reportAltDecl(obj Object) { 14 if pos := obj.Pos(); pos.IsValid() { 15 // We use "other" rather than "previous" here because 16 // the first declaration seen may not be textually 17 // earlier in the source. 18 check.errorf(pos, "\tother declaration of %s", obj.Name()) // secondary error, \t indented 19 } 20 } 21 22 func (check *Checker) declare(scope *Scope, id *ast.Ident, obj Object, pos token.Pos) { 23 // spec: "The blank identifier, represented by the underscore 24 // character _, may be used in a declaration like any other 25 // identifier but the declaration does not introduce a new 26 // binding." 27 if obj.Name() != "_" { 28 if alt := scope.Insert(obj); alt != nil { 29 check.errorf(obj.Pos(), "%s redeclared in this block", obj.Name()) 30 check.reportAltDecl(alt) 31 return 32 } 33 obj.setScopePos(pos) 34 } 35 if id != nil { 36 check.recordDef(id, obj) 37 } 38 } 39 40 // objDecl type-checks the declaration of obj in its respective (file) context. 41 // See check.typ for the details on def and path. 42 func (check *Checker) objDecl(obj Object, def *Named, path []*TypeName) { 43 if obj.Type() != nil { 44 return // already checked - nothing to do 45 } 46 47 if trace { 48 check.trace(obj.Pos(), "-- declaring %s", obj.Name()) 49 check.indent++ 50 defer func() { 51 check.indent-- 52 check.trace(obj.Pos(), "=> %s", obj) 53 }() 54 } 55 56 d := check.objMap[obj] 57 if d == nil { 58 check.dump("%s: %s should have been declared", obj.Pos(), obj.Name()) 59 unreachable() 60 } 61 62 // save/restore current context and setup object context 63 defer func(ctxt context) { 64 check.context = ctxt 65 }(check.context) 66 check.context = context{ 67 scope: d.file, 68 } 69 70 // Const and var declarations must not have initialization 71 // cycles. We track them by remembering the current declaration 72 // in check.decl. Initialization expressions depending on other 73 // consts, vars, or functions, add dependencies to the current 74 // check.decl. 75 switch obj := obj.(type) { 76 case *Const: 77 check.decl = d // new package-level const decl 78 check.constDecl(obj, d.typ, d.init) 79 case *Var: 80 check.decl = d // new package-level var decl 81 check.varDecl(obj, d.lhs, d.typ, d.init) 82 case *TypeName: 83 // invalid recursive types are detected via path 84 check.typeDecl(obj, d.typ, def, path) 85 case *Func: 86 // functions may be recursive - no need to track dependencies 87 check.funcDecl(obj, d) 88 default: 89 unreachable() 90 } 91 } 92 93 func (check *Checker) constDecl(obj *Const, typ, init ast.Expr) { 94 assert(obj.typ == nil) 95 96 if obj.visited { 97 obj.typ = Typ[Invalid] 98 return 99 } 100 obj.visited = true 101 102 // use the correct value of iota 103 assert(check.iota == nil) 104 check.iota = obj.val 105 defer func() { check.iota = nil }() 106 107 // provide valid constant value under all circumstances 108 obj.val = constant.MakeUnknown() 109 110 // determine type, if any 111 if typ != nil { 112 t := check.typ(typ) 113 if !isConstType(t) { 114 check.errorf(typ.Pos(), "invalid constant type %s", t) 115 obj.typ = Typ[Invalid] 116 return 117 } 118 obj.typ = t 119 } 120 121 // check initialization 122 var x operand 123 if init != nil { 124 check.expr(&x, init) 125 } 126 check.initConst(obj, &x) 127 } 128 129 func (check *Checker) varDecl(obj *Var, lhs []*Var, typ, init ast.Expr) { 130 assert(obj.typ == nil) 131 132 if obj.visited { 133 obj.typ = Typ[Invalid] 134 return 135 } 136 obj.visited = true 137 138 // var declarations cannot use iota 139 assert(check.iota == nil) 140 141 // determine type, if any 142 if typ != nil { 143 obj.typ = check.typ(typ) 144 // We cannot spread the type to all lhs variables if there 145 // are more than one since that would mark them as checked 146 // (see Checker.objDecl) and the assignment of init exprs, 147 // if any, would not be checked. 148 // 149 // TODO(gri) If we have no init expr, we should distribute 150 // a given type otherwise we need to re-evalate the type 151 // expr for each lhs variable, leading to duplicate work. 152 } 153 154 // check initialization 155 if init == nil { 156 if typ == nil { 157 // error reported before by arityMatch 158 obj.typ = Typ[Invalid] 159 } 160 return 161 } 162 163 if lhs == nil || len(lhs) == 1 { 164 assert(lhs == nil || lhs[0] == obj) 165 var x operand 166 check.expr(&x, init) 167 check.initVar(obj, &x, "variable declaration") 168 return 169 } 170 171 if debug { 172 // obj must be one of lhs 173 found := false 174 for _, lhs := range lhs { 175 if obj == lhs { 176 found = true 177 break 178 } 179 } 180 if !found { 181 panic("inconsistent lhs") 182 } 183 } 184 185 // We have multiple variables on the lhs and one init expr. 186 // Make sure all variables have been given the same type if 187 // one was specified, otherwise they assume the type of the 188 // init expression values (was issue #15755). 189 if typ != nil { 190 for _, lhs := range lhs { 191 lhs.typ = obj.typ 192 } 193 } 194 195 check.initVars(lhs, []ast.Expr{init}, token.NoPos) 196 } 197 198 // underlying returns the underlying type of typ; possibly by following 199 // forward chains of named types. Such chains only exist while named types 200 // are incomplete. 201 func underlying(typ Type) Type { 202 for { 203 n, _ := typ.(*Named) 204 if n == nil { 205 break 206 } 207 typ = n.underlying 208 } 209 return typ 210 } 211 212 func (n *Named) setUnderlying(typ Type) { 213 if n != nil { 214 n.underlying = typ 215 } 216 } 217 218 func (check *Checker) typeDecl(obj *TypeName, typ ast.Expr, def *Named, path []*TypeName) { 219 assert(obj.typ == nil) 220 221 // type declarations cannot use iota 222 assert(check.iota == nil) 223 224 named := &Named{obj: obj} 225 def.setUnderlying(named) 226 obj.typ = named // make sure recursive type declarations terminate 227 228 // determine underlying type of named 229 check.typExpr(typ, named, append(path, obj)) 230 231 // The underlying type of named may be itself a named type that is 232 // incomplete: 233 // 234 // type ( 235 // A B 236 // B *C 237 // C A 238 // ) 239 // 240 // The type of C is the (named) type of A which is incomplete, 241 // and which has as its underlying type the named type B. 242 // Determine the (final, unnamed) underlying type by resolving 243 // any forward chain (they always end in an unnamed type). 244 named.underlying = underlying(named.underlying) 245 246 // check and add associated methods 247 // TODO(gri) It's easy to create pathological cases where the 248 // current approach is incorrect: In general we need to know 249 // and add all methods _before_ type-checking the type. 250 // See https://play.golang.org/p/WMpE0q2wK8 251 check.addMethodDecls(obj) 252 } 253 254 func (check *Checker) addMethodDecls(obj *TypeName) { 255 // get associated methods 256 methods := check.methods[obj.name] 257 if len(methods) == 0 { 258 return // no methods 259 } 260 delete(check.methods, obj.name) 261 262 // use an objset to check for name conflicts 263 var mset objset 264 265 // spec: "If the base type is a struct type, the non-blank method 266 // and field names must be distinct." 267 base := obj.typ.(*Named) 268 if t, _ := base.underlying.(*Struct); t != nil { 269 for _, fld := range t.fields { 270 if fld.name != "_" { 271 assert(mset.insert(fld) == nil) 272 } 273 } 274 } 275 276 // Checker.Files may be called multiple times; additional package files 277 // may add methods to already type-checked types. Add pre-existing methods 278 // so that we can detect redeclarations. 279 for _, m := range base.methods { 280 assert(m.name != "_") 281 assert(mset.insert(m) == nil) 282 } 283 284 // type-check methods 285 for _, m := range methods { 286 // spec: "For a base type, the non-blank names of methods bound 287 // to it must be unique." 288 if m.name != "_" { 289 if alt := mset.insert(m); alt != nil { 290 switch alt.(type) { 291 case *Var: 292 check.errorf(m.pos, "field and method with the same name %s", m.name) 293 case *Func: 294 check.errorf(m.pos, "method %s already declared for %s", m.name, base) 295 default: 296 unreachable() 297 } 298 check.reportAltDecl(alt) 299 continue 300 } 301 } 302 check.objDecl(m, nil, nil) 303 // methods with blank _ names cannot be found - don't keep them 304 if m.name != "_" { 305 base.methods = append(base.methods, m) 306 } 307 } 308 } 309 310 func (check *Checker) funcDecl(obj *Func, decl *declInfo) { 311 assert(obj.typ == nil) 312 313 // func declarations cannot use iota 314 assert(check.iota == nil) 315 316 sig := new(Signature) 317 obj.typ = sig // guard against cycles 318 fdecl := decl.fdecl 319 check.funcType(sig, fdecl.Recv, fdecl.Type) 320 if sig.recv == nil && obj.name == "init" && (sig.params.Len() > 0 || sig.results.Len() > 0) { 321 check.errorf(fdecl.Pos(), "func init must have no arguments and no return values") 322 // ok to continue 323 } 324 325 // function body must be type-checked after global declarations 326 // (functions implemented elsewhere have no body) 327 if !check.conf.IgnoreFuncBodies && fdecl.Body != nil { 328 check.later(obj.name, decl, sig, fdecl.Body) 329 } 330 } 331 332 func (check *Checker) declStmt(decl ast.Decl) { 333 pkg := check.pkg 334 335 switch d := decl.(type) { 336 case *ast.BadDecl: 337 // ignore 338 339 case *ast.GenDecl: 340 var last *ast.ValueSpec // last ValueSpec with type or init exprs seen 341 for iota, spec := range d.Specs { 342 switch s := spec.(type) { 343 case *ast.ValueSpec: 344 switch d.Tok { 345 case token.CONST: 346 // determine which init exprs to use 347 switch { 348 case s.Type != nil || len(s.Values) > 0: 349 last = s 350 case last == nil: 351 last = new(ast.ValueSpec) // make sure last exists 352 } 353 354 // declare all constants 355 lhs := make([]*Const, len(s.Names)) 356 for i, name := range s.Names { 357 obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(iota))) 358 lhs[i] = obj 359 360 var init ast.Expr 361 if i < len(last.Values) { 362 init = last.Values[i] 363 } 364 365 check.constDecl(obj, last.Type, init) 366 } 367 368 check.arityMatch(s, last) 369 370 // spec: "The scope of a constant or variable identifier declared 371 // inside a function begins at the end of the ConstSpec or VarSpec 372 // (ShortVarDecl for short variable declarations) and ends at the 373 // end of the innermost containing block." 374 scopePos := s.End() 375 for i, name := range s.Names { 376 check.declare(check.scope, name, lhs[i], scopePos) 377 } 378 379 case token.VAR: 380 lhs0 := make([]*Var, len(s.Names)) 381 for i, name := range s.Names { 382 lhs0[i] = NewVar(name.Pos(), pkg, name.Name, nil) 383 } 384 385 // initialize all variables 386 for i, obj := range lhs0 { 387 var lhs []*Var 388 var init ast.Expr 389 switch len(s.Values) { 390 case len(s.Names): 391 // lhs and rhs match 392 init = s.Values[i] 393 case 1: 394 // rhs is expected to be a multi-valued expression 395 lhs = lhs0 396 init = s.Values[0] 397 default: 398 if i < len(s.Values) { 399 init = s.Values[i] 400 } 401 } 402 check.varDecl(obj, lhs, s.Type, init) 403 if len(s.Values) == 1 { 404 // If we have a single lhs variable we are done either way. 405 // If we have a single rhs expression, it must be a multi- 406 // valued expression, in which case handling the first lhs 407 // variable will cause all lhs variables to have a type 408 // assigned, and we are done as well. 409 if debug { 410 for _, obj := range lhs0 { 411 assert(obj.typ != nil) 412 } 413 } 414 break 415 } 416 } 417 418 check.arityMatch(s, nil) 419 420 // declare all variables 421 // (only at this point are the variable scopes (parents) set) 422 scopePos := s.End() // see constant declarations 423 for i, name := range s.Names { 424 // see constant declarations 425 check.declare(check.scope, name, lhs0[i], scopePos) 426 } 427 428 default: 429 check.invalidAST(s.Pos(), "invalid token %s", d.Tok) 430 } 431 432 case *ast.TypeSpec: 433 obj := NewTypeName(s.Name.Pos(), pkg, s.Name.Name, nil) 434 // spec: "The scope of a type identifier declared inside a function 435 // begins at the identifier in the TypeSpec and ends at the end of 436 // the innermost containing block." 437 scopePos := s.Name.Pos() 438 check.declare(check.scope, s.Name, obj, scopePos) 439 check.typeDecl(obj, s.Type, nil, nil) 440 441 default: 442 check.invalidAST(s.Pos(), "const, type, or var declaration expected") 443 } 444 } 445 446 default: 447 check.invalidAST(d.Pos(), "unknown ast.Decl node %T", d) 448 } 449 }