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  	"sort"
    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  	sort.Strings(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  	return resolve(name, s.elems[name])
    75  }
    76  
    77  // LookupParent follows the parent chain of scopes starting with s until
    78  // it finds a scope where Lookup(name) returns a non-nil object, and then
    79  // returns that scope and object. If a valid position pos is provided,
    80  // only objects that were declared at or before pos are considered.
    81  // If no such scope and object exists, the result is (nil, nil).
    82  //
    83  // Note that obj.Parent() may be different from the returned scope if the
    84  // object was inserted into the scope and already had a parent at that
    85  // time (see Insert). This can only happen for dot-imported objects
    86  // whose scope is the scope of the package that exported them.
    87  func (s *Scope) LookupParent(name string, pos token.Pos) (*Scope, Object) {
    88  	for ; s != nil; s = s.parent {
    89  		if obj := s.Lookup(name); obj != nil && (!pos.IsValid() || cmpPos(obj.scopePos(), pos) <= 0) {
    90  			return s, obj
    91  		}
    92  	}
    93  	return nil, nil
    94  }
    95  
    96  // Insert attempts to insert an object obj into scope s.
    97  // If s already contains an alternative object alt with
    98  // the same name, Insert leaves s unchanged and returns alt.
    99  // Otherwise it inserts obj, sets the object's parent scope
   100  // if not already set, and returns nil.
   101  func (s *Scope) Insert(obj Object) Object {
   102  	name := obj.Name()
   103  	if alt := s.Lookup(name); alt != nil {
   104  		return alt
   105  	}
   106  	s.insert(name, obj)
   107  	if obj.Parent() == nil {
   108  		obj.setParent(s)
   109  	}
   110  	return nil
   111  }
   112  
   113  // InsertLazy is like Insert, but allows deferring construction of the
   114  // inserted object until it's accessed with Lookup. The Object
   115  // returned by resolve must have the same name as given to InsertLazy.
   116  // If s already contains an alternative object with the same name,
   117  // InsertLazy leaves s unchanged and returns false. Otherwise it
   118  // records the binding and returns true. The object's parent scope
   119  // will be set to s after resolve is called.
   120  func (s *Scope) _InsertLazy(name string, resolve func() Object) bool {
   121  	if s.elems[name] != nil {
   122  		return false
   123  	}
   124  	s.insert(name, &lazyObject{parent: s, resolve: resolve})
   125  	return true
   126  }
   127  
   128  func (s *Scope) insert(name string, obj Object) {
   129  	if s.elems == nil {
   130  		s.elems = make(map[string]Object)
   131  	}
   132  	s.elems[name] = obj
   133  }
   134  
   135  // Squash merges s with its parent scope p by adding all
   136  // objects of s to p, adding all children of s to the
   137  // children of p, and removing s from p's children.
   138  // The function f is called for each object obj in s which
   139  // has an object alt in p. s should be discarded after
   140  // having been squashed.
   141  func (s *Scope) squash(err func(obj, alt Object)) {
   142  	p := s.parent
   143  	assert(p != nil)
   144  	for name, obj := range s.elems {
   145  		obj = resolve(name, obj)
   146  		obj.setParent(nil)
   147  		if alt := p.Insert(obj); alt != nil {
   148  			err(obj, alt)
   149  		}
   150  	}
   151  
   152  	j := -1 // index of s in p.children
   153  	for i, ch := range p.children {
   154  		if ch == s {
   155  			j = i
   156  			break
   157  		}
   158  	}
   159  	assert(j >= 0)
   160  	k := len(p.children) - 1
   161  	p.children[j] = p.children[k]
   162  	p.children = p.children[:k]
   163  
   164  	p.children = append(p.children, s.children...)
   165  
   166  	s.children = nil
   167  	s.elems = nil
   168  }
   169  
   170  // Pos and End describe the scope's source code extent [pos, end).
   171  // The results are guaranteed to be valid only if the type-checked
   172  // AST has complete position information. The extent is undefined
   173  // for Universe and package scopes.
   174  func (s *Scope) Pos() token.Pos { return s.pos }
   175  func (s *Scope) End() token.Pos { return s.end }
   176  
   177  // Contains reports whether pos is within the scope's extent.
   178  // The result is guaranteed to be valid only if the type-checked
   179  // AST has complete position information.
   180  func (s *Scope) Contains(pos token.Pos) bool {
   181  	return cmpPos(s.pos, pos) <= 0 && cmpPos(pos, s.end) < 0
   182  }
   183  
   184  // Innermost returns the innermost (child) scope containing
   185  // pos. If pos is not within any scope, the result is nil.
   186  // The result is also nil for the Universe scope.
   187  // The result is guaranteed to be valid only if the type-checked
   188  // AST has complete position information.
   189  func (s *Scope) Innermost(pos token.Pos) *Scope {
   190  	// Package scopes do not have extents since they may be
   191  	// discontiguous, so iterate over the package's files.
   192  	if s.parent == Universe {
   193  		for _, s := range s.children {
   194  			if inner := s.Innermost(pos); inner != nil {
   195  				return inner
   196  			}
   197  		}
   198  	}
   199  
   200  	if s.Contains(pos) {
   201  		for _, s := range s.children {
   202  			if s.Contains(pos) {
   203  				return s.Innermost(pos)
   204  			}
   205  		}
   206  		return s
   207  	}
   208  	return nil
   209  }
   210  
   211  // WriteTo writes a string representation of the scope to w,
   212  // with the scope elements sorted by name.
   213  // The level of indentation is controlled by n >= 0, with
   214  // n == 0 for no indentation.
   215  // If recurse is set, it also writes nested (children) scopes.
   216  func (s *Scope) WriteTo(w io.Writer, n int, recurse bool) {
   217  	const ind = ".  "
   218  	indn := strings.Repeat(ind, n)
   219  
   220  	fmt.Fprintf(w, "%s%s scope %p {\n", indn, s.comment, s)
   221  
   222  	indn1 := indn + ind
   223  	for _, name := range s.Names() {
   224  		fmt.Fprintf(w, "%s%s\n", indn1, s.Lookup(name))
   225  	}
   226  
   227  	if recurse {
   228  		for _, s := range s.children {
   229  			s.WriteTo(w, n+1, recurse)
   230  		}
   231  	}
   232  
   233  	fmt.Fprintf(w, "%s}\n", indn)
   234  }
   235  
   236  // String returns a string representation of the scope, for debugging.
   237  func (s *Scope) String() string {
   238  	var buf strings.Builder
   239  	s.WriteTo(&buf, 0, false)
   240  	return buf.String()
   241  }
   242  
   243  // A lazyObject represents an imported Object that has not been fully
   244  // resolved yet by its importer.
   245  type lazyObject struct {
   246  	parent  *Scope
   247  	resolve func() Object
   248  	obj     Object
   249  	once    sync.Once
   250  }
   251  
   252  // resolve returns the Object represented by obj, resolving lazy
   253  // objects as appropriate.
   254  func resolve(name string, obj Object) Object {
   255  	if lazy, ok := obj.(*lazyObject); ok {
   256  		lazy.once.Do(func() {
   257  			obj := lazy.resolve()
   258  
   259  			if _, ok := obj.(*lazyObject); ok {
   260  				panic("recursive lazy object")
   261  			}
   262  			if obj.Name() != name {
   263  				panic("lazy object has unexpected name")
   264  			}
   265  
   266  			if obj.Parent() == nil {
   267  				obj.setParent(lazy.parent)
   268  			}
   269  			lazy.obj = obj
   270  		})
   271  
   272  		obj = lazy.obj
   273  	}
   274  	return obj
   275  }
   276  
   277  // stub implementations so *lazyObject implements Object and we can
   278  // store them directly into Scope.elems.
   279  func (*lazyObject) Parent() *Scope                     { panic("unreachable") }
   280  func (*lazyObject) Pos() token.Pos                     { panic("unreachable") }
   281  func (*lazyObject) Pkg() *Package                      { panic("unreachable") }
   282  func (*lazyObject) Name() string                       { panic("unreachable") }
   283  func (*lazyObject) Type() Type                         { panic("unreachable") }
   284  func (*lazyObject) Exported() bool                     { panic("unreachable") }
   285  func (*lazyObject) Id() string                         { panic("unreachable") }
   286  func (*lazyObject) String() string                     { panic("unreachable") }
   287  func (*lazyObject) order() uint32                      { panic("unreachable") }
   288  func (*lazyObject) color() color                       { panic("unreachable") }
   289  func (*lazyObject) setType(Type)                       { panic("unreachable") }
   290  func (*lazyObject) setOrder(uint32)                    { panic("unreachable") }
   291  func (*lazyObject) setColor(color color)               { panic("unreachable") }
   292  func (*lazyObject) setParent(*Scope)                   { panic("unreachable") }
   293  func (*lazyObject) sameId(*Package, string, bool) bool { panic("unreachable") }
   294  func (*lazyObject) scopePos() token.Pos                { panic("unreachable") }
   295  func (*lazyObject) setScopePos(token.Pos)              { panic("unreachable") }
   296  

View as plain text