I am using clang matcher to obtain the result nodes. From the result nodes, I am able to get the line number, let us say 17. Now, I would like to get the entire source code in that line. Please help.
Let me explain in detail. I have a clang matcher that finds the floating literal in the source code. For example, line 17, sr = 2.0 * rt_urand_Upu32_Yd_f_pw_snf(u);
is the source code, then it matches the 2.0. This is my matcher:
const auto PA = floatLiteral(
isExpansionInMainFile(),
unless(hasAncestor(arraySubscriptExpr()))
).bind("pa");
MatchFinder MatchFinder;
MatchFinder.addMatcher(PA, &Handler);
MatchFinder.matchAST(Context);
From the matcher, I am able to obtain the node where it got matched. I am able to retrieve the line number (line 17) and column number (6). Please find my code below:
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;
Now, if I try to retrieve the source code I am getting only the partial data. After doing some research in online, I tried to retrieve the source code in two ways. First approach is using lexer, please find the code below:
llvm::StringRef ref = Lexer::getSourceText(CharSourceRange::getCharRange(statement->getSourceRange()), srcMgr, LangOptions());
cout << ref.str() << endl;
Second approach is using rewriter, please find the code below:
clang::Rewriter rewriter;
rewriter.setSourceMgr(Result.Context->getSourceManager(),Result.Context->getLangOpts());
cout<<rewriter.getRewrittenText (loc)<<endl;
To my understanding, it seems that I need the sourcerange starting from column 0 of line 17 to end of column in line 17. The AST matcher only matches specific node, so my question is:
1) is it possible to get the final column number of line 17?
2) is there any other approach to get the source code from line number?
3) is there any other approach to get the source code from matcher?
Thanks for the help.