lookup of a variable

Hi!

Given the qualified identifier of a variable (as a pure string like
"A::b::foo"), an ASTContext and a Sema how can I

1) verify a variable with the given name exists within the current
translation unit?
2) get its type?
3) the value it was initialized to, if any?

How about the same issue with an unqualified identifier and a
Decl/DeclContext to start the search from?

I found 'Sema::Lookup*Name' and it looks like a good start. But to use
that I need a 'LookupResult' which in turn needs a 'DeclarationNameInfo'
that yet again needs a 'SourceLocation'. And I do not have that but only
an ID...

Can I use these Sema lookups at all? All examples I saw use them from
within other Sema methods.

Any hint/help appreciated :slight_smile:

Regards, Jan.

Hi!

Given the qualified identifier of a variable (as a pure string like
"A::b::foo"), an ASTContext and a Sema how can I

If you're actually coming from a string, you should consider watching what the parser does when parsing A::b::foo as an id-expression.

1) verify a variable with the given name exists within the current
translation unit?

Sema::LookupQualifiedName can do this.

2) get its type?

Once you have a VarDecl, just use it's getType() member function.

3) the value it was initialized to, if any?

VarDecl::getInit().

How about the same issue with an unqualified identifier and a
Decl/DeclContext to start the search from?

I found 'Sema::Lookup*Name' and it looks like a good start. But to use
that I need a 'LookupResult' which in turn needs a 'DeclarationNameInfo'
that yet again needs a 'SourceLocation'. And I do not have that but only
an ID...

LookupResult is where the results go. If you don't care about location information, just synthesize the DeclarationNameInfo with an empty SourceLocation().

Can I use these Sema lookups at all? All examples I saw use them from
within other Sema methods.

Yes, these are the lookup functions you want. LookupName is unqualified lookup from a scope, LookupQualifiedName is qualified name lookup into a DeclContext.

  - Doug

Douglas Gregor meinte am 01.09.2010 16:18:

Given the qualified identifier of a variable (as a pure string like
"A::b::foo"), an ASTContext and a Sema how can I

If you're actually coming from a string, you should consider watching
what the parser does when parsing A::b::foo as an id-expression.

I did that, but ran into a dead end soon. The parser starts with a
'ParsingDeclSpec' which I cannot create because I'm missing a reference
to the parser. From there on I cannot replicate any of the actions the
parser does. Perhaps I should have mentioned earlier that I'm working
from inside a plugin's 'SemaConsumer'...

The core of my problem is that I need some way to hand craft an
'IdentifierInfo' without the parser. Is that possible at all?

Regards, Jan.

IdentifierInfo's are created by IdentifierTable::get(). The ASTContext has a reference to an IdentifierTable that you can use.

  - Doug