1

我是 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));
    }

但这会返回所有语句,包括注释。如何过滤语句以仅返回条件语句 if、while、for 等?

4

2 回答 2

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中找到用作案例模式的模式定义。

于 2013-12-29T10:07:29.110 回答
0

@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));
于 2013-12-30T09:23:44.403 回答