Source file src/cmd/compile/internal/types2/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 types2
     6  
     7  import (
     8  	"bytes"
     9  	"cmd/compile/internal/syntax"
    10  	"fmt"
    11  	"go/constant"
    12  	"strings"
    13  	"unicode"
    14  	"unicode/utf8"
    15  )
    16  
    17  // An Object is a named language entity.
    18  // An Object may be a constant ([Const]), type name ([TypeName]),
    19  // variable or struct field ([Var]), function or method ([Func]),
    20  // imported package ([PkgName]), label ([Label]),
    21  // built-in function ([Builtin]),
    22  // or the predeclared identifier 'nil' ([Nil]).
    23  //
    24  // The environment, which is structured as a tree of Scopes,
    25  // maps each name to the unique Object that it denotes.
    26  type Object interface {
    27  	Parent() *Scope  // scope in which this object is declared; nil for methods and struct fields
    28  	Pos() syntax.Pos // position of object identifier in declaration
    29  	Pkg() *Package   // package to which this object belongs; nil for labels and objects in the Universe scope
    30  	Name() string    // package local object name
    31  	Type() Type      // object type
    32  	Exported() bool  // reports whether the name starts with a capital letter
    33  	Id() string      // object name if exported, qualified name if not exported (see func Id)
    34  
    35  	// String returns a human-readable string of the object.
    36  	// Use [ObjectString] to control how package names are formatted in the string.
    37  	String() string
    38  
    39  	// order reflects a package-level object's source order: if object
    40  	// a is before object b in the source, then a.order() < b.order().
    41  	// order returns a value > 0 for package-level objects; it returns
    42  	// 0 for all other objects (including objects in file scopes).
    43  	order() uint32
    44  
    45  	// setType sets the type of the object.
    46  	setType(Type)
    47  
    48  	// setOrder sets the order number of the object. It must be > 0.
    49  	setOrder(uint32)
    50  
    51  	// setParent sets the parent scope of the object.
    52  	setParent(*Scope)
    53  
    54  	// sameId reports whether obj.Id() and Id(pkg, name) are the same.
    55  	// If foldCase is true, names are considered equal if they are equal with case folding
    56  	// and their packages are ignored (e.g., pkg1.m, pkg1.M, pkg2.m, and pkg2.M are all equal).
    57  	sameId(pkg *Package, name string, foldCase bool) bool
    58  
    59  	// scopePos returns the start position of the scope of this Object
    60  	scopePos() syntax.Pos
    61  
    62  	// setScopePos sets the start position of the scope for this Object.
    63  	setScopePos(pos syntax.Pos)
    64  }
    65  
    66  func isExported(name string) bool {
    67  	ch, _ := utf8.DecodeRuneInString(name)
    68  	return unicode.IsUpper(ch)
    69  }
    70  
    71  // Id returns name if it is exported, otherwise it
    72  // returns the name qualified with the package path.
    73  func Id(pkg *Package, name string) string {
    74  	if isExported(name) {
    75  		return name
    76  	}
    77  	// unexported names need the package path for differentiation
    78  	// (if there's no package, make sure we don't start with '.'
    79  	// as that may change the order of methods between a setup
    80  	// inside a package and outside a package - which breaks some
    81  	// tests)
    82  	path := "_"
    83  	// pkg is nil for objects in Universe scope and possibly types
    84  	// introduced via Eval (see also comment in object.sameId)
    85  	if pkg != nil && pkg.path != "" {
    86  		path = pkg.path
    87  	}
    88  	return path + "." + name
    89  }
    90  
    91  // An object implements the common parts of an Object.
    92  type object struct {
    93  	parent    *Scope
    94  	pos       syntax.Pos
    95  	pkg       *Package
    96  	name      string
    97  	typ       Type
    98  	order_    uint32
    99  	scopePos_ syntax.Pos
   100  }
   101  
   102  // Parent returns the scope in which the object is declared.
   103  // The result is nil for methods and struct fields.
   104  func (obj *object) Parent() *Scope { return obj.parent }
   105  
   106  // Pos returns the declaration position of the object's identifier.
   107  func (obj *object) Pos() syntax.Pos { return obj.pos }
   108  
   109  // Pkg returns the package to which the object belongs.
   110  // The result is nil for labels and objects in the Universe scope.
   111  func (obj *object) Pkg() *Package { return obj.pkg }
   112  
   113  // Name returns the object's (package-local, unqualified) name.
   114  func (obj *object) Name() string { return obj.name }
   115  
   116  // Type returns the object's type.
   117  func (obj *object) Type() Type { return obj.typ }
   118  
   119  // Exported reports whether the object is exported (starts with a capital letter).
   120  // It doesn't take into account whether the object is in a local (function) scope
   121  // or not.
   122  func (obj *object) Exported() bool { return isExported(obj.name) }
   123  
   124  // Id is a wrapper for Id(obj.Pkg(), obj.Name()).
   125  func (obj *object) Id() string { return Id(obj.pkg, obj.name) }
   126  
   127  func (obj *object) String() string       { panic("abstract") }
   128  func (obj *object) order() uint32        { return obj.order_ }
   129  func (obj *object) scopePos() syntax.Pos { return obj.scopePos_ }
   130  
   131  func (obj *object) setParent(parent *Scope)    { obj.parent = parent }
   132  func (obj *object) setType(typ Type)           { obj.typ = typ }
   133  func (obj *object) setOrder(order uint32)      { assert(order > 0); obj.order_ = order }
   134  func (obj *object) setScopePos(pos syntax.Pos) { obj.scopePos_ = pos }
   135  
   136  func (obj *object) sameId(pkg *Package, name string, foldCase bool) bool {
   137  	// If we don't care about capitalization, we also ignore packages.
   138  	if foldCase && strings.EqualFold(obj.name, name) {
   139  		return true
   140  	}
   141  	// spec:
   142  	// "Two identifiers are different if they are spelled differently,
   143  	// or if they appear in different packages and are not exported.
   144  	// Otherwise, they are the same."
   145  	if obj.name != name {
   146  		return false
   147  	}
   148  	// obj.Name == name
   149  	if obj.Exported() {
   150  		return true
   151  	}
   152  	// not exported, so packages must be the same
   153  	return samePkg(obj.pkg, pkg)
   154  }
   155  
   156  // cmp reports whether object a is ordered before object b.
   157  // cmp returns:
   158  //
   159  //	-1 if a is before b
   160  //	 0 if a is equivalent to b
   161  //	+1 if a is behind b
   162  //
   163  // Objects are ordered nil before non-nil, exported before
   164  // non-exported, then by name, and finally (for non-exported
   165  // functions) by package path.
   166  func (a *object) cmp(b *object) int {
   167  	if a == b {
   168  		return 0
   169  	}
   170  
   171  	// Nil before non-nil.
   172  	if a == nil {
   173  		return -1
   174  	}
   175  	if b == nil {
   176  		return +1
   177  	}
   178  
   179  	// Exported functions before non-exported.
   180  	ea := isExported(a.name)
   181  	eb := isExported(b.name)
   182  	if ea != eb {
   183  		if ea {
   184  			return -1
   185  		}
   186  		return +1
   187  	}
   188  
   189  	// Order by name and then (for non-exported names) by package.
   190  	if a.name != b.name {
   191  		return strings.Compare(a.name, b.name)
   192  	}
   193  	if !ea {
   194  		return strings.Compare(a.pkg.path, b.pkg.path)
   195  	}
   196  
   197  	return 0
   198  }
   199  
   200  // A PkgName represents an imported Go package.
   201  // PkgNames don't have a type.
   202  type PkgName struct {
   203  	object
   204  	imported *Package
   205  }
   206  
   207  // NewPkgName returns a new PkgName object representing an imported package.
   208  // The remaining arguments set the attributes found with all Objects.
   209  func NewPkgName(pos syntax.Pos, pkg *Package, name string, imported *Package) *PkgName {
   210  	return &PkgName{object{nil, pos, pkg, name, Typ[Invalid], 0, nopos}, imported}
   211  }
   212  
   213  // Imported returns the package that was imported.
   214  // It is distinct from Pkg(), which is the package containing the import statement.
   215  func (obj *PkgName) Imported() *Package { return obj.imported }
   216  
   217  // A Const represents a declared constant.
   218  type Const struct {
   219  	object
   220  	val constant.Value
   221  }
   222  
   223  // NewConst returns a new constant with value val.
   224  // The remaining arguments set the attributes found with all Objects.
   225  func NewConst(pos syntax.Pos, pkg *Package, name string, typ Type, val constant.Value) *Const {
   226  	return &Const{object{nil, pos, pkg, name, typ, 0, nopos}, val}
   227  }
   228  
   229  // Val returns the constant's value.
   230  func (obj *Const) Val() constant.Value { return obj.val }
   231  
   232  func (*Const) isDependency() {} // a constant may be a dependency of an initialization expression
   233  
   234  // A TypeName is an [Object] that represents a type with a name:
   235  // a defined type ([Named]),
   236  // an alias type ([Alias]),
   237  // a type parameter ([TypeParam]),
   238  // or a predeclared type such as int or error.
   239  type TypeName struct {
   240  	object
   241  }
   242  
   243  // NewTypeName returns a new type name denoting the given typ.
   244  // The remaining arguments set the attributes found with all Objects.
   245  //
   246  // The typ argument may be a defined (Named) type or an alias type.
   247  // It may also be nil such that the returned TypeName can be used as
   248  // argument for NewNamed, which will set the TypeName's type as a side-
   249  // effect.
   250  func NewTypeName(pos syntax.Pos, pkg *Package, name string, typ Type) *TypeName {
   251  	return &TypeName{object{nil, pos, pkg, name, typ, 0, nopos}}
   252  }
   253  
   254  // NewTypeNameLazy returns a new defined type like NewTypeName, but it
   255  // lazily calls unpack to finish constructing the Named object.
   256  func NewTypeNameLazy(pos syntax.Pos, pkg *Package, name string, load func(*Named) ([]*TypeParam, Type, []*Func, []func())) *TypeName {
   257  	obj := NewTypeName(pos, pkg, name, nil)
   258  	n := (*Checker)(nil).newNamed(obj, nil, nil)
   259  	n.loader = load
   260  	return obj
   261  }
   262  
   263  // IsAlias reports whether obj is an alias name for a type.
   264  func (obj *TypeName) IsAlias() bool {
   265  	switch t := obj.typ.(type) {
   266  	case nil:
   267  		return false
   268  	// case *Alias:
   269  	//	handled by default case
   270  	case *Basic:
   271  		// unsafe.Pointer is not an alias.
   272  		if obj.pkg == Unsafe {
   273  			return false
   274  		}
   275  		// Any user-defined type name for a basic type is an alias for a
   276  		// basic type (because basic types are pre-declared in the Universe
   277  		// scope, outside any package scope), and so is any type name with
   278  		// a different name than the name of the basic type it refers to.
   279  		// Additionally, we need to look for "byte" and "rune" because they
   280  		// are aliases but have the same names (for better error messages).
   281  		return obj.pkg != nil || t.name != obj.name || t == universeByte || t == universeRune
   282  	case *Named:
   283  		return obj != t.obj
   284  	case *TypeParam:
   285  		return obj != t.obj
   286  	default:
   287  		return true
   288  	}
   289  }
   290  
   291  // A Var represents a declared variable (including function parameters and results, and struct fields).
   292  type Var struct {
   293  	object
   294  	origin   *Var // if non-nil, the Var from which this one was instantiated
   295  	kind     VarKind
   296  	embedded bool // if set, the variable is an embedded struct field, and name is the type name
   297  }
   298  
   299  // A VarKind discriminates the various kinds of variables.
   300  type VarKind uint8
   301  
   302  const (
   303  	_          VarKind = iota // (not meaningful)
   304  	PackageVar                // a package-level variable
   305  	LocalVar                  // a local variable
   306  	RecvVar                   // a method receiver variable
   307  	ParamVar                  // a function parameter variable
   308  	ResultVar                 // a function result variable
   309  	FieldVar                  // a struct field
   310  )
   311  
   312  var varKindNames = [...]string{
   313  	0:          "VarKind(0)",
   314  	PackageVar: "PackageVar",
   315  	LocalVar:   "LocalVar",
   316  	RecvVar:    "RecvVar",
   317  	ParamVar:   "ParamVar",
   318  	ResultVar:  "ResultVar",
   319  	FieldVar:   "FieldVar",
   320  }
   321  
   322  func (kind VarKind) String() string {
   323  	if 0 <= kind && int(kind) < len(varKindNames) {
   324  		return varKindNames[kind]
   325  	}
   326  	return fmt.Sprintf("VarKind(%d)", kind)
   327  }
   328  
   329  // Kind reports what kind of variable v is.
   330  func (v *Var) Kind() VarKind { return v.kind }
   331  
   332  // SetKind sets the kind of the variable.
   333  // It should be used only immediately after [NewVar] or [NewParam].
   334  func (v *Var) SetKind(kind VarKind) { v.kind = kind }
   335  
   336  // NewVar returns a new variable.
   337  // The arguments set the attributes found with all Objects.
   338  //
   339  // The caller must subsequently call [Var.SetKind]
   340  // if the desired Var is not of kind [PackageVar].
   341  func NewVar(pos syntax.Pos, pkg *Package, name string, typ Type) *Var {
   342  	return newVar(PackageVar, pos, pkg, name, typ)
   343  }
   344  
   345  // NewParam returns a new variable representing a function parameter.
   346  //
   347  // The caller must subsequently call [Var.SetKind] if the desired Var
   348  // is not of kind [ParamVar]: for example, [RecvVar] or [ResultVar].
   349  func NewParam(pos syntax.Pos, pkg *Package, name string, typ Type) *Var {
   350  	return newVar(ParamVar, pos, pkg, name, typ)
   351  }
   352  
   353  // NewField returns a new variable representing a struct field.
   354  // For embedded fields, the name is the unqualified type name
   355  // under which the field is accessible.
   356  func NewField(pos syntax.Pos, pkg *Package, name string, typ Type, embedded bool) *Var {
   357  	v := newVar(FieldVar, pos, pkg, name, typ)
   358  	v.embedded = embedded
   359  	return v
   360  }
   361  
   362  // newVar returns a new variable.
   363  // The arguments set the attributes found with all Objects.
   364  func newVar(kind VarKind, pos syntax.Pos, pkg *Package, name string, typ Type) *Var {
   365  	return &Var{object: object{nil, pos, pkg, name, typ, 0, nopos}, kind: kind}
   366  }
   367  
   368  // Anonymous reports whether the variable is an embedded field.
   369  // Same as Embedded; only present for backward-compatibility.
   370  func (obj *Var) Anonymous() bool { return obj.embedded }
   371  
   372  // Embedded reports whether the variable is an embedded field.
   373  func (obj *Var) Embedded() bool { return obj.embedded }
   374  
   375  // IsField reports whether the variable is a struct field.
   376  func (obj *Var) IsField() bool { return obj.kind == FieldVar }
   377  
   378  // Origin returns the canonical Var for its receiver, i.e. the Var object
   379  // recorded in Info.Defs.
   380  //
   381  // For synthetic Vars created during instantiation (such as struct fields or
   382  // function parameters that depend on type arguments), this will be the
   383  // corresponding Var on the generic (uninstantiated) type. For all other Vars
   384  // Origin returns the receiver.
   385  func (obj *Var) Origin() *Var {
   386  	if obj.origin != nil {
   387  		return obj.origin
   388  	}
   389  	return obj
   390  }
   391  
   392  func (*Var) isDependency() {} // a variable may be a dependency of an initialization expression
   393  
   394  // A Func represents a declared function, concrete method, or abstract
   395  // (interface) method. Its Type() is always a *Signature.
   396  // An abstract method may belong to many interfaces due to embedding.
   397  type Func struct {
   398  	object
   399  	origin      *Func // if non-nil, the Func from which this one was instantiated
   400  	hasPtrRecv_ bool  // only valid for methods that don't have a type yet; use hasPtrRecv() to read
   401  	nointerface bool
   402  }
   403  
   404  // NewFunc returns a new function with the given signature, representing
   405  // the function's type.
   406  func NewFunc(pos syntax.Pos, pkg *Package, name string, sig *Signature) *Func {
   407  	var typ Type
   408  	if sig != nil {
   409  		typ = sig
   410  	} else {
   411  		// Don't store a (typed) nil *Signature.
   412  		// We can't simply replace it with new(Signature) either,
   413  		// as this would violate object.{Type,color} invariants.
   414  		// TODO(adonovan): propose to disallow NewFunc with nil *Signature.
   415  	}
   416  	return &Func{object{nil, pos, pkg, name, typ, 0, nopos}, nil, false, false}
   417  }
   418  
   419  // Signature returns the signature (type) of the function or method.
   420  func (obj *Func) Signature() *Signature {
   421  	if obj.typ != nil {
   422  		return obj.typ.(*Signature) // normal case
   423  	}
   424  	// No signature: Signature was called either:
   425  	// - within go/types, before a FuncDecl's initially
   426  	//   nil Func.Type was lazily populated, indicating
   427  	//   a types bug; or
   428  	// - by a client after NewFunc(..., nil),
   429  	//   which is arguably a client bug, but we need a
   430  	//   proposal to tighten NewFunc's precondition.
   431  	// For now, return a trivial signature.
   432  	return new(Signature)
   433  }
   434  
   435  // FullName returns the package- or receiver-type-qualified name of
   436  // function or method obj.
   437  func (obj *Func) FullName() string {
   438  	var buf bytes.Buffer
   439  	writeFuncName(&buf, obj, nil)
   440  	return buf.String()
   441  }
   442  
   443  // Scope returns the scope of the function's body block.
   444  // The result is nil for imported or instantiated functions and methods
   445  // (but there is also no mechanism to get to an instantiated function).
   446  func (obj *Func) Scope() *Scope { return obj.typ.(*Signature).scope }
   447  
   448  // Origin returns the canonical Func for its receiver, i.e. the Func object
   449  // recorded in Info.Defs.
   450  //
   451  // For synthetic functions created during instantiation (such as methods on an
   452  // instantiated Named type or interface methods that depend on type arguments),
   453  // this will be the corresponding Func on the generic (uninstantiated) type.
   454  // For all other Funcs Origin returns the receiver.
   455  func (obj *Func) Origin() *Func {
   456  	if obj.origin != nil {
   457  		return obj.origin
   458  	}
   459  	return obj
   460  }
   461  
   462  // Pkg returns the package to which the function belongs.
   463  //
   464  // The result is nil for methods of types in the Universe scope,
   465  // like method Error of the error built-in interface type.
   466  func (obj *Func) Pkg() *Package { return obj.object.Pkg() }
   467  
   468  // hasPtrRecv reports whether the receiver is of the form *T for the given method obj.
   469  func (obj *Func) hasPtrRecv() bool {
   470  	// If a method's receiver type is set, use that as the source of truth for the receiver.
   471  	// Caution: Checker.funcDecl (decl.go) marks a function by setting its type to an empty
   472  	// signature. We may reach here before the signature is fully set up: we must explicitly
   473  	// check if the receiver is set (we cannot just look for non-nil obj.typ).
   474  	if sig, _ := obj.typ.(*Signature); sig != nil && sig.recv != nil {
   475  		_, isPtr := deref(sig.recv.typ)
   476  		return isPtr
   477  	}
   478  
   479  	// If a method's type is not set it may be a method/function that is:
   480  	// 1) client-supplied (via NewFunc with no signature), or
   481  	// 2) internally created but not yet type-checked.
   482  	// For case 1) we can't do anything; the client must know what they are doing.
   483  	// For case 2) we can use the information gathered by the resolver.
   484  	return obj.hasPtrRecv_
   485  }
   486  
   487  func (*Func) isDependency() {} // a function may be a dependency of an initialization expression
   488  
   489  // A Label represents a declared label.
   490  // Labels don't have a type.
   491  type Label struct {
   492  	object
   493  	used bool // set if the label was used
   494  }
   495  
   496  // NewLabel returns a new label.
   497  func NewLabel(pos syntax.Pos, pkg *Package, name string) *Label {
   498  	return &Label{object{pos: pos, pkg: pkg, name: name, typ: Typ[Invalid]}, false}
   499  }
   500  
   501  // A Builtin represents a built-in function.
   502  // Builtins don't have a valid type.
   503  type Builtin struct {
   504  	object
   505  	id builtinId
   506  }
   507  
   508  func newBuiltin(id builtinId) *Builtin {
   509  	return &Builtin{object{name: predeclaredFuncs[id].name, typ: Typ[Invalid]}, id}
   510  }
   511  
   512  // Nil represents the predeclared value nil.
   513  type Nil struct {
   514  	object
   515  }
   516  
   517  func writeObject(buf *bytes.Buffer, obj Object, qf Qualifier) {
   518  	var tname *TypeName
   519  	typ := obj.Type()
   520  
   521  	switch obj := obj.(type) {
   522  	case *PkgName:
   523  		fmt.Fprintf(buf, "package %s", obj.Name())
   524  		if path := obj.imported.path; path != "" && path != obj.name {
   525  			fmt.Fprintf(buf, " (%q)", path)
   526  		}
   527  		return
   528  
   529  	case *Const:
   530  		buf.WriteString("const")
   531  
   532  	case *TypeName:
   533  		tname = obj
   534  		buf.WriteString("type")
   535  		if isTypeParam(typ) {
   536  			buf.WriteString(" parameter")
   537  		}
   538  
   539  	case *Var:
   540  		if obj.IsField() {
   541  			buf.WriteString("field")
   542  		} else {
   543  			buf.WriteString("var")
   544  		}
   545  
   546  	case *Func:
   547  		buf.WriteString("func ")
   548  		writeFuncName(buf, obj, qf)
   549  		if typ != nil {
   550  			WriteSignature(buf, typ.(*Signature), qf)
   551  		}
   552  		return
   553  
   554  	case *Label:
   555  		buf.WriteString("label")
   556  		typ = nil
   557  
   558  	case *Builtin:
   559  		buf.WriteString("builtin")
   560  		typ = nil
   561  
   562  	case *Nil:
   563  		buf.WriteString("nil")
   564  		return
   565  
   566  	default:
   567  		panic(fmt.Sprintf("writeObject(%T)", obj))
   568  	}
   569  
   570  	buf.WriteByte(' ')
   571  
   572  	// For package-level objects, qualify the name.
   573  	if obj.Pkg() != nil && obj.Pkg().scope.Lookup(obj.Name()) == obj {
   574  		buf.WriteString(packagePrefix(obj.Pkg(), qf))
   575  	}
   576  	buf.WriteString(obj.Name())
   577  
   578  	if typ == nil {
   579  		return
   580  	}
   581  
   582  	if tname != nil {
   583  		switch t := typ.(type) {
   584  		case *Basic:
   585  			// Don't print anything more for basic types since there's
   586  			// no more information.
   587  			return
   588  		case genericType:
   589  			if t.TypeParams().Len() > 0 {
   590  				newTypeWriter(buf, qf).tParamList(t.TypeParams().list())
   591  			}
   592  		}
   593  		if tname.IsAlias() {
   594  			buf.WriteString(" =")
   595  			if alias, ok := typ.(*Alias); ok { // materialized? TODO(gri) Do we still need this (e.g. for byte, rune)?
   596  				typ = alias.fromRHS
   597  			}
   598  		} else if t, _ := typ.(*TypeParam); t != nil {
   599  			typ = t.bound
   600  		} else {
   601  			// TODO(gri) should this be fromRHS for *Named?
   602  			// (See discussion in #66559.)
   603  			typ = typ.Underlying()
   604  		}
   605  	}
   606  
   607  	// Special handling for any: because WriteType will format 'any' as 'any',
   608  	// resulting in the object string `type any = any` rather than `type any =
   609  	// interface{}`. To avoid this, swap in a different empty interface.
   610  	if obj.Name() == "any" && obj.Parent() == Universe {
   611  		assert(Identical(typ, &emptyInterface))
   612  		typ = &emptyInterface
   613  	}
   614  
   615  	buf.WriteByte(' ')
   616  	WriteType(buf, typ, qf)
   617  }
   618  
   619  func packagePrefix(pkg *Package, qf Qualifier) string {
   620  	if pkg == nil {
   621  		return ""
   622  	}
   623  	var s string
   624  	if qf != nil {
   625  		s = qf(pkg)
   626  	} else {
   627  		s = pkg.Path()
   628  	}
   629  	if s != "" {
   630  		s += "."
   631  	}
   632  	return s
   633  }
   634  
   635  // ObjectString returns the string form of obj.
   636  // The Qualifier controls the printing of
   637  // package-level objects, and may be nil.
   638  func ObjectString(obj Object, qf Qualifier) string {
   639  	var buf bytes.Buffer
   640  	writeObject(&buf, obj, qf)
   641  	return buf.String()
   642  }
   643  
   644  func (obj *PkgName) String() string  { return ObjectString(obj, nil) }
   645  func (obj *Const) String() string    { return ObjectString(obj, nil) }
   646  func (obj *TypeName) String() string { return ObjectString(obj, nil) }
   647  func (obj *Var) String() string      { return ObjectString(obj, nil) }
   648  func (obj *Func) String() string     { return ObjectString(obj, nil) }
   649  func (obj *Label) String() string    { return ObjectString(obj, nil) }
   650  func (obj *Builtin) String() string  { return ObjectString(obj, nil) }
   651  func (obj *Nil) String() string      { return ObjectString(obj, nil) }
   652  
   653  func writeFuncName(buf *bytes.Buffer, f *Func, qf Qualifier) {
   654  	if f.typ != nil {
   655  		sig := f.typ.(*Signature)
   656  		if recv := sig.Recv(); recv != nil {
   657  			buf.WriteByte('(')
   658  			if _, ok := recv.Type().(*Interface); ok {
   659  				// gcimporter creates abstract methods of
   660  				// named interfaces using the interface type
   661  				// (not the named type) as the receiver.
   662  				// Don't print it in full.
   663  				buf.WriteString("interface")
   664  			} else {
   665  				WriteType(buf, recv.Type(), qf)
   666  			}
   667  			buf.WriteByte(')')
   668  			buf.WriteByte('.')
   669  		} else if f.pkg != nil {
   670  			buf.WriteString(packagePrefix(f.pkg, qf))
   671  		}
   672  	}
   673  	buf.WriteString(f.name)
   674  }
   675  
   676  // objectKind returns a description of the object's kind.
   677  func objectKind(obj Object) string {
   678  	switch obj := obj.(type) {
   679  	case *PkgName:
   680  		return "package name"
   681  	case *Const:
   682  		return "constant"
   683  	case *TypeName:
   684  		if obj.IsAlias() {
   685  			return "type alias"
   686  		} else if _, ok := obj.Type().(*TypeParam); ok {
   687  			return "type parameter"
   688  		} else {
   689  			return "defined type"
   690  		}
   691  	case *Var:
   692  		switch obj.Kind() {
   693  		case PackageVar:
   694  			return "package-level variable"
   695  		case LocalVar:
   696  			return "local variable"
   697  		case RecvVar:
   698  			return "receiver"
   699  		case ParamVar:
   700  			return "parameter"
   701  		case ResultVar:
   702  			return "result variable"
   703  		case FieldVar:
   704  			return "struct field"
   705  		}
   706  	case *Func:
   707  		if obj.Signature().Recv() != nil {
   708  			return "method"
   709  		} else {
   710  			return "function"
   711  		}
   712  	case *Label:
   713  		return "label"
   714  	case *Builtin:
   715  		return "built-in function"
   716  	case *Nil:
   717  		return "untyped nil"
   718  	}
   719  	if debug {
   720  		panic(fmt.Sprintf("unknown symbol (%T)", obj))
   721  	}
   722  	return "unknown symbol"
   723  }
   724  

View as plain text