如何检测标识符命名规范
代码中的标识符包括,类名、接口名、方法名、属性名、枚举、泛型等等。使用jrscript脚本可以简单的对各种标识符进行检测和标注。
脚本实现如下 (语法规范参考jrscript.cn):
#include "java.h”
string getClassName(token tk);
/**
* @discription 如何检测类名命名规则
* @parameter tk
* @retrun string
*/
string checkClassNaming() hooks tk : @"CLS" {
if(tk == null)
return null;
string cls_name=getClassName(tk);
if(cls_name == null){
return null;
}
boolean b=regMatch(cls_name, "[A-Z][a-zA-Z]+");
if(!b){
return "class name is not suitable.";
}
}
/**
* @discription 获得类名
* @parameter tk 单词
* @retrun string
*/
string getClassName(token tk){
token [] tkList = tk.childs;
var i=0;
while(i<tkList.length){
token ttk=tkList[i];
string s = toString(ttk.values);
if(s=="class"){
break;
}
i=i+1;
}
if(i<tkList.length){
token tkCName = tkList[i+1];
return toString(tkCName.values);
}
return null;
}
#include "java.h”表示hooks函数支持的编程语言。
hooks 方法定义 string checkClassNaming() hooks tk : @“CLS” 表示该脚本将对检测的所有代码文件中,“CLS” 单词,也就是类进行检测。getClassName方法是或的类名的标识符, regMatch是使用正则表达式对类名的标识符进行检测。根据检测结果,如果不符合规范的情况下 return “class name is not suitable.”。hooks函数返回非空时将对检测的单词,根据结构进行标注。