I wanted to know what is the right way to apply the parsing rules for multiple lines using ANTLR. I am using the below rule which works fine for single line statements. I wanted to just repeat this over next lines:
grammar Condition;
/* Parser Rules */
condition : (expr+)? EOF;
expr
: expr And expr # andExpr
| expr Or expr # orExpr
| LPar expr RPar # parExpr
| prop MIN Numerical expr # eqExpr
| prop some expr # someExpr
| prop only expr # onlyExpr
| prop value dataValue # valueExpr
| id # idExpr
| not id # idExpr
;
id : Identifier;
prop:Identifier;
dataValue:Identifier;
/* Lexical Tokens */
And : 'AND';
Or : 'OR';
LPar : '(';
RPar : ')';
Equals : '=';
some : 'some';
only : 'only';
MIN : 'MIN';
value:'value';
not:'not';
NEWLINE: ('\n') { skip(); };
Numerical : [1-9] [0-9]*;
Data
: [true]
| [false]
| [A]
| [B]
| [C]
| [D]
;
// Using generic identifier tokens so that better warnings can be given in later passes.
Identifier : [a-zA-Z_] [a-zA-Z0-9_]*;
// Skip parsing of whitespace but save on hidden channel to enable retrieval of original string.
WhiteSpace : [ \t\r\n]+ -> channel(HIDDEN);
// Invalid character rule is used so that the lexer pass never fails.
InvalidChar : .;
The above grammar gives correct results while testing, but when I try to use visitor it consume each token, it throws the below error :
line 2:0 extraneous input 'SafetyGoal' expecting {, 'AND', 'OR'}
Any suggestions?
EDIT Below is the code I am using to read the input file and call the visitor code:
Stream<String> stream = Files.lines( Paths.get("C:\\test\\RulesTest.txt"), StandardCharsets.UTF_8);
stream.forEach(s -> contentBuilder.append(s).append("\n"));
String input=contentBuilder.toString();
InputStream inStream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
org.antlr.v4.runtime.ANTLRInputStream in=new org.antlr.v4.runtime.ANTLRInputStream(inStream);
System.out.println("These are the lines:"+contentBuilder);
ConditionLexer lexer=new ConditionLexer(in);
org.antlr.v4.runtime.CommonTokenStream tokens= new org.antlr.v4.runtime.CommonTokenStream(lexer);
ConditionParser parser=new ConditionParser(tokens);
ParseTree tree=parser.expr();
MyVisitor vis=new MyVisitor();
vis.visit(tree);
The MyVisitor
basically contains the same code as generated by the ANTLR, where I am storing the results as it parses.
(FSR AND testedBy some (testResult value true))
and next lineSafetyGoal AND (fulfills some (not NR) OR fulfilledBy some NR)
– visrajcondition
, right? Btw: These are (probably) unrelated to your problem, but: A better way to write(expr+)?
would beexpr*
. You're handling newlines twice (once in theNEWLINE
and once in theWhiteSpace
rule, so the NEWLINE rule is redundant. Oh and[true]
matches a t, r, u or e, not the string "true". – sepp2kgrun Condition condition
after compiling your grammar without any changes. So please post an MCVE. – sepp2k