I'm trying to create my own ANTLR4 grammar so that I can parse some expressions, such as :
STARTS_WITH(this.sequence, "startSeq")
ENDS_WITH("sequenceToTest", "endSeq")
(I have a mix of constants and variables as function parameters).
The Lexer and Parser Rules have been created, but when I try to display the function ToStringTree, it seems like the tree is parsed in a wrong way.
I am using Antlr 4 with ASP.Net Core 2.1.
The grammar file :
grammar expression;
expression : bool_function (OPERATOR bool_function)* ;
bool_function : (FUNCTION_NAME PAR_OPEN parameter (COMMA parameter)* PAR_CLOSE) ;
parameter : constant | current_object_field ;
constant : DOUBLE_QUOTE ANY_BUT_DOUBLE_QUOTE DOUBLE_QUOTE ;
current_object_field : THIS ALPHANUM ;
WHITESPACE : (' ' | '\t' | '\n' |'\r' )+ -> skip ;
COMPARATOR : ('==' | '<=' | '>=' | '<>') ;
OPERATOR : ('&&' | '||') ;
PAR_OPEN : '(' ;
PAR_CLOSE : ')' ;
COMMA : ',' ;
DOLLAR : '$' ;
DOUBLE_QUOTE : '"' ;
THIS : 'this.' ;
NUMBER : [0-9]+ ;
ALPHANUM : [a-zA-Z_0-9]+ ;
ANY_BUT_DOUBLE_QUOTE : ~('"')+ ;
FUNCTION_NAME : ('STARTS_WITH' | 'ENDS_WITH' | 'CONTAINS' | 'EQUALS') ;
The unit testing, trying to parse one basic expression :
try
{
expressionParser expressionParser = Setup("STARTS_WITH(this.sequence, \"startSeq\")");
expressionParser.ExpressionContext expressionContext = expressionParser.expression();
var a = expressionContext.ToStringTree(expressionParser);
}
catch (Exception e)
{
var a = e.Message;
throw;
}
The output I receive for parsing my expression via ToStringTree is the following :
(expression (bool_function STARTS_WITH(this.sequence, " startSeq " )))
But I would expect a result, going deeper, such as :
(expression (bool_function STARTS_WITH((parameter(current_objet_field this.sequence)),(parameter(constant "startSeq")))))
Are there any obvious mistakes in the way I defined my Lexer/Parser ?
nullwhen they couldn't be parsed correctly). You can check whether there were errors (and how many there were) usingparser.NumberOfSyntaxErrors. For tests, I'd recommend using an error listener that collects all error messages in a set and then checks that you got the right number of errors with the right messages (for input that's supposed to produce errors). - sepp2k