Most examples I find of creating an arithmetic expression parser with ANTLR have them put almost everything in the grammar file.
I however need to parse the expression without putting everything in the .g4 file.
grammar Mau;
program
: statement*
;
statement
:( moduleDeclaration
| whileStatement
| loopStatement
| ifStatement
| varStatement
| funcStatement
| expr
) ';'
;
funcStatement
: 'func' IDENTIFIER '(' ( IDENTIFIER (',' IDENTIFIER)* )? ')' block
;
moduleDeclaration
: 'module' IDENTIFIER
;
varStatement
: IDENTIFIER? IDENTIFIER '=' expr
;
whileStatement
: 'while' expr block
;
ifStatement
: 'if' expr block
;
loopStatement
: 'loop' block
;
block
: '{' statement* '}'
;
expr
: multiplyMath (('+' | '-') multiplyMath)*
;
multiplyMath
: mathAtom (('*' | '/') mathAtom)*
;
mathAtom
: number
| STRING
| IDENTIFIER
| '(' expr ')'
| IDENTIFIER '(' expr (',' expr)+ ')'
;
number returns [double value]
: num=NUMBER { $value = Double.parseDouble($num.getText()); }
;
STRING: '"' (~["])* '"';
WHITESPACE: ('\t' | ' ' | '\r' | '\n' | '\u000C')+ -> skip;
IDENTIFIER: ('a'..'z' | 'A'..'Z' | '_') ('a'..'z' | 'A'..'Z' | '_' | '0'..'9')*;
NUMBER: ('0' .. '9') + ('.' ('0' .. '9')+)?;
When ever the parser sees a statement, it runs this code:
@Override
public void enterStatement(MauParser.StatementContext ctx) {
if (ctx.moduleDeclaration() != null) {
ModuleDeclarationContext statement = ctx.moduleDeclaration();
Mau.modules.put(statement.IDENTIFIER().getText(), mau);
} else if (ctx.varStatement() != null) {
VarStatementContext statement = ctx.varStatement();
mau.vars.put(statement.IDENTIFIER(1).getText(), mau.expr(statement.expr(), Mau.modules.get(statement.IDENTIFIER(0).getText())));
}
}
Whenever it needs to parse an expression, it calls mau.expr(ExprContext, MauModule)
So.. the question is:
How do I use a for-loop over the children of the ExprContext?
I cannot use ctx.children
as I do not know whether or not it's a number as NumberContext has a value
field in it.
This question is so poor-ly made.
Best Answer
ExprContext.MultiplyMath()
will return aList<MultiplyMathContext>
that you can use to iterate over, byfor(MauParser.MultiplyMathContext multiplyMathContext : ExprContext.MultiplyMath()) { (do something here) }