FAQ - C Target
How can Antlr Parser actions know the file names and line numbers from a C preprocessed file?
TerryArnold
One way is to follow this path:
Derive your own token from CommonToken and add file number field to it;
Get the lexer to produce those tokens and the parser to accept them;
Build a file table in the lexer and refer to it in error messages;
Keep track of current file in the lexer in case you need error messages from thelexer;
Keep track of current line number in the inferred file by setting it in your PPLINE rule then incrementing it in your NEWLINE rule;
Set the line and file number at the end of each rule (or override the nextToken stuff to set this automatically);
Start down that path and you will see the best way for your requirements.
In the C target there are user fields for storing such additional information so you can do the same thing as deriving a token.
AST
What is the ASTLabelType to be specified for tree grammar in C target?
KevinCummings
Use following:
options
{
ASTLabelType = pANTLR3_BASE_TREE;
language = C;
}How to skip a subtree with the C target of ANTLR v3.4?
Requirement: Implement an if/then/else interpreter. Parse only either the "then" or the "else" statement skipping the other one and going to the end of the if statement after having handled it.
GonzagueReydet
Sample grammar snippet: Custom function that walk the subtree counting the UP & DOWN tokens and ignoring all other tokens.
// ^(IF expression statement (ELSE statement)?)
if_
@declarations { ANTLR3_MARKER thenIdx, elseIdx = 0; }
: ^(IF expression
{
thenIdx = INDEX();
ignoreSubTree(ctx);
if (LA(1) == ELSE) {
MATCHT(ELSE, NULL);
elseIdx = INDEX();
ignoreSubTree(ctx);
}
})
{ // My code that rewind to either then or else block }
;and the ignoreSubTree() function is implemented as following:
static void ignoreSubTree(psshell_tree ctx)
{
ebd_sint32_t nestedS32 = 0;
do {
MATCHANYT();
if (HASEXCEPTION()) {
return;
}
switch(LA(1)) {
case DOWN:
nestedS32++;
break;
case UP:
nestedS32--;
break;
default:
break;
}
} while (nestedS32 > 0);
MATCHANYT(); // Eat last UP token
}How to get rid of bug in AST walking while implementing control flow in pre-ANTLR 3.2.1?
sample:
In an AST walker grammar following this example : http://www.antlr.org/wiki/display/CS652/Tree-based+interpreters
ifstat
: ^('if' c=expr s=. e=.?) // ^('if' expr stat stat?)In the generated code , variables e,s are not defined! (yet they are assigned values ) and the compiler complains about that , but when they are defined by hand (under the definition of variable c ) the code compiles fine.
MohamedYousef
Till the bug is fixed (>= 3.2.1), follow these guidelines
1. use something like
ifstat
: ^('if' c=expr s=. e=.)
{
pANTLR3_BASE_TREE s=(pANTLR3_BASE_TREE)LT(1);
pANTLR3_BASE_TREE e=(pANTLR3_BASE_TREE)LT(1);
You would not have the s=. and e=., just code to consume what you need.
//do whatever with return values or custom nodes in e&s
}