среда, 7 декабря 2016 г.

ANTLR, how to validate the balance?

Sometime we need to  check that open and closed brackets, quotes and double quoutes are in the balance. How to process it? The best way is to create the antlr grammar, parse the text then validate it.

Please, see the grammar text bellow.

 grammar GrammarValidator;  
 r  
 :  
      (  
           string  
           | expression  
      )*  
 ;  
 string  
 :  
      QUOTED  
 ;  
 expression  
 :  
      not_string_term  
      | '{'  
      (  
           r?  
      ) '}'  
      | '['  
      (  
           r?  
      ) ']'  
      | '('  
      (  
           r?  
      ) ')'  
 ;  
 not_string_term  
 :  
      NOT_STRING_CHAR+  
 ;  
 NOT_STRING_CHAR  
 :  
      ~['"'|'\'']  
 ;  
 QUOTED  
 :  
      '"' StringCharacters? '"'| CharacterLiteral  
 ;  
 CharacterLiteral  
   :  '\'' SingleCharacter '\''  
   |  '\'' EscapeSequence '\''  
   ;  
   fragment  
 SingleCharacter  
   :  ~['\\]  
   ;  
 fragment  
 StringCharacters  
   :  StringCharacter+  
   ;  
 fragment  
 StringCharacter  
   :  ~["\\]  
   |  EscapeSequence  
   ;  
 fragment  
 EscapeSequence  
   :  '\\' [btnfr"'\\];  
 WS  
 :  
      [ \t\r\n\u000C]+ -> skip  
 ;  

As you can see our main rule contents from the two subrules: string and expression. String contains any character except double quote or slash '\' or EscapeSequence. 
Expression contains not_string_term (anything except quote or double quote) or main rule inside the brackets.

Then we can validate error via standard antlr mechanism. That's all, very simple


Комментариев нет:

Отправить комментарий