im new with ANTLR and I don´t know how to compile my grammar.
I´m using the v4.4 of ANTLR with a .g4 file that contains:
grammar JayGrammar;
program: KEYWORD_VOI KEYWORD_MAI SEPARATOR_PAB SEPARATOR_PCD (declarations statements);
declarations: (declaration)*;
declaration: (type identifiers);
type: (KEYWORD_INT | KEYWORD_BOO);
identifiers: (IDENTIFIER)*;
statements: (statement)*;
statement: (block | assignment | ifstatement | whilestatementk);
block: SEPARATOR_LAB statements SEPARATOR_LCD;
assignment: (IDENTIFIER OPERATOR_IGU expression);
ifstatement: KEYWORD_IF SEPARATOR_PAB expression SEPARATOR_PCD statement (KEYWORD_ELS statement)?;
whilestatementk: KEYWORD_WHI SEPARATOR_PAB expression SEPARATOR_PCD statement;
expression: conjunction ((OPERATOR_O) conjunction)*;
conjunction: relation ((OPERATOR_Y) relation)*;
relation: addition ((OPERATOR_REL) addition)*;
addition: term ((OPERATOR_SUM|OPERATOR_RES) term)*;
term: negation ((OPERATOR_POR|OPERATOR_DIV) negation)*;
negation:(OPERATOR_NO) factor;
factor: IDENTIFIER|LITERAL|SEPARATOR_PAB expression SEPARATOR_PCD;
INPUTELEMENT: (WHITESPACE|TOKEN);
WHITESPACE: (' '|'\t'|'\r'|'\n'|'\f');
TOKEN: (IDENTIFIER|KEYWORD_BOO|KEYWORD_ELS|KEYWORD_IF|KEYWORD_MAI|KEYWORD_VOI|KEYWORD_WHI|LITERAL
|SEPARATOR_COM|SEPARATOR_LAB|SEPARATOR_LCD|SEPARATOR_PAB|SEPARATOR_PCD|SEPARATOR_PYC
|OPERATOR_REL|OPERATOR_DIV|OPERATOR_IGU|OPERATOR_NO|OPERATOR_O|OPERATOR_POR|OPERATOR_RES|OPERATOR_SUM|OPERATOR_Y);
LITERAL: (BOOLEAN INTEGER);
KEYWORD_BOO: BOOLEAN;
KEYWORD_ELS:'else';
KEYWORD_IF: 'if';
KEYWORD_INT: 'int';
KEYWORD_MAI: 'main';
KEYWORD_VOI: 'void';
KEYWORD_WHI: 'while';
BOOLEAN: ('true'|'false');
INTEGER: (DIGIT+);
IDENTIFIER: (LETTER (LETTER| DIGIT)*);
DIGIT: ('0'..'9')+;
LETTER: ('a'..'z'|'A'..'Z')+;
SEPARATOR_PAB: '(';
SEPARATOR_PCD: ')';
SEPARATOR_LAB: '{';
SEPARATOR_LCD: '}';
SEPARATOR_PYC: ';';
SEPARATOR_COM: ',';
OPERATOR_IGU: ('=');
OPERATOR_SUM: ('+');
OPERATOR_RES: ('-');
OPERATOR_POR: ('*');
OPERATOR_DIV: ('/');
OPERATOR_REL: ('<'|'<='|'>'|'>='|'=='|'!=');
OPERATOR_Y: ('&&');
OPERATOR_O: ('||');
OPERATOR_NO: ('!');
I'll be really glad if someone can tell me how to create the lexer and the parser with the extension ".java" and then compile them to create the classes.
I´ve been using NetBeans but i´m really confused, If there is another IDE I can use or anything else, please help me.
This is explained in the Antlr4 "Getting Started" page.
Doing it by hand is as simple as this:
$ antlr4 YourGrammar.g4
$ javac YourGrammar*.java
... assuming that you have installed and configured a Java JDK and Antlr.
There are a number of ways to use Antrlr with the Netbeans IDE:
Just write / generate an Ant build script, and then modify it to include rules for running antlr4 etcetera. With allows you to incorporate Antlr into your builds without any IDE-specific integration.
Follow the instructions here on integrating Antlr into Netbeans,
Install and use the Antlrworks 2 plugin.
Related
I'm trying to build Abstract Syntax Tree for Java in Python with antlr4 package.
I've downloaded Java grammar from
https://github.com/antlr/grammars-v4/blob/master/java8/Java8.g4
I want to use that grammar file to produce JavaLexer and JavaParser for Python2.
When I say
"$ antlr4 -Dlanguage=Python2 Java8.g4"
an error occured.That error is
error(134): Java8.g4:73:0: symbol type conflicts with generated code in target language or runtime
NOTE: I've deleted parts with Character.isJavaIdentifierPart(). Because these lines is not proper for python and i will use just ASCII.
Python has built-in function called type. Antlr4 prints an error for line 73 of the grammar:
type
: primitiveType
| referenceType
;
Looks like there is a name conflict and you have to rename type to something else in your grammar.
The situation:
rule : block+ ;
block : '[' String ']' ;
String : ([a-z] | '[' | '\\]')+ ;
Trick is String can contain [ without backslash escape and ] with backslasash escape, so in this example:
[hello\]world][hello[[world]
First block can be parsed correctly, but the second one... parser is trying find ] for every [. Is there way to say antlr parser to ignore this standalone [? I can't change format, but i need to find some workaround with antlr.
PS: Without antlr there is algorythm to avoid this, something like: collect [ in queue before we will find first ] and use only head of queue. But I really need antlr =_=
You can use Lexer modes.
Lexical modes allow us to split a single lexer grammar into multiple
sublexers. The lexer can only return tokens matched by rules from the
current mode.
You can read more about lexer rules in antlr documentation here.
First you will need to divide you grammar into separate lexer and parser. Than just use another mode after you see open bracket.
Parser grammar:
parser grammar TestParser;
options { tokenVocab=TestLexer; }
rul : block+ ;
block : LBR STRING RBR ;
Lexer grammar:
lexer grammar TestLexer;
LBR: '[' -> pushMode(InString);
mode InString;
STRING : ([a-z] | '\\]' | '[')+ ;
RBR: ']' -> popMode;
Working example is here.
You can read the documentation on lexer modes
I'm looking for some advice on my school project. I am supposed to create a program that takes a logical expression and outputs a truth table for it. The actually creating of the truth table for me is not difficult at all and I've already wrote the methods in Java for it. I would like to know if there are any classes in java that I could use to parse the expression for me and put it into a stack. If not I'm looking for help on parsing the expression. It's the parentheses that get me whenever I try and think it through. Also if this would be easier in any other language I would be open to doing it in that. Perl is probably my next best language.
Some examples
(P && Q) -> R
(P || Q || R) && ((P -> R) -> Q)
If you're allowed to use a parser generator tool like ANTLR, here's how you could get started. The grammar for a simple logic-language could look like this:
grammar Logic;
parse
: expression EOF
;
expression
: implication
;
implication
: or ('->' or)*
;
or
: and ('||' and)*
;
and
: not ('&&' not)*
;
not
: '~' atom
| atom
;
atom
: ID
| '(' expression ')'
;
ID : ('a'..'z' | 'A'..'Z')+;
Space : (' ' | '\t' | '\r' | '\n')+ {$channel=HIDDEN;};
However, if you'd parse input like (P || Q || R) && ((P -> R) -> Q) with a parser generated from the grammar above, the parse tree would contain the parenthesis (something you're not interested in after parsing the expression) and the operators would not be the root of each sub-trees, which doesn't make your life any easier if you're interested in evaluating the expression.
You'll need to tell ANTLR to omit certain tokens from the AST (this can be done by placing a ! after the token/rule) and make certain tokens/rules the root of their (sub) tree (this can be done by placing a ^ after it). Finally, you need to indicate in the options section of your grammar that you want a proper AST to be created instead of a simple parse tree.
So, the grammar above would look like this:
// save it in a file called Logic.g
grammar Logic;
options {
output=AST;
}
// parser/production rules start with a lower case letter
parse
: expression EOF! // omit the EOF token
;
expression
: implication
;
implication
: or ('->'^ or)* // make `->` the root
;
or
: and ('||'^ and)* // make `||` the root
;
and
: not ('&&'^ not)* // make `&&` the root
;
not
: '~'^ atom // make `~` the root
| atom
;
atom
: ID
| '('! expression ')'! // omit both `(` and `)`
;
// lexer/terminal rules start with an upper case letter
ID : ('a'..'z' | 'A'..'Z')+;
Space : (' ' | '\t' | '\r' | '\n')+ {$channel=HIDDEN;};
You can test the parser with the following class:
import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
import org.antlr.stringtemplate.*;
public class Main {
public static void main(String[] args) throws Exception {
// the expression
String src = "(P || Q || R) && ((P -> R) -> Q)";
// create a lexer & parser
LogicLexer lexer = new LogicLexer(new ANTLRStringStream(src));
LogicParser parser = new LogicParser(new CommonTokenStream(lexer));
// invoke the entry point of the parser (the parse() method) and get the AST
CommonTree tree = (CommonTree)parser.parse().getTree();
// print the DOT representation of the AST
DOTTreeGenerator gen = new DOTTreeGenerator();
StringTemplate st = gen.toDOT(tree);
System.out.println(st);
}
}
Now to run the Main class, do:
*nix/MacOS
java -cp antlr-3.3.jar org.antlr.Tool Logic.g
javac -cp antlr-3.3.jar *.java
java -cp .:antlr-3.3.jar Main
Windows
java -cp antlr-3.3.jar org.antlr.Tool Logic.g
javac -cp antlr-3.3.jar *.java
java -cp .;antlr-3.3.jar Main
which will print a DOT source of the following AST:
(image produced with graphviz-dev.appspot.com)
Now all you need to do is evaluate this AST! :)
In Perl you can use Regexp::Grammars to do the parsing. It may be a little on the "grenade to kill an ant" side, but it should work.
Edit: Here is a (very quick) example which might get you going.
#!/usr/bin/env perl
use strict;
use warnings;
use Regexp::Grammars;
use Data::Dumper;
my $parser = qr/
<nocontext:>
<Logic>
<rule: Logic> <[Element]>*
<rule: Element> <Group> | <Operator> | <Item>
<rule: Group> \( <[Element]>* \)
<rule: Operator> (?:&&) | (?:\|\|) | (?:\-\>)
<rule: Item> \w+
/xms; #/ #Fix Syntax Highlight
my $text = '(P && Q) -> R';
print Dumper \%/ if $text =~ $parser; #/ #Fix Syntax Highlight
Look into JavaCC or ANTLR.
Regexps won't work.
You can probably also run your own parser using StreamTokenizer.
Building an expression parser is easy. Attaching actions to compute a value as you parse it is easy, too.
I assume you can write a BNF for your expression language.
This answer shows you how to build a parser easily, if you have a BNF.
Is there an alternative for flex/bison that is usable on 8-bit embedded systems?
If you want to write your own parser, use the Shunting-yard algorithm to get rid of parentheses by converting the expression from infix into postfix notation or directly into a tree.
Another parser generator for Java is CUP.
I just started looking into ANTLR, and noticed ANTLRWorks 1.5 generates the Java parser file, but with incomplete throws declaration.
Grammar file:
grammar ASTDemo;
options {
output=AST;
}
parse
: orexpr+
| andexpr+
| TAG ' ' parens
| TAG (parens andexpr)+
| together+
;
parens
: '(' TAG ')';
andexpr
: TAG (AND^ TAG)+;
orexpr
: '[' TAG (OR^ TAG)+ ']';
together
: TAG (' '^ TAG)*
;
TAG : ('FOO' | 'BAR');
OR : '|';
AND : ': ';
WS : (' ')+;
Here is the sample line that has the incomplete throws statement
public final ASTDemoParser.parse_return parse() throws {
The current version of JDK being used to launch ANTLRWorks is 1.6x
Has anyone seen this before?
The unfortunate part, with this compile error ANTLRWorks is not allowing me to Debug my grammar within it. I'm forced to manually fix the file each time I want to test.
I have just compiled your grammar using ANTLRWorks 1.5 rc1 and JDK 1.7.0.11.
All compiled well, and mentioned code line looks like:
public final ASTDemoParser.parse_return parse() throws RecognitionException {
It could be arbitrary bug manifestation. Try to recompile it again, and may be you have try to use JDK 1.7.
I'm looking for some advice on my school project. I am supposed to create a program that takes a logical expression and outputs a truth table for it. The actually creating of the truth table for me is not difficult at all and I've already wrote the methods in Java for it. I would like to know if there are any classes in java that I could use to parse the expression for me and put it into a stack. If not I'm looking for help on parsing the expression. It's the parentheses that get me whenever I try and think it through. Also if this would be easier in any other language I would be open to doing it in that. Perl is probably my next best language.
Some examples
(P && Q) -> R
(P || Q || R) && ((P -> R) -> Q)
If you're allowed to use a parser generator tool like ANTLR, here's how you could get started. The grammar for a simple logic-language could look like this:
grammar Logic;
parse
: expression EOF
;
expression
: implication
;
implication
: or ('->' or)*
;
or
: and ('||' and)*
;
and
: not ('&&' not)*
;
not
: '~' atom
| atom
;
atom
: ID
| '(' expression ')'
;
ID : ('a'..'z' | 'A'..'Z')+;
Space : (' ' | '\t' | '\r' | '\n')+ {$channel=HIDDEN;};
However, if you'd parse input like (P || Q || R) && ((P -> R) -> Q) with a parser generated from the grammar above, the parse tree would contain the parenthesis (something you're not interested in after parsing the expression) and the operators would not be the root of each sub-trees, which doesn't make your life any easier if you're interested in evaluating the expression.
You'll need to tell ANTLR to omit certain tokens from the AST (this can be done by placing a ! after the token/rule) and make certain tokens/rules the root of their (sub) tree (this can be done by placing a ^ after it). Finally, you need to indicate in the options section of your grammar that you want a proper AST to be created instead of a simple parse tree.
So, the grammar above would look like this:
// save it in a file called Logic.g
grammar Logic;
options {
output=AST;
}
// parser/production rules start with a lower case letter
parse
: expression EOF! // omit the EOF token
;
expression
: implication
;
implication
: or ('->'^ or)* // make `->` the root
;
or
: and ('||'^ and)* // make `||` the root
;
and
: not ('&&'^ not)* // make `&&` the root
;
not
: '~'^ atom // make `~` the root
| atom
;
atom
: ID
| '('! expression ')'! // omit both `(` and `)`
;
// lexer/terminal rules start with an upper case letter
ID : ('a'..'z' | 'A'..'Z')+;
Space : (' ' | '\t' | '\r' | '\n')+ {$channel=HIDDEN;};
You can test the parser with the following class:
import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
import org.antlr.stringtemplate.*;
public class Main {
public static void main(String[] args) throws Exception {
// the expression
String src = "(P || Q || R) && ((P -> R) -> Q)";
// create a lexer & parser
LogicLexer lexer = new LogicLexer(new ANTLRStringStream(src));
LogicParser parser = new LogicParser(new CommonTokenStream(lexer));
// invoke the entry point of the parser (the parse() method) and get the AST
CommonTree tree = (CommonTree)parser.parse().getTree();
// print the DOT representation of the AST
DOTTreeGenerator gen = new DOTTreeGenerator();
StringTemplate st = gen.toDOT(tree);
System.out.println(st);
}
}
Now to run the Main class, do:
*nix/MacOS
java -cp antlr-3.3.jar org.antlr.Tool Logic.g
javac -cp antlr-3.3.jar *.java
java -cp .:antlr-3.3.jar Main
Windows
java -cp antlr-3.3.jar org.antlr.Tool Logic.g
javac -cp antlr-3.3.jar *.java
java -cp .;antlr-3.3.jar Main
which will print a DOT source of the following AST:
(image produced with graphviz-dev.appspot.com)
Now all you need to do is evaluate this AST! :)
In Perl you can use Regexp::Grammars to do the parsing. It may be a little on the "grenade to kill an ant" side, but it should work.
Edit: Here is a (very quick) example which might get you going.
#!/usr/bin/env perl
use strict;
use warnings;
use Regexp::Grammars;
use Data::Dumper;
my $parser = qr/
<nocontext:>
<Logic>
<rule: Logic> <[Element]>*
<rule: Element> <Group> | <Operator> | <Item>
<rule: Group> \( <[Element]>* \)
<rule: Operator> (?:&&) | (?:\|\|) | (?:\-\>)
<rule: Item> \w+
/xms; #/ #Fix Syntax Highlight
my $text = '(P && Q) -> R';
print Dumper \%/ if $text =~ $parser; #/ #Fix Syntax Highlight
Look into JavaCC or ANTLR.
Regexps won't work.
You can probably also run your own parser using StreamTokenizer.
Building an expression parser is easy. Attaching actions to compute a value as you parse it is easy, too.
I assume you can write a BNF for your expression language.
This answer shows you how to build a parser easily, if you have a BNF.
Is there an alternative for flex/bison that is usable on 8-bit embedded systems?
If you want to write your own parser, use the Shunting-yard algorithm to get rid of parentheses by converting the expression from infix into postfix notation or directly into a tree.
Another parser generator for Java is CUP.