language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
PHP
hhvm/hphp/hack/test/sound_dynamic/typing/pessimise_builtins/crash.bad.php
<?hh function so_map<Tv1, Tv2>( Traversable<Tv1> $traversable, (function(Tv1): Tv2) $value_func, ): vec<Tv2> { throw new Exception(); } <<__SupportDynamicType>> function stack_overflow(): void { $t1 = tuple('a', $x ==> Shapes::idx($x, 'a')); $t2 = tuple('b', $x ==> Shapes::idx($x, 'b')); $v = vec[$t1, $t2]; so_map( $v, $pair ==> { $p0 = $pair[0]; $p1 = $pair[1]; $p1($p0);}, ); }
hhvm/hphp/hack/test/sound_dynamic/typing/pessimise_builtins/HH_FLAGS
--allowed-fixme-codes-strict 1002,2049,2053,2063,4009,4029,4030,4051,4054,4055,4064,4090,4101,4102,4110,4123,4128,4323,4338,4341,9999,4107 --allowed-decl-fixme-codes 1002,2049,2053,4030,4054,4101,4338,4341 --enable-sound-dynamic-type --enable-supportdyn-hint --union-intersection-type-hints --like-type-hints
PHP
hhvm/hphp/hack/test/sound_dynamic/typing/pessimise_builtins/intersection_sub_union.good.php
<?hh enum E1 : string { A = 'A'; } enum E2 : string { use E1; B = 'B'; } function getShape():shape('a' => E2, ?'b' => string) { throw new Exception("A"); } async function genCheckRules( ): Awaitable<~(E1, string)> { $s = getShape(); $x = Shapes::idx($s, 'b') ?? 'a'; $y = $s['a'] as E1; return tuple($y, $x); }
hhvm/hphp/hack/test/sound_dynamic/typing/soundness_bugs/dune
(rule (alias sound_dynamic_typing_soundness_bugs_good) (deps %{exe:../../../../src/hh_single_type_check.exe} %{project_root}/hack/test/verify.py %{project_root}/hack/test/review.sh (glob_files %{project_root}/hack/test/sound_dynamic/typing/soundness_bugs/HH_FLAGS) (glob_files %{project_root}/hack/test/sound_dynamic/typing/soundness_bugs/*.good.php) (glob_files %{project_root}/hack/test/sound_dynamic/typing/soundness_bugs/*.good.php.exp) (glob_files %{project_root}/hack/test/sound_dynamic/typing/soundness_bugs/*.good.php.legacy_decl.exp)) (action (run %{project_root}/hack/test/verify.py %{project_root}/hack/test/sound_dynamic/typing/soundness_bugs --program %{exe:../../../../src/hh_single_type_check.exe} --batch --in-extension .good.php --out-extension .legacy_decl.out --expect-extension .legacy_decl.exp --fallback-expect-extension .exp --flags --enable-sound-dynamic-type --out-extension .legacy_decl.out --error-format plain))) (alias (name runtest) (deps (alias sound_dynamic_typing_soundness_bugs_good)))
PHP
hhvm/hphp/hack/test/sound_dynamic/typing/soundness_bugs/generic_params_2.good.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. <<file:__EnableUnstableFeatures('upcast_expression')>> <<__SupportDynamicType>> class Box<<<__RequireDynamic>> T> { public function __construct(private T $x) {} public function get() : T { return $this->x; } public function set(T $x) : void { $this->x = $x; } public function call_set() : void { $this->set("1" upcast dynamic); } } function expect_int(int $i) : void {} <<__EntryPoint>> function f() : void { $b = new Box<int>(1); $b->call_set(); expect_int($b->get()); }
PHP
hhvm/hphp/hack/test/tast/add_vector.php
<?hh // strict /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ class MyPhonyVector<T> { private Vector<T> $x; public function __construct() { $this->x = Vector {}; } public function add(T $x): void { $this->x[] = $x; } public function get(int $x): T { return $this->x[0]; } } class X {} class A extends X {} class B extends X {} function test(MyPhonyVector<X> $v): void { $x = new MyPhonyVector(); $x->add(new B()); $x->add(new A()); test($x); }
PHP
hhvm/hphp/hack/test/tast/array_get_base_hole.php
<?hh function f<T>(mixed $m, nonnull $n, T $t): void { $m[0]; // Hole actual type should be `mixed` $n[0]; // Hole actual type should be `nonnull` $t[0]; // Hole actual type should be `T` }
PHP
hhvm/hphp/hack/test/tast/async_lambda.php
<?hh // strict async function genString(string $s): Awaitable<string> { return $s; } function test(): void { $f0 = async () ==> { $str = await genString('foo'); }; $f1 = async $x ==> { $str = await genString($x); }; }
PHP
hhvm/hphp/hack/test/tast/awaitall.php
<?hh // strict async function genInt(): Awaitable<int> { return 1; } async function genString(): Awaitable<string> { return "foo"; } async function f(): Awaitable<void> { concurrent { $a = await genInt(); await genString(); $c = await genString(); } }
PHP
hhvm/hphp/hack/test/tast/bool_index.php
<?hh function f<T>(mixed $m, T $t, nonnull $n): void { $m[true]; // The key type argument to expected type of $m's hole is `nothing` $m[$t]; // The key type argument to expected type of $m's hole is `T & arraykey` $m[$n]; // The key type argument to expected type of $m's hole is `arraykey` $m[$m]; // The key type argument to expected type of $m's hole is `arraykey` }
PHP
hhvm/hphp/hack/test/tast/cconst.hhi.php
//// cconst.hhi <?hh class Klass { const int X1 = 0; const int X2; const string Y; const FunctionCredential Z; const int BAD = 'hello'; }
PHP
hhvm/hphp/hack/test/tast/class_const.php
<?hh // Copyright 2004-present Facebook. All Rights Reserved. class C { const FOO = dict[ 'a' => 1, 'b' => 2, ]; }
PHP
hhvm/hphp/hack/test/tast/class_get.php
<?hh /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ class TestClass { private static ?int $x = null; public static function get(): int { if (self::$x) { return self::$x; } else { return 0; } } }
PHP
hhvm/hphp/hack/test/tast/concurrent_error.php
<?hh // strict async function gen_int(): Awaitable<int> { return 1; } async function test(): Awaitable<int> { concurrent { $v1 = await gen_int(); $v2 = gen_int(); } return $v1 + $v2; }
PHP
hhvm/hphp/hack/test/tast/construct_unknown_class.php
<?hh // strict function test(vec<string> $x): Unknown { return new Unknown(3, 's', vec[3], ...$x); }
PHP
hhvm/hphp/hack/test/tast/contravariant_solve.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. interface I<-T> {} class E<T> implements I<T> {} function f<T>(I<T> $_, I<T> $_): I<T> { throw new Exception(); } function g<T>(T $_): E<T> { throw new Exception(); } function test(): void { $_ = f(g(1), g(2)); }
PHP
hhvm/hphp/hack/test/tast/dict_attribute.php
<?hh // strict <<file: Fi(dict['a' => 1, 'b' => 2])>> class A { public function __construct(dict<string, int> $_) {} } class C extends A implements HH\ClassAttribute {} class E extends A implements HH\EnumAttribute {} class F extends A implements HH\FunctionAttribute {} class Met extends A implements HH\MethodAttribute {} class IProp extends A implements HH\InstancePropertyAttribute {} class SProp extends A implements HH\StaticPropertyAttribute {} class P extends A implements HH\ParameterAttribute {} class TAlias extends A implements HH\TypeAliasAttribute {} class Fi extends A implements HH\FileAttribute {} <<F(dict['a' => 1, 'b' => 2])>> function ff(<<P(dict['a' => 1, 'b' => 2])>>int $i): void {} <<C(dict['a' => 1, 'b' => 2])>> class CC { <<IProp(dict['a' => 1, 'b' => 2])>> private int $mem = 4; <<SProp(dict['a' => 1, 'b' => 2])>> private static int $smem = 42; <<Met(dict['a' => 1, 'b' => 2])>> private function met(): void {} } <<E(dict['a' => 1, 'b' => 2])>> enum EE: int {} <<TAlias(dict['a' => 1, 'b' => 2])>> type tt = int;
hhvm/hphp/hack/test/tast/dune
(rule (alias tast) (deps %{exe:../../src/hh_single_type_check.exe} %{project_root}/hack/test/verify.py %{project_root}/hack/test/review.sh (glob_files %{project_root}/hack/test/hhi/XHPTest.hhi) (glob_files %{project_root}/hack/test/tast/HH_FLAGS) (glob_files %{project_root}/hack/test/tast/*.php) (glob_files %{project_root}/hack/test/tast/*.exp) (glob_files %{project_root}/hack/test/tast/class_level_where_clauses/HH_FLAGS) (glob_files %{project_root}/hack/test/tast/class_level_where_clauses/*.php) (glob_files %{project_root}/hack/test/tast/class_level_where_clauses/*.exp) (glob_files %{project_root}/hack/test/tast/control_flow/HH_FLAGS) (glob_files %{project_root}/hack/test/tast/control_flow/*.php) (glob_files %{project_root}/hack/test/tast/control_flow/*.exp) (glob_files %{project_root}/hack/test/tast/re_prefixed_string/HH_FLAGS) (glob_files %{project_root}/hack/test/tast/re_prefixed_string/*.php) (glob_files %{project_root}/hack/test/tast/re_prefixed_string/*.exp) (glob_files %{project_root}/hack/test/tast/xhp_modifier/HH_FLAGS) (glob_files %{project_root}/hack/test/tast/xhp_modifier/*.php) (glob_files %{project_root}/hack/test/tast/xhp_modifier/*.exp)) (action (run %{project_root}/hack/test/verify.py %{project_root}/hack/test/tast --program %{exe:../../src/hh_single_type_check.exe} --flags --everything-sdt))) (rule (alias tast_ordered_solving) (deps %{exe:../../src/hh_single_type_check.exe} %{project_root}/hack/test/verify.py %{project_root}/hack/test/review.sh (glob_files %{project_root}/hack/test/hhi/XHPTest.hhi) (glob_files %{project_root}/hack/test/tast/HH_FLAGS) (glob_files %{project_root}/hack/test/tast/*.php) (glob_files %{project_root}/hack/test/tast/*.exp) (glob_files %{project_root}/hack/test/tast/class_level_where_clauses/HH_FLAGS) (glob_files %{project_root}/hack/test/tast/class_level_where_clauses/*.php) (glob_files %{project_root}/hack/test/tast/class_level_where_clauses/*.exp) (glob_files %{project_root}/hack/test/tast/control_flow/HH_FLAGS) (glob_files %{project_root}/hack/test/tast/control_flow/*.php) (glob_files %{project_root}/hack/test/tast/control_flow/*.exp) (glob_files %{project_root}/hack/test/tast/re_prefixed_string/HH_FLAGS) (glob_files %{project_root}/hack/test/tast/re_prefixed_string/*.php) (glob_files %{project_root}/hack/test/tast/re_prefixed_string/*.exp) (glob_files %{project_root}/hack/test/tast/xhp_modifier/HH_FLAGS) (glob_files %{project_root}/hack/test/tast/xhp_modifier/*.php) (glob_files %{project_root}/hack/test/tast/xhp_modifier/*.exp)) (action (run %{project_root}/hack/test/verify.py %{project_root}/hack/test/tast --program %{exe:../../src/hh_single_type_check.exe} --flags --ordered-solving --everything-sdt))) (alias (name runtest) (deps (alias tast)))
PHP
hhvm/hphp/hack/test/tast/dynamic_member_access.php
<?hh function returnsTheStringFoo(): string { return 'foo'; } function test(dynamic $c): void { $foo = 'foo'; $c->foo; $c->$foo; $c->{returnsTheStringFoo()}; }
PHP
hhvm/hphp/hack/test/tast/eq_op.php
<?hh // strict function f(int $x): int { $x -= 4; $x += 4; $x *= 4; $arr = varray[1, 2, 3, 4]; $i = 2; $arr[$i - 1] += 4; return $x; }
PHP
hhvm/hphp/hack/test/tast/expected_traversable.php
<?hh function traversable(): Traversable<mixed> { return keyset[]; } function keyed_traversable(): KeyedTraversable<mixed, mixed> { return dict[]; }
PHP
hhvm/hphp/hack/test/tast/expected_traversable2.php
<?hh function traversable(): Traversable<num> { return keyset[]; // The inferred key type should be int } class C {} function keyed_traversable(): KeyedTraversable<C, mixed> { return dict[]; // The inferred key type should be nothing }
PHP
hhvm/hphp/hack/test/tast/fake_member.php
<?hh class C { private ?int $foo = null; public function get(): void { if ($this->foo) { $this->foo; } } }
PHP
hhvm/hphp/hack/test/tast/file_attributes_from_multiple_namespaces.php
<?hh // strict namespace A; <<file: AttrA>> class AttrA implements \HH\FileAttribute { } namespace B; <<file: AttrB>> class AttrB implements \HH\FileAttribute { }
PHP
hhvm/hphp/hack/test/tast/file_attributes_in_namespaces.php
<?hh // strict namespace MyNamespace; <<file: MyFileAttribute>> class MyFileAttribute implements \HH\FileAttribute { } class MyClass { }
PHP
hhvm/hphp/hack/test/tast/file_attributes_in_namespaces_with_namespaced_values.php
<?hh // strict namespace A { class MyStringFileAttribute implements \HH\FileAttribute { public function __construct(public string $attr_value) { } } class MyClass { const string MY_CLASS_CONST = 'my class const value' } <<file: MyStringFileAttribute(MyClass::MY_CLASS_CONST)>> } namespace B { class MyOtherClass { } }
PHP
hhvm/hphp/hack/test/tast/finally.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. async function gen_empty_shape(): Awaitable<shape()> { return shape(); } async function test(): Awaitable<void> { try { throw new Exception(); } catch (Exception $_) { } finally { $s = await gen_empty_shape(); Shapes::idx($s, 'foo'); } }
PHP
hhvm/hphp/hack/test/tast/fun_meth_variadic.php
<?hh function takes_string(string $s): void {} function f(string ...$args): void { foreach ($args as $arg) { takes_string($arg); } } class C1 { public function meth(...$args): void {} }
PHP
hhvm/hphp/hack/test/tast/gconst.hhi.php
//// gconst.hhi <?hh const int X1 = 0; const int X2; const string Y; const FunctionCredential Z; const int BAD = 'hello';
PHP
hhvm/hphp/hack/test/tast/initializer.php
<?hh // Copyright 2004-present Facebook. All Rights Reserved. class A {} class B {} abstract final class C { private static $d = darray[ 'a' => A::class, 'b' => B::class, ]; private static $s = Set {'foo'}; }
PHP
hhvm/hphp/hack/test/tast/lambda1.php
<?hh // strict function test_lambda1(): void { $s = 'foo'; $f = $n ==> { return $n . $s . '\n'; }; $x = $f(4); $y = $f('bar'); }
PHP
hhvm/hphp/hack/test/tast/lambda_contextual.php
<?hh // strict function takes_fun((function (int): num) $f): void {} function test(): void { takes_fun($x ==> $x); }
PHP
hhvm/hphp/hack/test/tast/lambda_efun.php
<?hh // strict /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ function foo(): void { $y = 2; $x = $z ==> $y + $z; // $y is captured $l = $x(2); $x = function($z) use ($y) { return $y + $z; // $y is captured } $l = $x(2); $x = ($a, $b) ==> $a + $b; // no captures $l = $x(2, $y) }
PHP
hhvm/hphp/hack/test/tast/lambda_return_type.php
<?hh function f(): void { // The lambda should have a string return type (string $s) ==> $s; } async function g(): Awaitable<void> { // Async should have an Awaitable<int> type await async { return 42; }; }
PHP
hhvm/hphp/hack/test/tast/mixed_mixed.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. function expect_mixed(mixed $_): void {} function test(int $a, string $b): void { expect_mixed( dict[ 'a' => $a, 'b' => $b, ], ); }
PHP
hhvm/hphp/hack/test/tast/module_references.php
<?hh <<file:__EnableUnstableFeatures('modules')>> <<file:__EnableUnstableFeatures('module_references')>> new module a.b { } new module a.c { } new module z.c { } new module z { imports { a.*, self.c, global, } exports { a.* } }
PHP
hhvm/hphp/hack/test/tast/multiple_type.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. class C1 { public function foo(): int { return 5; } } class C2 { public function foo(): string { return 's'; } } function test(C1 $c1, C2 $c2, bool $cond): arraykey { $x = $cond ? $c1 : $c2; return $x->foo(); }
PHP
hhvm/hphp/hack/test/tast/null_check.php
<?hh // strict function f(?int $x): int { if ($x === null) return 1; if (null === $x) return 2; return 0; }
PHP
hhvm/hphp/hack/test/tast/parent_construct.php
<?hh // strict class B { public function __construct(num $x) {} } class A extends B { public function __construct(int $x) { parent::__construct($x); } }
PHP
hhvm/hphp/hack/test/tast/parent_method.php
<?hh // strict class C { public function f(int $i): void {} } class D extends C { public function g(): void { parent::f(3); } }
PHP
hhvm/hphp/hack/test/tast/pseudofunctions.php
<?hh class C { public static function staticFoo(): void {} public function instanceFoo(): void {} } function test(C $c): void { echo('foo'); print('foo'); test<>; C::staticFoo<>; meth_caller(C::class, 'instanceFoo'); isset($c); unset($c); invariant(true, 'foo'); invariant_violation('foo'); }
PHP
hhvm/hphp/hack/test/tast/reactive.php
<?hh // strict <<__Rx>> function foo() : Pure<(function (int) : void)> { throw new Exception(); }
PHP
hhvm/hphp/hack/test/tast/reified_generic_attributes.php
<?hh class A implements HH\TypeParameterAttribute {} class B implements HH\TypeParameterAttribute {} function f<<<__Newable,__Enforceable,A>> reify T, >() {} function g<T, <<Enforceable,__Newable>> reify Tu>() {} function h<<<B>>T>() {} function j<<<__Soft>> reify Tv>() {} function ff<<<A(1)>> T>() {}
PHP
hhvm/hphp/hack/test/tast/reified_generic_shadowing.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. class Tcat {} function f<Tcat>(): void { new Tcat(); // "Tcat" } function g(): void { new Tcat(); // "\Tcat" }
PHP
hhvm/hphp/hack/test/tast/reified_generic_shadowing2.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. class Tc<Tc> { // Tc here comes from the type parameter public function f(Tc<int> $x): void {} } class Tc_other { // Tc here comes from the class public function f(Tc<int> $x): void {} }
PHP
hhvm/hphp/hack/test/tast/reified_generic_shadowing3.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. function f<T>(): void { new T(); // T new U(); // \U }
PHP
hhvm/hphp/hack/test/tast/reify_mix_with_erased.php
<?hh // strict function f<reify T, Tu>(Tu $f): Tu { return $f; } function g(): void { f<int, string>(42); }
PHP
hhvm/hphp/hack/test/tast/scope_resolution.php
<?hh // keep in sync with hphp/hack/test/nast/scope_resolution.php function bar(): string { return 'class'; } final class Foo { const string bar = 'baz'; const vec<nothing> class = vec[]; public static (function(): int) $_ = self::class<>; public static function bar(): float { return 3.14159; } public static function class(): int { return 42; } } // keep in sync with hphp/hack/test/nast/scope_resolution.php function class_const(dynamic $x): void { Foo::bar; $x::bar; Foo::bar(); $x::bar(); (Foo::bar); (($x::bar)); (((Foo::bar)))(); (((($x::bar))))(); Foo::bar\baz; (Foo::bar\baz); Foo::bar\baz(); (Foo::bar\baz)(); Foo::{bar}; (Foo::{bar}); Foo::{bar}(); (Foo::{bar})(); Foo::{(bar)}; (Foo::{((bar))}); Foo::{(((bar)))}(); (Foo::{((((bar))))})(); Foo::{bar\baz}; (Foo::{bar\baz}); Foo::{bar\baz}(); (Foo::{bar\baz})(); Foo::class; (Foo::class); Foo::class(); (Foo::class)(); Foo::{''}; (Foo::{''}); Foo::{''}(); (Foo::{''})(); Foo::{"bar"}; (Foo::{'bar'}); Foo::{'bar'}(); (Foo::{"bar"})(); Foo::{"bar\\baz"}; (Foo::{'bar\\baz'}); Foo::{'bar\\baz'}(); (Foo::{"bar\\baz"})(); Foo::{'class'}; (Foo::{"class"}); Foo::{"class"}(); (Foo::{'class'})(); Foo::{'$x'}; (Foo::{'$x'}); Foo::{'$x'}(); (Foo::{'$x'})(); Foo::{"\$x"}; (Foo::{"\$x"}); Foo::{"\$x"}(); (Foo::{"\$x"})(); Foo::{'$_'}; (Foo::{'$_'}); Foo::{'$_'}(); (Foo::{'$_'})(); Foo::{"\$_"}; (Foo::{"\$_"}); Foo::{"\$_"}(); (Foo::{"\$_"})(); Foo::{<<<EOD such amaze$ $ EOD }; (Foo::{<<<'EOD' very $wow EOD })(); } // keep in sync with hphp/hack/test/nast/scope_resolution.php function class_get(dynamic $x): void { Foo::$x; $x::$x; Foo::$x(); $x::$x(); (Foo::$x); (($x::$x)); (((Foo::$x)))(); (((($x::$x))))(); Foo::$_; (Foo::$_); Foo::$_(); (Foo::$_)(); Foo::{$x}; (Foo::{$x}); Foo::{$x}(); (Foo::{$x})(); Foo::{$_}; (Foo::{$_}); Foo::{$_}(); (Foo::{$_})(); Foo::{bar()}(); Foo::{vsprintf('%s', 'wow')}(); Foo::{(string)(123 + 456)}(); Foo::{'ba'."r"}(); Foo::{"bar\\".'baz'}(); Foo::{"$x"}(); Foo::{"$_"}(); Foo::{"ba$x"}(); Foo::{"ba$_"}(); Foo::{$x()}(); Foo::{$_()}(); Foo::{<<<EOD $much doge EOD }(); }
PHP
hhvm/hphp/hack/test/tast/set_dynamic_expected.php
<?hh function s(): dynamic { return Set {}; } function k(): dynamic { return keyset[]; } function is(): dynamic { return ImmSet {}; } function v(): dynamic { return vec[]; } function d(): dynamic { return dict[]; } function vc(): dynamic { return Vector {}; }
PHP
hhvm/hphp/hack/test/tast/set_mixed_expected.php
<?hh function s(): mixed { return Set {}; } function k(): mixed { return keyset[]; } function is(): mixed { return ImmSet {}; } function v(): mixed { return vec[]; } function d(): mixed { return dict[]; } function vc(): mixed { return Vector {}; }
PHP
hhvm/hphp/hack/test/tast/shapes_special_functions.php
<?hh // strict type Point = shape('x' => int, ?'y' => int); function test(Point $p): void { Shapes::idx($p, 'x'); Shapes::idx($p, 'x', 3); Shapes::keyExists($p, 'y'); Shapes::removeKey(inout $p, 'y'); Shapes::toArray($p); }
PHP
hhvm/hphp/hack/test/tast/singleton_unresolved_function_call.php
<?hh // strict function test(bool $b, (function (int): int) $f): int { if ($b) {} return $f(1); }
PHP
hhvm/hphp/hack/test/tast/switch_fallthrough.php
<?hh // strict function test(): void { // $x is an int $x = 0; hh_show($x); switch ($x) { case 0: // This is a noop fallthrough so we should not do an intersect case 1: // $x should be int, that isn't wrapped in an unresolved hh_show($x); // $x is a string $x = ''; hh_show($x); // FALLTHROUGH case 3: // $x should be string & int hh_show($x); $x = true; // $x should be string & int & bool hh_show($x); // FALLTHROUGH case 4: // $x should be int & string hh_show($x); break; case 4: // $x should be int hh_show($x); // $x should be float $x = 1.0; hh_show($x); break; } // $x should be int & string & float & bool hh_show($x); }
PHP
hhvm/hphp/hack/test/tast/try_catch.php
<?hh /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ function might_throw(): void {} function terminal_catch_can_do_whatever(): int { $a = 23; try { $a = 456; might_throw(); } catch (YourException $e) { return $a; } catch (MyException $e) { // It is ok to make this a string, since this clause is terminal $a = 'duck'; return 23904; } catch (Exception $e) { return $a; } finally { $a = 4; } return $a; } class YourException extends Exception {} class MyException extends Exception {}
PHP
hhvm/hphp/hack/test/tast/typeconsts.php
<?hh abstract class C { abstract const type Ta; abstract const type Tac as num; abstract const type Tad = int; abstract const type Tacd as num = int; const type Tpa as num = int; const type Tc = int; }
PHP
hhvm/hphp/hack/test/tast/typedef.php
<?hh // strict class Foo implements HH\TypeAliasAttribute { public function __construct(int... $x) {} } class Bar implements HH\TypeAliasAttribute {} class SingleAttribute implements HH\TypeAliasAttribute {} <<Foo(1,2,3), Bar>> type T1 = int; <<SingleAttribute>> type T2 = ?string; type Serialized_contra<-T> = string; type Serialized_co<+T> = string;
PHP
hhvm/hphp/hack/test/tast/unresolved_grown_after_lambda.php
<?hh // strict function test(int $i, string $s): int { $items = Vector { $i }; $f = (): int ==> { // When this function is typechecked, we have // $item : Tunion [int] // But in the TAST, we should have // $item : Tunion [int; string] $item = $items[1]; return $item; }; $items[] = $s; return $f(); }
PHP
hhvm/hphp/hack/test/tast/using.php
<?hh // strict class Handle implements IDisposable { public function __dispose(): void {} } function test(): void { using ($x = new Handle(), $y = new Handle()) { using ($z = new Handle()) {} } }
PHP
hhvm/hphp/hack/test/tast/wildcard_generic_depth.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. class A<Ta, reify Tb> {} function f(): void { 3 as A<_, A<_, _>>; }
PHP
hhvm/hphp/hack/test/tast/xhp.php
<?hh // strict class :foo extends XHPTest implements XHPChild { attribute enum {'herp', 'derp'} bar; } function main(): void { // Attribute list tests. <foo bar="herp" />; $derp = 'derp'; <foo bar={$derp} />; // Element list tests. <foo bar="herp"> <foo bar="derp"> <foo bar="herp" /> </foo> </foo>; }
PHP
hhvm/hphp/hack/test/tast/xml_child_order.php
<?hh class :hello extends XHPTest {} class :selam extends XHPTest implements XHPChild {} class :salut extends XHPTest implements XHPChild {} function f(): void { <hello> <selam /> <salut /> </hello>; }
PHP
hhvm/hphp/hack/test/tast/class_level_where_clauses/test_class_level_where_clauses.php
<?hh /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ class SingleConstr <T> where T = int {} class ListConstrs <T> where T = int T = string {} class MultiConstrs <T, Tu> where T = int, Tu = string Tu = int {} class AsConstr <T> where T as int {} class SuperConstr <T> where T super int {}
PHP
hhvm/hphp/hack/test/tast/control_flow/do.php
<?hh //strict function f(bool $b, int $a): void { do { $a; // int | string $a = ""; } while ($b); $a; // string }
PHP
hhvm/hphp/hack/test/tast/control_flow/dos.php
<?hh //strict /* test that there are no interference between the Do continuations of multiple * do loops */ function f(bool $b, int $a): void { do { $a; // int | string $a = ""; } while ($b); $a; // string do { $a; // string $a = ""; } while ($b); do { $a; // string $a = 0; do { $a; // int $a = 1; } while ($b); $a = ""; } while ($b); }
PHP
hhvm/hphp/hack/test/tast/control_flow/do_throw_while.php
<?hh // strict function throwFromDoWhileLoop(bool $cond): void { do { throw new Exception("DoWhileBody"); } while ($cond); }
PHP
hhvm/hphp/hack/test/tast/control_flow/loop_cond.php
<?hh // strict class A {} function get_A_opt(): ?A { return new A(); } function fwhile(): void { $x = new A(); while ($x) { $x = get_A_opt(); } } function ffor(): void { for ($x = new A(); $x; $x = get_A_opt()) { } }
PHP
hhvm/hphp/hack/test/tast/control_flow/while.php
<?hh //strict function f(bool $b, int $a): void { while ($b) { $a; // int | string $a = ""; } $a; // int | string }
PHP
hhvm/hphp/hack/test/tast/control_flow/while_throw.php
<?hh // strict function throwFromDoWhileLoop(bool $cond): void { while ($cond) { throw new Exception("DoWhileBody"); } }
PHP
hhvm/hphp/hack/test/tast/re_prefixed_string/re_prefixed_string.php
<?hh // strict function f(): void { $x = re"/Hello/"; // $x is an HH\Lib\Regex\Pattern $y = goodbye($x); // Can access the shape $y with an integer key // Since HH\Lib\Regex\Match es are always shapes with string values, // $y_0 will be a string $y_0 = $y[0]; // `re`-prefixed strings can still be concatenated like strings $z = $x.", world!"; } function goodbye<T as HH\Lib\Regex\Match>(HH\Lib\Regex\Pattern<T> $pattern): T { throw new Exception(); } /* Bad regex patterns that can't be compiled by PCRE give type errors */ /* Test that good ones get turned into the right shape keys */ function bad_pattern(): void { $good0 = re"/Hel(\D)(?'o'\D)/"; $bad1 = re"/He(?'l'\D)(?'l'\D)o/"; $bad2 = re"/He(?'42'\D)lo/"; $bad3 = re"/\c/"; $good4 = re"/He(?'one'\D)(\D)(?'three'\D)(\D)(\D)(?'six'\D)/"; $good5 = re"/a(b)(?<c>c)(d)(?<e>e)/"; $good6 = re"/Hello/"; $good7 = re"/a(?<b>b)(?<c>c)(?<d>d)(?<e>e)/"; $good8 = re"/a(b)(c)(d)?e/"; $good9 = re"/WoS Action: .*Disable.+\[(\w+)/s"; $good10 = re"/User disabled for having at least \d+ spam reports/"; $good11 = re"/(?<!\w)youtube.com$/"; $good12 = re"/.+(?P<version>(:s(\d)+)*:c(\d)+)$/U"; $good13 = re"/^t=((?<m>\d+)m)?(?<s>\d+)s?$/i"; $good14 = re"/(?<=\(currently )[^)](?=\))/"; $good15 = re"/(?<=\(currently )[^)]+(?=\))/"; $good16 = re"/(a)(b)(c)(?<d>d)(e)(f)(g)(?<h>h)(i)(j)(k)(l)(m)(?<n>n)/"; } /* Regex patterns must be delimited by non-alphanumeric, non-whitespace, non-backslash matching characters. */ function missing_delimiter(): void { $bad0 = re"Hello"; $good1 = re"/Hello/"; $bad2 = re"/Hello"; $good3 = re"#Hello#"; $bad4 = re"#Hello/"; $bad5 = re"#Hello"; $good6 = re"(Hello)"; $good7 = re")Hello)"; $bad8 = re"(Hello("; $good9 = re"[Hello]"; $bad10 = re"\\Hello\\"; $bad11 = re"HelloH"; } function parentheses_are_weird(): void { // $good0 is good in the typechecker but useless capture groups-wise and // confuses the parser for some reason $good0 = re"(He\(?'one'\D\)\(\D\)\(?'three'\D\)\(\D\)\(\D\)\(?'six'\D\))"; }
PHP
hhvm/hphp/hack/test/tast/sdt/methods.php
<?hh class C { public function m1(vec<int> $v, string $s): vec<int> { return $v; } public function m2(vec<int> $v, string $s): string { return $s; } }
PHP
hhvm/hphp/hack/test/tast/sdt/sdt.php
<?hh class C {} interface I {} trait T {} function f(): void {} // enums do not get SDT enum E: int {}
PHP
hhvm/hphp/hack/test/tast/under_dynamic/methods.php
<?hh class C { public function m1(vec<int> $v, string $s): vec<int> { return $v; } public function m2(vec<int> $v, string $s): string { return $s; } }
hhvm/hphp/hack/test/tools/lsp/.hhconfig
# default hh configuration for talking to LSP assume_php = false unsafe_xhp = false user_attributes = DataProvider ExpectedException ExpectedExceptionCode ExpectedExceptionMessage TestsBypassVisibility FBMock_DoNotMock UIComponentID Task FBTEnum ApiEnum HiddenNames XMLImpl XMLName XMLElement XMLTransient XMLTypeahead XMLKey XMLChildren XMLUseLenientParsing XMLJSModule TestPlatformVersions MinPlatformVersion MaxPlatformVersion Relative Iters MinMsec WarmUp DynamicallyCalledFrom AsyncPHPSerialization AsyncJobType AsyncFastFail Serialize SerializeAs GraphQLDeprecatedEnumValues GraphQLEnumValueDescriptions JsonField GraphQLObject GraphQLField GraphQLInterface Owner SelfDescriptive auto_namespace_map = {"Dict": "HH\\Lib\\Dict", "Vec": "HH\\Lib\\Vec", "Keyset": "HH\\Lib\\Keyset", "C": "HH\\Lib\\C", "Str": "HH\\Lib\\Str"} enable_experimental_tc_features = instanceof
Text
hhvm/hphp/hack/test/tools/lsp/definition.txt
[ { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "initializationOptions":{}, "processId":null, "rootPath":">>> path_expand('.')", "capabilities":{} } }, { "jsonrpc": "2.0", "method": "textDocument/didOpen", "params": { "textDocument": { "uri":">>> file_uri('sample.php')", "languageId": "hack", "version":1, "text":">>> read_file('sample.php')" } } }, { "jsonrpc": "2.0", "method": "textDocument/definition", "id": 2, "params": { "textDocument": { "uri":">>> file_uri('sample.php')" }, "position": {"line": 3, "character": 10} } }, { "jsonrpc": "2.0", "id": 3, "method": "shutdown", "params": {} } ]
Text
hhvm/hphp/hack/test/tools/lsp/didchange.txt
[ { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "initializationOptions":{}, "processId":null, "rootPath":">>> path_expand('.')", "capabilities":{} } }, { "jsonrpc": "2.0", "method": "textDocument/didOpen", "params": { "textDocument": { "uri":">>> file_uri('sample.php')", "languageId": "hack", "version":1, "text":">>> read_file('sample.php')" } } }, { "jsonrpc": "2.0", "method": "textDocument/didChange", "params": { "textDocument": { "uri":">>> file_uri('sample.php')" }, "contentChanges": [{ "range": { "start": {"line":2, "character":9}, "end": {"line":2, "character":12} }, "text":"***" }] } } ]
Text
hhvm/hphp/hack/test/tools/lsp/error.txt
[ { "jsonrpc": "2.0", "id": 1, "method": "textDocument/didOpen", "params": { "textDocument": { "uri":">>> file_uri('sample.php')", "languageId": "hack", "version":1, "text":">>> read_file('sample.php')" } } } ]
Text
hhvm/hphp/hack/test/tools/lsp/formatting.txt
[ { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "initializationOptions":{}, "processId":null, "rootPath":">>> path_expand('.')", "capabilities":{} } }, { "jsonrpc": "2.0", "method": "textDocument/didOpen", "params": { "textDocument": { "uri":">>> file_uri('messy.php')", "languageId": "hack", "version":1, "text":">>> read_file('messy.php')" } } }, { "jsonrpc": "2.0", "method": "textDocument/formatting", "id": 2, "params": { "textDocument": { "uri":">>> file_uri('messy.php')" }, "options": {"tabSize": 5, "insertSpaces": true} } }, { "jsonrpc": "2.0", "id": 3, "method": "shutdown", "params": {} } ]
Text
hhvm/hphp/hack/test/tools/lsp/highlight.txt
[ { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "initializationOptions":{}, "processId":null, "rootPath":">>> path_expand('.')", "capabilities":{} } }, { "jsonrpc": "2.0", "method": "textDocument/didOpen", "params": { "textDocument": { "uri":">>> file_uri('sample.php')", "languageId": "hack", "version":1, "text":">>> read_file('sample.php')" } } }, { "jsonrpc": "2.0", "method": "textDocument/documentHighlight", "id": 2, "params": { "textDocument": { "uri":">>> file_uri('sample.php')" }, "position": {"line": 3, "character": 10} } }, { "jsonrpc": "2.0", "id": 3, "method": "shutdown", "params": {} } ]
Text
hhvm/hphp/hack/test/tools/lsp/hover.txt
[ { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "initializationOptions":{}, "processId":null, "rootPath":">>> path_expand('.')", "capabilities":{} } }, { "jsonrpc": "2.0", "method": "textDocument/didOpen", "params": { "textDocument": { "uri":">>> file_uri('sample.php')", "languageId": "hack", "version":1, "text":">>> read_file('sample.php')" } } }, { "jsonrpc": "2.0", "method": "textDocument/hover", "id": 2, "params": { "textDocument": { "uri":">>> file_uri('sample.php')" }, "position": {"line": 3, "character": 10} } }, { "jsonrpc": "2.0", "id": 3, "method": "shutdown", "params": {} } ]
Text
hhvm/hphp/hack/test/tools/lsp/init.txt
[ { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "initializationOptions":{}, "processId":null, "rootPath":">>> path_expand('.')", "capabilities":{} } }, { "jsonrpc": "2.0", "id": 2, "method": "shutdown", "params": {} } ]
Python
hhvm/hphp/hack/test/tools/lsp/jsonrpc_stream.py
#!/usr/bin/env python3 import json from queue import Empty, Queue from threading import Thread class JsonRpcStreamReader: def __init__(self, stream): self.stream = stream self.queue = Queue() # daemon ensures the reading thread will get cleaned up when # the main program exits. no need to explicitly manage it. self.read_thread = Thread(target=self._async_read_loop, daemon=True) self.read_thread.start() def read(self): return self._read(timeout_seconds=None) def try_read(self, timeout_seconds): return self._read(timeout_seconds) def _async_read_loop(self): while True: self.queue.put(json.loads(self._read_payload())) def _read(self, timeout_seconds): try: return self.queue.get(block=True, timeout=timeout_seconds) except Empty: return None def _read_content_length(self): # read the 'Content-Length:' line and absorb the newline # after it length_line = self.stream.readline().decode() self.stream.read(len("\r\n")) # get the content length as an integer for the # rest of the package parts = length_line.split(":", 1) return int(parts[1].strip()) def _read_content(self, length): return self.stream.read(length) def _read_payload(self): length = self._read_content_length() return self._read_content(length) class JsonRpcStreamWriter: def __init__(self, stream): self.stream = stream def write(self, json_data): serialized = json.dumps(json_data) content_length = len(serialized) payload = f"Content-Length: {content_length}\n\n{serialized}" self._write_string(payload) def _write_string(self, s): self.stream.write(s.encode()) self.stream.flush()
Python
hhvm/hphp/hack/test/tools/lsp/lspcommand.py
#!/usr/bin/env python3 import contextlib import json import os import re import subprocess import urllib.parse import uuid from jsonrpc_stream import JsonRpcStreamReader, JsonRpcStreamWriter class LspCommandProcessor: def __init__(self, proc, reader, writer): self.proc = proc self.reader = reader self.writer = writer @classmethod @contextlib.contextmanager def create(cls): # yes shell = True is generally a bad idea, but # in this case we want to pick up your environment entirely because # hack depends heavily on it to work proc = subprocess.Popen( "hh_client lsp", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) reader = JsonRpcStreamReader(proc.stdout) writer = JsonRpcStreamWriter(proc.stdin) yield cls(proc, reader, writer) proc.stdin.close() proc.stdout.close() proc.stderr.close() @staticmethod def parse_commands(raw_data): raw_json = json.loads(raw_data) return [LspCommandProcessor._eval_json(command) for command in raw_json] # request_timeout is the number of seconds to wait for responses # that we expect the server to send back. this timeout can # be longer because it typically won't be hit. # # notify_timeout is the number of seconds to wait for responses # from the server that aren't caused by a request. these could # be errors or server notifications. def communicate( self, json_commands, request_timeout=30, notify_timeout=1, verbose=False ): transcript = self._send_commands({}, json_commands, verbose) # we are expecting at least one response per request sent so # we read these giving the server more time to respond with them. transcript = self._read_request_responses( transcript, json_commands, request_timeout, verbose ) # because it's possible the server sent us notifications # along with responses we need to try to keep reading # from the stream to get anything that might be left. return self._read_extra_responses(transcript, notify_timeout, verbose) def _send_commands(self, transcript, commands, verbose): for command in commands: LspCommandProcessor._log(verbose, f"Sending: {command}") self.writer.write(command) LspCommandProcessor._log(verbose, "Send OK.") transcript = self._scribe(transcript, sent=command, received=None) return transcript def _read_request_responses(self, transcript, commands, timeout_seconds, verbose): for _ in self._requests_in(commands): response = self._try_read_logged(timeout_seconds, verbose) transcript = self._scribe(transcript, sent=None, received=response) return transcript def _read_extra_responses(self, transcript, timeout_seconds, verbose): while True: response = self._try_read_logged(timeout_seconds, verbose) if not response: break transcript = self._scribe(transcript, sent=None, received=response) return transcript def _scribe(self, transcript, sent, received): transcript = dict(transcript) id = self._transcript_id(sent, received) if sent and not received: received = transcript[id]["received"] if id in transcript else None if received and not sent: sent = transcript[id]["sent"] if id in transcript else None transcript[id] = {"sent": sent, "received": received} return transcript def _transcript_id(self, sent, received): assert sent is not None or received is not None def make_id(json, idgen): if LspCommandProcessor._has_id(json): return LspCommandProcessor._request_id(json) else: return idgen() if sent: return make_id(sent, LspCommandProcessor._client_notify_id) else: return make_id(received, LspCommandProcessor._server_notify_id) def _requests_in(self, commands): return [c for c in commands if LspCommandProcessor._has_id(c)] def _try_read_logged(self, timeout_seconds, verbose): LspCommandProcessor._log(verbose, f"Reading, timeout={timeout_seconds}") response = self.reader.try_read(timeout_seconds) LspCommandProcessor._log(verbose, f"Response: {response}") return response @staticmethod def _log(verbose, message): if verbose: print(message) @staticmethod def _has_id(json): return "id" in json @staticmethod def _client_notify_id(): return LspCommandProcessor._notify_id("NOTIFY_CLIENT_TO_SERVER_") @staticmethod def _server_notify_id(): return LspCommandProcessor._notify_id("NOTIFY_SERVER_TO_CLIENT_") @staticmethod def _notify_id(prefix): return prefix + str(uuid.uuid4()) @staticmethod def _request_id(json_command): return "REQUEST_" + str(json_command["id"]) @staticmethod def _eval_json(json): if isinstance(json, dict): return {k: LspCommandProcessor._eval_json(v) for k, v in json.items()} elif isinstance(json, list): return [LspCommandProcessor._eval_json(i) for i in json] elif isinstance(json, str): match = re.match(r">>>(.*)", json) if match is None: return json return eval(match.group(1)) # noqa: P204 else: return json # string replacement methods meant to be called # within a command processing script. def path_expand(path): return os.path.abspath(path) def file_uri(path): return urllib.parse.urljoin("file://", path_expand(path)) def read_file(file): with open(file, "r") as f: return f.read()
PHP
hhvm/hphp/hack/test/tools/lsp/messy.php
<?hh //strict function x(): string { $a = "this"; $b = "is"; $c = "messy"; $d = "."; return "$a" . "$b" . "$c" . "d"; }
PHP
hhvm/hphp/hack/test/tools/lsp/sample.php
<?hh //strict function afunction(): int { return bfunction(); } function bfunction(): int { return 42; }
Python
hhvm/hphp/hack/test/tools/lsp/talk.py
#!/usr/bin/env python3 """ Takes LSP commands and communicates them with the LSP server. This script is useful for testing the LSP server: you can feed in a payload and confirm that the responses are correct. The LSP spec can be found here: https://github.com/Microsoft/language-server-protocol/blob/master/protocol.md The input files must contain an array of json-rpc commands to send to the language server. Commands that you expect a response from the server should include an "id" field. The field should be a unique integer per command. The server will send responses with the "id" passed in, and this tool will use them to line up sent/response pairs. Commands that are notificatins where you don't expect a server response should not contain an "id" field. See textDocument/didOpen for an example of this. Inside a command body, you can run a python function on the argument to cause the string output of that function to be replaced at run-time. For example, for a URI, you can use >>> file_uri('sample.php') which would generate something like file:///home/chrishahn/test/sample.php you can also use >>> read_file('sample.php') read_file() will read the contents of 'sample.php' and insert them. This is useful in conjunction with the textDocument/didOpen command. Suggested command-line usage: python talk.py filename.txt """ import argparse import fileinput import json from lspcommand import LspCommandProcessor def main(): parser = argparse.ArgumentParser() parser.add_argument( "--request_timeout", type=int, action="store", default=30, help="duration to wait for request responses, in seconds.", ) parser.add_argument( "--notify_timeout", type=int, action="store", default=1, help="duration to wait for notify responses, in seconds.", ) parser.add_argument( "--verbose", action="store_true", default=False, help="display diagnostic information while reading/writing.", ) parser.add_argument( "--silent", action="store_true", default=False, help="suppresses printing of transcript, but not diagnostics.", ) parser.add_argument( "files", metavar="FILE", nargs="*", default=["-"], help="list of files to read, if empty, stdin is used.", ) args = parser.parse_args() commands = LspCommandProcessor.parse_commands(read_commands(args.files)) with LspCommandProcessor.create() as lsp_proc: transcript = lsp_proc.communicate( commands, request_timeout=args.request_timeout, notify_timeout=args.notify_timeout, verbose=args.verbose, ) if not args.silent: print_transcript(lsp_proc, transcript) def print_transcript(lsp_proc, transcript): for id, package in transcript.items(): if package["sent"]: print(f"Sent [{id}]:\n") print(json.dumps(package["sent"], indent=2)) if package["received"]: print(f"\nReceived [{id}]:\n") print(json.dumps(package["received"], indent=2)) print("-" * 80) # this will read command data from stdin or # an arbitrary list of files def read_commands(files): command_lines = [] for line in fileinput.input(files=files): command_lines.append(line) return "".join(command_lines) if __name__ == "__main__": main()
PHP
hhvm/hphp/hack/test/typecheck/abstract_abstract1.php
<?hh // strict /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ abstract abstract class AbstractAbstractTest {}
PHP
hhvm/hphp/hack/test/typecheck/abstract_abstract2.php
<?hh // strict /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ abstract abstract final class AbstractAbstractTest {}
PHP
hhvm/hphp/hack/test/typecheck/abstract_abstract3.php
<?hh // strict /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ abstract final abstract class AbstractAbstractTest {}
PHP
hhvm/hphp/hack/test/typecheck/abstract_abstract4.php
<?hh // strict /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ final abstract abstract class AbstractAbstractTest {}
PHP
hhvm/hphp/hack/test/typecheck/abstract_defs.php
<?hh /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ trait FooTrait { abstract public function abstractFunc(): int; final public function doSomething(): int { return $this->abstractFunc(); } } abstract class Base { final public function abstractFunc(): int { return 4; } } class Child extends Base { use FooTrait; }
PHP
hhvm/hphp/hack/test/typecheck/abstract_final.php
<?hh /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ class Foo { final static abstract protected function bar(): void; }
PHP
hhvm/hphp/hack/test/typecheck/abstract_implement.php
<?hh // strict /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ // Allow delayed implementation for abstract classes interface IFace<T> { public function foo(): T; } abstract class AClass<T> implements IFace<T> {} class BClass extends AClass<int> { public function foo(): int { return $this->foo(); } }
PHP
hhvm/hphp/hack/test/typecheck/abstract_implement2.php
<?hh // strict /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ // Allow delayed implementation for abstract classes interface IFace<T> { public function foo(): T; } abstract class AClass<T> implements IFace<T> {} class BClass extends AClass<bool> { public function foo(): int { return $this->foo(); } }
PHP
hhvm/hphp/hack/test/typecheck/abstract_implement3.php
<?hh // strict /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ // Allow delayed implementation for abstract classes interface IFace<T> { public function foo(): T; } trait MyTrait implements IFace<int> { public function bar(): void { $this->foo(); } } abstract class AClass<T> { use MyTrait; } class BClass extends AClass<int> { public function foo(): int { return $this->foo(); } }
PHP
hhvm/hphp/hack/test/typecheck/abstract_implement4.php
<?hh // strict /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ // Allow delayed implementation for abstract classes interface IFace<T> { public function foo(): T; } trait MyTrait implements IFace<int> { public function bar(): void { $this->foo(); } } abstract class AClass<T> { use MyTrait; } class BClass extends AClass<int> {}
PHP
hhvm/hphp/hack/test/typecheck/abstract_implement5.php
<?hh // strict /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ // Allow delayed implementation for abstract classes interface IFace<T> { public function foo(IFace<T> $x): T; } trait MyTrait implements IFace<CClass> { public function bar(IFace<CClass> $x): void { $this->foo($x); } } abstract class AClass { use MyTrait; } class CClass extends AClass { public function foo(IFace<CClass> $x): CClass { return new CClass(); } }
PHP
hhvm/hphp/hack/test/typecheck/abstract_implement6.php
<?hh // strict /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ // Allow delayed implementation for abstract classes interface IFace { public function foo(): int; } // multiple layers abstract class AClass implements IFace {} abstract class BClass extends AClass {} abstract class CClass extends BClass {} class DClass extends CClass { /* should fail, foo is missing */ }
PHP
hhvm/hphp/hack/test/typecheck/abstract_implement7.php
<?hh // strict /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ // Allow delayed implementation for abstract classes interface IFace { public function foo(): int; } // multiple layers abstract class AClass implements IFace {} abstract class BClass extends AClass {} abstract class CClass extends BClass {} class DClass extends CClass { public function foo(): int { return 0; } }
PHP
hhvm/hphp/hack/test/typecheck/abstract_implement8.php
<?hh /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * * */ interface Alpha { public function getMyName(): string; } abstract class A implements Alpha { public function getMyName(): int { return 5; } }
PHP
hhvm/hphp/hack/test/typecheck/abstract_parent_override_interface.php
<?hh interface I { const FOO = "one"; } abstract class B { const FOO = "two"; } abstract class A extends B implements I {}