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

     1  // Copyright 2013 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 implements Scopes.
     6  
     7  package types2
     8  
     9  import (
    10  	"bytes"
    11  	"cmd/compile/internal/syntax"
    12  	"fmt"
    13  	"io"
    14  	"sort"
    15  	"strings"
    16  	"sync"
    17  )
    18  
    19  // A Scope maintains a set of objects and links to its containing
    20  // (parent) and contained (children) scopes. Objects may be inserted
    21  // and looked up by name. The zero value for Scope is a ready-to-use
    22  // empty scope.
    23  type Scope struct {
    24  	parent   *Scope
    25  	children []*Scope
    26  	number   int               // parent.children[number-1] is this scope; 0 if there is no parent
    27  	elems    map[string]Object // lazily allocated
    28  	pos, end syntax.Pos        // scope extent; may be invalid
    29  	comment  string            // for debugging only
    30  	isFunc   bool              // set if this is a function scope (internal use only)
    31  }
    32  
    33  // NewScope returns a new, empty scope contained in the given parent
    34  // scope, if any. The comment is for debugging only.
    35  func NewScope(parent *Scope, pos, end syntax.Pos, comment string) *Scope {
    36  	s := &Scope{parent, nil, 0, nil, pos, end, comment, false}
    37  	// don't add children to Universe scope!
    38  	if parent != nil && parent != Universe {
    39  		parent.children = append(parent.children, s)
    40  		s.number = len(parent.children)
    41  	}
    42  	return s
    43  }
    44  
    45  // Parent returns the scope's containing (parent) scope.
    46  func (s *Scope) Parent() *Scope { return s.parent }
    47  
    48  // Len returns the number of scope elements.
    49  func (s *Scope) Len() int { return len(s.elems) }
    50  
    51  // Names returns the scope's element names in sorted order.
    52  func (s *Scope) Names() []string {
    53  	names := make([]string, len(s.elems))
    54  	i := 0
    55  	for name := range s.elems {
    56  		names[i] = name
    57  		i++
    58  	}
    59  	sort.Strings(names)
    60  	return names
    61  }
    62  
    63  // NumChildren returns the number of scopes nested in s.
    64  func (s *Scope) NumChildren() int { return len(s.children) }
    65  
    66  // Child returns the i'th child scope for 0 <= i < NumChildren().
    67  func (s *Scope) Child(i int) *Scope { return s.children[i] }
    68  
    69  // Lookup returns the object in scope s with the given name if such an
    70  // object exists; otherwise the result is nil.
    71  func (s *Scope) Lookup(name string) Object {
    72  	return resolve(name, s.elems[name])
    73  }
    74  
    75  // LookupParent follows the parent chain of scopes starting with s until
    76  // it finds a scope where Lookup(name) returns a non-nil object, and then
    77  // returns that scope and object. If a valid position pos is provided,
    78  // only objects that were declared at or before pos are considered.
    79  // If no such scope and object exists, the result is (nil, nil).
    80  //
    81  // Note that obj.Parent() may be different from the returned scope if the
    82  // object was inserted into the scope and already had a parent at that
    83  // time (see Insert). This can only happen for dot-imported objects
    84  // whose scope is the scope of the package that exported them.
    85  func (s *Scope) LookupParent(name string, pos syntax.Pos) (*Scope, Object) {
    86  	for ; s != nil; s = s.parent {
    87  		if obj := s.Lookup(name); obj != nil && (!pos.IsKnown() || obj.scopePos().Cmp(pos) <= 0) {
    88  			return s, obj
    89  		}
    90  	}
    91  	return nil, nil
    92  }
    93  
    94  // Insert attempts to insert an object obj into scope s.
    95  // If s already contains an alternative object alt with
    96  // the same name, Insert leaves s unchanged and returns alt.
    97  // Otherwise it inserts obj, sets the object's parent scope
    98  // if not already set, and returns nil.
    99  func (s *Scope) Insert(obj Object) Object {
   100  	name := obj.Name()
   101  	if alt := s.Lookup(name); alt != nil {
   102  		return alt
   103  	}
   104  	s.insert(name, obj)
   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  // Squash merges s with its parent scope p by adding all
   134  // objects of s to p, adding all children of s to the
   135  // children of p, and removing s from p's children.
   136  // The function f is called for each object obj in s which
   137  // has an object alt in p. s should be discarded after
   138  // having been squashed.
   139  func (s *Scope) Squash(err func(obj, alt Object)) {
   140  	p := s.parent
   141  	assert(p != nil)
   142  	for name, obj := range s.elems {
   143  		obj = resolve(name, obj)
   144  		obj.setParent(nil)
   145  		if alt := p.Insert(obj); alt != nil {
   146  			err(obj, alt)
   147  		}
   148  	}
   149  
   150  	j := -1 // index of s in p.children
   151  	for i, ch := range p.children {
   152  		if ch == s {
   153  			j = i
   154  			break
   155  		}
   156  	}
   157  	assert(j >= 0)
   158  	k := len(p.children) - 1
   159  	p.children[j] = p.children[k]
   160  	p.children = p.children[:k]
   161  
   162  	p.children = append(p.children, s.children...)
   163  
   164  	s.children = nil
   165  	s.elems = nil
   166  }
   167  
   168  // Pos and End describe the scope's source code extent [pos, end).
   169  // The results are guaranteed to be valid only if the type-checked
   170  // AST has complete position information. The extent is undefined
   171  // for Universe and package scopes.
   172  func (s *Scope) Pos() syntax.Pos { return s.pos }
   173  func (s *Scope) End() syntax.Pos { return s.end }
   174  
   175  // Contains reports whether pos is within the scope's extent.
   176  // The result is guaranteed to be valid only if the type-checked
   177  // AST has complete position information.
   178  func (s *Scope) Contains(pos syntax.Pos) bool {
   179  	return s.pos.Cmp(pos) <= 0 && pos.Cmp(s.end) < 0
   180  }
   181  
   182  // Innermost returns the innermost (child) scope containing
   183  // pos. If pos is not within any scope, the result is nil.
   184  // The result is also nil for the Universe scope.
   185  // The result is guaranteed to be valid only if the type-checked
   186  // AST has complete position information.
   187  func (s *Scope) Innermost(pos syntax.Pos) *Scope {
   188  	// Package scopes do not have extents since they may be
   189  	// discontiguous, so iterate over the package's files.
   190  	if s.parent == Universe {
   191  		for _, s := range s.children {
   192  			if inner := s.Innermost(pos); inner != nil {
   193  				return inner
   194  			}
   195  		}
   196  	}
   197  
   198  	if s.Contains(pos) {
   199  		for _, s := range s.children {
   200  			if s.Contains(pos) {
   201  				return s.Innermost(pos)
   202  			}
   203  		}
   204  		return s
   205  	}
   206  	return nil
   207  }
   208  
   209  // WriteTo writes a string representation of the scope to w,
   210  // with the scope elements sorted by name.
   211  // The level of indentation is controlled by n >= 0, with
   212  // n == 0 for no indentation.
   213  // If recurse is set, it also writes nested (children) scopes.
   214  func (s *Scope) WriteTo(w io.Writer, n int, recurse bool) {
   215  	const ind = ".  "
   216  	indn := strings.Repeat(ind, n)
   217  
   218  	fmt.Fprintf(w, "%s%s scope %p {\n", indn, s.comment, s)
   219  
   220  	indn1 := indn + ind
   221  	for _, name := range s.Names() {
   222  		fmt.Fprintf(w, "%s%s\n", indn1, s.Lookup(name))
   223  	}
   224  
   225  	if recurse {
   226  		for _, s := range s.children {
   227  			s.WriteTo(w, n+1, recurse)
   228  		}
   229  	}
   230  
   231  	fmt.Fprintf(w, "%s}\n", indn)
   232  }
   233  
   234  // String returns a string representation of the scope, for debugging.
   235  func (s *Scope) String() string {
   236  	var buf bytes.Buffer
   237  	s.WriteTo(&buf, 0, false)
   238  	return buf.String()
   239  }
   240  
   241  // A lazyObject represents an imported Object that has not been fully
   242  // resolved yet by its importer.
   243  type lazyObject struct {
   244  	parent  *Scope
   245  	resolve func() Object
   246  	obj     Object
   247  	once    sync.Once
   248  }
   249  
   250  // resolve returns the Object represented by obj, resolving lazy
   251  // objects as appropriate.
   252  func resolve(name string, obj Object) Object {
   253  	if lazy, ok := obj.(*lazyObject); ok {
   254  		lazy.once.Do(func() {
   255  			obj := lazy.resolve()
   256  
   257  			if _, ok := obj.(*lazyObject); ok {
   258  				panic("recursive lazy object")
   259  			}
   260  			if obj.Name() != name {
   261  				panic("lazy object has unexpected name")
   262  			}
   263  
   264  			if obj.Parent() == nil {
   265  				obj.setParent(lazy.parent)
   266  			}
   267  			lazy.obj = obj
   268  		})
   269  
   270  		obj = lazy.obj
   271  	}
   272  	return obj
   273  }
   274  
   275  // stub implementations so *lazyObject implements Object and we can
   276  // store them directly into Scope.elems.
   277  func (*lazyObject) Parent() *Scope                        { panic("unreachable") }
   278  func (*lazyObject) Pos() syntax.Pos                       { panic("unreachable") }
   279  func (*lazyObject) Pkg() *Package                         { panic("unreachable") }
   280  func (*lazyObject) Name() string                          { panic("unreachable") }
   281  func (*lazyObject) Type() Type                            { panic("unreachable") }
   282  func (*lazyObject) Exported() bool                        { panic("unreachable") }
   283  func (*lazyObject) Id() string                            { panic("unreachable") }
   284  func (*lazyObject) String() string                        { panic("unreachable") }
   285  func (*lazyObject) order() uint32                         { panic("unreachable") }
   286  func (*lazyObject) color() color                          { panic("unreachable") }
   287  func (*lazyObject) setType(Type)                          { panic("unreachable") }
   288  func (*lazyObject) setOrder(uint32)                       { panic("unreachable") }
   289  func (*lazyObject) setColor(color color)                  { panic("unreachable") }
   290  func (*lazyObject) setParent(*Scope)                      { panic("unreachable") }
   291  func (*lazyObject) sameId(pkg *Package, name string) bool { panic("unreachable") }
   292  func (*lazyObject) scopePos() syntax.Pos                  { panic("unreachable") }
   293  func (*lazyObject) setScopePos(pos syntax.Pos)            { panic("unreachable") }
   294  

View as plain text