Reputation: 23
I am new to rascal and want to extract conditional statements (if,while,etc) from a java project.
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
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.?
Upvotes: 1
Views: 808
Reputation: 6696
@Geert-Jan Hut's answer is the best, because this is what visit is for.
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
:
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));
Upvotes: 0
Reputation: 140
Rascal implements the Visitor pattern for this. You could do something like this on your ast
variable:
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.
You can find the definitions of patterns to use as case patterns in the package lang::java::m3::AST.
Upvotes: 1