编译原理初探二
环境:win7 64位+llvm11+mingw+python3.7+libclang11
写一个函数行数统计工具
C语言测试代码:
/*calc1.c*/ #include<stdio.h> #include<stdlib.h> /*将操作定义为枚举类型*/ typedef enum { OP_ADD = 0, OP_SUB, OP_MUL, OP_DIV, }OP_TYPE; double ADD(double op1,double op2); /*加减乘除处理函数*/ double ADD(double op1,double op2) { return op1+op2; } double SUB(double op1,double op2) { return op1-op2; } double MUL(double op1,double op2) { return op1*op2; } double DIV(double op1,double op2) { return op1/op2; } double calc(int op,double op1,double op2) { /*使用switch,根据操作类型,选择操作*/ double result = 0; switch(op) { case OP_ADD: { result = ADD(op1,op2); break; } case OP_SUB: { result = SUB(op1,op2); break; } case OP_MUL: { result = MUL(op1,op2); break; } case OP_DIV: { result = DIV(op1,op2); break; } default: { printf("unsupport opration\n"); break; } } return result; } int main(int argc,char *argv[]) { if(4 > argc) { printf("usage:op num1 num2\n"); printf("op[0:add,1:sub,2:mul;3:div]\n"); return 0; } int op = atoi(argv[1]); double op1 = atof(argv[2]); double op2 = atof(argv[3]); printf("op:%d,op1:%.1f,op2:%.1f\n",op,op1,op2); double result = calc(op,op1,op2); printf("result is %.1f\n",result); return 0;
python脚本
from clang.cindex import Config #配置 from clang.cindex import TypeKind from clang.cindex import CursorKind from clang.cindex import Index #主要API from clang.cindex import Token def GetTranslationUnit(filename): index = Index.create() tu = index.parse(filename) print("tTranslation Unit=%s"%(tu.spelling)) return tu def LoadLibClang(libclangPath): if Config.loaded == True: pass else: Config.set_library_file(libclangPath) #主函数 if __name__ == '__main__': filename='calc.c' # C语言文件 libclangPath = r'C:\Program Files\LLVM\bin\libclang.dll' #libclang库路径 LoadLibClang(libclangPath) #加载libclang库 tu=GetTranslationUnit(filename)#解析main.c ast_root_node=tu.cursor #获取cursor根节点 functionList=[] print("Print all nodes in ast tree:") for node in ast_root_node.walk_preorder(): # 遍历词法分析结果 if node.kind==CursorKind.FUNCTION_DECL: if node.is_definition()and str(node.location.file)==filename: functionList.append(node) print('%-6s %-6s %-6s %-6s'%('文件','函数名','起始行号','函数行号')) for node in functionList: lines=node.extent.end.line-node.extent.start.line+1; print('%-8s %-8s %-8s %-6s'%(node.location.file,node.spelling,node.location.line,lines))
运行结果:
可以看到ADD函数起始行号是13行,函数体一共有4行
0.0分
0 人评分