[cfe-dev] Understanding Source Locations

Alex Denisov via cfe-dev cfe-dev at lists.llvm.org
Wed Feb 20 21:28:35 PST 2019


Btw, if anyone faces similar issue: the problem was caused by buildASTFromCodeWithArgs, not by source locations.
For some reason buildASTFromCodeWithArgs did not produce correct AST, presumably because of an include. When I inline the code from header it works as expected.
The workaround (or the proper solution?) is to use clang::ASTUnit::LoadFromCommandLine, which works correctly.

Best regards,
Alex.

> On 16. Feb 2019, at 00:07, Alex Denisov <1101.debian at gmail.com> wrote:
> 
> Hi there,
> 
> I'm having an issue using SourceLocations.
> I do the following:
> 
> 1. Create ASTUnit from code:
> 
> auto buffer = MemoryBuffer::getFile(path);
> Twine code(buffer.get()->getBuffer());
> auto ast = std::move(clang::tooling::buildASTFromCodeWithArgs(code,
>    { "-x", "c++", "-I", "<the right path to a header>"}, path));
> 
> 2. Create simple custom RecursiveASTVisitor and run it against the ASTUnit:
> 
> Visitor visitor(ast->getSourceManager());
> visitor.TraverseDecl(ast->getASTContext().getTranslationUnitDecl());
> 
> 3. In the visitor, dump locations of some BinaryOperators:
> 
> bool VisitBinaryOperator(clang::BinaryOperator *binaryOperator) {
>  auto range = binaryOperator->getSourceRange();
>  range.getBegin().dump(sourceManager);
> }
> 
> It all works good, until some point:
> 
> include/header.h:8:9
> main.cpp:5:7
> main.cpp:9:7
> main.cpp:13:7
> main.cpp:17:7
> <marker>
> main.cpp:18:126
> main.cpp:22:19
> main.cpp:32:7
> 
> All locations before the <marker> are correct, but then something happens and goes off the track: I certainly do not have 126 characters long lines. The last three locations point to a wrong place, both line- and column-wise.
> 
> I must be doing something wrong, but could not figure it out.
> I read through the related documentation I could find[1][2][3], but no luck so far. I also tried converting those locations into some other types of locations.
> 
> I would appreciate if anyone can give some hints on what could go wrong. I attach the files being parsed to this email, but they can be found here[4] as well.
> 
> [1] https://clang.llvm.org/docs/InternalsManual.html
> [2] https://clang.llvm.org/docs/PCHInternals.html
> [3] https://clang.llvm.org/docs/DriverInternals.html
> [4] https://gist.github.com/AlexDenisov/543da61e0ef6250d5f490f2464c52e9b
> 
> Thank you,
> Alex.
> 
> <main.cpp><header.h>




More information about the cfe-dev mailing list