intf(int x, float y){ g(); // forward reference is ok i = 3; // no declaration for i (error) g = 4; // g is not variable (error) return x + y; // x, y are defined, so no problem }
voidg(){ int x = 0; float y; y = 9; // y is defined f(); // backward reference is ok z(); // no such function (error) y(); // y is not function (error) x = f; // f is not a variable (error) }
public Symbol resolve(String name){ Symbol s = symbols.get(name); if ( s!=null ) return s;//在当前作用域找到了,直接返回 //如果临近作用域不空,那么就去临近作用域找 //比如,一个函数内,符号定义没找到,就去往上(全局)找 if ( enclosingScope != null ) return enclosingScope.resolve(name); //还找不到,那就是未定义,报错 returnnull; // not found }
publicvoiddefine(Symbol sym){ symbols.put(sym.name, sym); sym.scope = this; // track the scope in each symbol }
public Scope getEnclosingScope(){ return enclosingScope; }
public String toString(){ return getScopeName()+":"+symbols.keySet().toString(); } }
parser.setBuildParseTree(true); ParseTree tree = parser.file(); // show tree in text form //System.out.println(tree.toStringTree(parser));
ParseTreeWalker walker = new ParseTreeWalker(); DefPhase def = new DefPhase(); walker.walk(def, tree); // create next phase and feed symbol table info from def to ref phase RefPhase ref = new RefPhase(def.globals, def.scopes); walker.walk(ref, tree);
# muhe @ muheMacBookPro in ~/Study/antlr_study/chapter_8_4 [16:03:56] $ java CheckSymbols vars.cymbol locals:[] function<f:tINT>:[<x:tINT>, <y:tFLOAT>] locals:[x, y] function<g:tVOID>:[] globals:[f, g] line 3:4 no such variable: i line 4:4 g is not a variable line 13:4 no such function: z line 14:4 y is not a function line 15:8 f is not a variable