The grammar recognizes an unlimited number of {{expr}} next to each other

I am writing a C # application using ANTLR4 to recognize the following TeX 'ish style:

{a} {x} + {b} {y} + {C}

My current grammar always takes the last instance of '{' expr '}' , and then ignores the beginning of the line. Here are some output from the current grammar (described below):

  • Input: {a} Output: a [Pass]
  • Input: {a} + {x} Output: a + x [Pass]
  • Input: {a} {x} Output: x [Fail] Desired: ax
  • Input: {a} {x} + {b} Output: x + b [Fail] Desired: ax + b
  • Input: {a} {x} + {b} {y} Output: y [Fail] Desired: ax + by
  • Input: {a} {x} + {b} {y} + {c} Output: y + c [Fail] Desired: ax + by + s
  • Input: {a} {x} + {b} {y} + {c} {d} Output: d [Fail] Desired: ax + by + cd

Any ideas on how to fix this?

Grammar file MyGra.g4:

/*
 * Parser Rules
 */
prog: expr+ ;

expr : '{' expr '}'                 # CB_Expr
     | expr op=('+'|'-') expr       # AddSub
     | '{' ID '}'                   # CB_ID
     | ID                           # ID
     ;

/*
 * Lexer Rules
 */
ID: ('a' .. 'z' | 'A' .. 'Z')+;
ADD : '+';
SUB : '-';
WS:   (' ' | '\r' | '\n') -> channel(HIDDEN);

File MyGraVisitor.CS:

 public override string VisitID(MyGraParser.IDContext context)
 {
      return context.ID().GetText();
 }

 public override string VisitAddSub(MyGraParser.AddSubContext context)
 {
     if (context.op.Type == MyGraParser.ADD)
     {
         return Visit(context.expr(0)) + " + " + Visit(context.expr(1));
     }
     else
     {
         return Visit(context.expr(0)) + " - " + Visit(context.expr(1));
     }
 }

 public override string VisitCB_Expr(MyGraParser.CB_ExprContext context)
 {
     return Visit(context.expr());
 }

 public override string VisitCB_ID(MyGraParser.CB_IDContext context)
 {
     return context.ID().GetText();
 }

Update # 1:

It was proposed to include a grammar rule for

'{' expr '}{' expr '}'

, , {a} {b} {c} {d} + {e} {f} {g}, , "" ... , 1000 {expr} ? ? , , , , {expr} ?

: CB_Expr?

# 2:

:

| expr CB_Expr                  # CB_Expr2

:

public override string VisitCB_Expr2(MyGra.CB_Expr2Context context)
{
    return Visit(context.expr()) + Visit(context.CB_Expr());
}

, ( ).

+4
1

. : {x} ( ):

(CB_Expr {(expr (ID x))})

(DB_ID {x})

CB_ID , .

expr:

expr : left=id_expr op=('+' |'-') right=expr #AddSub
     | id_expr                               #ID_Expr
     ;

id_expr :
     | '{' ID '}' id_expr                    #ID_Ex
     | '{' ID '}'                            #ID
     ;

, , , .

id_expr , {ID} , , , .

+1

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


All Articles