github.com/miolini/go@v0.0.0-20160405192216-fca68c8cb408/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  	}
   145  
   146  	// check initialization
   147  	if init == nil {
   148  		if typ == nil {
   149  			// error reported before by arityMatch
   150  			obj.typ = Typ[Invalid]
   151  		}
   152  		return
   153  	}
   154  
   155  	if lhs == nil || len(lhs) == 1 {
   156  		assert(lhs == nil || lhs[0] == obj)
   157  		var x operand
   158  		check.expr(&x, init)
   159  		check.initVar(obj, &x, "variable declaration")
   160  		return
   161  	}
   162  
   163  	if debug {
   164  		// obj must be one of lhs
   165  		found := false
   166  		for _, lhs := range lhs {
   167  			if obj == lhs {
   168  				found = true
   169  				break
   170  			}
   171  		}
   172  		if !found {
   173  			panic("inconsistent lhs")
   174  		}
   175  	}
   176  	check.initVars(lhs, []ast.Expr{init}, token.NoPos)
   177  }
   178  
   179  // underlying returns the underlying type of typ; possibly by following
   180  // forward chains of named types. Such chains only exist while named types
   181  // are incomplete.
   182  func underlying(typ Type) Type {
   183  	for {
   184  		n, _ := typ.(*Named)
   185  		if n == nil {
   186  			break
   187  		}
   188  		typ = n.underlying
   189  	}
   190  	return typ
   191  }
   192  
   193  func (n *Named) setUnderlying(typ Type) {
   194  	if n != nil {
   195  		n.underlying = typ
   196  	}
   197  }
   198  
   199  func (check *Checker) typeDecl(obj *TypeName, typ ast.Expr, def *Named, path []*TypeName) {
   200  	assert(obj.typ == nil)
   201  
   202  	// type declarations cannot use iota
   203  	assert(check.iota == nil)
   204  
   205  	named := &Named{obj: obj}
   206  	def.setUnderlying(named)
   207  	obj.typ = named // make sure recursive type declarations terminate
   208  
   209  	// determine underlying type of named
   210  	check.typExpr(typ, named, append(path, obj))
   211  
   212  	// The underlying type of named may be itself a named type that is
   213  	// incomplete:
   214  	//
   215  	//	type (
   216  	//		A B
   217  	//		B *C
   218  	//		C A
   219  	//	)
   220  	//
   221  	// The type of C is the (named) type of A which is incomplete,
   222  	// and which has as its underlying type the named type B.
   223  	// Determine the (final, unnamed) underlying type by resolving
   224  	// any forward chain (they always end in an unnamed type).
   225  	named.underlying = underlying(named.underlying)
   226  
   227  	// check and add associated methods
   228  	// TODO(gri) It's easy to create pathological cases where the
   229  	// current approach is incorrect: In general we need to know
   230  	// and add all methods _before_ type-checking the type.
   231  	// See https://play.golang.org/p/WMpE0q2wK8
   232  	check.addMethodDecls(obj)
   233  }
   234  
   235  func (check *Checker) addMethodDecls(obj *TypeName) {
   236  	// get associated methods
   237  	methods := check.methods[obj.name]
   238  	if len(methods) == 0 {
   239  		return // no methods
   240  	}
   241  	delete(check.methods, obj.name)
   242  
   243  	// use an objset to check for name conflicts
   244  	var mset objset
   245  
   246  	// spec: "If the base type is a struct type, the non-blank method
   247  	// and field names must be distinct."
   248  	base := obj.typ.(*Named)
   249  	if t, _ := base.underlying.(*Struct); t != nil {
   250  		for _, fld := range t.fields {
   251  			if fld.name != "_" {
   252  				assert(mset.insert(fld) == nil)
   253  			}
   254  		}
   255  	}
   256  
   257  	// Checker.Files may be called multiple times; additional package files
   258  	// may add methods to already type-checked types. Add pre-existing methods
   259  	// so that we can detect redeclarations.
   260  	for _, m := range base.methods {
   261  		assert(m.name != "_")
   262  		assert(mset.insert(m) == nil)
   263  	}
   264  
   265  	// type-check methods
   266  	for _, m := range methods {
   267  		// spec: "For a base type, the non-blank names of methods bound
   268  		// to it must be unique."
   269  		if m.name != "_" {
   270  			if alt := mset.insert(m); alt != nil {
   271  				switch alt.(type) {
   272  				case *Var:
   273  					check.errorf(m.pos, "field and method with the same name %s", m.name)
   274  				case *Func:
   275  					check.errorf(m.pos, "method %s already declared for %s", m.name, base)
   276  				default:
   277  					unreachable()
   278  				}
   279  				check.reportAltDecl(alt)
   280  				continue
   281  			}
   282  		}
   283  		check.objDecl(m, nil, nil)
   284  		// methods with blank _ names cannot be found - don't keep them
   285  		if m.name != "_" {
   286  			base.methods = append(base.methods, m)
   287  		}
   288  	}
   289  }
   290  
   291  func (check *Checker) funcDecl(obj *Func, decl *declInfo) {
   292  	assert(obj.typ == nil)
   293  
   294  	// func declarations cannot use iota
   295  	assert(check.iota == nil)
   296  
   297  	sig := new(Signature)
   298  	obj.typ = sig // guard against cycles
   299  	fdecl := decl.fdecl
   300  	check.funcType(sig, fdecl.Recv, fdecl.Type)
   301  	if sig.recv == nil && obj.name == "init" && (sig.params.Len() > 0 || sig.results.Len() > 0) {
   302  		check.errorf(fdecl.Pos(), "func init must have no arguments and no return values")
   303  		// ok to continue
   304  	}
   305  
   306  	// function body must be type-checked after global declarations
   307  	// (functions implemented elsewhere have no body)
   308  	if !check.conf.IgnoreFuncBodies && fdecl.Body != nil {
   309  		check.later(obj.name, decl, sig, fdecl.Body)
   310  	}
   311  }
   312  
   313  func (check *Checker) declStmt(decl ast.Decl) {
   314  	pkg := check.pkg
   315  
   316  	switch d := decl.(type) {
   317  	case *ast.BadDecl:
   318  		// ignore
   319  
   320  	case *ast.GenDecl:
   321  		var last *ast.ValueSpec // last ValueSpec with type or init exprs seen
   322  		for iota, spec := range d.Specs {
   323  			switch s := spec.(type) {
   324  			case *ast.ValueSpec:
   325  				switch d.Tok {
   326  				case token.CONST:
   327  					// determine which init exprs to use
   328  					switch {
   329  					case s.Type != nil || len(s.Values) > 0:
   330  						last = s
   331  					case last == nil:
   332  						last = new(ast.ValueSpec) // make sure last exists
   333  					}
   334  
   335  					// declare all constants
   336  					lhs := make([]*Const, len(s.Names))
   337  					for i, name := range s.Names {
   338  						obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(iota)))
   339  						lhs[i] = obj
   340  
   341  						var init ast.Expr
   342  						if i < len(last.Values) {
   343  							init = last.Values[i]
   344  						}
   345  
   346  						check.constDecl(obj, last.Type, init)
   347  					}
   348  
   349  					check.arityMatch(s, last)
   350  
   351  					// spec: "The scope of a constant or variable identifier declared
   352  					// inside a function begins at the end of the ConstSpec or VarSpec
   353  					// (ShortVarDecl for short variable declarations) and ends at the
   354  					// end of the innermost containing block."
   355  					scopePos := s.End()
   356  					for i, name := range s.Names {
   357  						check.declare(check.scope, name, lhs[i], scopePos)
   358  					}
   359  
   360  				case token.VAR:
   361  					lhs0 := make([]*Var, len(s.Names))
   362  					for i, name := range s.Names {
   363  						lhs0[i] = NewVar(name.Pos(), pkg, name.Name, nil)
   364  					}
   365  
   366  					// initialize all variables
   367  					for i, obj := range lhs0 {
   368  						var lhs []*Var
   369  						var init ast.Expr
   370  						switch len(s.Values) {
   371  						case len(s.Names):
   372  							// lhs and rhs match
   373  							init = s.Values[i]
   374  						case 1:
   375  							// rhs is expected to be a multi-valued expression
   376  							lhs = lhs0
   377  							init = s.Values[0]
   378  						default:
   379  							if i < len(s.Values) {
   380  								init = s.Values[i]
   381  							}
   382  						}
   383  						check.varDecl(obj, lhs, s.Type, init)
   384  						if len(s.Values) == 1 {
   385  							// If we have a single lhs variable we are done either way.
   386  							// If we have a single rhs expression, it must be a multi-
   387  							// valued expression, in which case handling the first lhs
   388  							// variable will cause all lhs variables to have a type
   389  							// assigned, and we are done as well.
   390  							if debug {
   391  								for _, obj := range lhs0 {
   392  									assert(obj.typ != nil)
   393  								}
   394  							}
   395  							break
   396  						}
   397  					}
   398  
   399  					check.arityMatch(s, nil)
   400  
   401  					// declare all variables
   402  					// (only at this point are the variable scopes (parents) set)
   403  					scopePos := s.End() // see constant declarations
   404  					for i, name := range s.Names {
   405  						// see constant declarations
   406  						check.declare(check.scope, name, lhs0[i], scopePos)
   407  					}
   408  
   409  				default:
   410  					check.invalidAST(s.Pos(), "invalid token %s", d.Tok)
   411  				}
   412  
   413  			case *ast.TypeSpec:
   414  				obj := NewTypeName(s.Name.Pos(), pkg, s.Name.Name, nil)
   415  				// spec: "The scope of a type identifier declared inside a function
   416  				// begins at the identifier in the TypeSpec and ends at the end of
   417  				// the innermost containing block."
   418  				scopePos := s.Name.Pos()
   419  				check.declare(check.scope, s.Name, obj, scopePos)
   420  				check.typeDecl(obj, s.Type, nil, nil)
   421  
   422  			default:
   423  				check.invalidAST(s.Pos(), "const, type, or var declaration expected")
   424  			}
   425  		}
   426  
   427  	default:
   428  		check.invalidAST(d.Pos(), "unknown ast.Decl node %T", d)
   429  	}
   430  }