...

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

Documentation: cmd/compile/internal/types2

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