]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/object.go
[dev.typeparams] merge dev.regabi (618e3c1) into dev.typeparams
[gostls13.git] / src / cmd / compile / internal / types2 / object.go
1 // UNREVIEWED
2 // Copyright 2013 The Go Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
5
6 package types2
7
8 import (
9         "bytes"
10         "cmd/compile/internal/syntax"
11         "fmt"
12         "go/constant"
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.
20 //
21 type Object interface {
22         Parent() *Scope  // scope in which this object is declared; nil for methods and struct fields
23         Pos() syntax.Pos // position of object identifier in declaration
24         Pkg() *Package   // package to which this object belongs; nil for labels and objects in the Universe scope
25         Name() string    // package local object name
26         Type() Type      // object type
27         Exported() bool  // reports whether the name starts with a capital letter
28         Id() string      // object name if exported, qualified name if not exported (see func Id)
29
30         // String returns a human-readable string of the object.
31         String() string
32
33         // order reflects a package-level object's source order: if object
34         // a is before object b in the source, then a.order() < b.order().
35         // order returns a value > 0 for package-level objects; it returns
36         // 0 for all other objects (including objects in file scopes).
37         order() uint32
38
39         // color returns the object's color.
40         color() color
41
42         // setType sets the type of the object.
43         setType(Type)
44
45         // setOrder sets the order number of the object. It must be > 0.
46         setOrder(uint32)
47
48         // setColor sets the object's color. It must not be white.
49         setColor(color color)
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         sameId(pkg *Package, name string) bool
56
57         // scopePos returns the start position of the scope of this Object
58         scopePos() syntax.Pos
59
60         // setScopePos sets the start position of the scope for this Object.
61         setScopePos(pos syntax.Pos)
62 }
63
64 func isExported(name string) bool {
65         ch, _ := utf8.DecodeRuneInString(name)
66         return unicode.IsUpper(ch)
67 }
68
69 // Id returns name if it is exported, otherwise it
70 // returns the name qualified with the package path.
71 func Id(pkg *Package, name string) string {
72         if isExported(name) {
73                 return name
74         }
75         // unexported names need the package path for differentiation
76         // (if there's no package, make sure we don't start with '.'
77         // as that may change the order of methods between a setup
78         // inside a package and outside a package - which breaks some
79         // tests)
80         path := "_"
81         // pkg is nil for objects in Universe scope and possibly types
82         // introduced via Eval (see also comment in object.sameId)
83         if pkg != nil && pkg.path != "" {
84                 path = pkg.path
85         }
86         return path + "." + name
87 }
88
89 // An object implements the common parts of an Object.
90 type object struct {
91         parent    *Scope
92         pos       syntax.Pos
93         pkg       *Package
94         name      string
95         typ       Type
96         order_    uint32
97         color_    color
98         scopePos_ syntax.Pos
99 }
100
101 // color encodes the color of an object (see Checker.objDecl for details).
102 type color uint32
103
104 // An object may be painted in one of three colors.
105 // Color values other than white or black are considered grey.
106 const (
107         white color = iota
108         black
109         grey // must be > white and black
110 )
111
112 func (c color) String() string {
113         switch c {
114         case white:
115                 return "white"
116         case black:
117                 return "black"
118         default:
119                 return "grey"
120         }
121 }
122
123 // colorFor returns the (initial) color for an object depending on
124 // whether its type t is known or not.
125 func colorFor(t Type) color {
126         if t != nil {
127                 return black
128         }
129         return white
130 }
131
132 // Parent returns the scope in which the object is declared.
133 // The result is nil for methods and struct fields.
134 func (obj *object) Parent() *Scope { return obj.parent }
135
136 // Pos returns the declaration position of the object's identifier.
137 func (obj *object) Pos() syntax.Pos { return obj.pos }
138
139 // Pkg returns the package to which the object belongs.
140 // The result is nil for labels and objects in the Universe scope.
141 func (obj *object) Pkg() *Package { return obj.pkg }
142
143 // Name returns the object's (package-local, unqualified) name.
144 func (obj *object) Name() string { return obj.name }
145
146 // Type returns the object's type.
147 func (obj *object) Type() Type { return obj.typ }
148
149 // Exported reports whether the object is exported (starts with a capital letter).
150 // It doesn't take into account whether the object is in a local (function) scope
151 // or not.
152 func (obj *object) Exported() bool { return isExported(obj.name) }
153
154 // Id is a wrapper for Id(obj.Pkg(), obj.Name()).
155 func (obj *object) Id() string { return Id(obj.pkg, obj.name) }
156
157 func (obj *object) String() string       { panic("abstract") }
158 func (obj *object) order() uint32        { return obj.order_ }
159 func (obj *object) color() color         { return obj.color_ }
160 func (obj *object) scopePos() syntax.Pos { return obj.scopePos_ }
161
162 func (obj *object) setParent(parent *Scope)    { obj.parent = parent }
163 func (obj *object) setType(typ Type)           { obj.typ = typ }
164 func (obj *object) setOrder(order uint32)      { assert(order > 0); obj.order_ = order }
165 func (obj *object) setColor(color color)       { assert(color != white); obj.color_ = color }
166 func (obj *object) setScopePos(pos syntax.Pos) { obj.scopePos_ = pos }
167
168 func (obj *object) sameId(pkg *Package, name string) bool {
169         // spec:
170         // "Two identifiers are different if they are spelled differently,
171         // or if they appear in different packages and are not exported.
172         // Otherwise, they are the same."
173         if name != obj.name {
174                 return false
175         }
176         // obj.Name == name
177         if obj.Exported() {
178                 return true
179         }
180         // not exported, so packages must be the same (pkg == nil for
181         // fields in Universe scope; this can only happen for types
182         // introduced via Eval)
183         if pkg == nil || obj.pkg == nil {
184                 return pkg == obj.pkg
185         }
186         // pkg != nil && obj.pkg != nil
187         return pkg.path == obj.pkg.path
188 }
189
190 // A PkgName represents an imported Go package.
191 // PkgNames don't have a type.
192 type PkgName struct {
193         object
194         imported *Package
195         used     bool // set if the package was used
196 }
197
198 // NewPkgName returns a new PkgName object representing an imported package.
199 // The remaining arguments set the attributes found with all Objects.
200 func NewPkgName(pos syntax.Pos, pkg *Package, name string, imported *Package) *PkgName {
201         return &PkgName{object{nil, pos, pkg, name, Typ[Invalid], 0, black, nopos}, imported, false}
202 }
203
204 // Imported returns the package that was imported.
205 // It is distinct from Pkg(), which is the package containing the import statement.
206 func (obj *PkgName) Imported() *Package { return obj.imported }
207
208 // A Const represents a declared constant.
209 type Const struct {
210         object
211         val constant.Value
212 }
213
214 // NewConst returns a new constant with value val.
215 // The remaining arguments set the attributes found with all Objects.
216 func NewConst(pos syntax.Pos, pkg *Package, name string, typ Type, val constant.Value) *Const {
217         return &Const{object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}, val}
218 }
219
220 // Val returns the constant's value.
221 func (obj *Const) Val() constant.Value { return obj.val }
222
223 func (*Const) isDependency() {} // a constant may be a dependency of an initialization expression
224
225 // A TypeName represents a name for a (defined or alias) type.
226 type TypeName struct {
227         object
228 }
229
230 // NewTypeName returns a new type name denoting the given typ.
231 // The remaining arguments set the attributes found with all Objects.
232 //
233 // The typ argument may be a defined (Named) type or an alias type.
234 // It may also be nil such that the returned TypeName can be used as
235 // argument for NewNamed, which will set the TypeName's type as a side-
236 // effect.
237 func NewTypeName(pos syntax.Pos, pkg *Package, name string, typ Type) *TypeName {
238         return &TypeName{object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}}
239 }
240
241 // IsAlias reports whether obj is an alias name for a type.
242 func (obj *TypeName) IsAlias() bool {
243         switch t := obj.typ.(type) {
244         case nil:
245                 return false
246         case *Basic:
247                 // unsafe.Pointer is not an alias.
248                 if obj.pkg == Unsafe {
249                         return false
250                 }
251                 // Any user-defined type name for a basic type is an alias for a
252                 // basic type (because basic types are pre-declared in the Universe
253                 // scope, outside any package scope), and so is any type name with
254                 // a different name than the name of the basic type it refers to.
255                 // Additionally, we need to look for "byte" and "rune" because they
256                 // are aliases but have the same names (for better error messages).
257                 return obj.pkg != nil || t.name != obj.name || t == universeByte || t == universeRune
258         case *Named:
259                 return obj != t.obj
260         default:
261                 return true
262         }
263 }
264
265 // A Variable represents a declared variable (including function parameters and results, and struct fields).
266 type Var struct {
267         object
268         embedded bool // if set, the variable is an embedded struct field, and name is the type name
269         isField  bool // var is struct field
270         used     bool // set if the variable was used
271 }
272
273 // NewVar returns a new variable.
274 // The arguments set the attributes found with all Objects.
275 func NewVar(pos syntax.Pos, pkg *Package, name string, typ Type) *Var {
276         return &Var{object: object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}}
277 }
278
279 // NewParam returns a new variable representing a function parameter.
280 func NewParam(pos syntax.Pos, pkg *Package, name string, typ Type) *Var {
281         return &Var{object: object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}, used: true} // parameters are always 'used'
282 }
283
284 // NewField returns a new variable representing a struct field.
285 // For embedded fields, the name is the unqualified type name
286 /// under which the field is accessible.
287 func NewField(pos syntax.Pos, pkg *Package, name string, typ Type, embedded bool) *Var {
288         return &Var{object: object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}, embedded: embedded, isField: true}
289 }
290
291 // Anonymous reports whether the variable is an embedded field.
292 // Same as Embedded; only present for backward-compatibility.
293 func (obj *Var) Anonymous() bool { return obj.embedded }
294
295 // Embedded reports whether the variable is an embedded field.
296 func (obj *Var) Embedded() bool { return obj.embedded }
297
298 // IsField reports whether the variable is a struct field.
299 func (obj *Var) IsField() bool { return obj.isField }
300
301 func (*Var) isDependency() {} // a variable may be a dependency of an initialization expression
302
303 // A Func represents a declared function, concrete method, or abstract
304 // (interface) method. Its Type() is always a *Signature.
305 // An abstract method may belong to many interfaces due to embedding.
306 type Func struct {
307         object
308         hasPtrRecv bool // only valid for methods that don't have a type yet
309 }
310
311 // NewFunc returns a new function with the given signature, representing
312 // the function's type.
313 func NewFunc(pos syntax.Pos, pkg *Package, name string, sig *Signature) *Func {
314         // don't store a (typed) nil signature
315         var typ Type
316         if sig != nil {
317                 typ = sig
318         }
319         return &Func{object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}, false}
320 }
321
322 // FullName returns the package- or receiver-type-qualified name of
323 // function or method obj.
324 func (obj *Func) FullName() string {
325         var buf bytes.Buffer
326         writeFuncName(&buf, obj, nil)
327         return buf.String()
328 }
329
330 // Scope returns the scope of the function's body block.
331 func (obj *Func) Scope() *Scope { return obj.typ.(*Signature).scope }
332
333 // Less reports whether function a is ordered before function b.
334 //
335 // Functions are ordered exported before non-exported, then by name,
336 // and finally (for non-exported functions) by package path.
337 //
338 // TODO(gri) The compiler also sorts by package height before package
339 //           path for non-exported names.
340 func (a *Func) less(b *Func) bool {
341         if a == b {
342                 return false
343         }
344
345         // Exported functions before non-exported.
346         ea := isExported(a.name)
347         eb := isExported(b.name)
348         if ea != eb {
349                 return ea
350         }
351
352         // Order by name and then (for non-exported names) by package.
353         if a.name != b.name {
354                 return a.name < b.name
355         }
356         if !ea {
357                 return a.pkg.path < b.pkg.path
358         }
359
360         return false
361 }
362
363 func (*Func) isDependency() {} // a function may be a dependency of an initialization expression
364
365 // A Label represents a declared label.
366 // Labels don't have a type.
367 type Label struct {
368         object
369         used bool // set if the label was used
370 }
371
372 // NewLabel returns a new label.
373 func NewLabel(pos syntax.Pos, pkg *Package, name string) *Label {
374         return &Label{object{pos: pos, pkg: pkg, name: name, typ: Typ[Invalid], color_: black}, false}
375 }
376
377 // A Builtin represents a built-in function.
378 // Builtins don't have a valid type.
379 type Builtin struct {
380         object
381         id builtinId
382 }
383
384 func newBuiltin(id builtinId) *Builtin {
385         return &Builtin{object{name: predeclaredFuncs[id].name, typ: Typ[Invalid], color_: black}, id}
386 }
387
388 // Nil represents the predeclared value nil.
389 type Nil struct {
390         object
391 }
392
393 func writeObject(buf *bytes.Buffer, obj Object, qf Qualifier) {
394         var tname *TypeName
395         typ := obj.Type()
396
397         switch obj := obj.(type) {
398         case *PkgName:
399                 fmt.Fprintf(buf, "package %s", obj.Name())
400                 if path := obj.imported.path; path != "" && path != obj.name {
401                         fmt.Fprintf(buf, " (%q)", path)
402                 }
403                 return
404
405         case *Const:
406                 buf.WriteString("const")
407
408         case *TypeName:
409                 tname = obj
410                 buf.WriteString("type")
411
412         case *Var:
413                 if obj.isField {
414                         buf.WriteString("field")
415                 } else {
416                         buf.WriteString("var")
417                 }
418
419         case *Func:
420                 buf.WriteString("func ")
421                 writeFuncName(buf, obj, qf)
422                 if typ != nil {
423                         WriteSignature(buf, typ.(*Signature), qf)
424                 }
425                 return
426
427         case *Label:
428                 buf.WriteString("label")
429                 typ = nil
430
431         case *Builtin:
432                 buf.WriteString("builtin")
433                 typ = nil
434
435         case *Nil:
436                 buf.WriteString("nil")
437                 return
438
439         default:
440                 panic(fmt.Sprintf("writeObject(%T)", obj))
441         }
442
443         buf.WriteByte(' ')
444
445         // For package-level objects, qualify the name.
446         if obj.Pkg() != nil && obj.Pkg().scope.Lookup(obj.Name()) == obj {
447                 writePackage(buf, obj.Pkg(), qf)
448         }
449         buf.WriteString(obj.Name())
450
451         if typ == nil {
452                 return
453         }
454
455         if tname != nil {
456                 // We have a type object: Don't print anything more for
457                 // basic types since there's no more information (names
458                 // are the same; see also comment in TypeName.IsAlias).
459                 if _, ok := typ.(*Basic); ok {
460                         return
461                 }
462                 if tname.IsAlias() {
463                         buf.WriteString(" =")
464                 } else {
465                         typ = typ.Under()
466                 }
467         }
468
469         buf.WriteByte(' ')
470         WriteType(buf, typ, qf)
471 }
472
473 func writePackage(buf *bytes.Buffer, pkg *Package, qf Qualifier) {
474         if pkg == nil {
475                 return
476         }
477         var s string
478         if qf != nil {
479                 s = qf(pkg)
480         } else {
481                 s = pkg.Path()
482         }
483         if s != "" {
484                 buf.WriteString(s)
485                 buf.WriteByte('.')
486         }
487 }
488
489 // ObjectString returns the string form of obj.
490 // The Qualifier controls the printing of
491 // package-level objects, and may be nil.
492 func ObjectString(obj Object, qf Qualifier) string {
493         var buf bytes.Buffer
494         writeObject(&buf, obj, qf)
495         return buf.String()
496 }
497
498 func (obj *PkgName) String() string  { return ObjectString(obj, nil) }
499 func (obj *Const) String() string    { return ObjectString(obj, nil) }
500 func (obj *TypeName) String() string { return ObjectString(obj, nil) }
501 func (obj *Var) String() string      { return ObjectString(obj, nil) }
502 func (obj *Func) String() string     { return ObjectString(obj, nil) }
503 func (obj *Label) String() string    { return ObjectString(obj, nil) }
504 func (obj *Builtin) String() string  { return ObjectString(obj, nil) }
505 func (obj *Nil) String() string      { return ObjectString(obj, nil) }
506
507 func writeFuncName(buf *bytes.Buffer, f *Func, qf Qualifier) {
508         if f.typ != nil {
509                 sig := f.typ.(*Signature)
510                 if recv := sig.Recv(); recv != nil {
511                         buf.WriteByte('(')
512                         if _, ok := recv.Type().(*Interface); ok {
513                                 // gcimporter creates abstract methods of
514                                 // named interfaces using the interface type
515                                 // (not the named type) as the receiver.
516                                 // Don't print it in full.
517                                 buf.WriteString("interface")
518                         } else {
519                                 WriteType(buf, recv.Type(), qf)
520                         }
521                         buf.WriteByte(')')
522                         buf.WriteByte('.')
523                 } else if f.pkg != nil {
524                         writePackage(buf, f.pkg, qf)
525                 }
526         }
527         buf.WriteString(f.name)
528 }