Reputation: 753
I am trying to develop a tool using ANTLR 4.0. I am very new to ANTLR and Advance Java. I had downloaded the package i.e antlr-4.2.2-complete.jar
. ANTLER is working fine.
I have few doubts.
I took a very basic grammar , give below:
grammar test;
start : (aa) | (bb);
aa : A C D;
bb : A C B;
A : 'a';
B : 'b';
C : 'c';
D : 'd';
WS : [ \t\r\n] ->skip;
now I am using command prompt to parse string in it..
C:\javalib\test>java org.antlr.v4.Tool test.g4
C:\javalib\test>javac test*.java
C:\javalib\test>java org.antlr.v4.runtime.misc.TestRig test start -gui -tree
**acb**
^Z
(start (bb a c b))
string acb
was parsed and output obtained was (start (bb a c b))
.
Now, i want know how can i parse manystrings/ a file in ANTLR. Each line in that file will have different start rule.
For Example , file which we have to parse will look like (input file)
start : acb
bb : acb
aa : acd
I can't take the advice of changing the grammar accordingly so that i will get one start rule which can be used for all the strings, because the grammar on which i am working really very vast.
I can change the format of my input string, so that we can parse it easily in ANTLR. I wanted to give the basic idea, that i have many strings , each string have different start rule, how can i parse it in ANTLR.
Upvotes: 0
Views: 1203
Reputation: 5205
To parse each line with a given rule you could do this.
testcase :
singletest
( Linebreak singletest) *
;
singletest:
'ruleA' ':' ruleA
| 'ruleB' ':' ruleB
|...
;
Whitespace: [ \t] -> skip; // no line break!
Linebreak: '\r\n' | '\r' | '\n';
Upvotes: 1
Reputation: 170178
Now, i want know how can i parse manystrings/ a file in ANTLR.
To parse the file input.txt
, do:
testLexer lexer = new testLexer(new ANTLRFileStream("input.txt"));
testParser parser = new testParser(new CommonTokenStream(lexer));
ParseTree tree = parser.start();
System.out.println(tree.toStringTree());
Upvotes: 0