ANTLR如何评估ifdef else结束语句

时间:2013-01-27 12:48:57

标签: antlr conditional-compilation

我想知道如何评估ifdef ... else ... end语句,它可以放在代码中的任何地方。我从一个简单的例子开始,它实现了2个基本函数add(p1,p2)和diff(p1,p2),其中p1和p2是字符串。它只在p1和p2之间加一个+或a - 。这是我的语法:

grammar ifdef;

options {
  language = Java;
  output = AST;
  ASTLabelType=CommonTree;
}

tokens 
{
    EQUAL           = '=' ;
    HASH            = '#' ;
    DBLEQUOTE       = '"' ;
    SEMICOLON       = ';' ;
}


@header {
    package Grammar;

    import java.util.Map;
    import java.util.HashMap;

}

@lexer::header {
    package Grammar;    
}

@members {
    private Map<String, String> strMapID = new HashMap<String, String>();
    private Map<String, String> strMapDefine = new HashMap<String, String>();
}


rule returns [String strEval]
    :   {   StringBuilder strBuilder = new StringBuilder(); }
    (   command
        {   if ( $command.str != "" ) {
                strBuilder.append( $command.str );
                strBuilder.append( "\n" );
            }
        }

    )+ EOF
        { $strEval = strBuilder.toString(); }
    ;

command returns [String str]
    :   define      { $str=""; }
    |   undef       { $str=""; }
    |   set         { $str=""; }
    |   function    { $str = $function.str; }
    |   ifdef       { $str=""; }
    ;

define
    :   HASH 'define' ID
        { strMapDefine.put($ID.text, $ID.text); }       // save define ID into hash table
    ;

undef
    :   HASH 'undef' ID
        {   if ( strMapDefine.containsKey($ID.text) ) {
                strMapDefine.remove($ID.text);          // undef ID in hash table
                }
        }
    ;

set
    :   'set' ID EQUAL string SEMICOLON
        { strMapID.put($ID.text, $string.text); }       // save ID,string definition into hash table 
    ;

string
    :   DBLEQUOTE expr DBLEQUOTE
    ;

function returns [String str]
    :   add     { $str = $add.str; }
    |   diff    { $str = $diff.str; }
    ;

add returns [String str]
    :   'add' '(' p1=param ',' p2=param ')'
        {   StringBuilder strBuilder = new StringBuilder();
            strBuilder.append( $p1.str );
            strBuilder.append( "+" );
            strBuilder.append( $p2.str );
            $str = strBuilder.toString();
        }
    ;

diff returns [String str]
    :   'diff' '(' p1=param ',' p2=param ')'
        {   StringBuilder strBuilder = new StringBuilder();
            strBuilder.append( $p1.str );
            strBuilder.append( "-" );
            strBuilder.append( $p2.str );
            $str = strBuilder.toString();
        }
    ;

param returns [String str]
    :   ID          { $str = strMapID.get($ID.text); }      // assign ID definition to str
    |   string      { $str = $string.text; }
    |   function    { $str = $function.str; }
    ;

ifdef
    :   {   Boolean bElse= false;
            StringBuilder strBuilder = new StringBuilder(); }
        HASH 'ifdef' '(' ID ')' c1=expr ( HASH 'else' c2=expr { bElse= true; } )? HASH 'end'
        {   if ( strMapDefine.containsKey($ID.text) ) {
                strBuilder.append($c1.text);
            }
            else {
                if ( bElse ) {
                    strBuilder.append($c2.text);
                }
            }
            System.out.println("ifdef content is : " + strBuilder.toString() + "\n" );
        }
    ;

expr
    :   .+
    ;

ID
    :   ('a'..'z' | 'A'..'Z')+
    ;

WS
    :   ( ' ' | '\t' | '\n' | '\r' ) {$channel=HIDDEN;}
    ;

和java主类

package Grammar;

import java.io.IOException;

import org.antlr.runtime.ANTLRFileStream;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.TokenStream;

import Grammar.ifdefParser.rule_return;


public class mainifdef {

    public static void main(String[] args) throws RecognitionException {
        CharStream stream=null;
        try {
            stream = new ANTLRFileStream("src/input/test.txt");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ifdefLexer lexer = new ifdefLexer(stream);
        TokenStream tokenStream = new CommonTokenStream(lexer);
        ifdefParser parser = new ifdefParser(tokenStream);
        rule_return evaluator = parser.rule();

        System.out.println("Parsing Tree is \n" + evaluator.tree.toStringTree() + "\n");
        System.out.println("Evaluation is \n" + evaluator.strEval + "\n");

    }
}

输入文件内容如:

  

#undef Z
  设置AB =“toto”;
  设置CD =“titi”;

     

DIFF(CD, “essai”)
  #ifdef(Z)add(#end

     

add(AB,diff(CD,“essai”))

结果控制台符合预期

  

ifdef内容为:

     

解析树是
  #undef Z set AB =“toto”;设置CD =“titi”; diff(CD,“essai”)#ifdef(Z)add(#end add(AB,diff(CD,“essai”))

     

评价为
  “蒂蒂” - “essai”
  “toto”+“titi” - “essai”

我的问题是如何评估这样的输入文本应该给出相同的结果:

  

#undef Z
  设置AB =“toto”;
  设置CD =“titi”;

     

DIFF(CD, “essai”)
  #ifdef(Z)add(#end

     

add(AB,#ifdef(Z)add(#else diff(#end CD,“essai”))

结果控制台是(这是正常的ANTLR行为):

  

ifdef内容为:

     

src / input / test.txt第8:11行输入'#'没有可行的替代方案   src / input / test.txt 8:43在'CD'中缺少EOF
  ifdef内容是:diff(

     

解析树是
  #undef Z set AB =“toto”;设置CD =“titi”; diff(CD,“essai”)#ifdef(Z)add(#end add(AB,&lt; unexpected:[@ 59,94:94 ='#',&lt; 6&gt;,8:11],resync = #&gt;&lt; missing')'&gt; #ifdef(Z)add(#else diff(#end&lt; missing EOF&gt;

     

评价为
  “蒂蒂” - “essai”
  “toto”+ null

一些指导从哪里开始将更加欣赏 关心JPM

0 个答案:

没有答案