问题描述
我目前正在学习 Antlr4。 我尝试运行的文档中有一个示例:
DefPhase.java.
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.ParseTreeProperty;
public class DefPhase extends CymbolBaseListener {
ParseTreeProperty<Scope> scopes = new ParseTreeProperty<Scope>();
GlobalScope globals;
Scope currentScope; // define symbols in this scope
public void enterFile(CymbolParser.FileContext ctx) {
globals = new GlobalScope(null);
currentScope = globals;
}
public void exitFile(CymbolParser.FileContext ctx) {
System.out.println(globals);
}
public void enterFunctionDecl(CymbolParser.FunctionDeclContext ctx) {
String name = ctx.ID().getText();
int typetokenType = ctx.type().start.getType();
Symbol.Type type = CheckSymbols.getType(typetokenType);
// push new scope by making new one that points to enclosing scope
FunctionSymbol function = new FunctionSymbol(name,type,currentScope);
currentScope.define(function); // Define function in current scope
saveScope(ctx,function); // Push: set function's parent to current
currentScope = function; // Current scope is Now function scope
}
void saveScope(ParserRuleContext ctx,Scope s) { scopes.put(ctx,s); }
public void exitFunctionDecl(CymbolParser.FunctionDeclContext ctx) {
System.out.println(currentScope);
currentScope = currentScope.getEnclosingScope(); // pop scope
}
public void enterBlock(CymbolParser.BlockContext ctx) {
// push new local scope
currentScope = new LocalScope(currentScope);
saveScope(ctx,currentScope);
}
public void exitBlock(CymbolParser.BlockContext ctx) {
System.out.println(currentScope);
currentScope = currentScope.getEnclosingScope(); // pop scope
}
public void exitFormalParameter(CymbolParser.FormalParameterContext ctx) {
defineVar(ctx.type(),ctx.ID().getSymbol());
}
public void exitvarDecl(CymbolParser.VarDeclContext ctx) {
defineVar(ctx.type(),ctx.ID().getSymbol());
}
void defineVar(CymbolParser.TypeContext typeCtx,Token nametoken) {
int typetokenType = typeCtx.start.getType();
Symbol.Type type = CheckSymbols.getType(typetokenType);
VariableSymbol var = new VariableSymbol(nametoken.getText(),type);
currentScope.define(var); // Define symbol in current scope
}
}
由于某种原因,Symbol.Type 无法识别。挖了之后,似乎以前的 Antlr 有一个名为 symtab 的库。最新的是 1.0.8。该库包含所有相关定义,但仍不包含 Symbol.Type。 Anltr4 有专用的符号表吗?
我真的需要一些关于这个问题的帮助
解决方法
我认为你正在谈论的这个例子是这样的:https://github.com/remenska/Grammars/blob/master/book-examples/listeners/DefPhase.java
如果您查看它所在的包,您会发现类型 Symbol (https://github.com/remenska/Grammars/blob/master/book-examples/listeners/Symbol.java) 并且它具有字段类型。也许你可以以某种方式使用它。所以它真的来自这本书的例子。