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

View as plain text