[英]How to extract specific statements from java eclipse project using rascal
I am new to rascal and want to extract conditional statements (if,while,etc) from a java project. 我是rascal的新手,想从Java项目中提取条件语句(if,while等)。
The best method seems to be at http://tutor.rascal-mpl.org/Rascal/Libraries/analysis/m3/Core/containment/containment.html#/Rascal/Libraries/analysis/m3/AST/AST.html 最好的方法似乎在http://tutor.rascal-mpl.org/Rascal/Libraries/analysis/m3/Core/containment/containment.html#/Rascal/Libraries/analysis/m3/AST/AST.html
My code so far is 到目前为止,我的代码是
void statements(loc location) {
ast = createAstFromFile(location,true,javaVersion="1.7");
for(/Statement s := ast) println(readFile(s@src));
}
But this returns all statements including comments. 但这将返回所有语句,包括注释。 How do i filter the statements to only return conditional statements if,while,for,etc.?
我如何过滤语句以仅在条件等情况下返回条件语句?
Rascal implements the Visitor pattern for this. Rascal为此实现了Visitor模式。 You could do something like this on your
ast
variable: 您可以在
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"); }
};
This example returns the if
statements from the code. 本示例从代码返回
if
语句。
You can find the definitions of patterns to use as case patterns in the package lang::java::m3::AST . 您可以在lang :: java :: m3 :: AST包中找到用作案例模式的模式定义。
@Geert-Jan Hut's answer is the best, because this is what visit is for. @ Geert-Jan Hut的答案是最好的,因为这是访问的目的。
Here is some other methods: 这是其他一些方法:
for(/\if(icond,ithen,ielse) s := ast)
println(readFile(s@src));
for(/\if(icond,ithen) s := ast)
println(readFile(s@src));
Or, because both constructors have the same name, you could use is
: 或者,因为两个构造函数具有相同的名称,所以可以使用
is
:
for (/Statement s := ast, s is if)
println(readFile(s@src));
Or, first collect them all and then print: 或者,首先收集它们,然后打印:
conds = { c | /Statement s := ast, s is if };
for (c <- conds)
println(readFile(c@src));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.