我正在尝试为 Sonar javascript 插件创建一个自定义规则,以检查是否在几个 js 源文件之一中调用了 init() 函数。我首先订阅调用表达式:
public void init() {
subscribeTo(EcmaScriptGrammar.CALL_EXPRESSION);
}
然后,我通过覆盖 visitNode 方法确保调用了 init() 函数:
public void visitNode(AstNode node){
String functionCall=new String();
List<Token> tokens = node.getTokens();
for(int i=0; i<tokens.size(); i++){
functionCall+=tokens.get(i).getValue();
}
if(functionCall.equals("init()"))
callMade=true;
}
最后,在离开文件时,如果未调用 init(),我将创建违规:
public void leaveFile(AstNode node){
if(!callMade)
getContext().createLineViolation(this,"No call to init()",node);
}
这工作得很好,但是为每个不包含 init() 的 js 源文件创建了违规。我希望仅当在任何 js 源文件中未调用 init() 时才创建违规行为。我怎样才能做到这一点?