【问题标题】:How to extract specific statements from java eclipse project using rascal如何使用流氓从java eclipse项目中提取特定语句
【发布时间】:2013-12-27 13:41:39
【问题描述】:

我是 rascal 的新手,想从 java 项目中提取条件语句(if、while 等)。

最好的方法似乎是http://tutor.rascal-mpl.org/Rascal/Libraries/analysis/m3/Core/containment/containment.html#/Rascal/Libraries/analysis/m3/AST/AST.html

到目前为止我的代码是

    void statements(loc location) {
        ast = createAstFromFile(location,true,javaVersion="1.7");
        for(/Statement s := ast) println(readFile(s@src));
    }

但这会返回包括 cmets 在内的所有语句。 如何过滤语句以仅返回条件语句 if、while、for 等?

【问题讨论】:

    标签: java eclipse abstract-syntax-tree rascal


    【解决方案1】:

    Rascal 为此实现了访问者模式。你可以在你的 ast 变量上做这样的事情:

    visit(ast){ 
        case \if(icond,ithen,ielse): {
            println(" if-then-else statement with condition <icond> found"); } 
        case \if(icond,ithen): {
            println(" if-then statement with condition <icond> found"); } 
    };
    

    此示例从代码中返回 if 语句。

    您可以在包lang::java::m3::AST 中找到用作案例模式的模式定义。

    【讨论】:

      【解决方案2】:

      @Geert-Jan Hut 的回答是最好的,因为这就是访问的目的。

      这里有一些其他的方法:

      for(/\if(icond,ithen,ielse) s := ast) 
        println(readFile(s@src));
      
      for(/\if(icond,ithen) s := ast) 
        println(readFile(s@src));
      

      或者,因为两个构造函数同名,你可以使用is

      for (/Statement s := ast, s is if)
        println(readFile(s@src));
      

      或者,先把它们全部收集起来再打印:

      conds = { c | /Statement s := ast, s is if };
      for (c <- conds) 
         println(readFile(c@src));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-29
        • 2014-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-11
        • 2021-02-21
        • 2017-03-14
        相关资源
        最近更新 更多