[cfe-dev] parsing of self-referring vardecls

Steve Naroff snaroff at apple.com
Tue Sep 11 14:14:43 PDT 2007


On Sep 11, 2007, at 1:53 PM, Chris Lattner wrote:

> On Sep 11, 2007, at 11:28 AM, Ted Kremenek wrote:
>> I'm not certain if vardecls are being correctly parsed.  Consider the
>> following program (self-decl.c):
>
> You're right, this looks like a bug in the initializer parsing
> stuff.  "var" should be added to the scope chain before the
> initializer for var is parsed.  This will require some juggling of
> the actions hooks though, so it will be non-trivial.
>
> Steve, can you add this to your todo list?
>

Already added...Ted and I discussed this over lunch.

As you say, the fix requires some redesign of the parser/action dance...

snaroff

> -Chris
>
>> #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).
>> _______________________________________________
>> cfe-dev mailing list
>> cfe-dev at cs.uiuc.edu
>> http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev
>
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at cs.uiuc.edu
> http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev




More information about the cfe-dev mailing list