Help with left factoring a grammar to remove left recursion

前端 未结 1 1734
没有蜡笔的小新
没有蜡笔的小新 2021-01-12 09:37

I have a small custom scripting language, and I am trying to update it to allow boolean expressions such as a > 2 and a > 2 and (b < 3 or c >

1条回答
  •  伪装坚强ぢ
    2021-01-12 10:32

    Boolean expressions are just the same as the additive- and multiplicative expression, and should therefore not be separated from them. Here's how to account for all types of expressions:

    grammar test;
    
    parse
      :  expression EOF
      ;
    
    expression 
      :  or
      ;
    
    or
      :  and (OR and)*
      ;
    
    and
      :  rel (AND rel)*
      ;
    
    rel
      :  add (('=' | '>' | '<') add)*
      ;
    
    add
      :  mult (('+' | '-') mult)*
      ;
    
    mult
      :  unary (('*' | '/') unary)*
      ;
    
    unary 
      :  '-' term
      |  '+' term
      |  NOT term
      |  term
      ;
    
    term 
      :  INTEGER  
      |  IDENT       
      |  list
      |  '(' expression ')'
      ;
    
    list 
      :  '{' (expression (',' expression)*)? '}'
      ;
    
    AND     :  'and';
    OR      :  'or';
    NOT     :  'not';
    IDENT   :  LETTER LETTER*;
    INTEGER :  DIGIT+;
    WS      :  (' ' | '\n' | '\r' | '\t')+  { $channel = HIDDEN; };
    
    fragment DIGIT   : '0'..'9';
    fragment LETTER  : ('a'..'z' | 'A'..'Z');
    

    which will parse the example input:

    abc > 3 and (xyz < 5 or xyz > {1, 2, 3})
    

    into the following parse tree:

    enter image description here

    0 讨论(0)
提交回复
热议问题