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