hhvm icon indicating copy to clipboard operation
hhvm copied to clipboard

Hack: Allow this as a parameter to a callable in a static member variable

Open HRMsimon opened this issue 10 years ago • 2 comments

HHVM Version

3.15.0

Standalone code, or other way to reproduce the problem

<?hh // strict

abstract class Foo {
  protected static array<(function(this):void)> $callables = [];

  public static function getCallables(): array<(function(this):void)> {
    return static::$callables;
  }
}

Expected result

No errors!

Actual result

The type "this" cannot be used as a constraint on a class' generic, or as the type of a static member variable (Naming[2043])

HRMsimon avatar Sep 19 '16 22:09 HRMsimon

Our use case is a set of validator callables. We're working around this currently by using the base class as the type of the argument and then adding in an invariant call in each callback.

HRMsimon avatar Sep 19 '16 22:09 HRMsimon

Throwing this example to a typechecker engineer first. Your repro is No errors!, but I am most likely misunderstanding what it means to bind this as the argument of a callback. Both the runtime and the typechecker insist that calling (function(Foo): void) with ChildFoo is disallowed.

<<__EntryPoint>>
function main(): void {
    $wants_foo = Foo::wantsThis();
    $wants_child = ChildOfFoo::wantsThis();
    $wants_child(new ChildOfFoo());
    // Why can't I call `(function(Foo): void)` with `ChildOfFoo`?
    $wants_foo(new ChildOfFoo());
    /*
    Typing[4110] Invalid argument
       --> src/file.hack
      3 |     $wants_foo = Foo::wantsThis();
        |                  ^^^ Expected exactly the type Foo
        |                  ^^^   where the class 'Foo' was referenced here
      7 |     $wants_foo(new ChildOfFoo());
        |                ^^^^^^^^^^^^^^^^
     35 | class ChildOfFoo extends Foo {}
        |                          ^^^ But got the nonexact type Foo

    1 error found.

    Fatal error: Uncaught TypeError: Argument 1 passed to Foo::__invoke() must be an instance of this, ChildOfFoo given in /path/to/file.hack:25
    Stack trace:
    #0 /path/to/file.hack(7): Closure$Foo::wantsThis()
    #1 (): main()
    #2 {main}
    */
}

abstract class Foo {
    public static function wantsThis(): (function(this): void) {
        return (this $_) ==> {};
    }
}

class ChildOfFoo extends Foo {}

lexidor avatar May 27 '20 00:05 lexidor