github.com/euank/go@v0.0.0-20160829210321-495514729181/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  
   156  func (*Const) isDependency() {} // a constant may be a dependency of an initialization expression
   157  
   158  // A TypeName represents a declared type.
   159  type TypeName struct {
   160  	object
   161  }
   162  
   163  func NewTypeName(pos token.Pos, pkg *Package, name string, typ Type) *TypeName {
   164  	return &TypeName{object{nil, pos, pkg, name, typ, 0, token.NoPos}}
   165  }
   166  
   167  // A Variable represents a declared variable (including function parameters and results, and struct fields).
   168  type Var struct {
   169  	object
   170  	anonymous bool // if set, the variable is an anonymous struct field, and name is the type name
   171  	visited   bool // for initialization cycle detection
   172  	isField   bool // var is struct field
   173  	used      bool // set if the variable was used
   174  }
   175  
   176  func NewVar(pos token.Pos, pkg *Package, name string, typ Type) *Var {
   177  	return &Var{object: object{nil, pos, pkg, name, typ, 0, token.NoPos}}
   178  }
   179  
   180  func NewParam(pos token.Pos, pkg *Package, name string, typ Type) *Var {
   181  	return &Var{object: object{nil, pos, pkg, name, typ, 0, token.NoPos}, used: true} // parameters are always 'used'
   182  }
   183  
   184  func NewField(pos token.Pos, pkg *Package, name string, typ Type, anonymous bool) *Var {
   185  	return &Var{object: object{nil, pos, pkg, name, typ, 0, token.NoPos}, anonymous: anonymous, isField: true}
   186  }
   187  
   188  func (obj *Var) Anonymous() bool { return obj.anonymous }
   189  
   190  func (obj *Var) IsField() bool { return obj.isField }
   191  
   192  func (*Var) isDependency() {} // a variable may be a dependency of an initialization expression
   193  
   194  // A Func represents a declared function, concrete method, or abstract
   195  // (interface) method. Its Type() is always a *Signature.
   196  // An abstract method may belong to many interfaces due to embedding.
   197  type Func struct {
   198  	object
   199  }
   200  
   201  func NewFunc(pos token.Pos, pkg *Package, name string, sig *Signature) *Func {
   202  	// don't store a nil signature
   203  	var typ Type
   204  	if sig != nil {
   205  		typ = sig
   206  	}
   207  	return &Func{object{nil, pos, pkg, name, typ, 0, token.NoPos}}
   208  }
   209  
   210  // FullName returns the package- or receiver-type-qualified name of
   211  // function or method obj.
   212  func (obj *Func) FullName() string {
   213  	var buf bytes.Buffer
   214  	writeFuncName(&buf, obj, nil)
   215  	return buf.String()
   216  }
   217  
   218  func (obj *Func) Scope() *Scope {
   219  	return obj.typ.(*Signature).scope
   220  }
   221  
   222  func (*Func) isDependency() {} // a function may be a dependency of an initialization expression
   223  
   224  // A Label represents a declared label.
   225  type Label struct {
   226  	object
   227  	used bool // set if the label was used
   228  }
   229  
   230  func NewLabel(pos token.Pos, pkg *Package, name string) *Label {
   231  	return &Label{object{pos: pos, pkg: pkg, name: name, typ: Typ[Invalid]}, false}
   232  }
   233  
   234  // A Builtin represents a built-in function.
   235  // Builtins don't have a valid type.
   236  type Builtin struct {
   237  	object
   238  	id builtinId
   239  }
   240  
   241  func newBuiltin(id builtinId) *Builtin {
   242  	return &Builtin{object{name: predeclaredFuncs[id].name, typ: Typ[Invalid]}, id}
   243  }
   244  
   245  // Nil represents the predeclared value nil.
   246  type Nil struct {
   247  	object
   248  }
   249  
   250  func writeObject(buf *bytes.Buffer, obj Object, qf Qualifier) {
   251  	typ := obj.Type()
   252  	switch obj := obj.(type) {
   253  	case *PkgName:
   254  		fmt.Fprintf(buf, "package %s", obj.Name())
   255  		if path := obj.imported.path; path != "" && path != obj.name {
   256  			fmt.Fprintf(buf, " (%q)", path)
   257  		}
   258  		return
   259  
   260  	case *Const:
   261  		buf.WriteString("const")
   262  
   263  	case *TypeName:
   264  		buf.WriteString("type")
   265  		typ = typ.Underlying()
   266  
   267  	case *Var:
   268  		if obj.isField {
   269  			buf.WriteString("field")
   270  		} else {
   271  			buf.WriteString("var")
   272  		}
   273  
   274  	case *Func:
   275  		buf.WriteString("func ")
   276  		writeFuncName(buf, obj, qf)
   277  		if typ != nil {
   278  			WriteSignature(buf, typ.(*Signature), qf)
   279  		}
   280  		return
   281  
   282  	case *Label:
   283  		buf.WriteString("label")
   284  		typ = nil
   285  
   286  	case *Builtin:
   287  		buf.WriteString("builtin")
   288  		typ = nil
   289  
   290  	case *Nil:
   291  		buf.WriteString("nil")
   292  		return
   293  
   294  	default:
   295  		panic(fmt.Sprintf("writeObject(%T)", obj))
   296  	}
   297  
   298  	buf.WriteByte(' ')
   299  
   300  	// For package-level objects, qualify the name.
   301  	if obj.Pkg() != nil && obj.Pkg().scope.Lookup(obj.Name()) == obj {
   302  		writePackage(buf, obj.Pkg(), qf)
   303  	}
   304  	buf.WriteString(obj.Name())
   305  	if typ != nil {
   306  		buf.WriteByte(' ')
   307  		WriteType(buf, typ, qf)
   308  	}
   309  }
   310  
   311  func writePackage(buf *bytes.Buffer, pkg *Package, qf Qualifier) {
   312  	if pkg == nil {
   313  		return
   314  	}
   315  	var s string
   316  	if qf != nil {
   317  		s = qf(pkg)
   318  	} else {
   319  		s = pkg.Path()
   320  	}
   321  	if s != "" {
   322  		buf.WriteString(s)
   323  		buf.WriteByte('.')
   324  	}
   325  }
   326  
   327  // ObjectString returns the string form of obj.
   328  // The Qualifier controls the printing of
   329  // package-level objects, and may be nil.
   330  func ObjectString(obj Object, qf Qualifier) string {
   331  	var buf bytes.Buffer
   332  	writeObject(&buf, obj, qf)
   333  	return buf.String()
   334  }
   335  
   336  func (obj *PkgName) String() string  { return ObjectString(obj, nil) }
   337  func (obj *Const) String() string    { return ObjectString(obj, nil) }
   338  func (obj *TypeName) String() string { return ObjectString(obj, nil) }
   339  func (obj *Var) String() string      { return ObjectString(obj, nil) }
   340  func (obj *Func) String() string     { return ObjectString(obj, nil) }
   341  func (obj *Label) String() string    { return ObjectString(obj, nil) }
   342  func (obj *Builtin) String() string  { return ObjectString(obj, nil) }
   343  func (obj *Nil) String() string      { return ObjectString(obj, nil) }
   344  
   345  func writeFuncName(buf *bytes.Buffer, f *Func, qf Qualifier) {
   346  	if f.typ != nil {
   347  		sig := f.typ.(*Signature)
   348  		if recv := sig.Recv(); recv != nil {
   349  			buf.WriteByte('(')
   350  			if _, ok := recv.Type().(*Interface); ok {
   351  				// gcimporter creates abstract methods of
   352  				// named interfaces using the interface type
   353  				// (not the named type) as the receiver.
   354  				// Don't print it in full.
   355  				buf.WriteString("interface")
   356  			} else {
   357  				WriteType(buf, recv.Type(), qf)
   358  			}
   359  			buf.WriteByte(')')
   360  			buf.WriteByte('.')
   361  		} else if f.pkg != nil {
   362  			writePackage(buf, f.pkg, qf)
   363  		}
   364  	}
   365  	buf.WriteString(f.name)
   366  }