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

     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  		// ensure that the any TypeName reports a consistent Parent, after
   102  		// hijacking Universe.Lookup with gotypesalias=0.
   103  		universeAnyNoAlias.setParent(Universe)
   104  
   105  		// It shouldn't matter which representation of any is actually inserted
   106  		// into the Universe, but we lean toward the future and insert the Alias
   107  		// representation.
   108  		universeAnyAlias = NewTypeName(nopos, nil, "any", nil)
   109  		_ = NewAlias(universeAnyAlias, universeAnyNoAlias.Type().Underlying()) // Link TypeName and Alias
   110  		def(universeAnyAlias)
   111  	}
   112  
   113  	// type error interface{ Error() string }
   114  	{
   115  		obj := NewTypeName(nopos, nil, "error", nil)
   116  		typ := (*Checker)(nil).newNamed(obj, nil, nil)
   117  
   118  		// error.Error() string
   119  		recv := newVar(RecvVar, nopos, nil, "", typ)
   120  		res := newVar(ResultVar, nopos, nil, "", Typ[String])
   121  		sig := NewSignatureType(recv, nil, nil, nil, NewTuple(res), false)
   122  		err := NewFunc(nopos, nil, "Error", sig)
   123  
   124  		// interface{ Error() string }
   125  		ityp := &Interface{methods: []*Func{err}, complete: true}
   126  		computeInterfaceTypeSet(nil, nopos, ityp) // prevent races due to lazy computation of tset
   127  
   128  		typ.fromRHS = ityp
   129  		typ.Underlying()
   130  		def(obj)
   131  	}
   132  
   133  	// type comparable interface{} // marked as comparable
   134  	{
   135  		obj := NewTypeName(nopos, nil, "comparable", nil)
   136  		typ := (*Checker)(nil).newNamed(obj, nil, nil)
   137  
   138  		// interface{} // marked as comparable
   139  		ityp := &Interface{complete: true, tset: &_TypeSet{nil, allTermlist, true}}
   140  
   141  		typ.fromRHS = ityp
   142  		typ.Underlying()
   143  		def(obj)
   144  	}
   145  }
   146  
   147  var predeclaredConsts = [...]struct {
   148  	name string
   149  	kind BasicKind
   150  	val  constant.Value
   151  }{
   152  	{"true", UntypedBool, constant.MakeBool(true)},
   153  	{"false", UntypedBool, constant.MakeBool(false)},
   154  	{"iota", UntypedInt, constant.MakeInt64(0)},
   155  }
   156  
   157  func defPredeclaredConsts() {
   158  	for _, c := range predeclaredConsts {
   159  		def(NewConst(nopos, nil, c.name, Typ[c.kind], c.val))
   160  	}
   161  }
   162  
   163  func defPredeclaredNil() {
   164  	def(&Nil{object{name: "nil", typ: Typ[UntypedNil]}})
   165  }
   166  
   167  // A builtinId is the id of a builtin function.
   168  type builtinId int
   169  
   170  const (
   171  	// universe scope
   172  	_Append builtinId = iota
   173  	_Cap
   174  	_Clear
   175  	_Close
   176  	_Complex
   177  	_Copy
   178  	_Delete
   179  	_Imag
   180  	_Len
   181  	_Make
   182  	_Max
   183  	_Min
   184  	_New
   185  	_Panic
   186  	_Print
   187  	_Println
   188  	_Real
   189  	_Recover
   190  
   191  	// package unsafe
   192  	_Add
   193  	_Alignof
   194  	_Offsetof
   195  	_Sizeof
   196  	_Slice
   197  	_SliceData
   198  	_String
   199  	_StringData
   200  
   201  	// testing support
   202  	_Assert
   203  	_Trace
   204  )
   205  
   206  var predeclaredFuncs = [...]struct {
   207  	name     string
   208  	nargs    int
   209  	variadic bool
   210  	kind     exprKind
   211  }{
   212  	_Append:  {"append", 1, true, expression},
   213  	_Cap:     {"cap", 1, false, expression},
   214  	_Clear:   {"clear", 1, false, statement},
   215  	_Close:   {"close", 1, false, statement},
   216  	_Complex: {"complex", 2, false, expression},
   217  	_Copy:    {"copy", 2, false, statement},
   218  	_Delete:  {"delete", 2, false, statement},
   219  	_Imag:    {"imag", 1, false, expression},
   220  	_Len:     {"len", 1, false, expression},
   221  	_Make:    {"make", 1, true, expression},
   222  	// To disable max/min, remove the next two lines.
   223  	_Max:     {"max", 1, true, expression},
   224  	_Min:     {"min", 1, true, expression},
   225  	_New:     {"new", 1, false, expression},
   226  	_Panic:   {"panic", 1, false, statement},
   227  	_Print:   {"print", 0, true, statement},
   228  	_Println: {"println", 0, true, statement},
   229  	_Real:    {"real", 1, false, expression},
   230  	_Recover: {"recover", 0, false, statement},
   231  
   232  	_Add:        {"Add", 2, false, expression},
   233  	_Alignof:    {"Alignof", 1, false, expression},
   234  	_Offsetof:   {"Offsetof", 1, false, expression},
   235  	_Sizeof:     {"Sizeof", 1, false, expression},
   236  	_Slice:      {"Slice", 2, false, expression},
   237  	_SliceData:  {"SliceData", 1, false, expression},
   238  	_String:     {"String", 2, false, expression},
   239  	_StringData: {"StringData", 1, false, expression},
   240  
   241  	_Assert: {"assert", 1, false, statement},
   242  	_Trace:  {"trace", 0, true, statement},
   243  }
   244  
   245  func defPredeclaredFuncs() {
   246  	for i := range predeclaredFuncs {
   247  		id := builtinId(i)
   248  		if id == _Assert || id == _Trace {
   249  			continue // only define these in testing environment
   250  		}
   251  		def(newBuiltin(id))
   252  	}
   253  }
   254  
   255  // DefPredeclaredTestFuncs defines the assert and trace built-ins.
   256  // These built-ins are intended for debugging and testing of this
   257  // package only.
   258  func DefPredeclaredTestFuncs() {
   259  	if Universe.Lookup("assert") != nil {
   260  		return // already defined
   261  	}
   262  	def(newBuiltin(_Assert))
   263  	def(newBuiltin(_Trace))
   264  }
   265  
   266  func init() {
   267  	Universe = NewScope(nil, nopos, nopos, "universe")
   268  	Unsafe = NewPackage("unsafe", "unsafe")
   269  	Unsafe.complete = true
   270  
   271  	defPredeclaredTypes()
   272  	defPredeclaredConsts()
   273  	defPredeclaredNil()
   274  	defPredeclaredFuncs()
   275  
   276  	universeIota = Universe.Lookup("iota")
   277  	universeBool = Universe.Lookup("bool").Type()
   278  	universeByte = Universe.Lookup("byte").Type()
   279  	universeRune = Universe.Lookup("rune").Type()
   280  	universeError = Universe.Lookup("error").Type()
   281  	universeComparable = Universe.Lookup("comparable")
   282  }
   283  
   284  // Objects with names containing blanks are internal and not entered into
   285  // a scope. Objects with exported names are inserted in the unsafe package
   286  // scope; other objects are inserted in the universe scope.
   287  func def(obj Object) {
   288  	assert(obj.Type() != nil)
   289  	name := obj.Name()
   290  	if strings.Contains(name, " ") {
   291  		return // nothing to do
   292  	}
   293  	// fix Obj link for named types
   294  	if typ := asNamed(obj.Type()); typ != nil {
   295  		typ.obj = obj.(*TypeName)
   296  	}
   297  	// exported identifiers go into package unsafe
   298  	scope := Universe
   299  	if obj.Exported() {
   300  		scope = Unsafe.scope
   301  		// set Pkg field
   302  		switch obj := obj.(type) {
   303  		case *TypeName:
   304  			obj.pkg = Unsafe
   305  		case *Builtin:
   306  			obj.pkg = Unsafe
   307  		default:
   308  			panic("unreachable")
   309  		}
   310  	}
   311  	if scope.Insert(obj) != nil {
   312  		panic("double declaration of predeclared identifier")
   313  	}
   314  }
   315  

View as plain text