Variable scope

Hello everyone,

I’m writting some code for visiting variable, struct, … declarations (I’m using C Language). For that, my class derives from DeclVisitor. My goal is to determine the scope of each variable at its declaration (ie inside the VisitVarDecl method). The method getSourceRangeonly of VarDecl only returns the range of the declaration in terms of caracters, not the real scope. Is there method for getting the VarDecl scope ?

Thanks by advance,

Nicolas

Hello everyone,

I'm writting some code for visiting variable, struct, ... declarations (I'm
using C Language). For that, my class derives from DeclVisitor. My goal is
to determine the scope of each variable at its declaration (ie inside the
VisitVarDecl method). The method getSourceRangeonly of VarDecl only returns
the range of the declaration in terms of caracters, not the real scope.

Right, the notion of a source range is about a position in the source
text, not in the AST structure.

Is
there method for getting the VarDecl scope ?

You might look at getParentFunctionOrMethod and/or getDeclContext (and
if you use getDeclContext you might also want DeclContext::getParent).
I'm assuming here that you're writing C++ code that visits C code,
given that you spoke of a class derived from DeclVisitor.

-- James

Thank you James for your answer.

I already tried getDeclContext, getParentFunctionOrMethod and others, but I can not retrieve the correct scope in the following case:

int main (int argc, char ** argv)
{
int foo1;
{
int foo2;
}
}

At declaration, foo2 has a DeclContext whose kind is “Function”, which is not the correct scope…

Moreover, I see that there is a BlockDecl data structure, but VisitBlockDecl don’t work, as it seems to works only for objective C block (ie ^{…}). Why this don’t work for classical c-like blocks ?

Finally, I’d like to retrieve the scope of each declared variable in termes of SourceRange. How can I get the SourceRange from a DeclContext ?

I’m sorry, but I’m a clang beginner…
Thank you by advance!

Nicolas

2012/9/1 James Dennett <james.dennett@gmail.com>

Thank you James for your answer.

I already tried getDeclContext, getParentFunctionOrMethod and others, but I can not retrieve the correct scope in the following case:

int main (int argc, char ** argv)
{
int foo1;
{
int foo2;
}
}

At declaration, foo2 has a DeclContext whose kind is “Function”, which is not the correct scope…

Moreover, I see that there is a BlockDecl data structure, but VisitBlockDecl don’t work, as it seems to works only for objective C block (ie ^{…}). Why this don’t work for classical c-like blocks ?

Seeing as Objective-C blocks are in fact lambdas in disguise (or close enough), if VisitBlockDecl were to also visit regular blocks, it would be quite confusing => they are really totally different (and unrelated) concepts.

– Matthieu