I have a Lexer and a Parser called y86 Lexer and Parser which work as far as I know. But I have a file with y86 commands and I want to parse them using Java. So far I have code as follows.
y86Lexer y86 = null;
CommonTokenStream tokenStream = null;
y86Parser y86p = null;
try
{
y86 = new y86Lexer(CharStreams.fromFileName("C:\\Users\\saigbomian\\Documents"
+ "\\LearnANTLR\\src\\sum.ys"));
tokenStream = new CommonTokenStream(y86);
y86p = new y86Parser(tokenStream);
}
catch (IOException e)
{
log.error("Error occured while reading from file");
e.printStackTrace();
}
I'm not sure how to do the parsing. I have seen people use something like y86Parser.CompilationUnitContext but I can seem to find that class. I have tried printing from the Listeners antlr creates but I don't know how to trigger these listeners
For each rule ruleName
in your grammar, the y86Parser
class will contain a class named RuleNameContext
and a method named ruleName()
, which will parse the input according to that rule and return an instance of the RuleNameContext
class containing the parse tree. You can then use listeners or visitors to walk that parse tree.
So if you don't have a compilationUnit
method or a CompilationUnitContext
class, your grammar probably just doesn't have a rule named compilationUnit
. Instead you should pick a rule that you do have and call the method corresponding to that rule.