Source file src/go/types/object.go

     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  	"bytes"
     9  	"fmt"
    10  	"go/constant"
    11  	"go/token"
    12  )
    13  
    14  // An Object describes a named language entity such as a package,
    15  // constant, type, variable, function (incl. methods), or label.
    16  // All objects implement the Object interface.
    17  //
    18  type Object interface {
    19  	Parent() *Scope // scope in which this object is declared; nil for methods and struct fields
    20  	Pos() token.Pos // position of object identifier in declaration
    21  	Pkg() *Package  // package to which this object belongs; nil for labels and objects in the Universe scope
    22  	Name() string   // package local object name
    23  	Type() Type     // object type
    24  	Exported() bool // reports whether the name starts with a capital letter
    25  	Id() string     // object name if exported, qualified name if not exported (see func Id)
    26  
    27  	// String returns a human-readable string of the object.
    28  	String() string
    29  
    30  	// order reflects a package-level object's source order: if object
    31  	// a is before object b in the source, then a.order() < b.order().
    32  	// order returns a value > 0 for package-level objects; it returns
    33  	// 0 for all other objects (including objects in file scopes).
    34  	order() uint32
    35  
    36  	// color returns the object's color.
    37  	color() color
    38  
    39  	// setType sets the type of the object.
    40  	setType(Type)
    41  
    42  	// setOrder sets the order number of the object. It must be > 0.
    43  	setOrder(uint32)
    44  
    45  	// setColor sets the object's color. It must not be white.
    46  	setColor(color color)
    47  
    48  	// setParent sets the parent scope of the object.
    49  	setParent(*Scope)
    50  
    51  	// sameId reports whether obj.Id() and Id(pkg, name) are the same.
    52  	sameId(pkg *Package, name string) bool
    53  
    54  	// scopePos returns the start position of the scope of this Object
    55  	scopePos() token.Pos
    56  
    57  	// setScopePos sets the start position of the scope for this Object.
    58  	setScopePos(pos token.Pos)
    59  }
    60  
    61  // Id returns name if it is exported, otherwise it
    62  // returns the name qualified with the package path.
    63  func Id(pkg *Package, name string) string {
    64  	if token.IsExported(name) {
    65  		return name
    66  	}
    67  	// unexported names need the package path for differentiation
    68  	// (if there's no package, make sure we don't start with '.'
    69  	// as that may change the order of methods between a setup
    70  	// inside a package and outside a package - which breaks some
    71  	// tests)
    72  	path := "_"
    73  	// pkg is nil for objects in Universe scope and possibly types
    74  	// introduced via Eval (see also comment in object.sameId)
    75  	if pkg != nil && pkg.path != "" {
    76  		path = pkg.path
    77  	}
    78  	return path + "." + name
    79  }
    80  
    81  // An object implements the common parts of an Object.
    82  type object struct {
    83  	parent    *Scope
    84  	pos       token.Pos
    85  	pkg       *Package
    86  	name      string
    87  	typ       Type
    88  	order_    uint32
    89  	color_    color
    90  	scopePos_ token.Pos
    91  }
    92  
    93  // color encodes the color of an object (see Checker.objDecl for details).
    94  type color uint32
    95  
    96  // An object may be painted in one of three colors.
    97  // Color values other than white or black are considered grey.
    98  const (
    99  	white color = iota
   100  	black
   101  	grey // must be > white and black
   102  )
   103  
   104  func (c color) String() string {
   105  	switch c {
   106  	case white:
   107  		return "white"
   108  	case black:
   109  		return "black"
   110  	default:
   111  		return "grey"
   112  	}
   113  }
   114  
   115  // colorFor returns the (initial) color for an object depending on
   116  // whether its type t is known or not.
   117  func colorFor(t Type) color {
   118  	if t != nil {
   119  		return black
   120  	}
   121  	return white
   122  }
   123  
   124  // Parent returns the scope in which the object is declared.
   125  // The result is nil for methods and struct fields.
   126  func (obj *object) Parent() *Scope { return obj.parent }
   127  
   128  // Pos returns the declaration position of the object's identifier.
   129  func (obj *object) Pos() token.Pos { return obj.pos }
   130  
   131  // Pkg returns the package to which the object belongs.
   132  // The result is nil for labels and objects in the Universe scope.
   133  func (obj *object) Pkg() *Package { return obj.pkg }
   134  
   135  // Name returns the object's (package-local, unqualified) name.
   136  func (obj *object) Name() string { return obj.name }
   137  
   138  // Type returns the object's type.
   139  func (obj *object) Type() Type { return obj.typ }
   140  
   141  // Exported reports whether the object is exported (starts with a capital letter).
   142  // It doesn't take into account whether the object is in a local (function) scope
   143  // or not.
   144  func (obj *object) Exported() bool { return token.IsExported(obj.name) }
   145  
   146  // Id is a wrapper for Id(obj.Pkg(), obj.Name()).
   147  func (obj *object) Id() string { return Id(obj.pkg, obj.name) }
   148  
   149  func (obj *object) String() string      { panic("abstract") }
   150  func (obj *object) order() uint32       { return obj.order_ }
   151  func (obj *object) color() color        { return obj.color_ }
   152  func (obj *object) scopePos() token.Pos { return obj.scopePos_ }
   153  
   154  func (obj *object) setParent(parent *Scope)   { obj.parent = parent }
   155  func (obj *object) setType(typ Type)          { obj.typ = typ }
   156  func (obj *object) setOrder(order uint32)     { assert(order > 0); obj.order_ = order }
   157  func (obj *object) setColor(color color)      { assert(color != white); obj.color_ = color }
   158  func (obj *object) setScopePos(pos token.Pos) { obj.scopePos_ = pos }
   159  
   160  func (obj *object) sameId(pkg *Package, name string) bool {
   161  	// spec:
   162  	// "Two identifiers are different if they are spelled differently,
   163  	// or if they appear in different packages and are not exported.
   164  	// Otherwise, they are the same."
   165  	if name != obj.name {
   166  		return false
   167  	}
   168  	// obj.Name == name
   169  	if obj.Exported() {
   170  		return true
   171  	}
   172  	// not exported, so packages must be the same (pkg == nil for
   173  	// fields in Universe scope; this can only happen for types
   174  	// introduced via Eval)
   175  	if pkg == nil || obj.pkg == nil {
   176  		return pkg == obj.pkg
   177  	}
   178  	// pkg != nil && obj.pkg != nil
   179  	return pkg.path == obj.pkg.path
   180  }
   181  
   182  // A PkgName represents an imported Go package.
   183  // PkgNames don't have a type.
   184  type PkgName struct {
   185  	object
   186  	imported *Package
   187  	used     bool // set if the package was used
   188  }
   189  
   190  // NewPkgName returns a new PkgName object representing an imported package.
   191  // The remaining arguments set the attributes found with all Objects.
   192  func NewPkgName(pos token.Pos, pkg *Package, name string, imported *Package) *PkgName {
   193  	return &PkgName{object{nil, pos, pkg, name, Typ[Invalid], 0, black, token.NoPos}, imported, false}
   194  }
   195  
   196  // Imported returns the package that was imported.
   197  // It is distinct from Pkg(), which is the package containing the import statement.
   198  func (obj *PkgName) Imported() *Package { return obj.imported }
   199  
   200  // A Const represents a declared constant.
   201  type Const struct {
   202  	object
   203  	val constant.Value
   204  }
   205  
   206  // NewConst returns a new constant with value val.
   207  // The remaining arguments set the attributes found with all Objects.
   208  func NewConst(pos token.Pos, pkg *Package, name string, typ Type, val constant.Value) *Const {
   209  	return &Const{object{nil, pos, pkg, name, typ, 0, colorFor(typ), token.NoPos}, val}
   210  }
   211  
   212  // Val returns the constant's value.
   213  func (obj *Const) Val() constant.Value { return obj.val }
   214  
   215  func (*Const) isDependency() {} // a constant may be a dependency of an initialization expression
   216  
   217  // A TypeName represents a name for a (defined or alias) type.
   218  type TypeName struct {
   219  	object
   220  }
   221  
   222  // NewTypeName returns a new type name denoting the given typ.
   223  // The remaining arguments set the attributes found with all Objects.
   224  //
   225  // The typ argument may be a defined (Named) type or an alias type.
   226  // It may also be nil such that the returned TypeName can be used as
   227  // argument for NewNamed, which will set the TypeName's type as a side-
   228  // effect.
   229  func NewTypeName(pos token.Pos, pkg *Package, name string, typ Type) *TypeName {
   230  	return &TypeName{object{nil, pos, pkg, name, typ, 0, colorFor(typ), token.NoPos}}
   231  }
   232  
   233  // _NewTypeNameLazy returns a new defined type like NewTypeName, but it
   234  // lazily calls resolve to finish constructing the Named object.
   235  func _NewTypeNameLazy(pos token.Pos, pkg *Package, name string, load func(named *Named) (tparams []*TypeParam, underlying Type, methods []*Func)) *TypeName {
   236  	obj := NewTypeName(pos, pkg, name, nil)
   237  
   238  	resolve := func(_ *Context, t *Named) (*TypeParamList, Type, *methodList) {
   239  		tparams, underlying, methods := load(t)
   240  
   241  		switch underlying.(type) {
   242  		case nil, *Named:
   243  			panic(fmt.Sprintf("invalid underlying type %T", t.underlying))
   244  		}
   245  
   246  		return bindTParams(tparams), underlying, newMethodList(methods)
   247  	}
   248  
   249  	NewNamed(obj, nil, nil).resolver = resolve
   250  	return obj
   251  }
   252  
   253  // IsAlias reports whether obj is an alias name for a type.
   254  func (obj *TypeName) IsAlias() bool {
   255  	switch t := obj.typ.(type) {
   256  	case nil:
   257  		return false
   258  	case *Basic:
   259  		// unsafe.Pointer is not an alias.
   260  		if obj.pkg == Unsafe {
   261  			return false
   262  		}
   263  		// Any user-defined type name for a basic type is an alias for a
   264  		// basic type (because basic types are pre-declared in the Universe
   265  		// scope, outside any package scope), and so is any type name with
   266  		// a different name than the name of the basic type it refers to.
   267  		// Additionally, we need to look for "byte" and "rune" because they
   268  		// are aliases but have the same names (for better error messages).
   269  		return obj.pkg != nil || t.name != obj.name || t == universeByte || t == universeRune
   270  	case *Named:
   271  		return obj != t.obj
   272  	case *TypeParam:
   273  		return obj != t.obj
   274  	default:
   275  		return true
   276  	}
   277  }
   278  
   279  // A Variable represents a declared variable (including function parameters and results, and struct fields).
   280  type Var struct {
   281  	object
   282  	embedded bool // if set, the variable is an embedded struct field, and name is the type name
   283  	isField  bool // var is struct field
   284  	used     bool // set if the variable was used
   285  }
   286  
   287  // NewVar returns a new variable.
   288  // The arguments set the attributes found with all Objects.
   289  func NewVar(pos token.Pos, pkg *Package, name string, typ Type) *Var {
   290  	return &Var{object: object{nil, pos, pkg, name, typ, 0, colorFor(typ), token.NoPos}}
   291  }
   292  
   293  // NewParam returns a new variable representing a function parameter.
   294  func NewParam(pos token.Pos, pkg *Package, name string, typ Type) *Var {
   295  	return &Var{object: object{nil, pos, pkg, name, typ, 0, colorFor(typ), token.NoPos}, used: true} // parameters are always 'used'
   296  }
   297  
   298  // NewField returns a new variable representing a struct field.
   299  // For embedded fields, the name is the unqualified type name
   300  /// under which the field is accessible.
   301  func NewField(pos token.Pos, pkg *Package, name string, typ Type, embedded bool) *Var {
   302  	return &Var{object: object{nil, pos, pkg, name, typ, 0, colorFor(typ), token.NoPos}, embedded: embedded, isField: true}
   303  }
   304  
   305  // Anonymous reports whether the variable is an embedded field.
   306  // Same as Embedded; only present for backward-compatibility.
   307  func (obj *Var) Anonymous() bool { return obj.embedded }
   308  
   309  // Embedded reports whether the variable is an embedded field.
   310  func (obj *Var) Embedded() bool { return obj.embedded }
   311  
   312  // IsField reports whether the variable is a struct field.
   313  func (obj *Var) IsField() bool { return obj.isField }
   314  
   315  func (*Var) isDependency() {} // a variable may be a dependency of an initialization expression
   316  
   317  // A Func represents a declared function, concrete method, or abstract
   318  // (interface) method. Its Type() is always a *Signature.
   319  // An abstract method may belong to many interfaces due to embedding.
   320  type Func struct {
   321  	object
   322  	hasPtrRecv_ bool // only valid for methods that don't have a type yet; use hasPtrRecv() to read
   323  }
   324  
   325  // NewFunc returns a new function with the given signature, representing
   326  // the function's type.
   327  func NewFunc(pos token.Pos, pkg *Package, name string, sig *Signature) *Func {
   328  	// don't store a (typed) nil signature
   329  	var typ Type
   330  	if sig != nil {
   331  		typ = sig
   332  	}
   333  	return &Func{object{nil, pos, pkg, name, typ, 0, colorFor(typ), token.NoPos}, false}
   334  }
   335  
   336  // FullName returns the package- or receiver-type-qualified name of
   337  // function or method obj.
   338  func (obj *Func) FullName() string {
   339  	var buf bytes.Buffer
   340  	writeFuncName(&buf, obj, nil)
   341  	return buf.String()
   342  }
   343  
   344  // Scope returns the scope of the function's body block.
   345  // The result is nil for imported or instantiated functions and methods
   346  // (but there is also no mechanism to get to an instantiated function).
   347  func (obj *Func) Scope() *Scope { return obj.typ.(*Signature).scope }
   348  
   349  // hasPtrRecv reports whether the receiver is of the form *T for the given method obj.
   350  func (obj *Func) hasPtrRecv() bool {
   351  	// If a method's receiver type is set, use that as the source of truth for the receiver.
   352  	// Caution: Checker.funcDecl (decl.go) marks a function by setting its type to an empty
   353  	// signature. We may reach here before the signature is fully set up: we must explicitly
   354  	// check if the receiver is set (we cannot just look for non-nil obj.typ).
   355  	if sig, _ := obj.typ.(*Signature); sig != nil && sig.recv != nil {
   356  		_, isPtr := deref(sig.recv.typ)
   357  		return isPtr
   358  	}
   359  
   360  	// If a method's type is not set it may be a method/function that is:
   361  	// 1) client-supplied (via NewFunc with no signature), or
   362  	// 2) internally created but not yet type-checked.
   363  	// For case 1) we can't do anything; the client must know what they are doing.
   364  	// For case 2) we can use the information gathered by the resolver.
   365  	return obj.hasPtrRecv_
   366  }
   367  
   368  func (*Func) isDependency() {} // a function may be a dependency of an initialization expression
   369  
   370  // A Label represents a declared label.
   371  // Labels don't have a type.
   372  type Label struct {
   373  	object
   374  	used bool // set if the label was used
   375  }
   376  
   377  // NewLabel returns a new label.
   378  func NewLabel(pos token.Pos, pkg *Package, name string) *Label {
   379  	return &Label{object{pos: pos, pkg: pkg, name: name, typ: Typ[Invalid], color_: black}, false}
   380  }
   381  
   382  // A Builtin represents a built-in function.
   383  // Builtins don't have a valid type.
   384  type Builtin struct {
   385  	object
   386  	id builtinId
   387  }
   388  
   389  func newBuiltin(id builtinId) *Builtin {
   390  	return &Builtin{object{name: predeclaredFuncs[id].name, typ: Typ[Invalid], color_: black}, id}
   391  }
   392  
   393  // Nil represents the predeclared value nil.
   394  type Nil struct {
   395  	object
   396  }
   397  
   398  func writeObject(buf *bytes.Buffer, obj Object, qf Qualifier) {
   399  	var tname *TypeName
   400  	typ := obj.Type()
   401  
   402  	switch obj := obj.(type) {
   403  	case *PkgName:
   404  		fmt.Fprintf(buf, "package %s", obj.Name())
   405  		if path := obj.imported.path; path != "" && path != obj.name {
   406  			fmt.Fprintf(buf, " (%q)", path)
   407  		}
   408  		return
   409  
   410  	case *Const:
   411  		buf.WriteString("const")
   412  
   413  	case *TypeName:
   414  		tname = obj
   415  		buf.WriteString("type")
   416  		if isTypeParam(typ) {
   417  			buf.WriteString(" parameter")
   418  		}
   419  
   420  	case *Var:
   421  		if obj.isField {
   422  			buf.WriteString("field")
   423  		} else {
   424  			buf.WriteString("var")
   425  		}
   426  
   427  	case *Func:
   428  		buf.WriteString("func ")
   429  		writeFuncName(buf, obj, qf)
   430  		if typ != nil {
   431  			WriteSignature(buf, typ.(*Signature), qf)
   432  		}
   433  		return
   434  
   435  	case *Label:
   436  		buf.WriteString("label")
   437  		typ = nil
   438  
   439  	case *Builtin:
   440  		buf.WriteString("builtin")
   441  		typ = nil
   442  
   443  	case *Nil:
   444  		buf.WriteString("nil")
   445  		return
   446  
   447  	default:
   448  		panic(fmt.Sprintf("writeObject(%T)", obj))
   449  	}
   450  
   451  	buf.WriteByte(' ')
   452  
   453  	// For package-level objects, qualify the name.
   454  	if obj.Pkg() != nil && obj.Pkg().scope.Lookup(obj.Name()) == obj {
   455  		writePackage(buf, obj.Pkg(), qf)
   456  	}
   457  	buf.WriteString(obj.Name())
   458  
   459  	if typ == nil {
   460  		return
   461  	}
   462  
   463  	if tname != nil {
   464  		switch t := typ.(type) {
   465  		case *Basic:
   466  			// Don't print anything more for basic types since there's
   467  			// no more information.
   468  			return
   469  		case *Named:
   470  			if t.TypeParams().Len() > 0 {
   471  				newTypeWriter(buf, qf).tParamList(t.TypeParams().list())
   472  			}
   473  		}
   474  		if tname.IsAlias() {
   475  			buf.WriteString(" =")
   476  		} else if t, _ := typ.(*TypeParam); t != nil {
   477  			typ = t.bound
   478  		} else {
   479  			// TODO(gri) should this be fromRHS for *Named?
   480  			typ = under(typ)
   481  		}
   482  	}
   483  
   484  	// Special handling for any: because WriteType will format 'any' as 'any',
   485  	// resulting in the object string `type any = any` rather than `type any =
   486  	// interface{}`. To avoid this, swap in a different empty interface.
   487  	if obj == universeAny {
   488  		assert(Identical(typ, &emptyInterface))
   489  		typ = &emptyInterface
   490  	}
   491  
   492  	buf.WriteByte(' ')
   493  	WriteType(buf, typ, qf)
   494  }
   495  
   496  func writePackage(buf *bytes.Buffer, pkg *Package, qf Qualifier) {
   497  	if pkg == nil {
   498  		return
   499  	}
   500  	var s string
   501  	if qf != nil {
   502  		s = qf(pkg)
   503  	} else {
   504  		s = pkg.Path()
   505  	}
   506  	if s != "" {
   507  		buf.WriteString(s)
   508  		buf.WriteByte('.')
   509  	}
   510  }
   511  
   512  // ObjectString returns the string form of obj.
   513  // The Qualifier controls the printing of
   514  // package-level objects, and may be nil.
   515  func ObjectString(obj Object, qf Qualifier) string {
   516  	var buf bytes.Buffer
   517  	writeObject(&buf, obj, qf)
   518  	return buf.String()
   519  }
   520  
   521  func (obj *PkgName) String() string  { return ObjectString(obj, nil) }
   522  func (obj *Const) String() string    { return ObjectString(obj, nil) }
   523  func (obj *TypeName) String() string { return ObjectString(obj, nil) }
   524  func (obj *Var) String() string      { return ObjectString(obj, nil) }
   525  func (obj *Func) String() string     { return ObjectString(obj, nil) }
   526  func (obj *Label) String() string    { return ObjectString(obj, nil) }
   527  func (obj *Builtin) String() string  { return ObjectString(obj, nil) }
   528  func (obj *Nil) String() string      { return ObjectString(obj, nil) }
   529  
   530  func writeFuncName(buf *bytes.Buffer, f *Func, qf Qualifier) {
   531  	if f.typ != nil {
   532  		sig := f.typ.(*Signature)
   533  		if recv := sig.Recv(); recv != nil {
   534  			buf.WriteByte('(')
   535  			if _, ok := recv.Type().(*Interface); ok {
   536  				// gcimporter creates abstract methods of
   537  				// named interfaces using the interface type
   538  				// (not the named type) as the receiver.
   539  				// Don't print it in full.
   540  				buf.WriteString("interface")
   541  			} else {
   542  				WriteType(buf, recv.Type(), qf)
   543  			}
   544  			buf.WriteByte(')')
   545  			buf.WriteByte('.')
   546  		} else if f.pkg != nil {
   547  			writePackage(buf, f.pkg, qf)
   548  		}
   549  	}
   550  	buf.WriteString(f.name)
   551  }
   552  

View as plain text