Debian Codegraph @

src/cmd/compile/internal/types2/universe.go

raw
1 // Copyright 2011 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 // This file sets up the universe scope and the unsafe package.
6
7 package types2
8
9 import (
10 "go/constant"
11 "strings"
12 )
13
14 // The Universe scope contains all predeclared objects of Go.
15 // It is the outermost scope of any chain of nested scopes.
16 var Universe *Scope
17
18 // The Unsafe package is the package returned by an importer
19 // for the import path "unsafe".
20 var Unsafe *Package
21
22 var (
23 universeIota Object
24 universeBool Type
25 universeByte Type // uint8 alias, but has name "byte"
26 universeRune Type // int32 alias, but has name "rune"
27 universeAnyNoAlias *TypeName
28 universeAnyAlias *TypeName
29 universeError Type
30 universeComparable Object
31 )
32
33 // Typ contains the predeclared *Basic types indexed by their
34 // corresponding BasicKind.
35 //
36 // The *Basic type for Typ[Byte] will have the name "uint8".
37 // Use Universe.Lookup("byte").Type() to obtain the specific
38 // alias basic type named "byte" (and analogous for "rune").
39 var Typ = [...]*Basic{
40 Invalid: {Invalid, 0, "invalid type"},
41
42 Bool: {Bool, IsBoolean, "bool"},
43 Int: {Int, IsInteger, "int"},
44 Int8: {Int8, IsInteger, "int8"},
45 Int16: {Int16, IsInteger, "int16"},
46 Int32: {Int32, IsInteger, "int32"},
47 Int64: {Int64, IsInteger, "int64"},
48 Uint: {Uint, IsInteger | IsUnsigned, "uint"},
49 Uint8: {Uint8, IsInteger | IsUnsigned, "uint8"},
50 Uint16: {Uint16, IsInteger | IsUnsigned, "uint16"},
51 Uint32: {Uint32, IsInteger | IsUnsigned, "uint32"},
52 Uint64: {Uint64, IsInteger | IsUnsigned, "uint64"},
53 Uintptr: {Uintptr, IsInteger | IsUnsigned, "uintptr"},
54 Float32: {Float32, IsFloat, "float32"},
55 Float64: {Float64, IsFloat, "float64"},
56 Complex64: {Complex64, IsComplex, "complex64"},
57 Complex128: {Complex128, IsComplex, "complex128"},
58 String: {String, IsString, "string"},
59 UnsafePointer: {UnsafePointer, 0, "Pointer"},
60
61 UntypedBool: {UntypedBool, IsBoolean | IsUntyped, "untyped bool"},
62 UntypedInt: {UntypedInt, IsInteger | IsUntyped, "untyped int"},
63 UntypedRune: {UntypedRune, IsInteger | IsUntyped, "untyped rune"},
64 UntypedFloat: {UntypedFloat, IsFloat | IsUntyped, "untyped float"},
65 UntypedComplex: {UntypedComplex, IsComplex | IsUntyped, "untyped complex"},
66 UntypedString: {UntypedString, IsString | IsUntyped, "untyped string"},
67 UntypedNil: {UntypedNil, IsUntyped, "untyped nil"},
68 }
69
70 var basicAliases = [...]*Basic{
71 {Byte, IsInteger | IsUnsigned, "byte"},
72 {Rune, IsInteger, "rune"},
73 }
74
75 func defPredeclaredTypes() {
76 for _, t := range Typ {
77 def(NewTypeName(nopos, nil, t.name, t))
78 }
79 for _, t := range basicAliases {
80 def(NewTypeName(nopos, nil, t.name, t))
81 }
82
83 // type any = interface{}
84 //
85 // Implement two representations of any: one for the legacy gotypesalias=0,
86 // and one for gotypesalias=1. This is necessary for consistent
87 // representation of interface aliases during type checking, and is
88 // implemented via hijacking [Scope.Lookup] for the [Universe] scope.
89 //
90 // Both representations use the same distinguished pointer for their RHS
91 // interface type, allowing us to detect any (even with the legacy
92 // representation), and format it as "any" rather than interface{}, which
93 // clarifies user-facing error messages significantly.
94 //
95 // TODO(rfindley): once the gotypesalias GODEBUG variable is obsolete (and we
96 // consistently use the Alias node), we should be able to clarify user facing
97 // error messages without using a distinguished pointer for the any
98 // interface.
99 {
100 universeAnyNoAlias = NewTypeName(nopos, nil, "any", &Interface{complete: true, tset: &topTypeSet})
101 universeAnyNoAlias.setColor(black)
102 // ensure that the any TypeName reports a consistent Parent, after
103 // hijacking Universe.Lookup with gotypesalias=0.
104 universeAnyNoAlias.setParent(Universe)
105
106 // It shouldn't matter which representation of any is actually inserted
107 // into the Universe, but we lean toward the future and insert the Alias
108 // representation.
109 universeAnyAlias = NewTypeName(nopos, nil, "any", nil)
110 universeAnyAlias.setColor(black)
111 _ = NewAlias(universeAnyAlias, universeAnyNoAlias.Type().Underlying()) // Link TypeName and Alias
112 def(universeAnyAlias)
113 }
114
115 // type error interface{ Error() string }
116 {
117 obj := NewTypeName(nopos, nil, "error", nil)
118 obj.setColor(black)
119 typ := NewNamed(obj, nil, nil)
120
121 // error.Error() string
122 recv := newVar(RecvVar, nopos, nil, "", typ)
123 res := newVar(ResultVar, nopos, nil, "", Typ[String])
124 sig := NewSignatureType(recv, nil, nil, nil, NewTuple(res), false)
125 err := NewFunc(nopos, nil, "Error", sig)
126
127 // interface{ Error() string }
128 ityp := &Interface{methods: []*Func{err}, complete: true}
129 computeInterfaceTypeSet(nil, nopos, ityp) // prevent races due to lazy computation of tset
130
131 typ.SetUnderlying(ityp)
132 def(obj)
133 }
134
135 // type comparable interface{} // marked as comparable
136 {
137 obj := NewTypeName(nopos, nil, "comparable", nil)
138 obj.setColor(black)
139 typ := NewNamed(obj, nil, nil)
140
141 // interface{} // marked as comparable
142 ityp := &Interface{complete: true, tset: &_TypeSet{nil, allTermlist, true}}
143
144 typ.SetUnderlying(ityp)
145 def(obj)
146 }
147 }
148
149 var predeclaredConsts = [...]struct {
150 name string
151 kind BasicKind
152 val constant.Value
153 }{
154 {"true", UntypedBool, constant.MakeBool(true)},
155 {"false", UntypedBool, constant.MakeBool(false)},
156 {"iota", UntypedInt, constant.MakeInt64(0)},
157 }
158
159 func defPredeclaredConsts() {
160 for _, c := range predeclaredConsts {
161 def(NewConst(nopos, nil, c.name, Typ[c.kind], c.val))
162 }
163 }
164
165 func defPredeclaredNil() {
166 def(&Nil{object{name: "nil", typ: Typ[UntypedNil], color_: black}})
167 }
168
169 // A builtinId is the id of a builtin function.
170 type builtinId int
171
172 const (
173 // universe scope
174 _Append builtinId = iota
175 _Cap
176 _Clear
177 _Close
178 _Complex
179 _Copy
180 _Delete
181 _Imag
182 _Len
183 _Make
184 _Max
185 _Min
186 _New
187 _Panic
188 _Print
189 _Println
190 _Real
191 _Recover
192
193 // package unsafe
194 _Add
195 _Alignof
196 _Offsetof
197 _Sizeof
198 _Slice
199 _SliceData
200 _String
201 _StringData
202
203 // testing support
204 _Assert
205 _Trace
206 )
207
208 var predeclaredFuncs = [...]struct {
209 name string
210 nargs int
211 variadic bool
212 kind exprKind
213 }{
214 _Append: {"append", 1, true, expression},
215 _Cap: {"cap", 1, false, expression},
216 _Clear: {"clear", 1, false, statement},
217 _Close: {"close", 1, false, statement},
218 _Complex: {"complex", 2, false, expression},
219 _Copy: {"copy", 2, false, statement},
220 _Delete: {"delete", 2, false, statement},
221 _Imag: {"imag", 1, false, expression},
222 _Len: {"len", 1, false, expression},
223 _Make: {"make", 1, true, expression},
224 // To disable max/min, remove the next two lines.
225 _Max: {"max", 1, true, expression},
226 _Min: {"min", 1, true, expression},
227 _New: {"new", 1, false, expression},
228 _Panic: {"panic", 1, false, statement},
229 _Print: {"print", 0, true, statement},
230 _Println: {"println", 0, true, statement},
231 _Real: {"real", 1, false, expression},
232 _Recover: {"recover", 0, false, statement},
233
234 _Add: {"Add", 2, false, expression},
235 _Alignof: {"Alignof", 1, false, expression},
236 _Offsetof: {"Offsetof", 1, false, expression},
237 _Sizeof: {"Sizeof", 1, false, expression},
238 _Slice: {"Slice", 2, false, expression},
239 _SliceData: {"SliceData", 1, false, expression},
240 _String: {"String", 2, false, expression},
241 _StringData: {"StringData", 1, false, expression},
242
243 _Assert: {"assert", 1, false, statement},
244 _Trace: {"trace", 0, true, statement},
245 }
246
247 func defPredeclaredFuncs() {
248 for i := range predeclaredFuncs {
249 id := builtinId(i)
250 if id == _Assert || id == _Trace {
251 continue // only define these in testing environment
252 }
253 def(newBuiltin(id))
254 }
255 }
256
257 // DefPredeclaredTestFuncs defines the assert and trace built-ins.
258 // These built-ins are intended for debugging and testing of this
259 // package only.
260 func DefPredeclaredTestFuncs() {
261 if Universe.Lookup("assert") != nil {
262 return // already defined
263 }
264 def(newBuiltin(_Assert))
265 def(newBuiltin(_Trace))
266 }
267
268 func init() {
269 Universe = NewScope(nil, nopos, nopos, "universe")
270 Unsafe = NewPackage("unsafe", "unsafe")
271 Unsafe.complete = true
272
273 defPredeclaredTypes()
274 defPredeclaredConsts()
275 defPredeclaredNil()
276 defPredeclaredFuncs()
277
278 universeIota = Universe.Lookup("iota")
279 universeBool = Universe.Lookup("bool").Type()
280 universeByte = Universe.Lookup("byte").Type()
281 universeRune = Universe.Lookup("rune").Type()
282 universeError = Universe.Lookup("error").Type()
283 universeComparable = Universe.Lookup("comparable")
284 }
285
286 // Objects with names containing blanks are internal and not entered into
287 // a scope. Objects with exported names are inserted in the unsafe package
288 // scope; other objects are inserted in the universe scope.
289 func def(obj Object) {
290 assert(obj.color() == black)
291 name := obj.Name()
292 if strings.Contains(name, " ") {
293 return // nothing to do
294 }
295 // fix Obj link for named types
296 if typ := asNamed(obj.Type()); typ != nil {
297 typ.obj = obj.(*TypeName)
298 }
299 // exported identifiers go into package unsafe
300 scope := Universe
301 if obj.Exported() {
302 scope = Unsafe.scope
303 // set Pkg field
304 switch obj := obj.(type) {
305 case *TypeName:
306 obj.pkg = Unsafe
307 case *Builtin:
308 obj.pkg = Unsafe
309 default:
310 panic("unreachable")
311 }
312 }
313 if scope.Insert(obj) != nil {
314 panic("double declaration of predeclared identifier")
315 }
316 }