001: // Copyright (c) 1997 Per M.A. Bothner.
002: // This is free software; for terms and warranty disclaimer see ./COPYING.
003:
004: package gnu.bytecode;
005:
006: import java.io.*;
007:
008: public class Scope {
009: /** The enclosing scope. */
010: Scope parent;
011: Scope nextSibling;
012: Scope firstChild, lastChild;
013:
014: int start_pc;
015: int end_pc;
016: Variable vars;
017: Variable last_var;
018:
019: // Variable lookup (String name);
020: public final Variable firstVar() {
021: return vars;
022: }
023:
024: public VarEnumerator allVars() {
025: return new VarEnumerator(this );
026: }
027:
028: /** Link this scope as the next child of its parent scope. */
029: public void linkChild(Scope parent) {
030: this .parent = parent;
031: if (parent == null)
032: return;
033: if (parent.lastChild == null)
034: parent.firstChild = this ;
035: else
036: parent.lastChild.nextSibling = this ;
037: parent.lastChild = this ;
038: }
039:
040: public Variable addVariable(CodeAttr code, Type type, String name) {
041: Variable var = new Variable(name, type);
042: addVariable(code, var);
043: return var;
044: }
045:
046: public void addVariable(Variable var) {
047: if (last_var == null)
048: vars = var;
049: else
050: last_var.next = var;
051: last_var = var;
052: }
053:
054: /* Add a new Variable, linking it in after a given Variable, */
055: public void addVariableAfter(Variable prev, Variable var) {
056: if (prev == null) { // Put first
057: var.next = vars;
058: vars = var;
059: } else {
060: var.next = prev.next;
061: prev.next = var;
062: }
063: if (last_var == prev)
064: last_var = var;
065: if (var.next == var)
066: throw new Error("cycle");
067: }
068:
069: public void addVariable(CodeAttr code, Variable var) {
070: var.start_pc = code == null ? 0 : code.PC;
071: addVariable(var);
072: if (var.isSimple() && code != null)
073: var.allocateLocal(code);
074: }
075:
076: /**
077: * Return a variable the scope, by numerical index.
078: * @param index the number of the variable
079: */
080: public Variable getVariable(int index) {
081: Variable var = vars;
082: while (--index >= 0)
083: var = var.next;
084: return var;
085: }
086:
087: static boolean equals(byte[] name1, byte[] name2) {
088: if (name1.length != name2.length)
089: return false;
090: if (name1 == name2)
091: return true;
092: for (int i = name1.length; --i >= 0;)
093: if (name1[i] != name2[i])
094: return false;
095: return true;
096: }
097:
098: public void setStartPC(int PC) {
099: start_pc = PC;
100: for (Variable var = firstVar(); var != null; var = var
101: .nextVar())
102: var.start_pc = PC;
103: }
104:
105: /**
106: * Search by name for a Variable in this Scope (only).
107: * @param name name to search for
108: * @return the Variable, or null if not found (in this scope).
109: */
110: Variable lookup(String name) {
111: for (Variable var = vars; var != null; var = var.next) {
112: if (name.equals(var.name))
113: return var;
114: }
115: return null;
116: }
117: };
|