language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
PHP
hhvm/hphp/hack/test/ifc/check/foreach_dynamic.php
<?hh class A { <<__Policied("PRIVATE")>> public dynamic $dynamic = 42; <<__Policied("PUBLIC")>> public dynamic $public = 42; } <<__InferFlows>> function leak_implicitly(A $c): void { foreach ($c->dynamic as $k => $v) { $c->public = 0; // PRIVATE flows into PUBLIC } } <<__InferFlows>> function ok(A $c): void { foreach ($c->dynamic as $k => $v) { } $c->public = 0; } <<__SupportDynamicType>> class D { public bool $data = true; } <<__SupportDynamicType>> class C { <<__Policied("B")>> public bool $b = false; <<__Policied("D")>> public ~?D $d = null; } <<__InferFlows>> function f(C $c, dynamic $t): void { foreach($t as $d) { // we force $t to contain // objects that are subject to // the policy D $c->d = $d; } foreach($t as $d) { // Bad flow from B to D $d->data = $c->b; } }
PHP
hhvm/hphp/hack/test/ifc/check/foreach_traversable_iterable.php
<?hh class C { <<__Policied("PUBLIC")>> public int $public = 0; <<__Policied("PRIVATE")>> public int $private = 0; <<__Policied("PRIVATE")>> public vec<int> $privateVec = vec[]; <<__Policied("KEY")>> public int $key = 0; <<__Policied("VALUE")>> public int $value = 0; <<__InferFlows>> public function traverse(Traversable<int> $t): void { foreach ($t as $value) { $this->value = $value; } } <<__InferFlows>> public function traverse_no_assign(Traversable<int> $t): void { foreach ($t as $x) { $this->public = 0; } } <<__InferFlows>> public function vec(vec<int> $t): void { foreach ($t as $value) { $this->value = $value; } } <<__InferFlows>> public function keyedTraverse(KeyedTraversable<int,int> $t): void { foreach ($t as $key => $value) { $this->key = $key; $this->value = $value; } } <<__InferFlows>> public function dict(dict<int,int> $t): void { foreach ($t as $key => $value) { $this->key = $key; $this->value = $value; } } public function ok(): void { $this->traverse(vec[$this->value]); $this->vec(vec[$this->value]); $this->traverse(vec[$this->public]); $this->keyedTraverse(dict[$this->public => $this->public]); $this->dict(dict[$this->public => $this->public]); $this->traverse(vec[0]); $this->keyedTraverse(dict[0 => 0]); $this->dict(dict[0 => 0]); } <<__InferFlows>> public function leaks_due_to_key_value_conflation(): void { // KEY and VALUE are both governed by the lump policy of the Traversable in // keyedTraverse. Thus, unlike using foreach on a CoW array, we lose // specificity. $this->keyedTraverse(dict[$this->key => $this->value]); } <<__InferFlows>> public function leak_via_value1(): void { // PRIVATE leaks to VALUE $this->traverse(vec[$this->private]); } <<__InferFlows>> public function leak_via_value2(): void { // PRIVATE leaks to KEY // PRIVATE leaks to VALUE $this->keyedTraverse(dict[0 => $this->private]); } <<__InferFlows>> public function leak_via_key1(): void { // PRIVATE leaks to KEY // PRIVATE leaks to VALUE $this->keyedTraverse(dict[$this->private => 0]); } <<__InferFlows>> public function leak_via_key2(): void { $vec = vec[]; $vec[$this->private] = 42; // PRIVATE leaks to KEY // PRIVATE leaks to VALUE $this->keyedTraverse($vec); } <<__InferFlows>> public function leak_implicitly(): void { // PRIVATE leaks to PUBLIC due to implicit flow from length (governed by // self policy) $this->traverse_no_assign($this->privateVec); } }
PHP
hhvm/hphp/hack/test/ifc/check/for_as_while.php
<?hh // strict // This file is same as check/while.php except written in for loop syntax. // The results should be the same. class C { <<__Policied("PRIVATE")>> public string $pri = ""; <<__Policied("PRIVATE")>> public bool $prib = true; <<__Policied("PUBLIC")>> public string $pub = ""; <<__Policied("PUBLIC")>> public arraykey $out = 42; } <<__InferFlows>> function simple(bool $b, C $c): void { $x = 42; for (;$b;) { $x = $c->pri; $x = $c->pub; } // fine because $x can only be public $c->out = $x; } <<__InferFlows>> function breaks(bool $b, C $c): void { $x = 42; for (;$b;) { $x = $c->pri; if ($b) break; $x = $c->pub; } // this is an error, $x can be either // private or public depending on the break $c->out = $x; } <<__InferFlows>> function continues(bool $b, C $c): void { $x = 42; for (;$b;) { $x = $c->pri; if ($b) continue; $x = $c->pub; } // this is an error, for reasons similar to // the breaks() function above $c->out = $x; } <<__InferFlows>> function pcleak(C $c): void { $n = 0; for (;$c->prib;) { $n = 1; $c->prib = false; } // this is an error, some information about // the boolean $c->prib can be leaked $c->out = $n; } <<__InferFlows>> function niftyleak(bool $b, C $c): void { $x = 42; $y = 24; $z = 12; // look ma no fixpoint in ifc.ml! for (;$b;) { $c->out = $z; $z = $x; $x = $y; $y = $c->pri; } }
PHP
hhvm/hphp/hack/test/ifc/check/function_ptr.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class C { <<__Policied("A")>> public int $a = 0; <<__Policied("B")>> public int $b = 0; } <<__InferFlows>> function id(int $x): int { return $x; } <<__InferFlows>> function simple_ok(C $c): void { $f = id<>; $c->a = $f($c->a); // ok, A -> A } <<__InferFlows>> function simple_bad(C $c): void { $f = id<>; $c->b = $f($c->a); // bad, A -> B } <<__InferFlows>> function write_a(C $c, int $x): void { $c->a = $x; } <<__InferFlows>> function write_b(C $c, int $x): void { $c->a = $x; } <<__InferFlows>> function write_lit(C $c): void { $f = write_a<>; $f($c, 123); // ok } <<__InferFlows>> function write_leak(C $c): void { $f = write_a<>; $f($c, $c->b); // bad, B -> A } <<__InferFlows>> function leak_pc(C $c): void { $f = write_a<>; if ($c->b > 0) { $f($c, 123); // bad, B -> A via the PC } } <<__InferFlows>> function leak_data(C $c): void { if ($c->b > 0) { $f = write_a<>; } else { $f = write_b<>; } $f($c, 123); // bad, if A gets written, we know something about B } <<__InferFlows>> function throw_on_a(C $c, Exception $e): void { if ($c->a > 0) { throw $e; } } <<__InferFlows>> function throw_ok(C $c, Exception $e): void { $f = throw_on_a<>; $f($c, $e); $c->a = 1; // ok } <<__InferFlows>> function throw_bad(C $c, Exception $e): void { $f = throw_on_a<>; $f($c, $e); $c->b = 1; // bad, the PC now depends on A }
PHP
hhvm/hphp/hack/test/ifc/check/generics.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class C { <<__Policied("A")>> public int $a = 0; <<__Policied("B")>> public int $b = 0; } <<__InferFlows>> function id<T>(T $x): T { return $x; } <<__InferFlows>> function id_int(int $x): int { return id($x); // ok } <<__InferFlows>> function write_a_to_b(C $c): void { // not ok! $c->b = id($c->a); } <<__InferFlows>> function precision_ok(C $c, Exception $e): void { $f = ($a, $b) ==> { $c->a = $a; $c->b = $b; return $c->b; }; // ok $f($c->a, $c->b); } <<__InferFlows>> function precision_ko(C $c, Exception $e): void { $f = ($a, $b) ==> { $c->a = $a; $c->b = $b; return $c->b; }; // calling id on $f leads to imprecision $f2 = id($f); $f2($c->a, $c->b); } <<__InferFlows>> function apply<T1, T2>((function(T1): T2) $f, T1 $x): T2 { return $f($x); } <<__InferFlows>> function a_gets_b(C $c): void { $c->a = apply($x ==> $x, $c->b); } <<__InferFlows>> function assign_in_func_ok(C $c): void { $f = $x ==> { $c->a = $x; }; apply($f, $c->a); // ok } <<__InferFlows>> function assign_in_func_ko(C $c): void { $f = $x ==> { $c->a = $x; }; apply($f, $c->b); // error }
PHP
hhvm/hphp/hack/test/ifc/check/governed_basic.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class C { <<__Policied("A")>> public int $a = 0; <<__Policied("PUBLIC")>> public int $pub = 0; } // Valid Examples: <<__Policied>> function governed_identity(int $x): int { return $x; } <<__Policied>> function governed_basic(int $x, int $y): int { return $x + $y; } <<__Policied("A")>> function write_a_to_a(int $x, C $c): void { $c->a = $x; } <<__Policied("PUBLIC")>> function write_public_to_a(int $x, C $c): void { $c->a = $x; } // Invalid Examples <<__Policied>> function write_existential_into_A(int $x, C $c): void { $c->a = $x; } <<__Policied>> function write_existential_into_PUBLIC(int $x, C $c): void { $c->pub = $x; } <<__Policied>> function write_PUBLIC_into_PUBLIC(int $x, C $c): void { // This is still illegal because there is a dependency on the PC $c->pub = 0; }
PHP
hhvm/hphp/hack/test/ifc/check/governed_calls.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class C { <<__Policied("PUBLIC")>> public int $value = 0; <<__InferFlows>> public function __construct() {} } <<__InferFlows>> function plus(int $x, int $y): int { return $x + $y; } <<__InferFlows>> function store(int $x): void { $c = new C(); $c->value = $x; } <<__Policied>> function call_governed(): int { return call_inferred(123); } <<__Policied>> function call_inferred(int $x): int { // This is allowed return plus($x, 2); } // Functions below should trigger errors <<__Policied>> function leak_value(int $x): void { // This leaks $x (and pc) by storing into PUBLIC store($x); } <<__Policied>> function leak_pc(): void { // This leaks the PC by storing into PUBLIC store(123); } <<__Policied("PUBLIC")>> function public_pc(): void { // This does not leak the PC, because the context is public store(123); }
PHP
hhvm/hphp/hack/test/ifc/check/higher_order_functions.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class A { } class C { <<__Policied("PUBLIC")>> public int $value = 0; <<__Policied("FOO")>> public bool $foo = false; <<__Policied("PUBLIC")>> public A $a; <<__InferFlows>> public function __construct() { $this->a = new A(); } } <<__InferFlows>> function apply_ok((function(int): int) $f, C $c): void { // This is fine since we're inferring flows $c->value = $f(0); } // Function arguments of cipp function take in cipp // data and return cipp data <<__Policied>> function apply((function(int): int) $f, int $arg): int { return $f($arg); } <<__Policied>> function apply0((function(int): int) $f, C $c): void { // PUBLIC flows into CIPP, the call works because ints // are immutable $f($c->value); } // Functions below trigger errors <<__Policied>> function apply1((function(int): int) $f, C $c): void { $c->value = $f(0); } <<__Policied>> function apply2((function(): void) $f, C $c): void { if ($c->foo) { $f(); } } <<__Policied>> function apply3((function(A): void) $f, C $c): void { // Error, $c->a is mutable $f($c->a); }
PHP
hhvm/hphp/hack/test/ifc/check/inheritance.php
<?hh // strict class A { <<__Policied("P1")>> public int $i = 0; } trait T { <<__Policied("P2")>> public int $j = 0; } class B extends A { use T; <<__Policied("P3")>> public int $k = 0; } <<__InferFlows>> function test(B $b): void { $b->i = $b->k; $b->j = $b->k; }
PHP
hhvm/hphp/hack/test/ifc/check/keyset.php
<?hh class Basic { <<__Policied("S")>> public string $string = "string"; <<__Policied("A")>> public arraykey $arraykey = "string"; <<__Policied("K")>> public keyset<arraykey> $keyset = keyset[]; <<__InferFlows>> public function add(): void { // S flows into K $this->keyset[] = $this->string; } <<__InferFlows>> public function collection(): void { // S flows into K $this->keyset = keyset[42, $this->string]; } <<__InferFlows>> public function access(): void { // K flows into A $this->arraykey = $this->keyset['key']; } } class COW { <<__InferFlows>> public function __construct( <<__Policied("X")>> public string $x, <<__Policied("Y")>> public int $y, <<__Policied("KEYSET")>> public keyset<arraykey> $keyset, ) {} <<__InferFlows>> public function copyOnWrite(keyset<arraykey> $keyset): void { $keyset[] = $this->x; // X flows into KEYSET through keyset value $this->keyset = $keyset; $keyset[] = $this->y; // Y doesn't flow into KEYSET because keyset has copy-on-write semantics } }
PHP
hhvm/hphp/hack/test/ifc/check/lambda.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class C { <<__Policied("A")>> public int $a = 0; <<__Policied("B")>> public int $b = 0; } <<__InferFlows>> function apply((function(C): int) $f, C $c): void { $x = $f($c); $c->a = $x; } <<__InferFlows>> function store_a_in_a(C $c): void { $f = $x ==> $x->a; apply($f, $c); } <<__InferFlows>> function store_b_in_a(C $c): void { $f = $x ==> $x->b; apply($f, $c); } <<__InferFlows>> function store_b_in_a2(C $c): void { $f = $x ==> { if ($x->b > 0) { return 1; } else { return 0; } }; apply($f, $c); } <<__InferFlows>> function leak_pc(C $c): void { if ($c->a > 0) { $f = () ==> 0; } else { $f = () ==> 1; } $c->b = $f(); } <<__InferFlows>> function lambda_throw(C $c, Exception $e): void { $f = (int $x): void ==> { if ($x > 0) { throw $e; } }; try { $f($c->a); } catch (Exception $_) { // The PC is tainted by A $c->b = 99; } } <<__InferFlows>> function apply_lambda(C $c): void { $c->a = ($x ==> $x)($c->b); } <<__InferFlows>> function apply_var(C $c): void { $id = $x ==> $x; $c->a = $id($c->b); }
PHP
hhvm/hphp/hack/test/ifc/check/legacy_collection.php
<?hh class C { <<__Policied("KEY")>> public int $key = 0; <<__Policied("VALUE")>> public int $value = 0; <<__Policied("PUBLIC")>> public int $public = 0; <<__InferFlows>> public function leak_imm_vector(): void { $v = ImmVector { $this->value }; $this->public = $v[0]; } <<__InferFlows>> public function leak_imm_set(): void { $s = ImmSet { $this->value }; foreach ($s as $v) { $this->public = $this->value; } } <<__InferFlows>> public function leak_imm_map(): void { $m = ImmMap { $this->key => $this->value }; $this->public = $m[0]; } }
PHP
hhvm/hphp/hack/test/ifc/check/long_dataflow.php
<?hh class C { <<__InferFlows>> public function __construct( <<__Policied("PUBLIC")>> public int $public, <<__Policied("PRIVATE")>> public int $private, public int $unrelated, ) {} } <<__InferFlows>> function intermediate(C $obj, int $data): void { $obj->unrelated = $obj->private; $obj->public = $data; $obj->unrelated = $obj->private; } <<__InferFlows>> function writeToPublic(C $obj, int $data): void { $obj->unrelated = $obj->private; intermediate($obj, $data); $obj->unrelated = $obj->private; } <<__InferFlows>> function getPrivate(C $obj): int { $obj->unrelated = $obj->private; $tmp = $obj->private; $obj->unrelated = $obj->private; return $tmp; } <<__InferFlows>> function test(C $obj): void { $obj->unrelated = $obj->private; $private = getPrivate($obj); $obj->unrelated = $obj->private; writeToPublic($obj, $private); $obj->unrelated = $obj->private; }
PHP
hhvm/hphp/hack/test/ifc/check/multiple_sources.php
<?hh class C { <<__InferFlows>> public function __construct( <<__Policied("A")>> public int $a, <<__Policied("B")>> public int $b1, <<__Policied("B")>> public int $b2, <<__Policied("PUBLIC")>> public int $public, public int $v1, public int $v2, ) {} <<__InferFlows>> public function testDistinctPurposes(): void { $this->public = $this->a + $this->b1; } <<__InferFlows>> public function testSamePurpose(): void { $this->public = $this->b1 + $this->b2; } <<__InferFlows>> public function testIndirection1(): void { $this->v1 = $this->a + $this->b1; $this->public = $this->v1; } <<__InferFlows>> public function testIndirection2(): void { $this->v1 = $this->a; $this->public = $this->v1 + $this->b1; } <<__InferFlows>> public function testIndirection3(): void { $this->v1 = $this->a; $this->v2 = $this->b1; $this->public = $this->v1 + $this->v2; } <<__InferFlows>> public function halfIllegal(): void { $this->a += $this->b1; } }
PHP
hhvm/hphp/hack/test/ifc/check/mut_array_access.php
<?hh class D {} class C { <<__InferFlows>> public function __construct( <<__Policied("PRIVATE")>> public int $privateInt, <<__Policied("PUBLIC")>> public int $publicInt, <<__Policied("PRIVATE")>> public D $privateD, <<__Policied("PUBLIC")>> public D $publicD, ) {} } <<__InferFlows>> function leak_via_vector_prim_value(C $c): void { $vector = Vector {$c->privateInt}; // PRIVATE leaks to PUBLIC $c->publicInt = $vector[0]; } <<__InferFlows>> function leak_via_vector_object_value(C $c): void { $vector = Vector {$c->privateD}; // PRIVATE leaks to PUBLIC $c->publicD = $vector[0]; } <<__InferFlows>> function leak_via_vector_index(C $c, Vector<int> $vector): void { // PRIVATE leaks to PUBLIC $c->publicInt = $vector[$c->privateInt]; } <<__InferFlows>> function leak_via_map_value(C $c, Map<int,int> $vector): void { $vector = Map {0 => $c->privateInt}; // PRIVATE leaks to PUBLIC $c->publicInt = $vector[0]; } <<__InferFlows>> function leak_via_map_key(C $c, Map<int,int> $vector): void { $vector = Map {$c->privateInt => 0}; // PRIVATE leaks to PUBLIC $c->publicInt = $vector[0]; } <<__InferFlows>> function ok(C $c): void { $vector = Vector {$c->publicInt}; $c->publicInt = $vector[0]; }
PHP
hhvm/hphp/hack/test/ifc/check/mut_array_assign.php
<?hh class C { <<__Policied("I")>> public int $i = 0; <<__Policied("J")>> public int $j = 0; <<__Policied("PUBLIC")>> public Vector<int> $vector = Vector {}; } <<__InferFlows>> function ok(C $c): void { $vector = Vector {}; $vector[] = $c->i; $c->i = $vector[0]; } <<__InferFlows>> function leak_via_value(C $c, Vector<int> $vector): void { $vector[] = $c->i; $c->j = $vector[0]; // I flows into J } <<__InferFlows>> function leak_via_key(C $c, Vector<int> $vector): void { $vector[$c->i] = 0; $c->j = $vector[0]; // I flows into J } <<__InferFlows>> function not_copy_on_write(C $c, Vector<int> $v): void { $v[] = $c->i; // I flows into PUBLIC $c->vector = $v; $v[] = $c->j; // J flows inot PUBLIC } <<__InferFlows>> function leak_via_collection(C $c, Vector<shape()> $v0, Vector<shape()> $v1): void { if ($c->i) { $v = $v0; } else { $v = $v1; } $v[0] = shape(); try { $v0[0]; $c->j = 0; // I flows into J // If we $c->j is not zero we learn that $c->i was false. } catch (Exception $_) { } }
PHP
hhvm/hphp/hack/test/ifc/check/mut_array_control_flow.php
<?hh class C { <<__InferFlows>> public function __construct( <<__Policied("I")>> public int $i, <<__Policied("J")>> public int $j, ) {} } <<__InferFlows>> function ok_vector_ix(C $c, Vector<int> $vector): void { $vector[] = $c->i; // Force lump of vector to be I $c->j = 0; // OK because vector append does not raise an exception } <<__InferFlows>> function ok_map_extend(C $c, Map<string,int> $map): void { $map['hello'] = $c->i; // Force lump of vector to be I $c->j = 0; // OK because map extension does not raise an exception } <<__InferFlows>> function leak_via_exn(C $c, Vector<int> $vector): void { $vector[0] = $c->i; // Force lump of vector to be I // There is a flow from PC which is governed by length of vector due to the // conditional exception. The length is governed by the lump policy. $c->j = 0; // I flows into J }
PHP
hhvm/hphp/hack/test/ifc/check/mut_array_literal.php
<?hh class D {} class C { <<__InferFlows>> public function __construct( <<__Policied("CONTAINER")>> public Container<int> $container, <<__Policied("CONTAINER_COMPLEX")>> public Container<D> $containerComplex, <<__Policied("KEYED_CONTAINER")>> public KeyedContainer<string, int> $keyedContainer, <<__Policied("PUBLIC")>> public int $publicInt, <<__Policied("PUBLIC")>> public string $publicString, <<__Policied("VALUE_PRIM1")>> public int $valuePrim1, <<__Policied("VALUE_PRIM2")>> public int $valuePrim2, <<__Policied("VALUE_COMPLEX")>> public D $valueComplex, <<__Policied("KEY")>> public string $key, ) {} } <<__InferFlows>> function ok(C $c): void { $c->container = Vector {1, 2, 3}; $c->container = Set {1, 2, 3}; $c->keyedContainer = Map {'a' => 1, 'b' => 2, 'c' => 3}; $c->container = Vector {$c->publicInt, $c->publicInt}; $c->container = Set {$c->publicInt}; $c->keyedContainer = Map {$c->publicString => $c->publicInt, $c->publicString => $c->publicInt}; } <<__InferFlows>> function leak_through_simple_val(C $c): void { $c->container = Vector {1, $c->valuePrim1, 2, $c->valuePrim2}; } <<__InferFlows>> function leak_through_simple_key_val(C $c): void { $c->container = Map {$c->key => $c->valuePrim1, 'hi' => $c->valuePrim2}; } <<__InferFlows>> function leak_through_complex_val(C $c): void { $c->containerComplex = Vector {$c->valueComplex}; }
PHP
hhvm/hphp/hack/test/ifc/check/new.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class X { <<__InferFlows>> public function __construct(<<__Policied("PRIVATE")>> public int $valuex) {} <<__InferFlows>> public static function selfToSelf(): void { $x = new self(42); $y = new Y(24); $y->valuey = $x->valuex; } } class Y { <<__InferFlows>> public function __construct(<<__Policied("PUBLIC")>> public int $valuey) {} } class Z extends Y { <<__InferFlows>> public static function parentToSelf(): void { $x = new X(42); $y = new parent(24); $y->valuey = $x->valuex; } } <<__InferFlows>> function f(): void { $x = new X(1234); if ($x->valuex > 10) { $y = new Y(99); } }
PHP
hhvm/hphp/hack/test/ifc/check/new_return.php
<?hh class C { <<__InferFlows>> public function __construct( public string $file ): void {} } class D { <<__InferFlows>> public function __construct( <<__Policied("FILE")>> public string $file, <<__Policied("PUBLIC")>> public string $public_file, <<__Policied("PUBLIC")>> public C $public_c, ) {} } <<__InferFlows>> function leak_via_field(D $d): void { $c = new C($d->file); $d->public_file = $c->file; // FILE flows to PUBLIC } <<__InferFlows>> function leak_via_subtyping(D $d): void { $c = new C($d->file); $d->public_c = $c; // FILE flows to PUBLIC }
PHP
hhvm/hphp/hack/test/ifc/check/nominal_subtyping.php
<?hh class Secret { <<__InferFlows>> public function __construct( <<__Policied("PRIVATE")>> public int $secret, ) {} } class A { <<__InferFlows>> public function __construct( <<__Policied("PUBLIC")>> public int $pa, ) {} } class B extends A { <<__InferFlows>> public function __construct( public int $pa ) { parent::__construct($pa); } } class C extends B { <<__InferFlows>> public function __construct( public int $pa ) { parent::__construct($pa); } } <<__InferFlows>> function castBA(B $b): A { return $b; } <<__InferFlows>> function testBA(Secret $secret, B $b): void { castBA($b)->pa = $secret->secret; } <<__InferFlows>> function castCA(C $c): A { return $c; } <<__InferFlows>> function testCA(Secret $secret, C $c): void { castCA($c)->pa = $secret->secret; }
PHP
hhvm/hphp/hack/test/ifc/check/null_leak.php
<?hh // strict class A { <<__Policied("X")>> public int $x = 0; <<__Policied("Y")>> public int $y = 0; }; <<__InferFlows>> function g(A $a): void { $x = $a; if ($a->x > 0) { $x = null; } // $x: (A | null<X>) if ($x) { // the test's outcome depends on the policies // in the union type; in particular it depends // on X; so there is a bogus flow from X to Y $a->y = 1; } }
PHP
hhvm/hphp/hack/test/ifc/check/out_of_bounds_exceptions.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class X { <<__InferFlows>> public function __construct(<<__Policied("PRIVATE")>> public int $valuex) {} } class Y { <<__InferFlows>> public function __construct(<<__Policied("PUBLIC")>> public int $valuey) {} } <<__InferFlows>> function koVecAccess(X $x, Y $y, vec<int> $v): void { if ($x->valuex > 10) { // The following may throw out of bounds exception. // Should conservatively behave same as throw. $v[0]; } $y->valuey = 10; } <<__InferFlows>> function koVecAssign(X $x, Y $y, vec<int> $v): void { if ($x->valuex > 10) { // The following may throw out of bounds exception. // Should conservatively behave same as throw. $v[0] = 42; } $y->valuey = 10; } <<__InferFlows>> function okDictAssign(X $x, Y $y, dict<int,int> $dict): void { // Assigning to a dictionary does not cause an exception to be thrown, so // there is no leak here. if ($x->valuex > 10) { $dict[0] = 42; } $y->valuey = 10; } <<__InferFlows>> function koDictAccess(X $x, Y $y, dict<string,int> $v): void { if ($x->valuex > 10) { // The following may throw out of bounds exception. // Should conservatively behave same as throw. $v['hi']; } $y->valuey = 10; } <<__InferFlows>> function okDict(X $x, Y $y, dict<string,int> $v): void { if ($x->valuex > 10) { // The following is fine because we handle all exceptions. try { $v['hi']; } catch (Exception $_) { } } $y->valuey = 10; } class V { <<__Policied("VEC")>> public vec<string> $vec = vec[]; <<__Policied("PUBLIC")>> public bool $b = false; <<__InferFlows>> public function koIsEmptyAccess(): void { if (isEmptyAccess($this->vec)) { $this->b = true; // VEC leaks to PUBLIC through length } } <<__InferFlows>> public function koIsEmptyAssign(): void { if (isEmptyAssign($this->vec)) { $this->b = true; // VEC leaks to PUBLIC through length } } } // The following decides the length using exceptions. <<__InferFlows>> function isEmptyAccess(vec<string> $v): bool { try { $v[1]; return false; // Leak goes through here } catch (Exception $_) { return true; // Leak also goes through here } } // The following decides the length using exceptions. <<__InferFlows>> function isEmptyAssign(vec<string> $v): bool { try { $v[1] = 42; return false; // Leak goes through here } catch (Exception $_) { return true; // Leak also goes through here } }
PHP
hhvm/hphp/hack/test/ifc/check/parent_construct.php
<?hh class C { <<__InferFlows>> public function __construct( <<__Policied("PRIVATE")>> public int $private, ) { } } class D extends C { <<__InferFlows>> public function __construct( <<__Policied("PUBLIC")>> public int $public, public int $private, ) { parent::__construct($private); } } <<__InferFlows>> function test(): void { $d = new D(42,24); $d->public = $d->private; }
PHP
hhvm/hphp/hack/test/ifc/check/pass_external.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class A { <<__InferFlows>> public function __construct() {} } class B { <<__Policied("PUBLIC")>> public A $pub; <<__Policied("PRIVATE")>> public A $priv; <<__InferFlows>> public function __construct() { $this->pub = new A(); $this->priv = new A(); } } <<__Policied("A")>> function f(<<__External>> A $x): void {} <<__Policied("A")>> function g(A $x): void {} <<__Policied("A")>> function governed_to_external(A $x): void { // Ok! Regular values can be passed to external because external is more // restrictive f($x); } <<__Policied("A")>> function external_to_governed(<<__External>> A $x): void { // Not ok! An external cannot be used as a regular value g($x); } <<__InferFlows>> function public_to_A(B $x): void { // Ok! Even though f is governed by the policy A its argument is marked as // external and, as such, can be subject to any policy P such that P flows to // A. Public is such a policy, so the call is fine. f($x->pub); } <<__Policied("PUBLIC")>> function external_to_external(<<__External>> A $x): void { try { // Ok because the arg is external f($x); } catch (Exception $_) {} } <<__InferFlows>> function private_to_A(B $x): void { // Not allowed because PRIVATE does not flow to A f($x->priv); } <<__Policied("PRIVATE")>> function private_external_to_A(<<__External>> A $x): void { // Not allowed! $x can be subject to any policy P that flows to Private, that // is, to any policy. In particular P might not flow into A as required for // f's argument, so the call is invalid. f($x); }
PHP
hhvm/hphp/hack/test/ifc/check/pipe.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class C { <<__Policied("A")>> public int $a = 0; <<__Policied("B")>> public int $b = 0; } <<__InferFlows>> function basic_pipe(C $c): void { $c->a = $c->b |> $$; } <<__InferFlows>> function pc_pipe(C $c, Exception $e): void { $maybe_throw = (int $x) ==> { if ($x > 0) { throw $e; } return 0; }; $write_a = $x ==> { $c->a = $x; }; // Illegal! The PC during the write depends on B $maybe_throw($c->b) |> $write_a($$); } <<__InferFlows>> function chained_pipes(C $c): void { $ret_a = (int $_) ==> $c->a; $ret_b = (int $_) ==> $c->b; $c->a = 0 |> $ret_a($$) // $$ is Public |> $ret_b($$); // $$ is A }
PHP
hhvm/hphp/hack/test/ifc/check/private_functions.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class A { <<__Policied("A")>> public int $value = 0; } <<__Policied>> function apply(<<__CanCall>> (function(int): int) $f, int $x): void { try { $f($x); } catch (Exception $_) {} } <<__InferFlows>> function throw_private(A $a, Exception $e): void { $lambda = $x ==> { if ($x > $a->value) { throw $e; } return $x; }; apply($lambda, 123); } <<__Policied>> function no_catch(<<__CanCall>> (function(): void) $f): void { // This is illegal because $f could leak info via exceptions $f(); } <<__Policied>> function use_result(<<__CanCall>> (function(): int) $f): int { $x = 0; try { $x = $f(); } catch (Exception $_) {} // This is illegal because $x is private return $x; }
PHP
hhvm/hphp/hack/test/ifc/check/security_lattice.php
<?hh // strict // With respect to the implicitly constructed lattice: // // PRIVATE // / \ // A B // \ / // PUBLIC class C { <<__InferFlows>> public function __construct( <<__Policied("A")>> public int $a, <<__Policied("B")>> public int $b, <<__Policied("PUBLIC")>> public int $public, <<__Policied("PRIVATE")>> public int $private, ) {} <<__InferFlows>> public function test(): void { $this->public = $this->public; // Ok $this->private = $this->public; // Ok $this->private = $this->private; // Ok $this->private = $this->a; // Ok $this->a = $this->public; // Ok $this->a = $this->a; // Ok $this->public = $this->private; // Not ok $this->a = $this->private; // Not ok $this->b = $this->a; // Not ok } }
PHP
hhvm/hphp/hack/test/ifc/check/shape_basic.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class C { <<__Policied("PUBLIC")>> public shape("x" => int, "y" => string) $pub = shape("x" => 1, "y" => ""); <<__Policied("A")>> public shape("y" => string, "x" => int) $a = shape("x" => 1, "y" => ""); <<__Policied("B")>> public shape("x" => int, "y" => string) $b = shape("x" => 1, "y" => ""); } <<__InferFlows>> function assign_literal(C $c): void { $sh = shape("x" => 123, "y" => "hello world"); // all ok $c->pub = $sh; $c->a = $sh; $c->b = $sh; } <<__InferFlows>> function assign_pub(C $c): void { // all ok $c->a = $c->pub; $c->b = $c->pub; } <<__InferFlows>> function bad_assign_ko1(C $c): void { // illegal! $c->pub = $c->a; } <<__InferFlows>> function bad_assign_ko2(C $c): void { // illegal! $c->a = $c->b; } <<__Policied("PUBLIC")>> function takes_pub(shape("x" => int, "y" => string) $sh): void {} <<__Policied("A")>> function takes_a(shape("x" => int, "y" => string) $sh): void {} <<__InferFlows>> function pass_to_pub_ok(C $c): void { // ok takes_pub($c->pub); } <<__InferFlows>> function pass_to_pub_ko(C $c): void { // illegal takes_pub($c->a); } <<__InferFlows>> function pass_to_a_ok(C $c): void { // ok takes_a($c->pub); takes_a($c->a); } <<__InferFlows>> function pass_to_a_ko(C $c): void { // illegal takes_a($c->b); } <<__Policied("PUBLIC")>> function id(shape("x" => int) $s): shape("x" => int) { return $s; }
PHP
hhvm/hphp/hack/test/ifc/check/shape_get.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class C { <<__Policied("PUBLIC")>> public shape("x" => int, "y" => string) $pub = shape("x" => 1, "y" => ""); <<__Policied("A")>> public shape("y" => string, "x" => int) $a = shape("x" => 1, "y" => ""); <<__Policied("B")>> public shape("x" => int, "y" => string) $b = shape("x" => 1, "y" => ""); } <<__InferFlows>> function assign_literal(C $c): void { // ok because literals are public $c->a["x"] = 1; $c->b["x"] = 2; } <<__InferFlows>> function assign_pc(C $c): void { if ($c->a["x"] > 0) { // illegal because pc depends on A $c->b["y"] = ""; } } <<__InferFlows>> function ok_assign(C $c): void { // ok $c->a["x"] = $c->pub["x"]; } <<__InferFlows>> function bad_assign(C $c): void { // illegal! $c->a["y"] = $c->b["y"]; } <<__InferFlows>> function cow_ok(C $c): void { $alias = $c->pub; // ok because shapes are CoW $alias["x"] = $c->a["x"]; $alias["y"] = $c->b["y"]; }
PHP
hhvm/hphp/hack/test/ifc/check/shape_idx.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class C { <<__Policied("A")>> public int $a = 0; <<__Policied("A")>> public mixed $a_mixed = 0; <<__Policied("B")>> public int $b = 0; <<__Policied("B")>> public mixed $b_mixed = 0; <<__Policied("PRIVATE")>> public mixed $priv = 0; <<__Policied("PUBLIC")>> public mixed $pub = 0; } <<__InferFlows>> function get_x(shape(...) $s): mixed { return Shapes::idx($s, "x"); } <<__InferFlows>> function get_optional_x(shape(?"x" => int) $s): mixed { return Shapes::idx($s, "x"); } <<__InferFlows>> function write_a_to_a(C $c): void { $s = shape("x" => $c->a); // all ok $c->a_mixed = Shapes::idx($s, "x"); $c->a_mixed = get_x($s); } <<__InferFlows>> function write_a_to_b(C $c): void { $s = shape("x" => $c->a); // leak! $c->b_mixed = get_x($s); } <<__InferFlows>> function write_a_to_b2(C $c): void { $s = shape("x" => $c->b, "y" => $c->a); // Even though "x" has policy B, A also flows into the shape's lump $c->b_mixed = get_x($s); } <<__InferFlows>> function write_private(C $c): void { $s = shape("x" => $c->b, "y" => $c->a); // ok, because the covariant ints can flow to private $c->priv = get_x($s); } <<__InferFlows>> function write_private_bad(C $c): void { $s = shape("x" => $c->b_mixed, "y" => $c->a_mixed); // bad, because the mixed values have invariant policies $c->priv = get_x($s); } <<__InferFlows>> function optional_leaks_pc(C $c): void { $s = shape(); if ($c->a > 0) { $s["x"] = 1; } $c->b_mixed = Shapes::idx($s, "x"); } <<__InferFlows>> function default_leaks(C $c): void { $s = shape(); if ($c->a > 0) { $s["x"] = 1; } // B leaks to A because "x" might not be defined $c->a_mixed = Shapes::idx($s, "x", $c->b); } <<__InferFlows>> function default_no_leak(C $c): void { $s = shape("x" => 1); // We consider this a leak because the analysis is conservative $c->a_mixed = Shapes::idx($s, "x", $c->b); } <<__InferFlows>> function get_public_null(C $c): void { // ok, the shape has no non-public data $c->pub = get_x(shape()); $c->pub = get_optional_x(shape()); } <<__InferFlows>> function non_public_null(C $c): void { $s = shape(); if ($c->a > 0) { $s["x"] = 1; } // Illegal! The optional field has info about the PC $c->pub = get_optional_x($s); }
PHP
hhvm/hphp/hack/test/ifc/check/shape_pc.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class C { <<__Policied("PUBLIC")>> public shape("x" => int, "y" => string) $pub = shape("x" => 1, "y" => ""); <<__Policied("A")>> public shape("y" => string, "x" => int) $a = shape("x" => 1, "y" => ""); <<__Policied("B")>> public shape("x" => int, "y" => string) $b = shape("x" => 1, "y" => ""); } <<__InferFlows>> function pc_ok(C $c): void { $s = $c->a; if ($c->b["x"] > 0) { // Only field "x" depends on the PC $s["x"] = 1; } $c->a["y"] = $s["y"]; // ok } <<__InferFlows>> function pc_bad(C $c): void { $s = $c->a; if ($c->b["x"] > 0) { // Only field "x" depends on the PC $s["x"] = 1; } $c->a["x"] = $s["x"]; // error }
PHP
hhvm/hphp/hack/test/ifc/check/switch.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class C { <<__Policied("A")>> public int $a = 0; <<__Policied("B")>> public int $b = 0; } <<__InferFlows>> function switch_basic(C $c): void { switch ($c->a) { case 0: // illegal! leaks PC $c->b = 1; break; default: break; } $c->b = 1; // ok, PC is erased at this point } <<__InferFlows>> function leak_in_case_expr(C $c, int $x): void { switch ($x) { case $c->a: $c->b = $x; break; default: break; } } <<__InferFlows>> function leak_in_fallthrough(C $c, int $x): void { $y = 0; switch ($x) { case 0: $y = $c->a; // FALLTHROUGH case 1: $c->b = $y; break; default: break; } } <<__InferFlows>> function leak_after_switch(C $c, int $x): void { switch ($x) { case 0: $y = $c->a; break; default: $y = 1; break; } $c->b = $y; } <<__InferFlows>> function leak_fallthrough_pc(C $c, int $x): void { switch ($x) { case 0: if ($c->a > 0) { return; } // FALLTHROUGH default: $c->b = 1; } } <<__InferFlows>> function leak_pc_after_switch(C $c): void { switch ($c->a) { case 0: return; default: break; } $c->b = 1; } <<__InferFlows>> function leak_pc_complex(C $c, int $x, Exception $e): void { switch ($x) { case 0: $c->b = 0; // ok, no leak break; case $c->a: $c->b = 1; // illegal! we know A equals $x break; case 2: $c->b = 2; // illegal! we know A is not 2 break; default: $c->b = 3; // illegal! we know that A is not $x } } <<__InferFlows>> function leak_pc_in_case_exp(C $c): int { $f = () ==> { $c->a = 0; return 1; }; switch ($c->b) { case $f(): return 0; default: return 1; } }
PHP
hhvm/hphp/hack/test/ifc/check/tuple.php
<?hh class C { <<__Policied("S")>> public string $s = ""; <<__Policied("I")>> public int $i = 0; <<__Policied("J")>> public int $j = 0; <<__Policied("B")>> public bool $b = true; <<__Policied("PUBLIC")>> public (bool,int) $tuple = tuple(false, 0); } <<__InferFlows>> function ok(C $c): void { $tuple = tuple($c->s, $c->i, $c->b, $c->j); $c->i = $tuple[1]; $tuple[3] = $c->i; $c->i = $tuple[1]; $pair = Pair { $c->i, $c->j }; $c->i = $pair[0]; } <<__InferFlows>> function leak_through_access_tuple(C $c): void { $tuple = tuple($c->s, $c->i, $c->b, $c->j); // J leaks to I $c->i = $tuple[3]; } <<__InferFlows>> function leak_through_access_pair(C $c): void { $pair = Pair { $c->i, $c->j }; // J leaks to I $c->i = $pair[1]; } <<__InferFlows>> function leak_through_assignment_tuple(C $c): void { $tuple = tuple($c->s, $c->i, $c->b, $c->j); $tuple[1] = $c->j; // J leaks to I $c->i = $tuple[1]; } // Copy-on-write semantics means `$this->tuple` becomes `tuple(false, $this->i)` // after the first assignment and thus does not depend on `$this->j` from the // second assignment. <<__InferFlows>> function copyOnWrite(C $c): void { $tuple = tuple(false, 0); $tuple[1] = $c->i; $c->tuple = $tuple; // I leaks to PUBLIC $tuple[1] = $c->j; // J does NOT leak to PUBLIC } <<__InferFlows>> function leakPreservedOnAssignment(C $c): void { $tuple = tuple($c->i,0); $tuple[1] = 1; $c->j = $tuple[0]; }
PHP
hhvm/hphp/hack/test/ifc/check/tuple_overwrite.php
<?hh class C { <<__Policied("PUBLIC")>> public int $public = 0; <<__Policied("PRIVATE")>> public int $private = 0; } <<__InferFlows>> function overwrite_to_make_ok(C $c): void { $t = tuple($c->private, $c->public); $t[0] = $c->public; $c->public = $t[0]; } <<__InferFlows>> function overwrite_to_make_ko(C $c): void { $t = tuple($c->public, $c->public); $t[0] = $c->private; $c->public = $t[0]; // PRIVATE flows into PUBLIC } <<__InferFlows>> function overwrite_to_stay_ok(C $c): void { $t = tuple($c->public, $c->public); $t[0] = $c->private; $c->public = $t[1]; } <<__InferFlows>> function overwrite_to_stay_ko(C $c): void { $t = tuple($c->private, $c->private); $t[0] = $c->public; $c->public = $t[1]; // PRIVATE flows into PUBLIC }
PHP
hhvm/hphp/hack/test/ifc/check/unary_operators.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class C { <<__Policied("A")>> public int $a = 0; <<__Policied("B")>> public int $b = 0; } <<__InferFlows>> function incr_pc_ok1(C $c): void { if (!($c->a > 0)) { $c->a--; // ok } } <<__InferFlows>> function incr_pc_ok2(C $c): void { if (!($c->a > 0)) { --$c->a; // ok } } <<__InferFlows>> function incr_pc_ko1(C $c): void { if (!($c->a > 0)) { $c->b++; // This is illegal because the PC depends on A } } <<__InferFlows>> function incr_pc_ko2(C $c): void { if (!($c->a > 0)) { ++$c->b; // This is illegal because the PC depends on A } } <<__InferFlows>> function assign_uop_ko1(C $c): void { // illegal $c->b = ~$c->a; } <<__InferFlows>> function assign_uop_ko2(C $c): void { // illegal $c->b = -$c->a; }
PHP
hhvm/hphp/hack/test/ifc/check/varray.php
<?hh class C { <<__Policied("PUBLIC")>> public int $public = 0; <<__Policied("PRIVATE")>> private int $private = 0; public function __construct( <<__Policied("PUBLIC")>> public varray<int> $vPublic, <<__Policied("PRIVATE")>> public varray<int> $vPrivate, ) {} <<__InferFlows>> public function subtypeKO(): void { // PRIVATE leaks to PUBLIC $this->vPublic = varray[$this->private]; } <<__InferFlows>> public function subtypeOK(): void { $this->vPublic = varray[42]; } <<__InferFlows>> public function accessKO(): void { // PRIVATE leaks to PUBLIC $this->public = $this->vPrivate[0]; } <<__InferFlows>> public function accessOK(): void { $this->public = $this->vPublic[0]; } <<__InferFlows>> public function addKO(): void { // PRIVATE leaks to PUBLIC $this->vPublic[] = $this->private; } <<__InferFlows>> public function addOK(): void { $this->vPublic[] = 42; } <<__InferFlows>> public function overrideValKO(): void { // PRIVATE leaks to PUBLIC $this->vPublic[0] = $this->private; } <<__InferFlows>> public function overrideKeyKO(): void { // PRIVATE leaks to PUBLIC $this->vPublic[$this->private] = 0; } <<__InferFlows>> public function overrideOK(): void { $this->vPublic[0] = 42; } }
PHP
hhvm/hphp/hack/test/ifc/check/vec.php
<?hh // strict class Basic { <<__Policied("I")>> public int $i = 0; <<__Policied("V")>> public vec<int> $v = vec[]; <<__InferFlows>> public function set(): void { $this->v[] = $this->i; } <<__InferFlows>> public function mutation(): void { $this->v[0] += $this->i; } <<__InferFlows>> public function mutationKeyLeak(): void { $this->v[$this->i] = 42; // I leaks to V through the key } <<__InferFlows>> public function nested(vec<vec<int>> $vv): void { $vv[42][] = $this->v[0]; $this->i = $vv[0][0]; } } class COW { <<__InferFlows>> public function __construct( <<__Policied("X")>> public int $x, <<__Policied("Y")>> public int $y, <<__Policied("VX")>> public vec<int> $vx, ) {} // copy-on-write semantics means $this->vx is vec[$x] and thus // does not depend on $this->y <<__InferFlows>> public function copyOnWrite(vec<int> $v): void { $v[] = $this->x; $this->vx = $v; $v[] = $this->y; } }
PHP
hhvm/hphp/hack/test/ifc/check/while.php
<?hh // strict class C { <<__Policied("PRIVATE")>> public string $pri = ""; <<__Policied("PRIVATE")>> public bool $prib = true; <<__Policied("PUBLIC")>> public string $pub = ""; <<__Policied("PUBLIC")>> public arraykey $out = 42; } <<__InferFlows>> function simple(bool $b, C $c): void { $x = 42; while ($b) { $x = $c->pri; $x = $c->pub; } // fine because $x can only be public $c->out = $x; } <<__InferFlows>> function breaks(bool $b, C $c): void { $x = 42; while ($b) { $x = $c->pri; if ($b) break; $x = $c->pub; } // this is an error, $x can be either // private or public depending on the break $c->out = $x; } <<__InferFlows>> function continues(bool $b, C $c): void { $x = 42; while ($b) { $x = $c->pri; if ($b) continue; $x = $c->pub; } // this is an error, for reasons similar to // the breaks() function above $c->out = $x; } <<__InferFlows>> function pcleak(C $c): void { $n = 0; while ($c->prib) { $n = 1; $c->prib = false; } // this is an error, some information about // the boolean $c->prib can be leaked $c->out = $n; } <<__InferFlows>> function niftyleak(bool $b, C $c): void { $x = 42; $y = 24; $z = 12; // look ma no fixpoint in ifc.ml! while ($b) { $c->out = $z; $z = $x; $x = $y; $y = $c->pri; } }
PHP
hhvm/hphp/hack/test/ifc/decl/calls_basics.php
<?hh // strict class C { <<__Policied("A")>> public int $a = 0; <<__Policied("B")>> public int $b = 0; <<__InferFlows>> public function setb(int $n): void { $this->b = $n; } <<__InferFlows>> public function is_a_pos(): bool { if ($this->a > 0) { return true; } else { return false; } } } <<__InferFlows>> function dbl(int $x): int { $x += $x; return $x; } <<__InferFlows>> function flow_a_to_b(C $c): void { $n = dbl($c->a); $c->setb($n); } <<__InferFlows>> function flow_b_to_b(C $c): void { $c->setb($c->b); } <<__InferFlows>> function flow_bot_to_b(C $c): void { $c->setb(dbl(dbl(42))); } <<__InferFlows>> function indirect_flow_a_to_b(C $c): void { if ($c->a > 0) { $c->setb(42); } } <<__InferFlows>> function indirect_flow_a_to_b_bis(C $c1, C $c2): void { if ($c1->is_a_pos()) { $c2->setb($c2->b + 1); } }
hhvm/hphp/hack/test/ifc/decl/dune
(rule (alias ifc) (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/ifc/decl/*.php) (glob_files %{project_root}/hack/test/ifc/decl/*.php.exp)) (action (run %{project_root}/hack/test/verify.py %{project_root}/hack/test/ifc/decl --program %{exe:../../../src/hh_single_type_check.exe} --in-extension .php --flags --like-type-hints --ifc decl "" --error-format plain))) (alias (name runtest) (deps (alias ifc)))
PHP
hhvm/hphp/hack/test/ifc/decl/property_inheritance.php
<?hh // strict trait R { use T; <<__Policied("PUBLIC")>> public int $rPub = 0; <<__Policied("PUBLIC")>> private int $rPri = 0; <<__Policied("PUBLIC")>> protected int $rPro = 0; public int $rUnpolicied = 0; } class C extends B { use T; <<__Policied("PUBLIC")>> public int $cPub = 0; <<__Policied("PUBLIC")>> private int $cPri = 0; <<__Policied("PUBLIC")>> protected int $cPro = 0; public int $cUnpolicied = 0; } class A { <<__Policied("PUBLIC")>> public int $aPub = 0; <<__Policied("PUBLIC")>> private int $aPri = 0; <<__Policied("PUBLIC")>> protected int $aPro = 0; public int $aUnpolicied = 0; } class B extends A { <<__Policied("PUBLIC")>> public int $bPub = 0; <<__Policied("PUBLIC")>> private int $bPri = 0; <<__Policied("PUBLIC")>> protected int $bPro = 0; public int $bUnpolicied = 0; } trait T { <<__Policied("PUBLIC")>> public int $tPub = 0; <<__Policied("PUBLIC")>> private int $tPri = 0; <<__Policied("PUBLIC")>> protected int $tPro = 0; public int $tUnpolicied = 0; } trait ZTrait { <<__Policied("PUBLIC")>> public int $replicaPP = 0; <<__Policied("PUBLIC")>> public int $replicaPU = 0; public int $replicaUP = 0; } class Z { use ZTrait; <<__Policied("PUBLIC")>> public int $replicaPP = 0; public int $replicaPU = 0; <<__Policied("PUBLIC")>> public int $replicaUP = 0; }
PHP
hhvm/hphp/hack/test/ifc/unknown_syntax/basic.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. <<__InferFlows>> function variable_in_scope(): int { do { // $x is always in scope $x = 0; } while (false); // IFC never registers $x, but the analysis does not fatal return $x; }
hhvm/hphp/hack/test/ifc/unknown_syntax/dune
(rule (alias ifc) (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/ifc/unknown_syntax/*.php) (glob_files %{project_root}/hack/test/ifc/unknown_syntax/*.php.exp)) (action (run %{project_root}/hack/test/verify.py %{project_root}/hack/test/ifc/unknown_syntax --program %{exe:../../../src/hh_single_type_check.exe} --in-extension .php --flags --ifc check "" --error-format plain))) (alias (name runtest) (deps (alias ifc)))
PHP
hhvm/hphp/hack/test/ifc/unknown_syntax/ifc_errors.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class A { <<__Policied("PUBLIC")>> public int $pub = 0; <<__Policied("PRIVATE")>> public int $priv = 1; } <<__InferFlows>> function f(A $a): void { $x = $a->priv; // We still get a flow error here $a->pub = $x; }
PHP
hhvm/hphp/hack/test/ifc/unknown_syntax/late_static_binding.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class A { <<__InferFlows>> public static function f(): int { return 1; } <<__InferFlows>> public function g(): int { return static::f(); } } class B extends A { <<__InferFlows>> public static function f(): int { return 2; } }
hhvm/hphp/hack/test/incremental/dune
(executable (name test_method_override) (link_flags (:standard (:include ../../src/dune_config/ld-opts.sexp))) (modules test_method_override) (modes exe byte_complete) (libraries integration_test_base)) (rule (alias method_override) (deps test_method_override.exe) (action (run ./test_method_override.exe))) (executable (name test_inconsistent_state) (link_flags (:standard (:include ../../src/dune_config/ld-opts.sexp))) (modules test_inconsistent_state) (modes exe byte_complete) (libraries integration_test_base)) (rule (alias inconsistent_state) (deps test_inconsistent_state.exe) (action (run ./test_inconsistent_state.exe))) (executable (name test_enum_exhaustiveness) (link_flags (:standard (:include ../../src/dune_config/ld-opts.sexp))) (modules test_enum_exhaustiveness) (modes exe byte_complete) (libraries integration_test_base)) (rule (alias enum_exhaustiveness) (deps test_enum_exhaustiveness.exe) (action (run ./test_enum_exhaustiveness.exe))) (alias (name runtest) (deps (alias method_override) (alias inconsistent_state) (alias enum_exhaustiveness)))
OCaml
hhvm/hphp/hack/test/incremental/test_enum_exhaustiveness.ml
open Integration_test_base_types open ServerEnv module Test = Integration_test_base let init_base_content = "<?hh enum DynamicTemplateField : string { BRAND = 'brand'; DESCRIPTION = 'description'; // NAME = 'name'; }" let err_base_content = "<?hh enum DynamicTemplateField : string { BRAND = 'brand'; DESCRIPTION = 'description'; NAME = 'name'; }" let make_disk_changes base_content = [ ("base.php", base_content); ( "test.php", "<?hh // strict function test( DynamicTemplateField $field, ): string { // Switch enforces enum exhaustiveness switch ($field) { case DynamicTemplateField::BRAND: return 'Brand'; case DynamicTemplateField::DESCRIPTION: return 'Description'; } }" ); ] let errors_to_string errors = List.fold_left (fun str error -> str ^ (error |> User_error.to_absolute |> Errors.to_string)) "" @@ errors let () = let env = Test.setup_server () in (* Initially we expect no errors *) let (env, _) = Test.( run_loop_once env { default_loop_input with disk_changes = make_disk_changes init_base_content; }) in let errors = Errors.get_sorted_error_list env.errorl in if errors <> [] then Test.fail ("Expected no errors. Got:\n" ^ errors_to_string errors); (* We expect errors when we change base.php to err_base_content *) let (env, _) = Test.( run_loop_once env { default_loop_input with disk_changes = make_disk_changes err_base_content; }) in let expected_errors = Errors.get_sorted_error_list env.errorl in if expected_errors = [] then Test.fail "Expected there to be errors!"; (* We reset the disk changes to the initial state. Should be no errors *) let (env, _) = Test.( run_loop_once env { default_loop_input with disk_changes = make_disk_changes init_base_content; }) in let errors = Errors.get_sorted_error_list env.errorl in if errors <> [] then Test.fail ("Expected no errors. Got:\n" ^ errors_to_string errors); (* We now change only base.php. We expect the same errors as before *) let (env, _) = Test.( run_loop_once env { default_loop_input with disk_changes = [("base.php", err_base_content)]; }) in let incremental_errors = Errors.get_sorted_error_list env.errorl in if incremental_errors <> expected_errors then Test.fail ("Incremental mode gave different errors than a full type check.\n\n" ^ "Full Type Check Errors:\n" ^ errors_to_string expected_errors ^ "\n" ^ "Incremental Mode Errors:\n" ^ errors_to_string incremental_errors)
OCaml
hhvm/hphp/hack/test/incremental/test_inconsistent_state.ml
open Integration_test_base_types open ServerEnv module Test = Integration_test_base let init_disk_changes = [ ( "base.php", "<?hh // strict abstract class Base { public static function meth(): void {} }" ); ("parent.php", "<?hh // strict abstract class ParentClass extends Base { }"); ( "achild.php", "<?hh // strict class AChild extends ParentClass { public static function test(): void { $achild = new self(); $achild->__meth(); } private function __meth(): void {} } " ); ] let next_disk_changes = [ ("base.php", "<?hh // strict abstract class Base { } "); ( "achild.php", "<?hh // strict class AChild extends ParentClass { public static function test(): void { $achild = new self(); $achild->meth(); } private function meth(): void {} } " ); ] let errors_to_string errors = List.fold_left (fun str error -> str ^ (error |> User_error.to_absolute |> Errors.to_string)) "" @@ errors let () = let env = Test.setup_server () in let (env, _) = Test.( run_loop_once env { default_loop_input with disk_changes = init_disk_changes }) in let errors = Errors.get_sorted_error_list env.errorl in if errors <> [] then Test.fail ("Expected no errors. Got:\n" ^ errors_to_string errors); let (env, _) = Test.( run_loop_once env { default_loop_input with disk_changes = next_disk_changes }) in let errors = Errors.get_sorted_error_list env.errorl in if errors <> [] then Test.fail ("Expected no errors. Got:\n" ^ errors_to_string errors)
OCaml
hhvm/hphp/hack/test/incremental/test_method_override.ml
open Integration_test_base_types open ServerEnv module Test = Integration_test_base let init_base_content = "<?hh // strict abstract class Base { public static function meth(int $x): void {} }" let err_base_content = "<?hh // strict abstract class Base { public static function meth(): void {} }" let make_disk_changes base_content = [ ("base.php", base_content); ("parent.php", "<?hh // strict abstract class ParentClass extends Base { }"); ( "child1.php", "<?hh // strict class Child1 extends ParentClass { public static function meth(int $x): void {} public static function callParentMeth(): void { parent::meth(9); } }" ); ( "child2.php", "<?hh // strict class Child2 extends ParentClass { public static function meth(int $x): void {} }" ); ] let errors_to_string errors = List.fold_left (fun str error -> str ^ (error |> User_error.to_absolute |> Errors.to_string)) "" @@ errors let () = let env = Test.setup_server () in (* Initially we expect no errors *) let (env, _) = Test.( run_loop_once env { default_loop_input with disk_changes = make_disk_changes init_base_content; }) in let errors = Errors.get_sorted_error_list env.errorl in if errors <> [] then Test.fail ("Expected no errors. Got:\n" ^ errors_to_string errors); (* We expect errors when we change base.php to err_base_content *) let (env, _) = Test.( run_loop_once env { default_loop_input with disk_changes = make_disk_changes err_base_content; }) in let expected_errors = Errors.get_sorted_error_list env.errorl in if expected_errors = [] then Test.fail "Expected there to be errors!"; (* We reset the disk changes to the initial state. Should be no errors *) let (env, _) = Test.( run_loop_once env { default_loop_input with disk_changes = make_disk_changes init_base_content; }) in let errors = Errors.get_sorted_error_list env.errorl in if errors <> [] then Test.fail ("Expected no errors. Got:\n" ^ errors_to_string errors); (* We now change only base.php. We expect the same errors as before *) let (env, _) = Test.( run_loop_once env { default_loop_input with disk_changes = [("base.php", err_base_content)]; }) in let incremental_errors = Errors.get_sorted_error_list env.errorl in if incremental_errors <> expected_errors then Test.fail ("Incremental mode gave different errors than a full type check.\n\n" ^ "Full Type Check Errors:\n" ^ errors_to_string expected_errors ^ "\n" ^ "Incremental Mode Errors:\n" ^ errors_to_string incremental_errors)
Python
hhvm/hphp/hack/test/integration/common_tests.py
# pyre-strict from __future__ import absolute_import, division, print_function, unicode_literals import datetime import json import os import re import shutil import signal import subprocess import sys import tempfile import time from typing import ClassVar, List, Mapping, NamedTuple, Optional, Tuple from hh_paths import hackfmt, hh_client, hh_server from test_case import TestCase, TestDriver class AllLogs(NamedTuple): all_server_logs: str all_monitor_logs: str client_log: str current_server_log: str current_monitor_log: str lsp_log: str ide_log: str class CommonTestDriver(TestDriver): # This needs to be overridden in child classes. The files in this # directory will be used to set up the initial environment for each # test. template_repo: ClassVar[str] repo_dir: ClassVar[str] test_env: ClassVar[Mapping[str, str]] base_tmp_dir: ClassVar[str] hh_tmp_dir: ClassVar[str] bin_dir: ClassVar[str] @classmethod def setUpClass(cls, template_repo: str) -> None: cls.template_repo = template_repo cls.maxDiff = 2000 cls.base_tmp_dir = tempfile.mkdtemp() # we don't create repo_dir using mkdtemp() because we want to create # it with copytree(). copytree() will fail if the directory already # exists. cls.repo_dir = os.path.join(cls.base_tmp_dir, "repo") # Where the hhi files, socket, etc get extracted cls.hh_tmp_dir = tempfile.mkdtemp() cls.bin_dir = tempfile.mkdtemp() hh_server_dir = os.path.dirname(hh_server) print("hh_server_dir " + hh_server_dir) cls.test_env = dict( os.environ, **{ "HH_TEST_MODE": "1", "HH_TMPDIR": cls.hh_tmp_dir, "PATH": ( "%s:%s:/bin:/usr/bin:/usr/local/bin" % (hh_server_dir, cls.bin_dir) ), "HH_HOME": os.path.dirname(hh_client), "OCAMLRUNPARAM": "b", "HH_LOCALCONF_PATH": cls.repo_dir, }, ) @classmethod def tearDownClass(cls) -> None: shutil.rmtree(cls.base_tmp_dir) shutil.rmtree(cls.bin_dir) shutil.rmtree(cls.hh_tmp_dir) def write_load_config(self, use_saved_state: bool = False) -> None: """ Writes out a script that will print the list of changed files, and adds the path to that script to .hhconfig """ raise NotImplementedError() def wait_until_server_ready(self) -> None: """ We don't want to accidentally connect to an old hh_server, so we wait 2 seconds for the monitor to start up the new server first. """ time.sleep(2) self.run_check() def start_hh_server( self, changed_files: Optional[List[str]] = None, saved_state_path: Optional[str] = None, args: Optional[List[str]] = None, ) -> None: """Start an hh_server. changed_files is ignored here (as it has no meaning) and is only exposed in this API for the derived classes. """ if changed_files is None: changed_files = [] if args is None: args = [] cmd = [hh_server, "--daemon", "--max-procs", "2", self.repo_dir] + args self.proc_call(cmd) self.wait_until_server_ready() def stop_hh_server(self, retries: int = 3) -> None: (_, _, exit_code) = self.proc_call([hh_client, "stop", self.repo_dir]) if exit_code == 0: return elif retries > 0 and exit_code != 0: self.stop_hh_server(retries=retries - 1) else: self.assertEqual(exit_code, 0, msg="Stopping hh_server failed") def setUp(self) -> None: shutil.copytree(self.template_repo, self.repo_dir) def tearDownWithRetries(self, retries: int = 3) -> None: self.stop_hh_server(retries=retries) shutil.rmtree(self.repo_dir) def tearDown(self) -> None: self.tearDownWithRetries() @classmethod # pyre-fixme[24]: Generic type `subprocess.Popen` expects 1 type parameter. def proc_create(cls, args: List[str], env: Mapping[str, str]) -> subprocess.Popen: return subprocess.Popen( args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=dict(cls.test_env, **env), universal_newlines=True, ) @classmethod def proc_call( cls, args: List[str], env: Optional[Mapping[str, str]] = None, stdin: Optional[str] = None, log: bool = True, ) -> Tuple[str, str, int]: """ Invoke a subprocess, return stdout, send stderr to our stderr (for debugging) """ env = {} if env is None else env if log: print( "[%s] proc_call: %s" % (datetime.datetime.now().strftime("%H:%M:%S"), " ".join(args)), file=sys.stderr, ) proc = cls.proc_create(args, env) (stdout_data, stderr_data) = proc.communicate(stdin) sys.stderr.write(stderr_data) sys.stderr.flush() retcode = proc.wait() return (stdout_data, stderr_data, retcode) @classmethod def wait_pid_with_timeout(cls, pid: int, timeout: int) -> None: """ Like os.waitpid but with a timeout in seconds. """ waited_time = 0 while True: pid_expected, _ = os.waitpid(pid, os.WNOHANG) if pid_expected == pid: break elif waited_time >= timeout: raise subprocess.TimeoutExpired else: time.sleep(1) waited_time += 1 @classmethod def get_all_logs(cls, repo_dir: str) -> AllLogs: # noqa: C901 time.sleep(2) # wait for logs to be written server_file = cls.proc_call([hh_client, "--logname", repo_dir], log=False)[ 0 ].strip() monitor_file = cls.proc_call( [hh_client, "--monitor-logname", repo_dir], log=False )[0].strip() client_file = cls.proc_call( [hh_client, "--client-logname", repo_dir], log=False )[0].strip() lsp_file = cls.proc_call([hh_client, "--lsp-logname", repo_dir], log=False)[ 0 ].strip() ide_file = cls.proc_call([hh_client, "--ide-logname", repo_dir], log=False)[ 0 ].strip() # Server log try: with open(server_file) as f: current_server_log = f.read() all_server_logs = "[CURRENT-SERVER-LOG] %s\n%s" % ( server_file, current_server_log, ) except IOError as err: current_server_log = "[error]" all_server_logs = "[CURRENT-SERVER-LOG] %s\n%s" % (server_file, format(err)) try: with open(server_file + ".old") as f: all_server_logs = "[OLD-SERVER-LOG] %s.old\n%s\n\n%s" % ( server_file, f.read(), all_server_logs, ) except Exception: pass # Monitor log try: with open(monitor_file) as f: current_monitor_log = f.read() all_monitor_logs = "[CURRENT-MONITOR-LOG] %s\n%s" % ( monitor_file, current_monitor_log, ) except Exception as err: current_monitor_log = "[error]" all_monitor_logs = "[CURRENT-MONITOR-LOG] %s\n%s" % ( monitor_file, format(err), ) try: with open(monitor_file + ".old") as f: all_monitor_logs = "[OLD-MONITOR-LOG] %s.old\n%s\n\n%s" % ( monitor_file, f.read(), all_monitor_logs, ) except Exception: pass # Client log try: with open(client_file) as f: client_log = f.read() except Exception as err: client_log = client_file + " - " + format(err) try: with open(client_log + ".old") as f: old_client_log = f.read() client_log = "%s\n%s\n" % (old_client_log, client_log) except Exception: pass # Lsp log try: with open(lsp_file) as f: lsp_log = f.read() except Exception as err: lsp_log = lsp_file + " - " + format(err) # Ide log try: with open(ide_file) as f: ide_log = f.read() except Exception as err: ide_log = ide_file + " - " + format(err) # All together... return AllLogs( all_server_logs=all_server_logs, all_monitor_logs=all_monitor_logs, client_log=client_log, current_server_log=current_server_log, current_monitor_log=current_monitor_log, lsp_log=lsp_log, ide_log=ide_log, ) def run_check( self, stdin: Optional[str] = None, options: Optional[List[str]] = None ) -> Tuple[str, str, int]: options = [] if options is None else options root = self.repo_dir + os.path.sep return self.proc_call( [ hh_client, "check", "--retries", "240", "--error-format", "raw", self.repo_dir, ] + list(map(lambda x: x.format(root=root), options)), stdin=stdin, ) def run_hackfmt( self, stdin: Optional[str] = None, options: Optional[List[str]] = None, expected_output: Optional[str] = None, ) -> bool: options = [] if options is None else options (output, err, retcode) = self.proc_call([hackfmt] + options, stdin=stdin) if retcode != 0: print("check returned non-zero code: " + str(retcode), file=sys.stderr) if expected_output is not None: self.assertEqual(expected_output, output) return True # Runs `hh_client check` asserting the stdout is equal the expected. # Returns stdout and stderr. # Note: assert_laoded_mini_state is ignored here and only used # in some derived classes. def check_cmd( self, expected_output: Optional[List[str]], stdin: Optional[str] = None, options: Optional[List[str]] = None, assert_loaded_saved_state: bool = False, ) -> Tuple[str, str]: (output, err, retcode) = self.run_check(stdin, options) root = self.repo_dir + os.path.sep if retcode != 0: print("check returned non-zero code: " + str(retcode), file=sys.stderr) if expected_output is not None: # pyre-fixme[8]: Attribute has type `int`; used as `None`. self.maxDiff = None expected_lines = [x.format(root=root) for x in expected_output] try: # assertCountEqual basically sorts the two lists and determines # if the sorted outputs are equal. We use this because we want # to be insensitive to non-determinism in error message order. self.assertCountEqual(expected_lines, output.splitlines()) except Exception: # the error messages produced by assertCountEqual can be quite hard # to read. Let's just write everything out plainly. nl = "\n" print( f"EXPECTED OUTPUT\n{nl.join(expected_lines)}\nACTUAL OUTPUT:\n{output}\n", file=sys.stderr, ) raise return output, err def check_cmd_and_json_cmd( self, expected_output: List[str], expected_json: List[str], stdin: Optional[str] = None, options: Optional[List[str]] = None, ) -> None: try: # we run the --json version first because --json --refactor doesn't # change any files, but plain --refactor does (i.e. the latter isn't # idempotent) if options is None: options = [] self.check_cmd(expected_json, stdin, options + ["--json"]) self.check_cmd(expected_output, stdin, options) except Exception: logs = self.get_all_logs(self.repo_dir) print("SERVER-LOG:\n%s\n\n" % logs.all_server_logs, file=sys.stderr) print("MONITOR-LOG:\n%s\n\n" % logs.all_monitor_logs, file=sys.stderr) raise def start_hh_loop_forever_assert_timeout(self) -> None: # create a file with 10 dependencies. Only "big" jobs, that use # workers can be interrupted at the moment. with open(os.path.join(self.repo_dir, "__hh_loop_forever_foo.php"), "w") as f: f.write( """<?hh //strict function __hh_loop_forever_foo(): int { return 4; }""" ) for i in range(1, 10): with open( os.path.join(self.repo_dir, "__hh_loop_forever_bar%d.php" % i), "w" ) as f: f.write( """<?hh //strict function __hh_loop_forever_bar%d(): int { return __hh_loop_forever_foo(); }""" % i ) self.check_cmd(["No errors!"]) # trigger rechecking of all 11 file, and make one of them loop # until cancelled with open(os.path.join(self.repo_dir, "__hh_loop_forever_foo.php"), "w") as f: f.write( """<?hh //strict function __hh_loop_forever_foo(): string { hh_loop_forever(); }""" ) # this should timeout due to infinite loop try: # empty output means no results due to timeout self.check_cmd([], options=["--retries", "1"]) except AssertionError: # one of the test drivers doesn't like timeouts pass def stop_hh_loop_forever(self) -> None: # subsequent change should interrupt the "loop forever" part with open(os.path.join(self.repo_dir, "__hh_loop_forever_foo.php"), "w") as f: f.write( """<?hh //strict function __hh_loop_forever_foo(): int { return 4; }""" ) self.check_cmd(["No errors!"]) # The most basic of tests. # Exercises server responsiveness, and updating errors after changing files class BarebonesTests(TestCase[CommonTestDriver]): # hh should should work with 0 retries. def test_responsiveness(self) -> None: self.test_driver.start_hh_server() self.test_driver.check_cmd(["No errors!"]) self.test_driver.check_cmd(["No errors!"], options=["--retries", "0"]) def test_new_file(self) -> None: """ Add a new file that contains an error. """ with open(os.path.join(self.test_driver.repo_dir, "foo_4.php"), "w") as f: f.write( """<?hh function k(): int { return 'a'; } """ ) self.test_driver.start_hh_server(changed_files=["foo_4.php"]) self.test_driver.check_cmd( [ "{root}foo_4.php:4:24,26: Invalid return type (Typing[4110])", " {root}foo_4.php:3:27,29: Expected `int`", " {root}foo_4.php:4:24,26: But got `string`", ] ) def test_new_naming_error(self) -> None: """ Add a new file which contains a naming collisions with an old file """ with open(os.path.join(self.test_driver.repo_dir, "foo_4.php"), "w") as f: f.write( """<?hh class FOO {} function H (): void {} """ ) self.test_driver.start_hh_server(changed_files=["foo_4.php"]) self.test_driver.check_cmd( [ "{root}foo_4.php:3:19,21: Name already bound: `FOO` (Naming[2012])", " {root}foo_3.php:7:15,17: Previous definition is here", "{root}foo_4.php:4:22,22: Name already bound: `H` (Naming[2012])", " {root}foo_3.php:3:18,18: Previous definition is here", ] ) # We put this test in Barebones tests so that dependencies on class B # show an error (i.e. class_3.php) with both the save state driver # and the classic save state driver def test_modify_extends_deps(self) -> None: """ Introduce a change to a base class that causes an error in a use case on one of its subclasses. """ with open(os.path.join(self.test_driver.repo_dir, "class_1.php"), "w") as f: f.write( """<?hh // strict class B { public static function foo () : bool { return true; } } """ ) self.test_driver.start_hh_server(changed_files=["class_1.php"]) self.test_driver.check_cmd( [ "{root}class_3.php:5:12,19: Invalid return type (Typing[4110])", " {root}class_3.php:4:28,30: Expected `int`", " {root}class_1.php:4:51,54: But got `bool`", ] ) # Common tests, includes the Barebones Tests above class CommonTests(BarebonesTests): def test_json_errors(self) -> None: """ If you ask for errors in JSON format, you will get them on standard output. Changing this will break the tools that depend on it (like editor plugins), and this test is here to remind you about it. """ self.test_driver.start_hh_server() stdout, _ = self.test_driver.check_cmd(None, options=["--json"]) output = json.loads(stdout) self.assertEqual(output["errors"], []) self.assertEqual(output["passed"], True) self.assertIn("version", output) def test_modify_file(self) -> None: """ Add an error to a file that previously had none. """ with open(os.path.join(self.test_driver.repo_dir, "foo_2.php"), "w") as f: f.write( """<?hh function g(): int { return 'a'; } """ ) self.test_driver.start_hh_server(changed_files=["foo_2.php"]) self.test_driver.check_cmd( [ "{root}foo_2.php:4:24,26: Invalid return type (Typing[4110])", " {root}foo_2.php:3:27,29: Expected `int`", " {root}foo_2.php:4:24,26: But got `string`", ] ) def test_deleted_file(self) -> None: """ Delete a file that still has dangling references before restoring from a saved state. """ os.remove(os.path.join(self.test_driver.repo_dir, "foo_2.php")) self.test_driver.start_hh_server(changed_files=["foo_2.php"]) self.test_driver.check_cmd( [ "{root}foo_1.php:4:20,20: Unbound name (typing): `g` (Typing[4107])", "{root}foo_1.php:4:20,20: Unbound name: `g` (a global function) (Naming[2049])", ] ) def test_file_delete_after_load(self) -> None: """ Delete a file that still has dangling references after restoring from a saved state. """ self.test_driver.start_hh_server() self.test_driver.check_cmd(["No errors!"]) os.remove(os.path.join(self.test_driver.repo_dir, "foo_2.php")) self.test_driver.check_cmd( [ "{root}foo_1.php:4:20,20: Unbound name: `g` (a global function) (Naming[2049])", "{root}foo_1.php:4:20,20: Unbound name (typing): `g` (Typing[4107])", ] ) def test_duplicated_file(self) -> None: self.test_driver.start_hh_server(changed_files=["foo_2.php"]) self.test_driver.check_cmd(["No errors!"]) shutil.copyfile( os.path.join(self.test_driver.repo_dir, "foo_2.php"), os.path.join(self.test_driver.repo_dir, "foo_2_dup.php"), ) self.test_driver.check_cmd( [ "{root}foo_2_dup.php:3:18,18: Name already bound: `g` (Naming[2012])", " {root}foo_2.php:3:18,18: Previous definition is here", ] ) os.remove(os.path.join(self.test_driver.repo_dir, "foo_2.php")) self.test_driver.check_cmd(["No errors!"]) def test_moved_file(self) -> None: """ Move a file, then create an error that references a definition in it. Check that the new file name is displayed in the error. """ self.test_driver.start_hh_server( changed_files=["foo_1.php", "foo_2.php", "bar_2.php"] ) os.rename( os.path.join(self.test_driver.repo_dir, "foo_2.php"), os.path.join(self.test_driver.repo_dir, "bar_2.php"), ) with open(os.path.join(self.test_driver.repo_dir, "foo_1.php"), "w") as f: f.write( """<?hh function f(): string { return g(); } """ ) self.test_driver.check_cmd( [ "{root}foo_1.php:4:24,26: Invalid return type (Typing[4110])", " {root}foo_1.php:3:27,32: Expected `string`", " {root}bar_2.php:3:23,25: But got `int`", ] ) def test_find_refs(self) -> None: """ Test hh_client --find-refs, --find-class-refs """ self.test_driver.start_hh_server() self.test_driver.check_cmd_and_json_cmd( ['File "{root}foo_3.php", line 11, characters 13-13: h', "1 total results"], [ '[{{"name":"h","filename":"{root}foo_3.php","line":11,"char_start":13,"char_end":13}}]' ], options=["--find-refs", "h"], ) self.test_driver.check_cmd_and_json_cmd( [ 'File "{root}foo_3.php", line 10, characters 17-19: Foo::__construct', "1 total results", ], [ '[{{"name":"Foo::__construct","filename":"{root}foo_3.php","line":10,"char_start":17,"char_end":19}}]' ], options=["--find-refs", "Foo::__construct"], ) self.test_driver.check_cmd_and_json_cmd( [ 'File "{root}foo_3.php", line 10, characters 17-19: Foo', "1 total results", ], [ '[{{"name":"Foo","filename":"{root}foo_3.php","line":10,' '"char_start":17,"char_end":19}}]' ], options=["--find-class-refs", "Foo"], ) def test_identify_symbol(self) -> None: """ Test hh_client --identify """ self.test_driver.start_hh_server() self.test_driver.check_cmd_and_json_cmd( [], [ '[{{"full_name":"B","pos":{{"filename":"{root}class_1.php","line":3,"char_start":7,"char_end":7}},"kind":"class"}}]' ], options=["--identify", "B"], ) self.test_driver.check_cmd_and_json_cmd( [], [ '[{{"full_name":"B::foo","pos":{{"filename":"{root}class_1.php","line":5,"char_start":26,"char_end":28}},"kind":"method"}}]' ], options=["--identify", "B::foo"], ) self.test_driver.check_cmd_and_json_cmd( [], [ '[{{"full_name":"CONST_SOME_COOL_VALUE","pos":{{"filename":"{root}const_1.php","line":3,"char_start":11,"char_end":31}},"kind":"const"}}]' ], options=["--identify", "CONST_SOME_COOL_VALUE"], ) self.test_driver.check_cmd_and_json_cmd( [], [ '[{{"full_name":"FbidMapField","pos":{{"filename":"{root}enum_1.php","line":3,"char_start":6,"char_end":17}},"kind":"enum"}}]' ], options=["--identify", "FbidMapField"], ) self.test_driver.check_cmd_and_json_cmd( [], [ '[{{"full_name":"FbidMapField::FBID","pos":{{"filename":"{root}enum_1.php","line":4,"char_start":3,"char_end":6}},"kind":"class constant"}}]' ], options=["--identify", "FbidMapField::FBID"], ) self.test_driver.check_cmd_and_json_cmd( [], [ '[{{"full_name":"f","pos":{{"filename":"{root}foo_1.php","line":3,"char_start":18,"char_end":18}},"kind":"function"}}]' ], options=["--identify", "f"], ) def test_list_files(self) -> None: """ Test hh_client --list-files """ os.remove(os.path.join(self.test_driver.repo_dir, "foo_2.php")) self.test_driver.start_hh_server(changed_files=["foo_2.php"]) self.test_driver.check_cmd_and_json_cmd( ["{root}foo_1.php"], ["{root}foo_1.php"], # see comment for identify-function options=["--list-files"], ) def test_type_at_pos(self) -> None: """ Test hh_client --type-at-pos """ self.test_driver.start_hh_server() self.test_driver.check_cmd_and_json_cmd( ["string"], [ '{{"type":"string",' + '"pos":{{"filename":"","line":0,"char_start":0,"char_end":0}},' + '"full_type":{{"src_pos":{{"filename":"{root}foo_3.php","line":3,"char_start":23,"char_end":28}},"kind":"primitive","name":"string"}}}}' ], options=["--type-at-pos", "{root}foo_3.php:11:14"], ) def test_type_at_pos_batch(self) -> None: """ Test hh_client --type-at-pos-batch """ self.test_driver.start_hh_server() self.test_driver.check_cmd( [ '{{"position":' + '{{"file":"{root}foo_3.php",' + '"line":11,' + '"character":14}}' + ',"type":{{' + '"src_pos":{{"filename":"{root}foo_3.php","line":3,"char_start":23,"char_end":28}},' + '"kind":"primitive",' + '"name":"string"}}}}' ], options=["--type-at-pos-batch", "{root}foo_3.php:11:14"], ) def test_type_at_pos_batch_readonly(self) -> None: """ Test hh_client --type-at-pos-batch """ self.test_driver.start_hh_server() self.test_driver.check_cmd( [ '{{"position":' + '{{"file":"{root}foo_readonly.php",' + '"line":4,' + '"character":4}}' + ',"type":{{' + '"src_pos":{{"filename":"{root}foo_readonly.php","line":3,"char_start":23,"char_end":68}},' + '"kind":"function",' + '"readonly_this":true,' + '"params":[{{"callConvention":"normal","readonly":true,"type":{{' + '"src_pos":{{"filename":"{root}foo_readonly.php","line":3,"char_start":51,"char_end":53}},"kind":"primitive","name":"int"}}}}],' + '"readonly_return":true,' + '"result":{{"src_pos":{{"filename":"{root}foo_readonly.php","line":3,"char_start":65,"char_end":67}},"kind":"primitive","name":"int"}}}}' + "}}" ], options=["--type-at-pos-batch", "{root}foo_readonly.php:4:4"], ) def test_ide_get_definition(self) -> None: """ Test hh_client --ide-get-definition """ self.test_driver.start_hh_server() self.test_driver.check_cmd_and_json_cmd( [ "name: \\bar, kind: function, span: line 1, characters 42-44," " is_declaration: false", "definition:", " bar", " kind: function", " id: function::bar", ' position: File "", line 1, characters 15-17:', ' span: File "", line 1, character 6 - line 1, character 22:', " modifiers: ", " params:", "", "", ], [ '[{{"name":"\\\\bar","result_type":"function",' '"pos":{{"filename":"","line":1,"char_start":42,"char_end":44}},' '"definition_pos":{{"filename":"","line":1,"char_start":15,' '"char_end":17}},"definition_span":{{"filename":"","line_start":1,' '"char_start":6,"line_end":1,"char_end":22}},' '"definition_id":"function::bar"}}]' ], options=["--ide-get-definition", "1:43"], stdin="<?hh function bar() {} function test() { bar() }", ) def test_ide_outline(self) -> None: """ Test hh_client --ide-outline """ self.test_driver.start_hh_server() """ This call is here to ensure that server is running. Outline command doesn't require it to be, but integration test suite assumes it and checks it's state after each test. """ self.test_driver.check_cmd(["No errors!"]) self.test_driver.check_cmd_and_json_cmd( [ "bar", " kind: function", " id: function::bar", ' position: File "", line 1, characters 15-17:', ' span: File "", line 1, character 6 - line 1, character 22:', " modifiers: ", " params:", "", ], [ '[{{"kind":"function","name":"bar","id":"function::bar",' '"position":{{"filename":"",' '"line":1,"char_start":15,"char_end":17}},"span":' '{{"filename":"","line_start":1,"char_start":6,"line_end":1,' '"char_end":22}},"modifiers":[],"params":[]}}]' ], options=["--ide-outline"], stdin="<?hh function bar() {}", ) def test_ide_get_definition_multi_file(self) -> None: """ Test hh_client --ide-get-definition when definition we look for is in file different from input file """ self.test_driver.start_hh_server() self.test_driver.check_cmd_and_json_cmd( [ "name: \\ClassToBeIdentified::methodToBeIdentified, kind: method," " span: line 1, characters 45-64, is_declaration: false", "definition:", " methodToBeIdentified", " kind: method", " id: method::ClassToBeIdentified::methodToBeIdentified", ' position: File "{root}foo_5.php", line 4, characters 26-45:', ' span: File "{root}foo_5.php", line 4, character 3 - line 4,' " character 56:", " modifiers: public static ", " params:", "", "", ], [ '[{{"name":"\\\\ClassToBeIdentified::methodToBeIdentified",' '"result_type":"method","pos":{{"filename":"","line":1,' '"char_start":45,"char_end":64}},"definition_pos":' '{{"filename":"{root}foo_5.php","line":4,"char_start":26,' '"char_end":45}},"definition_span":{{"filename":"{root}foo_5.php",' '"line_start":4,"char_start":3,"line_end":4,"char_end":56}},' '"definition_id":' '"method::ClassToBeIdentified::methodToBeIdentified"}}]' ], options=["--ide-get-definition", "1:50"], stdin="<?hh function test() { " "ClassToBeIdentified::methodToBeIdentified () }", ) def test_abnormal_typechecker_exit_message(self) -> None: """ Tests that the monitor outputs a useful message when its typechecker exits abnormally. """ self.test_driver.start_hh_server() logs = self.test_driver.get_all_logs(self.test_driver.repo_dir) monitor_logs = logs.current_monitor_log m = re.search( "Just started typechecker server with pid: ([0-9]+)", monitor_logs ) self.assertIsNotNone(m) assert m is not None, "for mypy" pid = m.group(1) self.assertIsNotNone(pid) os.kill(int(pid), signal.SIGTERM) # We've sent a kill signal to the server, but it may take some time for # the server to actually die. For instance, it may be attempting to # print a backtrace in the signal handler, which takes less than a # second in @//mode/opt, but can take minutes in @//mode/dev. If we # attempt to connect before the server process actually dies, the # monitor will happily hand us off to the dying server, which will # abruptly close our connection when its process exits. What we want # instead is to connect to the monitor after its waitpid on the server # completes, so that it can report to us the signal which killed the # server. We can't waitpid here because the server isn't a child of this # process, so we poll the monitor logs until the monitor records the # TYPECHECKER_EXIT event. attempts = 0 while attempts < 5 * 60: logs = self.test_driver.get_all_logs(self.test_driver.repo_dir) monitor_logs = logs.current_monitor_log m = re.search("TYPECHECKER_EXIT", monitor_logs) if m is not None: break attempts += 1 time.sleep(1) _, client_error = self.test_driver.check_cmd( expected_output=None, assert_loaded_saved_state=False ) self.assertIn("Last server killed by signal", client_error) def test_duplicate_parent(self) -> None: """ This checks that we handle duplicate parent classes, i.e. when Bar extends Foo and there are two declarations of Foo. We want to make sure that when the duplicate gets removed, we recover correctly by redeclaring Bar with the remaining parent class. """ with open(os.path.join(self.test_driver.repo_dir, "foo_4.php"), "w") as f: f.write( """<?hh class Foo { // also declared in foo_3.php, which setUp copies from the template repo "integration/data/simple_repo" public static ?int $x; } """ ) with open(os.path.join(self.test_driver.repo_dir, "foo_5.php"), "w") as f: f.write( """<?hh class Bar extends Foo {} function main(Bar $a): ?int { return $a::$y; } """ ) self.test_driver.start_hh_server(changed_files=["foo_4.php", "foo_5.php"]) self.test_driver.check_cmd( [ "{root}foo_4.php:3:19,21: Name already bound: `Foo` (Naming[2012])", " {root}foo_3.php:7:15,17: Previous definition is here", "{root}foo_5.php:6:28,29: No class variable `$y` in `Bar` (Typing[4090])", " {root}foo_5.php:3:19,21: Declaration of `Bar` is here", ] ) os.remove(os.path.join(self.test_driver.repo_dir, "foo_4.php")) self.test_driver.check_cmd( [ "{root}foo_5.php:6:28,29: No class variable `$y` in `Bar` (Typing[4090])", " {root}foo_5.php:3:19,21: Declaration of `Bar` is here", ] ) with open(os.path.join(self.test_driver.repo_dir, "foo_4.php"), "w") as f: f.write( """<?hh class Foo { public static ?int $y; } """ ) os.remove(os.path.join(self.test_driver.repo_dir, "foo_3.php")) self.test_driver.check_cmd(["No errors!"]) def test_refactor_methods(self) -> None: with open(os.path.join(self.test_driver.repo_dir, "foo_4.php"), "w") as f: f.write( """<?hh class Bar extends Foo { public function f(): void {} public function g(): void {} } class Baz extends Bar { public function g(): void { $this->f(); } } """ ) self.test_driver.start_hh_server(changed_files=["foo_4.php"]) self.test_driver.check_cmd_and_json_cmd( ["Rewrote 1 file."], [ '[{{"filename":"{root}foo_4.php","patches":[' '{{"char_start":74,"char_end":75,"line":4,"col_start":33,"col_end":33,"patch_type":"replace","replacement":"wat"}},' '{{"char_start":254,"char_end":255,"line":10,"col_start":28,"col_end":28,"patch_type":"replace","replacement":"wat"}},' '{{"char_start":42,"char_end":42,"line":4,"col_start":1,"col_end":1,"patch_type":"insert","replacement":"\\n <<__Deprecated(\\"Use `wat` instead\\")>>\\n public function f(): void {{\\n $this->wat();\\n }}\\n"}}' "]}}]" ], options=["--refactor", "Method", "Bar::f", "Bar::wat"], ) self.test_driver.check_cmd_and_json_cmd( ["Rewrote 1 file."], [ '[{{"filename":"{root}foo_4.php","patches":[' '{{"char_start":270,"char_end":271,"line":10,"col_start":33,"col_end":33,"patch_type":"replace","replacement":"overrideMe"}},' '{{"char_start":366,"char_end":367,"line":14,"col_start":33,"col_end":33,"patch_type":"replace","replacement":"overrideMe"}},' '{{"char_start":238,"char_end":238,"line":10,"col_start":1,"col_end":1,"patch_type":"insert","replacement":"\\n <<__Deprecated(\\"Use `overrideMe` instead\\")>>\\n public function g(): void {{\\n $this->overrideMe();\\n }}\\n"}}' "]}}]" ], options=["--refactor", "Method", "Bar::g", "Bar::overrideMe"], ) with open(os.path.join(self.test_driver.repo_dir, "foo_4.php")) as f: out = f.read() self.assertEqual( out, """<?hh class Bar extends Foo { <<__Deprecated("Use `wat` instead")>> public function f(): void { $this->wat(); } public function wat(): void {} <<__Deprecated("Use `overrideMe` instead")>> public function g(): void { $this->overrideMe(); } public function overrideMe(): void {} } class Baz extends Bar { public function overrideMe(): void { $this->wat(); } } """, ) def test_refactor_classes(self) -> None: with open(os.path.join(self.test_driver.repo_dir, "foo_4.php"), "w") as f: f.write( """<?hh class Bar extends Foo { const int FOO = 42; private static int $val = 0; public function f(): void {} public function g(): void {} public static function h(): void {} public static function i(): void { self::h(); self::$val = 1; static::$val = 2; $x = self::FOO; } } class Baz extends Bar { public function g(): void { $this->f(); parent::g(); } } """ ) self.test_driver.start_hh_server(changed_files=["foo_4.php"]) self.test_driver.check_cmd_and_json_cmd( ["Rewrote 2 files."], [ '[{{"filename":"{root}foo_4.php","patches":[{{' '"char_start":36,"char_end":39,"line":3,"col_start":31,' '"col_end":33,"patch_type":"replace","replacement":"Qux"}}]}},' '{{"filename":"{root}foo_3.php","patches":[{{' '"char_start":86,"char_end":89,"line":7,"col_start":15,' '"col_end":17,"patch_type":"replace","replacement":"Qux"}},' '{{"char_start":161,"char_end":164,"line":10,"col_start":17,' '"col_end":19,"patch_type":"replace","replacement":"Qux"}}]' "}}]" ], options=["--refactor", "Class", "Foo", "Qux"], ) self.test_driver.check_cmd_and_json_cmd( ["Rewrote 1 file."], [ '[{{"filename":"{root}foo_4.php","patches":[{{' '"char_start":24,"char_end":27,"line":3,"col_start":19,' '"col_end":21,"patch_type":"replace","replacement":"Quux"}},' '{{"char_start":522,"char_end":525,"line":19,"col_start":31,' '"col_end":33,"patch_type":"replace","replacement":"Quux"}}]}}]' ], options=["--refactor", "Class", "Bar", "Quux"], ) with open(os.path.join(self.test_driver.repo_dir, "foo_4.php")) as f: out = f.read() self.assertEqual( out, """<?hh class Quux extends Qux { const int FOO = 42; private static int $val = 0; public function f(): void {} public function g(): void {} public static function h(): void {} public static function i(): void { self::h(); self::$val = 1; static::$val = 2; $x = self::FOO; } } class Baz extends Quux { public function g(): void { $this->f(); parent::g(); } } """, ) with open(os.path.join(self.test_driver.repo_dir, "foo_3.php")) as f: out = f.read() self.assertEqual( out, """<?hh function h(): string { return "a"; } class Qux {} function some_long_function_name(): void { new Qux(); h(); } """, ) # test no double-rename (T157645473) with open(os.path.join(self.test_driver.repo_dir, "foo_4.php"), "w") as f: f.write( """<?hh class Foo { const type TEntry = int; public function main(): self::TEntry { return 3; } } """ ) self.test_driver.start_hh_server(changed_files=["foo_4.php"]) self.test_driver.check_cmd_and_json_cmd( ["Rewrote 1 file."], [ '[{{"filename":"{root}foo_4.php","patches":[{{"char_start":27,"char_end":30,"line":2,"col_start":23,"col_end":25,"patch_type":"replace","replacement":"Bar"}}' "]}}]" ], options=["--refactor", "Class", "Foo", "Bar"], ) def test_refactor_functions(self) -> None: with open(os.path.join(self.test_driver.repo_dir, "foo_4.php"), "w") as f: f.write( """<?hh function wow(): int { wat(); return f(); } function wat(): void {} """ ) self.test_driver.start_hh_server(changed_files=["foo_4.php"]) self.test_driver.check_cmd_and_json_cmd( ["Rewrote 1 file."], [ '[{{"filename":"{root}foo_4.php","patches":[' '{{"char_start":127,"char_end":130,"line":8,"col_start":22,"col_end":24,"patch_type":"replace","replacement":"woah"}},' '{{"char_start":56,"char_end":59,"line":4,"col_start":17,"col_end":19,"patch_type":"replace","replacement":"woah"}},' '{{"char_start":105,"char_end":105,"line":7,"col_start":1,"col_end":1,"patch_type":"insert","replacement":"\\n <<__Deprecated(\\"Use `woah` instead\\")>>\\n function wat(): void {{\\n woah();\\n }}\\n"}}' "]}}]" ], options=["--refactor", "Function", "wat", "woah"], ) self.test_driver.check_cmd_and_json_cmd( ["Rewrote 2 files."], [ '[{{"filename":"{root}foo_4.php","patches":[' '{{"char_start":87,"char_end":88,"line":5,"col_start":24,"col_end":24,"patch_type":"replace","replacement":"fff"}}' ']}},{{"filename":"{root}foo_1.php","patches":[' '{{"char_start":23,"char_end":24,"line":3,"col_start":18,"col_end":18,"patch_type":"replace","replacement":"fff"}},' '{{"char_start":5,"char_end":5,"line":2,"col_start":1,"col_end":1,"patch_type":"insert","replacement":"\\n <<__Deprecated(\\"Use `fff` instead\\")>>\\n function f(): int {{\\n return fff();\\n }}\\n"}}' "]}}]" ], options=["--refactor", "Function", "f", "fff"], ) with open(os.path.join(self.test_driver.repo_dir, "foo_4.php")) as f: out = f.read() self.assertEqual( out, """<?hh function wow(): int { woah(); return fff(); } <<__Deprecated("Use `woah` instead")>> function wat(): void { woah(); } function woah(): void {} """, ) with open(os.path.join(self.test_driver.repo_dir, "foo_1.php")) as f: out = f.read() self.assertEqual( out, """<?hh <<__Deprecated("Use `fff` instead")>> function f(): int { return fff(); } function fff(): int { return g() + 1; } """, ) def test_refactor_typedefs(self) -> None: with open(os.path.join(self.test_driver.repo_dir, "foo_4.php"), "w") as f: f.write( """<?hh newtype NewType = int; type Type = int; class MyClass { public function myFunc(Type $x): NewType { return $x; } } """ ) self.test_driver.start_hh_server(changed_files=["foo_4.php"]) self.test_driver.check_cmd_and_json_cmd( ["Rewrote 1 file."], [ '[{{"filename":"{root}foo_4.php","patches":[{{' '"char_start":26,"char_end":33,"line":3,"col_start":21,' '"col_end":27,"patch_type":"replace","replacement":"NewTypeX"}},' '{{"char_start":148,"char_end":155,"line":7,"col_start":50,' '"col_end":56,"patch_type":"replace","replacement":"NewTypeX"}}]' "}}]" ], options=["--refactor", "Class", "NewType", "NewTypeX"], ) self.test_driver.check_cmd_and_json_cmd( ["Rewrote 1 file."], [ '[{{"filename":"{root}foo_4.php","patches":[{{' '"char_start":59,"char_end":63,"line":4,"col_start":18,' '"col_end":21,"patch_type":"replace","replacement":"TypeX"}},' '{{"char_start":139,"char_end":143,"line":7,"col_start":40,' '"col_end":43,"patch_type":"replace","replacement":"TypeX"}}]' "}}]" ], options=["--refactor", "Class", "Type", "TypeX"], ) with open(os.path.join(self.test_driver.repo_dir, "foo_4.php")) as f: out = f.read() self.assertEqual( out, """<?hh newtype NewTypeX = int; type TypeX = int; class MyClass { public function myFunc(TypeX $x): NewTypeX { return $x; } } """, ) def test_auto_namespace_alias_addition(self) -> None: """ Add namespace alias and check if it is still good """ self.test_driver.start_hh_server() self.test_driver.check_cmd(["No errors!"]) with open(os.path.join(self.test_driver.repo_dir, "auto_ns_2.php"), "w") as f: f.write( """<?hh function haha(): int { Herp\\f(); return 1; } """ ) self.test_driver.check_cmd(["No errors!"]) def test_interrupt(self) -> None: # filesystem interruptions are only triggered by Watchman with open(os.path.join(self.test_driver.repo_dir, ".watchmanconfig"), "w") as f: f.write("{}") with open(os.path.join(self.test_driver.repo_dir, "hh.conf"), "a") as f: f.write( "use_watchman = true\n" + "interrupt_on_watchman = true\n" + "interrupt_on_client = true\n" + "watchman_subscribe_v2 = true\n" ) self.test_driver.start_hh_server() self.test_driver.start_hh_loop_forever_assert_timeout() self.test_driver.check_cmd( ["string"], options=["--type-at-pos", "{root}foo_3.php:11:14"] ) self.test_driver.stop_hh_loop_forever() def test_status_single(self) -> None: """ Test hh_client check --single """ self.test_driver.start_hh_server() with open( os.path.join(self.test_driver.repo_dir, "typing_error.php"), "w" ) as f: f.write("<?hh //strict\n function aaaa(): int { return h(); }") self.test_driver.check_cmd( [ "{root}typing_error.php:2:32,34: Invalid return type (Typing[4110])", " {root}typing_error.php:2:19,21: Expected `int`", " {root}foo_3.php:3:23,28: But got `string`", ], options=["--single", "{root}typing_error.php"], stdin="", ) self.test_driver.check_cmd( [ ":2:11,14: Name already bound: `aaaa` (Naming[2012])", " {root}typing_error.php:2:11,14: Previous definition is here", ":2:32,34: Invalid return type (Typing[4110])", " :2:19,21: Expected `int`", " {root}foo_3.php:3:23,28: But got `string`", ], options=["--single", "-"], stdin="<?hh //strict\n function aaaa(): int { return h(); }", ) def test_incremental_typecheck_same_file(self) -> None: self.maxDiff = None self.test_driver.start_hh_server() # Important: typecheck the file after creation but before adding contents # to test forward naming table updating. open( os.path.join( self.test_driver.repo_dir, "test_incremental_typecheck_same_file.php" ), "w", ).close() self.test_driver.check_cmd(["No errors!"]) with open( os.path.join( self.test_driver.repo_dir, "test_incremental_typecheck_same_file.php" ), "w", ) as f: f.write( """<?hh // strict // test_incremental_typecheck_same_file class TestIncrementalTypecheckSameFile {} """ ) self.test_driver.check_cmd(["No errors!"]) # Notice how the only change is the removed doc block. with open( os.path.join( self.test_driver.repo_dir, "test_incremental_typecheck_same_file.php" ), "w", ) as f: f.write( """<?hh // strict class TestIncrementalTypecheckSameFile {} """ ) self.test_driver.check_cmd(["No errors!"])
Shell Script
hhvm/hphp/hack/test/integration/decl_from_stdin.sh
#!/bin/bash # Regression test for "--identify-function <src" set -u # terminate upon read of uninitalized variable set -e # terminate upon non-zero-exit-codes (in case of pipe, only checks at end of pipe) set -o pipefail # in a pipe, the whole pipe runs, but its exit code is that of the first failure export PS4='+[$(date +%k:%M:%S)]($(basename ${BASH_SOURCE}):${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' trap 'echo "exit code $? at line $LINENO" >&2' ERR # Parse command-line arguments hh_client="$1" srcs_dir="$2" echo "hh_client=$hh_client" echo "srcs_dir=$srcs_dir" test -x "$hh_client" # verify that it's an executable test -f "$srcs_dir/decl_from_stdin1.php" # verify that files are present test -f "$srcs_dir/decl_from_stdin2.php" # New directory for test case. Make it a mercurial dir, and an empty hh project TEMPDIR="$(mktemp -d)" cd "$TEMPDIR" mkdir ".hg" touch ".hhconfig" cat <<EOF > "hh.conf" max_workers = 1 symbolindex_search_provider = NoIndex EOF export HH_LOCALCONF_PATH="$TEMPDIR" # so it uss our hh.conf export HH_TEST_MODE=1 # avoid writing a bunch of telemetry # From now on we'll use our own error handling instead of "set -e" set +e # Start up hh timeout 20s "$hh_client" code=$? logname=$("$hh_client" --logname) [[ $code == 7 ]] && { echo "Too many retries; skipping test."; exit 0; } [[ $code == 124 ]] && { echo "Timeout starting hh; skipping test."; exit 0; } [[ $code != 0 ]] && { echo "hh exit code $code"; exit "$code"; } # Repro. This repro also catches a weird case where the second call failed # only if the first one had previously been run. results1=$(< "$srcs_dir/decl_from_stdin1.php" "$hh_client" --identify-function 13:9) code1=$? echo "RESULTS1: decl_from_stdin1.php" echo "$results1" results2=$(< "$srcs_dir/decl_from_stdin2.php" "$hh_client" --identify-function 8:9) code2=$? echo "RESULTS2: decl_from_stdin2.php" echo "$results2" # Cleanup "$hh_client" stop > /dev/null 2>&1 rmdir ".hg" rm ".hhconfig" rm "hh.conf" cd / rmdir "$TEMPDIR" # Exit conditions [[ $code1 == 0 && $results1 != "" && $code2 == 0 && $results2 != "" ]] && exit 0 cat "$logname" exit 1
Shell Script
hhvm/hphp/hack/test/integration/decl_from_stdin_named.sh
#!/bin/bash # Regression test for "--identify-function <src" set -u # terminate upon read of uninitalized variable set -e # terminate upon non-zero-exit-codes (in case of pipe, only checks at end of pipe) set -o pipefail # in a pipe, the whole pipe runs, but its exit code is that of the first failure export PS4='+[$(date +%k:%M:%S)]($(basename ${BASH_SOURCE}):${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' trap 'echo "exit code $? at line $LINENO" >&2' ERR # Parse command-line arguments hh_client="$1" srcs_dir="$2" echo "hh_client=$hh_client" echo "srcs_dir=$srcs_dir" test -x "$hh_client" # verify that it's an executable test -f "$srcs_dir/decl_from_stdin1.php" # verify that files are present test -f "$srcs_dir/decl_from_stdin2.php" # New directory for test case. Make it a mercurial dir, and an empty hh project TEMPDIR="$(mktemp -d)" cd "$TEMPDIR" mkdir ".hg" touch ".hhconfig" cp "$srcs_dir/decl_from_stdin1.php" . cp "$srcs_dir/decl_from_stdin2.php" . cat <<EOF > "hh.conf" max_workers = 1 symbolindex_search_provider = NoIndex EOF export HH_LOCALCONF_PATH="$TEMPDIR" # so it uss our hh.conf export HH_TEST_MODE=1 # avoid writing a bunch of telemetry # From now on we'll use our own error handling instead of "set -e" set +e # Start up hh timeout 20s "$hh_client" code=$? logname=$("$hh_client" --logname) [[ $code == 7 ]] && { echo "Too many retries; skipping test."; exit 0; } [[ $code == 124 ]] && { echo "Timeout starting hh; skipping test."; exit 0; } [[ $code != 0 ]] && { echo "hh exit code $code"; exit "$code"; } # Repro. This repro also catches a weird case where the second call failed # only if the first one had previously been run. results1=$(< "$srcs_dir/decl_from_stdin1.php" "$hh_client" --identify-function 13:9 --stdin-name decl_from_stdin1.php) code1=$? echo "RESULTS1: decl_from_stdin1.php" echo "$results1" results2=$(< "$srcs_dir/decl_from_stdin2.php" "$hh_client" --identify-function 8:9 --stdin-name decl_from_stdin2.php) code2=$? echo "RESULTS2: decl_from_stdin2.php" echo "$results2" # Cleanup "$hh_client" stop > /dev/null 2>&1 rmdir ".hg" rm ".hhconfig" rm "hh.conf" rm "decl_from_stdin1.php" rm "decl_from_stdin2.php" cd / rmdir "$TEMPDIR" # Exit conditions [[ $code1 == 0 && $results1 != "" && $code2 == 0 && $results2 != "" ]] && exit 0 cat "$logname" exit 1
Shell Script
hhvm/hphp/hack/test/integration/findrefs_after_mv.sh
#!/bin/bash # This test makes sure that --find-class-refs still works after file move set -u err() { local status="$1" local msg="$2" 1>&2 printf '%s\n' "$msg" exit "$status" } hh_client=$1 hh_server=$2 test -x "$hh_client" || err 10 'hh_client is not executable' test -x "$hh_server" || err 12 'hh_client is not executable' # defensively go to root directory cd "/" || err 15 'cannot go to /' # make new directory for test case tempdir="$(mktemp /tmp/hhtest_repo_XXXX -d)" test -d "$tempdir" || err 20 'cannot create tempdir' cd "$tempdir" || err 21 'cannot change to tempdir' # Make it a mercurial directory so we get deterministic errors from hg. # Our attempts to get revision number will be met with "Error getting hg revision: # ... abort: unknown revision 'master'" mkdir ".hg" test -d ".hg" || err 22 'cannot create tempdir/.hg' # We'll use this instead of /tmp/hh_server hh_tmpdir="$(mktemp /tmp/hhtest_hh_tmpdir_XXXX -d)" test -d "$hh_tmpdir" || err 23 'cannot create hh_tmpdir' export HH_TMPDIR="$hh_tmpdir" # write files cat <<EOF > "c.php" <?hh // strict class C { public static function cf(): void {D::df();} } EOF test -f "c.php" || err 30 'cannot write c.php' cat <<EOF > "d.php" <?hh // strict class D { public static function df(): void {C::cf();} } EOF test -f "d.php" || err 31 'cannot write d.php' # touch config directory touch ".hhconfig" test -f ".hhconfig" || err 40 'cannot create empty .hhconfig' # create hh.conf cat <<EOF > "hh.conf" use_mini_state = false load_state_natively_v4 = false lazy_decl = true lazy_parse = true lazy_init2 = true max_workers = 1 remote_type_check_enabled = false EOF test -f "hh.conf" || err 41 'cannot create hh.conf' # set environment variable to point to hh.conf export HH_LOCALCONF_PATH="$tempdir" export HH_TEST_MODE=1 # start hh_server. "$hh_server" . --daemon 1>out.log 2>err.log status="$?" [[ "$status" == 0 ]] || err 50 "Expected hh_server to start with error code 0 not $status" # run hh_client. It should succeed "$hh_client" 1>out.log 2>err.log status="$?" [[ "$status" == 0 ]] || err 51 "Expected hh_client to exit with error code 0 not $status" # --find-class-refs C. It should find 1 result "$hh_client" --find-class-refs C 1>out.log 2>err.log status="$?" [[ "$status" == 0 ]] || err 60 "Expected hh_client --find-class-refs to exit with error code 0 not $status" <"out.log" grep -i '1 total results' > /dev/null || err 61 "--find-class-refs results incomplete - $tempdir/out.log" # move a file! mv d.php e.php || err 70 "failed to move file" # --find-class-refs C. Current buggy behavior is that it crashes "$hh_client" --find-class-refs C 1>out.log 2>err.log status="$?" [[ "$status" == 0 ]] || err 80 "Expected second hh_client --find-class-refs to exit with error code 0 not $status" <"out.log" grep -i '1 total results' > /dev/null || err 81 "second --find-class-refs results incomplete - $tempdir/out.log" "$hh_client" stop # incidentally, "hh_client <dir> stop" doesn't seem to stop it; hence why we did "cd" earlier 2>&1 echo "success!" cd "/" || err 90 'cannot go to /' rm -rf "$tempdir" rm -rf "$hh_tmpdir" exit 0
Python
hhvm/hphp/hack/test/integration/hh_paths.py
from __future__ import absolute_import, division, print_function, unicode_literals import os import sys from typing import List # Any python_unittest target which directly or indirectly uses the hh_paths library # must set these four environment variables: # env = { # "HACKFMT_TEST_PATH": "$(exe_target //hphp/hack/src:hackfmt)", # "HH_CLIENT_PATH": "$(exe_target //hphp/hack/src:hh_client_precopy)", # "HH_FANOUT_PATH": "$(exe_target //hphp/hack/src/hh_fanout:hh_fanout)", # "HH_SERVER_PATH": "$(exe_target //hphp/hack/src:hh_server_precopy)", # }, # Then, they can use hh_paths.{hackfmt,hh_client,hh_fanout,hh_server} confident in the # knowledge that these will be absolute paths which point to existing binaries, # and moreover that hh_server and hh_client are in the same directory. # It's an all-or-nothing deal for convenience -- even tests that only use some of these binaries # must use all of them. # # How does it work? Because the unit test has $(exe_target), then buck2 knows that even if the exe # had been built on a different machine, it must still be fetched from CAS and placed into # the appropriate path in buck-out on the machine that's running the unit test. # # Why use $(exe_target) ? # $(exe) - for tools needed for doing work on the host machine; is typically NOSAN # $(exe_target) - for the binaries you aim to test; in dev mode is ASAN by default. # $(location) - doesn't specify anything about the binary! # # GOTCHA 1. clientStart.ml will use HH_SERVER_PATH if defined, and failing that will look # for "hh_server" in "dirname(realpath(hh_client))/hh_server", and if that doesn't exist # will just use unqualified "hh_server" hence looking it up in the path. # That typically means going via /usr/local/bin/hh_server, which is find_hh.sh. # Also, part of the python tests set HH_HOME=dirname(hh_client) and hence find_hh will use $HH_HOME/hh_server. # But, # we will just use the HH_SERVER_PATH approach! which is already defined by the # unit-test target, and all we do here is verify that it really exists. So we're supporting # two mechanisms: # (1) for any tests which launch hh_client, hh_client will get to use HH_SERVER_PATH # (2) for any tests which launch hh_paths.hh_server, they will launch the correct binary # # GOTCHA 2. serverFormat.ml will use HACKFMT_TEST_PATH if defined and found, otherwise it will # use "/usr/local/bin/hackfmt" (which again is usually find_hh.sh). Our test target is assumed # to have defined it, and all we're doing is verifying that it points to something that exists # on disk. # # GOTCHA 3. Some authorities claim that $(exe/location :foo) produces a repo-relative path # and that our test is run with CWD=repo-root. Other authorites suggest that it produces # an absolute path. We will use os.path.abspath to cover both cases. hackfmt: str = os.path.abspath(os.getenv("HACKFMT_TEST_PATH", "?")) hh_fanout: str = os.path.abspath(os.getenv("HH_FANOUT_PATH", "?")) hh_client: str = os.path.abspath(os.getenv("HH_CLIENT_PATH", "?")) hh_server: str = os.path.abspath(os.getenv("HH_SERVER_PATH", "?")) errors: List[str] = [] if not os.path.exists(hackfmt): errors.append("Not found HACKFMT_TEST_PATH") if not os.path.exists(hh_fanout): errors.append("Not found HH_FANOUT_PATH") if not os.path.exists(hh_client): errors.append("Not found HH_CLIENT_PATH") if not os.path.exists(hh_server): errors.append("Not found HH_SERVER_PATH") if len(errors) > 0: errors: List[str] = [ "CWD=" + os.getcwd(), "HACKFMT_TEST_PATH=" + os.getenv("HACKFMT_TEST_PATH", "?") + " => " + hackfmt, "HH_FANOUT_PATH=" + os.getenv("HH_FANOUT_PATH", "?") + " => " + hh_fanout, "HH_SERVER_PATH=" + os.getenv("HH_SERVER_PATH", "?") + " => " + hh_server, "HH_CLIENT_PATH=" + os.getenv("HH_CLIENT_PATH", "?") + " => " + hh_client, "-------------", ] + errors print("\n".join(errors), file=sys.stderr) exit(1)
Python
hhvm/hphp/hack/test/integration/hierarchy_tests.py
#! /usr/bin/env python3 # pyre-strict from common_tests import CommonTestDriver from test_case import TestCase class HierarchyTests(TestCase[CommonTestDriver]): @classmethod def get_template_repo(cls) -> str: return "hphp/hack/test/integration/data/hierarchy" def test_inheritance(self) -> None: """ Test --inheritance-ancestors and --inheritance-children """ self.test_driver.start_hh_server() self.test_driver.check_cmd( [ 'File "{root}foo.php", line 3, characters 7-9: Foo', ' inherited by File "{root}bar.php", line 3, characters 7-9: Bar', 'File "{root}foo.php", line 4, characters 19-19: Foo::f', ' inherited by File "{root}bar.php", line 4, characters 19-19: Bar::f', 'File "{root}foo.php", line 3, characters 7-9: Foo', ' inherited by File "{root}baz.php", line 3, characters 7-9: Baz', 'File "{root}foo.php", line 5, characters 19-19: Foo::g', ' inherited by File "{root}baz.php", line 4, characters 19-19: Baz::g', ], options=["--inheritance-children", "Foo"], ) self.test_driver.check_cmd( [ 'File "{root}baz.php", line 3, characters 7-9: Baz', ' inherited from File "{root}foo.php", line 3, characters 7-9: Foo', 'File "{root}baz.php", line 4, characters 19-19: Baz::g', ' inherited from File "{root}foo.php", line 5, characters 19-19: Foo::g', 'File "{root}baz.php", line 3, characters 7-9: Baz', ' inherited from File "{root}bar.php", line 3, characters 7-9: Bar', ], options=["--inheritance-ancestors", "Baz"], ) def test_inheritance_filter(self) -> None: self.test_driver.start_hh_server() self.test_driver.check_cmd( [ 'File "{root}filter.php", line 15, characters 7-12: Filter', ' inherited from File "{root}filter.php", line 3, characters 7-13: CFilter', 'File "{root}filter.php", line 18, characters 19-31: Filter::cfilterMethod', ' inherited from File "{root}filter.php", line 4, characters 19-31: CFilter::cfilterMethod', ], options=["--inheritance-ancestor-classes", "Filter"], ) self.test_driver.check_cmd( [ 'File "{root}filter.php", line 15, characters 7-12: Filter', ' inherited from File "{root}filter.php", line 7, characters 11-17: IFilter', 'File "{root}filter.php", line 19, characters 19-31: Filter::ifilterMethod', ' inherited from File "{root}filter.php", line 8, characters 19-31: IFilter::ifilterMethod', ], options=["--inheritance-ancestor-interfaces", "Filter"], ) self.test_driver.check_cmd( [ 'File "{root}filter.php", line 15, characters 7-12: Filter', ' inherited from File "{root}filter.php", line 11, characters 7-13: TFilter', 'File "{root}filter.php", line 20, characters 19-31: Filter::tfilterMethod', ' inherited from File "{root}filter.php", line 12, characters 19-31: TFilter::tfilterMethod', ], options=["--inheritance-ancestor-traits", "Filter"], )
Python
hhvm/hphp/hack/test/integration/jsonrpc_stream.py
# pyre-strict from __future__ import absolute_import, division, print_function, unicode_literals import json from queue import Empty, Queue from threading import Thread from typing import BinaryIO, Optional from utils import Json class JsonRpcStreamReader: def __init__(self, stream: BinaryIO) -> None: self.stream = stream # pyre-fixme[11]: Annotation `Json` is not defined as a type. # pyre-fixme[11]: Annotation `Json` is not defined as a type. self.queue: Queue[Json] = 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, timeout_seconds: float) -> Optional[Json]: try: return self.queue.get(block=True, timeout=timeout_seconds) except Empty: return None def _async_read_loop(self) -> None: while True: try: self.queue.put(json.loads(self._read_payload())) except ValueError: break except IndexError: break def _read_content_length(self) -> int: # 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: int) -> bytes: return self.stream.read(length) def _read_payload(self) -> bytes: length = self._read_content_length() return self._read_content(length) class JsonRpcStreamWriter: def __init__(self, stream: BinaryIO) -> None: self.stream = stream def write(self, json_data: Json) -> None: serialized = json.dumps(json_data) content_length = len(serialized) payload = "Content-Length: {c}\n\n{s}".format(c=content_length, s=serialized) self._write_string(payload) def _write_string(self, s: str) -> None: self.stream.write(s.encode()) self.stream.flush()
Python
hhvm/hphp/hack/test/integration/lspcommand.py
# pyre-strict from __future__ import absolute_import, division, print_function, unicode_literals import contextlib import json import os import pprint import subprocess import urllib import uuid from typing import ( Callable, Iterator, List, Mapping, NamedTuple, Optional, Sequence, Set, Tuple, Type, TypeVar, ) from hh_paths import hh_client from jsonrpc_stream import JsonRpcStreamReader, JsonRpcStreamWriter from utils import Json # pyre-fixme[4]: Attribute must be annotated. class TranscriptEntry(NamedTuple): # pyre-fixme[11]: Annotation `Json` is not defined as a type. # pyre-fixme[11]: Annotation `Json` is not defined as a type. # pyre-fixme[11]: Annotation `Json` is not defined as a type. sent: Optional[Json] received: Optional[Json] def __repr__(self) -> str: return ( "TranscriptEntry" + pprint.pformat({"sent": self.sent, "received": self.received}) + "\n" ) Transcript = Mapping[str, TranscriptEntry] U = TypeVar("U", bound="LspCommandProcessor") class LspCommandProcessor: def __init__( self, # pyre-fixme[24]: Generic type `subprocess.Popen` expects 1 type parameter. proc: subprocess.Popen, reader: JsonRpcStreamReader, writer: JsonRpcStreamWriter, ) -> None: self.proc = proc self.reader = reader self.writer = writer @classmethod @contextlib.contextmanager def create( cls: Type[U], env: Mapping[str, str], lsp_args: List[str], repo_dir: str, ) -> Iterator[U]: args = lsp_args + ["--enhanced-hover", "--verbose"] proc = subprocess.Popen( [hh_client, "lsp"] + args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None, # so hh_client inherits (=> writes to) our own stderr env=env, cwd=repo_dir, ) # Use the unbuffered versions of these streams, as the buffered versions # of these streams sometimes cause deadlocks when accessed from multiple # threads. stdin = proc.stdin.detach() # pyre-ignore stdout = proc.stdout.detach() try: reader = JsonRpcStreamReader(stdout) writer = JsonRpcStreamWriter(stdin) yield cls(proc, reader, writer) finally: stdin.close() stdout.close() # 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: Sequence[Json], request_timeout: float = 30, notify_timeout: float = 1, ) -> Transcript: transcript = self._send_commands({}, json_commands) transcript = self._wait_for_shutdown(transcript) # 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. dummy_id = LspCommandProcessor.dummy_request_id() transcript = self._read_extra_responses(transcript, notify_timeout) return {k: v for k, v in transcript.items() if k != dummy_id} def _send_commands( self, transcript: Transcript, commands: Sequence[Json] ) -> Transcript: processed_transcript_ids = set() for command in commands: if command["method"] == "$test/waitForRequest": (transcript, processed_transcript_ids) = self._wait_for_request( transcript, command, processed_transcript_ids=processed_transcript_ids, ) elif command["method"] == "$test/waitForResponse": transcript = self._wait_for_response( transcript, command["params"]["id"] ) elif command["method"] == "$test/waitForNotification": (transcript, processed_transcript_ids) = self._wait_for_notification( transcript, command, processed_transcript_ids=processed_transcript_ids, ) elif command["method"] == "$test/waitForHhServerReady": # Hack: HackLSP server only connects to hh_server asynchronously. # We want to delay until after it's connected before testing more. transcript = self._wait_for_initialized(transcript) elif command["method"] == "$test/writeToDisk": self._write_to_disk(command) else: self.writer.write(command) transcript = self._scribe(transcript, sent=command, received=None) return transcript def _wait_for_initialized(self, transcript: Transcript) -> Transcript: dummy_command = { "jsonrpc": "2.0", "method": "workspace/symbol", "id": -1, "params": {"query": "my test query"}, } id = self._client_request_id(dummy_command["id"]) def has_error_message(entry: TranscriptEntry, message: str) -> bool: if ( entry.received is None or entry.received.get("error") is None or entry.received["error"].get("message") is None ): return False else: return message in entry.received["error"]["message"] while True: transcript = dict(transcript) if id in transcript: del transcript[id] transcript = self._send_commands(transcript, [dummy_command]) transcript = self._wait_for_response( transcript, request_id=dummy_command["id"] ) if not has_error_message( transcript[id], "Server busy" ) and not has_error_message(transcript[id], "hh_server initializing"): return transcript def _wait_for_shutdown(self, transcript: Transcript) -> Transcript: shutdown_commands = [ v.sent for v in transcript.values() if v.sent is not None and v.sent.get("method") == "shutdown" ] num_shutdown_commands = len(shutdown_commands) assert num_shutdown_commands == 1, ( "Expected this test case to have sent " + "exactly 1 shutdown command to wait for, " + f"but instead got {num_shutdown_commands}. " + "If you are writing an LSP test, " + "make sure that you have exactly one `shutdown` command at the end, " + "as we wait for that `shutdown` command to return " + "to know when the test is done running. " + f"Here are the shutdown commands I saw: {shutdown_commands}" ) [shutdown_command] = shutdown_commands return self._wait_for_response(transcript, shutdown_command["id"]) def _wait_for_response( self, transcript: Transcript, request_id: Json ) -> Transcript: transcript_id = self._client_request_id(request_id) request = transcript[transcript_id].sent while transcript[transcript_id].received is None: message = self._try_read_logged(timeout_seconds=120.0) assert message is not None, ( f"Timed out while waiting for the response to request {transcript_id}. " + f"Here is the request: {request}. " + f"Here is the transcript so far: {transcript}" ) transcript = self._scribe(transcript, sent=None, received=message) return transcript def _wait_for_message_from_server( self, transcript: Transcript, comment: Optional[str], method: str, params: Json, processed_transcript_ids: Set[int], ) -> Tuple[Transcript, str, Json]: def is_target_message(transcript_id: str, entry: TranscriptEntry) -> bool: return ( transcript_id not in processed_transcript_ids and entry.received is not None and entry.received.get("method") == method and entry.received.get("params") == params ) while not any( is_target_message(transcript_id, entry) for transcript_id, entry in transcript.items() ): timeout_seconds = 30.0 message = self._try_read_logged(timeout_seconds=timeout_seconds) comment = comment or "<none>" assert ( message is not None ), f"""\ Timed out after {timeout_seconds} seconds while waiting for a {method!r} message to be sent from the server (comment: {comment}), which must not have an ID in {processed_transcript_ids!r}. The message was expected to have params: {json.dumps(params, indent=2)} Transcript of all the messages we saw: {json.dumps(transcript, indent=2)}""" transcript = self._scribe(transcript, sent=None, received=message) [(transcript_id, message)] = [ (transcript_id, entry.received) for transcript_id, entry in transcript.items() if is_target_message(transcript_id, entry) ] return (transcript, transcript_id, message) def _wait_for_request( self, transcript: Transcript, command: Json, processed_transcript_ids: Set[str] ) -> Tuple[Transcript, Set[str]]: comment = command["comment"] method = command["params"]["method"] params = command["params"]["params"] (transcript, transcript_id, message) = self._wait_for_message_from_server( transcript, comment=comment, method=method, params=params, # pyre-fixme[6]: Expected `Set[int]` for 5th param but got `Set[str]`. processed_transcript_ids=processed_transcript_ids, ) # Ensure that we don't double-count one received request as having # responded to multiple wait-for-request instructions. processed_transcript_ids = set(processed_transcript_ids) processed_transcript_ids.add(transcript_id) if "result" in command["params"]: response = { "jsonrpc": 2.0, "id": message["id"], "result": command["params"]["result"], } self.writer.write(response) else: response = { "jsonrpc": 2.0, "id": message["id"], "result": "<acknowledged this message, but did not send a response>", } # Record that we responded to this message so that we don't flag it # later as a message we didn't handle. transcript = self._scribe(transcript, sent=response, received=None) return (transcript, processed_transcript_ids) def _wait_for_notification( self, transcript: Transcript, command: Json, processed_transcript_ids: Set[str] ) -> Tuple[Transcript, Set[str]]: comment = command["comment"] method = command["params"]["method"] params = command["params"]["params"] (transcript, transcript_id, _message) = self._wait_for_message_from_server( transcript, comment=comment, method=method, params=params, # pyre-fixme[6]: Expected `Set[int]` for 5th param but got `Set[str]`. processed_transcript_ids=processed_transcript_ids, ) processed_transcript_ids = set(processed_transcript_ids) processed_transcript_ids.add(transcript_id) return (transcript, processed_transcript_ids) def _write_to_disk(self, command: Json) -> None: params = command["params"] path = urllib.parse.urlparse(params["uri"]).path contents = params["contents"] if contents is not None: with open(path, "w") as f: f.write(contents) else: os.remove(path) def _read_request_responses( self, transcript: Transcript, commands: Sequence[Json], timeout_seconds: float ) -> Transcript: for _ in self._requests_in(commands): response = self._try_read_logged(timeout_seconds) if response: transcript = self._scribe(transcript, sent=None, received=response) return transcript def _read_extra_responses( self, transcript: Transcript, timeout_seconds: float ) -> Transcript: while True: response = self._try_read_logged(timeout_seconds) if not response: break transcript = self._scribe(transcript, sent=None, received=response) return transcript def _scribe( self, transcript: Transcript, sent: Optional[Json], received: Optional[Json] ) -> Transcript: transcript = dict(transcript) id = self._transcript_id(sent, received) existing_entry = transcript.get(id) if existing_entry: if not sent: sent = existing_entry.sent if not received: received = existing_entry.received assert sent is not None or received is not None transcript[id] = TranscriptEntry(sent=sent, received=received) return transcript def _transcript_id(self, sent: Optional[Json], received: Optional[Json]) -> str: assert sent is not None or received is not None def make_id( json: Json, is_client_request: bool, idgen: Callable[[], str] ) -> str: if LspCommandProcessor._has_id(json): if is_client_request: return LspCommandProcessor._client_request_id(json["id"]) else: return LspCommandProcessor._server_request_id(json["id"]) else: return idgen() if sent: is_client_request = LspCommandProcessor._is_request(sent) return make_id( sent, is_client_request, LspCommandProcessor._client_notify_id ) elif received: is_client_request = not LspCommandProcessor._is_request(received) return make_id( received, is_client_request, LspCommandProcessor._server_notify_id ) else: raise Exception("This should have failed up above in the assert") def _requests_in(self, commands: Sequence[Json]) -> Sequence[Json]: return [c for c in commands if LspCommandProcessor._has_id(c)] def _try_read_logged(self, timeout_seconds: float) -> Optional[Json]: response = self.reader.read(timeout_seconds) return response @staticmethod def _has_id(json: Json) -> bool: return "id" in json @staticmethod def _is_request(json: Json) -> bool: return "id" in json and "method" in json @staticmethod def _client_notify_id() -> str: return LspCommandProcessor._notify_id("NOTIFY_CLIENT_TO_SERVER_") @staticmethod def _server_notify_id() -> str: return LspCommandProcessor._notify_id("NOTIFY_SERVER_TO_CLIENT_") @staticmethod def _notify_id(prefix: str) -> str: return prefix + str(uuid.uuid4()) @staticmethod def _client_request_id(id: Json) -> str: return "REQUEST_CLIENT_TO_SERVER_" + str(id) @staticmethod def _server_request_id(id: Json) -> str: return "REQUEST_SERVER_TO_CLIENT_" + str(id) @staticmethod def dummy_request_id() -> str: return LspCommandProcessor._client_request_id(-1)
Python
hhvm/hphp/hack/test/integration/lsptestspec.py
# pyre-strict from __future__ import absolute_import, division, print_function, unicode_literals import copy import difflib import inspect import itertools import os.path import pprint import textwrap from dataclasses import dataclass from typing import ( AbstractSet, Iterable, List, Mapping, Optional, Sequence, Tuple, Union, ) import libcst from libcst.metadata import CodeRange, MetadataWrapper, PositionProvider from lspcommand import LspCommandProcessor, Transcript, TranscriptEntry from utils import ( fixup_hhi_json, interpolate_variables, Json, uninterpolate_variables, VariableMap, ) _MessageSpec = Union[ "_RequestSpec", "_DebugRequestSpec", "_NotificationSpec", "_WaitForNotificationSpec", "_WaitForRequestSpec", "_WaitForResponseSpec", "_WaitForHhServerReadySpec", ] # pyre-fixme[5]: Global expression must be annotated. _LspIdMap = Mapping[_MessageSpec, Json] _Traceback = Sequence[inspect.FrameInfo] @dataclass class _CallSiteInfo: line_num: int traceback: _Traceback class NoResponse: """Indicates that no response should be sent (different from `None` since `None` is a valid JSON value).""" pass def line() -> int: """Get the line number that this function was called at. Previously, we used to do this automatically whenever we called `.request`. However, a recent upgrade of Python breaks that functionality for chained function calls in some cases, and it instead reports the line number of the first function call in the chain. We use `line()` to ensure that we don't have a chained function call and can get the line number accurately. """ cf = inspect.currentframe() assert ( cf is not None ), "Must be able to get current call frame to produce error messages for test" # pyre-fixme[16]: `Optional` has no attribute `f_lineno`. return cf.f_back.f_lineno class LspTestSpec: """Represents an LSP test to be run, in a declarative fashion. Since `LspTestSpec`s are just values, they can be composed using regular functions. For example, you can make an `initialize_spec` function that returns an `LspTestSpec` with the `initialize` request already sent and checked.""" def __init__(self, name: str) -> None: self.name = name self._messages: Sequence["_MessageSpec"] = [] self._ignored_notification_methods: AbstractSet[str] = set() # pyre-fixme[11]: Annotation `Json` is not defined as a type. self._ignored_requests: Sequence[Tuple[str, Optional[Json]]] = [] def ignore_notifications(self, *, method: str) -> "LspTestSpec": """For example .ignore_notifications(method="textDocument/publishDiagnostics") -- normally an unexpected notification from the LSP server would result in test failure, but this directive means that unexpected notifications with this exact method name do not.""" ignored_notification_methods = set(self._ignored_notification_methods) ignored_notification_methods.add(method) return self._update(ignored_notification_methods=ignored_notification_methods) def ignore_requests( self, *, method: str, params: Optional[Json], comment: Optional[str] = None ) -> "LspTestSpec": """For example .ignore_requests(comment="for_tester", method="window/showStatus", params={"type":2}) -- normally an unexpected request from the LSP server would result in test failure, but this directive means that unexpected requests with this exact method name and params do not. If you pass params=None then unexpected requests with this exact method name and *any* params do not. Typically used for window/showStatus messages!""" ignored_requests = list(self._ignored_requests) ignored_requests.append((method, params)) return self._update(ignored_requests=ignored_requests) def request( self, line: int, method: str, params: Json, *, result: Json, wait_id: Optional[str] = None, comment: Optional[str] = None, powered_by: Optional[str] = None, ) -> "LspTestSpec": """Add a request to this test's messages.""" traceback = inspect.stack() assert traceback is not None, "Failed to get traceback info" messages = list(self._messages) if wait_id is not None and any( isinstance(message, _RequestSpec) and message.wait_id == wait_id for message in messages ): raise ValueError(f"Duplicate wait ID: {wait_id}") messages.append( _RequestSpec( method=method, params=params, result=result, wait_id=wait_id, comment=comment, powered_by=powered_by, call_site_info=_CallSiteInfo(line_num=line, traceback=traceback), ) ) return self._update(messages=messages) def debug(self) -> "LspTestSpec": """Issue a `telemetry/rage` request for debugging. The language server has to support the `telemetry/rage` request. Once the response is received, its debugging output is rendered in the test output. This can be useful when trying to debug the internal state of the language server. The test will not pass while there's a `debug()` statement in its spec, so it must be removed before committing the code. """ messages = list(self._messages) messages.append(_DebugRequestSpec()) return self._update(messages=messages) def notification( self, method: str, params: Json, *, comment: Optional[str] = None ) -> "LspTestSpec": messages = list(self._messages) messages.append( _NotificationSpec(method=method, params=params, comment=comment) ) return self._update(messages=messages) def wait_for_server_request( self, method: str, params: Json, *, result: Union[Json, NoResponse], comment: Optional[str] = None, ) -> "LspTestSpec": messages = list(self._messages) messages.append( _WaitForRequestSpec( method=method, params=params, result=result, comment=comment ) ) return self._update(messages=messages) def wait_for_notification( self, method: str, params: Json, *, comment: Optional[str] = None ) -> "LspTestSpec": messages = list(self._messages) messages.append( _WaitForNotificationSpec(method=method, params=params, comment=comment) ) return self._update(messages=messages) def wait_for_response(self, wait_id: str) -> "LspTestSpec": messages = list(self._messages) messages.append(_WaitForResponseSpec(wait_id=wait_id)) return self._update(messages=messages) def wait_for_hh_server_ready(self) -> "LspTestSpec": messages = list(self._messages) messages.append(_WaitForHhServerReadySpec()) return self._update(messages=messages) def start_hh_server(self, comment: str) -> "LspTestSpec": return self.request( line=line(), comment=comment, method="$test/startHhServer", params=None, result=None, powered_by="serverless_ide", ) def stop_hh_server(self, comment: str) -> "LspTestSpec": return self.request( line=line(), comment=comment, method="$test/stopHhServer", params=None, result=None, powered_by="serverless_ide", ) def write_to_disk( self, *, comment: Optional[str] = None, uri: str, contents: Optional[str], notify: bool, ) -> "LspTestSpec": """Write a file to disk in the middle of the LSP test. If `contents` is `None`, delete the file from disk. If `notify` is `True`, also send a `workspace/didChangeWatchedFiles` notification to the language server corresponding to the file you just changed. """ messages = list(self._messages) messages.append( _NotificationSpec( method="$test/writeToDisk", params={"uri": uri, "contents": contents}, comment=comment, ) ) if notify: messages.append( _NotificationSpec( method="workspace/didChangeWatchedFiles", params={"changes": [{"uri": uri, "type": 2}]}, comment=comment, ) ) return self._update(messages=messages) def run( self, lsp_command_processor: LspCommandProcessor, variables: VariableMap ) -> Tuple[Transcript, Optional[str]]: """Run the test given the LSP command processor. Raises an exception with useful debugging information if the test fails.""" (json_commands, lsp_id_map) = self._get_json_commands(variables=variables) transcript = lsp_command_processor.communicate(json_commands=json_commands) errors = list( self._verify_transcript( variables=variables, transcript=transcript, lsp_id_map=lsp_id_map ) ) if errors: num_errors = len(errors) error_details = ( f"Test case {self.name} failed with {num_errors} errors:\n\n" ) for i, error in enumerate(errors, 1): error_details += f"Error {i}/{num_errors}:\n" error_details += str(error) + "\n" error_details += """\ If you want to examine the raw LSP logs, you can check the `.sent.log` and `.received.log` files that were generated in the template repo for this test.""" else: error_details = None return (transcript, error_details) ### Internal. ### def _update( self, messages: Optional[Sequence["_MessageSpec"]] = None, ignored_notification_methods: Optional[AbstractSet[str]] = None, ignored_requests: Optional[Sequence[Tuple[str, Json]]] = None, ) -> "LspTestSpec": spec = copy.copy(self) if messages is not None: spec._messages = messages if ignored_notification_methods is not None: spec._ignored_notification_methods = ignored_notification_methods if ignored_requests is not None: spec._ignored_requests = ignored_requests return spec def _get_json_commands( self, variables: VariableMap # pyre-fixme[11]: Annotation `_LspIdMap` is not defined as a type. ) -> Tuple[Sequence[Json], "_LspIdMap"]: """Transforms this test spec into something the LSP command processor can interpret.""" json_commands = [] lsp_id_map = {} current_id = 0 for message in self._messages: current_id += 1 lsp_id_map[message] = current_id if isinstance(message, _RequestSpec): json_commands.append( { "jsonrpc": "2.0", "comment": message.comment, "id": current_id, "method": message.method, "params": interpolate_variables( message.params, variables=variables ), } ) if message.wait_id is None: # Assume that if no wait ID was explicitly passed, we want # to wait on the response before sending the next message. json_commands.append( { "jsonrpc": "2.0", "method": "$test/waitForResponse", "params": {"id": current_id}, } ) elif isinstance(message, _DebugRequestSpec): json_commands.append( { "jsonrpc": "2.0", "id": current_id, "method": "telemetry/rage", "params": {}, } ) elif isinstance(message, _NotificationSpec): json_commands.append( { "jsonrpc": "2.0", "comment": message.comment, "method": message.method, "params": interpolate_variables( message.params, variables=variables ), } ) elif isinstance(message, _WaitForRequestSpec): params = { "method": message.method, "params": interpolate_variables( message.params, variables=variables ), } if not isinstance(message.result, NoResponse): params["result"] = message.result json_commands.append( { "jsonrpc": "2.0", "comment": message.comment, "method": "$test/waitForRequest", "params": params, } ) elif isinstance(message, _WaitForNotificationSpec): json_commands.append( { "jsonrpc": "2.0", "comment": message.comment, "method": "$test/waitForNotification", "params": { "method": message.method, "params": interpolate_variables( message.params, variables=variables ), }, } ) elif isinstance(message, _WaitForResponseSpec): lsp_ids = [ lsp_id for previous_message, lsp_id in lsp_id_map.items() if isinstance(previous_message, _RequestSpec) and previous_message.wait_id == message.wait_id ] assert len(lsp_ids) == 1, ( f"Should have had exactly one previous message with wait ID {message.wait_id!r}, " # noqa: B950 + "but got {len(lsp_ids)}" ) [lsp_id] = lsp_ids json_commands.append( { "jsonrpc": "2.0", "method": "$test/waitForResponse", "params": {"id": lsp_id}, } ) elif isinstance(message, _WaitForHhServerReadySpec): json_commands.append( { "jsonrpc": "2.0", "method": "$test/waitForHhServerReady", "params": {}, } ) else: raise ValueError(f"unhandled message type {message.__class__.__name__}") return (json_commands, lsp_id_map) def _verify_transcript( self, *, variables: VariableMap, transcript: Transcript, lsp_id_map: "_LspIdMap" ) -> Iterable["_ErrorDescription"]: handled_entries = set() for message in self._messages: lsp_id = lsp_id_map[message] if isinstance(message, _RequestSpec): transcript_id = LspCommandProcessor._client_request_id(lsp_id) handled_entries.add(transcript_id) assert transcript_id in transcript, ( f"Expected message with ID {lsp_id!r} to have an entry in the transcript " + f"under key {transcript_id!r}, " + f"but it was not found. Transcript: {transcript!r}" ) entry = transcript[transcript_id] error_description = self._verify_request( variables=variables, entry=entry, lsp_id=lsp_id, request=message ) if error_description is not None: yield error_description elif isinstance(message, _DebugRequestSpec): transcript_id = LspCommandProcessor._client_request_id(lsp_id) handled_entries.add(transcript_id) assert transcript_id in transcript, ( f"Expected message with ID {lsp_id!r} to have an entry in the transcript " + f"under key {transcript_id!r}, " + f"but it was not found. Transcript: {transcript!r}" ) entry = transcript[transcript_id] error_description = self._render_telemetry_rage( debug_request=message, result=entry.received["result"] ) yield error_description elif isinstance(message, _NotificationSpec): # Nothing needs to be done here, since we sent the notification # and don't expect a response. pass elif isinstance( message, ( _WaitForRequestSpec, _WaitForNotificationSpec, _WaitForResponseSpec, _WaitForHhServerReadySpec, ), ): # Nothing needs to be done here -- if we failed to wait for the # message, an exception will have been thrown at the # `LspCommandProcessor` layer. pass else: raise ValueError(f"unhandled message type {message.__class__.__name__}") handled_entries |= set(self._find_ignored_transcript_ids(transcript)) yield from self._flag_unhandled_messages( handled_entries, variables, transcript, lsp_id_map ) def _verify_request( self, *, variables: VariableMap, lsp_id: Json, entry: TranscriptEntry, request: "_RequestSpec", ) -> Optional["_ErrorDescription"]: actual_result = entry.received.get("result") actual_powered_by = entry.received.get("powered_by") if request.comment is not None: request_description = ( f"Request with ID {lsp_id!r} (comment: {request.comment!r})" ) else: request_description = f"Request with ID {lsp_id!r}" # Because of the way hack allocates a different HHI folder for each running # process, let's replace the standard HHI foldername actual_result = fixup_hhi_json(actual_result) expected_result = interpolate_variables( payload=request.result, variables=variables ) expected_result = fixup_hhi_json(expected_result) if actual_result != expected_result: error_description = self._pretty_print_diff( actual=actual_result, expected=expected_result ) description = f"""\ {request_description} got an incorrect result: {error_description}""" request_context = self._get_context_for_call_site_info( request.call_site_info ) context = f"""\ This was the associated request: {request_context}""" remediation = self._describe_response_for_remediation( variables=variables, request=request, actual_response=entry.received ) return _ErrorDescription( description=description, context=context, remediation=remediation ) elif entry.received.get("powered_by") != request.powered_by: description = f"""\ {request_description} had an incorrect value for the `powered_by` field (expected {request.powered_by!r}; got {actual_powered_by!r}) """ request_context = self._get_context_for_call_site_info( request.call_site_info ) context = f"""\ This was the associated request: {request_context}""" remediation = self._describe_response_for_remediation( variables=variables, request=request, actual_response=entry.received ) return _ErrorDescription( description=description, context=context, remediation=remediation ) def _get_context_for_call_site_info(self, call_site_info: _CallSiteInfo) -> str: # Find the first caller frame that isn't in this source file. The # assumption is that the first such frame is in the test code. caller_frame = next( frame for frame in call_site_info.traceback if frame.filename != __file__ ) source_filename = caller_frame.filename with open(source_filename) as f: source_text = f.read() ( start_line_num_0idx_incl, end_line_num_0idx_incl, ) = self._find_line_range_for_function_call( file_contents=source_text, line_num_1idx=call_site_info.line_num ) return self._pretty_print_file_context( file_path=source_filename, file_contents=source_text, start_line_num_0idx_incl=start_line_num_0idx_incl, end_line_num_0idx_incl=end_line_num_0idx_incl, ) def _find_line_range_for_function_call( self, file_contents: str, line_num_1idx: int ) -> Tuple[int, int]: tree = libcst.parse_module(file_contents) function_call_finder = _FunctionCallFinder() MetadataWrapper(tree).visit(function_call_finder) function_calls_containing_line = [ (node, node_range) for node, node_range in function_call_finder.function_calls if node_range.start.line <= line_num_1idx <= node_range.end.line ] node_range = max( function_calls_containing_line, key=lambda node_with_range: node_with_range[1].end.line - node_with_range[1].start.line, )[1] start_line_num_0idx_incl = node_range.start.line - 1 end_line_num_0idx_incl = node_range.end.line - 1 return (start_line_num_0idx_incl, end_line_num_0idx_incl) def _pretty_print_file_context( self, file_path: str, file_contents: str, start_line_num_0idx_incl: int, end_line_num_0idx_incl: int, ) -> str: source_lines = file_contents.splitlines(keepends=True) context_lines = source_lines[ start_line_num_0idx_incl : end_line_num_0idx_incl + 1 ] context_lines = [ # Include the line number in a gutter for display. f"{line_num:>5} | {line_contents}" for line_num, line_contents in enumerate( context_lines, start=start_line_num_0idx_incl + 1 ) ] file_context = "".join(context_lines) # The full path is likely not useful, since it includes any temporary # directories that Buck introduced. prefix = os.path.commonprefix([file_path, __file__]) display_filename = file_path[len(prefix) :] return display_filename + "\n" + file_context def _describe_response_for_remediation( self, variables: VariableMap, request: "_RequestSpec", actual_response: Json ) -> str: method = request.method params = request.params result = uninterpolate_variables( payload=actual_response.get("result"), variables=variables ) powered_by = actual_response.get("powered_by") request_snippet = """\ .request( line=line(),""" if request.comment is not None: request_snippet += f""" comment={request.comment!r},""" request_snippet += f""" method={method!r}, params={params!r}, result={result!r},""" if request.wait_id is not None: request_snippet += f""" wait_id={request.wait_id!r},""" if powered_by is not None: request_snippet += f""" powered_by={powered_by!r},""" request_snippet += """ )""" remediation = f"""\ 1) If this was unexpected, then the language server is buggy and should be fixed. 2) If this was expected, you can update your request with the following code to make it match: {request_snippet} """ return remediation def _find_ignored_transcript_ids(self, transcript: Transcript) -> Iterable[str]: for transcript_id, entry in transcript.items(): if ( entry.received is not None and "id" not in entry.received and entry.received.get("method") in self._ignored_notification_methods ): yield transcript_id if ( entry.received is not None and "id" in entry.received and "method" in entry.received and "params" in entry.received and ( (entry.received["method"], entry.received["params"]) in self._ignored_requests or (entry.received["method"], None) in self._ignored_requests ) ): yield transcript_id def _flag_unhandled_messages( self, handled_entries: AbstractSet[str], variables: VariableMap, transcript: Transcript, lsp_id_map: _LspIdMap, ) -> Iterable["_ErrorDescription"]: for transcript_id, entry in transcript.items(): if transcript_id in handled_entries: continue received = entry.received if received is None: continue if entry.sent is not None: # We received a request and responded to it. continue method = received["method"] params = received["params"] payload = self._pretty_print_snippet(received) if "id" in received: description = f"""\ An unexpected request of type {method!r} was sent by the language server. Here is the request payload: {payload} """ at_nocommit = "@" + "nocommit" remediation = f"""\ 1) If this was unexpected, then the language server is buggy and should be fixed. 2) If all requests of type {method!r} with theses params should be ignored, add this directive anywhere in your test: .{self.ignore_requests.__name__}(method={method!r}, params={params!r}) 3) To handle this request, add this directive to your test to wait for it and respond to it before proceeding: .{self.wait_for_server_request.__name__}( method={method!r}, params={params!r}, result={{ "{at_nocommit}": "fill in request data here", }}, ) """ else: if any( isinstance(message, _WaitForNotificationSpec) and message.method == method and interpolate_variables( payload=message.params, variables=variables ) == params for message in self._messages ): # This was a notification we we explicitly waiting for, so skip # it. continue uninterpolated_params = uninterpolate_variables( payload=params, variables=variables ) description = f"""\ An unexpected notification of type {method!r} was sent by the language server. Here is the notification payload: {payload} """ remediation = f"""\ 1) If this was unexpected, then the language server is buggy and should be fixed. 2) If all notifications of type {method!r} should be ignored, add this directive anywhere in your test: .{self.ignore_notifications.__name__}(method={method!r}) 3) If this single instance of the notification was expected, add this directive to your test to wait for it before proceeding: .{self.wait_for_notification.__name__}( method={method!r}, params={uninterpolated_params!r}, ) """ previous_request = self._find_previous_request( transcript, lsp_id_map, current_id=transcript_id ) if previous_request is not None: request_context = self._get_context_for_call_site_info( previous_request.call_site_info ) else: request_context = "<no previous request was found>" context = f"""\ This was the most recent request issued from the language client before it received the notification: {request_context}""" yield _ErrorDescription( description=description, context=context, remediation=remediation ) def _find_previous_request( self, transcript: Transcript, lsp_id_map: _LspIdMap, current_id: str ) -> Optional["_RequestSpec"]: previous_transcript_entries = itertools.takewhile( lambda kv: kv[0] != current_id, transcript.items() ) previous_request_entries = [ entry.sent for _id, entry in previous_transcript_entries if entry.sent is not None and LspCommandProcessor._is_request(entry.sent) ] if previous_request_entries: previous_request_lsp_id = previous_request_entries[-1]["id"] else: return None [corresponding_request] = [ request for request, lsp_id in lsp_id_map.items() if lsp_id == previous_request_lsp_id ] assert isinstance( corresponding_request, _RequestSpec ), "We should have identified a client-to-server request at this point" return corresponding_request def _render_telemetry_rage( self, debug_request: "_DebugRequestSpec", result: Json ) -> "_ErrorDescription": sections = [] for row in result: title = row["title"] if title is None: title = "<none>" data = row.get("data") sections.append( f"""\ ### Section {title} ### {data} """ ) sections = textwrap.indent("".join(sections), prefix=" ") description = f"""\ Here are the results of issuing a `telemetry/rage` request to the language server: {sections}""" context = """\ <none> """ remediation = """\ Remove this `debug` request once you're done debugging. """ return _ErrorDescription( description=description, context=context, remediation=remediation ) def _pretty_print_snippet(self, obj: object) -> str: return textwrap.indent(pprint.pformat(obj), prefix=" ") def _pretty_print_diff(self, actual: object, expected: object) -> str: # Similar to the standard library's `unittest` module: # https://github.com/python/cpython/blob/35d9c37e271c35b87d64cc7422600e573f3ee244/Lib/unittest/case.py#L1147-L1149 # noqa B950 return ( "(- is expected lines, + is actual lines)\n" + "\n".join( difflib.ndiff( pprint.pformat(expected).splitlines(), pprint.pformat(actual).splitlines(), ) ) + "\n" ) ### Internal. ### class _FunctionCallFinder(libcst.CSTVisitor): """Find function calls and their locations in the given syntax tree. Chained function calls include the entire chain as the callee. For example, the chain `x().y().z()` might include `x().y().z` as the callee and `()` as the function call itself. But in the case of function call chains, we really want just the range covered by the parentheses. However, that's not directly available in `libcst`, so we approximate this by finding the location of `z` and assume that's where the function call starts. """ METADATA_DEPENDENCIES = (PositionProvider,) def __init__(self) -> None: self.function_calls: List[Tuple[libcst.Call, CodeRange]] = [] def visit_Call(self, node: libcst.Call) -> None: node_range = self.get_metadata(PositionProvider, node) start_node = node.func while isinstance(start_node, libcst.Attribute): start_node = start_node.attr start_node_range = self.get_metadata(PositionProvider, start_node) start_position = start_node_range.start end_position = node_range.end node_range = CodeRange(start=start_position, end=end_position) self.function_calls.append((node, node_range)) class _RequestSpec: __slots__ = [ "method", "params", "result", "wait_id", "comment", "powered_by", "call_site_info", ] def __init__( self, *, method: str, params: Json, result: Json, wait_id: Optional[str], comment: Optional[str], powered_by: Optional[str], call_site_info: _CallSiteInfo, ) -> None: # pyre-fixme[4]: Attribute must be annotated. self.method = method # pyre-fixme[4]: Attribute must be annotated. self.params = params # pyre-fixme[4]: Attribute must be annotated. self.result = result # pyre-fixme[4]: Attribute must be annotated. self.wait_id = wait_id # pyre-fixme[4]: Attribute must be annotated. self.comment = comment # pyre-fixme[4]: Attribute must be annotated. self.powered_by = powered_by # pyre-fixme[4]: Attribute must be annotated. self.call_site_info = call_site_info class _DebugRequestSpec: pass class _NotificationSpec: __slots__ = ["method", "params", "comment"] def __init__(self, *, method: str, params: Json, comment: Optional[str]) -> None: # pyre-fixme[4]: Attribute must be annotated. self.method = method # pyre-fixme[4]: Attribute must be annotated. self.params = params # pyre-fixme[4]: Attribute must be annotated. self.comment = comment class _WaitForRequestSpec: __slots__ = ["method", "params", "result", "comment"] def __init__( self, *, method: str, params: Json, result: Union[Json, NoResponse], comment: Optional[str], ) -> None: # pyre-fixme[4]: Attribute must be annotated. self.method = method # pyre-fixme[4]: Attribute must be annotated. self.params = params # pyre-fixme[4]: Attribute must be annotated. self.result = result # pyre-fixme[4]: Attribute must be annotated. self.comment = comment class _WaitForNotificationSpec: __slots__ = ["method", "params", "comment"] def __init__(self, *, method: str, params: Json, comment: Optional[str]) -> None: # pyre-fixme[4]: Attribute must be annotated. self.method = method # pyre-fixme[4]: Attribute must be annotated. self.params = params # pyre-fixme[4]: Attribute must be annotated. self.comment = comment class _WaitForResponseSpec: __slots__ = ["wait_id"] def __init__(self, *, wait_id: str) -> None: # pyre-fixme[4]: Attribute must be annotated. self.wait_id = wait_id class _WaitForHhServerReadySpec: pass class _ErrorDescription: def __init__(self, description: str, context: str, remediation: str) -> None: self.description = description self.context = context self.remediation = remediation def __str__(self) -> str: result = f"""\ Description: {self.description} """ if self.context is not None: result += f"""\ Context: {self.context} """ result += f"""\ Remediation: {self.remediation}""" return result
Shell Script
hhvm/hphp/hack/test/integration/lsp_delayUntilDoneInit.sh
#!/bin/bash # This test makes sure that hh_client lsp respects delayUntilDoneInit HH_CLIENT="$1" NAMING_TABLE=$(realpath "$2") ROOT=$(realpath "$3") FILE=$(realpath "$3/foo_1.php") # this is a file which I know exists in simple-repo cd "$ROOT" || exit 1 # because "hh_client lsp" must be launched from root { CMD1=$(cat <<EOF { "jsonrpc": "2.0", "id":1, "method":"initialize", "params": { "rootPath": "$ROOT", "rootUri": "file://$ROOT", "initializationOptions": { "namingTableSavedStatePath": "$NAMING_TABLE", "namingTableSavedStateTestDelay": 1.0, "delayUntilDoneInit": true }, "capabilities": { "workspace": { "didChangeWatchedFiles": { "dynamicRegistration": true } } } } } EOF ) printf "Content-Length: %s\r\n\r\n%s" "${#CMD1}" "$CMD1" CMD3=$(cat <<EOF { "jsonrpc": "2.0", "method": "textDocument/didOpen", "params": { "textDocument": { "uri": "file://$FILE", "languageId": "hack", "version": 1, "text": $(jq --slurp --raw-input . "$FILE") } } } EOF ) printf "Content-Length: %s\r\n\r\n%s" "$(printf "%s" "$CMD3" | wc -c)" "$CMD3" CMD4=$(cat <<EOF { "jsonrpc": "2.0", "id": 2, "method": "textDocument/hover", "params": { "textDocument": { "uri": "file://$FILE" }, "position": { "line": 0, "character": 0 } } } EOF ) printf "Content-Length: %s\r\n\r\n%s" "${#CMD4}" "$CMD4" CMD98='{"jsonrpc":"2.0", "id":98, "method":"shutdown"}' printf "Content-Length: %s\r\n\r\n%s" "${#CMD98}" "$CMD98" CMD99='{"jsonrpc":"2.0", "method":"exit"}' printf "Content-Length: %s\r\n\r\n%s" "${#CMD99}" "$CMD99" } | "$HH_CLIENT" lsp | tee >(cat 1>&2) | grep '"id":2,"result":null' # Here we're sending the entire LSP series of requests into the stdin of "hh_client lsp", # and verifying that its responses over stdout include response "null" to our hover request id 2. # If grep fails, then it will have exit code 1, and our test runner will likely # display all of stdout+stderr. Well, the stdout lsp responses have been gobbled up by grep, # but we used "tee" to duplicate them into stderr, so we'll get that in case of failure.
Python
hhvm/hphp/hack/test/integration/saved_state_test_driver.py
# pyre-strict from __future__ import absolute_import, division, print_function, unicode_literals import json import os import shlex import shutil import sys import tempfile from typing import ( Iterable, List, Mapping, NamedTuple, Optional, TextIO, Tuple, TypeVar, Union, ) import common_tests from hh_paths import hh_client, hh_fanout, hh_server T = TypeVar("T") ChangedFile = Union[str, Mapping[str, str]] def write_echo_json(f: TextIO, obj: T) -> None: f.write("echo %s\n" % shlex.quote(json.dumps(obj))) class SaveStateCommandResult(NamedTuple): retcode: int class SaveStateResult(NamedTuple): path: str returned_values: SaveStateCommandResult class SavedStateTestDriver(common_tests.CommonTestDriver): repo_dir: str enable_naming_table_fallback = False saved_state_dir: str @classmethod def setUpClass(cls, template_repo: str) -> None: super().setUpClass(template_repo) # we create the state in a different dir from the one we run our tests # on, to verify that the saved state does not depend on any absolute # paths init_dir = os.path.join(cls.base_tmp_dir, "init") shutil.copytree(cls.template_repo, init_dir) cls.saved_state_dir = tempfile.mkdtemp() cls.save_command(init_dir) cls.proc_call([hh_client, "stop", init_dir]) shutil.rmtree(init_dir) @classmethod def tearDownClass(cls) -> None: super().tearDownClass() shutil.rmtree(cls.saved_state_dir) @classmethod def saved_state_path(cls) -> str: return os.path.join(cls.saved_state_dir, "foo") @classmethod def naming_saved_state_path(cls, base_path: Optional[str]) -> str: if base_path is None: return os.path.join(cls.saved_state_dir, "naming.sql") else: return base_path + "_naming.sql" @classmethod def save_command( cls, init_dir: str, saved_state_path: Optional[str] = None, ignore_errors: bool = False, ) -> SaveStateCommandResult: actual_saved_state_path: str = ( saved_state_path if saved_state_path is not None else cls.saved_state_path() ) edges_dir = tempfile.mkdtemp() hhdg_path = actual_saved_state_path + ".hhdg" # call hh hh_command: List[str] = [ hh_client, "--json", "--save-64bit", edges_dir, "--save-state", actual_saved_state_path, init_dir, "--config", "max_workers=2", ] if ignore_errors: hh_command.append("--gen-saved-ignore-type-errors") stdout, stderr, retcode = cls.proc_call(hh_command) if not (retcode == 0 or (ignore_errors and retcode == 2)): logs = cls.get_all_logs(init_dir) print("STDOUT:\n%s\n\n" % stdout, file=sys.stderr) print("STDERR:\n%s\n\n" % stderr, file=sys.stderr) print("SERVER-LOG:\n%s\n\n" % logs.all_server_logs, file=sys.stderr) print("MONITOR-LOG:\n%s\n\n" % logs.all_monitor_logs, file=sys.stderr) raise Exception("Failed to save!") result = SaveStateCommandResult(retcode) if cls.enable_naming_table_fallback: cls.dump_naming_saved_state(init_dir, saved_state_path) # construct dep graph using hh_fanout _, _, retcode = cls.proc_call( [ hh_fanout, "build", "--output", hhdg_path, "--edges", edges_dir, ] ) assert retcode == 0 return result @classmethod def dump_saved_state( cls, ignore_errors: bool = False, ) -> SaveStateResult: # Dump a saved state to a temporary directory. # Return the path to the saved state. saved_state_path = os.path.join(tempfile.mkdtemp(), "new_saved_state") result: SaveStateCommandResult = cls.save_command( cls.repo_dir, saved_state_path, ignore_errors, ) return SaveStateResult(saved_state_path, result) @classmethod def save_command_incr( cls, init_dir: str, saved_state_path: str, original_saved_state_path: str, ignore_errors: bool = False, ) -> SaveStateCommandResult: delta_file = saved_state_path + "_64bit_dep_graph.delta" hhdg_path = saved_state_path + ".hhdg" original_hhdg_path = original_saved_state_path + ".hhdg" # call hh hh_command: List[str] = [ hh_client, "--json", "--save-state", saved_state_path, init_dir, "--config", "max_workers=2", ] if ignore_errors: hh_command.append("--gen-saved-ignore-type-errors") stdout, stderr, retcode = cls.proc_call(hh_command) if not (retcode == 0 or (ignore_errors and retcode == 2)): raise Exception( 'Failed to save! stdout: "%s" stderr: "%s"' % (stdout, stderr) ) result = SaveStateCommandResult(retcode) if cls.enable_naming_table_fallback: cls.dump_naming_saved_state(init_dir, saved_state_path) # construct dep graph using hh_fanout _, _, retcode = cls.proc_call( [ hh_fanout, "build", "--output", hhdg_path, "--incremental", original_hhdg_path, "--delta", delta_file, ] ) assert retcode == 0 return result @classmethod def dump_saved_state_incr( cls, original_saved_state_result: SaveStateResult, ignore_errors: bool = False, ) -> SaveStateResult: # Dump a saved state to a temporary directory. # Return the path to the saved state. saved_state_path = os.path.join(tempfile.mkdtemp(), "new_saved_state") original_saved_state_path = original_saved_state_result.path result: SaveStateCommandResult = cls.save_command_incr( cls.repo_dir, saved_state_path, original_saved_state_path, ignore_errors, ) return SaveStateResult(saved_state_path, result) @classmethod def dump_naming_saved_state( cls, init_dir: str, saved_state_path: Optional[str] = None ) -> str: naming_saved_state_path = cls.naming_saved_state_path(saved_state_path) cls.proc_call( [ hh_client, "--json", "--save-naming", naming_saved_state_path, init_dir, "--config", "max_workers=2", ] ) return naming_saved_state_path def write_local_conf(self) -> None: with open(os.path.join(self.repo_dir, "hh.conf"), "w") as f: f.write( r""" # some comment use_mini_state = true use_watchman = true watchman_subscribe_v2 = true lazy_decl = true lazy_parse = true lazy_init2 = true """ ) def write_hhconfig(self) -> None: with open(os.path.join(self.repo_dir, ".hhconfig"), "w") as f: f.write( r""" # some comment assume_php = false auto_namespace_map = {"Herp": "Derp\\Lib\\Herp"} """ ) def write_watchman_config(self) -> None: with open(os.path.join(self.repo_dir, ".watchmanconfig"), "w") as f: f.write("{}") os.mkdir(os.path.join(self.repo_dir, ".hg")) def setUp(self) -> None: super(SavedStateTestDriver, self).setUp() self.write_local_conf() self.write_hhconfig() self.write_watchman_config() def start_hh_server( self, changed_files: Optional[Iterable[ChangedFile]] = None, changed_naming_files: Optional[Iterable[str]] = None, saved_state_path: Optional[str] = None, naming_saved_state_path: Optional[str] = None, args: Optional[List[str]] = None, ) -> None: if changed_files is None: changed_files = [] if changed_naming_files is None: changed_naming_files = [] if naming_saved_state_path is None: naming_saved_state_path = self.naming_saved_state_path(saved_state_path) # Yeah, gross again. This function's default value for a parameter # is from the object's state. if saved_state_path is None: saved_state_path = self.saved_state_path() if args is None: args = [] state = { "state": saved_state_path, "corresponding_base_revision": "1", "is_cached": True, "deptable": saved_state_path + ".hhdg", "changes": changed_files, "naming_changes": changed_naming_files, } with_state_arg = {"data_dump": state} cmd = [ hh_server, "--daemon", "--with-mini-state", json.dumps(with_state_arg), self.repo_dir, "--max-procs", "2", ] + args if self.enable_naming_table_fallback: cmd += [ "--config", "enable_naming_table_fallback=true", "--config", "naming_sqlite_path={nt}".format(nt=naming_saved_state_path), ] self.proc_call(cmd) self.wait_until_server_ready() def check_cmd( self, expected_output: Optional[List[str]], stdin: Optional[str] = None, options: Optional[List[str]] = None, assert_loaded_saved_state: bool = True, ) -> Tuple[str, str]: result = super(SavedStateTestDriver, self).check_cmd( expected_output, stdin, options ) logs = self.get_all_logs(self.repo_dir) try: self.assertTrue("Using watchman" in logs.current_server_log) if assert_loaded_saved_state: self.assertTrue( "loading saved state succeeded" in logs.current_server_log, "***Logs contain an init with no saved state. Did your " "hh_server die and get restarted by the monitor?***", ) except AssertionError: print("SERVER-LOG:\n%s\n\n" % logs.all_server_logs, file=sys.stderr) print("MONITOR_LOG:\n%s\n\n" % logs.all_monitor_logs, file=sys.stderr) raise return result def assertEqualString( self, first: str, second: str, msg: Optional[str] = None ) -> None: root = self.repo_dir + os.path.sep second = second.format(root=root) self.assertEqual(first, second, msg)
OCaml
hhvm/hphp/hack/test/integration/symbol_index_test.ml
open Hh_prelude open IndexBuilderTypes open SearchUtils open SearchTypes open Test_harness module Args = Test_harness_common_args module SA = Asserter.String_asserter module IA = Asserter.Int_asserter let rec assert_docblock_markdown (expected : DocblockService.result) (actual : DocblockService.result) : unit = DocblockService.( match (expected, actual) with | ([], []) -> () | ([], _) -> failwith "Expected end of list" | (_, []) -> failwith "Expected markdown item" | (exp_hd :: exp_list, act_hd :: act_list) -> let () = match (exp_hd, act_hd) with | (Markdown exp_txt, Markdown act_txt) -> SA.assert_equals exp_txt act_txt "Markdown text should match" | (XhpSnippet exp_txt, XhpSnippet act_txt) -> SA.assert_equals exp_txt act_txt "XhpSnippet should match" | (HackSnippet exp_txt, HackSnippet act_txt) -> SA.assert_equals exp_txt act_txt "HackSnippet should match" | _ -> failwith "Type of item does not match" in assert_docblock_markdown exp_list act_list) let assert_ns_matches (expected_ns : string) (actual : SearchTypes.si_item list) : unit = let found = List.fold actual ~init:false ~f:(fun acc item -> String.equal item.si_name expected_ns || acc) in (if not found then let results_str = List.fold actual ~init:"" ~f:(fun acc item -> acc ^ ";" ^ item.si_name) in let msg = Printf.sprintf "Did not find [%s] in [%s]" expected_ns results_str in IA.assert_equals 0 1 msg); () let assert_autocomplete ~(query_text : string) ~(kind : si_kind) ~(expected : int) ~(sienv_ref : si_env ref) : unit = let context = match kind with | SI_Interface | SI_Enum -> Actype (* the `Acid` context rules out interfaces+enums, so we pick one that allows them *) | _ -> Acid in (* Search for the symbol *) let (results, _is_complete) = SymbolIndex.find_matching_symbols ~sienv_ref ~query_text ~max_results:100 ~kind_filter:(Some kind) ~context in (* Verify correct number of results *) IA.assert_equals expected (List.length results) (Printf.sprintf "Should be %d result(s) for [%s]" expected query_text); if expected > 0 then ( let r = List.hd_exn results in (* Assert string match *) SA.assert_equals query_text r.si_name (Printf.sprintf "Should be able to find autocomplete for '%s'" query_text); (* Assert kind match *) IA.assert_equals (kind_to_int kind) (kind_to_int r.si_kind) (Printf.sprintf "Mismatch in kind for '%s'" query_text) ) let run_index_builder (harness : Test_harness.t) : si_env = let hhi_folder = Hhi.get_hhi_root () in Relative_path.set_path_prefix Relative_path.Root harness.repo_dir; Relative_path.set_path_prefix Relative_path.Tmp (Path.make "/tmp"); Relative_path.set_path_prefix Relative_path.Hhi hhi_folder; let repo_path = Path.to_string harness.repo_dir in (* Set up initial variables *) let fn = Caml.Filename.temp_file "autocomplete." ".db" in let file_opt = Some fn in let ctxt = { repo_folder = repo_path; sqlite_filename = file_opt; hhi_root_folder = Some hhi_folder; namespace_map = []; silent = true; } in (* Scan the repo folder and produce answers in sqlite *) IndexBuilder.go ctxt None; let sienv = SymbolIndex.initialize ~gleanopt:GleanOptions.default ~namespace_map:[] ~provider_name:"SqliteIndex" ~quiet:true ~savedstate_file_opt:file_opt ~workers:None in Hh_logger.log "Built Sqlite database [%s]" fn; sienv let test_sqlite_plus_local (harness : Test_harness.t) : bool = let sienv_ref = ref (run_index_builder harness) in (* Find one of each major type *) assert_autocomplete ~query_text:"UsesA" ~kind:SI_Class ~expected:1 ~sienv_ref; assert_autocomplete ~query_text:"NoBigTrait" ~kind:SI_Trait ~expected:1 ~sienv_ref; assert_autocomplete ~query_text:"some_long_function_name" ~kind:SI_Function ~expected:1 ~sienv_ref; assert_autocomplete ~query_text:"ClassToBeIdentified" ~kind:SI_Class ~expected:1 ~sienv_ref; Hh_logger.log "First pass complete"; (* Now, let's remove a few files and try again - assertions should change *) let bar1path = Relative_path.from_root ~suffix:"/bar_1.php" in let foo3path = Relative_path.from_root ~suffix:"/foo_3.php" in let s = Relative_path.Set.empty in let s = Relative_path.Set.add s bar1path in let s = Relative_path.Set.add s foo3path in sienv_ref := SymbolIndexCore.remove_files ~sienv:!sienv_ref ~paths:s; Hh_logger.log "Removed files"; (* Two of these have been removed! *) assert_autocomplete ~query_text:"UsesA" ~kind:SI_Class ~expected:1 ~sienv_ref; assert_autocomplete ~query_text:"NoBigTrait" ~kind:SI_Trait ~expected:0 ~sienv_ref; assert_autocomplete ~query_text:"some_long_function_name" ~kind:SI_Function ~expected:0 ~sienv_ref; assert_autocomplete ~query_text:"ClassToBeIdentified" ~kind:SI_Class ~expected:1 ~sienv_ref; Hh_logger.log "Second pass complete"; (* Add the files back! *) let nobigtrait_id = (FileInfo.File (FileInfo.Class, bar1path), "\\NoBigTrait", None) in let some_long_function_name_id = (FileInfo.File (FileInfo.Fun, foo3path), "\\some_long_function_name", None) in let bar1fileinfo = { FileInfo.hash = None; file_mode = None; funs = []; classes = [nobigtrait_id]; typedefs = []; consts = []; comments = Some []; modules = []; } in let foo3fileinfo = { FileInfo.hash = None; file_mode = None; funs = [some_long_function_name_id]; classes = []; typedefs = []; consts = []; comments = Some []; modules = []; } in let changelist = [ (bar1path, bar1fileinfo, TypeChecker); (foo3path, foo3fileinfo, TypeChecker); ] in let init_id = Random_id.short_string () in let env = ServerEnvBuild.make_env ~init_id ~deps_mode:(Typing_deps_mode.InMemoryMode None) ServerConfig.default_config in let ctx = Provider_utils.ctx_from_server_env env in sienv_ref := SymbolIndexCore.update_files ~ctx ~sienv:!sienv_ref ~paths:changelist; let n = LocalSearchService.count_local_fileinfos ~sienv:!sienv_ref in Hh_logger.log "Added back; local search service now contains %d files" n; (* Find one of each major type *) assert_autocomplete ~query_text:"UsesA" ~kind:SI_Class ~expected:1 ~sienv_ref; assert_autocomplete ~query_text:"NoBigTrait" ~kind:SI_Trait ~expected:1 ~sienv_ref; assert_autocomplete ~query_text:"some_long_function_name" ~kind:SI_Function ~expected:1 ~sienv_ref; assert_autocomplete ~query_text:"ClassToBeIdentified" ~kind:SI_Class ~expected:1 ~sienv_ref; Hh_logger.log "Third pass complete"; (* If we got here, all is well *) true (* Test the ability of the index builder to capture a variety of * names and kinds correctly *) let test_builder_names (harness : Test_harness.t) : bool = let sienv = run_index_builder harness in let sienv_ref = ref sienv in (* Assert that we can capture all kinds of symbols *) assert_autocomplete ~query_text:"UsesA" ~kind:SI_Class ~expected:1 ~sienv_ref; assert_autocomplete ~query_text:"NoBigTrait" ~kind:SI_Trait ~expected:1 ~sienv_ref; assert_autocomplete ~query_text:"some_long_function_name" ~kind:SI_Function ~expected:1 ~sienv_ref; assert_autocomplete ~query_text:"ClassToBeIdentified" ~kind:SI_Class ~expected:1 ~sienv_ref; assert_autocomplete ~query_text:"CONST_SOME_COOL_VALUE" ~kind:SI_GlobalConstant ~expected:1 ~sienv_ref; assert_autocomplete ~query_text:"IMyFooInterface" ~kind:SI_Interface ~expected:1 ~sienv_ref; assert_autocomplete ~query_text:"SomeTypeAlias" ~kind:SI_Typedef ~expected:1 ~sienv_ref; assert_autocomplete ~query_text:"FbidMapField" ~kind:SI_Enum ~expected:1 ~sienv_ref; (* XHP is considered a class at the moment - this may change. * Note that XHP classes are saved WITH a leading colon. * Storing them without the leading colon results in incorrect * text for XHP class autocomplete. *) assert_autocomplete ~query_text:":xhp:helloworld" ~kind:SI_Class ~expected:1 ~sienv_ref; (* All good *) true (* Ensure that the namespace map handles common use cases *) let test_namespace_map (harness : Test_harness.t) : bool = NamespaceSearchService.( let _ = harness in let sienv = SearchUtils.quiet_si_env in (* Register a namespace and fetch it back exactly *) register_namespace ~sienv ~namespace:"HH\\Lib\\Str\\fb"; let ns = find_exact_match ~sienv ~namespace:"HH" in SA.assert_equals "\\HH" ns.nss_full_namespace "Basic match"; let ns = find_exact_match ~sienv ~namespace:"HH\\Lib" in SA.assert_equals "\\HH\\Lib" ns.nss_full_namespace "Basic match"; let ns = find_exact_match ~sienv ~namespace:"HH\\Lib\\Str" in SA.assert_equals "\\HH\\Lib\\Str" ns.nss_full_namespace "Basic match"; let ns = find_exact_match ~sienv ~namespace:"HH\\Lib\\Str\\fb" in SA.assert_equals "\\HH\\Lib\\Str\\fb" ns.nss_full_namespace "Basic match"; (* Fetch back case insensitive *) let ns = find_exact_match ~sienv ~namespace:"hh" in SA.assert_equals "\\HH" ns.nss_full_namespace "Case insensitive"; let ns = find_exact_match ~sienv ~namespace:"hh\\lib" in SA.assert_equals "\\HH\\Lib" ns.nss_full_namespace "Case insensitive"; let ns = find_exact_match ~sienv ~namespace:"hh\\lib\\str" in SA.assert_equals "\\HH\\Lib\\Str" ns.nss_full_namespace "Case insensitive"; let ns = find_exact_match ~sienv ~namespace:"hh\\lib\\str\\FB" in SA.assert_equals "\\HH\\Lib\\Str\\fb" ns.nss_full_namespace "Case insensitive"; (* Register an alias and verify that it works as expected *) register_alias ~sienv ~alias:"Str" ~target:"HH\\Lib\\Str"; let ns = find_exact_match ~sienv ~namespace:"Str" in SA.assert_equals "\\HH\\Lib\\Str" ns.nss_full_namespace "Alias search"; let ns = find_exact_match ~sienv ~namespace:"Str\\fb" in SA.assert_equals "\\HH\\Lib\\Str\\fb" ns.nss_full_namespace "Alias search"; (* Register an alias with a leading backslash *) register_alias ~sienv ~alias:"StrFb" ~target:"\\HH\\Lib\\Str\\fb"; let ns = find_exact_match ~sienv ~namespace:"StrFb" in SA.assert_equals "\\HH\\Lib\\Str\\fb" ns.nss_full_namespace "Alias search"; (* Add a new namespace under an alias, and make sure it's visible *) register_namespace ~sienv ~namespace:"StrFb\\SecureRandom"; let ns = find_exact_match ~sienv ~namespace:"\\hh\\lib\\str\\fb\\securerandom" in SA.assert_equals "\\HH\\Lib\\Str\\fb\\SecureRandom" ns.nss_full_namespace "Late bound namespace"; (* Should always be able to find root *) let ns = find_exact_match ~sienv ~namespace:"\\" in SA.assert_equals "\\" ns.nss_full_namespace "Find root"; let ns = find_exact_match ~sienv ~namespace:"" in SA.assert_equals "\\" ns.nss_full_namespace "Find root"; let ns = find_exact_match ~sienv ~namespace:"\\\\" in SA.assert_equals "\\" ns.nss_full_namespace "Find root"; (* Test partial matches *) let matches = find_matching_namespaces ~sienv ~query_text:"st" in assert_ns_matches "Str" matches; (* Assuming we're in a leaf node, find matches under that leaf node *) let matches = find_matching_namespaces ~sienv ~query_text:"StrFb\\Secu" in assert_ns_matches "SecureRandom" matches; (* Special case: empty string always provides zero matches *) let matches = find_matching_namespaces ~sienv ~query_text:"" in IA.assert_equals 0 (List.length matches) "Empty string / zero matches"; (* Special case: single backslash should show at least these root namespaces *) let matches = find_matching_namespaces ~sienv ~query_text:"\\" in assert_ns_matches "Str" matches; assert_ns_matches "StrFb" matches; assert_ns_matches "HH" matches; (* Normal use case *) Hh_logger.log "Reached the hh section"; let matches = find_matching_namespaces ~sienv ~query_text:"hh" in assert_ns_matches "Lib" matches; let matches = find_matching_namespaces ~sienv ~query_text:"\\HH\\" in assert_ns_matches "Lib" matches; true) (* Rapid unit tests to verify docblocks are found and correct *) let test_docblock_finder (harness : Test_harness.t) : bool = let _ = harness in let init_id = Random_id.short_string () in let env = ServerEnvBuild.make_env ~init_id ~deps_mode:(Typing_deps_mode.InMemoryMode None) ServerConfig.default_config in let handle = SharedMem.init ~num_workers:0 SharedMem.default_config in ignore (handle : SharedMem.handle); (* Search for docblocks for various items *) let ctx = Provider_utils.ctx_from_server_env env in Relative_path.set_path_prefix Relative_path.Root harness.repo_dir; let path = Relative_path.create_detect_prefix (Path.to_string (Path.concat harness.repo_dir "/bar_1.php")) in let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path in let docblock = ServerDocblockAt.go_docblock_ctx ~ctx ~entry ~line:6 ~column:7 ~kind:SI_Trait in assert_docblock_markdown [DocblockService.Markdown "This is a docblock for NoBigTrait"] docblock; true (* Main test suite *) let tests args = let harness_config = { Test_harness.hh_server = args.Args.hh_server; hh_client = args.Args.hh_client; template_repo = args.Args.template_repo; } in [ ( "test_sqlite_plus_local", fun () -> Test_harness.run_test ~stop_server_in_teardown:false harness_config test_sqlite_plus_local ); ( "test_builder_names", fun () -> Test_harness.run_test ~stop_server_in_teardown:false harness_config test_builder_names ); ( "test_namespace_map", fun () -> Test_harness.run_test ~stop_server_in_teardown:false harness_config test_namespace_map ); ( "test_docblock_finder", fun () -> Test_harness.run_test ~stop_server_in_teardown:false harness_config test_docblock_finder ); ] let () = Daemon.check_entry_point (); let args = Args.parse () in EventLogger.init_fake (); Unit_test.run_all (tests args)
Python
hhvm/hphp/hack/test/integration/test_case.py
# pyre-strict import abc import os import unittest from typing import Generic, Optional, TypeVar class TestDriver(abc.ABC, unittest.TestCase): @classmethod @abc.abstractmethod def setUpClass(cls, template_repo: str) -> None: raise NotImplementedError() @classmethod @abc.abstractmethod def tearDownClass(cls) -> None: raise NotImplementedError() @abc.abstractmethod def setUp(self) -> None: raise NotImplementedError() @abc.abstractmethod def tearDown(self) -> None: raise NotImplementedError() T = TypeVar("T", bound=TestDriver) class TestCase(unittest.TestCase, Generic[T]): @classmethod def get_template_repo(cls) -> str: return "hphp/hack/test/integration/data/simple_repo" @classmethod def get_test_driver(cls) -> T: raise NotImplementedError() _test_driver: Optional[T] = None @property def test_driver(self) -> T: test_driver = self._test_driver assert test_driver is not None return test_driver @classmethod def setUpClass(cls) -> None: cls._test_driver = cls.get_test_driver() cls._test_driver.setUpClass(cls.get_template_repo()) @classmethod def tearDownClass(cls) -> None: test_driver = cls._test_driver assert test_driver is not None test_driver.tearDownClass() def setUp(self) -> None: # These scripts assume working directory fbcode. cwd = os.path.basename(os.getcwd()) if cwd == "fbcode": self.undo_chdir = None pass # buck elif cwd == "fbsource": self.undo_chdir = os.getcwd() os.chdir("fbcode") # buck2 else: raise RuntimeError("Invalid working directory") self.test_driver.setUp() def tearDown(self) -> None: if self.undo_chdir is not None: # If we chdir then TPX/Buck2 get confused, so make sure we # put things back to how they were. # T107261961 to fix this on the TPX/Buck2 side. os.chdir(self.undo_chdir) self.undo_chdir = None self.test_driver.tearDown()
Python
hhvm/hphp/hack/test/integration/test_codemod_sdt.py
import os import tempfile from typing import List import common_tests class TestCodemodSdt(common_tests.CommonTestDriver): @classmethod def setUpClass(cls): super().setUpClass(template_repo="hphp/hack/test/integration/data/codemod_sdt/") def filename(self): return os.path.join(self.repo_dir, "integration_test_codemod_sdt1.php") def codemod_sdt(self, codemod_jsonl: str, codemod_sdt_args: List[str]) -> str: with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8") as f: f.write(codemod_jsonl) f.flush() codemod_file = f.name self.start_hh_server() log_remotely_arg = "false" stdout, stderr, ret_code = self.run_check( options=[ "--codemod-sdt", codemod_file, log_remotely_arg, *codemod_sdt_args, ], ) if ret_code != 0: self.fail(f"codemod failed: {ret_code=} {stderr=}") return stdout def expect_contents(self, expected): with open(self.filename(), "r") as f: actual = f.read() self.assertEqual(actual, expected) def test_codemod(self) -> None: # jsonl produced by sdt_analysis_exe codemod_jsonl = """ {"entry_kind":"stats","id_cnt":3,"nadable_cnt":3,"syntactically_nadable_cnt":3} {"entry_kind":"add_no_auto_dynamic_attr","items":[{"kind":"((Cclass Concrete))","path":"integration_test_codemod_sdt1.php","sid":"\\C"},{"kind":"(Cinterface)","path":"integration_test_codemod_sdt1.php","sid":"\\I"}]} {"entry_kind":"add_no_auto_dynamic_attr","items":[{"kind":"((Cclass Concrete))","path":"integration_test_codemod_sdt1.php","sid":"\\D"},{"kind":"(Cinterface)","path":"integration_test_codemod_sdt1.php","sid":"\\I"}]} """.strip() stdout = self.codemod_sdt(codemod_jsonl, ["the-tag", "cumulative-groups"]) self.assertIn('"patches_json"', stdout, msg="logging probably works") self.assertIn('"the-tag"', stdout, msg="logging probably works") self.expect_contents( """<?hh <<__NoAutoDynamic>> interface I { public function foo(vec<int> $_): void; } <<__NoAutoDynamic>> final class C implements I { public function foo(vec<int> $_): void {} } <<__NoAutoDynamic>> final class D implements I { public function foo(vec<int> $_): void {} } """ )
Shell Script
hhvm/hphp/hack/test/integration/test_concatenate_all.sh
#!/bin/bash # Copyright (c) Facebook, Inc. and its affiliates. # 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. set -e WORKING_DIR="$(pwd)" TEST_DIR="$(realpath "$(dirname "$0")")" DATA_DIR="${TEST_DIR}/data/concat_all" if [ ! -d "${DATA_DIR}" ]; then DATA_DIR="${WORKING_DIR}/data/concat_all" fi if [ ! -d "${DATA_DIR}" ]; then DATA_DIR="${WORKING_DIR}/hphp/hack/test/integration/data/concat_all" fi if [ ! -d "${DATA_DIR}" ]; then echo "Couldn't find data directory: $DATA_DIR" exit 1 fi function usage() { echo "Usage: $0 /path/to/hh_client /path/to/hh_server" } HH_CLIENT="$1" if [ ! -e "${HH_CLIENT}" ]; then usage exit 1 fi HH_SERVER="$2" if [ ! -e "${HH_SERVER}" ]; then usage exit 1 fi HH_SERVER_DIR="$(dirname "${HH_SERVER}")" if [ "${HH_SERVER}" != "${HH_SERVER_DIR}/hh_server" ]; then # We don't have a way to actually specify the executable, so # we set $PATH instead echo "${HH_SERVER} must be an executable called hh_server" exit 1 fi export PATH="${HH_SERVER_DIR}:$PATH" export HH_TEST_MODE=1 # avoid writing a bunch of telemetry NEW_DATA_DIR="$(mktemp -d)" cp -Ra "${DATA_DIR}"/{*.hack,*.php,.hhconfig} "${NEW_DATA_DIR}/" OUTPUT_DIR="${DATA_DIR}" DATA_DIR="${NEW_DATA_DIR}" function cleanup() { cd "${DATA_DIR}" "${HH_CLIENT}" stop cd / rm -rf --preserve-root "${DATA_DIR}" } trap cleanup exit cd "${DATA_DIR}" "${HH_CLIENT}" stop || true "${HH_CLIENT}" --no-load # syntax tests "${HH_CLIENT}" --concatenate-all no_ns*.hack > "${OUTPUT_DIR}/no_ns.hack.out" "${HH_CLIENT}" --concatenate-all ns_body*.hack > "${OUTPUT_DIR}/ns_body.hack.out" "${HH_CLIENT}" --concatenate-all ns_empty_body*.{hack,php} > "${OUTPUT_DIR}/ns_empty_body.hack.out" # 01-child, 02-parent, 03-grandparent are intentionally in the wrong order; we # need to check that concatenate-all reorders them # 04-sibling is present to make sure the dep table is actually used instead of # merely reversing the import order "${HH_CLIENT}" --concatenate-all 0{1,2,3,4}*.hack > "${OUTPUT_DIR}/dependencies.hack.out" cd "${OUTPUT_DIR}" OUTPUT_DIR_RELATIVE="$(realpath --relative-to="${WORKING_DIR}" "${OUTPUT_DIR}")" EXIT_CODE=0 for OUT in *.out; do EXPECT="$(basename "$OUT" .out).exp" if [ ! -e "$EXPECT" ]; then echo ">>> NEW TEST: ${OUT} <<<" sed 's/^/ > /' "$OUT" echo "Would you like to record ${EXPECT} ? y/n" read -r RESPONSE if [ "$RESPONSE" = "y" ]; then cp "$OUT" "$EXPECT" else EXIT_CODE=1 fi elif ! diff "$OUT" "$EXPECT" > /dev/null; then # diff exits with 0 if files are the same, 1 if there are differences echo ">>> Error: ${OUT} does not match ${EXPECT}:" git diff --no-index --color=always --word-diff=color \ --src-prefix="${OUTPUT_DIR_RELATIVE}/" \ --dst-prefix="${OUTPUT_DIR_RELATIVE}/" \ "$EXPECT" "$OUT" EXIT_CODE=1 fi done exit $EXIT_CODE
Python
hhvm/hphp/hack/test/integration/test_extract_standalone.py
from __future__ import absolute_import, unicode_literals import os from sys import stderr from typing import List from common_tests import CommonTestDriver from test_case import TestCase hh_single_type_check = os.path.abspath(os.getenv("HH_SINGLE_TYPE_CHECK", "<undefined>")) # we expect env var to be repo-relative, so abspath will find it relative to CWD which is repo-root if not os.path.exists(hh_single_type_check): print("Not found HH_SINGLE_TYPE_CHECK=" + hh_single_type_check, file=stderr) exit(1) class ExtractStandaloneDriver(CommonTestDriver): UPDATE_TESTS = False error_file_ext = ".err" auto_namespace_map = '{"PHP": "HH\\\\Lib\\\\PHP"}' def write_load_config( self, use_serverless_ide: bool = False, use_saved_state: bool = False ) -> None: with open(os.path.join(self.repo_dir, ".hhconfig"), "w") as f: f.write( """ auto_namespace_map = {} allowed_fixme_codes_strict = 4101 allowed_decl_fixme_codes = 4101 disable_xhp_element_mangling = false """.format( self.auto_namespace_map ) ) def expected_file_name(self, function_name: str) -> str: return "expected/{}.php.exp".format( function_name.replace(":", "+").replace("\\", "__") ) def expected_file_path(self, function_name: str) -> str: return os.path.join(self.repo_dir, self.expected_file_name(function_name)) def expected_code(self, function_name: str) -> str: with open(self.expected_file_path(function_name)) as expected_file: return expected_file.read().strip() def expected_code_type_errors(self, function_name: str) -> str: with open( self.expected_file_path(function_name) + self.error_file_ext ) as error_file: return error_file.read().strip() def extract_code(self, function_name: str) -> str: extracted_code, _, retcode = self.run_check( options=["--extract-standalone", function_name] ) self.assertEqual( 0, retcode, "hh --extract-standalone {} returned non-zero code".format(function_name), ) result = extracted_code.strip() if self.UPDATE_TESTS: expected_file_path = os.path.join( os.getcwd(), TestExtractStandalone.get_template_repo(), self.expected_file_name(function_name), ) with open(expected_file_path, "w") as expected_file: expected_file.write(result) expected_file.write("\n") return result def assert_expected_code_matches_extracted_code(self, function_name: str) -> None: self.assertMultiLineEqual( self.expected_code(function_name), self.extract_code(function_name), f"The expected result of extracting {function_name} doesn't match the extracted code", ) def type_check_expected_files(self, function_names: List[str]) -> None: files = [ self.expected_file_path(function_name) for function_name in function_names ] self.proc_call( [ hh_single_type_check, "--allowed-fixme-codes-strict", "4101", "--allowed-decl-fixme-codes", "4101", "--auto-namespace-map", self.auto_namespace_map, "--batch-files", "--out-extension", self.error_file_ext, ] + files ) def assert_expected_code_is_well_typed(self, function_name: str) -> None: self.assertMultiLineEqual( "No errors", self.expected_code_type_errors(function_name), f"The expected result of extracting {function_name} has type errors", ) class TestExtractStandalone(TestCase[ExtractStandaloneDriver]): @classmethod def setUpClass(cls) -> None: super().setUpClass() @classmethod def get_template_repo(cls) -> str: return "hphp/hack/test/integration/data/dependencies" @classmethod def get_test_driver(cls) -> ExtractStandaloneDriver: return ExtractStandaloneDriver() def test_extract(self) -> None: self.test_driver.write_load_config() function_names = [ "\\shallow_toplevel", "\\with_typedefs", "\\with_generics", "\\with_generics_with_bounds", "\\Ns\\same_name_different_namespaces", "\\with_interface", "\\with_overriding", "\\with_enum_and_constant", "\\with_traits", "\\with_requiring_trait", "\\with_nontrivial_fun_decls", "\\call_defaulted", "\\call_with_default_and_variadic", "\\call_with_default_and_anonymous_variadic", "\\use_properties", "\\call_constructors", "\\with_constants", "\\SimpleClass::simple_method", "\\with_type_constants", "\\WithAbstractConst::with_abstract_type_constants", "\\WithConst::with_type_constants", "\\with_bounded_generic_class_tparam", "\\with_generic_type", "\\with_generic_method", "\\builtin_argument_types", "\\with_static_property", "\\SimpleDerived::call_parent_method", "\\recursive_function", "\\WithRecursiveMethods::recursive_static", "\\WithRecursiveMethods::recursive_instance", "\\does_not_use_class_methods", "\\with_requiring_interface", "\\with_generic_interface", "\\with_non_generic_type", "\\with_mapped_namespace", "\\WithNameMatchingClassName", "\\with_generic_method_with_wildcard_tparam", "\\with_is_refinement", "\\with_switch", "\\with_classname", "\\with_parent_constructor_call", "\\with_type_const_from_required_interface", "\\with_built_in_constant", "\\with_shape_type_alias", "\\with_enum_type_alias", "\\with_enum_class_name", "\\with_type_const_from_implemented_interface", "\\with_nested_type_const", "\\with_indirect_require_extends", "\\call_reactive", "\\WithReactiveMethods::call_reactive", "\\frob_query", "\\corge", "\\with_implementations", "\\with_constructor_dependency", "\\kwery", "\\with_newtype_with_bound", "\\with_newtype_with_newtype_bound", "\\with_method_defined_in_trait", "\\with_method_defined_in_trait2", "\\ImplementingBase::must_implement", "\\CCC::with_nested_type_access", "\\TFlob::g", "\\Derived::overridden", "\\with_xhp", "\\WithOptionalConstructorArguments::get", "\\TExtendsWithConsistentConstruct::get", "\\with_IEWGPCOUP", "\\with_contra_tparam", "\\WithLateInit::getCount", "\\TFlobby::g", "\\with_omitted_generics", "\\:foo::render", "\\with_unsafe_type_hh_fixme", "\\with_reified_generics", "\\SealedInterface::method", "\\WithTypeAliasHint::getX", "\\respects_newtype_abstraction", "\\function_in_typedef", "\\contexts_in_typedef", "\\with_argument_dependent_context", "\\Contextual::with_argument_dependent_context", "\\WithContextConstant::has_io", "\\with_optional_argument_dependent_context", "\\with_expr_in_user_attrs", "\\with_arg_with_sealed_whitelist", "\\with_user_attr", "\\with_param_with_user_attr", "\\with_tparam_with_user_attr", "\\WithPropWithUserAttr::foo", "\\WithStaticPropWithUserAttr::foo", "\\WithTypeConstantWithUserAttr::foo", "\\WithMethodWithUserAttr::foo", "\\WithUserAttr::foo", "\\enum_with_user_attr", "\\opaque_with_user_attr", "\\transparent_with_user_attr", "\\with_constr_prop_with_user_attr", "\\with_where_constraint", "\\with_open_shape", "\\TestExtractConstruct::__construct", "\\with_escaped_char_in_attr", "\\with_class_name_in_attr", "\\with_tparam_constraint", "\\with_prop_in_construct", "\\WithTypeConstantParamConstraint::foo", ] for function_name in function_names: with self.subTest(msg=function_name): self.test_driver.assert_expected_code_matches_extracted_code( function_name ) self.test_driver.type_check_expected_files(function_names) for function_name in function_names: with self.subTest(msg=function_name): self.test_driver.assert_expected_code_is_well_typed(function_name) def test_failing(self) -> None: self.test_driver.write_load_config() self.test_driver.assert_expected_code_matches_extracted_code( "\\nonexistent_function" ) self.test_driver.assert_expected_code_matches_extracted_code( "\\nonexistent_dependency" )
Python
hhvm/hphp/hack/test/integration/test_fresh_init.py
# pyre-strict from __future__ import absolute_import, division, print_function, unicode_literals import os import time import unittest from typing import List, Optional, Tuple import common_tests from hh_paths import hh_client class FreshInitTestDriver(common_tests.CommonTestDriver): def write_load_config( self, use_serverless_ide: bool = False, use_saved_state: bool = False ) -> None: # Fresh init tests don't care about which files changed, so we can # just use the default .hhconfig in the template repo pass def check_cmd( self, expected_output: Optional[List[str]], stdin: Optional[str] = None, options: Optional[List[str]] = None, retries: int = 30, assert_loaded_saved_state: bool = False, ) -> Tuple[str, str]: if options is None: options = [] time.sleep(2) # wait for Hack to catch up with file system changes root = self.repo_dir + os.path.sep (output, err, retcode) = self.proc_call( [ hh_client, "check", "--retries", "120", "--no-load", "--error-format", "raw", "--config", "max_workers=2", self.repo_dir, ] + list(map(lambda x: x.format(root=root), options)), stdin=stdin, ) if (retcode == 6 or retcode == 7) and retries > 0: # 6 = "No_server_running_should_retry" or "Server_hung_up_should_retry" # 7 = "Out_of_time" or "Out_of_retries" return self.check_cmd(expected_output, stdin, options, retries - 1) if retcode == 7: raise unittest.SkipTest("Hack server exit code 7 - out of time/retries") self.assertIn(retcode, [0, 2]) if expected_output is not None: self.assertCountEqual( map(lambda x: x.format(root=root), expected_output), output.splitlines() ) return output, err def assertEqualString( self, first: str, second: str, msg: Optional[str] = None ) -> None: root = self.repo_dir + os.path.sep second = second.format(root=root) self.assertEqual(first, second, msg) class TestFreshInit(common_tests.CommonTests): @classmethod def get_test_driver(cls) -> common_tests.CommonTestDriver: return common_tests.CommonTestDriver() def test_remove_dead_fixmes(self) -> None: with open(os.path.join(self.test_driver.repo_dir, "foo_4.php"), "w") as f: f.write( """<?hh // strict function foo(?string $s): void { /* HH_FIXME[4010] We can delete this one */ /* HH_FIXME[4089] We need to keep this one */ /* HH_FIXME[4099] We can delete this one */ if (/* HH_FIXME[4011] We can delete this one */ $s) { print "hello"; } else if ($s /* HH_FIXME[4011] We can delete this one */) { print "world"; } /* HH_FIXME[4099] We can delete this one */ /* HH_FIXME[4098] We can delete this one */ print "done\n"; } """ ) self.test_driver.start_hh_server( changed_files=["foo_4.php"], args=["--no-load"] ) self.test_driver.check_cmd( expected_output=None, options=["--remove-dead-fixmes"] ) with open(os.path.join(self.test_driver.repo_dir, "foo_4.php")) as f: out = f.read() self.assertEqual( out, """<?hh // strict function foo(?string $s): void { if ($s) { print "hello"; } else if ($s ) { print "world"; } print "done\n"; } """, ) def test_remove_dead_fixmes_single_alive(self) -> None: with open( os.path.join(self.test_driver.repo_dir, "foo_fixme_single_alive.php"), "w" ) as f: f.write( """<?hh function takes_int(int $_): void {} function foo(): void { /* HH_FIXME[4110] not dead. */ takes_int("not an int"); } """ ) self.test_driver.start_hh_server( changed_files=["foo_fixme_single_alive.php"], args=["--no-load"] ) self.test_driver.check_cmd( expected_output=None, options=["--remove-dead-fixmes"] ) with open( os.path.join(self.test_driver.repo_dir, "foo_fixme_single_alive.php") ) as f: out = f.read() self.assertEqual( out, """<?hh function takes_int(int $_): void {} function foo(): void { /* HH_FIXME[4110] not dead. */ takes_int("not an int"); } """, ) def test_remove_dead_unsafe_casts(self) -> None: with open(os.path.join(self.test_driver.repo_dir, "foo_5.php"), "w") as f: f.write( r"""<?hh function takes_string(string $i): void {} function id<T>(T $t): T { return $t; } function foo(?string $s): ?string { takes_string(\HH\FIXME\UNSAFE_CAST<?string, string>($s)); // Not redundant \HH\FIXME\UNSAFE_CAST<mixed, ?string>($s); // Redundant if (\HH\FIXME\UNSAFE_CAST<mixed, ?string>(id($s)) === 'test') { // Redundant print "hello"; return \HH\FIXME\UNSAFE_CAST<?string, string>($s); // Not redundant } else { return \HH\FIXME\UNSAFE_CAST<mixed, ?string>($s); // Redundant } } """ ) self.test_driver.start_hh_server( changed_files=["foo_5.php"], args=["--no-load", "--config", "populate_dead_unsafe_cast_heap=true"], ) self.test_driver.check_cmd( expected_output=None, options=["--remove-dead-unsafe-casts"] ) with open(os.path.join(self.test_driver.repo_dir, "foo_5.php")) as f: out = f.read() self.assertEqual( out, r"""<?hh function takes_string(string $i): void {} function id<T>(T $t): T { return $t; } function foo(?string $s): ?string { takes_string(\HH\FIXME\UNSAFE_CAST<?string, string>($s)); // Not redundant $s; // Redundant if (id($s) === 'test') { // Redundant print "hello"; return \HH\FIXME\UNSAFE_CAST<?string, string>($s); // Not redundant } else { return $s; // Redundant } } """, )
OCaml
hhvm/hphp/hack/test/integration/test_harness.ml
open Hh_prelude module Tools = struct let boxed_string content = Printf.sprintf "%s%s%s" "\n============================\n" content "\n============================\n" end module Tempfile = struct let mkdtemp () = let tmp_dir = Sys_utils.temp_dir_name in let tmp_dir = Path.make tmp_dir in let name = Random_id.short_string () in let tmp_dir = Path.concat tmp_dir name in let () = Unix.mkdir (Path.to_string tmp_dir) 0o740 in tmp_dir end exception Process_failed of Process_types.failure type t = { repo_dir: Path.t; test_env: string list; hh_client_path: string; hh_server_path: string; } type config = { hh_server: Path.t; hh_client: Path.t; template_repo: Path.t; } (** Invoke a subprocess on the harness's repo with its environment. *) let exec_hh_client args harness = let args = args @ [Path.to_string harness.repo_dir; "--config"; "max_workers=2"] in Printf.eprintf "executing hh_client. Args: %s\n%!" (String.concat ~sep:", " args); Process.exec (Exec_command.For_use_in_testing_only harness.hh_client_path) ~env:(Process_types.Augment harness.test_env) args let get_server_logs harness = let process = exec_hh_client ["--logname"] harness in match Process.read_and_wait_pid ~timeout:5 process with | Ok { Process_types.stdout; _ } -> let log_path = Path.make (String.strip stdout) in (try Some (Sys_utils.cat (Path.to_string log_path)) with | Sys_error m when Sys_utils.string_contains m "No such file or directory" -> None) | Error failure -> raise @@ Process_failed failure let wait_until_lock_free lock_file _harness = Lock.blocking_grab_then_release lock_file let get_recording_path harness = let recording_re = Str.regexp ("^.+ About to spawn recorder daemon\\. " ^ "Output will go to \\(.+\\)\\. Logs to \\(.+\\)\\. " ^ "Lock_file to \\(.+\\)\\.$") in Option.( let logs = get_server_logs harness in logs >>= fun logs -> try let _ = Str.search_forward recording_re logs 0 in Some ( Path.make (Str.matched_group 1 logs), Path.make (Str.matched_group 2 logs) ) with | Caml.Not_found -> Printf.eprintf "recorder path or lock file not found\n%!"; Printf.eprintf "See also server logs: %s\n%!" logs; None) let check_cmd harness = let process = exec_hh_client ["check"] harness in Printf.eprintf "Waiting for process\n%!"; match Process.read_and_wait_pid ~timeout:30 process with | Ok { Process_types.stdout; _ } -> Sys_utils.split_lines stdout | Error failure -> raise @@ Process_failed failure let stop_server harness = let process = exec_hh_client ["stop"] harness in match Process.read_and_wait_pid ~timeout:30 process with | Ok { Process_types.stdout; _ } -> stdout | Error failure -> raise @@ Process_failed failure let run_test ?(stop_server_in_teardown = true) config test_case = let base_tmp_dir = Tempfile.mkdtemp () in let repo_dir = Path.concat base_tmp_dir "repo" in let () = Unix.mkdir (Path.to_string repo_dir) 0o740 in let command = Printf.sprintf "cp -r %s/. %s" (Path.to_string config.template_repo) (Path.to_string repo_dir) in let () = Printf.eprintf "Executing command: %s\n" command in let retcode = Sys.command command in if not (retcode = 0) then let () = Printf.eprintf "Failed to copy template repo\n" in false else (* Where the hhi files, socket, etc get extracted *) (* TODO: Get HH_TMPDIR working; currently this is commented out. * * Right now, we will have to pollute the system's main tmp directory * for HH_TMPDIR instead of using a custom one for testing. * * The problem is that we look for a server's socket file in * GlobalConfig.tmp_dir, which is a static constant. So, when we * start a server by forking hh_client (with a custom HH_TMPDIR env * variable), it puts the socket file in that custom directory. But * when we try to open a connection inside this existing process, * it looks for the socket file in the default directory. * * Globals suck. *) (* let hh_tmpdir = Tempfile.mkdtemp () in *) let bin_dir = Tempfile.mkdtemp () in let hh_server_dir = Path.parent config.hh_server in let test_env = [ ("HH_TEST_MODE", "1"); (* ("HH_TMPDIR", (Path.to_string hh_tmpdir)); *) ( "PATH", Printf.sprintf "'%s:%s:/bin:/usr/bin:/usr/local/bin" (Path.to_string hh_server_dir) (Path.to_string bin_dir) ); ("OCAMLRUNPARAM", "b"); ("HH_LOCALCONF_PATH", Path.to_string repo_dir); ] in let test_env = List.map test_env ~f:(fun (k, v) -> Printf.sprintf "%s=%s" k v) in let harness = { repo_dir; test_env; hh_client_path = Path.to_string config.hh_client; hh_server_path = Path.to_string config.hh_server; } in let () = Printf.eprintf "Repo_dir: %s; bin_dir: %s;\n%!" (Path.to_string repo_dir) (Path.to_string bin_dir) in let tear_down () = let () = Printf.eprintf "Tearing down test, deleting temp directories\n%!" in let () = if stop_server_in_teardown then ignore @@ stop_server harness else () in let () = Sys_utils.rm_dir_tree (Path.to_string bin_dir) in let () = Sys_utils.rm_dir_tree (Path.to_string repo_dir) in let () = Sys_utils.rm_dir_tree (Path.to_string base_tmp_dir) in () in let with_exception_printing test_case harness = let result = try test_case harness with | Process_failed (Process_types.Abnormal_exit { status; stderr; _ }) as e -> Printf.eprintf "Process exited abnormally (%s). See also Stderr: %s\n" (Process.status_to_string status) (Tools.boxed_string stderr); raise e in result in Utils.try_finally ~f:(fun () -> with_exception_printing test_case harness) ~finally:tear_down let with_local_conf local_conf_str test_case harness = let conf_file = Path.concat harness.repo_dir "hh.conf" in let oc = Stdlib.open_out (Path.to_string conf_file) in let () = Stdlib.output_string oc local_conf_str in let () = Stdlib.close_out oc in test_case harness
OCaml
hhvm/hphp/hack/test/integration/test_harness_common_args.ml
(* * These are the arguments that integration test binaries using Test_harness * will want to parse. *) type t = { hh_server: Path.t; hh_client: Path.t; template_repo: Path.t; } let usage = Printf.sprintf "Usage: %s --hh-server <%s> --hh-client <%s> [template repo]\n" "hh_server_path" "hh_client_path" Sys.argv.(0) let usage_exit () = Printf.eprintf "%s\n" usage; exit 1 let string_spec str_ref = Arg.String (fun x -> str_ref := Some x) let requires name opt = match !opt with | None -> let () = Printf.eprintf "Missing required argument: %s\n" name in usage_exit () | Some x -> x let parse () = let template_repo = ref None in let hh_server = ref None in let hh_client = ref None in let options = [ ("--hh-server", string_spec hh_server, "Path to hh_server"); ("--hh-client", string_spec hh_client, "Path to hh_client"); ] in let () = Arg.parse options (fun s -> template_repo := Some s) usage in let template_repo = requires "template repo" template_repo in let hh_server = requires "hh_server" hh_server in let hh_client = requires "hh_client" hh_client in { hh_server = Path.make hh_server; hh_client = Path.make hh_client; template_repo = Path.make template_repo; }
Shell Script
hhvm/hphp/hack/test/integration/test_hhis.sh
#!/bin/bash set -ex HH_SERVER="$1" if [ ! -x "${HH_SERVER}" ]; then echo "Usage: $0 /path/to/hh_server" exit 1 fi REPO="$(mktemp -d)" cat > "${REPO}/.hhconfig" <<EOF unsafe_rx=false EOF export HH_TEST_MODE=1 # avoid writing a bunch of telemetry set +e "${HH_SERVER}" --check "${REPO}" --config max_workers=2 code=$? if [[ "$code" == 126 ]]; then # 126 means "not executable", typically in buck2 from "Text file is busy" because there are still open FD write handles to the binary # Ugly workaround for now: https://www.internalfb.com/intern/qa/312685/text-file-is-busy---test-is-run-before-fclose-on-e # This workaround should be removed once T107518211 is closed. sleep 20 "${HH_SERVER}" --check "${REPO}" --config max_workers=2 fi rm -rf "${REPO}"
Python
hhvm/hphp/hack/test/integration/test_lsp.py
# pyre-strict # flake8: noqa: B950 from __future__ import absolute_import, division, print_function, unicode_literals import copy import enum import json import os import re import sys import unittest import urllib.parse from typing import Dict, Iterable, List, Mapping, Optional, Tuple import common_tests from hh_paths import hh_server from lspcommand import LspCommandProcessor, Transcript from lsptestspec import line, LspTestSpec, NoResponse from test_case import TestCase from utils import interpolate_variables, Json, JsonObject class LspTestDriver(common_tests.CommonTestDriver): def write_load_config( self, use_saved_state: bool = False, ) -> None: # Will use the .hhconfig already in the repo directory # As for hh.conf, we'll write it explicitly each test. with open(os.path.join(self.repo_dir, "hh.conf"), "w") as f: f.write( """ use_watchman = true watchman_subscribe_v2 = true interrupt_on_watchman = true interrupt_on_client = true max_workers = 2 load_state_natively_v4 = {use_saved_state} use_mini_state = {use_saved_state} require_mini_state = {use_saved_state} lazy_decl = {use_saved_state} lazy_parse = {use_saved_state} lazy_init2 = {use_saved_state} symbolindex_search_provider = NoIndex ide_symbolindex_search_provider = SqliteIndex allow_unstable_features = true ide_batch_process_changes = true """.format( use_saved_state=str(use_saved_state).lower(), ) ) def write_naming_table_saved_state(self) -> str: naming_table_saved_state_path = os.path.join( self.repo_dir, "naming_table_saved_state.sqlite" ) (stdout, stderr, retcode) = self.proc_call( [ hh_server, "--check", self.repo_dir, "--save-naming", naming_table_saved_state_path, ] ) assert retcode == 0, ( f"Failed to save naming table saved state: {retcode}\n" + f"STDOUT:\n{stdout}\n" + f"STDERR:\n{stderr}\n" ) return naming_table_saved_state_path class TestLsp(TestCase[LspTestDriver]): @classmethod def get_test_driver(cls) -> LspTestDriver: return LspTestDriver() @classmethod def get_template_repo(cls) -> str: return "hphp/hack/test/integration/data/lsp_exchanges/" def repo_file(self, file: str) -> str: return os.path.join(self.test_driver.repo_dir, file) def read_repo_file(self, file: str) -> str: with open(self.repo_file(file), "r") as f: return f.read() def repo_file_uri(self, file: str) -> str: return urllib.parse.urljoin("file://", self.repo_file(file)) # pyre-fixme[11]: Annotation `Json` is not defined as a type. def parse_test_data(self, file: str, variables: Mapping[str, str]) -> Json: text = self.read_repo_file(file) data: Json = json.loads(text) data = interpolate_variables(data, variables) return data def load_test_data( self, test_name: str, variables: Mapping[str, str] ) -> Tuple[Json, Json]: test = self.parse_test_data(test_name + ".json", variables) expected = self.parse_test_data(test_name + ".expected", variables) return (test, expected) def write_observed(self, test_name: str, observed_transcript: Json) -> None: file = os.path.join(self.test_driver.template_repo, test_name + ".observed.log") text = json.dumps( list(self.get_important_received_items(observed_transcript)), indent=2 ) with open(file, "w") as f: f.write(text) # pyre-fixme[11]: Annotation `JsonObject` is not defined as a type. def order_response(self, response: JsonObject) -> str: if "id" in response: return str(response["id"]) else: return json.dumps(response, indent=2) # sorts a list of responses using the 'id' parameter so they can be # compared in sequence even if they came back from the server out of sequence. # this can happen based on how json rpc is specified to work. # if 'id' isn't present the response is a notification. we sort notifications # by their entire text. def sort_responses(self, responses: Iterable[JsonObject]) -> List[JsonObject]: return sorted(responses, key=lambda response: self.order_response(response)) # removes stack traces from error responses since these can be noisy # as code changes and they contain execution environment specific details # by ignoring these when comparing responses we might miss some minor issues # but will still catch the core error being thrown or not. def sanitize_exceptions( self, responses: Iterable[JsonObject] ) -> Iterable[JsonObject]: sanitized = copy.deepcopy(responses) for response in sanitized: if "error" in response: if "data" in response["error"]: del response["error"]["data"] return sanitized # dumps an LSP response into a standard json format that can be used for # doing precise text comparison in a way that is human readable in the case # of there being an error. def serialize_responses(self, responses: Iterable[Json]) -> List[str]: return [json.dumps(response, indent=2) for response in responses] # generates received responses from an LSP communication transcript # ignoring the non-deterministic ones "progress" and "actionRequired" def get_important_received_items(self, transcript: Transcript) -> Iterable[Json]: for entry in transcript.values(): received = entry.received or None if received is None: continue method = received.get("method") or "" if method in [ "window/progress", "window/actionRequired", "window/showStatus", "telemetry/event", "textDocument/publishDiagnostics", "client/registerCapability", ]: continue yield received # gets a set of loaded responses ready for validation by sorting them # by id and serializing them for precise text comparison def prepare_responses(self, responses: Iterable[JsonObject]) -> List[str]: return self.serialize_responses( self.sanitize_exceptions(self.sort_responses(responses)) ) def run_lsp_test( self, test_name: str, test: Json, expected: Json, lsp_args: List[str], ) -> None: with LspCommandProcessor.create( self.test_driver.test_env, lsp_args, self.test_driver.repo_dir ) as lsp: observed_transcript = lsp.communicate(test) self.write_observed(test_name, observed_transcript) expected_items = self.prepare_responses(expected) observed_items = self.prepare_responses( list(self.get_important_received_items(observed_transcript)) ) # If the server's busy, maybe the machine's just under too much # pressure to give results in a timely fashion. Doing a retry would # only defer the question of what to do in that case, so instead # we'll just skip. self.throw_skip_if_transcript_includes_server_busy(observed_transcript) # validation checks that the number of items matches and that # the responses are exactly identical to what we expect. # Python equality on lists requires identical lengths, # identical order, and does == on each element... if expected_items != observed_items: msg = "Observed this:\n" + json.dumps( observed_transcript, indent=2, separators=(",", ": "), sort_keys=True ) while ( expected_items and observed_items and expected_items[0] == observed_items[0] ): expected_items.pop(0) observed_items.pop(0) msg += ( f"\n\nIt first went wrong here...\n" f"Expected:\n{expected_items[0] if expected_items else '[none]'}\n\n" f"Observed:\n{observed_items[0] if observed_items else '[none]'}\n" ) raise AssertionError(msg) def throw_skip_if_transcript_includes_server_busy( self, transcript: Transcript ) -> None: failure_messages = ["Server busy", "timed out"] for entry in transcript.values(): received = entry.received if received is None: continue if received.get("error"): message = received["error"]["message"] for failure_message in failure_messages: if failure_message in message: raise unittest.SkipTest(message) def write_hhconf_and_naming_table(self) -> Dict[str, str]: self.maxDiff = None self.test_driver.write_load_config(use_saved_state=False) naming_table_saved_state_path = ( self.test_driver.write_naming_table_saved_state() ) return dict( { "naming_table_saved_state_path": naming_table_saved_state_path, "root_path": self.test_driver.repo_dir, } ) def load_and_run( self, test_name: str, variables: Mapping[str, str], lsp_args: Optional[List[str]] = None, ) -> None: test, expected = self.load_test_data(test_name, variables) if lsp_args is None: lsp_args = [] self.run_lsp_test( test_name=test_name, test=test, expected=expected, lsp_args=lsp_args, ) def run_spec( self, spec: LspTestSpec, variables: Mapping[str, str], fall_back_to_full_index: bool = True, ) -> None: lsp_config_args = [ "--config", f"ide_fall_back_to_full_index={str(fall_back_to_full_index).lower()}", ] with LspCommandProcessor.create( self.test_driver.test_env, lsp_config_args, self.test_driver.repo_dir ) as lsp_command_processor: (observed_transcript, error_details) = spec.run( lsp_command_processor=lsp_command_processor, variables=variables ) file = os.path.join(self.test_driver.template_repo, spec.name + ".sent.log") text = json.dumps( [ sent for sent, _received in observed_transcript.values() if sent is not None ], indent=2, ) with open(file, "w") as f: f.write(text) file = os.path.join(self.test_driver.template_repo, spec.name + ".received.log") text = json.dumps( [ received for _sent, received in observed_transcript.values() if received is not None ], indent=2, ) with open(file, "w") as f: f.write(text) # If the server's busy, maybe the machine's just under too much # pressure to give results in a timely fashion. Doing a retry would # only defer the question of what to do in that case, so instead # we'll just skip. self.throw_skip_if_transcript_includes_server_busy(observed_transcript) if error_details is not None: logs = self.test_driver.get_all_logs(self.test_driver.repo_dir) print("CLIENT_LOG:\n%s\n\n" % logs.client_log, file=sys.stderr) print("IDE_LOG:\n%s\n\n" % logs.ide_log, file=sys.stderr) print("LSP_LOG:\n%s\n\n" % logs.lsp_log, file=sys.stderr) raise AssertionError(error_details) def setup_php_file(self, test_php: str) -> Mapping[str, str]: return { "php_file_uri": self.repo_file_uri(test_php), "php_file": self.read_repo_file(test_php), } def test_init_shutdown(self) -> None: variables = self.write_hhconf_and_naming_table() self.load_and_run("initialize_shutdown", variables) def test_optional_param_completion(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("optional_param_completion.php")) spec = ( self.initialize_spec(LspTestSpec("optional_param_completion")) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .notification( comment="Insert the beginning of a method call", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 4, "character": 0}, "end": {"line": 4, "character": 0}, }, "text": "$mfc->doSt", } ], }, ) .request( line=line(), comment="autocomplete method", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 4, "character": 10}, }, result={ "isIncomplete": False, "items": [ { "label": "doStuff", "kind": 2, "detail": "function(int $x, int $y = _): void", "sortText": "doStuff", "insertTextFormat": 2, "textEdit": { "range": { "start": {"line": 4, "character": 6}, "end": {"line": 4, "character": 10}, }, # We don't want to require the user to provide optional arguments, so # only insert $x, not $y. "newText": "doStuff(${1:\\$x})", }, "data": { "fullname": "doStuff", "filename": "${root_path}/optional_param_completion.php", "line": 8, "char": 19, "base_class": "\\MyFooCompletion", }, } ], }, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_all_optional_params_completion(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("all_optional_params_completion.php")) spec = ( self.initialize_spec(LspTestSpec("all_optional_params_completion")) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .notification( comment="Insert the beginning of a method call", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 4, "character": 0}, "end": {"line": 4, "character": 0}, }, "text": "$mfc->doSt", } ], }, ) .request( line=line(), comment="autocomplete method", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 4, "character": 10}, }, result={ "isIncomplete": False, "items": [ { "label": "doStuff", "kind": 2, "detail": "function(int $x = _, int $y = _): void", "sortText": "doStuff", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 4, "character": 6}, "end": {"line": 4, "character": 10}, }, "newText": "doStuff()", }, "data": { "fullname": "doStuff", "filename": "${root_path}/all_optional_params_completion.php", "line": 8, "char": 19, "base_class": "\\MyFooCompletionOptional", }, } ], }, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_completion(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("completion.php")) spec = ( self.initialize_spec(LspTestSpec("ide_completion")) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .notification( comment="Add '$x = $point1['' to test autocomplete for shapes", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 22, "character": 0}, "end": {"line": 22, "character": 0}, }, "text": "$x = $point1['", } ], }, ) .request( line=line(), comment="autocomplete after user types a shape", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 22, "character": 14}, }, result={ "isIncomplete": False, "items": [ { "label": "'x'", "kind": 12, "detail": "literal", "sortText": "'x'", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 22, "character": 13}, "end": {"line": 22, "character": 14}, }, "newText": "'x'", }, "data": { "fullname": "'x'", "filename": "${root_path}/completion.php", "line": 22, "char": 19, }, }, { "label": "'y'", "kind": 12, "detail": "literal", "sortText": "'y'", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 22, "character": 13}, "end": {"line": 22, "character": 14}, }, "newText": "'y'", }, "data": { "fullname": "'y'", "filename": "${root_path}/completion.php", "line": 22, "char": 30, }, }, ], }, powered_by="serverless_ide", ) .notification( comment="Add automatically closed apostrophes when typing a shape key, the way visual studio code does it", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 22, "character": 0}, "end": {"line": 22, "character": 14}, }, "text": "$x = $point1['']", } ], }, ) .request( line=line(), comment="autocomplete after a shape, with VS Code automatically closed apostrophes", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 22, "character": 14}, }, result={ "isIncomplete": False, "items": [ { "label": "'x", "kind": 12, "detail": "literal", "sortText": "'x", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 22, "character": 13}, "end": {"line": 22, "character": 13}, }, "newText": "'x", }, "data": { "fullname": "'x'", "filename": "${root_path}/completion.php", "line": 22, "char": 19, }, }, { "label": "'y", "kind": 12, "detail": "literal", "sortText": "'y", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 22, "character": 13}, "end": {"line": 22, "character": 13}, }, "newText": "'y", }, "data": { "fullname": "'y'", "filename": "${root_path}/completion.php", "line": 22, "char": 30, }, }, ], }, powered_by="serverless_ide", ) .notification( comment="Add '$x = <'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 0}, }, "text": "$x = <", } ], }, ) .request( line=line(), comment="autocomplete after '$x = <'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 6}, }, result={ "isIncomplete": False, "items": [ { "label": "ab:cd:alpha", "kind": 7, "detail": "class", "sortText": "ab:cd:alpha", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 6}, "end": {"line": 3, "character": 6}, }, "newText": "ab:cd:alpha>$0</ab:cd:alpha>", }, "data": {"fullname": ":ab:cd:alpha"}, }, { "label": "ab:cd:text", "kind": 7, "detail": "class", "sortText": "ab:cd:text", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 6}, "end": {"line": 3, "character": 6}, }, "newText": "ab:cd:text>$0</ab:cd:text>", }, "data": {"fullname": ":ab:cd:text"}, }, { "label": "xhp:enum-attribute", "kind": 7, "detail": "class", "sortText": "xhp:enum-attribute", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 6}, "end": {"line": 3, "character": 6}, }, "newText": "xhp:enum-attribute>$0</xhp:enum-attribute>", }, "data": {"fullname": ":xhp:enum-attribute"}, }, { "label": "xhp:generic", "kind": 7, "detail": "class", "sortText": "xhp:generic", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 6}, "end": {"line": 3, "character": 6}, }, "newText": "xhp:generic>$0</xhp:generic>", }, "data": {"fullname": ":xhp:generic"}, }, ], }, powered_by="serverless_ide", ) .notification( comment="Add '$x = <a'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 6}, }, "text": "$x = <a", } ], }, ) .request( line=line(), comment="autocomplete after '$x = <a'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 7}, }, result={ "isIncomplete": False, "items": [ { "label": "ab:cd:alpha", "kind": 7, "detail": "class", "sortText": "ab:cd:alpha", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 6}, "end": {"line": 3, "character": 7}, }, "newText": "ab:cd:alpha>$0</ab:cd:alpha>", }, "data": {"fullname": ":ab:cd:alpha"}, }, { "label": "ab:cd:text", "kind": 7, "detail": "class", "sortText": "ab:cd:text", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 6}, "end": {"line": 3, "character": 7}, }, "newText": "ab:cd:text>$0</ab:cd:text>", }, "data": {"fullname": ":ab:cd:text"}, }, ], }, powered_by="serverless_ide", ) .notification( comment="Add '$x = <ab:'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 7}, }, "text": "$x = <ab:", } ], }, ) .request( line=line(), comment="autocomplete after '$x = <ab:'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 9}, }, result={ "isIncomplete": False, "items": [ { "label": "ab:cd:alpha", "kind": 7, "detail": "class", "sortText": "ab:cd:alpha", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 6}, "end": {"line": 3, "character": 9}, }, "newText": "ab:cd:alpha>$0</ab:cd:alpha>", }, "data": {"fullname": ":ab:cd:alpha"}, }, { "label": "ab:cd:text", "kind": 7, "detail": "class", "sortText": "ab:cd:text", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 6}, "end": {"line": 3, "character": 9}, }, "newText": "ab:cd:text>$0</ab:cd:text>", }, "data": {"fullname": ":ab:cd:text"}, }, ], }, powered_by="serverless_ide", ) .notification( comment="Add '$x = <ab:cd:text '", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 9}, }, "text": "$x = <ab:cd:text ", } ], }, ) .request( line=line(), comment="autocomplete after '$x = <ab:cd:text '", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 17}, }, result={ "isIncomplete": False, "items": [ { "label": "width", "kind": 5, "detail": "?int", "sortText": "width", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 17}, "end": {"line": 3, "character": 17}, }, "newText": "width", }, "data": { "fullname": ":width", "filename": "${root_path}/xhp_class_definitions.php", "line": 5, "char": 27, "base_class": "\\:ab:cd:text", }, }, { "label": "color", "kind": 5, "detail": "?string", "sortText": "color", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 17}, "end": {"line": 3, "character": 17}, }, "newText": "color", }, "data": { "fullname": ":color", "filename": "${root_path}/xhp_class_definitions.php", "line": 5, "char": 13, "base_class": "\\:ab:cd:text", }, }, ], }, powered_by="serverless_ide", ) .notification( comment="Add '$x = <ab:cd:text w'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 17}, }, "text": "$x = <ab:cd:text w", } ], }, ) .request( line=line(), comment="autocomplete after '$x = <ab:cd:text w'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 18}, }, result={ "isIncomplete": False, "items": [ { "label": "width", "kind": 5, "detail": "?int", "sortText": "width", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 17}, "end": {"line": 3, "character": 18}, }, "newText": "width", }, "data": { "fullname": ":width", "filename": "${root_path}/xhp_class_definitions.php", "line": 5, "char": 27, "base_class": "\\:ab:cd:text", }, }, { "label": "color", "kind": 5, "detail": "?string", "sortText": "color", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 17}, "end": {"line": 3, "character": 18}, }, "newText": "color", }, "data": { "fullname": ":color", "filename": "${root_path}/xhp_class_definitions.php", "line": 5, "char": 13, "base_class": "\\:ab:cd:text", }, }, ], }, powered_by="serverless_ide", ) .notification( comment="Add '$x = new :'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 18}, }, "text": "$x = new :", } ], }, ) .request( line=line(), comment="autocomplete after '$x = new :'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 10}, }, result={ "isIncomplete": False, "items": [ { "label": ":ab:cd:alpha", "kind": 7, "detail": "class", "sortText": ":ab:cd:alpha", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 9}, "end": {"line": 3, "character": 10}, }, "newText": ":ab:cd:alpha", }, "data": {"fullname": ":ab:cd:alpha"}, }, { "label": ":ab:cd:text", "kind": 7, "detail": "class", "sortText": ":ab:cd:text", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 9}, "end": {"line": 3, "character": 10}, }, "newText": ":ab:cd:text", }, "data": {"fullname": ":ab:cd:text"}, }, { "label": ":xhp:enum-attribute", "kind": 7, "detail": "class", "sortText": ":xhp:enum-attribute", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 9}, "end": {"line": 3, "character": 10}, }, "newText": ":xhp:enum-attribute", }, "data": {"fullname": ":xhp:enum-attribute"}, }, { "label": ":xhp:generic", "kind": 7, "detail": "class", "sortText": ":xhp:generic", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 9}, "end": {"line": 3, "character": 10}, }, "newText": ":xhp:generic", }, "data": {"fullname": ":xhp:generic"}, }, ], }, powered_by="serverless_ide", ) .notification( comment="Add '$x = new :a'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 10}, }, "text": "$x = new :a", } ], }, ) .request( line=line(), comment="autocomplete after '$x = new :a'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 11}, }, result={ "isIncomplete": False, "items": [ { "label": ":ab:cd:alpha", "kind": 7, "detail": "class", "sortText": ":ab:cd:alpha", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 9}, "end": {"line": 3, "character": 11}, }, "newText": ":ab:cd:alpha", }, "data": {"fullname": ":ab:cd:alpha"}, }, { "label": ":ab:cd:text", "kind": 7, "detail": "class", "sortText": ":ab:cd:text", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 9}, "end": {"line": 3, "character": 11}, }, "newText": ":ab:cd:text", }, "data": {"fullname": ":ab:cd:text"}, }, ], }, powered_by="serverless_ide", ) # Note that this request should match the result in the previous example .request( line=line(), comment="autocomplete resolving after '$x = new :a'", method="completionItem/resolve", params={ "label": ":ab:cd:alpha", "kind": 7, "detail": "class", "insertText": ":ab:cd:alpha", "insertTextFormat": 1, "data": {"fullname": ":ab:cd:alpha"}, }, result={ "label": ":ab:cd:alpha", "kind": 7, "detail": "class", "documentation": { "kind": "markdown", "value": ":ab:cd:alpha docblock", }, "insertText": ":ab:cd:alpha", "insertTextFormat": 1, "data": {"fullname": ":ab:cd:alpha"}, }, powered_by="serverless_ide", ) # Try the same thing again, but this time without "new", instead using "<xhp" style .notification( comment="Add '$x = <a'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 11}, }, "text": "$x = <a", } ], }, ) .request( line=line(), comment="autocomplete after '$x = <a'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 7}, }, result={ "isIncomplete": False, "items": [ { "label": "ab:cd:alpha", "kind": 7, "detail": "class", "sortText": "ab:cd:alpha", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 6}, "end": {"line": 3, "character": 7}, }, "newText": "ab:cd:alpha>$0</ab:cd:alpha>", }, "data": {"fullname": ":ab:cd:alpha"}, }, { "label": "ab:cd:text", "kind": 7, "detail": "class", "sortText": "ab:cd:text", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 6}, "end": {"line": 3, "character": 7}, }, "newText": "ab:cd:text>$0</ab:cd:text>", }, "data": {"fullname": ":ab:cd:text"}, }, ], }, powered_by="serverless_ide", ) .request( line=line(), comment="autocomplete resolving after '$x = <a'", method="completionItem/resolve", params={ "label": "ab:cd:alpha", "kind": 7, "detail": "class", "insertText": "ab:cd:alpha", "insertTextFormat": 1, "data": {"fullname": ":ab:cd:alpha"}, }, result={ "label": "ab:cd:alpha", "kind": 7, "detail": "class", "documentation": { "kind": "markdown", "value": ":ab:cd:alpha docblock", }, "insertText": "ab:cd:alpha", "insertTextFormat": 1, "data": {"fullname": ":ab:cd:alpha"}, }, powered_by="serverless_ide", ) .notification( comment="Add '$x = <ab:cd:text/>; $y = $x->'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 7}, }, "text": "$x = <ab:cd:text/>; $y = $x->", } ], }, ) .request( line=line(), comment="autocomplete after '$x = <ab:cd:text/>; $y = $x->'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 29}, }, result={ "isIncomplete": False, "items": [ { "label": ":width", "kind": 5, "detail": "?int", "sortText": ":width", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 29}, "end": {"line": 3, "character": 29}, }, "newText": ":width", }, "data": { "fullname": ":width", "filename": "${root_path}/xhp_class_definitions.php", "line": 5, "char": 27, "base_class": "\\:ab:cd:text", }, }, { "label": ":color", "kind": 5, "detail": "?string", "sortText": ":color", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 29}, "end": {"line": 3, "character": 29}, }, "newText": ":color", }, "data": { "fullname": ":color", "filename": "${root_path}/xhp_class_definitions.php", "line": 5, "char": 13, "base_class": "\\:ab:cd:text", }, }, ], }, powered_by="serverless_ide", ) .notification( comment="Add '$x = <ab:cd:text/>; $y = $x->:'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 29}, }, "text": "$x = <ab:cd:text/>; $y = $x->:", } ], }, ) .request( line=line(), comment="autocomplete after '$x = <ab:cd:text/>; $y = $x->:'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 30}, }, result={ "isIncomplete": False, "items": [ { "label": ":width", "kind": 5, "detail": "?int", "sortText": ":width", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 29}, "end": {"line": 3, "character": 30}, }, "newText": ":width", }, "data": { "fullname": ":width", "filename": "${root_path}/xhp_class_definitions.php", "line": 5, "char": 27, "base_class": "\\:ab:cd:text", }, }, { "label": ":color", "kind": 5, "detail": "?string", "sortText": ":color", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 29}, "end": {"line": 3, "character": 30}, }, "newText": ":color", }, "data": { "fullname": ":color", "filename": "${root_path}/xhp_class_definitions.php", "line": 5, "char": 13, "base_class": "\\:ab:cd:text", }, }, ], }, powered_by="serverless_ide", ) .notification( comment="Add 'test_fun'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 30}, }, "text": "test_fun", } ], }, ) .request( line=line(), comment="autocomplete after 'test_fun'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 8}, }, result={ "isIncomplete": False, "items": [ { "label": "test_function", "kind": 3, "detail": "function", "sortText": "test_function", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 8}, }, "newText": "test_function", }, "data": {"fullname": "test_function"}, } ], }, powered_by="serverless_ide", ) .request( line=line(), comment="autocomplete resolving after 'test_fun'", method="completionItem/resolve", params={ "label": "test_function", "kind": 3, "detail": "function(): void", "insertText": "test_function", "insertTextFormat": 1, "data": { "filename": "${root_path}/completion.php", "line": 8, "char": 10, }, }, result={ "label": "test_function", "kind": 3, "detail": "function(): void", "documentation": { "kind": "markdown", "value": "test_function docblock.", }, "insertText": "test_function", "insertTextFormat": 1, "data": { "filename": "${root_path}/completion.php", "line": 8, "char": 10, }, }, powered_by="serverless_ide", ) .notification( comment="Add 'switch (Elsa::Alonso) { case Elsa:'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 8}, }, "text": "switch (Elsa::Alonso) { case Elsa:", } ], }, ) .request( line=line(), comment="autocomplete after 'switch (Elsa::Alonso) { case Elsa:'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 34}, }, result={"isIncomplete": False, "items": []}, powered_by="serverless_ide", ) .notification( comment="Add 'switch (Elsa::Alonso) { case Elsa::'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 34}, }, "text": "switch (Elsa::Alonso) { case Elsa::", } ], }, ) .request( line=line(), comment="autocomplete after 'switch (Elsa::Alonso) { case Elsa::'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 35}, }, result={ "isIncomplete": False, "items": [ { "label": "class", "kind": 21, "detail": "classname<this>", "sortText": "class", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 35}, "end": {"line": 3, "character": 35}, }, "newText": "class", }, "data": { "fullname": "class", "filename": "${root_path}/completion_extras.php", "line": 3, "char": 6, "base_class": "\\Elsa", }, }, { "label": "Bard", "kind": 21, "detail": "Elsa", "sortText": "Bard", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 35}, "end": {"line": 3, "character": 35}, }, "newText": "Bard", }, "data": { "fullname": "Bard", "filename": "${root_path}/completion_extras.php", "line": 3, "char": 12, "base_class": "\\Elsa", }, }, { "label": "Alonso", "kind": 21, "detail": "Elsa", "sortText": "Alonso", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 35}, "end": {"line": 3, "character": 35}, }, "newText": "Alonso", }, "data": { "fullname": "Alonso", "filename": "${root_path}/completion_extras.php", "line": 3, "char": 12, "base_class": "\\Elsa", }, }, { "label": "isValid", "kind": 2, "detail": "function(mixed $value): bool", "sortText": "isValid", "insertTextFormat": 2, "textEdit": { "range": { "start": {"line": 3, "character": 35}, "end": {"line": 3, "character": 35}, }, "newText": "isValid(${1:\\$value})", }, "data": { "fullname": "isValid", "filename": "/tmp/cleansed_hhi_path/BuiltinEnum.hhi", "line": 51, "char": 34, "base_class": "\\Elsa", }, }, { "label": "getValues", "kind": 2, "detail": "function(): dict<string, Elsa>", "sortText": "getValues", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 35}, "end": {"line": 3, "character": 35}, }, "newText": "getValues()", }, "data": { "fullname": "getValues", "filename": "/tmp/cleansed_hhi_path/BuiltinEnum.hhi", "line": 34, "char": 34, "base_class": "\\Elsa", }, }, { "label": "getNames", "kind": 2, "detail": "function(): dict<Elsa, string>", "sortText": "getNames", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 35}, "end": {"line": 3, "character": 35}, }, "newText": "getNames()", }, "data": { "fullname": "getNames", "filename": "/tmp/cleansed_hhi_path/BuiltinEnum.hhi", "line": 43, "char": 34, "base_class": "\\Elsa", }, }, { "label": "coerce", "kind": 2, "detail": "function(mixed $value): ?Elsa", "sortText": "coerce", "insertTextFormat": 2, "textEdit": { "range": { "start": {"line": 3, "character": 35}, "end": {"line": 3, "character": 35}, }, "newText": "coerce(${1:\\$value})", }, "data": { "fullname": "coerce", "filename": "/tmp/cleansed_hhi_path/BuiltinEnum.hhi", "line": 58, "char": 34, "base_class": "\\Elsa", }, }, { "label": "assertAll", "kind": 2, "detail": "function(Traversable<mixed> $values): Container<Elsa>", "sortText": "assertAll", "insertTextFormat": 2, "textEdit": { "range": { "start": {"line": 3, "character": 35}, "end": {"line": 3, "character": 35}, }, "newText": "assertAll(${1:\\$values})", }, "data": { "fullname": "assertAll", "filename": "/tmp/cleansed_hhi_path/BuiltinEnum.hhi", "line": 72, "char": 34, "base_class": "\\Elsa", }, }, { "label": "assert", "kind": 2, "detail": "function(mixed $value): Elsa", "sortText": "assert", "insertTextFormat": 2, "textEdit": { "range": { "start": {"line": 3, "character": 35}, "end": {"line": 3, "character": 35}, }, "newText": "assert(${1:\\$value})", }, "data": { "fullname": "assert", "filename": "/tmp/cleansed_hhi_path/BuiltinEnum.hhi", "line": 65, "char": 34, "base_class": "\\Elsa", }, }, ], }, powered_by="serverless_ide", ) .notification( comment="Add 'switch (Elsa::Alonso) { case Elsa::Alonso:'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 35}, }, "text": "switch (Elsa::Alonso) { case Elsa::Alonso:", } ], }, ) .request( line=line(), comment="autocomplete after 'switch (Elsa::Alonso) { case Elsa::Alonso:'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 42}, }, result={"isIncomplete": False, "items": []}, powered_by="serverless_ide", ) .notification( comment="Add 'TestNS\\'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 42}, }, "text": "TestNS\\", } ], }, ) .request( line=line(), comment="autocomplete after 'TestNS\\'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 7}, }, result={ "isIncomplete": False, "items": [ { "label": "test_func", "kind": 3, "detail": "function", "sortText": "test_func", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 7}, "end": {"line": 3, "character": 7}, }, "newText": "test_func", }, "data": {"fullname": "TestNS\\test_func"}, } ], }, powered_by="serverless_ide", ) .notification( comment="Add '$cc = new CompletionClass(); $cc->interfa'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 7}, }, "text": "$cc = new CompletionClass(); $cc->interfa", } ], }, ) .request( line=line(), comment="autocomplete after '$cc = new CompletionClass(); $cc->interfa'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 41}, }, result={ "isIncomplete": False, "items": [ { "label": "interfaceDocBlockMethod", "kind": 2, "detail": "function(): void", "sortText": "interfaceDocBlockMethod", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 34}, "end": {"line": 3, "character": 41}, }, "newText": "interfaceDocBlockMethod()", }, "data": { "fullname": "interfaceDocBlockMethod", "filename": "${root_path}/completion.php", "line": 18, "char": 19, "base_class": "\\CompletionClass", }, } ], }, powered_by="serverless_ide", ) .request( line=line(), comment="autocomplete resolving after '$cc = new CompletionClass(); $cc->interfa'", method="completionItem/resolve", params={ "label": "interfaceDocBlockMethod", "kind": 2, "detail": "function(): void", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 34}, "end": {"line": 3, "character": 41}, }, "newText": "interfaceDocBlockMethod", }, "data": { "filename": "${root_path}/completion.php", "line": 18, "char": 19, }, }, result={ "label": "interfaceDocBlockMethod", "kind": 2, "detail": "function(): void", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 34}, "end": {"line": 3, "character": 41}, }, "newText": "interfaceDocBlockMethod", }, "data": { "filename": "${root_path}/completion.php", "line": 18, "char": 19, }, }, powered_by="serverless_ide", ) .notification( comment="Add 'DeprecatedClass::'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 41}, }, "text": "DeprecatedClass::", } ], }, ) .request( line=line(), comment="autocomplete after 'DeprecatedClass::'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 17}, }, result={ "isIncomplete": False, "items": [ { "label": "class", "kind": 21, "detail": "classname<this>", "sortText": "class", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 17}, "end": {"line": 3, "character": 17}, }, "newText": "class", }, "data": { "fullname": "class", "filename": "${root_path}/completion_extras.php", "line": 8, "char": 13, "base_class": "\\DeprecatedClass", }, }, { "label": "test_do_not_use", "kind": 2, "detail": "function(): void", "sortText": "~test_do_not_use", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 17}, "end": {"line": 3, "character": 17}, }, "newText": "test_do_not_use()", }, "data": { "fullname": "test_do_not_use", "filename": "${root_path}/completion_extras.php", "line": 12, "char": 26, "base_class": "\\DeprecatedClass", }, }, { "label": "getName", "kind": 2, "detail": "function(): void", "sortText": "getName", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 17}, "end": {"line": 3, "character": 17}, }, "newText": "getName()", }, "data": { "fullname": "getName", "filename": "${root_path}/completion_extras.php", "line": 9, "char": 26, "base_class": "\\DeprecatedClass", }, }, { "label": "getAttributes_DO_NOT_USE", "kind": 2, "detail": "function(): void", "sortText": "~getAttributes_DO_NOT_USE", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 17}, "end": {"line": 3, "character": 17}, }, "newText": "getAttributes_DO_NOT_USE()", }, "data": { "fullname": "getAttributes_DO_NOT_USE", "filename": "${root_path}/completion_extras.php", "line": 11, "char": 26, "base_class": "\\DeprecatedClass", }, }, { "label": "__getLoader", "kind": 2, "detail": "function(): void", "sortText": "~__getLoader", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 17}, "end": {"line": 3, "character": 17}, }, "newText": "__getLoader()", }, "data": { "fullname": "__getLoader", "filename": "${root_path}/completion_extras.php", "line": 10, "char": 26, "base_class": "\\DeprecatedClass", }, }, ], }, powered_by="serverless_ide", ) .notification( comment="Add 'call_lambda(3, $m'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 30, "character": 0}, "end": {"line": 30, "character": 0}, }, "text": " call_lambda(3, $m", } ], }, ) .request( line=line(), comment="autocomplete results for 'call_lambda(3, $m'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 30, "character": 19}, }, result={ "isIncomplete": False, "items": [ { "label": "$mylambda", "kind": 6, "detail": "(function(int $n): int)", "sortText": "$mylambda", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 30, "character": 17}, "end": {"line": 30, "character": 19}, }, "newText": "$mylambda", }, "data": { "fullname": "$mylambda", "filename": "${root_path}/completion.php", "line": 30, "char": 15, }, } ], }, powered_by="serverless_ide", ) .request( line=line(), comment="resolve autocompletion for $mylambda'", method="completionItem/resolve", params={ "label": "$mylambda", "kind": 6, "detail": "(function(int $n): int)", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 30, "character": 17}, "end": {"line": 30, "character": 19}, }, "newText": "$mylambda", }, "data": { "filename": "${root_path}/completion.php", "line": 30, "char": 15, }, }, result={ "label": "$mylambda", "kind": 6, "detail": "(function(int $n): int)", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 30, "character": 17}, "end": {"line": 30, "character": 19}, }, "newText": "$mylambda", }, "data": { "filename": "${root_path}/completion.php", "line": 30, "char": 15, }, }, powered_by="serverless_ide", ) .notification( comment="Add '<xhp:enum-attribute enum-attribute={}'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 17}, }, "text": "<xhp:enum-attribute enum-attribute={}", } ], }, ) .request( line=line(), comment="autocomplete after '<xhp:enum-attribute enum-attribute={'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 36}, "context": {"triggerKind": 2, "triggerCharacter": "{"}, }, result={ "isIncomplete": False, "items": [ { "label": "MyEnum::TYPE_C", "kind": 13, "detail": "enum", "sortText": "MyEnum::TYPE_C", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 36}, "end": {"line": 3, "character": 36}, }, "newText": "MyEnum::TYPE_C", }, "data": { "fullname": "MyEnum::TYPE_C", "filename": "${root_path}/xhp_class_definitions.php", "line": 13, "char": 14, "base_class": "\\MyEnum", }, }, { "label": "MyEnum::TYPE_B", "kind": 13, "detail": "enum", "sortText": "MyEnum::TYPE_B", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 36}, "end": {"line": 3, "character": 36}, }, "newText": "MyEnum::TYPE_B", }, "data": { "fullname": "MyEnum::TYPE_B", "filename": "${root_path}/xhp_class_definitions.php", "line": 13, "char": 14, "base_class": "\\MyEnum", }, }, { "label": "MyEnum::TYPE_A", "kind": 13, "detail": "enum", "sortText": "MyEnum::TYPE_A", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 36}, "end": {"line": 3, "character": 36}, }, "newText": "MyEnum::TYPE_A", }, "data": { "fullname": "MyEnum::TYPE_A", "filename": "${root_path}/xhp_class_definitions.php", "line": 13, "char": 14, "base_class": "\\MyEnum", }, }, ], }, powered_by="serverless_ide", ) .notification( comment="Add '1 is strin'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 37}, }, "text": "1 is strin", } ], }, ) .request( line=line(), comment="autocomplete after '1 is strin'", method="textDocument/completion", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 10}, }, result={ "isIncomplete": False, "items": [ { "label": "string", "kind": 25, "detail": "builtin", "documentation": { "kind": "markdown", "value": "A sequence of characters.", }, "sortText": "string", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 5}, "end": {"line": 3, "character": 10}, }, "newText": "string", }, "data": {"fullname": "string"}, }, { "label": "StringBuffer", "kind": 7, "detail": "class", "sortText": "StringBuffer", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 5}, "end": {"line": 3, "character": 10}, }, "newText": "StringBuffer", }, "data": {"fullname": "StringBuffer"}, }, { "label": "Stringish", "kind": 8, "detail": "interface", "sortText": "Stringish", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 5}, "end": {"line": 3, "character": 10}, }, "newText": "Stringish", }, "data": {"fullname": "Stringish"}, }, { "label": "StringishObject", "kind": 8, "detail": "interface", "sortText": "StringishObject", "insertTextFormat": 1, "textEdit": { "range": { "start": {"line": 3, "character": 5}, "end": {"line": 3, "character": 10}, }, "newText": "StringishObject", }, "data": {"fullname": "StringishObject"}, }, ], }, powered_by="serverless_ide", ) .request( line=line(), comment="autocomplete resolving after '1 is strin'", method="completionItem/resolve", params={ "data": {"fullname": "string"}, "detail": "builtin", "documentation": { "kind": "markdown", "value": "A sequence of characters.", }, "insertText": "string", "insertTextFormat": 1, "kind": 25, "label": "string", "sortText": "string", }, result={ "data": {"fullname": "string"}, "detail": "builtin", "documentation": { "kind": "markdown", "value": "A sequence of characters.", }, "insertText": "string", "insertTextFormat": 1, "kind": 25, "label": "string", "sortText": "string", }, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_definition(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("definition.php")) spec = ( self.initialize_spec(LspTestSpec("serverless_ide_definition")) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), comment="call to `b_definition`", method="textDocument/definition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 10}, }, result=[ { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 6, "character": 9}, "end": {"line": 6, "character": 21}, }, "title": "b_definition", } ], powered_by="serverless_ide", ) .request( line=line(), comment="call to `new BB(1)`", method="textDocument/definition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 29, "character": 13}, }, result=[ { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 11, "character": 18}, "end": {"line": 11, "character": 29}, }, "title": "BB::__construct", } ], powered_by="serverless_ide", ) .request( line=line(), comment="call to `new CC(1)`", method="textDocument/definition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 30, "character": 13}, }, result=[ { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 14, "character": 6}, "end": {"line": 14, "character": 8}, }, "title": "CC", }, { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 11, "character": 18}, "end": {"line": 11, "character": 29}, }, "title": "BB::__construct", }, ], powered_by="serverless_ide", ) .request( line=line(), comment="call to `new DD(1)`", method="textDocument/definition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 31, "character": 13}, }, result=[ { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 17, "character": 6}, "end": {"line": 17, "character": 8}, }, "title": "DD", }, { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 11, "character": 18}, "end": {"line": 11, "character": 29}, }, "title": "BB::__construct", }, ], powered_by="serverless_ide", ) .request( line=line(), comment="call to `new EE(1)`", method="textDocument/definition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 32, "character": 13}, }, result=[ { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 21, "character": 18}, "end": {"line": 21, "character": 29}, }, "title": "EE::__construct", } ], powered_by="serverless_ide", ) .request( line=line(), comment="call to `new FF(1)`", method="textDocument/definition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 33, "character": 13}, }, result=[ { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 26, "character": 6}, "end": {"line": 26, "character": 8}, }, "title": "FF", } ], powered_by="serverless_ide", ) .request( line=line(), comment="call to `new TakesString(HasString::MyString)`", method="textDocument/definition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 45, "character": 23}, }, result=[ { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 40, "character": 6}, "end": {"line": 40, "character": 15}, }, "title": "HasString", } ], powered_by="serverless_ide", ) .notification( comment="make local, unsaved change to the file", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}", "version": 2}, "contentChanges": [ { "text": "test", "range": { "start": {"line": 3, "character": 9}, "end": {"line": 3, "character": 21}, }, } ], }, ) .request( line=line(), comment="call to `test` instead of `b_definition`", method="textDocument/definition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 10}, }, result=[ { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 28, "character": 9}, "end": {"line": 28, "character": 13}, }, "title": "test", } ], powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_overridden_definition(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("override.php")) spec = ( self.initialize_spec( LspTestSpec("serverless_ide_overridden_definition"), ) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), comment="find overridden method from trait. It's arbitrary which one we pick. This test embodies the current implementation.", method="textDocument/definition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 13, "character": 5}, }, result=[ { "uri": "${php_file_uri}", "range": { "start": {"line": 3, "character": 18}, "end": {"line": 3, "character": 21}, }, "title": "MyParent::foo", } ], powered_by="serverless_ide", ) .request( line=line(), comment="find overridden static method. It's arbitrary which one we pick. This test embodies the current implementation.", method="textDocument/definition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 26, "character": 5}, }, result=[ { "uri": "file://${root_path}/override.php", "range": { "start": {"line": 23, "character": 25}, "end": {"line": 23, "character": 28}, }, "title": "C2::bar", } ], powered_by="serverless_ide", ) .request( line=line(), comment="find overridden interface method", method="textDocument/definition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 35, "character": 5}, }, result=[ { "uri": "file://${root_path}/override.php", "range": { "start": {"line": 32, "character": 18}, "end": {"line": 32, "character": 22}, }, "title": "I1::quux", } ], powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_document_symbol(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("definition.php")) spec = ( self.initialize_spec(LspTestSpec("serverless_ide_document_symbol")) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), comment="documentSymbol call", method="textDocument/documentSymbol", params={"textDocument": {"uri": "${php_file_uri}"}}, result=[ { "name": "First", "kind": 14, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 50, "character": 18}, "end": {"line": 50, "character": 47}, }, }, "containerName": "MyEnumClass", }, { "name": "MyEnumClass", "kind": 10, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 49, "character": 0}, "end": {"line": 52, "character": 1}, }, }, }, { "name": "testClassMemberInsideConstructorInvocation", "kind": 12, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 44, "character": 0}, "end": {"line": 46, "character": 1}, }, }, }, { "name": "MyString", "kind": 14, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 41, "character": 8}, "end": {"line": 41, "character": 29}, }, }, "containerName": "HasString", }, { "name": "HasString", "kind": 5, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 40, "character": 0}, "end": {"line": 42, "character": 1}, }, }, }, { "name": "__construct", "kind": 6, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 37, "character": 2}, "end": {"line": 37, "character": 43}, }, }, "containerName": "TakesString", }, { "name": "TakesString", "kind": 5, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 36, "character": 0}, "end": {"line": 38, "character": 1}, }, }, }, { "name": "FF", "kind": 5, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 26, "character": 0}, "end": {"line": 26, "character": 11}, }, }, }, { "name": "__construct", "kind": 6, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 21, "character": 2}, "end": {"line": 23, "character": 3}, }, }, "containerName": "EE", }, { "name": "EE", "kind": 5, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 20, "character": 0}, "end": {"line": 24, "character": 1}, }, }, }, { "name": "CC", "kind": 5, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 14, "character": 0}, "end": {"line": 15, "character": 1}, }, }, }, { "name": "__construct", "kind": 6, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 11, "character": 2}, "end": {"line": 11, "character": 40}, }, }, "containerName": "BB", }, { "name": "BB", "kind": 5, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 10, "character": 0}, "end": {"line": 12, "character": 1}, }, }, }, { "name": "a_definition", "kind": 12, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 2, "character": 0}, "end": {"line": 4, "character": 1}, }, }, }, { "name": "b_definition", "kind": 12, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 6, "character": 0}, "end": {"line": 8, "character": 1}, }, }, }, { "name": "DD", "kind": 5, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 17, "character": 0}, "end": {"line": 18, "character": 1}, }, }, }, { "name": "test", "kind": 12, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 28, "character": 0}, "end": {"line": 34, "character": 1}, }, }, }, { "name": "MyEnumClassKind", "kind": 5, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 48, "character": 0}, "end": {"line": 48, "character": 24}, }, }, }, { "name": "Second", "kind": 14, "location": { "uri": "${php_file_uri}", "range": { "start": {"line": 51, "character": 18}, "end": {"line": 51, "character": 48}, }, }, "containerName": "MyEnumClass", }, ], powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def initialize_spec( self, spec: LspTestSpec, has_status_capability: bool = False, # do we tell the server that we have the "status" capability, i.e. want to receive window/showStatus? wait_for_init_done: bool = True, # do we wish to wait for init to be done before the test starts? ) -> LspTestSpec: initialization_options = { "namingTableSavedStatePath": "${naming_table_saved_state_path}", "namingTableSavedStateTestDelay": 0.0, } if not wait_for_init_done: # A small delay, since otherwise init completes immediately # This isn't very racy. All we need is a tiny delay so that # other things which are in the queue get processed, rather # than continuing synchronously initialization_options["namingTableSavedStateTestDelay"] = 0.5 window_capabilities = {} if has_status_capability: window_capabilities["status"] = {"dynamicRegistration": False} spec = spec.ignore_notifications(method="telemetry/event").request( line=line(), method="initialize", params={ "initializationOptions": initialization_options, "processId": None, "rootPath": "${root_path}", "capabilities": { "window": window_capabilities, "textDocument": { "completion": {"completionItem": {"snippetSupport": True}} }, }, }, result={ "capabilities": { "textDocumentSync": { "openClose": True, "change": 2, "willSave": False, "willSaveWaitUntil": True, "save": {"includeText": False}, }, "hoverProvider": True, "completionProvider": { "resolveProvider": True, "triggerCharacters": [ "$", ">", "\\", ":", "<", "[", "'", '"', "{", "#", ], }, "signatureHelpProvider": {"triggerCharacters": ["(", ","]}, "definitionProvider": True, "typeDefinitionProvider": True, "referencesProvider": True, "documentHighlightProvider": True, "documentSymbolProvider": True, "workspaceSymbolProvider": True, "codeActionProvider": {"resolveProvider": True}, "documentFormattingProvider": True, "documentRangeFormattingProvider": True, "documentOnTypeFormattingProvider": { "firstTriggerCharacter": ";", "moreTriggerCharacter": ["}"], }, "renameProvider": True, "implementationProvider": True, "rageProvider": True, "experimental": {"snippetTextEdit": True}, } }, ) spec = spec.wait_for_server_request( method="client/registerCapability", params={ "registrations": [ { "id": "did-change-watched-files", "method": "workspace/didChangeWatchedFiles", "registerOptions": { "watchers": [ { "globPattern": "**/*.{php,phpt,hack,hackpartial,hck,hh,hhi,xhp}", "kind": 7, } ] }, } ] }, result=None, ) if wait_for_init_done: spec = spec.wait_for_notification( comment="wait for clientIdeDaemon to finish init", method="telemetry/event", params={"type": 4, "message": "[client-ide] Finished init: ok"}, ) return spec def test_serverless_ide_type_definition(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("type_definition.php")) spec = ( self.initialize_spec(LspTestSpec("serverless_ide_type_definition")) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), comment="Conditional Type Definition of HH or II", method="textDocument/typeDefinition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 32, "character": 2}, }, result=[ { "uri": "${php_file_uri}", "range": { "start": {"line": 2, "character": 6}, "end": {"line": 2, "character": 8}, }, "title": "\\HH", }, { "uri": "${php_file_uri}", "range": { "start": {"line": 12, "character": 6}, "end": {"line": 12, "character": 8}, }, "title": "\\LL", }, ], powered_by="serverless_ide", ) .request( line=line(), comment="Standard Class Definition", method="textDocument/typeDefinition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 40, "character": 2}, }, result=[ { "uri": "${php_file_uri}", "range": { "start": {"line": 2, "character": 6}, "end": {"line": 2, "character": 8}, }, "title": "\\HH", } ], powered_by="serverless_ide", ) .request( line=line(), comment="Class Type Definition with Casting", method="textDocument/typeDefinition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 41, "character": 2}, }, result=[ { "uri": "${php_file_uri}", "range": { "start": {"line": 2, "character": 6}, "end": {"line": 2, "character": 8}, }, "title": "\\HH", } ], powered_by="serverless_ide", ) .request( line=line(), comment="Primitive Type Definition", method="textDocument/typeDefinition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 42, "character": 2}, }, result=[], powered_by="serverless_ide", ) .request( line=line(), comment="Function Return Type Definition", method="textDocument/typeDefinition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 43, "character": 2}, }, result=[ { "uri": "${php_file_uri}", "range": { "start": {"line": 12, "character": 6}, "end": {"line": 12, "character": 8}, }, "title": "\\LL", } ], powered_by="serverless_ide", ) .request( line=line(), comment="Function definition with primitive return type", method="textDocument/typeDefinition", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 44, "character": 2}, }, result=[ { "uri": "${php_file_uri}", "range": { "start": {"line": 22, "character": 9}, "end": {"line": 22, "character": 29}, }, "title": "(function(): int)", } ], powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_hover(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("hover.php")) spec = ( self.initialize_spec(LspTestSpec("serverless_ide_hover")) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), comment="hover over function invocation", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 16}, }, result={ "contents": [ {"language": "hack", "value": "int"}, "A comment describing b_hover.", ], "range": { "start": {"line": 3, "character": 9}, "end": {"line": 3, "character": 16}, }, }, powered_by="serverless_ide", ) .request( line=line(), comment="hover over string literal outside call", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 25, "character": 12}, # 9 - 16 }, result={"contents": [{"language": "hack", "value": "string"}]}, powered_by="serverless_ide", ) .request( line=line(), comment="hover over string literal inside call", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 26, "character": 20}, # 16 - 29 }, result={ "contents": [ {"language": "hack", "value": "string"}, {"language": "hack", "value": "Parameter: $s"}, ] }, powered_by="serverless_ide", ) .request( line=line(), comment="hover over int literal inside call", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 26, "character": 32}, # 31 - 33 }, result={ "contents": [ {"language": "hack", "value": "int"}, {"language": "hack", "value": "Parameter: $i"}, ] }, powered_by="serverless_ide", ) .request( line=line(), comment="hover over constant reference", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 15, "character": 19}, }, result={ "contents": [ {"language": "hack", "value": "THE_ANSWER"}, "A comment describing THE_ANSWER", ], "range": { "start": {"line": 15, "character": 9}, "end": {"line": 15, "character": 19}, }, }, powered_by="serverless_ide", ) .request( line=line(), comment="hover over whitespace", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 1}, }, result=None, powered_by="serverless_ide", ) .request( line=line(), comment="hover over a comment", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 1, "character": 4}, }, result=None, powered_by="serverless_ide", ) .request( line=line(), comment="hover past the end of a line", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 100}, }, result=None, powered_by="serverless_ide", ) .request( line=line(), comment="hover past the end of a file", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 300, "character": 0}, }, result=None, powered_by="serverless_ide", ) .request( line=line(), comment="hover over class with copyright docblock", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 37, "character": 15}, }, result={ "contents": [ {"language": "hack", "value": "final class CopyrightClass"}, "Testing copyright removal", ], "range": { "start": {"line": 37, "character": 2}, "end": {"line": 37, "character": 16}, }, }, powered_by="serverless_ide", ) .request( line=line(), comment="hover over class with generated docblock", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 58, "character": 15}, }, result={ "contents": [ {"language": "hack", "value": "final class GeneratedClass"}, "Testing generated text removal", ], "range": { "start": {"line": 58, "character": 2}, "end": {"line": 58, "character": 16}, }, }, powered_by="serverless_ide", ) .request( line=line(), comment="hover over an primitive attribute in an xhp literal", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 62, "character": 25}, }, result={ "contents": [ {"language": "hack", "value": "attribute ?string name"}, ":xhp:enum-attribute::name docblock", ], "range": { "start": {"line": 62, "character": 22}, "end": {"line": 62, "character": 26}, }, }, powered_by="serverless_ide", ) .request( line=line(), comment="hover over a nonprimitive attribute in an xhp literal", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 62, "character": 36}, }, result={ "contents": [ { "language": "hack", "value": "attribute ?MyEnum enum-attribute", } ], "range": { "start": {"line": 62, "character": 33}, "end": {"line": 62, "character": 47}, }, }, powered_by="serverless_ide", ) .request( line=line(), comment="hover over a generic attribute in an xhp literal", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 63, "character": 16}, }, result={ "contents": [ {"language": "hack", "value": "attribute ?ID<EntSomething> id"} ], "range": { "start": {"line": 63, "character": 15}, "end": {"line": 63, "character": 17}, }, }, powered_by="serverless_ide", ) .notification( comment="Add '<xhp:enum-attribute name' to test hover for incomplete xhp attribute", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 69, "character": 0}, "end": {"line": 69, "character": 0}, }, "text": "<xhp:enum-attribute name", } ], }, ) .request( line=line(), comment="hover over an attribute in an xhp literal without a value", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 69, "character": 22}, }, result={ "contents": [ {"language": "hack", "value": "attribute ?string name"}, ":xhp:enum-attribute::name docblock", ], "range": { "start": {"line": 69, "character": 20}, "end": {"line": 69, "character": 24}, }, }, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_file_touched_on_disk(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("hover.php")) spec = ( self.initialize_spec( LspTestSpec("serverless_ide_file_on_disk_change"), ) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .notification( method="workspace/didChangeWatchedFiles", params={"changes": [{"uri": "${php_file_uri}", "type": 2}]}, ) .request( line=line(), method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 16}, }, result={ "contents": [ {"language": "hack", "value": "int"}, "A comment describing b_hover.", ], "range": { "start": {"line": 3, "character": 9}, "end": {"line": 3, "character": 16}, }, }, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_file_hover_with_errors(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("hover_with_errors.php")) spec = ( self.initialize_spec( LspTestSpec("serverless_ide_file_hover_with_errors"), ) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), comment="Totally normal hover", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 14, "character": 37}, }, result={ "contents": [ { "language": "hack", "value": "// Defined in HoverWithErrorsClass\npublic static function staticMethod(string $z): void", }, 'During testing, we\'ll remove the "public" tag from this ' "method\n" "to ensure that we can still get IDE services", ], "range": { "end": {"character": 39, "line": 14}, "start": {"character": 27, "line": 14}, }, }, powered_by="serverless_ide", ) .notification( comment="Remove the 'public' visibility modifier which triggers AST->AAST errors", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 10, "character": 2}, "end": {"line": 10, "character": 8}, }, "text": "", } ], }, ) .request( line=line(), comment="Hover should still work even if visibility modifier has been removed", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 14, "character": 37}, }, result={ "contents": [ { "language": "hack", "value": "// Defined in HoverWithErrorsClass\npublic static function staticMethod(string $z): void", }, 'During testing, we\'ll remove the "public" tag from this ' "method\n" "to ensure that we can still get IDE services", ], "range": { "end": {"character": 39, "line": 14}, "start": {"character": 27, "line": 14}, }, }, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_formatting(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("messy.php")) spec = ( self.initialize_spec(LspTestSpec("formatting")) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), method="textDocument/formatting", params={ "textDocument": {"uri": "${php_file_uri}"}, "options": {"tabSize": 5, "insertSpaces": True}, }, result=[ { "range": { "start": {"line": 0, "character": 0}, "end": {"line": 11, "character": 0}, }, "newText": "<?hh //strict\n\nfunction x(): string {\n" + ' $a = "this";\n\n' + ' $b = "is";\n\n' + ' $c = "messy";\n\n' + ' $d = ".";\n' + ' return "$a"."$b"."$c"."d";\n', } ], ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_rangeformatting(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("messy.php")) spec = ( self.initialize_spec(LspTestSpec("range_formatting")) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), method="textDocument/rangeFormatting", params={ "textDocument": {"uri": "${php_file_uri}"}, "range": { "start": {"line": 3, "character": 0}, "end": {"line": 4, "character": 0}, }, "options": {"tabSize": 5, "insertSpaces": True}, }, result=[ { "range": { "start": {"line": 3, "character": 0}, "end": {"line": 4, "character": 0}, }, "newText": ' $a = "this";\n', } ], ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_ontypeformatting(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("ontypeformatting.php")) spec = ( self.initialize_spec(LspTestSpec("ontypeformatting")) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), method="textDocument/onTypeFormatting", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 9, "character": 58}, "ch": ";", "options": {"tabSize": 2, "insertSpaces": True}, }, result=[ { "range": { "start": {"line": 5, "character": 23}, "end": {"line": 9, "character": 58}, }, "newText": "{\n test_otf(\n" + " '1234567890',\n" + " '1234567890',\n" + " '1234567890',\n" + " '1234567890',\n" + " '1234567890',\n" + " '1234567890',\n );", } ], ) .request( line=line(), method="textDocument/onTypeFormatting", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 15, "character": 23}, "ch": "}", "options": {"tabSize": 2, "insertSpaces": True}, }, result=[ { "range": { "start": {"line": 15, "character": 0}, "end": {"line": 15, "character": 23}, }, "newText": "function otf(): void {}", } ], ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_did_change(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("didchange.php")) spec = ( self.initialize_spec(LspTestSpec("did_change")) .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .wait_for_notification( method="textDocument/publishDiagnostics", params={"uri": "${php_file_uri}", "diagnostics": []}, ) .notification( method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 7, "character": 11}, "end": {"line": 7, "character": 12}, }, "text": "a", } ], }, ) .wait_for_notification( method="textDocument/publishDiagnostics", params={ "uri": "${php_file_uri}", "diagnostics": [ { "range": { "start": {"line": 7, "character": 11}, "end": {"line": 7, "character": 11}, }, "severity": 1, "code": 1002, "source": "Hack", "message": "A semicolon ; is expected here.", "relatedLocations": [], "relatedInformation": [], } ], }, ) .request(line=line(), method="shutdown", params={}, result=None) .wait_for_notification( comment="Hack appears to clear out diagnostics before shutting down", method="textDocument/publishDiagnostics", params={"uri": "${php_file_uri}", "diagnostics": []}, ) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_fixme(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("fixme.php")) spec = ( self.initialize_spec(LspTestSpec("fixme")) .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .wait_for_notification( method="textDocument/publishDiagnostics", params={"uri": "${php_file_uri}", "diagnostics": []}, ) .notification( comment="disable the first fixme by turning 'HH_FIXME' into 'NO_FIXME'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 5}, "end": {"line": 3, "character": 7}, }, "text": "NO", } ], }, ) .wait_for_notification( method="textDocument/publishDiagnostics", params={ "uri": "${php_file_uri}", "diagnostics": [ { "range": { "start": {"line": 4, "character": 9}, "end": {"line": 4, "character": 10}, }, "severity": 1, "code": 4110, "source": "Hack", "message": "Invalid return type", "relatedInformation": [ { "location": { "uri": "${php_file_uri}", "range": { "start": {"line": 2, "character": 25}, "end": {"line": 2, "character": 31}, }, }, "message": "Expected string", }, { "location": { "uri": "${php_file_uri}", "range": { "start": {"line": 4, "character": 9}, "end": {"line": 4, "character": 10}, }, }, "message": "But got int", }, ], "relatedLocations": [ { "location": { "uri": "${php_file_uri}", "range": { "start": {"line": 2, "character": 25}, "end": {"line": 2, "character": 31}, }, }, "message": "Expected string", }, { "location": { "uri": "${php_file_uri}", "range": { "start": {"line": 4, "character": 9}, "end": {"line": 4, "character": 10}, }, }, "message": "But got int", }, ], } ], }, ) .notification( comment="restore the first fixme by turning 'NO_FIXME' back 'HH_FIXME'", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 3, "character": 5}, "end": {"line": 3, "character": 7}, }, "text": "HH", } ], }, ) .wait_for_notification( method="textDocument/publishDiagnostics", params={"uri": "${php_file_uri}", "diagnostics": []}, ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_go_to_implementation(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("go_to_implementation.php")) self.test_driver.start_hh_server() self.test_driver.run_check() spec = ( self.initialize_spec(LspTestSpec("test_go_to_implementation")) .ignore_notifications(method="textDocument/publishDiagnostics") .wait_for_hh_server_ready() .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), comment="go to implementation: abstract class", method="textDocument/implementation", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 1, "character": 17}, }, result=[ { "uri": "${php_file_uri}", "range": { "start": {"line": 7, "character": 6}, "end": {"line": 7, "character": 9}, }, } ], ) .request( line=line(), comment="go to implementation: interface", method="textDocument/implementation", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 13, "character": 13}, }, result=[ { "uri": "${php_file_uri}", "range": { "start": {"line": 17, "character": 6}, "end": {"line": 17, "character": 9}, }, } ], ) .request( line=line(), comment="go to implementation: trait", method="textDocument/implementation", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 23, "character": 10}, }, result=[ { "uri": "${php_file_uri}", "range": { "start": {"line": 30, "character": 6}, "end": {"line": 30, "character": 16}, }, } ], ) .request( line=line(), comment="go to implementation: method", method="textDocument/implementation", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 19, "character": 18}, }, result=[ { "uri": "${php_file_uri}", "range": { "start": {"line": 8, "character": 18}, "end": {"line": 8, "character": 22}, }, } ], ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_signature_help(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("signaturehelp.php")) spec = ( self.initialize_spec(LspTestSpec("test_signature_help")) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), comment="signature help for 0-argument constructor" " (left of opening paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 16, "character": 18}, }, result=None, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 0-argument constructor", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 16, "character": 19}, }, result={ "signatures": [ { "label": "public function __construct(): void", "documentation": "Constructor with doc block", "parameters": [], } ], "activeSignature": 0, "activeParameter": 0, }, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 0-argument constructor" " (right of closing paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 16, "character": 20}, }, result=None, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 2-argument instance method" " (left of opening paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 17, "character": 20}, }, result=None, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 2-argument instance method" " (right of opening paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 17, "character": 21}, }, result={ "signatures": [ { "label": "public function instanceMethod" "(int $x1, int $x2): void", "documentation": "Instance method with doc block", "parameters": [{"label": "$x1"}, {"label": "$x2"}], } ], "activeSignature": 0, "activeParameter": 0, }, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 2-argument instance method" " (left of first comma)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 17, "character": 22}, }, result={ "signatures": [ { "label": "public function instanceMethod" "(int $x1, int $x2): void", "documentation": "Instance method with doc block", "parameters": [{"label": "$x1"}, {"label": "$x2"}], } ], "activeSignature": 0, "activeParameter": 1, }, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 2-argument instance method" " (right of first comma)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 17, "character": 23}, }, result={ "signatures": [ { "label": "public function instanceMethod" "(int $x1, int $x2): void", "documentation": "Instance method with doc block", "parameters": [{"label": "$x1"}, {"label": "$x2"}], } ], "activeSignature": 0, "activeParameter": 1, }, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 2-argument instance method" " (left of closing paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 17, "character": 24}, }, result={ "signatures": [ { "label": "public function instanceMethod" "(int $x1, int $x2): void", "documentation": "Instance method with doc block", "parameters": [{"label": "$x1"}, {"label": "$x2"}], } ], "activeSignature": 0, "activeParameter": 1, }, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 2-argument instance method" " (right of closing paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 17, "character": 25}, }, result=None, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 1-argument static method" " (left of open paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 18, "character": 23}, }, result=None, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 1-argument static method" " (right of open paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 18, "character": 24}, }, result={ "signatures": [ { "label": "public static function staticMethod" "(string $z): void", "documentation": "Static method with doc block", "parameters": [{"label": "$z"}], } ], "activeSignature": 0, "activeParameter": 0, }, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 2-argument global function" " (left of open paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 19, "character": 17}, }, result=None, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 2-argument global function" " (right of open paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 19, "character": 18}, }, result={ "signatures": [ { "label": "function global_function" "(string $s, int $x): void", "documentation": "Global function with doc block", "parameters": [{"label": "$s"}, {"label": "$x"}], } ], "activeSignature": 0, "activeParameter": 0, }, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 1-argument namespace-aliased global" " function (right of open paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 20, "character": 26}, }, result=None, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 1-argument namespace-aliased global" " function (right of open paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 20, "character": 26}, }, result=None, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 1-argument namespace-aliased global" " function (right of open paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 20, "character": 27}, }, result={ "signatures": [ { "label": "function aliased_global_func(string $s): void", "documentation": "Namespace-aliased function with doc block", "parameters": [{"label": "$s"}], } ], "activeSignature": 0, "activeParameter": 0, }, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 1-argument namespace-aliased global" " function (right of open paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 20, "character": 28}, }, result={ "signatures": [ { "label": "function aliased_global_func(string $s): void", "documentation": "Namespace-aliased function with doc block", "parameters": [{"label": "$s"}], } ], "activeSignature": 0, "activeParameter": 0, }, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 2-argument function with params" " (right of open paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 21, "character": 30}, }, result={ "signatures": [ { "label": "function test_signature_help_params1(" "\n string $param1,\n string $param2\n): void", "documentation": "comment describing the method" "\n@param $param1 info1" "\n@param param2 info2", "parameters": [ {"label": "$param1", "documentation": "info1"}, {"label": "$param2", "documentation": "info2"}, ], } ], "activeSignature": 0, "activeParameter": 0, }, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 2-argument function with params" " (right of open paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 22, "character": 30}, }, result={ "signatures": [ { "label": "function test_signature_help_params2(" "\n string $param1,\n string $param2\n): void", "documentation": "comment describing the method" "\n@param $param1 info1", "parameters": [ {"label": "$param1", "documentation": "info1"}, {"label": "$param2"}, ], } ], "activeSignature": 0, "activeParameter": 0, }, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for 2-argument function with params" " (right of open paren)", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 23, "character": 30}, }, result={ "signatures": [ { "label": "function test_signature_help_params3(" "\n string $param1,\n string $param2\n): string", "documentation": "@param $param1 info1" "\n for param1" "\n@param $param2 info2" "\n@return the string" "\n 'hack'", "parameters": [ { "label": "$param1", "documentation": "info1 for param1", }, {"label": "$param2", "documentation": "info2"}, ], } ], "activeSignature": 0, "activeParameter": 0, }, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_signature_help_lambda(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("signaturehelp_lambda.php")) spec = ( self.initialize_spec( LspTestSpec("test_serverless_ide_signature_help_lambda"), ) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), comment="signature help for a normal function call", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 8, "character": 29}, }, result={ "activeParameter": 0, "activeSignature": 0, "signatures": [ { "label": "function test_lambda_sighelp(\n" " string $str,\n" " (function(string): int) $f\n" "): int", "parameters": [{"label": "$str"}, {"label": "$f"}], } ], }, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for normal function call within a lambda", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 9, "character": 21}, }, result={ "activeParameter": 0, "activeSignature": 0, "signatures": [ { "label": "function normal_test_func(string $str): void", "parameters": [{"label": "$str"}], } ], }, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for text within a lambda, left side of an open paren", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 10, "character": 15}, }, result=None, powered_by="serverless_ide", ) .request( line=line(), comment="signature help for text within a lambda, right side of an open paren", method="textDocument/signatureHelp", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 10, "character": 16}, }, result=None, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_rename_ok(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("rename.php")) variables.update( { "rename2_file_uri": self.repo_file_uri("rename2.php"), "rename2_file": self.read_repo_file("rename2.php"), } ) self.test_driver.start_hh_server() self.test_driver.run_check() self.load_and_run("rename_ok", variables) def test_rename_with_server(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("rename.php")) self.test_driver.start_hh_server() self.test_driver.run_check() self.load_and_run("rename_with_server", variables) def test_rename_in_interface(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("rename_in_interface.php")) self.test_driver.start_hh_server() self.test_driver.run_check() spec = ( self.initialize_spec(LspTestSpec("rename_in_interface")) .ignore_notifications(method="textDocument/publishDiagnostics") .wait_for_hh_server_ready() .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), method="textDocument/rename", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 19}, "newName": "previouslyCalledSomeMethod", }, result={ "changes": { "${php_file_uri}": [ { "range": { "start": {"line": 3, "character": 18}, "end": {"line": 3, "character": 28}, }, "newText": "previouslyCalledSomeMethod", }, ] } }, ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_references_ok(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("references.php")) self.test_driver.start_hh_server() self.test_driver.run_check() self.load_and_run("references_ok", variables) def test_references_server_cancel(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("references.php")) self.test_driver.start_hh_server() self.test_driver.run_check() self.load_and_run("references_server_cancel", variables) def test_references_client_cancel(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("references.php")) self.test_driver.start_hh_server() self.load_and_run("references_client_cancel", variables) def test_references_with_server(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("references.php")) self.test_driver.start_hh_server() self.test_driver.run_check() self.load_and_run("references_with_server", variables) def test_references_no_server(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("references.php")) self.load_and_run("references_no_server", variables) def test_non_existing_method(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("nomethod.php")) self.load_and_run("nomethod", variables) def test_bad_call(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("bad_call.php")) self.load_and_run("bad_call", variables) def test_code_action_missing_method(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("code_action_missing_method.php")) spec = ( self.initialize_spec(LspTestSpec("code_action_missing_method")) .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( comment="make local, unsaved change to the file", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}", "version": 2}, "contentChanges": [ { "text": """\ <?hh class ClassWithFooBar { public function foobar(): void {} } function call_method(ClassWithFooBar $mc): void { $mc->foobaz(); } """ } ], }, ) .request( line=line(), comment="get actions", method="textDocument/codeAction", params={ "textDocument": {"uri": "${php_file_uri}"}, "range": { "start": {"line": 7, "character": 7}, "end": {"line": 7, "character": 13}, }, "context": { "diagnostics": [ { "range": { "start": {"line": 7, "character": 7}, "end": {"line": 7, "character": 13}, }, "severity": 1, "code": 4053, "source": "Hack", "message": "No instance method foobaz in ClassWithFooBar", "relatedInformation": [ { "location": { "uri": "${php_file_uri}", "range": { "start": {"line": 3, "character": 18}, "end": {"line": 3, "character": 24}, }, }, "message": "Did you mean foobar instead?", }, { "location": { "uri": "${php_file_uri}", "range": { "start": {"line": 6, "character": 21}, "end": {"line": 6, "character": 36}, }, }, "message": "This is why I think it is an object of type ClassWithFooBar", }, { "location": { "uri": "${php_file_uri}", "range": { "start": {"line": 2, "character": 6}, "end": {"line": 2, "character": 21}, }, }, "message": "Declaration of ClassWithFooBar is here", }, ], "relatedLocations": [ { "location": { "uri": "${php_file_uri}", "range": { "start": {"line": 3, "character": 18}, "end": {"line": 3, "character": 24}, }, }, "message": "Did you mean foobar instead?", }, { "location": { "uri": "${php_file_uri}", "range": { "start": {"line": 6, "character": 21}, "end": {"line": 6, "character": 36}, }, }, "message": "This is why I think it is an object of type ClassWithFooBar", }, { "location": { "uri": "${php_file_uri}", "range": { "start": {"line": 2, "character": 6}, "end": {"line": 2, "character": 21}, }, }, "message": "Declaration of ClassWithFooBar is here", }, ], } ] }, }, result=[ { "title": "Change to ->foobar", "kind": "quickfix", "diagnostics": [], "data": { "textDocument": {"uri": "${php_file_uri}"}, "range": { "start": {"line": 7, "character": 7}, "end": {"line": 7, "character": 13}, }, "context": { "diagnostics": [ { "range": { "start": {"line": 7, "character": 7}, "end": {"line": 7, "character": 13}, }, "severity": 1, "code": 4053, "source": "Hack", "message": "No instance method foobaz in ClassWithFooBar", "relatedInformation": [ { "location": { "uri": "${php_file_uri}", "range": { "start": { "line": 3, "character": 18, }, "end": { "line": 3, "character": 24, }, }, }, "message": "Did you mean foobar instead?", }, { "location": { "uri": "${php_file_uri}", "range": { "start": { "line": 6, "character": 21, }, "end": { "line": 6, "character": 36, }, }, }, "message": "This is why I think it is an object of type ClassWithFooBar", }, { "location": { "uri": "${php_file_uri}", "range": { "start": { "line": 2, "character": 6, }, "end": { "line": 2, "character": 21, }, }, }, "message": "Declaration of ClassWithFooBar is here", }, ], "relatedLocations": [ { "location": { "uri": "${php_file_uri}", "range": { "start": { "line": 3, "character": 18, }, "end": { "line": 3, "character": 24, }, }, }, "message": "Did you mean foobar instead?", }, { "location": { "uri": "${php_file_uri}", "range": { "start": { "line": 6, "character": 21, }, "end": { "line": 6, "character": 36, }, }, }, "message": "This is why I think it is an object of type ClassWithFooBar", }, { "location": { "uri": "${php_file_uri}", "range": { "start": { "line": 2, "character": 6, }, "end": { "line": 2, "character": 21, }, }, }, "message": "Declaration of ClassWithFooBar is here", }, ], } ] }, }, }, { "title": "Extract into variable", "kind": "refactor", "diagnostics": [], "data": { "textDocument": {"uri": "${php_file_uri}"}, "range": { "start": {"line": 7, "character": 7}, "end": {"line": 7, "character": 13}, }, "context": { "diagnostics": [ { "range": { "start": {"line": 7, "character": 7}, "end": {"line": 7, "character": 13}, }, "severity": 1, "code": 4053, "source": "Hack", "message": "No instance method foobaz in ClassWithFooBar", "relatedInformation": [ { "location": { "uri": "${php_file_uri}", "range": { "start": { "line": 3, "character": 18, }, "end": { "line": 3, "character": 24, }, }, }, "message": "Did you mean foobar instead?", }, { "location": { "uri": "${php_file_uri}", "range": { "start": { "line": 6, "character": 21, }, "end": { "line": 6, "character": 36, }, }, }, "message": "This is why I think it is an object of type ClassWithFooBar", }, { "location": { "uri": "${php_file_uri}", "range": { "start": { "line": 2, "character": 6, }, "end": { "line": 2, "character": 21, }, }, }, "message": "Declaration of ClassWithFooBar is here", }, ], "relatedLocations": [ { "location": { "uri": "${php_file_uri}", "range": { "start": { "line": 3, "character": 18, }, "end": { "line": 3, "character": 24, }, }, }, "message": "Did you mean foobar instead?", }, { "location": { "uri": "${php_file_uri}", "range": { "start": { "line": 6, "character": 21, }, "end": { "line": 6, "character": 36, }, }, }, "message": "This is why I think it is an object of type ClassWithFooBar", }, { "location": { "uri": "${php_file_uri}", "range": { "start": { "line": 2, "character": 6, }, "end": { "line": 2, "character": 21, }, }, }, "message": "Declaration of ClassWithFooBar is here", }, ], } ] }, }, }, ], powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_code_action_flip_around_comma(self) -> None: """This test is mainly for testing lazy code action resolution: - The server returns a code action with neither 'edit' nor 'command' field - The client must send `codeAction/resolve` - The server then replies with a complete code action """ variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("code_action_flip_around_comma.php")) spec = ( self.initialize_spec(LspTestSpec("code_action_flip_around_comma")) .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .ignore_notifications(method="textDocument/publishDiagnostics") .request( line=line(), comment="get actions", method="textDocument/codeAction", params={ "textDocument": {"uri": "${php_file_uri}"}, "range": { "start": {"line": 3, "character": 10}, "end": {"line": 3, "character": 10}, }, "context": {"diagnostics": []}, }, result=[ { "title": "Flip around comma", "kind": "refactor", "diagnostics": [], "data": { "textDocument": {"uri": "${php_file_uri}"}, "range": { "start": {"line": 3, "character": 10}, "end": {"line": 3, "character": 10}, }, "context": {"diagnostics": []}, }, } ], powered_by="serverless_ide", ) .request( line=line(), comment="resolve code action", method="codeAction/resolve", params={ "title": "Flip around comma", "data": { "textDocument": {"uri": "${php_file_uri}"}, "range": { "start": {"line": 3, "character": 10}, "end": {"line": 3, "character": 10}, }, "context": {"diagnostics": []}, }, "kind": "refactor", "diagnostics": [], }, result={ "title": "Flip around comma", "kind": "refactor", "diagnostics": [], "edit": { "changes": { "${root_path}/code_action_flip_around_comma.php": [ { "range": { "start": {"line": 3, "character": 6}, "end": {"line": 3, "character": 19}, }, "newText": '"b", "a", "c"', } ] } }, }, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_code_action_content_modified(self) -> None: """Test that we handle the following situation gracefully: - client sends textDocument/codeAction - server sends back a partially-resolved code action - client sends codeAction/resolve with a *different* position s.t. the server can't find a code action with the given position and title. We should reply with an LSP error `ContentModified`, per https://github.com/microsoft/language-server-protocol/issues/1738 """ variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("code_action_flip_around_comma.php")) spec = ( self.initialize_spec(LspTestSpec("code_action_flip_around_comma")) .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .ignore_notifications(method="textDocument/publishDiagnostics") .request( line=line(), comment="get actions", method="textDocument/codeAction", params={ "textDocument": {"uri": "${php_file_uri}"}, "range": { "start": {"line": 3, "character": 10}, "end": {"line": 3, "character": 10}, }, "context": {"diagnostics": []}, }, result=[ { "title": "Flip around comma", "kind": "refactor", "diagnostics": [], "data": { "textDocument": {"uri": "${php_file_uri}"}, "range": { "start": {"line": 3, "character": 10}, "end": {"line": 3, "character": 10}, }, "context": {"diagnostics": []}, }, } ], powered_by="serverless_ide", ) .request( line=line(), comment="resolve code action", method="codeAction/resolve", params={ "title": "Flip around comma", "data": { "textDocument": {"uri": "${php_file_uri}"}, "range": { "start": {"line": 3, "character": 2}, "end": {"line": 3, "character": 3}, }, "context": {"diagnostics": []}, }, "kind": "refactor", "diagnostics": [], }, result={ "code": -32801, "message": "Expected the code action requested with codeAction/resolve to be findable.\nNote: This error message may be caused by the source text changing between\nwhen the code action menu pops up and when the user selects the code action.\nIn such cases we may not be able to find a code action at the same location with\nthe same title, so cannot resolve the code action.\n ", }, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_hierarchy_file_change_on_disk(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("incremental_derived.php")) changed_php_file_uri = self.repo_file("incremental_base.php") variables.update({"changed_php_file_uri": changed_php_file_uri}) spec = ( self.initialize_spec( LspTestSpec("serverless_ide_hierarchy_file_change_on_disk"), ) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), comment="hover before change to class hierarchy should be `int`", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 7, "character": 14}, }, result={ "contents": [ { "language": "hack", "value": "// Defined in BaseClassIncremental\npublic function foo(): int", }, ], "range": { "start": {"line": 7, "character": 12}, "end": {"line": 7, "character": 15}, }, }, powered_by="serverless_ide", ) .write_to_disk( uri=changed_php_file_uri, contents="""\ <?hh // strict class BaseClassIncremental { public function foo(): string { return ''; } } """, notify=True, ) .request( line=line(), comment="hover after change to class hierarchy should be `string`", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 7, "character": 14}, }, result={ "contents": [ { "language": "hack", "value": "// Defined in BaseClassIncremental\npublic function foo(): string", }, ], "range": { "start": {"line": 7, "character": 12}, "end": {"line": 7, "character": 15}, }, }, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_decl_in_unsaved_buffer_changed(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("hover.php")) spec = ( self.initialize_spec( LspTestSpec("serverless_ide_decl_in_unsaved_buffer_changed"), ) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), comment="hover over function invocation", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 16}, }, result={ "contents": [ {"language": "hack", "value": "int"}, "A comment describing b_hover.", ], "range": { "start": {"line": 3, "character": 9}, "end": {"line": 3, "character": 16}, }, }, powered_by="serverless_ide", ) .notification( comment="make local, unsaved change to the file", method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}", "version": 2}, "contentChanges": [ { "text": """\ <?hh // strict // comment function a_hover(): int { return b_hover(); } // A comment describing b_hover differently. function b_hover(): string { return 42; } """ } ], }, ) .request( line=line(), comment="another hover over function invocation, should be string now", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 16}, }, result={ "contents": [ {"language": "hack", "value": "string"}, "A comment describing b_hover differently.", ], "range": { "start": {"line": 3, "character": 9}, "end": {"line": 3, "character": 16}, }, }, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_decl_two_unsaved_buffers(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("unsaved1.php")) variables.update({"unsaved2_file_uri": self.repo_file_uri("unsaved2.php")}) spec = ( self.initialize_spec( LspTestSpec("test_serverless_ide_decl_two_unsaved_buffers"), ) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( comment="open 'unsaved1.php', since we'll be hovering in it", method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .notification( comment="open 'unsaved2.php' with a bool-returning signature, different from disk", method="textDocument/didOpen", params={ "textDocument": { "uri": "${unsaved2_file_uri}", "languageId": "hack", "version": 1, "text": """\ <?hh //strict function unsaved_bar(): bool { return true; } """, } }, ) .request( line=line(), comment="hover 'unsaved1.php' is with respect to disk contents of 'unsaved2.php'", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 1, "character": 39}, }, result={ "contents": [ {"language": "hack", "value": "function unsaved_bar(): int"}, ], "range": { "start": {"line": 1, "character": 34}, "end": {"line": 1, "character": 45}, }, }, powered_by="serverless_ide", ) .notification( comment="change signature in 'unsaved2.php' to return string", method="textDocument/didChange", params={ "textDocument": {"uri": "${unsaved2_file_uri}", "version": 2}, "contentChanges": [ { "text": """\ <?hh //strict function unsaved_bar(): string { return "hello"; } """ } ], }, ) .request( line=line(), comment="this is a dummy hover in 'unsaved2.php' just to ensure its decl is cached", method="textDocument/hover", params={ "textDocument": {"uri": "${unsaved2_file_uri}"}, "position": {"line": 0, "character": 0}, }, result=None, powered_by="serverless_ide", ) .request( line=line(), comment="hover 'unsaved1.php' is still with respect to disk contents of 'unsaved2.php'", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 1, "character": 39}, }, result={ "contents": [ {"language": "hack", "value": "function unsaved_bar(): int"}, ], "range": { "start": {"line": 1, "character": 34}, "end": {"line": 1, "character": 45}, }, }, powered_by="serverless_ide", ) .write_to_disk( comment="save signature in 'unsaved2' to return string", uri=variables["unsaved2_file_uri"], contents="""\ <?hh // strict function unsaved_bar(): string { return "hello"; } """, notify=True, ) .request( line=line(), comment="hover 'unsaved1.php' gets new disk contents of 'unsaved2.php'", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 1, "character": 39}, }, result={ "contents": [ {"language": "hack", "value": "function unsaved_bar(): string"}, ], "range": { "start": {"line": 1, "character": 34}, "end": {"line": 1, "character": 45}, }, }, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_hover_without_file_open(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("hover.php")) spec = ( self.initialize_spec( LspTestSpec("test_hover_without_file_open"), ) .ignore_notifications(method="textDocument/publishDiagnostics") .request( line=line(), comment="hover before file_open will fail", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 26, "character": 20}, }, result=None, ) .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), comment="hover after file_open will succeed", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 26, "character": 20}, }, result={ "contents": [ {"language": "hack", "value": "string"}, {"language": "hack", "value": "Parameter: $s"}, ] }, powered_by="serverless_ide", ) .notification( method="textDocument/didClose", params={"textDocument": {"uri": "${php_file_uri}"}}, ) .request( line=line(), comment="hover after file_close will fail", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 26, "character": 20}, }, result=None, ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_highlight(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("highlight.php")) spec = ( self.initialize_spec(LspTestSpec("serverless_ide_highlight")) .ignore_notifications(method="textDocument/publishDiagnostics") .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .request( line=line(), comment="document highlight, id 2", method="textDocument/documentHighlight", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 10}, }, result=[ { "range": { "start": {"line": 3, "character": 9}, "end": {"line": 3, "character": 20}, } } ], powered_by="serverless_ide", ) .request( line=line(), comment="shutdown, id 3", method="shutdown", params={}, result=None, ) ) self.run_spec(spec, variables) def test_status_running(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("hover.php")) spec = ( self.initialize_spec( LspTestSpec("status_running"), has_status_capability=True, ) .ignore_requests( comment="Ignore all status requests not explicitly waited for in the test", method="window/showStatus", params=None, ) .start_hh_server("starting") .wait_for_server_request( method="window/showStatus", params={ "message": "<ROOT>\n\nHack IDE support is ready\n\nhh_server is ready", "shortMessage": "Hack", "type": 3, }, result=NoResponse(), ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_status_stopped(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("hover.php")) spec = ( self.initialize_spec( LspTestSpec("serverless_ide_status_stopped"), has_status_capability=True, ) .ignore_requests( comment="Ignore all status requests not explicitly waited for in the test", method="window/showStatus", params=None, ) .wait_for_server_request( method="window/showStatus", params={ "type": 1, "message": "<ROOT>\n\nHack IDE support is ready\n\nhh_server is stopped. Try running `hh` at the command-line.", "shortMessage": "Hack: hh_server stopped", }, result=NoResponse(), ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_standalone_status(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("hover.php")) spec = ( self.initialize_spec( LspTestSpec("test_standalone_status"), has_status_capability=True, ) .ignore_requests( comment="Ignore all status requests not explicitly waited for in the test", method="window/showStatus", params=None, ) .wait_for_server_request( comment="standalone status upon startup when it starts with hh_server stopped", method="window/showStatus", params={ "message": "<ROOT>\n\nHack IDE support is ready\n\nhh_server is stopped. Try running `hh` at the command-line.", "shortMessage": "Hack: hh_server stopped", "type": 1, }, result=NoResponse(), ) .start_hh_server("Restart HH Server") .wait_for_server_request( comment="standalone status when hh_server transitions to starting up", method="window/showStatus", params={ "message": "<ROOT>\n\nHack IDE support is ready\n\nhh_server is ready", "shortMessage": "Hack", "type": 3, }, result=NoResponse(), ) .stop_hh_server("Shutdown HH Server") .wait_for_server_request( comment="standalone status when hh_server transitions to stopped", method="window/showStatus", params={ "message": "<ROOT>\n\nHack IDE support is ready\n\nhh_server is stopped. Try running `hh` at the command-line.", "shortMessage": "Hack: hh_server stopped", "type": 1, }, result=NoResponse(), ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_standalone_errors(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("hover.php")) errors_a_uri = self.repo_file_uri("errors_a.php") errors_b_uri = self.repo_file_uri("errors_b.php") variables.update({"errors_a_uri": errors_a_uri, "errors_b_uri": errors_b_uri}) spec = ( self.initialize_spec( LspTestSpec("test_standalone_errors"), has_status_capability=True, ) .ignore_requests( comment="Ignore all status requests not explicitly waited for in the test", method="window/showStatus", params=None, ) .write_to_disk( comment="create file errors_a.php", uri="${errors_a_uri}", contents="<?hh\nfunction aaa(): int { return 1 }\n", notify=False, ) .write_to_disk( comment="create file errors_b.php", uri="${errors_b_uri}", contents="<?hh\nfunction bbb(): int { return 2 }\n", notify=False, ) .notification( comment="actually open something that's different from what was on disk (with extra newline)", method="textDocument/didOpen", params={ "textDocument": { "uri": "${errors_a_uri}", "languageId": "hack", "version": 1, "text": "<?hh\n\n\n\nfunction aaa(): int { return 1 }\n", } }, ) .wait_for_notification( comment="standalone should report a squiggle in errors_a.php from serverless", method="textDocument/publishDiagnostics", params={ "uri": "${errors_a_uri}", "diagnostics": [ { "range": { "start": {"line": 4, "character": 31}, "end": {"line": 4, "character": 31}, }, "severity": 1, "code": 1002, "source": "Hack", "message": "A semicolon ; is expected here.", "relatedLocations": [], "relatedInformation": [], } ], }, ) .start_hh_server("start HH Server") .wait_for_notification( comment="standalone should report a squiggle in errors_b.php from errors.bin", method="textDocument/publishDiagnostics", params={ "uri": "${errors_b_uri}", "diagnostics": [ { "range": { "start": {"line": 1, "character": 31}, "end": {"line": 1, "character": 31}, }, "severity": 1, "code": 1002, "source": "Hack", "message": "A semicolon ; is expected here.", "relatedLocations": [], "relatedInformation": [], } ], }, ) .start_hh_server("start HH Server") .request(line=line(), method="shutdown", params={}, result=None) .wait_for_notification( comment="standalone should clean up squiggles - a", method="textDocument/publishDiagnostics", params={"uri": "${errors_a_uri}", "diagnostics": []}, ) .wait_for_notification( comment="standalone should clean up squiggles - b", method="textDocument/publishDiagnostics", params={"uri": "${errors_b_uri}", "diagnostics": []}, ) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_live_squiggles(self) -> None: """This tests that "live squiggles" (those from clientIdeDaemon) are correctly produced by didOpen, didChange, codeAction and publishDiagnostics.""" variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("hover.php")) errors_a_uri = self.repo_file_uri("errors_a.php") errors_b_uri = self.repo_file_uri("errors_b.php") variables.update({"errors_a_uri": errors_a_uri, "errors_b_uri": errors_b_uri}) spec = ( self.initialize_spec( LspTestSpec("test_live_squiggles"), ) .write_to_disk( comment="create file errors_a.php", uri="${errors_a_uri}", contents="<?hh\nfunction aaa() { }\n", notify=False, ) .notification( comment="open errors_a.php", method="textDocument/didOpen", params={ "textDocument": { "uri": "${errors_a_uri}", "languageId": "hack", "version": 1, "text": "<?hh\nfunction aaa() { }\n", } }, ) .wait_for_notification( comment="didOpen should report a live squiggle in errors_a.php", method="textDocument/publishDiagnostics", params={ "uri": "${errors_a_uri}", "diagnostics": [ { "range": { "start": {"line": 1, "character": 9}, "end": {"line": 1, "character": 12}, }, "severity": 1, "code": 4030, "source": "Hack", "message": "Was expecting a return type hint", "relatedLocations": [], "relatedInformation": [], } ], }, ) .notification( comment="change errors_a.php", method="textDocument/didChange", params={ "textDocument": {"uri": "${errors_a_uri}"}, "contentChanges": [ { "range": { "start": {"line": 1, "character": 0}, "end": {"line": 1, "character": 0}, }, "text": "\n", } ], }, ) .wait_for_notification( comment="didChange should update live squiggles in errors_a.php (one line down from what we got in didOpen)", method="textDocument/publishDiagnostics", params={ "uri": "${errors_a_uri}", "diagnostics": [ { "range": { "start": {"line": 2, "character": 9}, "end": {"line": 2, "character": 12}, }, "severity": 1, "code": 4030, "source": "Hack", "message": "Was expecting a return type hint", "relatedLocations": [], "relatedInformation": [], } ], }, ) .write_to_disk( comment="create file errors_b.php and send didChangeWatchedFiles", uri="${errors_b_uri}", contents="<?hh\nfunction bbb(): int { return 2; }\n", notify=True, ) .request( line=line(), comment="send codeAction to trigger errors to be refreshed", method="textDocument/codeAction", params={ "textDocument": {"uri": "${errors_a_uri}"}, "range": { "start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 0}, }, "context": {"diagnostics": []}, }, result=[], powered_by="serverless_ide", ) .wait_for_notification( comment="codeAction should update live squiggles in errors_a.php (same as what we had from didChange)", method="textDocument/publishDiagnostics", params={ "uri": "${errors_a_uri}", "diagnostics": [ { "range": { "start": {"line": 2, "character": 9}, "end": {"line": 2, "character": 12}, }, "severity": 1, "code": 4030, "source": "Hack", "message": "Was expecting a return type hint", "relatedLocations": [], "relatedInformation": [], } ], }, ) .notification( method="textDocument/didClose", params={"textDocument": {"uri": "${errors_a_uri}"}}, ) .wait_for_notification( comment="didClose should update live squiggles in (unsaved) errors_a.php back to what they were on disk", method="textDocument/publishDiagnostics", params={ "uri": "${errors_a_uri}", "diagnostics": [ { "range": { "start": {"line": 1, "character": 9}, "end": {"line": 1, "character": 12}, }, "severity": 1, "code": 4030, "source": "Hack", "message": "Was expecting a return type hint", "relatedLocations": [], "relatedInformation": [], } ], }, ) .request(line=line(), method="shutdown", params={}, result=None) .wait_for_notification( comment="shutdown should clear out live squiggles", method="textDocument/publishDiagnostics", params={ "uri": "${errors_a_uri}", "diagnostics": [], }, ) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_parsing_squiggles_priority(self) -> None: """This tests that parsing squiggles suppress typing squiggles from clientIdeDaemon""" variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("hover.php")) errors_a_uri = self.repo_file_uri("errors_a.php") variables.update({"errors_a_uri": errors_a_uri}) spec = ( self.initialize_spec( LspTestSpec("test_parsing_squiggles_priority"), ) .write_to_disk( comment="create file errors_a.php", uri="${errors_a_uri}", contents="<?hh\nfunction aaa(): int { return $undefined }\n", notify=False, ) .notification( comment="open errors_a.php", method="textDocument/didOpen", params={ "textDocument": { "uri": "${errors_a_uri}", "languageId": "hack", "version": 1, "text": "<?hh\nfunction aaa(): int { return $undefined }\n", } }, ) .wait_for_notification( comment="didOpen should report only a parsing squiggle in errors_a.php", method="textDocument/publishDiagnostics", params={ "uri": "${errors_a_uri}", "diagnostics": [ { "range": { "start": {"line": 1, "character": 40}, "end": {"line": 1, "character": 40}, }, "severity": 1, "code": 1002, "source": "Hack", "message": "A semicolon ; is expected here.", "relatedLocations": [], "relatedInformation": [], } ], }, ) .notification( comment="change errors_a.php", method="textDocument/didChange", params={ "textDocument": {"uri": "${errors_a_uri}"}, "contentChanges": [ { "range": { "start": {"line": 1, "character": 39}, "end": {"line": 1, "character": 39}, }, "text": ";", } ], }, ) .wait_for_notification( comment="didChange should update live squiggles in errors_a.php (now revealing the typing error)", method="textDocument/publishDiagnostics", params={ "uri": "${errors_a_uri}", "diagnostics": [ { "range": { "start": {"line": 1, "character": 29}, "end": {"line": 1, "character": 39}, }, "severity": 1, "code": 2050, "source": "Hack", "message": "Variable $undefined is undefined, or not always defined.", "relatedLocations": [], "relatedInformation": [], } ], }, ) .request(line=line(), method="shutdown", params={}, result=None) .wait_for_notification( comment="shutdown should clear out live squiggles", method="textDocument/publishDiagnostics", params={ "uri": "${errors_a_uri}", "diagnostics": [], }, ) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_falls_back_to_full_index(self) -> None: # Test recovery behavior when we fail to load a naming table, but we're # permitted to fall back to the full index naming table build. variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("hover.php")) assert "naming_table_saved_state_path" in variables variables["naming_table_saved_state_path"] = "/tmp/nonexistent" spec = ( self.initialize_spec( LspTestSpec("serverless_ide_falls_back_to_full_index"), has_status_capability=True, wait_for_init_done=False, ) .ignore_requests( comment="Ignore all status requests not explicitly waited for in the test", method="window/showStatus", params=None, ) .wait_for_server_request( comment="standalone status upon startup when it starts with hh_server stopped", method="window/showStatus", params={ "message": "<ROOT>\n\nHack IDE support is ready\n\nhh_server is stopped. Try running `hh` at the command-line.", "shortMessage": "Hack: hh_server stopped", "type": 1, }, result=NoResponse(), ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec( spec, variables, ) def test_serverless_ide_failed_to_load_saved_state_no_full_index(self) -> None: # This test examines the failure behavior when the naming table is # non-existent and we are *not* falling back to full index. variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("hover.php")) assert "naming_table_saved_state_path" in variables variables["naming_table_saved_state_path"] = "/tmp/nonexistent" spec = ( self.initialize_spec( LspTestSpec("serverless_ide_status_failed_to_load_saved_state"), has_status_capability=True, wait_for_init_done=False, ) .ignore_requests( comment="Ignore all status requests not explicitly waited for in the test", method="window/showStatus", params=None, ) .wait_for_notification( method="window/logMessage", params={ "type": 1, "message": "Hack IDE support has failed.\nThis is unexpected.\nPlease file a bug within your IDE, and try restarting it.\nMore details: http://dummy/HH_TEST_MODE", }, ) .wait_for_server_request( method="window/showStatus", params={ "message": "<ROOT>\n\nHack IDE support has failed. See Output\u203aHack for details.\n\nhh_server is stopped. Try running `hh` at the command-line.", "shortMessage": "Hack: failed", "type": 1, }, result=NoResponse(), ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) # By setting `fall_back_to_full_index` to `False`, the IDE will give up once it fails to load a saved state instead of attempting the naming table build. self.run_spec( spec, variables, fall_back_to_full_index=False, ) def test_workspace_symbol(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("didchange.php")) spec = ( self.initialize_spec(LspTestSpec("test_workspace_symbol")) .ignore_notifications(method="textDocument/publishDiagnostics") .request( line=line(), comment="Look up symbols", method="workspace/symbol", params={"query": "TestNS\\test"}, result=[ { "name": "TestNS\\test_func", "kind": 12, "location": { "uri": "file://${root_path}/completion_extras_namespace.php", "range": { "start": {"line": 4, "character": 9}, "end": {"line": 4, "character": 25}, }, }, } ], powered_by="serverless_ide", ) .request( line=line(), comment="Look up symbols starting with 'test_f' within multiple namespaces", method="workspace/symbol", params={"query": "test_f"}, result=[ { "name": "test_function", "kind": 12, "location": { "uri": "file://${root_path}/completion.php", "range": { "start": {"line": 7, "character": 9}, "end": {"line": 7, "character": 22}, }, }, }, { "name": "TestNS\\test_func", "kind": 12, "location": { "uri": "file://${root_path}/completion_extras_namespace.php", "range": { "start": {"line": 4, "character": 9}, "end": {"line": 4, "character": 25}, }, }, }, ], powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_naming_error1(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("didchange.php")) variables.update( { "main_file": self.repo_file("main.php"), "main_file_contents": """\ <?hh function main(): int { return aaa(); } """, "file_a": self.repo_file("a.php"), "file_b": self.repo_file("b.php"), } ) spec = ( self.initialize_spec(LspTestSpec("serverless_ide_naming_error1")) .write_to_disk( uri="${main_file}", contents="${main_file_contents}", notify=True ) .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${main_file}", "languageId": "hack", "version": 1, "text": "${main_file_contents}", } }, ) .wait_for_notification( method="textDocument/publishDiagnostics", params={ "uri": "file://${main_file}", "diagnostics": [ { "range": { "start": {"line": 2, "character": 11}, "end": {"line": 2, "character": 14}, }, "severity": 1, "code": 2049, "source": "Hack", "message": "Unbound name: aaa (a global function)", "relatedInformation": [], "relatedLocations": [], }, { "range": { "start": {"line": 2, "character": 11}, "end": {"line": 2, "character": 14}, }, "severity": 1, "code": 4107, "source": "Hack", "message": "Unbound name (typing): aaa", "relatedInformation": [], "relatedLocations": [], }, ], }, ) .request( line=line(), comment="Ensure that hover over `aaa` works even when the name is not yet defined", method="textDocument/hover", params={ "textDocument": {"uri": "${main_file}"}, "position": {"line": 2, "character": 13}, }, result={ "contents": [{"language": "hack", "value": "nothing"}], "range": { "start": {"line": 2, "character": 11}, "end": {"line": 2, "character": 14}, }, }, powered_by="serverless_ide", ) .write_to_disk( comment="create file A", uri="${file_a}", contents="""\ <?hh function aaa(): int { return 1; } """, notify=True, ) .request( line=line(), comment="Ensure that hover over `aaa` works when there are no naming errors", method="textDocument/hover", params={ "textDocument": {"uri": "${main_file}"}, "position": {"line": 2, "character": 13}, }, result={ "contents": [ {"language": "hack", "value": "function aaa(): int"}, ], "range": { "start": {"line": 2, "character": 11}, "end": {"line": 2, "character": 14}, }, }, powered_by="serverless_ide", ) .write_to_disk( comment="create file B", uri="${file_b}", contents="""\ <?hh function aaa(): string { return "foo"; } """, notify=True, ) .request( line=line(), comment="Ensure that hover over `aaa` works even when there is a duplicate name", method="textDocument/hover", params={ "textDocument": {"uri": "${main_file}"}, "position": {"line": 2, "character": 13}, }, result={ "contents": [ {"language": "hack", "value": "function aaa(): int"}, ], "range": { "start": {"line": 2, "character": 11}, "end": {"line": 2, "character": 14}, }, }, powered_by="serverless_ide", ) .write_to_disk( comment="delete file A", uri="${file_a}", contents=None, notify=True ) .request( line=line(), comment="Now that we've fixed the error, hover should work.", method="textDocument/hover", params={ "textDocument": {"uri": "${main_file}"}, "position": {"line": 2, "character": 13}, }, result={ "contents": [ {"language": "hack", "value": "function aaa(): string"}, ], "range": { "start": {"line": 2, "character": 11}, "end": {"line": 2, "character": 14}, }, }, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .wait_for_notification( method="textDocument/publishDiagnostics", params={"uri": "file://${main_file}", "diagnostics": []}, ) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_naming_error2(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("naming_error_caller.php")) variables.update( { "contents": self.read_repo_file("naming_error_declaration.php"), "original": self.repo_file("naming_error_declaration.php"), "copy": self.repo_file("naming_error_copy.php"), } ) spec = ( self.initialize_spec(LspTestSpec("serverless_ide_naming_error2")) .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .wait_for_notification( method="textDocument/publishDiagnostics", params={"uri": "${php_file_uri}", "diagnostics": []}, ) .write_to_disk( comment="create copy", uri="${copy}", contents="${contents}", notify=True, ) .write_to_disk( comment="delete copy", uri="${copy}", contents=None, notify=True ) .request( line=line(), comment="hover should work fine after making copy then deleting copy.", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 15}, }, result={ "contents": [ { "language": "hack", "value": "function naming_error_declaration(): void", }, ], "range": { "start": {"line": 3, "character": 2}, "end": {"line": 3, "character": 26}, }, }, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_naming_error3(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update(self.setup_php_file("naming_error_caller.php")) variables.update( { "contents": self.read_repo_file("naming_error_declaration.php"), "original": self.repo_file("naming_error_declaration.php"), "copy": self.repo_file("naming_error_copy.php"), } ) spec = ( self.initialize_spec(LspTestSpec("serverless_ide_naming_error3")) .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "${php_file}", } }, ) .wait_for_notification( method="textDocument/publishDiagnostics", params={"uri": "${php_file_uri}", "diagnostics": []}, ) .write_to_disk( comment="create copy", uri="${copy}", contents="${contents}", notify=True, ) .write_to_disk( comment="delete original", uri="${original}", contents=None, notify=True ) .request( line=line(), comment="hover should work fine after making copy then deleting original.", method="textDocument/hover", params={ "textDocument": {"uri": "${php_file_uri}"}, "position": {"line": 3, "character": 15}, }, result={ "contents": [ { "language": "hack", "value": "function naming_error_declaration(): void", }, ], "range": { "start": {"line": 3, "character": 2}, "end": {"line": 3, "character": 26}, }, }, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_requests_before_init(self) -> None: variables = self.write_hhconf_and_naming_table() spec = ( self.initialize_spec( LspTestSpec("test_serverless_ide_requests_before_init"), has_status_capability=True, wait_for_init_done=False, ) .ignore_notifications(method="textDocument/publishDiagnostics") .ignore_requests( method="window/showStatus", params={ "type": 2, "message": "<ROOT>\n\nHack IDE support is initializing (loading saved state)\n\nhh_server is stopped. Try running `hh` at the command-line.", "shortMessage": "Hack: initializing", }, ) .ignore_requests( method="window/showStatus", params={ "type": 2, "message": "<ROOT>\n\nHack is working on IDE requests\n\nhh_server is stopped. Try running `hh` at the command-line.", "shortMessage": "Hack: hh_server stopped", }, ) .write_to_disk( notify=True, uri="file://${root_path}/beforeInit1.php", contents="<?hh // strict\nfunction beforeInit1(): int {\n return 42;\n}\n", ) .notification( comment="open a file before init has finished", method="textDocument/didOpen", params={ "textDocument": { "uri": "file://${root_path}/beforeInit2.php", "languageId": "hack", "version": 1, "text": "<?hh // strict\nfunction beforeInit2(): void {\n $foo = beforeInit1();\n}\n", } }, ) .request( line=line(), comment="hover before init will fail", method="textDocument/hover", params={ "textDocument": {"uri": "file://${root_path}/beforeInit2.php"}, "position": {"line": 2, "character": 4}, }, result=None, ) .request( line=line(), comment="documentSymbol before init will succeed", method="textDocument/documentSymbol", params={"textDocument": {"uri": "file://${root_path}/beforeInit2.php"}}, result=[ { "name": "beforeInit2", "kind": 12, "location": { "uri": "file://${root_path}/beforeInit2.php", "range": { "start": {"line": 1, "character": 0}, "end": {"line": 3, "character": 1}, }, }, } ], powered_by="serverless_ide", ) .wait_for_notification( comment="wait for clientIdeDaemon to init", method="telemetry/event", params={"type": 4, "message": "[client-ide] Finished init: ok"}, ) .wait_for_server_request( method="window/showStatus", params={ "type": 1, "message": "<ROOT>\n\nHack IDE support is ready\n\nhh_server is stopped. Try running `hh` at the command-line.", "shortMessage": "Hack: hh_server stopped", }, result=NoResponse(), ) .request( line=line(), comment="hover after init will succeed", method="textDocument/hover", params={ "textDocument": {"uri": "file://${root_path}/beforeInit2.php"}, "position": {"line": 2, "character": 4}, }, result={ "contents": [{"language": "hack", "value": "int"}], "range": { "start": {"line": 2, "character": 2}, "end": {"line": 2, "character": 6}, }, }, powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_serverless_ide_workspace_symbol(self) -> None: variables = self.write_hhconf_and_naming_table() spec = ( self.initialize_spec(LspTestSpec("serverless_ide_workspace_symbol")) .request( line=line(), comment="workspace symbol call, global, powered by sqlite (generated during serverless-ide-init)", method="workspace/symbol", params={"query": "TakesString"}, result=[ { "name": "TakesString", "kind": 5, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 36, "character": 6}, "end": {"line": 36, "character": 17}, }, }, } ], powered_by="serverless_ide", ) .request( line=line(), comment="workspace symbol call, member (derived from naming-table)", method="workspace/symbol", params={"query": "TakesString::"}, result=[ { "name": "__construct", "kind": 6, "location": { "uri": "file://${root_path}/definition.php", "range": { "start": {"line": 37, "character": 18}, "end": {"line": 37, "character": 29}, }, }, } ], powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_errors_before_init(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update({"php_file_uri": self.repo_file_uri("php_file.php")}) spec = ( self.initialize_spec( LspTestSpec("errors_before_init"), wait_for_init_done=False, ) .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "<?hh\nfunction f(): int { return 1 }\n", } }, ) .wait_for_notification( method="telemetry/event", params={"type": 4, "message": "[client-ide] Finished init: ok"}, ) .wait_for_notification( method="textDocument/publishDiagnostics", params={ "uri": "${php_file_uri}", "diagnostics": [ { "range": { "start": {"line": 1, "character": 29}, "end": {"line": 1, "character": 29}, }, "severity": 1, "code": 1002, "source": "Hack", "message": "A semicolon ; is expected here.", "relatedInformation": [], "relatedLocations": [], } ], }, ) .request( comment="the codeAction request will push diagnostics if they've not already been pushed", line=line(), method="textDocument/codeAction", params={ "textDocument": {"uri": "${php_file_uri}"}, "range": { "start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 0}, }, "context": {"diagnostics": []}, }, result=[], powered_by="serverless_ide", ) .request(line=line(), method="shutdown", params={}, result=None) .wait_for_notification( method="textDocument/publishDiagnostics", params={"uri": "${php_file_uri}", "diagnostics": []}, ) .notification(method="exit", params={}) ) self.run_spec(spec, variables) def test_skip_errors(self) -> None: variables = self.write_hhconf_and_naming_table() variables.update({"php_file_uri": self.repo_file_uri("php_file.php")}) spec = ( self.initialize_spec( LspTestSpec("skip_errors"), wait_for_init_done=False, ) .notification( method="textDocument/didOpen", params={ "textDocument": { "uri": "${php_file_uri}", "languageId": "hack", "version": 1, "text": "<?hh\nfunction f(): int { return 1 }\n", } }, ) .notification( method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 1, "character": 0}, "end": {"line": 1, "character": 30}, }, "text": "function f(): int { return 12 }", } ], }, ) .notification( method="textDocument/didChange", params={ "textDocument": {"uri": "${php_file_uri}"}, "contentChanges": [ { "range": { "start": {"line": 1, "character": 0}, "end": {"line": 1, "character": 31}, }, "text": "function f(): int { return 123 }", } ], }, ) .wait_for_notification( method="telemetry/event", params={"type": 4, "message": "[client-ide] Finished init: ok"}, ) .wait_for_notification( method="textDocument/publishDiagnostics", params={ "uri": "${php_file_uri}", "diagnostics": [ { "range": { "start": {"line": 1, "character": 31}, "end": {"line": 1, "character": 31}, }, "severity": 1, "code": 1002, "source": "Hack", "message": "A semicolon ; is expected here.", "relatedInformation": [], "relatedLocations": [], } ], }, ) .request(line=line(), method="shutdown", params={}, result=None) .wait_for_notification( method="textDocument/publishDiagnostics", params={"uri": "${php_file_uri}", "diagnostics": []}, ) .notification(method="exit", params={}) ) self.run_spec(spec, variables)
Python
hhvm/hphp/hack/test/integration/test_pess_type_at_pos.py
import common_tests from test_case import TestCase class ImplicitPessTests(TestCase[common_tests.CommonTestDriver]): @classmethod def get_template_repo(cls) -> str: return "hphp/hack/test/integration/data/implicit_pess_repo" @classmethod def get_test_driver(cls) -> common_tests.CommonTestDriver: return common_tests.CommonTestDriver() def test_type_at_pos_enum(self) -> None: """ Test hh_client --type-at-pos """ self.test_driver.start_hh_server() self.test_driver.check_cmd_and_json_cmd( ["(string & ~MyEnum)"], [ '{{"type":"(string & ~MyEnum)",' + '"pos":{{"filename":"","line":0,"char_start":0,"char_end":0}},' + '"full_type":{{"src_pos":{{"filename":"{root}foo_enum.php","line":8,"char_start":24,"char_end":29}},"kind":"enum","name":"\\\\MyEnum",' + '"as":{{"src_pos":{{"filename":"{root}foo_enum.php","line":3,"char_start":24,"char_end":29}},"kind":"primitive","name":"string"}}}}}}' ], options=["--type-at-pos", "{root}foo_enum.php:15:3"], )
Python
hhvm/hphp/hack/test/integration/test_refactor_sound_dynamic.py
import os import common_tests class TestRenameSoundDynamic(common_tests.CommonTests): @classmethod def get_test_driver(cls) -> common_tests.CommonTestDriver: return common_tests.CommonTestDriver() def write_load_config(self): with open(os.path.join(self.test_driver.repo_dir, ".hhconfig"), "w") as f: f.write( """ enable_sound_dynamic_type = true """ ) def write_and_test_one_file( self, file_input, command_type, element_name, upcast_locations, using_sd=True ) -> None: with open(os.path.join(self.test_driver.repo_dir, "a.php"), "w") as f: f.write(file_input) if using_sd: self.write_load_config() self.test_driver.start_hh_server(changed_files=["a.php"], args=["--no-load"]) self.check_upcast_cmd(command_type, element_name, upcast_locations, using_sd) def check_upcast_cmd( self, command_type, element_name, upcast_locations, using_sd=True ): if using_sd: expected_output = [ "Server is using sound dynamic. ", f"Number of upcast positions for \\{element_name} is {len(upcast_locations)}", ] expected_output.extend(upcast_locations) else: expected_output = [ "Server is NOT using sound dynamic. Change the .hhconfig file to enable sound dynamic. ", ] self.test_driver.check_cmd( expected_output=expected_output, options=["--refactor-sound-dynamic", command_type, element_name], ) def test_no_sd(self) -> None: self.write_and_test_one_file( """<?hh <<file:__EnableUnstableFeatures('upcast_expression')>> <<__SupportDynamicType>> function h(shape(...) $m): int { $x = h<> upcast dynamic; } """, "Function", "h", [], using_sd=False, ) def test_one_upcast_one_function(self) -> None: self.write_and_test_one_file( """<?hh <<file:__EnableUnstableFeatures('upcast_expression')>> <<__SupportDynamicType>> function h(shape(...) $m): int { $x = h<> upcast dynamic; } """, "Function", "h", [ f'File "{self.test_driver.repo_dir}/a.php", line 5, characters 20-37:', ], ) def test_one_upcast_one_class(self) -> None: self.write_and_test_one_file( """ <?hh <<file:__EnableUnstableFeatures('upcast_expression')>> <<__SupportDynamicType>> class Counter { private int $i = 0; } function c(dynamic $d): void { $g = Counter::class upcast dynamic; $h = new Counter() upcast dynamic; } """, "Class", "Counter", [ f'File "{self.test_driver.repo_dir}/a.php", line 10, characters 8-36:', f'File "{self.test_driver.repo_dir}/a.php", line 11, characters 8-35:', ], ) def test_one_upcast_multiple_function(self) -> None: self.write_and_test_one_file( """<?hh <<file:__EnableUnstableFeatures('upcast_expression')>> <<__SupportDynamicType>> function h(shape(...) $m): int { $x = h<> upcast dynamic; } <<__SupportDynamicType>> function g(int $m): int { $x = g<> upcast dynamic; } """, "Function", "h", [ f'File "{self.test_driver.repo_dir}/a.php", line 5, characters 20-37:', ], ) def test_multiple_files(self) -> None: with open(os.path.join(self.test_driver.repo_dir, "a.php"), "w") as f: f.write( """<?hh <<file:__EnableUnstableFeatures('upcast_expression')>> <<__SupportDynamicType>> function h(shape(...) $m): int { $x = h<> upcast dynamic; } <<__SupportDynamicType>> function g(int $m): int { $x = g<> upcast dynamic; } """ ) with open(os.path.join(self.test_driver.repo_dir, "b.php"), "w") as f: f.write( """<?hh <<file:__EnableUnstableFeatures('upcast_expression')>> <<__SupportDynamicType>> function b(dynamic $d): void { $y = h<> upcast dynamic; $d(3); } """ ) with open(os.path.join(self.test_driver.repo_dir, "c.php"), "w") as f: f.write( """<?hh <<file:__EnableUnstableFeatures('upcast_expression')>> <<__SupportDynamicType>> function c(int $i): void { $z = h<> upcast dynamic; } """ ) self.write_load_config() self.test_driver.start_hh_server( changed_files=["a.php", "b.php", "c.php"], args=["--no-load"] ) self.check_upcast_cmd( "Function", "h", [ f'File "{self.test_driver.repo_dir}/a.php", line 5, characters 20-37:', f'File "{self.test_driver.repo_dir}/b.php", line 5, characters 24-41:', f'File "{self.test_driver.repo_dir}/c.php", line 5, characters 24-41:', ], )
Python
hhvm/hphp/hack/test/integration/test_safe_rename_sound_dynamic.py
import os import common_tests class TestSafeRenameSoundDynamic(common_tests.CommonTestDriver): @classmethod def setUpClass(cls): super().setUpClass( template_repo="hphp/hack/test/integration/data/lsp_exchanges/" ) def filename(self): return os.path.join(self.repo_dir, "a.php") def write_hh_config(self): with open(os.path.join(self.repo_dir, ".hhconfig"), "w") as f: f.write( """ like_type_hints = true enable_sound_dynamic_type = true union_intersection_type_hints = true everything_sdt = true """ ) def run_hh(self, file_input) -> None: with open(self.filename(), "w") as f: f.write(file_input) self.write_hh_config() self.start_hh_server(changed_files=["a.php"], args=["--no-load"]) def expect_contents(self, expected): with open(self.filename(), "r") as f: actual = f.read() self.assertEqual(expected, actual) def rename(self, kind, old_name, new_name): self.check_cmd( expected_output=None, options=["--refactor", kind, old_name, new_name], ) def test_no_auto_dynamic(self) -> None: self.run_hh( """<?hh <<__NoAutoDynamic>> class Nad { public static function smeth(): void {} public function meth1(): void {} <<__NoAutoDynamic, __SupportDynamicType>> public function meth2(): void {} <<__SupportDynamicType>> public function meth3(): void {} } """ ) self.rename("Method", "Nad::meth3", "Nad::meth3b") self.rename("Method", "Nad::meth2", "Nad::meth2b") self.rename("Method", "Nad::meth1", "Nad::meth1b") self.rename("Method", "Nad::smeth", "Nad::smethb") self.expect_contents( """<?hh <<__NoAutoDynamic>> class Nad { public static function smethb(): void {} public function meth1b(): void {} <<__Deprecated("Use `meth2b` instead")>> public function meth2(): void { $this->meth2b(); } <<__NoAutoDynamic, __SupportDynamicType>> public function meth2b(): void {} <<__Deprecated("Use `meth3b` instead")>> public function meth3(): void { $this->meth3b(); } <<__SupportDynamicType>> public function meth3b(): void {} } """ ) def test_implicit_pess(self) -> None: self.run_hh( """<?hh class Sd { public static function smeth(): void {} public function meth1(): void {} <<__NoAutoDynamic, __SupportDynamicType>> public function meth2(): void {} <<__SupportDynamicType>> public function meth3(): void {} <<__NoAutoDynamic>> public function meth4(): void {} } """ ) self.rename("Method", "Sd::meth4", "Sd::meth4b") self.rename("Method", "Sd::meth3", "Sd::meth3b") self.rename("Method", "Sd::meth2", "Sd::meth2b") self.rename("Method", "Sd::meth1", "Sd::meth1b") self.rename("Method", "Sd::smeth", "Sd::smethb") self.expect_contents( """<?hh class Sd { <<__Deprecated("Use `smethb` instead")>> public static function smeth(): void { self::smethb(); } public static function smethb(): void {} <<__Deprecated("Use `meth1b` instead")>> public function meth1(): void { $this->meth1b(); } public function meth1b(): void {} <<__Deprecated("Use `meth2b` instead")>> public function meth2(): void { $this->meth2b(); } <<__NoAutoDynamic, __SupportDynamicType>> public function meth2b(): void {} <<__Deprecated("Use `meth3b` instead")>> public function meth3(): void { $this->meth3b(); } <<__SupportDynamicType>> public function meth3b(): void {} <<__Deprecated("Use `meth4b` instead")>> public function meth4(): void { $this->meth4b(); } <<__NoAutoDynamic>> public function meth4b(): void {} } """ )
Python
hhvm/hphp/hack/test/integration/test_save_state.py
# pyre-strict from __future__ import absolute_import, division, print_function, unicode_literals import json import os import shlex import shutil import sqlite3 import stat import sys import time import unittest from typing import Optional, TextIO import common_tests import hierarchy_tests from hh_paths import hh_client from saved_state_test_driver import SavedStateTestDriver, SaveStateResult from test_case import TestCase def write_echo_json(f: TextIO, obj: object) -> None: f.write("echo %s\n" % shlex.quote(json.dumps(obj))) class LazyInitTestDriver(SavedStateTestDriver): def write_local_conf(self) -> None: with open(os.path.join(self.repo_dir, "hh.conf"), "w") as f: f.write( r""" # some comment use_mini_state = true use_watchman = true watchman_subscribe_v2 = true lazy_decl = true lazy_parse = true lazy_init2 = true incremental_init = true enable_fuzzy_search = false max_workers = 2 """ ) class LazyInitCommonTests(common_tests.CommonTests): @classmethod def get_test_driver(cls) -> LazyInitTestDriver: return LazyInitTestDriver() class LazyInitHeirarchyTests(hierarchy_tests.HierarchyTests): @classmethod def get_test_driver(cls) -> LazyInitTestDriver: return LazyInitTestDriver() class SavedStateCommonTests(common_tests.CommonTests): @classmethod def get_test_driver(cls) -> SavedStateTestDriver: return SavedStateTestDriver() class SavedStateHierarchyTests(hierarchy_tests.HierarchyTests): @classmethod def get_test_driver(cls) -> SavedStateTestDriver: return SavedStateTestDriver() class SavedStateTests(TestCase[SavedStateTestDriver]): @classmethod def get_test_driver(cls) -> SavedStateTestDriver: return SavedStateTestDriver() def test_hhconfig_change(self) -> None: """ Start hh_server, then change .hhconfig and check that the server kills itself. """ self.test_driver.start_hh_server() self.test_driver.check_cmd(["No errors!"]) with open(os.path.join(self.test_driver.repo_dir, ".hhconfig"), "w") as f: f.write( r""" # some comment assume_php = true """ ) # Server may take some time to kill itself. time.sleep(2) _, stderr = self.test_driver.check_cmd( None, options=["--autostart-server", "false"], assert_loaded_saved_state=False, ) self.assertIn("Error: no hh_server running", stderr) # check how the old one exited log_file = self.test_driver.proc_call( [hh_client, "--logname", self.test_driver.repo_dir] )[0].strip() with open(log_file) as f: logs = f.read() self.assertIn(".hhconfig changed in an incompatible way", logs) def test_watchman_timeout(self) -> None: with open(os.path.join(self.test_driver.repo_dir, "hh.conf"), "a") as f: f.write( r""" watchman_init_timeout = 1 """ ) with open(os.path.join(self.test_driver.bin_dir, "watchman"), "w") as f: f.write( r"""#!/bin/sh sleep 2""" ) os.fchmod(f.fileno(), stat.S_IRWXU) self.test_driver.run_check() # Stop the server, ensuring that its logs get flushed self.test_driver.proc_call([hh_client, "stop", self.test_driver.repo_dir]) logs = self.test_driver.get_all_logs(self.test_driver.repo_dir) self.assertIn("Watchman_sig.Types.Timeout", logs.current_server_log) def test_incrementally_generated_saved_state(self) -> None: old_saved_state: SaveStateResult = self.test_driver.dump_saved_state() self.test_driver.proc_call([hh_client, "stop", self.test_driver.repo_dir]) self.test_driver.start_hh_server( changed_files=[], saved_state_path=old_saved_state.path, ) new_file = os.path.join(self.test_driver.repo_dir, "class_3b.php") self.add_file_that_depends_on_class_a(new_file) self.test_driver.check_cmd(["No errors!"], assert_loaded_saved_state=False) new_saved_state: SaveStateResult = self.test_driver.dump_saved_state_incr( old_saved_state ) self.change_return_type_on_base_class( os.path.join(self.test_driver.repo_dir, "class_1.php") ) self.test_driver.check_cmd( [ "{root}class_3.php:5:12,19: Invalid return type (Typing[4110])", " {root}class_3.php:4:28,30: Expected `int`", " {root}class_1.php:5:33,38: But got `string`", "{root}class_3b.php:5:8,15: Invalid return type (Typing[4110])", " {root}class_3b.php:4:26,28: Expected `int`", " {root}class_1.php:5:33,38: But got `string`", ], assert_loaded_saved_state=False, ) self.test_driver.proc_call([hh_client, "stop", self.test_driver.repo_dir]) # Start server with the original saved state. Will be missing the # second error because of the missing edge. self.test_driver.start_hh_server( changed_files=["class_1.php"], saved_state_path=old_saved_state.path ) self.test_driver.check_cmd( [ "{root}class_3.php:5:12,19: Invalid return type (Typing[4110])", " {root}class_3.php:4:28,30: Expected `int`", " {root}class_1.php:5:33,38: But got `string`", ] ) self.test_driver.proc_call([hh_client, "stop", self.test_driver.repo_dir]) # Start another server with the new saved state. Will have both errors. self.test_driver.start_hh_server( changed_files=["class_1.php"], saved_state_path=new_saved_state.path ) self.test_driver.check_cmd( [ "{root}class_3.php:5:12,19: Invalid return type (Typing[4110])", " {root}class_3.php:4:28,30: Expected `int`", " {root}class_1.php:5:33,38: But got `string`", "{root}class_3b.php:5:8,15: Invalid return type (Typing[4110])", " {root}class_3b.php:4:26,28: Expected `int`", " {root}class_1.php:5:33,38: But got `string`", ] ) def test_incrementally_generated_saved_state_after_loaded_saved_state(self) -> None: # Same as the above test, except we begin the test by starting up # a Hack Server that loads a saved state. self.test_driver.start_hh_server() # Hack server is now started with a saved state self.test_driver.check_cmd(["No errors!"], assert_loaded_saved_state=True) self.test_driver.proc_call([hh_client, "stop", self.test_driver.repo_dir]) old_saved_state = self.test_driver.dump_saved_state() self.test_driver.proc_call([hh_client, "stop", self.test_driver.repo_dir]) self.test_driver.start_hh_server( changed_files=[], saved_state_path=old_saved_state.path, ) new_file = os.path.join(self.test_driver.repo_dir, "class_3b.php") self.add_file_that_depends_on_class_a(new_file) self.test_driver.check_cmd(["No errors!"], assert_loaded_saved_state=True) new_saved_state = self.test_driver.dump_saved_state_incr(old_saved_state) self.change_return_type_on_base_class( os.path.join(self.test_driver.repo_dir, "class_1.php") ) self.test_driver.check_cmd( [ "{root}class_3.php:5:12,19: Invalid return type (Typing[4110])", " {root}class_3.php:4:28,30: Expected `int`", " {root}class_1.php:5:33,38: But got `string`", "{root}class_3b.php:5:8,15: Invalid return type (Typing[4110])", " {root}class_3b.php:4:26,28: Expected `int`", " {root}class_1.php:5:33,38: But got `string`", ], assert_loaded_saved_state=True, ) self.test_driver.proc_call([hh_client, "stop", self.test_driver.repo_dir]) # Start server with the original saved state. Will be missing the # second error because of the missing edge. self.test_driver.start_hh_server( changed_files=["class_1.php"], saved_state_path=old_saved_state.path ) self.test_driver.check_cmd( [ "{root}class_3.php:5:12,19: Invalid return type (Typing[4110])", " {root}class_3.php:4:28,30: Expected `int`", " {root}class_1.php:5:33,38: But got `string`", ] ) self.test_driver.proc_call([hh_client, "stop", self.test_driver.repo_dir]) # Start another server with the new saved state. Will have both errors. self.test_driver.start_hh_server( changed_files=["class_1.php"], saved_state_path=new_saved_state.path ) self.test_driver.check_cmd( [ "{root}class_3.php:5:12,19: Invalid return type (Typing[4110])", " {root}class_3.php:4:28,30: Expected `int`", " {root}class_1.php:5:33,38: But got `string`", "{root}class_3b.php:5:8,15: Invalid return type (Typing[4110])", " {root}class_3b.php:4:26,28: Expected `int`", " {root}class_1.php:5:33,38: But got `string`", ] ) def test_incrementally_generated_saved_state_with_errors(self) -> None: # Introduce an error in "master" self.change_return_type_on_base_class( os.path.join(self.test_driver.repo_dir, "class_1.php") ) saved_state_with_1_error: SaveStateResult = self.test_driver.dump_saved_state( ignore_errors=True ) self.test_driver.proc_call([hh_client, "stop", self.test_driver.repo_dir]) # Start server with the saved state, assume there are no local changes. self.test_driver.start_hh_server( changed_files=None, saved_state_path=saved_state_with_1_error.path ) # We still expect that the error from the saved state shows up. self.test_driver.check_cmd( [ "{root}class_3.php:5:12,19: Invalid return type (Typing[4110])", " {root}class_3.php:4:28,30: Expected `int`", " {root}class_1.php:5:33,38: But got `string`", ] ) self.test_driver.proc_call([hh_client, "stop", self.test_driver.repo_dir]) new_file = os.path.join(self.test_driver.repo_dir, "class_3b.php") self.add_file_that_depends_on_class_a(new_file) # Start server with the saved state, the only change is in the new file. self.test_driver.start_hh_server( changed_files=["class_3b.php"], saved_state_path=saved_state_with_1_error.path, ) # Now we expect 2 errors - one from the saved state and one # from the change. self.test_driver.check_cmd( [ "{root}class_3.php:5:12,19: Invalid return type (Typing[4110])", " {root}class_3.php:4:28,30: Expected `int`", " {root}class_1.php:5:33,38: But got `string`", "{root}class_3b.php:5:8,15: Invalid return type (Typing[4110])", " {root}class_3b.php:4:26,28: Expected `int`", " {root}class_1.php:5:33,38: But got `string`", ], assert_loaded_saved_state=False, ) saved_state_with_2_errors = self.test_driver.dump_saved_state_incr( saved_state_with_1_error, ignore_errors=True ) self.test_driver.proc_call([hh_client, "stop", self.test_driver.repo_dir]) # Let's fix the error self.change_return_type_on_base_class( filename=os.path.join(self.test_driver.repo_dir, "class_1.php"), type="int", value="11", ) # Start another server with the new saved state. Will have both errors. self.test_driver.start_hh_server( changed_files=["class_1.php"], saved_state_path=saved_state_with_2_errors.path, ) self.test_driver.check_cmd(["No errors!"], assert_loaded_saved_state=True) def add_file_that_depends_on_class_a(self, filename: str) -> None: with open(filename, "w") as f: f.write( """<?hh // strict class UsesAToo { public function test() : int { return A::foo(); } } """ ) def change_return_type_on_base_class( self, filename: str, type: str = "string", value: str = '"Hello"' ) -> None: # Change the return type with open(filename, "w") as f: f.write( """<?hh // strict class B { public static function foo () : %s { return %s; } } """ % (type, value) ) class ReverseNamingTableFallbackTestDriver(SavedStateTestDriver): enable_naming_table_fallback = True def write_local_conf(self) -> None: with open(os.path.join(self.repo_dir, "hh.conf"), "w") as f: f.write( r""" # some comment use_mini_state = true use_watchman = true watchman_subscribe_v2 = true lazy_decl = true lazy_parse = true lazy_init2 = true enable_naming_table_fallback = true """ ) class ReverseNamingTableSavedStateCommonTests(common_tests.CommonTests): @classmethod def get_test_driver(cls) -> ReverseNamingTableFallbackTestDriver: return ReverseNamingTableFallbackTestDriver() class ReverseNamingTableSavedStateHierarchyTests(hierarchy_tests.HierarchyTests): @classmethod def get_test_driver(cls) -> ReverseNamingTableFallbackTestDriver: return ReverseNamingTableFallbackTestDriver() class ReverseNamingTableSavedStateTests(SavedStateTests): @classmethod def get_test_driver(cls) -> ReverseNamingTableFallbackTestDriver: return ReverseNamingTableFallbackTestDriver() def test_file_moved(self) -> None: new_file = os.path.join(self.test_driver.repo_dir, "class_3b.php") self.add_file_that_depends_on_class_a(new_file) self.test_driver.check_cmd(["No errors!"], assert_loaded_saved_state=False) naming_table_path = self.test_driver.dump_naming_saved_state( self.test_driver.repo_dir, saved_state_path=os.path.join(self.test_driver.repo_dir, "new"), ) self.test_driver.proc_call([hh_client, "stop", self.test_driver.repo_dir]) new_file2 = os.path.join(self.test_driver.repo_dir, "class_3c.php") shutil.move(new_file, new_file2) self.test_driver.start_hh_server( changed_files=[], changed_naming_files=["class_3c.php"], naming_saved_state_path=naming_table_path, ) self.test_driver.check_cmd(["No errors!"], assert_loaded_saved_state=True)
Python
hhvm/hphp/hack/test/integration/test_tast_holes.py
# pyre-strict from __future__ import absolute_import, unicode_literals import json import os from common_tests import CommonTestDriver from test_case import TestCase class TastHolesDriver(CommonTestDriver): error_file_ext = ".holes" auto_namespace_map = '{"PHP": "HH\\\\Lib\\\\PHP"}' repo_dir = "hphp/hack/test/integration/data/holes" def write_load_config( self, use_serverless_ide: bool = False, use_saved_state: bool = False ) -> None: with open(os.path.join(self.repo_dir, ".hhconfig"), "w") as f: f.write( """ auto_namespace_map = {} allowed_fixme_codes_strict = 4101,4323,4110 allowed_decl_fixme_codes = 4101,4323,4110 disable_xhp_element_mangling = false """.format( self.auto_namespace_map ) ) def expected_file_name(self, file_name: str) -> str: return "{}.holes.exp".format(file_name) def expected_file_path(self, file_name: str) -> str: return os.path.join(self.repo_dir, self.expected_file_name(file_name)) def expected_type_error(self, file_name: str) -> str: with open(self.expected_file_path(file_name)) as expected_file: return expected_file.read().strip() def extract_type_error(self, file_name: str) -> str: arg = os.path.join(self.repo_dir, file_name) extracted_error, err, retcode = self.run_check( options=["--tast-holes", arg, "--json"] ) self.assertEqual( 0, retcode, "hh --tast-holes {} returned non-zero code: {}".format(file_name, err), ) return json.dumps( json.loads(extracted_error.replace(self.repo_dir, "")), indent=2 ) def assert_expected_error_matches_extracted_error(self, file_name: str) -> None: self.assertMultiLineEqual( self.expected_type_error(file_name), self.extract_type_error(file_name), f"The expected result of extracting tast Holes from {file_name} doesn't match the extracted ", ) class TestTastHoles(TestCase[TastHolesDriver]): @classmethod def setUpClass(cls) -> None: super().setUpClass() @classmethod def get_template_repo(cls) -> str: return "hphp/hack/test/integration/data/holes" @classmethod def get_test_driver(cls) -> TastHolesDriver: return TastHolesDriver() def test_type_error(self) -> None: self.test_driver.write_load_config() cases = [ "call_single.php", "call_multiple.php", "call_unpack.php", "return_expr_only.php", "return_and_fn_arg.php", "member_call_multiple.php", "coincident_holes.php", ] for file_name in cases: with self.subTest(msg=f"{file_name}"): self.test_driver.assert_expected_error_matches_extracted_error( file_name )
Python
hhvm/hphp/hack/test/integration/test_type_error_at_pos.py
from __future__ import absolute_import, unicode_literals import json import os from common_tests import CommonTestDriver from test_case import TestCase class TypeErrorAtPosDriver(CommonTestDriver): error_file_ext = ".err" auto_namespace_map = '{"PHP": "HH\\\\Lib\\\\PHP"}' repo_dir = "hphp/hack/test/integration/data/holes" def write_load_config( self, use_serverless_ide: bool = False, use_saved_state: bool = False ) -> None: with open(os.path.join(self.repo_dir, ".hhconfig"), "w") as f: f.write( """ auto_namespace_map = {} allowed_fixme_codes_strict = 4101,4323 allowed_decl_fixme_codes = 4101,4323 disable_xhp_element_mangling = false enable_sound_dynamic_type = true everything_sdt = true like_type_hints = true """.format( self.auto_namespace_map ) ) def expected_file_name(self, file_name: str, row_num: int, col_num: int) -> str: return "{}+{}+{}.err.exp".format(file_name, row_num, col_num) def expected_file_path(self, file_name: str, row_num: int, col_num: int) -> str: return os.path.join( self.repo_dir, self.expected_file_name(file_name, row_num, col_num) ) def expected_type_error(self, file_name: str, row_num: int, col_num: int) -> str: with open( self.expected_file_path(file_name, row_num, col_num) ) as expected_file: return expected_file.read().strip() def extract_type_error(self, file_name: str, row_num: int, col_num: int) -> str: arg = os.path.join( self.repo_dir, "{}:{}:{}".format(file_name, row_num, col_num) ) extracted_error, _, retcode = self.run_check( options=["--type-error-at-pos", arg, "--json"] ) self.assertEqual( 0, retcode, "hh --type-error-at-pos {} returned non-zero code".format(arg), ) return json.dumps( json.loads(extracted_error.replace(self.repo_dir, "")), indent=2 ) def assert_expected_error_matches_extracted_error( self, file_name: str, row_num: int, col_num: int ) -> None: self.assertMultiLineEqual( self.expected_type_error(file_name, row_num, col_num), self.extract_type_error(file_name, row_num, col_num), f"The expected result of extracting type error in {file_name}, row {row_num}, column {col_num}, doesn't match the extracted ", ) class TestTypeErrorAtPos(TestCase[TypeErrorAtPosDriver]): @classmethod def setUpClass(cls) -> None: super().setUpClass() @classmethod def get_template_repo(cls) -> str: return "hphp/hack/test/integration/data/holes" @classmethod def get_test_driver(cls) -> TypeErrorAtPosDriver: return TypeErrorAtPosDriver() def test_type_error(self) -> None: self.test_driver.write_load_config() cases = [ ("call_single.php", [(7, 10), (10, 10)]), ("call_multiple.php", [(7, 5), (7, 8)]), ("call_unpack.php", [(7, 8)]), ("return_expr_only.php", [(5, 10), (5, 21)]), ("return_and_fn_arg.php", [(5, 10), (5, 21)]), ] for (file_name, positions) in cases: for (row_num, col_num) in positions: with self.subTest(msg=f"{file_name}:{row_num}:{col_num}"): self.test_driver.assert_expected_error_matches_extracted_error( file_name, row_num, col_num )
Python
hhvm/hphp/hack/test/integration/test_write_symbol_info.py
# pyre-strict from __future__ import absolute_import, division, print_function, unicode_literals import json import os from typing import ClassVar, Dict, List, Optional, Type import test_case from common_tests import CommonTestDriver from glean.schema.gencode.types import GenCode from glean.schema.hack.types import ( ClassConstDeclaration, ClassConstDefinition, ClassDeclaration, ClassDefinition, DeclarationComment, DeclarationLocation, DeclarationSpan, EnumDeclaration, EnumDefinition, Enumerator, FileCall, FileDeclarations, FileXRefs, FunctionDeclaration, FunctionDefinition, GlobalConstDeclaration, GlobalConstDefinition, GlobalNamespaceAlias, IndexerInputsHash, InheritedMembers, InterfaceDeclaration, InterfaceDefinition, MemberCluster, MethodDeclaration, MethodDefinition, MethodOccurrence, MethodOverrides, ModuleDeclaration, ModuleDefinition, NamespaceDeclaration, NamespaceQName, PropertyDeclaration, PropertyDefinition, QName, TraitDeclaration, TraitDefinition, TypeConstDeclaration, TypeConstDefinition, TypedefDeclaration, TypedefDefinition, TypeInfo, ) from glean.schema.src.types import FileLines from hh_paths import hh_server from thrift.py3 import deserialize, Protocol, Struct class WriteSymbolInfoTests(test_case.TestCase[CommonTestDriver]): write_repo: ClassVar[str] = "default_symbol_info_test_dir" valid_keys: ClassVar[Dict[str, List[object]]] = {} @classmethod def get_test_driver(cls) -> CommonTestDriver: return CommonTestDriver() def setUp(self) -> None: super().setUp() with open(os.path.join(self.test_driver.repo_dir, "hh.conf"), "w") as f: f.write( r""" # some comment use_mini_state = true use_watchman = true watchman_subscribe_v2 = true lazy_decl = true lazy_parse = true lazy_init2 = true incremental_init = true enable_fuzzy_search = false max_workers = 2 """ ) def tearDown(self) -> None: try: # driver.tearDown() can throw if the env is not as expected super().tearDown() except Exception as e: print("Error during test teardown : {}".format(str(e))) @classmethod def setUpClass(cls) -> None: super().setUpClass() test_driver = cls._test_driver if test_driver is not None: cls.write_repo = os.path.join(test_driver.repo_dir, "symbol_info_test_dir") else: print("Test driver error during class setup") def verify_json(self) -> None: for filename in os.listdir(self.write_repo): self.assertTrue( filename.endswith(".json"), "All output files are in JSON format" ) with open(os.path.join(self.write_repo, filename)) as file: json_predicate_list = json.load(file) for pred_obj in json_predicate_list: self.assertTrue( "predicate" in pred_obj and "facts" in pred_obj, "JSON predicate has correct form", ) fact_type = self.predicate_name_to_type(pred_obj["predicate"]) if fact_type is None: self.fail( "Could not find matching Thrift definition for {}".format( pred_obj["predicate"] ) ) for fact in pred_obj["facts"]: try: deserialize( fact_type, json.dumps(fact).encode("UTF-8"), protocol=Protocol.JSON, ) except Exception as e: self.fail( "Could not deserialize {} fact JSON: {}\nDeserialization error: {}".format( fact_type, fact, e ) ) def predicate_name_to_type(self, predicate_name: str) -> Optional[Type[Struct]]: predicate_dict = { "hack.FileCall": FileCall, "hack.ClassConstDeclaration": ClassConstDeclaration, "hack.ClassConstDefinition": ClassConstDefinition, "hack.ClassDeclaration": ClassDeclaration, "hack.ClassDefinition": ClassDefinition, "hack.DeclarationComment": DeclarationComment, "hack.DeclarationLocation": DeclarationLocation, "hack.DeclarationSpan": DeclarationSpan, "hack.EnumDeclaration": EnumDeclaration, "hack.EnumDefinition": EnumDefinition, "hack.Enumerator": Enumerator, "hack.FileDeclarations": FileDeclarations, "hack.FileXRefs": FileXRefs, "hack.FunctionDeclaration": FunctionDeclaration, "hack.FunctionDefinition": FunctionDefinition, "hack.GlobalConstDeclaration": GlobalConstDeclaration, "hack.GlobalConstDefinition": GlobalConstDefinition, "hack.InheritedMembers": InheritedMembers, "hack.InterfaceDeclaration": InterfaceDeclaration, "hack.InterfaceDefinition": InterfaceDefinition, "hack.IndexerInputsHash": IndexerInputsHash, "hack.MemberCluster": MemberCluster, "hack.MethodDeclaration": MethodDeclaration, "hack.MethodDefinition": MethodDefinition, "hack.MethodOccurrence": MethodOccurrence, "hack.MethodOverrides": MethodOverrides, "hack.ModuleDeclaration": ModuleDeclaration, "hack.ModuleDefinition": ModuleDefinition, "hack.NamespaceDeclaration": NamespaceDeclaration, "hack.NamespaceQName": NamespaceQName, "hack.PropertyDeclaration": PropertyDeclaration, "hack.PropertyDefinition": PropertyDefinition, "hack.QName": QName, "hack.TraitDeclaration": TraitDeclaration, "hack.TraitDefinition": TraitDefinition, "hack.TypeConstDeclaration": TypeConstDeclaration, "hack.TypeConstDefinition": TypeConstDefinition, "hack.TypedefDeclaration": TypedefDeclaration, "hack.TypedefDefinition": TypedefDefinition, "hack.TypeInfo": TypeInfo, "hack.GlobalNamespaceAlias": GlobalNamespaceAlias, "src.FileLines": FileLines, "gencode.GenCode": GenCode, } predicate_base = predicate_name[: predicate_name.rfind(".")] return predicate_dict.get(predicate_base) def start_hh_server( self, changed_files: Optional[List[str]] = None, saved_state_path: Optional[str] = None, args: Optional[List[str]] = None, ) -> None: """Start an hh_server. changed_files is ignored here (as it has no meaning) and is only exposed in this API for the derived classes. """ if changed_files is None: changed_files = [] if args is None: args = [] cmd = [ hh_server, "--max-procs", "2", "--config", "symbolindex_search_provider=NoIndex", self.test_driver.repo_dir, ] + args self.test_driver.proc_call(cmd) def test_json_format(self) -> None: print("repo_contents : {}".format(os.listdir(self.test_driver.repo_dir))) args: Optional[List[str]] = ["--write-symbol-info", self.write_repo] self.start_hh_server(args=args) self.verify_json()
Python
hhvm/hphp/hack/test/integration/utils.py
# pyre-strict from __future__ import absolute_import, division, print_function, unicode_literals import os import re import signal from types import FrameType from typing import BinaryIO, Callable, Iterable, Mapping, Union try: from typing import ForwardRef except ImportError: # pyre-fixme[21]: Could not find name `_ForwardRef` in `typing`. from typing import _ForwardRef as ForwardRef # pyre-fixme[5]: Global expression must be annotated. # pyre-fixme[6]: Expected `Tuple[typing.Type[Variable[typing._KT]], # typing.Type[Variable[typing._VT_co](covariant)]]` for 1st param but got # `Tuple[typing.Type[str], ForwardRef]`. JsonObject = Mapping[str, ForwardRef("Json")] # pyre-fixme[5]: Global expression must be annotated. # pyre-fixme[16]: `Iterable` has no attribute `__getitem__`. JsonArray = Iterable[ForwardRef("Json")] JsonScalar = Union[str, int, float, bool, None] # pyre-fixme[5]: Global expression must be annotated. Json = Union[JsonObject, JsonArray, JsonScalar] VariableMap = Mapping[str, str] def touch(fn: str) -> None: with open(fn, "a"): os.utime(fn, None) def write_files(files: Mapping[str, str], dir_path: str) -> None: """ Write a bunch of files into the directory at dir_path. files: dict of file name => file contents """ for fn, content in files.items(): path = os.path.join(dir_path, fn) with open(path, "w") as f: f.write(content) def ensure_output_contains(f: BinaryIO, s: str, timeout: int = 20) -> None: """ Looks for a match in a process' output, subject to a timeout in case the process hangs """ lines = [] # pyre-fixme[53]: Captured variable `lines` is not annotated. def handler(signo: int, frame: FrameType) -> None: raise AssertionError( "Failed to find %s in the following output: %s" % (s, "".join(lines)) ) try: signal.signal(signal.SIGALRM, handler) signal.alarm(timeout) while True: line = f.readline().decode("utf-8") if s in line: return lines.append(line) finally: signal.alarm(0) # pyre-fixme[11]: Annotation `Json` is not defined as a type. # pyre-fixme[11]: Annotation `Json` is not defined as a type. def map_json_scalars(json: Json, f: Callable[[JsonScalar], JsonScalar]) -> Json: if isinstance(json, dict): return { map_json_scalars(json=k, f=f): map_json_scalars(json=v, f=f) for k, v in json.items() } elif isinstance(json, list): return [map_json_scalars(json=i, f=f) for i in json] elif isinstance(json, (str, int, float, bool, type(None))): return f(json) else: raise AssertionError(f"Unhandled JSON case: {json.__class__.__name__}") # Because HHI folders are different for each process, # let's just standardize them def fixup_hhi_json(payload: Json) -> Json: def interpolate(json: JsonScalar) -> JsonScalar: if isinstance(json, str): json = re.sub( "/[a-zA-Z0-9/_]*/hhi_[0-9a-f]*/", "/tmp/cleansed_hhi_path/", json ) return json return map_json_scalars(json=payload, f=interpolate) def interpolate_variables(payload: Json, variables: VariableMap) -> Json: def interpolate(json: JsonScalar) -> JsonScalar: if isinstance(json, str): for variable, value in variables.items(): json = json.replace("${" + variable + "}", value) if re.search(r"\$\{[^0-9]", json) is not None: raise ValueError( f"There was an undefined ${{}}-variable " + f"in this JSON value: {json!r}. " + f"Make sure that you have initialized everything correctly and " + f"passed the correct variable map " + f"to {interpolate_variables.__name__}. " + f"It is currently: {variables!r}" ) return json return map_json_scalars(json=payload, f=interpolate) def uninterpolate_variables(payload: Json, variables: VariableMap) -> Json: # Sort so that we process the variable with the longest-length bindings first. variable_bindings = sorted( variables.items(), key=lambda kv: len(kv[1]), reverse=True ) for variable, value in variable_bindings: # pyre-fixme[53]: Captured variable `value` is not annotated. def uninterpolate(json: JsonScalar) -> JsonScalar: if isinstance(json, str): return json.replace(value, "${" + variable + "}") else: return json payload = map_json_scalars(json=payload, f=uninterpolate) return payload
Python
hhvm/hphp/hack/test/integration/utils_test.py
import unittest from utils import interpolate_variables, uninterpolate_variables class UtilsTest(unittest.TestCase): def test_interpolate_variables_simple(self) -> None: variables = {"foo": "bar"} payload = {"hello": "hi ${foo} hi"} expected = {"hello": "hi bar hi"} self.assertEqual(interpolate_variables(payload, variables), expected) self.assertEqual(uninterpolate_variables(expected, variables), payload) def test_interpolate_variables_multiple(self) -> None: variables = {"foo": "bar", "baz": "qux"} payload = { "hello": "${foo} ${baz}", "nested": {"foo": "${foo}"}, "in key: ${baz}": True, } expected = {"hello": "bar qux", "nested": {"foo": "bar"}, "in key: qux": True} self.assertEqual(interpolate_variables(payload, variables), expected) self.assertEqual(uninterpolate_variables(expected, variables), payload) def test_undefined_variable_raises_exception(self) -> None: variables = {} payload = {"hello": "bar ${foo} bar"} with self.assertRaises(ValueError): interpolate_variables(payload, variables)
PHP
hhvm/hphp/hack/test/integration/autocomplete/some_other_file.php
<?hh // Doesn't work as of today, as top level symbols information is not correctly // populated /* function autocomplete0_fp(): void { */ /* SomeAUTO332 */ function autocomplete1(): void { SomeEnumClass::AUTO332 function autocomplete2(): void { SomeEnumClass#AUTO332
hhvm/hphp/hack/test/integration/data/codemod_sdt/.hhconfig
like_type_hints = true enable_sound_dynamic_type = true union_intersection_type_hints = true everything_sdt = true enable_no_auto_dynamic = true
PHP
hhvm/hphp/hack/test/integration/data/codemod_sdt/integration_test_codemod_sdt1.php
<?hh interface I { public function foo(vec<int> $_): void; } final class C implements I { public function foo(vec<int> $_): void {} } final class D implements I { public function foo(vec<int> $_): void {} }
Hack
hhvm/hphp/hack/test/integration/data/concat_all/ns_body_a.hack
namespace NSBodyA { use type TypeA as MyType; function do_stuff(): void { new MyType(); } }
Hack
hhvm/hphp/hack/test/integration/data/concat_all/ns_body_b.hack
namespace NSBodyB { use type TypeB as MyType; function do_stuff(): void { new MyType(); } }
PHP
hhvm/hphp/hack/test/integration/data/decl_from_stdin/decl_from_stdin1.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. // CARE! the decl_from_stdin test looks at line 13 column 9 of this file class C1 { public function m1(): void {} } final class D1 { public function n1(): void { $x = new C1(); $x->m1(); } }
PHP
hhvm/hphp/hack/test/integration/data/decl_from_stdin/decl_from_stdin2.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. // CARE! the decl_from_stdin test looks at line 8 column 9 of this file final class C2 { public function m2(): void { new C2(); } }
PHP
hhvm/hphp/hack/test/integration/data/dependencies/builtins.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. namespace HH\Lib\PHP; function ini_set(string $varname, ?int $newvalue = null): void {}
PHP
hhvm/hphp/hack/test/integration/data/dependencies/classes-generic.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. class GenericBase<Tfirst, Tsecond> { const int GENERIC_CONSTANT = -(1 + 2); public function __construct(public Tfirst $first, public Tsecond $second) {} } type GenericType<T> = GenericBase<T, int>; enum Mode: int as int { One = 1; Two = 2; } function with_enum_and_constant(Mode $arg): int { return $arg + Mode::One + GenericBase::GENERIC_CONSTANT; } class GenericDerived<Tfirst> extends GenericBase<Tfirst, Mode> { public function __construct(Tfirst $first, Mode $second) { parent::__construct($first, $second); $this->property = $second; } protected int $property; public function foo(): void {} } class First {} class Second {} class NonGenericDerived extends GenericBase<First, Second> {} class Regular { public function generic_method<T>(T $arg): void {} } function with_generic_method(int $arg): void { $r = new Regular(); $r->generic_method($arg); } function with_generic_method_with_wildcard_tparam(int $arg): void { $r = new Regular(); $r->generic_method<_>($arg); } function with_properties<T>(GenericDerived<T> $arg) : Mode { $x = new GenericDerived<int>(1, Mode::Two); return $arg->second; } function with_generic_type<T>(GenericType<T> $arg): void { } function with_non_generic_type(NonGenericDerived $_): void {} interface GenericInterface<Tfirst, Tsecond> {} interface IGenericDerived<T> extends GenericInterface<T, int> { require extends GenericBase<float, T>; } function with_generic_interface<T>(IGenericDerived<T> $arg): void {} function with_is_refinement<Tfirst, Tsecond>( GenericBase<Tfirst, Tsecond> $x, ): void { if ($x is GenericDerived<_>) { $x->foo(); } } class BoundedGeneric<T as arraykey> { public function emptyKeyset(): keyset<T> { return keyset[]; } } function with_bounded_generic_class_tparam(BoundedGeneric<int> $x): keyset<int> { return $x->emptyKeyset(); } interface IResult<+T> {} class Result<+T> implements IResult<T> {} interface IKwery<TResult as Result<mixed>> {} class Kwery<TValue, TResult as Result<TValue>> implements IKwery<TResult> {} function kwery(): Kwery<int, Result<int>> { return new Kwery(); } <<__ConsistentConstruct>> abstract class Box<+T> { private function __construct(private T $value) {} final public static function make(T $value): this { return new static($value); } } class IntBox extends Box<int> {} function with_contra_tparam(): Box<int> { return IntBox::make(42); } class WithReifiedGenerics<reify T as arraykey> {} function with_reified_generics(): WithReifiedGenerics<int> { return new WithReifiedGenerics<int>(); }
PHP
hhvm/hphp/hack/test/integration/data/dependencies/classes-interfaces.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. interface BaseInterface {} interface DerivedInterface extends BaseInterface { public function routine(): void; } function with_interface(DerivedInterface $arg): void { $arg->routine(); } interface SimpleInterface { require extends AbstractBase; } trait RequiringTrait { require implements BaseInterface; require implements SimpleInterface; } class Implementing extends AbstractBase implements DerivedInterface { public function routine(): void { $this->must_implement(); } protected function must_implement(): void {} } class DerivedImplementing extends Implementing implements SimpleInterface { use RequiringTrait; } function with_requiring_trait(DerivedImplementing $arg): void {} class ImplementsBuiltin implements StringishObject { public function __toString(): string { return ""; } } function does_not_use_class_methods(ImplementsBuiltin $arg): void {} abstract class Bee { public function f(): void {} } interface Eye { require extends Bee; } interface Jay extends Eye {} function with_indirect_require_extends(Jay $x): void { $x->f(); } abstract class BB { abstract public function f(): void; } interface II { abstract const type T; public function g(): this::T; public function h(): void; } final class CC extends BB implements II { const type T = int; public function f(): void {} public function g(): int { return 42; } public function h(): void {} } function with_implementations(BB $b, II $i, CC $c): void { $b->f(); $_ = $i->g(); } <<__ConsistentConstruct>> interface IWithNullaryConstructor { public function __construct(); } trait TDummy implements IWithNullaryConstructor {} class WithOptionalConstructorArguments implements IWithNullaryConstructor { use TDummy; public function __construct(?int $x = null, ?string $y = null) {} public static function get(): this { return new static(); } } <<__ConsistentConstruct>> class WithConsistentConstruct { public function __construct() {} } interface IExtendsWithConsistentConstruct { require extends WithConsistentConstruct; } trait TExtendsWithConsistentConstruct { require implements IExtendsWithConsistentConstruct; public static function get(): this { return new static(); } } function with_IEWGPCOUP(IEWGPCOUB $x): IEWGP { return $x->f(); } interface IEWGPCOUB extends IEWGPMB, IEPCOUB {} interface IEWGPMB extends IEPMB { abstract const type T as IEWGP; } interface IEPCOUB extends IEMBUIDCOUB {} interface IEPMB extends IEMBUIDMB { abstract const type T as IEP; } interface IEMBUIDCOUB extends IEMBUIDMB {} interface IEMBUIDMB { abstract const type T as IEMBUID; public function f(): this::T; } interface IEWGP extends IEP {} interface IEP extends IEMBUID {} interface IEMBUID {} <<__Sealed(OnSealedWhitelist::class)>> interface WithSealedWhitelist<T as arraykey> { } interface OnSealedWhitelist<T as arraykey> extends WithSealedWhitelist<T> { public function __construct(T ...$values); } function with_arg_with_sealed_whitelist(WithSealedWhitelist<int> $f): void {}
PHP
hhvm/hphp/hack/test/integration/data/dependencies/classes-traits.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. trait ImplementingAbstractBase { protected function must_implement(): void { } } trait T { require extends AbstractBase; public function routine(): void { $this->must_implement(); } } class TraitBase extends AbstractBase { use ImplementingAbstractBase; use T; } function with_traits(TraitBase $arg) : void { $arg->routine(); } interface IHasFoo { abstract const type TFoo; public function getDefaultFoo(): this::TFoo; } trait THasFoo { require implements IHasFoo; public function getFoo(): this::TFoo { return $this->getDefaultFoo(); } } class IntFooWrapper implements IHasFoo { use THasFoo; const type TFoo = int; public function getDefaultFoo(): this::TFoo { return 0; } } function with_type_const_from_required_interface( IntFooWrapper $w, ): int { return $w->getFoo(); } abstract class HasBar { abstract const type TBar; public function getDefaultBar(): ?this::TBar { return null; } } interface IHasBar { const type TBar = string; } class StringBarWrapper extends HasBar implements IHasBar { public function getBar(): this::TBar { $bar = $this->getDefaultBar(); return $bar ?? 'bar'; } } function with_type_const_from_implemented_interface( StringBarWrapper $w, ): string { return $w->getBar(); } interface IHasBaz { abstract const type TBaz as IHasQuux; const type TQuux = this::TBaz::TQuux; public function takeQuux(this::TQuux $_): void; } interface IHasQuux { abstract const type TQuux; } interface IntBazWrapper extends IHasBaz { const type TBaz = IntQuuxWrapper; } class IntQuuxWrapper implements IHasQuux { const type TQuux = int; } function with_nested_type_const(IntBazWrapper $x): void { $x->takeQuux(42); } interface IContext {} interface IUniverse { abstract const type TContext as IContext; } class Universe implements IUniverse { const type TContext = IContext; } interface ICreation { abstract const type TUniverse as IUniverse; const type TContext = this::TUniverse::TContext; } abstract class BaseQuery<TContext> {} abstract class Query extends BaseQuery<this::TContext> { abstract const type TCreation as ICreation; const type TContext = this::TCreation::TContext; } class Frob implements ICreation { const type TUniverse = Universe; } trait TFrobQuery { require extends BaseQuery<Frob::TContext>; } final class FrobQuery extends Query { use TFrobQuery; const type TCreation = Frob; } function frob_query(): FrobQuery { return new FrobQuery(); } interface ICorge { abstract const type Tthis as this; public function get(): this::Tthis; } final class Corge implements ICorge { const type Tthis = Corge; public function get(): this::Tthis { return $this; } } function corge(Corge $x, ICorge $y): void { $_ = $x->get(); $_ = $y->get(); } interface IWibble { public function f(): void; } trait TWibble { require implements IWibble; public function f(): void {} } class Wibble implements IWibble { use TWibble; } function with_method_defined_in_trait(IWibble $w, Wibble $_): void { $w->f(); } abstract class WobbleBase { abstract public function f(): void; } trait TWobble { require extends WobbleBase; public function f(): void {} } class Wobble extends WobbleBase { use TWobble; } function with_method_defined_in_trait2(WobbleBase $w, Wobble $_): void { $w->f(); } abstract class AAA { abstract const type T; } abstract class BBB { abstract const type TA as AAA; } abstract class CCC { abstract const type TB as BBB; const type TA = this::TB::TA; const type T = this::TA::T; public function with_nested_type_access(this::T $_): void {} } interface IFlob { abstract const type T; public function f1(): void; public static function f2(): this::T; } interface IToto { const type T = int; } abstract class FlobBase { public function f1(): void {} public static function f2(): int { return 42; } } final class Flob extends FlobBase implements IFlob, IToto { use TFlob; } trait TFlob { require implements IFlob; public function g(Flob $_): void { $this->f1(); $_ = static::f2(); } } final class Flobby extends FlobBase { use TFlobby; } trait TFlobby { require extends FlobBase; final public function g(): void { $flobby = $this->asFlobby(); $flobby->f1(); } private function asFlobby(): Flobby { return $this as Flobby; } } <<__Sealed(Mumble::class)>> interface SealedInterface { public function method(): void; public function otherMethod(): void; } <<__Sealed(Mumble::class)>> trait SealedTrait { require implements SealedInterface; public function method(): void {} public function otherMethod(): void {} } final class Mumble implements SealedInterface { use SealedTrait; }
PHP
hhvm/hphp/hack/test/integration/data/dependencies/classes.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. abstract class AbstractBase { const BASE_CONSTANT = 42; public static int $static_base_property = 0; public float $base_property = 42.; abstract protected function must_implement(): void; } function with_abstract(AbstractBase $arg) : float { return AbstractBase::BASE_CONSTANT + $arg->base_property + AbstractBase::$static_base_property; } class ImplementingBase extends AbstractBase { public function inherited(): void {} public function overridden(): int { return -1; } protected function must_implement(): void { $this->inherited(); } } final class Derived extends ImplementingBase { public function __construct(int $num) { $this->result = $num; } <<__Override>> public function overridden(): int { return $this->result; } private int $result; } function with_overriding(Derived $arg): int { $arg->inherited(); return $arg->overridden(); } function call_constructors(): void { $a = new ImplementingBase(); $b = new Derived(0); } function only_variadic(int ...$args): void {} function variadic(inout int $arg, int ...$args): void{} function with_nontrivial_fun_decls(): void { $num = 17; variadic(inout $num, 18, 19); only_variadic($num, 18, 19); $d = new Derived($num); } class WithProperties { public function __construct(int $arg) { $this->first = $arg; } public int $first; public int $second = 42; public static int $third = 7; } function use_properties(WithProperties $arg): int { return $arg->first + $arg->second + WithProperties::$third; } class SimpleClass { public function __construct(string $s, int $i) {} public function simple_method(): void {} public function another_method(): void { $this->coarse_grained_dependency(); } public function coarse_grained_dependency(): void {} } class SimpleDerived extends SimpleClass { public function __construct(float $f, bool $b, mixed ...$args) { parent::__construct('mumble', 42); } public function call_parent_method(): void { parent::simple_method(); ++SimpleDerived::$calls; } private static int $calls = 0; } interface IWithRequirement { require extends A; } function with_requiring_interface(IWithRequirement $arg): void {} function WithNameMatchingClassName(): WithNameMatchingClassName { return new WithNameMatchingClassName(); } class WithNameMatchingClassName {} function with_classname(): string { return SimpleClass::class; } function with_parent_constructor_call(): void { $_ = new SimpleClass('frob', 1337); $_ = new SimpleDerived(3.14, true, null); } class WithReactiveMethods { public function reactive(): void {} public function call_reactive(): void { $this->reactive(); } } class WithLateInit { <<__LateInit>> private int $count; public function getCount(): int { return $this->count; } public function setCount(int $count): void { $this->count = $count; } } abstract class TestExtractConstruct { public function __construct() {} } interface IAsConstraint{} abstract class WithTparamConstraint<T as IAsConstraint>{} class WithPropInConstruct<T> { public function __construct(public T $x)[] {} } class WithTypeConstant { const type T = string; } class WithTypeConstantParamConstraint<T as WithTypeConstant::T> { public function foo(): void {} }
PHP
hhvm/hphp/hack/test/integration/data/dependencies/constants.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. type TypedefForString = string; enum SomeEnum: int { FIRST = 2; SECOND = 3; } enum SecondEnum: string { FIRST = "4"; SECOND = "5"; } type SomeEnumType = SomeEnum; enum ThirdEnum: SomeEnumType { MUMBLE = SomeEnum::FIRST; } function with_enum_type_alias(ThirdEnum $_): void {} function with_enum_class_name(): void { $_ = SomeEnum::class; } abstract class WithAbstractConst { abstract const type ABS_WO_CONSTRAINT; abstract const type ABS_WITH_CONSTRAINT as string; const type NESTED = WithConst; abstract public function with_abstract_type_constants(this::ABS_WO_CONSTRAINT $arg) : this::ABS_WITH_CONSTRAINT; } class WithConst { const float CFLOAT = 1.2; const string CSTRING = 'foo'; const SomeEnum CENUM = SomeEnum::SECOND; const CWITHOUT_HINT = 'constant with inferred type'; const type WITH_CONSTRAINT = A0; const type WITH_THIS = this::WITH_CONSTRAINT; const type TYPECONST = int; public function with_type_constants(this::TYPECONST $arg1, this::WITH_CONSTRAINT $arg2): void {} } const shape('x' => int, 'y' => SecondEnum) SHAPE1 = shape('x' => 5, 'y' => SecondEnum::SECOND); const shape(WithConst::CSTRING => int) SHAPE2 = shape(WithConst::CSTRING => 42); const shape('a' => int, 'b' => string, ...) SHAPE3 = shape('a' => 42, 'b' => 'foo', 'c' => 3.14); const (int, ?(string, float)) OPTION = tuple(7, null); const darray<string, int> ARR = darray['a' => 1, 'b' => 2]; const darray<string, int> AGE_RANGE = darray['min' => 21]; const varray<string> MAP_INDEX = varray['MAP_1', 'MAP_2']; const classname<WithConst> CLASSNAME = WithConst::class; const keyset<string> KEYSET = keyset['a', 'b']; const TypedefForString TYPEDEF = "hello"; const varray_or_darray<int> CVARRAY_OR_DARRAY = varray[1, 2, 3]; function with_constants(): void { $_ = WithConst::CFLOAT; $_ = WithConst::CENUM; $_ = SHAPE1; $_ = OPTION; $_ = ARR; $_ = AGE_RANGE; $_ = MAP_INDEX; $_ = CLASSNAME; $_ = KEYSET; $_ = TYPEDEF; $_ = SHAPE2; $_ = CVARRAY_OR_DARRAY; $_ = SHAPE3; $_ = WithConst::CWITHOUT_HINT; } function with_type_constants(WithAbstractConst::NESTED::WITH_THIS $arg) : WithConst::TYPECONST { return 1; } class WithStaticProperty { public static Map<SomeEnum, string> $map = Map {SomeEnum::FIRST => 'first', SomeEnum::SECOND => 'second'}; public static Vector<A> $vector = Vector {}; } function with_static_property(): void { $a = WithStaticProperty::$map; $b = WithStaticProperty::$vector; } function with_switch(SomeEnum $x): void { switch ($x) { case SomeEnum::FIRST: return; default: return; } } type SomeShape = shape(WithConst::CSTRING => mixed); function with_shape_type_alias(SomeShape $_): void {}
PHP
hhvm/hphp/hack/test/integration/data/dependencies/namespaces.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. namespace Test1 { class A {} function f(int $x) : A { return new A(); } namespace NestedTest { class A extends UltraNested\B {} function g(int $x) : A { return new A(); } namespace UltraNested { class B {} function noop() : void {} } } } namespace Test2 { function f(int $x) : \Test1\A { return new \Test1\A(); } } namespace Ns { function same_name_different_namespaces(int $x) : int { \Test1\NestedTest\g($x); \Test1\NestedTest\UltraNested\noop(); if ($x < 0) { \Test1\f($x); return $x; } else { \Test2\f($x); return -$x; } } }
PHP
hhvm/hphp/hack/test/integration/data/dependencies/partial.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. function expect_darray(darray $_): void {} function with_omitted_generics(): void { expect_darray(darray['a' => 1, 'b' => 2]); } function respects_newtype_abstraction (Point $p) : void {} function with_default_and_anonymous_variadic(float $x, ?string $y = null, mixed ...$args): void {} function call_with_default_and_anonymous_variadic(string $s): void { with_default_and_anonymous_variadic(3.14); with_default_and_anonymous_variadic(3.14, 'pi'); with_default_and_anonymous_variadic(3.14, '%s', $s); } newtype N as arraykey = int;
PHP
hhvm/hphp/hack/test/integration/data/dependencies/toplevel.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. interface I1 {} class A0 {} class A extends A0 implements I1 {} class B implements I1 {} class C extends A {} class D<Tfirst, Tsecond> extends B {} class E<T> extends D<T, int> {} type Complex = shape('first' => int, 'second' => B); newtype Point = shape('x' => int, 'y' => int); function generic<T>(): int { return 1; } function generic_with_bound<T as arraykey>(T $x): keyset<T> { return keyset[$x]; } function g() : void { $b = new B(); } function shallow_toplevel(C $c): void { g(); } function with_generics<Tfirst, Tsecond>(D<Tfirst, Tsecond> $d, E<Tfirst> $e): int { return generic<C>(); } function with_generics_with_bounds(int $x): keyset<int> { return generic_with_bound($x); } function with_typedefs(Complex $c, shape('x' => int, 'y' => C) $pair) : Point { return shape('x' => $pair['x'], 'y' => $c['first']); } function with_defaults(int $arg = 42, float $argf = 4.2): void { } function call_defaulted(int $arg): void { with_defaults($arg); with_defaults(); } function with_default_and_variadic(mixed $x, ?string $y = null, mixed ...$z): void {} function call_with_default_and_variadic(string $s): void { with_default_and_variadic(42); with_default_and_variadic(42, 'meaning of life'); with_default_and_variadic(42, '%s', $s); } function nonexistent_dependency(BogusType $arg): void {} function builtin_argument_types(Exception $e, keyset<string> $k): void {} function recursive_function(int $n): int { if ($n <= 0) { return 0; } return $n + recursive_function($n - 1); } class WithRecursiveMethods { public function recursive_instance(): void { $this->recursive_instance(); } public static function recursive_static(): void { WithRecursiveMethods::recursive_static(); } } function with_mapped_namespace(): void { PHP\ini_set('foo', 42); } function with_built_in_constant(): int { return PHP_INT_MAX; } function reactive(mixed $x = null): void {} function call_reactive(): void { reactive(); } class Fred {} class Thud { public int $n; public function __construct(Fred $_) { $this->n = 42; } } function with_constructor_dependency(Thud $x): int { return $x->n; } function with_newtype_with_bound(dict<N, mixed> $_): void {} newtype M as N = nothing; function with_newtype_with_newtype_bound(M $_): void {} type UNSAFE_TYPE_HH_FIXME_<T> = T; /* HH_FIXME[4101] */ type UNSAFE_TYPE_HH_FIXME = UNSAFE_TYPE_HH_FIXME_; function with_unsafe_type_hh_fixme(UNSAFE_TYPE_HH_FIXME $x): int { return $x; } type Option<T> = Id<?T>; type Id<T> = T; class WithTypeAliasHint { private Option<int> $x = null; public function getX(): Option<int> { return $this->x; } } type TydefWithFun<T> = ( (function(int, ?T): void), (function(int, float...):void) ); function function_in_typedef<T>(TydefWithFun<T> $y):void {} type TydefWithCapabilities<T> = ( (function(): void), (function()[]: void), (function()[write_props,rx]: void), ); function contexts_in_typedef<T>(TydefWithCapabilities<T> $y):void {} function with_argument_dependent_context_callee( (function()[_]: void) $f, )[write_props, ctx $f]: void { $f(); } function with_argument_dependent_context()[ defaults, zoned]: void { with_argument_dependent_context_callee(()[defaults] ==> { echo "write"; }); } class Contextual { public static function with_argument_dependent_context( (function()[_]: void) $f, )[write_props, ctx $f]: void { $f(); } } class WithContextConstant { const ctx C = [defaults]; public function has_io()[self::C]: void { echo "I have IO!"; } } function with_optional_argument_dependent_context_callee( ?(function()[_]: void) $f1, )[ctx $f1]: void { if ($f1 is nonnull) { $f1(); } } function with_optional_argument_dependent_context(): void { with_optional_argument_dependent_context_callee(null); } function my_keys<Tk as arraykey, Tv>( KeyedTraversable<Tk, Tv> $traversable, )[]: keyset<Tk> { $result = keyset[]; foreach ($traversable as $key => $_) { $result[] = $key; } return $result; } function with_expr_in_user_attrs(): void { $_ = my_keys(vec[]); } <<MyUserAttr(SimpleClass::class)>> type WithClassNameInAttr= int; <<MyUserAttr('blah \' blah blah')>> type WithEscapedCharInAttr= int; <<MyUserAttr('blah')>> type TransparentWithUserAttr = int; <<MyUserAttr('blah')>> newtype OpaqueWithUserAttr = int; <<MyUserAttr('blah')>> enum EnumWithUserAttr: int as int { Blah = 0; } function enum_with_user_attr(EnumWithUserAttr $x): void {} function transparent_with_user_attr(TransparentWithUserAttr $x): void {} function opaque_with_user_attr(OpaqueWithUserAttr $x): void {} function with_escaped_char_in_attr(WithEscapedCharInAttr $_): void {} function with_class_name_in_attr(WithClassNameInAttr $_): void {} <<MyUserAttr('blah')>> class WithUserAttr { public function foo(): void {} } class WithMethodWithUserAttr { <<MyUserAttr('blah')>> public function foo(): void {} } class WithTypeConstantWithUserAttr { <<MyUserAttr('blah')>> const type T = int; public function foo(): self::T { return 1; } } class WithStaticPropWithUserAttr { <<MyUserAttr('blah')>> public static int $i = 0; public function foo(): int { return self::$i; } } class WithPropWithUserAttr { <<MyUserAttr('blah')>> public int $i = 0; public function foo(): int { return $this->i; } } class WithConstrPropWithUserAttr { public function __construct(<<MyUserAttr('blah')>> private int $i){} } function with_constr_prop_with_user_attr():void { $_ = new WithConstrPropWithUserAttr(2); } <<MyUserAttr('blah')>> function with_user_attr(): void {} function with_param_with_user_attr(<<MyUserAttr('blah')>> int $s): void {} function with_tparam_with_user_attr<<<MyUserAttr('blah')>> T>(T $x): void {} final class MyUserAttr implements HH\ClassAttribute, HH\MethodAttribute, HH\TypeAliasAttribute, HH\EnumAttribute, HH\FunctionAttribute, HH\InstancePropertyAttribute, HH\StaticPropertyAttribute, HH\ParameterAttribute, HH\TypeParameterAttribute, HH\TypeConstantAttribute { public function __construct(string $first, string ...$remainder)[] {} } interface IC { public function foo(): void; } class DC implements IC { public function foo(): void {} } class WithWhereConstraint<T> { public function __construct(T $x) where T as IC { $x->foo(); } } function with_where_constraint(): void { $z = new WithWhereConstraint(new DC()); } function with_open_shape(shape(...) $x): void {} function with_tparam_constraint(WithTparamConstraint<IAsConstraint> $_) : void {} function with_prop_in_construct() : void { $x = new WithPropInConstruct(1); }
PHP
hhvm/hphp/hack/test/integration/data/dependencies/xhp.php
<?hh // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. class :xhp implements XHPChild { public function __construct( darray<string, mixed> $attr, varray<mixed> $children, string $file, int $line ) {} public function getAttribute( string $_attribute ): mixed { return null; } } class :foo extends :xhp { attribute int bar @required, num baz @lateinit, string quux = 'mumble'; public function render(): :xhp { return <xhp> bar = {$this->:bar}, baz = {$this->:baz}, quux = {$this->:quux} </xhp>; } } function with_xhp(): :xhp { return <foo bar={42} />; }
PHP
hhvm/hphp/hack/test/integration/data/hierarchy/filter.php
<?hh class CFilter { public function cfilterMethod(): void {} } interface IFilter { public function ifilterMethod(): void; } trait TFilter { public function tfilterMethod(): void {} } class Filter extends CFilter implements IFilter { use TFilter; public function cfilterMethod(): void {} public function ifilterMethod(): void {} public function tfilterMethod(): void {} }
PHP
hhvm/hphp/hack/test/integration/data/holes/call_multiple.php
<?hh function f(int $x, vec<int> $y):void {} function call_multiple(bool $x, vec<bool> $y): void { /* HH_FIXME[4110] */ f($x,$y); /* call_multiple.php:7:5 call_multiple.php:7:8 */ }
PHP
hhvm/hphp/hack/test/integration/data/holes/call_single.php
<?hh function prim(int $i): void {} function call_prim(float $f, ?int $x): void { /* HH_FIXME[4110] */ prim($f); /* call_single.php:7:10 */ /* HH_FIXME[4110] */ prim($x); /* call_single.php:10:10 */ }