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