null this, classes, methods and "null this" assertion

ketmar via Digitalmars-d digitalmars-d at puremagic.com
Fri Apr 10 19:58:47 PDT 2015


On Fri, 10 Apr 2015 22:49:07 -0400, Steven Schveighoffer wrote:

> On 4/10/15 10:17 PM, ketmar wrote:
>> On Fri, 10 Apr 2015 22:06:53 -0400, Steven Schveighoffer wrote:
>>
>>> In non-release mode, it's calling the invariant, which is a virtual
>>> function.
>>
>> yet compiler can generate `CondExp` instead of `AssertExp`, and don't
>> fail when `this` is `null`.
>>
>>
> A virtual function cannot be called on a null pointer. I would have
> actually expected it to crash, but maybe it does something special for
> invariant.

it does literally this:

      Expression *v = new ThisExp(Loc());
      v->type = vthis->type;
      if (ad->isStructDeclaration())
          v = v->addressOf();
      Expression *se = new StringExp(Loc(), (char *)"null this");
      se = se->semantic(sc);
      se->type = Type::tchar->arrayOf();
      e = new AssertExp(Loc(), v, se);

what i suggest is to change `AssertExp` to `CondExp` (when 
global.params.useAssert and global.params.useInvariants are both set). it 
*should* do the same, i think. i.e. do something like this:

    if (global.params.useAssert && global.params.useInvariants) {
      Expression *v = new ThisExp(Loc());
      v->type = vthis->type;
      if (ad->isStructDeclaration())
          v = v->addressOf();
      e = new CondExp(Loc(), v, v->syntaxCopy(), new NullExp(Loc()));
    } else {
      e = new HaltExp(Loc());
    }
    e = e->semantic(sc);
    e->type = Type::tvoid;

dunno if `syntaxCopy` is necessary here, though, and how is it all 
related to calling invariant function. it's just a blind guess.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20150411/6cab3675/attachment.sig>


More information about the Digitalmars-d mailing list