...

Source file src/go/types/object.go

Documentation: go/types

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

View as plain text