我正在使用 clang matcher 来获取结果节点。从结果节点中,我能够获取行号,假设为 17。现在,我想获取该行中的整个源代码。请帮忙。
让我详细解释一下。我有一个 clang 匹配器,可以在源代码中查找浮动文字。例如,第17行sr = 2.0 * rt_urand_Upu32_Yd_f_pw_snf(u);是源代码,那么它匹配2.0。这是我的匹配器:
const auto PA = floatLiteral(
isExpansionInMainFile(),
unless(hasAncestor(arraySubscriptExpr()))
).bind("pa");
MatchFinder MatchFinder;
MatchFinder.addMatcher(PA, &Handler);
MatchFinder.matchAST(Context);
Run Code Online (Sandbox Code Playgroud)
从匹配器中,我可以获得匹配的节点。我能够检索行号(第 17 行)和列号(6)。请在下面找到我的代码:
const clang::FloatingLiteral* Variable = Result.Nodes.getNodeAs<clang::FloatingLiteral>("pa");
clang::SourceRange loc = Variable16->getSourceRange();
locStart = srcMgr.getPresumedLoc(loc.getBegin());
locEnd = srcMgr.getPresumedLoc(loc.getEnd());
std::cout << locStart.getLine()<< ":" << locEnd.getLine() << std::endl;
std::cout << locStart.getColumn() <<":" << locEnd.getColumn() << std::endl;
Run Code Online (Sandbox Code Playgroud)
现在,如果我尝试检索源代码,我只能得到部分数据。在网上做了一些研究后,我尝试通过两种方式检索源代码。第一种方法是使用词法分析器,请找到下面的代码:
llvm::StringRef ref = Lexer::getSourceText(CharSourceRange::getCharRange(statement->getSourceRange()), srcMgr, LangOptions());
cout << ref.str() << endl;
Run Code Online (Sandbox Code Playgroud)
第二种方法是使用重写器,请找到下面的代码:
clang::Rewriter rewriter;
rewriter.setSourceMgr(Result.Context->getSourceManager(),Result.Context->getLangOpts());
cout<<rewriter.getRewrittenText (loc)<<endl;
Run Code Online (Sandbox Code Playgroud)
据我了解,我似乎需要从第 …
我刚开始使用 ASTMatcher 并遵循教程中的代码 - https://github.com/peter-can-talk/cppnow-2017。在这里,可以使用以下命令运行工具 clang-variables:
cd code/clang-variables
docker run -it -v $PWD:/home clang
root@5196c095092d:/home# ./clang-variables test.cpp -- -std=c++14
Run Code Online (Sandbox Code Playgroud)
如果我使用另一个源文件,而不是 test.cpp 文件,则会出现以下错误:
fatal error: 'stddef.h' file not found
#include <stddef.h>
^~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
我知道我的源文件有这些需要包含的头文件。我尝试将它们包含在 Makefile 中,如下所示,但错误仍然存在:
clang-variables: $(TARGET).cpp
$(CXX) $(HEADERS) $(LDFLAGS) $(CXXFLAGS) $(TARGET).cpp $(LIBS) -o $(TARGET) -I$(START_DIR)/source -I$(HOME_ROOT)/extern/include
Run Code Online (Sandbox Code Playgroud)
编译时没有错误。所以我想知道,是否可以将包含文件作为 ASTMatcher 的参数提及?请在下面找到代码:
// Clang includes
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Type.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
// LLVM includes
#include "llvm/ADT/ArrayRef.h" …Run Code Online (Sandbox Code Playgroud)