我正在编写一个 libtooling 重构工具。我有课,比方说Foo
,在名为的标头中定义foo.h
。我想看看是否foo.h
包含在一个文件中。目前,要检查是否bar.cc
包括foo.h
,我只是使用匹配recordDecl(hasName("Foo"))
。这有效是因为class Foo { ... };
将存在于bar.cc
预处理后的 AST,如果bar.cc
包括foo.h
.
但这不起作用,例如,bar.cc
包括cat.h
包括foo.h
。我想bar.cc
明确包括foo.h
.
此外,我希望能够匹配#define
macros.
我编写工具的方式使这两个目标变得不可能,因为我匹配的 AST 已经过预处理。我想做的事情可能吗?我挖了周围Preprocessor
Clang 的 Doxygen 页面上的类参考,但我还没有找到我要找的东西。
我在深入研究 Clang 的 Doxygen 和代码后发现了这一点。我需要使用PPCallbacks
类与Preprocessor
班级。下面是一个例子。请注意,这不能保证是功能代码片段,但它说明了一般用法。有关详细信息,请参阅 Clang 的PP回调文档以及以下文档添加PP回调 and 获取PP回调 in clang::预处理器.
class Find_Includes : public PPCallbacks
{
public:
bool has_include;
void InclusionDirective(
SourceLocation hash_loc,
const Token &include_token,
StringRef file_name,
bool is_angled,
CharSourceRange filename_range,
const FileEntry *file,
StringRef search_path,
StringRef relative_path,
const Module *imported)
{
// do something with the include
has_include = true;
}
};
class Include_Matching_Action : public ASTFrontendAction
{
bool BeginSourceFileAction(CompilerInstance &ci, StringRef)
{
std::unique_ptr<Find_Includes> find_includes_callback(new Find_Includes());
Preprocessor &pp = ci.getPreprocessor();
pp.addPPCallbacks(std::move(find_includes_callback));
return true;
}
void EndSourceFileAction()
{
CompilerInstance &ci = getCompilerInstance();
Preprocessor &pp = ci.getPreprocessor();
Find_Includes *find_includes_callback = static_cast<Find_Includes>(pp.getPPCallbacks());
// do whatever you want with the callback now
if (find_includes_callback->has_include)
std::cout << "Found at least one include" << std::endl;
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)