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

View as plain text