[cfe-dev] parsing of self-referring vardecls
Ted Kremenek
kremenek at apple.com
Tue Sep 11 11:28:49 PDT 2007
I'm not certain if vardecls are being correctly parsed. Consider the
following program (self-decl.c):
#include <stdio.h>
int foo(int var)
{
{ // note the extra scope
L1:
int var = var+1;
return var;
}
}
int main() {
printf("%d\n",foo(10));
return 0;
}
The output of this program is not what you might expected:
(kremenek at grue:tmp)$ gcc -o self-decl self-decl.c
(kremenek at grue:tmp)$ ./self-decl
1
What happens is that the declaration of "var" at label "L1" refers to
itself, and thus is undefined. This is because "var" comes into scope
before its initialization. I wrote a checker to look for such cases,
but it isn't flagging any warnings because the initialization is
falsely referring to the decl in the enclosing scope. This can be
seen from a dump of the AST:
int foo(int var)
(CompoundStmt 0x710fd0 </tmp/self-decl.c:3:18, line:8:1>
(CompoundStmt 0x710f60 <line:4:3, line:7:3>
(DeclStmt 0x70f210 <:0:0>
0x710f00 "int var =
(BinaryOperator 0x710ee0 </tmp/t2.c:5:15, col:19> 'int' '+'
(DeclRefExpr 0x70ec50 <col:15> 'int' ParmVariable='var'
0x710e90)
(IntegerLiteral 0x710ec0 <col:19> 'int' 1))")
(ReturnStmt 0x710f50 <line:6:5, col:12>
(DeclRefExpr 0x710f30 <col:12> 'int' BlockVariable='var'
0x710f00))))
Notice the "DeclRefExpr" refers to the ParmVariable, not a VarDecl
(the choice of using a parameter in this case just easily
disambiguates this case, but "var" could have been a variable declared
in any enclosing scope).
More information about the cfe-dev
mailing list