src/share/classes/com/sun/tools/javac/code/Scope.java

Sun, 17 Feb 2013 16:44:55 -0500

author
dholmes
date
Sun, 17 Feb 2013 16:44:55 -0500
changeset 1571
af8417e590f4
parent 1357
c75be5bc5283
child 1886
79c3146e417b
permissions
-rw-r--r--

Merge

     1 /*
     2  * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.code;
    28 import java.util.Iterator;
    30 import com.sun.tools.javac.util.*;
    32 /** A scope represents an area of visibility in a Java program. The
    33  *  Scope class is a container for symbols which provides
    34  *  efficient access to symbols given their names. Scopes are implemented
    35  *  as hash tables with "open addressing" and "double hashing".
    36  *  Scopes can be nested; the next field of a scope points
    37  *  to its next outer scope. Nested scopes can share their hash tables.
    38  *
    39  *  <p><b>This is NOT part of any supported API.
    40  *  If you write code that depends on this, you do so at your own risk.
    41  *  This code and its internal interfaces are subject to change or
    42  *  deletion without notice.</b>
    43  */
    44 public class Scope {
    46     /** The number of scopes that share this scope's hash table.
    47      */
    48     private int shared;
    50     /** Next enclosing scope (with whom this scope may share a hashtable)
    51      */
    52     public Scope next;
    54     /** The scope's owner.
    55      */
    56     public Symbol owner;
    58     /** A hash table for the scope's entries.
    59      */
    60     Entry[] table;
    62     /** Mask for hash codes, always equal to (table.length - 1).
    63      */
    64     int hashMask;
    66     /** A linear list that also contains all entries in
    67      *  reverse order of appearance (i.e later entries are pushed on top).
    68      */
    69     public Entry elems;
    71     /** The number of elements in this scope.
    72      * This includes deleted elements, whose value is the sentinel.
    73      */
    74     int nelems = 0;
    76     /** A list of scopes to be notified if items are to be removed from this scope.
    77      */
    78     List<ScopeListener> listeners = List.nil();
    80     /** Use as a "not-found" result for lookup.
    81      * Also used to mark deleted entries in the table.
    82      */
    83     private static final Entry sentinel = new Entry(null, null, null, null);
    85     /** The hash table's initial size.
    86      */
    87     private static final int INITIAL_SIZE = 0x10;
    89     /** A value for the empty scope.
    90      */
    91     public static final Scope emptyScope = new Scope(null, null, new Entry[]{});
    93     /** Construct a new scope, within scope next, with given owner, using
    94      *  given table. The table's length must be an exponent of 2.
    95      */
    96     private Scope(Scope next, Symbol owner, Entry[] table) {
    97         this.next = next;
    98         Assert.check(emptyScope == null || owner != null);
    99         this.owner = owner;
   100         this.table = table;
   101         this.hashMask = table.length - 1;
   102     }
   104     /** Convenience constructor used for dup and dupUnshared. */
   105     private Scope(Scope next, Symbol owner, Entry[] table, int nelems) {
   106         this(next, owner, table);
   107         this.nelems = nelems;
   108     }
   110     /** Construct a new scope, within scope next, with given owner,
   111      *  using a fresh table of length INITIAL_SIZE.
   112      */
   113     public Scope(Symbol owner) {
   114         this(null, owner, new Entry[INITIAL_SIZE]);
   115     }
   117     /** Construct a fresh scope within this scope, with same owner,
   118      *  which shares its table with the outer scope. Used in connection with
   119      *  method leave if scope access is stack-like in order to avoid allocation
   120      *  of fresh tables.
   121      */
   122     public Scope dup() {
   123         return dup(this.owner);
   124     }
   126     /** Construct a fresh scope within this scope, with new owner,
   127      *  which shares its table with the outer scope. Used in connection with
   128      *  method leave if scope access is stack-like in order to avoid allocation
   129      *  of fresh tables.
   130      */
   131     public Scope dup(Symbol newOwner) {
   132         Scope result = new Scope(this, newOwner, this.table, this.nelems);
   133         shared++;
   134         // System.out.println("====> duping scope " + this.hashCode() + " owned by " + newOwner + " to " + result.hashCode());
   135         // new Error().printStackTrace(System.out);
   136         return result;
   137     }
   139     /** Construct a fresh scope within this scope, with same owner,
   140      *  with a new hash table, whose contents initially are those of
   141      *  the table of its outer scope.
   142      */
   143     public Scope dupUnshared() {
   144         return new Scope(this, this.owner, this.table.clone(), this.nelems);
   145     }
   147     /** Remove all entries of this scope from its table, if shared
   148      *  with next.
   149      */
   150     public Scope leave() {
   151         Assert.check(shared == 0);
   152         if (table != next.table) return next;
   153         while (elems != null) {
   154             int hash = getIndex(elems.sym.name);
   155             Entry e = table[hash];
   156             Assert.check(e == elems, elems.sym);
   157             table[hash] = elems.shadowed;
   158             elems = elems.sibling;
   159         }
   160         Assert.check(next.shared > 0);
   161         next.shared--;
   162         next.nelems = nelems;
   163         // System.out.println("====> leaving scope " + this.hashCode() + " owned by " + this.owner + " to " + next.hashCode());
   164         // new Error().printStackTrace(System.out);
   165         return next;
   166     }
   168     /** Double size of hash table.
   169      */
   170     private void dble() {
   171         Assert.check(shared == 0);
   172         Entry[] oldtable = table;
   173         Entry[] newtable = new Entry[oldtable.length * 2];
   174         for (Scope s = this; s != null; s = s.next) {
   175             if (s.table == oldtable) {
   176                 Assert.check(s == this || s.shared != 0);
   177                 s.table = newtable;
   178                 s.hashMask = newtable.length - 1;
   179             }
   180         }
   181         int n = 0;
   182         for (int i = oldtable.length; --i >= 0; ) {
   183             Entry e = oldtable[i];
   184             if (e != null && e != sentinel) {
   185                 table[getIndex(e.sym.name)] = e;
   186                 n++;
   187             }
   188         }
   189         // We don't need to update nelems for shared inherited scopes,
   190         // since that gets handled by leave().
   191         nelems = n;
   192     }
   194     /** Enter symbol sym in this scope.
   195      */
   196     public void enter(Symbol sym) {
   197         Assert.check(shared == 0);
   198         enter(sym, this);
   199     }
   201     public void enter(Symbol sym, Scope s) {
   202         enter(sym, s, s);
   203     }
   205     /**
   206      * Enter symbol sym in this scope, but mark that it comes from
   207      * given scope `s' accessed through `origin'.  The last two
   208      * arguments are only used in import scopes.
   209      */
   210     public void enter(Symbol sym, Scope s, Scope origin) {
   211         Assert.check(shared == 0);
   212         if (nelems * 3 >= hashMask * 2)
   213             dble();
   214         int hash = getIndex(sym.name);
   215         Entry old = table[hash];
   216         if (old == null) {
   217             old = sentinel;
   218             nelems++;
   219         }
   220         Entry e = makeEntry(sym, old, elems, s, origin);
   221         table[hash] = e;
   222         elems = e;
   224         //notify listeners
   225         for (List<ScopeListener> l = listeners; l.nonEmpty(); l = l.tail) {
   226             l.head.symbolAdded(sym, this);
   227         }
   228     }
   230     Entry makeEntry(Symbol sym, Entry shadowed, Entry sibling, Scope scope, Scope origin) {
   231         return new Entry(sym, shadowed, sibling, scope);
   232     }
   235     public interface ScopeListener {
   236         public void symbolAdded(Symbol sym, Scope s);
   237         public void symbolRemoved(Symbol sym, Scope s);
   238     }
   240     public void addScopeListener(ScopeListener sl) {
   241         listeners = listeners.prepend(sl);
   242     }
   244     /** Remove symbol from this scope.  Used when an inner class
   245      *  attribute tells us that the class isn't a package member.
   246      */
   247     public void remove(Symbol sym) {
   248         Assert.check(shared == 0);
   249         Entry e = lookup(sym.name);
   250         if (e.scope == null) return;
   252         // remove e from table and shadowed list;
   253         int i = getIndex(sym.name);
   254         Entry te = table[i];
   255         if (te == e)
   256             table[i] = e.shadowed;
   257         else while (true) {
   258             if (te.shadowed == e) {
   259                 te.shadowed = e.shadowed;
   260                 break;
   261             }
   262             te = te.shadowed;
   263         }
   265         // remove e from elems and sibling list
   266         te = elems;
   267         if (te == e)
   268             elems = e.sibling;
   269         else while (true) {
   270             if (te.sibling == e) {
   271                 te.sibling = e.sibling;
   272                 break;
   273             }
   274             te = te.sibling;
   275         }
   277         //notify listeners
   278         for (List<ScopeListener> l = listeners; l.nonEmpty(); l = l.tail) {
   279             l.head.symbolRemoved(sym, this);
   280         }
   281     }
   283     /** Enter symbol sym in this scope if not already there.
   284      */
   285     public void enterIfAbsent(Symbol sym) {
   286         Assert.check(shared == 0);
   287         Entry e = lookup(sym.name);
   288         while (e.scope == this && e.sym.kind != sym.kind) e = e.next();
   289         if (e.scope != this) enter(sym);
   290     }
   292     /** Given a class, is there already a class with same fully
   293      *  qualified name in this (import) scope?
   294      */
   295     public boolean includes(Symbol c) {
   296         for (Scope.Entry e = lookup(c.name);
   297              e.scope == this;
   298              e = e.next()) {
   299             if (e.sym == c) return true;
   300         }
   301         return false;
   302     }
   304     static final Filter<Symbol> noFilter = new Filter<Symbol>() {
   305         public boolean accepts(Symbol s) {
   306             return true;
   307         }
   308     };
   310     /** Return the entry associated with given name, starting in
   311      *  this scope and proceeding outwards. If no entry was found,
   312      *  return the sentinel, which is characterized by having a null in
   313      *  both its scope and sym fields, whereas both fields are non-null
   314      *  for regular entries.
   315      */
   316     public Entry lookup(Name name) {
   317         return lookup(name, noFilter);
   318     }
   319     public Entry lookup(Name name, Filter<Symbol> sf) {
   320         Entry e = table[getIndex(name)];
   321         if (e == null || e == sentinel)
   322             return sentinel;
   323         while (e.scope != null && (e.sym.name != name || !sf.accepts(e.sym)))
   324             e = e.shadowed;
   325         return e;
   326     }
   328     /*void dump (java.io.PrintStream out) {
   329         out.println(this);
   330         for (int l=0; l < table.length; l++) {
   331             Entry le = table[l];
   332             out.print("#"+l+": ");
   333             if (le==sentinel) out.println("sentinel");
   334             else if(le == null) out.println("null");
   335             else out.println(""+le+" s:"+le.sym);
   336         }
   337     }*/
   339     /** Look for slot in the table.
   340      *  We use open addressing with double hashing.
   341      */
   342     int getIndex (Name name) {
   343         int h = name.hashCode();
   344         int i = h & hashMask;
   345         // The expression below is always odd, so it is guaranteed
   346         // to be mutually prime with table.length, a power of 2.
   347         int x = hashMask - ((h + (h >> 16)) << 1);
   348         int d = -1; // Index of a deleted item.
   349         for (;;) {
   350             Entry e = table[i];
   351             if (e == null)
   352                 return d >= 0 ? d : i;
   353             if (e == sentinel) {
   354                 // We have to keep searching even if we see a deleted item.
   355                 // However, remember the index in case we fail to find the name.
   356                 if (d < 0)
   357                     d = i;
   358             } else if (e.sym.name == name)
   359                 return i;
   360             i = (i + x) & hashMask;
   361         }
   362     }
   364     public Iterable<Symbol> getElements() {
   365         return getElements(noFilter);
   366     }
   368     public Iterable<Symbol> getElements(final Filter<Symbol> sf) {
   369         return new Iterable<Symbol>() {
   370             public Iterator<Symbol> iterator() {
   371                 return new Iterator<Symbol>() {
   372                     private Scope currScope = Scope.this;
   373                     private Scope.Entry currEntry = elems;
   374                     {
   375                         update();
   376                     }
   378                     public boolean hasNext() {
   379                         return currEntry != null;
   380                     }
   382                     public Symbol next() {
   383                         Symbol sym = (currEntry == null ? null : currEntry.sym);
   384                         if (currEntry != null) {
   385                             currEntry = currEntry.sibling;
   386                         }
   387                         update();
   388                         return sym;
   389                     }
   391                     public void remove() {
   392                         throw new UnsupportedOperationException();
   393                     }
   395                     private void update() {
   396                         skipToNextMatchingEntry();
   397                         while (currEntry == null && currScope.next != null) {
   398                             currScope = currScope.next;
   399                             currEntry = currScope.elems;
   400                             skipToNextMatchingEntry();
   401                         }
   402                     }
   404                     void skipToNextMatchingEntry() {
   405                         while (currEntry != null && !sf.accepts(currEntry.sym)) {
   406                             currEntry = currEntry.sibling;
   407                         }
   408                     }
   409                 };
   410             }
   411         };
   412     }
   414     public Iterable<Symbol> getElementsByName(Name name) {
   415         return getElementsByName(name, noFilter);
   416     }
   418     public Iterable<Symbol> getElementsByName(final Name name, final Filter<Symbol> sf) {
   419         return new Iterable<Symbol>() {
   420             public Iterator<Symbol> iterator() {
   421                  return new Iterator<Symbol>() {
   422                     Scope.Entry currentEntry = lookup(name, sf);
   424                     public boolean hasNext() {
   425                         return currentEntry.scope != null;
   426                     }
   427                     public Symbol next() {
   428                         Scope.Entry prevEntry = currentEntry;
   429                         currentEntry = currentEntry.next(sf);
   430                         return prevEntry.sym;
   431                     }
   432                     public void remove() {
   433                         throw new UnsupportedOperationException();
   434                     }
   435                 };
   436             }
   437         };
   438     }
   440     public String toString() {
   441         StringBuilder result = new StringBuilder();
   442         result.append("Scope[");
   443         for (Scope s = this; s != null ; s = s.next) {
   444             if (s != this) result.append(" | ");
   445             for (Entry e = s.elems; e != null; e = e.sibling) {
   446                 if (e != s.elems) result.append(", ");
   447                 result.append(e.sym);
   448             }
   449         }
   450         result.append("]");
   451         return result.toString();
   452     }
   454     /** A class for scope entries.
   455      */
   456     public static class Entry {
   458         /** The referenced symbol.
   459          *  sym == null   iff   this == sentinel
   460          */
   461         public Symbol sym;
   463         /** An entry with the same hash code, or sentinel.
   464          */
   465         private Entry shadowed;
   467         /** Next entry in same scope.
   468          */
   469         public Entry sibling;
   471         /** The entry's scope.
   472          *  scope == null   iff   this == sentinel
   473          *  for an entry in an import scope, this is the scope
   474          *  where the entry came from (i.e. was imported from).
   475          */
   476         public Scope scope;
   478         public Entry(Symbol sym, Entry shadowed, Entry sibling, Scope scope) {
   479             this.sym = sym;
   480             this.shadowed = shadowed;
   481             this.sibling = sibling;
   482             this.scope = scope;
   483         }
   485         /** Return next entry with the same name as this entry, proceeding
   486          *  outwards if not found in this scope.
   487          */
   488         public Entry next() {
   489             return shadowed;
   490         }
   492         public Entry next(Filter<Symbol> sf) {
   493             if (shadowed.sym == null || sf.accepts(shadowed.sym)) return shadowed;
   494             else return shadowed.next(sf);
   495         }
   497         public Scope getOrigin() {
   498             // The origin is only recorded for import scopes.  For all
   499             // other scope entries, the "enclosing" type is available
   500             // from other sources.  See Attr.visitSelect and
   501             // Attr.visitIdent.  Rather than throwing an assertion
   502             // error, we return scope which will be the same as origin
   503             // in many cases.
   504             return scope;
   505         }
   506     }
   508     public static class ImportScope extends Scope {
   510         public ImportScope(Symbol owner) {
   511             super(owner);
   512         }
   514         @Override
   515         Entry makeEntry(Symbol sym, Entry shadowed, Entry sibling, Scope scope, Scope origin) {
   516             return new ImportEntry(sym, shadowed, sibling, scope, origin);
   517         }
   519         static class ImportEntry extends Entry {
   520             private Scope origin;
   522             ImportEntry(Symbol sym, Entry shadowed, Entry sibling, Scope scope, Scope origin) {
   523                 super(sym, shadowed, sibling, scope);
   524                 this.origin = origin;
   525             }
   527             @Override
   528             public Scope getOrigin() { return origin; }
   529         }
   530     }
   532     public static class StarImportScope extends ImportScope implements ScopeListener {
   534         public StarImportScope(Symbol owner) {
   535             super(owner);
   536         }
   538         public void importAll (Scope fromScope) {
   539             for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
   540                 if (e.sym.kind == Kinds.TYP && !includes(e.sym))
   541                     enter(e.sym, fromScope);
   542             }
   543             // Register to be notified when imported items are removed
   544             fromScope.addScopeListener(this);
   545         }
   547         public void symbolRemoved(Symbol sym, Scope s) {
   548             remove(sym);
   549         }
   550         public void symbolAdded(Symbol sym, Scope s) { }
   551     }
   553     /** An empty scope, into which you can't place anything.  Used for
   554      *  the scope for a variable initializer.
   555      */
   556     public static class DelegatedScope extends Scope {
   557         Scope delegatee;
   558         public static final Entry[] emptyTable = new Entry[0];
   560         public DelegatedScope(Scope outer) {
   561             super(outer, outer.owner, emptyTable);
   562             delegatee = outer;
   563         }
   564         public Scope dup() {
   565             return new DelegatedScope(next);
   566         }
   567         public Scope dupUnshared() {
   568             return new DelegatedScope(next);
   569         }
   570         public Scope leave() {
   571             return next;
   572         }
   573         public void enter(Symbol sym) {
   574             // only anonymous classes could be put here
   575         }
   576         public void enter(Symbol sym, Scope s) {
   577             // only anonymous classes could be put here
   578         }
   579         public void remove(Symbol sym) {
   580             throw new AssertionError(sym);
   581         }
   582         public Entry lookup(Name name) {
   583             return delegatee.lookup(name);
   584         }
   585     }
   587     /** A class scope adds capabilities to keep track of changes in related
   588      *  class scopes - this allows client to realize whether a class scope
   589      *  has changed, either directly (because a new member has been added/removed
   590      *  to this scope) or indirectly (i.e. because a new member has been
   591      *  added/removed into a supertype scope)
   592      */
   593     public static class CompoundScope extends Scope implements ScopeListener {
   595         public static final Entry[] emptyTable = new Entry[0];
   597         private List<Scope> subScopes = List.nil();
   598         private int mark = 0;
   600         public CompoundScope(Symbol owner) {
   601             super(null, owner, emptyTable);
   602         }
   604         public void addSubScope(Scope that) {
   605            if (that != null) {
   606                 subScopes = subScopes.prepend(that);
   607                 that.addScopeListener(this);
   608                 mark++;
   609                 for (ScopeListener sl : listeners) {
   610                     sl.symbolAdded(null, this); //propagate upwards in case of nested CompoundScopes
   611                 }
   612            }
   613          }
   615         public void symbolAdded(Symbol sym, Scope s) {
   616             mark++;
   617             for (ScopeListener sl : listeners) {
   618                 sl.symbolAdded(sym, s);
   619             }
   620         }
   622         public void symbolRemoved(Symbol sym, Scope s) {
   623             mark++;
   624             for (ScopeListener sl : listeners) {
   625                 sl.symbolRemoved(sym, s);
   626             }
   627         }
   629         public int getMark() {
   630             return mark;
   631         }
   633         @Override
   634         public String toString() {
   635             StringBuilder buf = new StringBuilder();
   636             buf.append("CompoundScope{");
   637             String sep = "";
   638             for (Scope s : subScopes) {
   639                 buf.append(sep);
   640                 buf.append(s);
   641                 sep = ",";
   642             }
   643             buf.append("}");
   644             return buf.toString();
   645         }
   647         @Override
   648         public Iterable<Symbol> getElements(final Filter<Symbol> sf) {
   649             return new Iterable<Symbol>() {
   650                 public Iterator<Symbol> iterator() {
   651                     return new CompoundScopeIterator(subScopes) {
   652                         Iterator<Symbol> nextIterator(Scope s) {
   653                             return s.getElements(sf).iterator();
   654                         }
   655                     };
   656                 }
   657             };
   658         }
   660         @Override
   661         public Iterable<Symbol> getElementsByName(final Name name, final Filter<Symbol> sf) {
   662             return new Iterable<Symbol>() {
   663                 public Iterator<Symbol> iterator() {
   664                     return new CompoundScopeIterator(subScopes) {
   665                         Iterator<Symbol> nextIterator(Scope s) {
   666                             return s.getElementsByName(name, sf).iterator();
   667                         }
   668                     };
   669                 }
   670             };
   671         }
   673         abstract class CompoundScopeIterator implements Iterator<Symbol> {
   675             private Iterator<Symbol> currentIterator;
   676             private List<Scope> scopesToScan;
   678             public CompoundScopeIterator(List<Scope> scopesToScan) {
   679                 this.scopesToScan = scopesToScan;
   680                 update();
   681             }
   683             abstract Iterator<Symbol> nextIterator(Scope s);
   685             public boolean hasNext() {
   686                 return currentIterator != null;
   687             }
   689             public Symbol next() {
   690                 Symbol sym = currentIterator.next();
   691                 if (!currentIterator.hasNext()) {
   692                     update();
   693                 }
   694                 return sym;
   695             }
   697             public void remove() {
   698                 throw new UnsupportedOperationException();
   699             }
   701             private void update() {
   702                 while (scopesToScan.nonEmpty()) {
   703                     currentIterator = nextIterator(scopesToScan.head);
   704                     scopesToScan = scopesToScan.tail;
   705                     if (currentIterator.hasNext()) return;
   706                 }
   707                 currentIterator = null;
   708             }
   709         }
   711         @Override
   712         public Entry lookup(Name name, Filter<Symbol> sf) {
   713             throw new UnsupportedOperationException();
   714         }
   716         @Override
   717         public Scope dup(Symbol newOwner) {
   718             throw new UnsupportedOperationException();
   719         }
   721         @Override
   722         public void enter(Symbol sym, Scope s, Scope origin) {
   723             throw new UnsupportedOperationException();
   724         }
   726         @Override
   727         public void remove(Symbol sym) {
   728             throw new UnsupportedOperationException();
   729         }
   730     }
   732     /** An error scope, for which the owner should be an error symbol. */
   733     public static class ErrorScope extends Scope {
   734         ErrorScope(Scope next, Symbol errSymbol, Entry[] table) {
   735             super(next, /*owner=*/errSymbol, table);
   736         }
   737         public ErrorScope(Symbol errSymbol) {
   738             super(errSymbol);
   739         }
   740         public Scope dup() {
   741             return new ErrorScope(this, owner, table);
   742         }
   743         public Scope dupUnshared() {
   744             return new ErrorScope(this, owner, table.clone());
   745         }
   746         public Entry lookup(Name name) {
   747             Entry e = super.lookup(name);
   748             if (e.scope == null)
   749                 return new Entry(owner, null, null, null);
   750             else
   751                 return e;
   752         }
   753     }
   754 }

mercurial