Help us shape the future of Go! Take the 2026 Go Developer Survey

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

View as plain text