github.com/dannin/go@v0.0.0-20161031215817-d35dfd405eaa/src/go/types/object.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  	"bytes"
     9  	"fmt"
    10  	"go/ast"
    11  	"go/constant"
    12  	"go/token"
    13  )
    14  
    15  // TODO(gri) Document factory, accessor methods, and fields. General clean-up.
    16  
    17  // An Object describes a named language entity such as a package,
    18  // constant, type, variable, function (incl. methods), or label.
    19  // All objects implement the Object interface.
    20  //
    21  type Object interface {
    22  	Parent() *Scope // scope in which this object is declared; nil for methods and struct fields
    23  	Pos() token.Pos // position of object identifier in declaration
    24  	Pkg() *Package  // nil for objects in the Universe scope and labels
    25  	Name() string   // package local object name
    26  	Type() Type     // object type
    27  	Exported() bool // reports whether the name starts with a capital letter
    28  	Id() string     // object id (see Id below)
    29  
    30  	// String returns a human-readable string of the object.
    31  	String() string
    32  
    33  	// order reflects a package-level object's source order: if object
    34  	// a is before object b in the source, then a.order() < b.order().
    35  	// order returns a value > 0 for package-level objects; it returns
    36  	// 0 for all other objects (including objects in file scopes).
    37  	order() uint32
    38  
    39  	// setOrder sets the order number of the object. It must be > 0.
    40  	setOrder(uint32)
    41  
    42  	// setParent sets the parent scope of the object.
    43  	setParent(*Scope)
    44  
    45  	// sameId reports whether obj.Id() and Id(pkg, name) are the same.
    46  	sameId(pkg *Package, name string) bool
    47  
    48  	// scopePos returns the start position of the scope of this Object
    49  	scopePos() token.Pos
    50  
    51  	// setScopePos sets the start position of the scope for this Object.
    52  	setScopePos(pos token.Pos)
    53  }
    54  
    55  // Id returns name if it is exported, otherwise it
    56  // returns the name qualified with the package path.
    57  func Id(pkg *Package, name string) string {
    58  	if ast.IsExported(name) {
    59  		return name
    60  	}
    61  	// unexported names need the package path for differentiation
    62  	// (if there's no package, make sure we don't start with '.'
    63  	// as that may change the order of methods between a setup
    64  	// inside a package and outside a package - which breaks some
    65  	// tests)
    66  	path := "_"
    67  	// TODO(gri): shouldn't !ast.IsExported(name) => pkg != nil be an precondition?
    68  	// if pkg == nil {
    69  	// 	panic("nil package in lookup of unexported name")
    70  	// }
    71  	if pkg != nil {
    72  		path = pkg.path
    73  		if path == "" {
    74  			path = "_"
    75  		}
    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  	scopePos_ token.Pos
    89  }
    90  
    91  func (obj *object) Parent() *Scope      { return obj.parent }
    92  func (obj *object) Pos() token.Pos      { return obj.pos }
    93  func (obj *object) Pkg() *Package       { return obj.pkg }
    94  func (obj *object) Name() string        { return obj.name }
    95  func (obj *object) Type() Type          { return obj.typ }
    96  func (obj *object) Exported() bool      { return ast.IsExported(obj.name) }
    97  func (obj *object) Id() string          { return Id(obj.pkg, obj.name) }
    98  func (obj *object) String() string      { panic("abstract") }
    99  func (obj *object) order() uint32       { return obj.order_ }
   100  func (obj *object) scopePos() token.Pos { return obj.scopePos_ }
   101  
   102  func (obj *object) setParent(parent *Scope)   { obj.parent = parent }
   103  func (obj *object) setOrder(order uint32)     { assert(order > 0); obj.order_ = order }
   104  func (obj *object) setScopePos(pos token.Pos) { obj.scopePos_ = pos }
   105  
   106  func (obj *object) sameId(pkg *Package, name string) bool {
   107  	// spec:
   108  	// "Two identifiers are different if they are spelled differently,
   109  	// or if they appear in different packages and are not exported.
   110  	// Otherwise, they are the same."
   111  	if name != obj.name {
   112  		return false
   113  	}
   114  	// obj.Name == name
   115  	if obj.Exported() {
   116  		return true
   117  	}
   118  	// not exported, so packages must be the same (pkg == nil for
   119  	// fields in Universe scope; this can only happen for types
   120  	// introduced via Eval)
   121  	if pkg == nil || obj.pkg == nil {
   122  		return pkg == obj.pkg
   123  	}
   124  	// pkg != nil && obj.pkg != nil
   125  	return pkg.path == obj.pkg.path
   126  }
   127  
   128  // A PkgName represents an imported Go package.
   129  type PkgName struct {
   130  	object
   131  	imported *Package
   132  	used     bool // set if the package was used
   133  }
   134  
   135  func NewPkgName(pos token.Pos, pkg *Package, name string, imported *Package) *PkgName {
   136  	return &PkgName{object{nil, pos, pkg, name, Typ[Invalid], 0, token.NoPos}, imported, false}
   137  }
   138  
   139  // Imported returns the package that was imported.
   140  // It is distinct from Pkg(), which is the package containing the import statement.
   141  func (obj *PkgName) Imported() *Package { return obj.imported }
   142  
   143  // A Const represents a declared constant.
   144  type Const struct {
   145  	object
   146  	val     constant.Value
   147  	visited bool // for initialization cycle detection
   148  }
   149  
   150  func NewConst(pos token.Pos, pkg *Package, name string, typ Type, val constant.Value) *Const {
   151  	return &Const{object{nil, pos, pkg, name, typ, 0, token.NoPos}, val, false}
   152  }
   153  
   154  func (obj *Const) Val() constant.Value { return obj.val }
   155  func (*Const) isDependency()           {} // a constant may be a dependency of an initialization expression
   156  
   157  // A TypeName represents a declared type.
   158  type TypeName struct {
   159  	object
   160  }
   161  
   162  func NewTypeName(pos token.Pos, pkg *Package, name string, typ Type) *TypeName {
   163  	return &TypeName{object{nil, pos, pkg, name, typ, 0, token.NoPos}}
   164  }
   165  
   166  // A Variable represents a declared variable (including function parameters and results, and struct fields).
   167  type Var struct {
   168  	object
   169  	anonymous bool // if set, the variable is an anonymous struct field, and name is the type name
   170  	visited   bool // for initialization cycle detection
   171  	isField   bool // var is struct field
   172  	used      bool // set if the variable was used
   173  }
   174  
   175  func NewVar(pos token.Pos, pkg *Package, name string, typ Type) *Var {
   176  	return &Var{object: object{nil, pos, pkg, name, typ, 0, token.NoPos}}
   177  }
   178  
   179  func NewParam(pos token.Pos, pkg *Package, name string, typ Type) *Var {
   180  	return &Var{object: object{nil, pos, pkg, name, typ, 0, token.NoPos}, used: true} // parameters are always 'used'
   181  }
   182  
   183  func NewField(pos token.Pos, pkg *Package, name string, typ Type, anonymous bool) *Var {
   184  	return &Var{object: object{nil, pos, pkg, name, typ, 0, token.NoPos}, anonymous: anonymous, isField: true}
   185  }
   186  
   187  func (obj *Var) Anonymous() bool { return obj.anonymous }
   188  func (obj *Var) IsField() bool   { return obj.isField }
   189  func (*Var) isDependency()       {} // a variable may be a dependency of an initialization expression
   190  
   191  // A Func represents a declared function, concrete method, or abstract
   192  // (interface) method. Its Type() is always a *Signature.
   193  // An abstract method may belong to many interfaces due to embedding.
   194  type Func struct {
   195  	object
   196  }
   197  
   198  func NewFunc(pos token.Pos, pkg *Package, name string, sig *Signature) *Func {
   199  	// don't store a nil signature
   200  	var typ Type
   201  	if sig != nil {
   202  		typ = sig
   203  	}
   204  	return &Func{object{nil, pos, pkg, name, typ, 0, token.NoPos}}
   205  }
   206  
   207  // FullName returns the package- or receiver-type-qualified name of
   208  // function or method obj.
   209  func (obj *Func) FullName() string {
   210  	var buf bytes.Buffer
   211  	writeFuncName(&buf, obj, nil)
   212  	return buf.String()
   213  }
   214  
   215  func (obj *Func) Scope() *Scope { return obj.typ.(*Signature).scope }
   216  func (*Func) isDependency()     {} // a function may be a dependency of an initialization expression
   217  
   218  // An Alias represents a declared alias.
   219  type Alias struct {
   220  	object
   221  	orig Object      // aliased constant, type, variable, or function; never an alias
   222  	kind token.Token // token.CONST, token.TYPE, token.VAR, or token.FUNC (type-checking internal use only)
   223  }
   224  
   225  func NewAlias(pos token.Pos, pkg *Package, name string, orig Object) *Alias {
   226  	return &Alias{object{pos: pos, pkg: pkg, name: name}, orig, token.ILLEGAL}
   227  }
   228  
   229  // Orig returns the aliased object, or nil if there was an error.
   230  // The returned object is never an Alias.
   231  func (obj *Alias) Orig() Object { return obj.orig }
   232  
   233  // A Label represents a declared label.
   234  type Label struct {
   235  	object
   236  	used bool // set if the label was used
   237  }
   238  
   239  func NewLabel(pos token.Pos, pkg *Package, name string) *Label {
   240  	return &Label{object{pos: pos, pkg: pkg, name: name, typ: Typ[Invalid]}, false}
   241  }
   242  
   243  // A Builtin represents a built-in function.
   244  // Builtins don't have a valid type.
   245  type Builtin struct {
   246  	object
   247  	id builtinId
   248  }
   249  
   250  func newBuiltin(id builtinId) *Builtin {
   251  	return &Builtin{object{name: predeclaredFuncs[id].name, typ: Typ[Invalid]}, id}
   252  }
   253  
   254  // Nil represents the predeclared value nil.
   255  type Nil struct {
   256  	object
   257  }
   258  
   259  func writeObject(buf *bytes.Buffer, obj Object, qf Qualifier) {
   260  	typ := obj.Type()
   261  	switch obj := obj.(type) {
   262  	case *PkgName:
   263  		fmt.Fprintf(buf, "package %s", obj.Name())
   264  		if path := obj.imported.path; path != "" && path != obj.name {
   265  			fmt.Fprintf(buf, " (%q)", path)
   266  		}
   267  		return
   268  
   269  	case *Const:
   270  		buf.WriteString("const")
   271  
   272  	case *TypeName:
   273  		buf.WriteString("type")
   274  		typ = typ.Underlying()
   275  
   276  	case *Var:
   277  		if obj.isField {
   278  			buf.WriteString("field")
   279  		} else {
   280  			buf.WriteString("var")
   281  		}
   282  
   283  	case *Func:
   284  		buf.WriteString("func ")
   285  		writeFuncName(buf, obj, qf)
   286  		if typ != nil {
   287  			WriteSignature(buf, typ.(*Signature), qf)
   288  		}
   289  		return
   290  
   291  	case *Alias:
   292  		buf.WriteString("alias")
   293  
   294  	case *Label:
   295  		buf.WriteString("label")
   296  		typ = nil
   297  
   298  	case *Builtin:
   299  		buf.WriteString("builtin")
   300  		typ = nil
   301  
   302  	case *Nil:
   303  		buf.WriteString("nil")
   304  		return
   305  
   306  	default:
   307  		panic(fmt.Sprintf("writeObject(%T)", obj))
   308  	}
   309  
   310  	buf.WriteByte(' ')
   311  
   312  	// For package-level objects, qualify the name.
   313  	if obj.Pkg() != nil && obj.Pkg().scope.Lookup(obj.Name()) == obj {
   314  		writePackage(buf, obj.Pkg(), qf)
   315  	}
   316  	buf.WriteString(obj.Name())
   317  	if typ != nil {
   318  		buf.WriteByte(' ')
   319  		WriteType(buf, typ, qf)
   320  	}
   321  }
   322  
   323  func writePackage(buf *bytes.Buffer, pkg *Package, qf Qualifier) {
   324  	if pkg == nil {
   325  		return
   326  	}
   327  	var s string
   328  	if qf != nil {
   329  		s = qf(pkg)
   330  	} else {
   331  		s = pkg.Path()
   332  	}
   333  	if s != "" {
   334  		buf.WriteString(s)
   335  		buf.WriteByte('.')
   336  	}
   337  }
   338  
   339  // ObjectString returns the string form of obj.
   340  // The Qualifier controls the printing of
   341  // package-level objects, and may be nil.
   342  func ObjectString(obj Object, qf Qualifier) string {
   343  	var buf bytes.Buffer
   344  	writeObject(&buf, obj, qf)
   345  	return buf.String()
   346  }
   347  
   348  func (obj *PkgName) String() string  { return ObjectString(obj, nil) }
   349  func (obj *Const) String() string    { return ObjectString(obj, nil) }
   350  func (obj *TypeName) String() string { return ObjectString(obj, nil) }
   351  func (obj *Var) String() string      { return ObjectString(obj, nil) }
   352  func (obj *Func) String() string     { return ObjectString(obj, nil) }
   353  func (obj *Alias) String() string    { return ObjectString(obj, nil) }
   354  func (obj *Label) String() string    { return ObjectString(obj, nil) }
   355  func (obj *Builtin) String() string  { return ObjectString(obj, nil) }
   356  func (obj *Nil) String() string      { return ObjectString(obj, nil) }
   357  
   358  func writeFuncName(buf *bytes.Buffer, f *Func, qf Qualifier) {
   359  	if f.typ != nil {
   360  		sig := f.typ.(*Signature)
   361  		if recv := sig.Recv(); recv != nil {
   362  			buf.WriteByte('(')
   363  			if _, ok := recv.Type().(*Interface); ok {
   364  				// gcimporter creates abstract methods of
   365  				// named interfaces using the interface type
   366  				// (not the named type) as the receiver.
   367  				// Don't print it in full.
   368  				buf.WriteString("interface")
   369  			} else {
   370  				WriteType(buf, recv.Type(), qf)
   371  			}
   372  			buf.WriteByte(')')
   373  			buf.WriteByte('.')
   374  		} else if f.pkg != nil {
   375  			writePackage(buf, f.pkg, qf)
   376  		}
   377  	}
   378  	buf.WriteString(f.name)
   379  }