I am newbie to ANTLR4 and DSL. I want to create my DSL. I tried basic demo to get idea of it see here . Now I want to define multiple rules(which will represent one functionality/function in corresponding Java class) under one grammar. Where as in DSL input(text file), I want to consume rules randomly and traverse those rules (trees) only(not all rules).
My grammar:
grammar Hello;
sayHello : 'hello' STRING ';' ;
welcomeMessage : 'welcome' STRING ';' ;
newTest : 'newhello' STRING ';' ;
STRING : [a-zA-Z]+ ;
WS : [ \t\r\n]+ -> skip ;
public static void main( String[] args) throws Exception
{
ANTLRInputStream input = new ANTLRInputStream("hello world;"
+ "newhello newworld;" );
HelloLexer lexer = new HelloLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
HelloParser parser = new HelloParser(tokens);
parser.addParseListener(new MyHelloLister());
// At runtime how to define which tree(parser function to invoke) to generate and traverse.
// parser. sayHello(); // Error, because not traversed tree, and input is mismatched.
// parser.welcomeMessage();
parser.newTest();
}
Error: line 1:0 mismatched input 'hello' expecting 'newhello'
So, I want to know from input DSL file, which rules to invoke. Can anyone briefly give me idea about it ?
Well, you call newTest()
. The rule for newTest is this:
newTest : 'newhello' STRING ';' ;
So the parser expects something like "newhello abcdef;". But you passed "hello world;newhello newworld;". That does not start with "newhello", as the error message tells you.
You could change your rule like this (not 100% sure about ANTLR syntax, so you have to try yourself):
newTest : welcomeMessage? 'newhello' STRING ';' ;
Then your example should pass.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.