hhvm icon indicating copy to clipboard operation
hhvm copied to clipboard

Hack: Memoize doesn't play nice with LSB

Open HRMsimon opened this issue 10 years ago • 6 comments

See example run: https://3v4l.org/fKi0j

<?hh

class A {
    protected static string $string = 'Hello';

    <<__Memoize>>
    public static function foo(): string {
        return static::$string;
    }
}

class B extends A {
    protected static string $string = 'World';
}

I'd expect B::foo() to return 'World' in this case, whereas it returns Hello.

HRMsimon avatar Dec 08 '15 00:12 HRMsimon

I'm fairly certain this is by design. __Memoize caches are keyed based only on parameters, and an extending class doesn't have its own cache for memoized statics in the parent.

paulbiss avatar Dec 08 '15 01:12 paulbiss

Yeah, I suspect this is wontfix, poke @dlreeves @dabek and @int3 just in case.

jwatzman avatar Dec 08 '15 22:12 jwatzman

If that's the case, should static:: usage throw an error in a __Memoize method?

HRMsimon avatar Dec 08 '15 22:12 HRMsimon

Have managed to work around this with a nasty hack:

<?hh

class A {
    protected static string $string = 'Hello';

    <<__Memoize>>
    public static function foo($class = get_called_class()): string {
        // UNSAFE
        return $class::$string;
    }
}

class B extends A {
    protected static string $string = 'World';
}

Is slightly nicer than how we've been polluting the global namespace with a bunch of functions that are basically:

<<__Memoize>>
function getMemoizedB(): string {
  return B::foo();
}

An actual solution will be nicer though.

HRMsimon avatar Sep 06 '16 23:09 HRMsimon

This topic tends to come up from time to time internally. The consensus now seems to be that both behaviors are potentially surprising (one could easily assume the memoization was per declaration site or per LSB target).

Changing __Memoize is unlikely to be a viable option as we've found that most of the time the LSB isn't something we care about, but adding a __MemoizedLSB has been proposed a few times and is generally something I'd be in favor of adding (though I've not had time to poke at it myself).

paulbiss avatar Sep 07 '16 00:09 paulbiss

3.28 includes <<__MemoizeLSB>> as an experimental feature

fredemmott avatar Aug 28 '18 22:08 fredemmott