how does clang tackle DeclContext, like ForContext


In a C for loop like:
int a[10];
for(int i = 0; i < 10; i++){
a[i] = i + 1;

The variable “i” is declared in the ForContext in ParseForStatement(), and then when parse body, I.E., the expression “a[i]” later, how does it know that “i” is declared?

In other words, how does the ForContext affect the later parsing of variable “i” ?

By performing a name lookup into appropriate Scope. Scopes are linked in a chain and name lookup traverses them starting from the inner one.

Adding back cfe-dev

If you’re tying to introduce a new variable I suggest you look at what happens with ‘i’ in ‘for (int i;;)’. I don’t think your code is adding the VarDecl to the AST, you’re building the node but how does it connect to existing nodes? You probably don’t want to do all this work manually anyway, I’m not sure if ActOnVariableDeclarator is the right function but it might do most of the work for you. I’m not sure how IdentifierResolver, IdentifierTable and other machinery is supposed to be updated by one of Sema functions likely does it.

Thank you, Nikola.

I will try what you said.

Yes, after source-2-source, I can get the DeclStmt, but the reference to the new-variable in the loop body is said have not been declared.