C/C++头文件解析(使用Eclipse插件CDT现有API)
需求
解析C/C++头文件,展示出C/C++头文件中定义的头文件原型。一个现有的资源就是CDT自带的C/C++,如下图右边所示:
注意: 以上图中(CDT)是需要打开头文件的。我们需要在不打开头文件的情况下进行分析数据。
我不想自己造轮子,想通过CDT源码中现有API解决该问题。阅读到的相关类有:
CEditor
CContentOutlinePage
CDocumentProvider
IWorkingCopyManager
和WorkingCopy
FunctionDeclaration
最终实现代码及数据展示
FileEditorInput editorInput = WorkbenchUtil.getFileEditorInput(relativePath);
// 获取C/C++头文件解析数据 ICElement[] ,源码中拼凑
CDocumentProvider cdp = new CDocumentProvider();
IWorkingCopyManager manager = new WorkingCopyManager(cdp);
manager.connect(editorInput);
WorkingCopy workingCopy = (WorkingCopy)manager.getWorkingCopy(editorInput);
ICElement[] children = workingCopy.getChildren();
if(Objects.isNull(children)) continue;
for(ICElement cElement : children) {
if(!(cElement instanceof FunctionDeclaration)) continue;
if(Objects.isNull(cElement)) continue;
FunctionDeclaration functionDeclaration = (FunctionDeclaration)cElement;
}
测试
准备的头文件
math-01.h 头文件信息
#pragma once
int add(int a, int b);
debug 数据展示
Debug 调试结果:
Debug Shell 调试代码及输出:
// 相对于eclipse 工作空间的文件路径
relativePath
(java.lang.String) 函数库管理\sys\include\math-01.h
// 第一个函数数据
// 返回值
functionDeclaration.getReturnType()
(java.lang.String) int
//参数类型列表
functionDeclaration.getParameterTypes()
(java.lang.String[]) [int, int]
//函数名
functionDeclaration.getElementName()
(java.lang.String) add
// 由以上数据可以拼接出函数原型
// int add(int,int);
附
其中 WorkbenchUtil
工具包中与 getFileEditorInput
相关代码如下
/**
* 获取工作空间
* @return
*/
public static IWorkspace getWorkspace() {
return ResourcesPlugin.getWorkspace();
}
/**
* 获取根工作空间
* @return
*/
public static IWorkspaceRoot getWorkspaceRoot() {
return getWorkspace().getRoot();
}
/**
* 获取工作空间中的文件
* @param filePath
* @return
*/
public static IFile getWorkSpaceFile(String filePath) {
return getWorkSpaceFile(new Path(filePath));
}
/**
* 获取工作空间中的文件
* @param filePath 文件路径
* @return
*/
public static IFile getWorkSpaceFile(IPath filePath) {
return getWorkspaceRoot().getFile(filePath);
}
/**
* 获取文件编辑器输入文件
* @param fileName
* @return
*/
public static FileEditorInput getFileEditorInput(String fileName) {
IFile file = getWorkSpaceFile(fileName);
if (Objects.isNull(file) || !file.exists()) {
return null;
}
String exString = file.getFileExtension();
if (exString == null)
return null;
return new FileEditorInput(file);
}