ANTLR ambiguous grammar?

I have a couple of ANTLR rules that I don’t know how to make them work.

The first rule:

STRING_LITERAL
    :  '"' ( EscapeSequence | ~('\\'|'"') )* '"'
    ;

The second rule:

element 
 :  name '='  math_formula  ;
math_formula
        :        '"' expression '"';

Expression is a regular C-like expression

Syntax example

 "count" = "array[3]"

count is a string, and array [3] is an expression

My problem is that the lexer always returns both "count" and "array [3]" as strings, and Parser cannot recognize the expression.

I am using java target.

EDIT: change "variable_name" to "count".

EDIT2: explained my second attempt below:

I can detect the beginning of an expression with "=", but I cannot detect the end of the expression in Lexer, causing false line detection when I have two elements separated by the ","

"count1" = "array[1]",
"count2" = "array[2]"

'= " START_EXPRESSION, , , , ", \n ", .

3:

STRING_LITERAL

STRING_LITERAL  
    :   (~('=') '"' ( EscapeSequence | ~('\\'|'"') )* '"')=> '"' ( EscapeSequence | ~('\\'|'"') )* '"'
    ;

, , ~ ('=') , somthing

+3
3

, 10 , ANTLR - . , , , , element. , element; , STRING_LITERAL.


ANTLR . , , :

protected
STRING : whatever...
;
protected
EXPRESSION: whatever...
;
STRING_OR_EXPR
: ( EXPRESSION ) => EXPRESSION { $setType(EXPRESSION); }
| STRING { $setType(STRING); }
;
+1

, , , - SO, , , , . , ANTLR

"variable_name" = "array[3]"

( ), STRING_LITERAL, , , , .

variable_name = "array[3]"

, ,

variable_name = array[3]

- , .

:
, STRING ( , ), , "" . , , STRING_LITTERAL, math_formula , , , , "name" = "STRING_LITERAL", .

0

? , :

ASSIGN:
    ('=' '"')=> /* assuming whitespace doesn't exist */
     '=' {some_global_flaggy_thing=1;}
    |'='
    ;
STRING_LITERAL:
    {some_global_flaggy_thing==1}? '"' {$type=QUOTE; some_gobal_flaggy_thing=2;}
    |{some_global_flaggy_thing==2}? '"' {$type=QUOTE; some_global_flaggy_thing=0;}
    | '"' /* normal string literal stuff */ '"'
    ;

Of course, your inline expression cannot contain string literals.
Note. I am more familiar with ANTLR2

0
source

Source: https://habr.com/ru/post/1719638/


All Articles