我正在尝试解析Java文件并计算其中的方法声明。现在我使用以下代码:
import ParseTree;
import lang::java::\syntax::Java15;
import IO;
public int countMethods(loc file) {
int n = 0;
try {
comp = parse(#CompilationUnit, file);
for (/MethodDec md <- comp) {
n = n + 1;
}
} catch ParseError(loc l): {
println("Error at line <l.begin.line>, col <l.begin.column>.");
}
return n;
}
我遇到了CompilationUnit类型不可枚举的错误消息。现在我想知道如何获得/遍历所有方法?
答案 0 :(得分:4)
int x <- l
表示迭代l
并在其上应用模式匹配int x
,如果成功,则将x
绑定到该值。这意味着对于<-
,右侧必须是可以使用的(列表,集合,地图......)。如果要使用后代匹配匹配所有案例,通常需要使用:=
匹配运算符。即使右手边是可枚举的。见下面的例子:
import IO;
list[list[int]] ll = [[1,2],[1,3,4],[3],[1,1,1,3,4]];
println("Pattern match on the children of ll");
for (/list[value] v <- ll) {
println(v);
}
println("Pattern match on the children of ll and ll itself");
for (/list[value] v := ll) {
println(v);
}
此输出:
Pattern match on the children of ll
[1,2]
[1,3,4]
[3]
[1,1,1,3,4]
Pattern match on the children of ll and ll itself
[1,2]
[1,3,4]
[3]
[1,1,1,3,4]
[[1,2],[1,3,4],[3],[1,1,1,3,4]]
区别在于模式匹配器尝试的候选者。
对于您的具体示例,您也可以使用redurs编写它:
public int countMethods(loc file) {
try {
return (0 | it + 1 | /MethodDec md := parse(#CompilationUnit, file));
} catch ParseError(loc l): {
println("Error at line <l.begin.line>, col <l.begin.column>.");
return 0;
}
}
答案 1 :(得分:3)
为什么不呢?
public int countMethods(loc file)
{
try
{
return size([1 | /MethodDec md <- parse(#CompilationUnit, file)]);
}
catch ParseError(loc l):
{
println("Error at line <l.begin.line>, col <l.begin.column>.");
return 0;
}
}