Source file src/go/types/scope.go

     1  // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
     2  // Source: ../../cmd/compile/internal/types2/scope.go
     3  
     4  // Copyright 2013 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 implements Scopes.
     9  
    10  package types
    11  
    12  import (
    13  	"fmt"
    14  	"go/token"
    15  	"io"
    16  	"slices"
    17  	"strings"
    18  	"sync"
    19  )
    20  
    21  // A Scope maintains a set of objects and links to its containing
    22  // (parent) and contained (children) scopes. Objects may be inserted
    23  // and looked up by name. The zero value for Scope is a ready-to-use
    24  // empty scope.
    25  type Scope struct {
    26  	parent   *Scope
    27  	children []*Scope
    28  	number   int               // parent.children[number-1] is this scope; 0 if there is no parent
    29  	elems    map[string]Object // lazily allocated
    30  	pos, end token.Pos         // scope extent; may be invalid
    31  	comment  string            // for debugging only
    32  	isFunc   bool              // set if this is a function scope (internal use only)
    33  }
    34  
    35  // NewScope returns a new, empty scope contained in the given parent
    36  // scope, if any. The comment is for debugging only.
    37  func NewScope(parent *Scope, pos, end token.Pos, comment string) *Scope {
    38  	s := &Scope{parent, nil, 0, nil, pos, end, comment, false}
    39  	// don't add children to Universe scope!
    40  	if parent != nil && parent != Universe {
    41  		parent.children = append(parent.children, s)
    42  		s.number = len(parent.children)
    43  	}
    44  	return s
    45  }
    46  
    47  // Parent returns the scope's containing (parent) scope.
    48  func (s *Scope) Parent() *Scope { return s.parent }
    49  
    50  // Len returns the number of scope elements.
    51  func (s *Scope) Len() int { return len(s.elems) }
    52  
    53  // Names returns the scope's element names in sorted order.
    54  func (s *Scope) Names() []string {
    55  	names := make([]string, len(s.elems))
    56  	i := 0
    57  	for name := range s.elems {
    58  		names[i] = name
    59  		i++
    60  	}
    61  	slices.Sort(names)
    62  	return names
    63  }
    64  
    65  // NumChildren returns the number of scopes nested in s.
    66  func (s *Scope) NumChildren() int { return len(s.children) }
    67  
    68  // Child returns the i'th child scope for 0 <= i < NumChildren().
    69  func (s *Scope) Child(i int) *Scope { return s.children[i] }
    70  
    71  // Lookup returns the object in scope s with the given name if such an
    72  // object exists; otherwise the result is nil.
    73  func (s *Scope) Lookup(name string) Object {
    74  	obj := resolve(name, s.elems[name])
    75  	// Hijack Lookup for "any": with gotypesalias=1, we want the Universe to
    76  	// return an Alias for "any", and with gotypesalias=0 we want to return
    77  	// the legacy representation of aliases.
    78  	//
    79  	// This is rather tricky, but works out after auditing of the usage of
    80  	// s.elems. The only external API to access scope elements is Lookup.
    81  	//
    82  	// TODO: remove this once gotypesalias=0 is no longer supported.
    83  	if obj == universeAnyAlias && !aliasAny() {
    84  		return universeAnyNoAlias
    85  	}
    86  	return obj
    87  }
    88  
    89  // Insert attempts to insert an object obj into scope s.
    90  // If s already contains an alternative object alt with
    91  // the same name, Insert leaves s unchanged and returns alt.
    92  // Otherwise it inserts obj, sets the object's parent scope
    93  // if not already set, and returns nil.
    94  func (s *Scope) Insert(obj Object) Object {
    95  	name := obj.Name()
    96  	if alt := s.Lookup(name); alt != nil {
    97  		return alt
    98  	}
    99  	s.insert(name, obj)
   100  	// TODO(gri) Can we always set the parent to s (or is there
   101  	// a need to keep the original parent or some race condition)?
   102  	// If we can, than we may not need environment.lookupScope
   103  	// which is only there so that we get the correct scope for
   104  	// marking "used" dot-imported packages.
   105  	if obj.Parent() == nil {
   106  		obj.setParent(s)
   107  	}
   108  	return nil
   109  }
   110  
   111  // InsertLazy is like Insert, but allows deferring construction of the
   112  // inserted object until it's accessed with Lookup. The Object
   113  // returned by resolve must have the same name as given to InsertLazy.
   114  // If s already contains an alternative object with the same name,
   115  // InsertLazy leaves s unchanged and returns false. Otherwise it
   116  // records the binding and returns true. The object's parent scope
   117  // will be set to s after resolve is called.
   118  func (s *Scope) _InsertLazy(name string, resolve func() Object) bool {
   119  	if s.elems[name] != nil {
   120  		return false
   121  	}
   122  	s.insert(name, &lazyObject{parent: s, resolve: resolve})
   123  	return true
   124  }
   125  
   126  func (s *Scope) insert(name string, obj Object) {
   127  	if s.elems == nil {
   128  		s.elems = make(map[string]Object)
   129  	}
   130  	s.elems[name] = obj
   131  }
   132  
   133  // WriteTo writes a string representation of the scope to w,
   134  // with the scope elements sorted by name.
   135  // The level of indentation is controlled by n >= 0, with
   136  // n == 0 for no indentation.
   137  // If recurse is set, it also writes nested (children) scopes.
   138  func (s *Scope) WriteTo(w io.Writer, n int, recurse bool) {
   139  	const ind = ".  "
   140  	indn := strings.Repeat(ind, n)
   141  
   142  	fmt.Fprintf(w, "%s%s scope %p {\n", indn, s.comment, s)
   143  
   144  	indn1 := indn + ind
   145  	for _, name := range s.Names() {
   146  		fmt.Fprintf(w, "%s%s\n", indn1, s.Lookup(name))
   147  	}
   148  
   149  	if recurse {
   150  		for _, s := range s.children {
   151  			s.WriteTo(w, n+1, recurse)
   152  		}
   153  	}
   154  
   155  	fmt.Fprintf(w, "%s}\n", indn)
   156  }
   157  
   158  // String returns a string representation of the scope, for debugging.
   159  func (s *Scope) String() string {
   160  	var buf strings.Builder
   161  	s.WriteTo(&buf, 0, false)
   162  	return buf.String()
   163  }
   164  
   165  // A lazyObject represents an imported Object that has not been fully
   166  // resolved yet by its importer.
   167  type lazyObject struct {
   168  	parent  *Scope
   169  	resolve func() Object
   170  	obj     Object
   171  	once    sync.Once
   172  }
   173  
   174  // resolve returns the Object represented by obj, resolving lazy
   175  // objects as appropriate.
   176  func resolve(name string, obj Object) Object {
   177  	if lazy, ok := obj.(*lazyObject); ok {
   178  		lazy.once.Do(func() {
   179  			obj := lazy.resolve()
   180  
   181  			if _, ok := obj.(*lazyObject); ok {
   182  				panic("recursive lazy object")
   183  			}
   184  			if obj.Name() != name {
   185  				panic("lazy object has unexpected name")
   186  			}
   187  
   188  			if obj.Parent() == nil {
   189  				obj.setParent(lazy.parent)
   190  			}
   191  			lazy.obj = obj
   192  		})
   193  
   194  		obj = lazy.obj
   195  	}
   196  	return obj
   197  }
   198  
   199  // stub implementations so *lazyObject implements Object and we can
   200  // store them directly into Scope.elems.
   201  func (*lazyObject) Parent() *Scope                     { panic("unreachable") }
   202  func (*lazyObject) Pos() token.Pos                     { panic("unreachable") }
   203  func (*lazyObject) Pkg() *Package                      { panic("unreachable") }
   204  func (*lazyObject) Name() string                       { panic("unreachable") }
   205  func (*lazyObject) Type() Type                         { panic("unreachable") }
   206  func (*lazyObject) Exported() bool                     { panic("unreachable") }
   207  func (*lazyObject) Id() string                         { panic("unreachable") }
   208  func (*lazyObject) String() string                     { panic("unreachable") }
   209  func (*lazyObject) order() uint32                      { panic("unreachable") }
   210  func (*lazyObject) color() color                       { panic("unreachable") }
   211  func (*lazyObject) setType(Type)                       { panic("unreachable") }
   212  func (*lazyObject) setOrder(uint32)                    { panic("unreachable") }
   213  func (*lazyObject) setColor(color color)               { panic("unreachable") }
   214  func (*lazyObject) setParent(*Scope)                   { panic("unreachable") }
   215  func (*lazyObject) sameId(*Package, string, bool) bool { panic("unreachable") }
   216  func (*lazyObject) scopePos() token.Pos                { panic("unreachable") }
   217  func (*lazyObject) setScopePos(token.Pos)              { panic("unreachable") }
   218  

View as plain text