Antlr 语法

基本语法:四个语言模式

four abstract computer language patterns.

  • Sequence: This is a sequence of elements such as the values in an array initializer.
  • Choice: This is a choice between multiple, alternative phrases such as the different kinds of statements in a programming language.
  • Token dependence: The presence of one token requires the presence of its counterpart elsewhere in a phrase such as matching left and right parentheses.
  • Nested phrase: This is a self-similar language construct such as nested arithmetic expressions or nested statement blocks in a programming language.

To implement these patterns, we really only need grammar rules comprised of alternatives, token references, and rule references(Backus-Naur-Format [BNF]).

  1. Sequence
subrule operator meaning sample
+ one or more elements (INT)+ INT+
* Zero or more INT*
? optional constructs ('='expr)? is the same as ('='expr|)
  • sequence with terminator and sequence with separator
file : (row '\n')* ;       // sequence with a '\n' terminator
row : field (',' field)* ; // sequence with a ',' separator
field: INT ; // assume fields are just integers 
  1. Choice

    Sample:

field : INT | STRING ;
stmt: node_stmt | edge_stmt | attr_stmt | id '=' id | subgraph ;
  1. Token Dependency

    use a sequence that specifies both symbols, usually enclosing or grouping other elements.

    Sample: vector : '[' INT+ ']' ; // [1], [1 2], [1 2 3], ...

  2. Nested Phrase

    stat: 'while' '(' expr ')' stat     // match WHILE statement
     | '{' stat* '}'  // match block of statements in curlies
    

高级语法:嵌入代码

原文见另一博客的文章

你可能感兴趣的:(Antlr 语法)