美文网首页
Antlr 语法

Antlr 语法

作者: EqualII | 来源:发表于2017-09-24 02:31 被阅读0次

    基本语法:四个语言模式

    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 语法

          本文链接:https://www.haomeiwen.com/subject/enghextx.html