ANTLR:从不同的语法中调用规则

时间:2011-07-11 14:01:53

标签: antlr grammar modularity rule

是否可以从不同的语法中调用规则?
目的是在同一个文件中使用两种语言,第二种语言以(begin ...)开头,其中......是第二种语言。语法应调用另一种语法来解析第二种语言。

例如:


grammar A;

start_rule
    :    '(' 'begin' B.program ')' //or something like that
    ;


grammar B;

program
    :   something* EOF
    ;

something
    : ...
    ;

1 个答案:

答案 0 :(得分:10)

您的问题可以(至少)以两种方式解释:

  1. 将规则从大型语法分离为单独的语法;
  2. 在“主要”语言(岛语法)中解析单独的语言。
  3. 我认为它是第一个,在这种情况下你可以导入语法。

    选项1的演示:

    档案:L.g

    lexer grammar L;
    
    Digit
      :  '0'..'9'
      ;
    

    档案:Sub.g

    parser grammar Sub;
    
    number
      :  Digit+
      ;
    

    档案:Root.g

    grammar Root;
    
    import Sub;
    
    parse
      :  number EOF {System.out.println("Parsed: " + $number.text);}
      ;
    

    file:Main.java

    import org.antlr.runtime.*;
    
    public class Main {
      public static void main(String[] args) throws Exception {
        L lexer = new L(new ANTLRStringStream("42"));
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        RootParser parser = new RootParser(tokens);
        parser.parse();
      }
    }
    

    运行演示:

    bart@hades:~/Programming/ANTLR/Demos/Composite$ java -cp antlr-3.3.jar org.antlr.Tool L.g
    bart@hades:~/Programming/ANTLR/Demos/Composite$ java -cp antlr-3.3.jar org.antlr.Tool Root.g 
    bart@hades:~/Programming/ANTLR/Demos/Composite$ javac -cp antlr-3.3.jar *.java
    bart@hades:~/Programming/ANTLR/Demos/Composite$ java -cp .:antlr-3.3.jar Main
    

    将打印:

    Parsed: 42
    

    到控制台。

    更多信息,请参阅:http://www.antlr.org/wiki/display/ANTLR3/Composite+Grammars

    选项2的演示:

    语言中一种语言的一个很好的例子是正则表达式。你有一个带有元字符的“普通”正则表达式语言,但还有另外一个:描述字符集(或字符类)的语言。

    您可以简单地将字符集视为由单个标记组成的单个标记,而不是在您的正则表达式语法中考虑字符集的元字符(范围-,否定^等)。一个[,然后是你的正则表达式语法中包含](可能包含\]!)的所有内容。当您在其中一个解析器规则中偶然发现CharSet令牌时,您将调用CharSet解析器。

    档案:Regex.g

    grammar Regex;
    
    options { 
      output=AST;
    }
    
    tokens {
      REGEX;
      ATOM;
      CHARSET;
      INT;
      GROUP;
      CONTENTS;
    }
    
    @members {
      public static CommonTree ast(String source) throws RecognitionException {
        RegexLexer lexer = new RegexLexer(new ANTLRStringStream(source));
        RegexParser parser = new RegexParser(new CommonTokenStream(lexer));
        return (CommonTree)parser.parse().getTree();
      }
    }
    
    parse
      :  atom+ EOF -> ^(REGEX atom+)
      ;
    
    atom
      :  group quantifier?     -> ^(ATOM group quantifier?)
      |  EscapeSeq quantifier? -> ^(ATOM EscapeSeq quantifier?)
      |  Other quantifier?     -> ^(ATOM Other quantifier?)
      |  CharSet quantifier?   -> ^(CHARSET {CharSetParser.ast($CharSet.text)} quantifier?)
      ;
    
    group
      :  '(' atom+ ')' -> ^(GROUP atom+)
      ;
    
    quantifier
      :  '+'
      |  '*'
      ;
    
    CharSet
      :  '[' (('\\' .) | ~('\\' | ']'))+ ']'
      ;
    
    EscapeSeq
      :  '\\' .
      ;
    
    Other
      :  ~('\\' | '(' | ')' | '[' | ']' | '+' | '*')
      ;
    

    文件:CharSet.g

    grammar CharSet;
    
    options { 
      output=AST;
    }
    
    tokens {
      NORMAL_CHAR_SET;
      NEGATED_CHAR_SET;
      RANGE;
    }
    
    @members {
      public static CommonTree ast(String source) throws RecognitionException {
        CharSetLexer lexer = new CharSetLexer(new ANTLRStringStream(source));
        CharSetParser parser = new CharSetParser(new CommonTokenStream(lexer));
        return (CommonTree)parser.parse().getTree();
      }
    }
    
    parse
      :  OSqBr ( normal  -> ^(NORMAL_CHAR_SET normal)
               | negated -> ^(NEGATED_CHAR_SET negated)
               ) 
         CSqBr
      ;
    
    normal
      :  (EscapeSeq | Hyphen | Other) atom* Hyphen?
      ;
    
    negated
      :  Caret normal -> normal
      ;
    
    atom
      :  EscapeSeq
      |  Caret
      |  Other
      |  range
      ;
    
    range
      :  from=Other Hyphen to=Other -> ^(RANGE $from $to)
      ;
    
    OSqBr
          :  '['
      ;
    
    CSqBr
      :  ']'
      ;
    
    EscapeSeq
      :  '\\' .
      ;
    
    Caret
      :  '^'
      ;
    
    Hyphen
      :  '-'
      ;
    
    Other
      :  ~('-' | '\\' | '[' | ']')
      ;
    

    file:Main.java

    import org.antlr.runtime.*;
    import org.antlr.runtime.tree.*;
    import org.antlr.stringtemplate.*;
    
    public class Main {
      public static void main(String[] args) throws Exception {
        CommonTree tree = RegexParser.ast("((xyz)*[^\\da-f])foo");
        DOTTreeGenerator gen = new DOTTreeGenerator();
        StringTemplate st = gen.toDOT(tree);
        System.out.println(st);
      }
    }
    

    如果你运行主课程,你会看到正则表达式((xyz)*[^\\da-f])foo的{​​{3}},它是以下树:

    enter image description here

    魔术在Regex.g规则中的atom语法中,我通过调用ast类中的静态CharSetParser方法在重写规则中插入树节点:

    CharSet ... -> ^(... {CharSetParser.ast($CharSet.text)} ...)
    

    请注意,在这样的重写规则中,必须是半冒号!所以,这是错误的:{CharSetParser.ast($CharSet.text);}

    修改

    以下是如何为两种语法创建树步行器:

    档案:RegexWalker.g

    tree grammar RegexWalker;
    
    options {
      tokenVocab=Regex;
      ASTLabelType=CommonTree;
    }
    
    walk
      :  ^(REGEX atom+) {System.out.println("REGEX: " + $start.toStringTree());}
      ;
    
    atom
      :  ^(ATOM group quantifier?)
      |  ^(ATOM EscapeSeq quantifier?)
      |  ^(ATOM Other quantifier?)
      |  ^(CHARSET t=. quantifier?) {CharSetWalker.walk($t);}
      ;
    
    group
      :  ^(GROUP atom+)
      ;
    
    quantifier
      :  '+'
      |  '*'
      ;
    

    file:CharSetWalker.g

    tree grammar CharSetWalker;
    
    options {
      tokenVocab=CharSet;
      ASTLabelType=CommonTree;
    }
    
    @members {
      public static void walk(CommonTree tree) {
        try {
          CommonTreeNodeStream nodes = new CommonTreeNodeStream(tree);
          CharSetWalker walker = new CharSetWalker(nodes);
          walker.walk();
        } catch(Exception e) {
          e.printStackTrace();
        }
      }
    }
    
    walk
      :  ^(NORMAL_CHAR_SET normal)  {System.out.println("NORMAL_CHAR_SET: " + $start.toStringTree());}
      |  ^(NEGATED_CHAR_SET normal) {System.out.println("NEGATED_CHAR_SET: " + $start.toStringTree());}
      ;
    
    normal
      :  (EscapeSeq | Hyphen | Other) atom* Hyphen?
      ;
    
    atom
      :  EscapeSeq
      |  Caret
      |  Other
      |  range
      ;
    
    range
      :  ^(RANGE Other Other)
      ;
    

    Main.java

    import org.antlr.runtime.*;
    import org.antlr.runtime.tree.*;
    import org.antlr.stringtemplate.*;
    
    public class Main {
      public static void main(String[] args) throws Exception {
        CommonTree tree = RegexParser.ast("((xyz)*[^\\da-f])foo");
        CommonTreeNodeStream nodes = new CommonTreeNodeStream(tree);
        RegexWalker walker = new RegexWalker(nodes);
        walker.walk();
      }
    }
    

    要运行演示,请执行:

    java -cp antlr-3.3.jar org.antlr.Tool CharSet.g 
    java -cp antlr-3.3.jar org.antlr.Tool Regex.g
    java -cp antlr-3.3.jar org.antlr.Tool CharSetWalker.g
    java -cp antlr-3.3.jar org.antlr.Tool RegexWalker.g 
    javac -cp antlr-3.3.jar *.java
    java -cp .:antlr-3.3.jar Main
    

    将打印:

    NEGATED_CHAR_SET: (NEGATED_CHAR_SET \d (RANGE a f))
    REGEX: (REGEX (ATOM (GROUP (ATOM (GROUP (ATOM x) (ATOM y) (ATOM z)) *) (CHARSET (NEGATED_CHAR_SET \d (RANGE a f))))) (ATOM f) (ATOM o) (ATOM o))