6

I'm using clang 3.0 library for some analysis of C/C++ code, and I need to get location of variable declaration, I tried this code:

clang::VarDecl * vd = ...;
clang::SourceManager & srcMgr = ...;

clang::SourceRange loc = vd->getSourceRange();
clang::PresumedLoc locStart = srcMgr.getPresumedLoc(loc.getBegin());
clang::PresumedLoc locEnd = srcMgr.getPresumedLoc(loc.getEnd());

But locStart and locEnd points to the beginning (and ending) of declaration variable (with type, and, possibly initialiser). For example:

const char * ptr = 0;
^            ^ ^   ^

locStart will point at the first pointer(^) , and locEnd will point at the last pointer. How can I get the location of the second and third pointers (only name, without type and initialiser)?

Mat
  • 202,337
  • 40
  • 393
  • 406
Alexey
  • 938
  • 5
  • 13

1 Answers1

6

I'm currently not in the position to test it but I think you want to extract the SourceLocation obtained by getLocation() from your VarDecl. This function is actually defined by the Decl base class. Although it seems to identify just one location it seems to be usable to identify the entire name (I haven't tried to extract its individual ends, however, just used it to indicate the variable).

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • Sorry, but `getQualifierLoc()` does not helps. This function returns `NestedNameSpecifierLoc`, and for my case it returns empty object (without any information). – Alexey Jan 30 '12 at 15:00
  • Yes, you are right: this is actually for the location of things like `const` or `volatile`. I have tested with a sample program and it seems that it is as simple as using `getLocation()`: while the `VarDecl` itself want to start with the type, the `SourceLocation` returned by `getLocation()` seems to identify the name. – Dietmar Kühl Jan 30 '12 at 23:32
  • Thanks, it really helps, i dont know, why i started to use `getSourceRange`, `getLocation` works for me! – Alexey Jan 31 '12 at 14:18
  • @Alexey - Please post the code in answer to get better understanding and reference. – S S Aug 25 '15 at 14:49