Source file src/go/types/universe.go

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

View as plain text