ANTLR Parse Grammar -> Tree Grammar - antlr

Our last assignment for our compiler theory class has us creating a compiler for a small subset of Java (not MiniJava). Our prof gave us the option of using whatever tools we wish, and after a lot of poking around, I settled on ANTLR. I've managed to get the scanner and the parser up and running, and the parser outputting an AST. I'm stuck now trying to get a tree grammar file to compile. I understand the basic idea is to copy the grammar rules from the parser and eliminate most of the code, leaving the rewrite rules in place, but it doesn't seem to want to compile (offendingToken error). Am I on the right track? Am I missing something trivial?
Tree Grammar:
tree grammar J0_SemanticAnalysis;
options {
language = Java;
tokenVocab = J0_Parser;
ASTLabelType = CommonTree;
}
#header
{
package ritterre.a4;
import java.util.Map;
import java.util.HashMap;
}
#members
{
}
walk
: compilationunit
;
compilationunit
: ^(UNIT importdeclaration* classdeclaration*)
;
importdeclaration
: ^(IMP_DEC IDENTIFIER+)
;
classdeclaration
: ^(CLASS IDENTIFIER ^(EXTENDS IDENTIFIER)? fielddeclaration* methoddeclaration*)
;
fielddeclaration
: ^(FIELD_DEC IDENTIFIER type visibility? STATIC?)
;
methoddeclaration
: ^(METHOD_DEC IDENTIFIER type visibility? STATIC? ^(PARAMS parameter+)? body)
;
visibility
: PRIVATE
| PUBLIC
;
parameter
: ^(PARAM IDENTIFIER type)
;
body
: ^(BODY ^(DECLARATIONS localdeclaration*) ^(STATEMENTS statement*))
;
localdeclaration
: ^(DECLARATION type IDENTIFIER)
;
statement
: assignment
| ifstatement
| whilestatement
| returnstatement
| callstatement
| printstatement
| block
;
assignment
: ^(ASSIGN IDENTIFIER+ expression? expression)
;
ifstatement
: ^(IF relation statement ^(ELSE statement)?)
;
whilestatement
: ^(WHILE relation statement)
;
returnstatement
: ^(RETURN expression?)
;
callstatement
: ^(CALL IDENTIFIER+ expression+)
;
printstatement
: ^(PRINT expression)
;
block
: ^(STATEMENTS statement*)
;
relation
// : expression (LTHAN | GTHAN | EQEQ | NEQ)^ expression
: ^(LTHAN expression expression)
| ^(GTHAN expression expression)
| ^(EQEQ expression expression)
| ^(NEQ expression expression)
;
expression
// : (PLUS | MINUS)? term ((PLUS | MINUS)^ term)*
: ^(PLUS term term)
| ^(MINUS term term)
;
term
// : factor ((MULT | DIV)^ factor)*
: ^(MULT factor factor)
| ^(DIV factor factor)
;
factor
: NUMBER
| IDENTIFIER (DOT IDENTIFIER | LBRAC expression RBRAC)?
| NULL
| NEW IDENTIFIER LPAREN RPAREN
| NEW (INT | IDENTIFIER) (LBRAC RBRAC)?
;
type
: (INT | IDENTIFIER) (LBRAC RBRAC)?
| VOID
;
Parser Grammar:
parser grammar J0_Parser;
options
{
output = AST; // Output an AST
tokenVocab = J0_Scanner; // Pull Tokens from Scanner
//greedy = true; // forcing this throughout?! success!!
//cannot force greedy true throughout. bad things happen and the parser doesnt build
}
tokens
{
UNIT;
IMP_DEC;
FIELD_DEC;
METHOD_DEC;
PARAMS;
PARAM;
BODY;
DECLARATIONS;
STATEMENTS;
DECLARATION;
ASSIGN;
CALL;
}
#header { package ritterre.a4; }
// J0 - Extended Specification - EBNF
parse
: compilationunit EOF -> compilationunit
;
compilationunit
: importdeclaration* classdeclaration*
-> ^(UNIT importdeclaration* classdeclaration*)
;
importdeclaration
: IMPORT IDENTIFIER (DOT IDENTIFIER)* SCOLON
-> ^(IMP_DEC IDENTIFIER+)
;
classdeclaration
: (PUBLIC)? CLASS n=IDENTIFIER (EXTENDS e=IDENTIFIER)? LBRAK (fielddeclaration|methoddeclaration)* RBRAK
-> ^(CLASS $n ^(EXTENDS $e)? fielddeclaration* methoddeclaration*)
;
fielddeclaration
: visibility? STATIC? type IDENTIFIER SCOLON
-> ^(FIELD_DEC IDENTIFIER type visibility? STATIC?)
;
methoddeclaration
: visibility? STATIC? type IDENTIFIER LPAREN (parameter (COMMA parameter)*)? RPAREN body
-> ^(METHOD_DEC IDENTIFIER type visibility? STATIC? ^(PARAMS parameter+)? body)
;
visibility
: PRIVATE
| PUBLIC
;
parameter
: type IDENTIFIER
-> ^(PARAM IDENTIFIER type)
;
body
: LBRAK localdeclaration* statement* RBRAK
-> ^(BODY ^(DECLARATIONS localdeclaration*) ^(STATEMENTS statement*))
;
localdeclaration
: type IDENTIFIER SCOLON
-> ^(DECLARATION type IDENTIFIER)
;
statement
: assignment
| ifstatement
| whilestatement
| returnstatement
| callstatement
| printstatement
| block
;
assignment
: IDENTIFIER (DOT IDENTIFIER | LBRAC a=expression RBRAC)? EQ b=expression SCOLON
-> ^(ASSIGN IDENTIFIER+ $a? $b)
;
ifstatement
: IF LPAREN relation RPAREN statement (options {greedy=true;} : ELSE statement)?
-> ^(IF relation statement ^(ELSE statement)?)
;
whilestatement
: WHILE LPAREN relation RPAREN statement
-> ^(WHILE relation statement)
;
returnstatement
: RETURN expression? SCOLON
-> ^(RETURN expression?)
;
callstatement
: IDENTIFIER (DOT IDENTIFIER)? LPAREN (expression (COMMA expression)*)? RPAREN SCOLON
-> ^(CALL IDENTIFIER+ expression+)
;
printstatement
: PRINT LPAREN expression RPAREN SCOLON
-> ^(PRINT expression)
;
block
: LBRAK statement* RBRAK
-> ^(STATEMENTS statement*)
;
relation
: expression (LTHAN | GTHAN | EQEQ | NEQ)^ expression
;
expression
: (PLUS | MINUS)? term ((PLUS | MINUS)^ term)*
;
term
: factor ((MULT | DIV)^ factor)*
;
factor
: NUMBER
| IDENTIFIER (DOT IDENTIFIER | LBRAC expression RBRAC)?
| NULL
| NEW IDENTIFIER LPAREN RPAREN
| NEW (INT | IDENTIFIER) (LBRAC RBRAC)?
;
type
: (INT | IDENTIFIER) (LBRAC RBRAC)?
| VOID
;

The problem is that in your tree grammar, you do the following (3 times I believe):
classdeclaration
: ^(CLASS ... ^(EXTENDS IDENTIFIER)? ... )
;
the ^(EXTENDS IDENTIFIER)? part is wrong: you need to wrap the tree around parenthesis, and only then make it optional:
classdeclaration
: ^(CLASS ... (^(EXTENDS IDENTIFIER))? ... )
;
However, it would be a bit too easy if that was all, wouldn't it? :)
When you fix the problem mentioned above, ANTLR will complain that the tree grammar is ambiguous when trying to generate a tree-walker from your tree grammar. ANTLR will throw the following towards you:
error(211): J0_SemanticAnalysis.g:61:26: [fatal] rule assignment has non-LL(*)
decision due to recursive rule invocations reachable from alts 1,2. Resolve by
left-factoring or using syntactic predicates or using backtrack=true option.
It complains about the assignment rule in your grammar:
assignment
: ^(ASSIGN IDENTIFIER+ expression? expression)
;
since ANTLR is an LL parser generator1, it parses tokens from left to right. Therefor the optional expression in IDENTIFIER+ expression? expression makes the grammar ambiguous. Fix this by moving the ? to the last expression:
assignment
: ^(ASSIGN IDENTIFIER+ expression expression?)
;
1 don't let the last two letters in the name ANTLR mislead you, they stand for Language Recognition, not the class of parsers it generates!

Related

How do I convert this Antlr3 AST to Antlr4?

I'm trying to convert my existing Antlr3 project to Antlr4 to get more functionality. I have this grammar that wouldn't compile with Antlr4.9
expr
: term ( OR^ term )* ;
and
factor
: ava | NOT^ factor | (LPAREN! expr RPAREN!) ;
Mostly because Antlr4 doesn't support ^ and ! anymore. From the documentation it seems like those are
AST root operator. When generating abstract syntax trees (ASTs), token
references suffixed with the "^" root operator force AST nodes to be
created and added as the root of the current tree. This symbol is only
effective when the buildAST option is set. More information about ASTs
is also available.
AST exclude operator. When generating abstract syntax trees, token
references suffixed with the "!" exclude operator are not included in
the AST constructed for that rule. Rule references can also be
suffixed with the exclude operator, which implies that, while the tree
for the referenced rule is constructed, it is not linked into the tree
for the referencing rule. This symbol is only effective when the
buildAST option is set. More information about ASTs is also available.
If I took those out it would compile but I'm not sure what do those mean and how would Antlr4 supports it.
LPAREN and RPAREN is tokens
tokens {
EQUALS = '=';
LPAREN = '(';
RPAREN = ')';
}
which Antlr4 kindly provides the way to convert that in the error messages but not ^ and !. The grammar is for parsing boolean expression for example (a=b AND b=c)
I think this is the rule
targetingexpr returns [boolean value]
: expr { $value = $expr.value; } ;
expr returns [boolean value]
: ^(NOT a=expr) { $value = !a; }
| ^(AND a=expr b=expr) { $value = a && b; }
| ^(OR a=expr b=expr) { $value = a || b; }
| ^(EQUALS A=ALPHANUM B=ALPHANUM) { $value = targetingContext.contains($A.text,$B.text); }
;
The v3 grammar:
...
tokens {
EQUALS = '=';
LPAREN = '(';
RPAREN = ')';
}
...
expr
: term ( OR^ term )* ;
factor
: ava | NOT^ factor | (LPAREN! expr RPAREN!) ;
in v4 would look like this:
...
expr
: term ( OR term )* ;
factor
: ava | NOT factor | (LPAREN expr RPAREN) ;
EQUALS : '=';
LPAREN : '(';
RPAREN : ')';
So, just remove the inline ^ and ! operators (tree rewriting is no longer available in ANTLR4), and move the literal tokens in the tokens { ... } sections into own lexer rules.
I think this is the rule
targetingexpr returns [boolean value]
: expr { $value = $expr.value; } ;
expr returns [boolean value]
: ^(NOT a=expr) { $value = !a; }
| ^(AND a=expr b=expr) { $value = a && b; }
| ^(OR a=expr b=expr) { $value = a || b; }
| ^(EQUALS A=ALPHANUM B=ALPHANUM) { $value = targetingContext.contains($A.text,$B.text); }
;
What you posted there is part of a tree grammar for which there is no equivalent. In ANTLR4 you'd use a visitor to evaluate your expressions instead of inside a tree grammar.

Decision can match input such as "MULOP LETTER" using multiple alternatives: 1, 2

I'm getting this error
[22:52:55] warning(200): ProjLang.g:53:30:
Decision can match input such as "MULOP LETTER" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
It seems like there could be some ambiguity in my grammar from my googling. I don't know how I can remove the ambiguity.
fragment LETTER
: ('a'..'z') | ('A'..'Z');
fragment DIGIT
: ('0'..'9');
ADDOP : ('+'|'-'|'|')
;
MULOP : ('*'|'/'|'&')
;
RELOP : ('<'|'=')
;
LPAR : '(';
RPAR : ')';
BOOL : 'true'|'false';
LCURL : '{';
RCURL : '}';
// parser rules: non terminal states should be lowercase
input : expr EOF
;
expr : 'if' expr 'then' expr 'else' expr
| 'let'( 'val' id RELOP expr 'in' expr 'end'|'fun' id LPAR id RPAR RELOP expr 'in' expr 'end')
| 'while' expr 'do' expr
| LCURL expr (';'expr)* RCURL
| '!'expr
| id ':=' expr
| relexpr
;
relexpr
: arithexpr (RELOP arithexpr)?
;
arithexpr
: term (MULOP term)*
;
term : factor (MULOP factor)*
;
factor : num
| BOOL
| id (LPAR expr RPAR)?
| LPAR expr RPAR
;
id : LETTER (LETTER | DIGIT)*;
num : DIGIT+;
I expect to write a grammar without error message so I can generate a lexer and a parser for it.
These rules do essentially the same:
arithexpr
: term (MULOP term)*
;
term : factor (MULOP factor)*
;
If you combine them you will get:
arithexpr: factor (MULOP factor)* (MULOP factor (MULOP factor)*)*
which contains an ambiquity (which of the two MULOP tokens should be matched after the initial factor?). But from the rewrite it's easy to see what to do:
arithexpr: factor (MULOP factor)*;
which replaces the original term and arithexpr rules.

Antlr Skip text outside tag

Im trying to skip/ignore the text outside a custom tag:
This text is a unique token to skip < ?compo \5+5\ ?> also this < ?compo \1+1\ ?>
I tried with the follow lexer:
TAG_OPEN : '<?compo ' -> pushMode(COMPOSER);
mode COMPOSER;
TAG_CLOSE : ' ?>' -> popMode;
NUMBER_DIGIT : '1'..'9';
ZERO : '0';
LOGICOP
: OR
| AND
;
COMPAREOP
: EQ
| NE
| GT
| GE
| LT
| LE
;
WS : ' ';
NEWLINE : ('\r\n'|'\n'|'\r');
TAB : ('\t');
...
and parser:
instructions
: (TAG_OPEN statement TAG_CLOSE)+?;
statement
: if_statement
| else
| else_if
| if_end
| operation_statement
| mnemonic
| comment
| transparent;
But it doesn't work (I test it by using the intelliJ tester on the rule "instructions")...
I have also add some skip rules outside the "COMPOSER" mode:
TEXT_SKIP : TAG_CLOSE .*? (TAG_OPEN | EOF) -> skip;
But i don't have any results...
Someone can help me?
EDIT:
I change "instructions" and now the parser tree is correctly builded for every instruction of every tag:
instructions : (.*? TAG_OPEN statement TAG_CLOSE .*?)+;
But i have a not recognized character error outside the the tags...
Below is a quick demo that worked for me.
Lexer grammar:
lexer grammar CompModeLexer;
TAG_OPEN
: '<?compo' -> pushMode(COMPOSER)
;
OTHER
: . -> skip
;
mode COMPOSER;
TAG_CLOSE
: '?>' -> popMode
;
OPAR
: '('
;
CPAR
: ')'
;
INT
: '0'
| [1-9] [0-9]*
;
LOGICOP
: 'AND'
| 'OR'
;
COMPAREOP
: [<>!] '='
| [<>=]
;
MULTOP
: [*/%]
;
ADDOP
: [+-]
;
SPACE
: [ \t\r\n\f] -> skip
;
Parser grammar:
parser grammar CompModeParser;
options {
tokenVocab=CompModeLexer;
}
parse
: tag* EOF
;
tag
: TAG_OPEN statement TAG_CLOSE
;
statement
: expr
;
expr
: '(' expr ')'
| expr MULTOP expr
| expr ADDOP expr
| expr COMPAREOP expr
| expr LOGICOP expr
| INT
;
A test with the input This text is a unique token to skip <?compo 5+5 ?> also this <?compo 1+1 ?> resulted in the following tree:
I found another solution (not elegant as the previous):
Create a generic TEXT token in the general context (so outside the tag's mode)
TEXT : ( ~[<] | '<' ~[?])+ -> skip;
Create a parser rule for handle a generic text
code
: TEXT
| (TEXT? instruction TEXT?)+;
Create a parser rule for handle an instruction
instruction
: TAG_OPEN statement TAG_CLOSE;

Antlr4 Grammar for Function Application

I'm trying to write a simple lambda calculus grammar (show below). The issue I am having is that function application seems to be treated as right associative instead of left associative e.g. "f 1 2" is parsed as (f (1 2)) instead of ((f 1) 2). ANTLR has an assoc option for tokens, but I don't see how that helps here since there is no operator for function application. Does anyone see a solution?
LAMBDA : '\\';
DOT : '.';
OPEN_PAREN : '(';
CLOSE_PAREN : ')';
fragment ID_START : [A-Za-z+\-*/_];
fragment ID_BODY : ID_START | DIGIT;
fragment DIGIT : [0-9];
ID : ID_START ID_BODY*;
NUMBER : DIGIT+ (DOT DIGIT+)?;
WS : [ \t\r\n]+ -> skip;
parse : expr EOF;
expr : variable #VariableExpr
| number #ConstantExpr
| function_def #FunctionDefinition
| expr expr #FunctionApplication
| OPEN_PAREN expr CLOSE_PAREN #ParenExpr
;
function_def : LAMBDA ID DOT expr;
number : NUMBER;
variable : ID;
Thanks!
this breaks 4.1's pattern matcher for left-recursion. cleaned up in main branch I believe. try downloading last master and build. CUrrently 4.1 generates:
expr[int _p]
: ( {} variable
| number
| function_def
| OPEN_PAREN expr CLOSE_PAREN
)
(
{2 >= $_p}? expr
)*
;
for that rule. expr ref in loop is expr[0] actually, which isn't right.

Solving antlr left recursion

I'm trying to parse a language using ANTLR which can contain the following syntax:
someVariable, somVariable.someMember, functionCall(param).someMember, foo.bar.baz(bjork).buffalo().xyzzy
This is the ANTLR grammar which i've come up with so far, and the access_operation throws the error
The following sets of rules are mutually left-recursive [access_operation, expression]:
grammar Test;
options {
output=AST;
ASTLabelType=CommonTree;
}
tokens {
LHS;
RHS;
CALL;
PARAMS;
}
start
: body? EOF
;
body
: expression (',' expression)*
;
expression
: function -> ^(CALL)
| access_operation
| atom
;
access_operation
: (expression -> ^(LHS)) '.'! (expression -> ^(RHS))
;
function
: (IDENT '(' body? ')') -> ^(IDENT PARAMS?)
;
atom
: IDENT
| NUMBER
;
fragment LETTER : ('a'..'z' | 'A'..'Z');
fragment DIGIT : '0'..'9';
IDENT : (LETTER)+ ;
NUMBER : (DIGIT)+ ;
SPACE : (' ' | '\t' | '\r' | '\n') { $channel=HIDDEN; };
What i could manage so far was to refactor the access_operation rule to '.' expression which generates an AST where the access_operation node only contains the right side of the operation.
What i'm looking for instead is something like this:
How can the left-recursion problem solved in this case?
By "wrong AST" I'll make a semi educated guess that, for input like "foo.bar.baz", you get an AST where foo is the root with bar as a child who in its turn has baz as a child, which is a leaf in the AST. You may want to have this reversed. But I'd not go for such an AST if I were you: I'd keep the AST as flat as possible:
foo
/ | \
/ | \
bar baz ...
That way, evaluating is far easier: you simply look up foo, and then walk from left to right through its children.
A quick demo:
grammar Test;
options {
output=AST;
ASTLabelType=CommonTree;
}
tokens {
BODY;
ACCESS;
CALL;
PARAMS;
}
start
: body EOF -> body
;
body
: expression (',' expression)* -> ^(BODY expression+)
;
expression
: atom
;
atom
: NUMBER
| (IDENT -> IDENT) ( tail -> ^(IDENT tail)
| call tail? -> ^(CALL IDENT call tail?)
)?
;
tail
: (access)+
;
access
: ('.' IDENT -> ^(ACCESS IDENT)) (call -> ^(CALL IDENT call))?
;
call
: '(' (expression (',' expression)*)? ')' -> ^(PARAMS expression*)
;
IDENT : LETTER+;
NUMBER : DIGIT+;
SPACE : (' ' | '\t' | '\r' | '\n') {$channel=HIDDEN;};
fragment LETTER : ('a'..'z' | 'A'..'Z');
fragment DIGIT : '0'..'9';
which can be tested with:
import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
import org.antlr.stringtemplate.*;
public class Main {
public static void main(String[] args) throws Exception {
String src = "someVariable, somVariable.someMember, functionCall(param).someMember, " +
"foo.bar.baz(bjork).buffalo().xyzzy";
TestLexer lexer = new TestLexer(new ANTLRStringStream(src));
TestParser parser = new TestParser(new CommonTokenStream(lexer));
CommonTree tree = (CommonTree)parser.start().getTree();
DOTTreeGenerator gen = new DOTTreeGenerator();
StringTemplate st = gen.toDOT(tree);
System.out.println(st);
}
}
The output of Main corresponds to the following AST:
EDIT
And since you indicated your ultimate goal is not evaluating the input, but that you rather need to conform the structure of the AST to some 3rd party API, here's a grammar that will create an AST like you indicated in your edited question:
grammar Test;
options {
output=AST;
ASTLabelType=CommonTree;
}
tokens {
BODY;
ACCESS_OP;
CALL;
PARAMS;
LHS;
RHS;
}
start
: body EOF -> body
;
body
: expression (',' expression)* -> ^(BODY expression+)
;
expression
: atom
;
atom
: NUMBER
| (ID -> ID) ( ('(' params ')' -> ^(CALL ID params))
('.' expression -> ^(ACCESS_OP ^(LHS ^(CALL ID params)) ^(RHS expression)))?
| '.' expression -> ^(ACCESS_OP ^(LHS ID) ^(RHS expression))
)?
;
params
: (expression (',' expression)*)? -> ^(PARAMS expression*)
;
ID : LETTER+;
NUMBER : DIGIT+;
SPACE : (' ' | '\t' | '\r' | '\n') {$channel=HIDDEN;};
fragment LETTER : ('a'..'z' | 'A'..'Z');
fragment DIGIT : '0'..'9';
which creates the following AST if you run the Main class:
The atom rule may be a bit daunting, but you can't shorten it much since the left ID needs to be available to most of the alternatives. ANTLRWorks helps in visualizing the alternative paths this rule may take:
which means atom can be any of the 5 following alternatives (with their corresponding AST's):
+----------------------+--------------------------------------------------------+
| alternative | generated AST |
+----------------------+--------------------------------------------------------+
| NUMBER | NUMBER |
| ID | ID |
| ID params | ^(CALL ID params) |
| ID params expression | ^(ACCESS_OP ^(LHS ^(CALL ID params)) ^(RHS expression))|
| ID expression | ^(ACCESS_OP ^(LHS ID) ^(RHS expression) |
+----------------------+--------------------------------------------------------+