language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
PHP
hhvm/hphp/hack/test/hackfmt/tests/inout_params.php
<?hh function noop<T>(inout T $_): void {} function add1(inout int $x): void { $x += 1; } function swap( inout$a, inout mixed$b, ): void { $tmp = $a; $a = $b; $b = $tmp; } function extend<T>(inout vec<T> $dst, Traversable<T> $src): bool { if (!$src) { return false; } foreach ($src as $e) { $dst[] = $e; } return true; } function herp( (function ( inout vec<int> , Container<int> ): mixed) $f, inout vec<int> $dst, ): void { $f(inout $dst, keyset[5]); } function long_function_name_with_lots_of_args($a, string $b, inout$c, inout dict<int,vec<string>> $d, inout bool $e, int ...$f): bool { return true;} function test(): void { $i = 42; $s = 'foo'; $b = true; noop( inout $i); add1(inout $i); swap(inout$i , inout $s, ); swap(inout $i, inout$s); swap(inout $i,inout $s); swap(inout $i, inout $s); $v = vec[]; extend( inout $v, vec[0, 1, 2]); extend( inout $v, dict['spam' => 3, 'eggs' => 4]); herp(fun('extend'), inout $v, ); $d = dict['derp' => dict[6 => vec['burp']]]; $derp = () ==> 'derp'; long_function_name_with_lots_of_args( 42, 'whatever', inout $i,inout $d [ $derp() ], inout $b, $v[0],... $v); }
PHP
hhvm/hphp/hack/test/hackfmt/tests/intersection_types.php
<?hh type Foo = (A & B); type Bar = (A & B & C); type Baz = (A_______________________________________ & B_______________________________________); type Qux = (A_______________________________________ & B_______________________________________ & C_______________________________________);
PHP
hhvm/hphp/hack/test/hackfmt/tests/isset.php
<?hh $foo_is_set = isset($foo); $bar_is_set = isset( $bar ); $long_variable_is_set = isset($long_variable_which_will_bring_this_line_over_80_chars);
PHP
hhvm/hphp/hack/test/hackfmt/tests/is_as_breaking.php
<?hh $xxxxxxxxxxxxxxxxxxxxx = $aaaaaaaaaaaaaaaaaaaaaaaaaaa as Fooooooooooooooooooooooo; $yyyyyyyyyyyyyyyyyyyyy = $bbbbbbbbbbbbbbbbbbbbbbbbbbb is Baaaaaaaaaaaaaaaaaaaaaar; $zzzzzzzzzzzzzzzzzzzzz = $ccccccccccccccccccccccccccc ?as Baaaaaaaaaaaaaaaaaaaaaaz;
PHP
hhvm/hphp/hack/test/hackfmt/tests/lambda_with_typehints.php
<?hh class Foo { public function foo() { if (true) { if (true) { $some_query = $some_query->whereAsync(P::asyncLambda(( SomeEntityType $entity, ) ==> $entity->genIsAvailableInLanguage($language))); } } } }
PHP
hhvm/hphp/hack/test/hackfmt/tests/lateinit_property.php
<?hh class C { <<__LateInit>> private int $a; <<__LateInit>> private int $b; <<__LateInit>> private static int $c; <<__LateInit>> private static int $d; <<__LateInit>> private static dict<A____________,B_____________> $e___________; <<__LateInit>> private static dict<A________________________,B___________________> $f______________; <<__LateInit, __OtherAttribute, __AnotherAttribute>> private int $g; <<__LateInit, __OtherAttribute, __AnotherAttribute, __AFurtherAttribute>> private int $h; <<__LateInit, __OtherAttribute, __AnotherAttribute, __AFurtherAttribute>> private static dict<A____________,B_____________> $i___________; <<__LateInit, __OtherAttribute, __AnotherAttribute, __AFurtherAttribute>> private static dict<A________________________,B___________________> $j______________; <<__LateInit, __OtherAttribute, __AnotherAttribute, __AFurtherAttribute, __OneMoreAttribute>> private int $k; }
PHP
hhvm/hphp/hack/test/hackfmt/tests/lazy_rule_with_trivia.php
<?hh function lazy_rule_with_trivia(): void { // Sample comment $index_to_vec >= count($vector) ? $vector[] = $element : $vector[$index_to_vec] = $element; }
PHP
hhvm/hphp/hack/test/hackfmt/tests/line_width_30.php
<?hh // strict class Point { private $x; // Cartesian x-coordinate private $y; // Cartesian y-coordinate public function __construct($x = 0, $y = 0) { $this->x = $x; $this->y = $y; } public function move($x, $y) { $this->x = $x; $this->y = $y; } public function translate($x, $y) { $this->x += $x; $this->y += $y; } public function magnitude() { return sqrt($this->x ** 2 + $this->y ** 2); } public function __toString() { return '(' . $this->x . ',' . $this->y . ')'; } }
PHP
hhvm/hphp/hack/test/hackfmt/tests/lint_ignores_suppress_breaking_next_line.php
<?hh /* @lint-ignore */ class HasFixme { public function why() { // Here is a motivating example for the fixmes-suppress-formatting feature. // We do not want to format this node because it would move the suppression // comment away from the error, causing it to fail to suppress the error: /* @lint-ignore */ f($some_type_error_we_would_like_to_suppress, $xxxxxxxxxx, $yyyyyyyyyy, $zzzzzzzzzz); } public function cases() { // The FIXME on the class definition only suppresses formatting for the // first line (containing the tokens "class" "HasFixme" "{"). Statements // inside the class, like this one, are still formatted normally. $this_is + $formatted; /* @lint-ignore */ func($not_formatted, $formatted, $formatted); /* @lint-ignore */ func($not_formatted, $formatted); /* @lint-ignore */ func($not_formatted, $not_formatted, $formatted, $formatted); /* @lint-ignore */// not formatted /* @lint-ignore */ // not formatted /* @lint-ignore */ func($not_formatted, $not_formatted, $formatted, $formatted); /* @lint-ignore */ f($some_type_error_we_would_like_to_suppress, $xxxxxxxxxx, $yyyyyyyyyy, $zzzzzzzzzz) + $this_part_of_the_expression + $is_still_formatted; /* @lint-ignore */ expect(PHPism_FIXME::varrayFuzzyEqualsDarray($config['foo'], varray[ 'apples', 'oranges', 'kiwis', 'pears', ]))->toBeTrue(); } }
PHP
hhvm/hphp/hack/test/hackfmt/tests/long_generic_class.php
<?hh final class Ccccccccccccccccccccccccccccc<Taaaaaaaa as Ibbbbbbbbbbbbbbbbbbbbb, Tccccccccccccccccccc, Tdddddddddd as arraykey> implements Igggggggggggggggggggggggggggggggggggggg<Tccccccccccccccccccc, Eeeeeeeeeeee<Tdddddddddd, bool>, Ffffffffffffff<Taaaaaaaa>> { }
PHP
hhvm/hphp/hack/test/hackfmt/tests/long_single_trait_use.php
<?hh class C { // Don't break between keyword and single trait name, even though it would // bring this line under the length limit use TraitXxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; // Do break when multiple names are listed use TraitXxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, Y; }
PHP
hhvm/hphp/hack/test/hackfmt/tests/long_where_clauses.php
<?hh class C { public static function f___________________< Tx as A, Ty as B, Tz as C, >( Ty $y, Tz $z, ): void where Tx::Tt = Ty, Tx::Tu = Tz, Tx::Tv as D, Tx::Tw as E, { do_something($y, $z); } public static function g___________________< <<__Enforceable>> reify Tx as A___________________, Ty as B___________________, Tz as C___________________, >( Ty $y, Tz $z, ): void where Tx::Tt = Ty, Tx::Tu = Tz, Tx::Tv as D____________________, Tx::Tw as E_________________________, { do_something_else($y, $z); } public static function h___________________< <<__Enforceable>> reify Tx as A___________________, Ty__________________ as B___________________, Tz__________________ as C___________________, >( Ty__________________ $y, Tz__________________ $z, A___________________ $a, B___________________ $b, ): ( A___________________, B___________________, B___________________, C___________________, ) where Tx::Tt = Ty__________________, Tx::Tu = Tz__________________, Tx::Tv as D____________________, Tx::Tw as E_________________________, { return tuple($a, $b, $y, $z); } }
PHP
hhvm/hphp/hack/test/hackfmt/tests/match_statement.php
<?hh function print_json(json $json) { match ($json) { _: null => { print('null'); } _: bool => { print($json ? 'true' : 'false'); } _: string => { print($json); } _: num => { print((string)$json); } _: vec<_> => { print('array'); } _: dict<_, _> => { print('object'); } } } function patterns(mixed $x) { match ($x) { $variable_pattern => {} $variable_pattern_______________________________________________________ => {} _: A => {} _: A\B => {} _: \A\B => {} _: \A\B<C________________________________________________________> => {} $_: A => {} $_: A\B => {} $_: \A\B => {} $_: \A\B<C________________________________________________________> => {} $a: A => {} $b: A\B => {} $b: \A\B => {} $abc____________________________________________________: \A\B<C________________________________________________________> => {} None => {} Some($x) => {} _ => {} _named_wildcard => {} } }
PHP
hhvm/hphp/hack/test/hackfmt/tests/member_and_function_call_chaining.php
<?hh // strict function member_and_function_call_chain(MyObject $my_object): void { $my_object ->getASubObjectFromMyObject() ->getSomeOtherObject() ->directObject ?->field ->subField ?->method(); $my_object ?->getASubObjectFromMyObject ->getSomeOtherObject() ->directObject ?->field ->subField ->method(); $my_object ?->getASubObjectFromMyObject() ->getSomeOtherObject() ->directObject ?->field ->subField; $my_object ?->getASubObjectFromMyObject ->getSomeOtherObject() ->directObject ?->field; }
PHP
hhvm/hphp/hack/test/hackfmt/tests/multiline_strings.php
<?hh $foo = 'bar baz'.' qux'; $sql = 'SELECT * FROM table WHERE foo > bar ORDER BY bar DESC'; execute('SELECT * FROM table WHERE foo > bar ORDER BY bar DESC' ); execute( 'SELECT * FROM table WHERE foo > bar ORDER BY bar DESC', $connection_pool, );
PHP
hhvm/hphp/hack/test/hackfmt/tests/multiline_ternary.php
<?hh // strict $a = ($very_very_very_very_very_very_very_long_multilined_parenthesized_expression) ? $if_true : $if_false;
PHP
hhvm/hphp/hack/test/hackfmt/tests/multiline_xhp_string_v1.php
<?hh function foobar(): void { { $body = <fbt desc="A literal which is too long to fit on a single line, so the author added a line break in the middle of it."> </fbt>; } }
PHP
hhvm/hphp/hack/test/hackfmt/tests/multiline_xhp_string_v2.php
<?hh function foobar(): void { { $body = <fbt desc="A literal which is too long to fit on a single line, so the author added a line break in the middle of it."> </fbt>; } }
PHP
hhvm/hphp/hack/test/hackfmt/tests/namespaces_bracketed.php
<?hh namespace NS1 { const c = 0; function f(): void { } class C { } interface I { } trait T { } } namespace NS2 { use \NS1\C, \NS1\I, \NS1\T; class D extends C implements I { use T; } \NS1\f(); use \NS1\C as C2; $c2 = new C2; } namespace { use \NS1\{C, I, T}; use function \NS1\f; use const \NS1\c; } namespace { use function \NS1\{f}; use const \NS1\{c}; }
PHP
hhvm/hphp/hack/test/hackfmt/tests/namespaces_unbracketed.php
<?hh namespace foo; use \Things\{AbstractBeanFactoryFactoryController, InternXControllerManager, OtherContrivedNamespace}; use \Things\AbstractBeanFactoryFactoryController, \Things\InternXControllerManager, \Things\OtherContrivedNamespace;
PHP
hhvm/hphp/hack/test/hackfmt/tests/namespace_use_kind.php
<?hh //strict namespace X { use Foo\Bar\Baz\{CL, function f1, const CN, CL2}; function f(): void { } }
PHP
hhvm/hphp/hack/test/hackfmt/tests/non_parental_argish_lists.php
<?hh f(vec[ $foo, // single-line comment forces the vec's rule to split, but not f's $bar, ]); Vec\map($foo, $x ==> { bar($x); baz($x); }); const dict<string, shape( 'fooooooo' => string, 'baaaaaar' => string, 'baaaaaaz' => string, 'quuuuuux' => string, )> X = dict[];
PHP
hhvm/hphp/hack/test/hackfmt/tests/non_parental_chaining.php
<?hh $foo->property->otherProperty->method( $a_____________________, $b_____________________, $c_____________________, ); $foo->property->method()->otherMethod( $a_____________________, $b_____________________, $c_____________________, ); // This example is not preserved because we can fit the otherMethod call on one // line. That solution is considered more desirable because of the cost of the // Span wrapping otherMethod's argument list. $foo->property->method()->otherMethod( $a_____________________, $b_____________________, );
PHP
hhvm/hphp/hack/test/hackfmt/tests/non_parental_type_specifiers.php
<?hh const array<shape( 'fooooooo' => string, 'baaaaaar' => string, 'baaaaaaz' => string, 'quuuuuux' => string, )> A = varray[]; const array<string, shape( 'fooooooo' => string, 'baaaaaar' => string, 'baaaaaaz' => string, 'quuuuuux' => string, )> B = darray[]; const vec<shape( 'fooooooo' => string, 'baaaaaar' => string, 'baaaaaaz' => string, 'quuuuuux' => string, )> C = vec[]; const dict<string, shape( 'fooooooo' => string, 'baaaaaar' => string, 'baaaaaaz' => string, 'quuuuuux' => string, )> D = dict[]; const Foo<shape( 'fooooooo' => string, 'baaaaaar' => string, 'baaaaaaz' => string, 'quuuuuux' => string, )> E = new Foo(); const Foo<string, shape( 'fooooooo' => string, 'baaaaaar' => string, 'baaaaaaz' => string, 'quuuuuux' => string, )> F = new Foo(); const Foo<string, int, shape( 'fooooooo' => string, 'baaaaaar' => string, 'baaaaaaz' => string, 'quuuuuux' => string, )> G = new Foo(); // This example is not preserved, since Bar<string> contains internal splits. const Foo<string, int, Bar<string>, shape( 'fooooooo' => string, 'baaaaaar' => string, 'baaaaaaz' => string, 'quuuuuux' => string, )> H = new Foo();
PHP
hhvm/hphp/hack/test/hackfmt/tests/partially_generated.php
<?hh // strict // @partially-generated class Foo { function a () : int { return 0; } /* BEGIN MANUAL SECTION */ function b () : int { return 0; } function c () : int { return 0; } /* END MANUAL SECTION */ function d () : int { return 0; } /* BEGIN MANUAL SECTION */ function e () : int { /* HH_FIXME[4110] */ return vec[ 1 , 2 , 3 ]; } /* END MANUAL SECTION */ }
PHP
hhvm/hphp/hack/test/hackfmt/tests/partially_generated_empty_section.php
<?hh // strict // @partially-generated class Foo { function a () : int { return 0; } /* BEGIN MANUAL SECTION */ /* END MANUAL SECTION */ function b () : int { return 0; } /* BEGIN MANUAL SECTION */ function c () : int { /* HH_FIXME[4110] */ return vec[ 1 , 2 , 3 ]; } /* END MANUAL SECTION */ }
PHP
hhvm/hphp/hack/test/hackfmt/tests/partially_generated_force_formatting.php
<?hh // strict // @partially-generated class Foo { function a () : int { return 0; } /* BEGIN MANUAL SECTION */ function b () : int { return 0; } function c () : int { return 0; } /* END MANUAL SECTION */ function d () : int { return 0; } /* BEGIN MANUAL SECTION */ function e () : int { /* HH_FIXME[4110] */ return vec[ 1 , 2 , 3 ]; } /* END MANUAL SECTION */ }
PHP
hhvm/hphp/hack/test/hackfmt/tests/partially_generated_indentation.php
<?hh // strict // @partially-generated // The BEGIN and END comments are not included in the range to be formatted, so // their indentation is not corrected. class Foo { function a () : int { return 0; } /* BEGIN MANUAL SECTION */ function b () : int { return 0; } /* END MANUAL SECTION */ function c () : int { return 0; } }
PHP
hhvm/hphp/hack/test/hackfmt/tests/partially_generated_multiple_ends.php
<?hh // strict // @partially-generated // Only Foo::b and Foo::e are formatted--when we have multiple END tags in a // row, we consider only the first. class Foo { function a () : int { return 0; } // not formatted /* BEGIN MANUAL SECTION */ function b () : int { return 0; } /* END MANUAL SECTION */ function c () : int { return 0; } // not formatted /* END MANUAL SECTION */ function d () : int { return 0; } // not formatted /* BEGIN MANUAL SECTION */ function e () : int { return 0; } /* END MANUAL SECTION */ function f () : int { return 0; } // not formatted }
PHP
hhvm/hphp/hack/test/hackfmt/tests/partially_generated_no_manual_sections.php
<?hh // @partially-generated class Whatever { public function foo(): int { return 42; } }
PHP
hhvm/hphp/hack/test/hackfmt/tests/partially_generated_no_tag.php
<?hh // strict // This entire file is formatted because it does not contain the // "partially-generated" tag. class Foo { function a () : int { return 0; } /* BEGIN MANUAL SECTION */ function b () : int { return 0; } function c () : int { return 0; } /* END MANUAL SECTION */ function d () : int { return 0; } /* BEGIN MANUAL SECTION */ function e () : int { /* HH_FIXME[4110] */ return vec[ 1 , 2 , 3 ]; } /* END MANUAL SECTION */ }
PHP
hhvm/hphp/hack/test/hackfmt/tests/partially_generated_only_empty_sections.php
<?hh // strict // @partially-generated class Foo { function a () : int { return 0; } /* BEGIN MANUAL SECTION */ /* END MANUAL SECTION */ function b () : int { return 0; } /* BEGIN MANUAL SECTION */ /* END MANUAL SECTION */ function c () : int { return 0; } }
PHP
hhvm/hphp/hack/test/hackfmt/tests/partially_generated_unclosed_begin.php
<?hh // strict // @partially-generated // Only Foo::c and Foo::e are formatted--when we have multiple BEGIN tags in a // row, we consider only the last. class Foo { function a () : int { return 0; } // not formatted /* BEGIN MANUAL SECTION */ function b () : int { return 0; } // not formatted /* BEGIN MANUAL SECTION */ function c () : int { return 0; } /* END MANUAL SECTION */ function d () : int { return 0; } // not formatted /* BEGIN MANUAL SECTION */ function e () : int { return 0; } /* END MANUAL SECTION */ function f () : int { return 0; } // not formatted }
PHP
hhvm/hphp/hack/test/hackfmt/tests/partially_generated_unpaired_begin.php
<?hh // strict // @partially-generated // An unpaired BEGIN is ignored. class Foo { function a () : int { return 0; } // not formatted /* BEGIN MANUAL SECTION */ function b () : int { return 0; } /* END MANUAL SECTION */ function c () : int { return 0; } // not formatted /* BEGIN MANUAL SECTION */ function d () : int { return 0; } // not formatted }
PHP
hhvm/hphp/hack/test/hackfmt/tests/partially_generated_unpaired_end.php
<?hh // strict // @partially-generated // An unpaired END is ignored. class Foo { function a () : int { return 0; } // not formatted /* END MANUAL SECTION */ function b () : int { return 0; } // not formatted /* BEGIN MANUAL SECTION */ function c () : int { return 0; } /* END MANUAL SECTION */ function d () : int { return 0; } // not formatted }
PHP
hhvm/hphp/hack/test/hackfmt/tests/pipe_in_arguments.php
<?hh // strict f( $aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa |> nullthrows($$), $bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb |> nullthrows($$), );
PHP
hhvm/hphp/hack/test/hackfmt/tests/pipe_operator.php
<?hh f() |> g($$) |> h($$); f() |> g($$) |> h($$); f() |> g($$) |> h($$); f() |> g($$) |> h($$); f() |> g($$) |> h($$);
PHP
hhvm/hphp/hack/test/hackfmt/tests/pipe_operator_breaking.php
<?hh class Foo { function getPipedThing($thing): int { return $thing |> self::doSomething($$) |> BarManager::manageBarsAndBarlikes($$, $bar_comparator->getBarAttributes()) |> self::finalizeBars($$); } }
PHP
hhvm/hphp/hack/test/hackfmt/tests/pipe_operator_nested_call.php
<?hh function piped(): int { $a = Foo::aaaaaaaaaaaaaaaaaaaaa() |> bar(Bar::bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb()->g($$)) |> h($$); }
PHP
hhvm/hphp/hack/test/hackfmt/tests/pipe_operator_nested_call2.php
<?hh function piped(): int { $a = Foo::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() ->h(f() |> g($$) |> h($$)); }
PHP
hhvm/hphp/hack/test/hackfmt/tests/prefixed_string.php
<?hh function f() : void { $x = "It"; $y = "best"; $z = f"{$x} was the {$y} of times"; $w = re"blah blah"; }
PHP
hhvm/hphp/hack/test/hackfmt/tests/readonly.php
<?hh class Foo { } // Can technically use this function to readonlyfy things function ro<T>(T $x) : readonly T { return $x; } async function returns_readonly() : readonly Awaitable<Foo> { return new Foo(); } async function returns_normal(): Awaitable<Foo> { return new Foo(); } async function expressions(readonly Foo $x) : readonly Awaitable<Foo> { // lambda $f = (readonly Foo $y) : readonly Foo ==> { return $y;}; // function $z = function(readonly Foo $f) : readonly Foo { return $f; }; $r = readonly new Foo(); $w = $z(readonly $r); $readonly_first = readonly await returns_normal(); $await_readonly = await readonly returns_readonly(); // This should parse, but won't typecheck and will fail at runtime // because returns_readonly returns a readonly value, it must be explicitly // cast to readonly $readonly_first_readonly = readonly await returns_readonly(); // like below // note that the first readonly is redundant, just testing parsing. $correct = readonly await readonly returns_readonly(); return $x; } function closure_type_spec( (readonly function(readonly Foo, readonly Bar) : readonly Foo) $f ) : readonly (function(): void) { } class Bar { public readonly Foo $x; public function __construct( public readonly Foo $y, ) { $this->x = new Foo(); } public readonly function getFoo() : void { $f = /* <<readonly>> */ (Foo $y) ==> {return $y;}; // TODO: readonly annotation on anonymous function $z = readonly function(Foo $f) : void { }; } }
PHP
hhvm/hphp/hack/test/hackfmt/tests/require_implements.php
<?hh trait C { require implements Aaaaaaaaaaaaaaaaaaaaaaaaaaa<Bbbbbbbbbbbbbbb, Cccccccccccccc>; require implements Aaaaaaaaaaaaaaaaaaaaaaaaaaa<Bbbbbbbbbbbbbbbbbbbbbbb, Ccccccccccccccccccccccc>; require implements Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<Bbbbbbbbbbbbbbbbbbbbbbb, Ccccccccccccccccccccccc>; require implements ShortNameWithNoSplits; require implements LongNameWithNoSplits________________________________________; require implements VeryLongNameWithNoSplits_____________________________________________________; }
PHP
hhvm/hphp/hack/test/hackfmt/tests/runs_out_of_retries_in_line_splitter.php
<?hh class Foo { public static function foo() { return $doughnutFryer ->start() ->then($_ ==> $frosting_glazer->start()) ->then($_ ==> Future::wait(varray[ $conveyor_belts->start(), $sprinkle_sprinkler->start(), $sauce_dripper->start(), ])) ->catchError($cannot_get_conveyor_belt_running) ->then($_ ==> $tell_everyone_donuts_are_just_about_done()) ->then($_ ==> Future::wait(varray[ $croissant_factory->start(), $giant_baking_ovens->start(), $butter_butterer->start(), ]) ->catchError($handle_baking_failures) ->timeout($script_load_timeout, $handle_baking_failures) ->catchError($cannot_get_conveyor_belt_running)) ->catchError($cannot_get_conveyor_belt_running) ->restart() ->then($_ ==> $frosting_glazer->start()) ->then($_ ==> Future::wait(varray[ $conveyor_belts->start(), $sprinkle_sprinkler->start(), $sauce_dripper->start(), ])) ->catchError($cannot_get_conveyor_belt_running) ->then($_ ==> $tell_everyone_donuts_are_just_about_done()) ->then($_ ==> Future::wait(varray[ $croissant_factory->start(), $giant_baking_ovens->start(), $butter_butterer->start(), ]) ->catchError($handle_baking_failures) ->timeout($script_load_timeout, $handle_baking_failures) ->catchError($cannot_get_conveyor_belt_running)) ->catchError($cannot_get_conveyor_belt_running) ->restart() ->then($_ ==> $frosting_glazer->start()) ->then($_ ==> Future::wait(varray[ $conveyor_belts->start(), $sprinkle_sprinkler->start(), $sauce_dripper->start(), ])) ->catchError($cannot_get_conveyor_belt_running) ->then($_ ==> $tell_everyone_donuts_are_just_about_done()) ->then($_ ==> Future::wait(varray[ $croissant_factory->start(), $giant_baking_ovens->start(), $butter_butterer->start(), ]) ->catchError($handle_baking_failures) ->timeout($script_load_timeout, $handle_baking_failures) ->catchError($cannot_get_conveyor_belt_running)) ->catchError($cannot_get_conveyor_belt_running) ->then($_ ==> $tell_everyone_donuts_are_just_about_done()) ->then($_ ==> Future::wait(varray[ $croissant_factory->start(), $giant_baking_ovens->start(), $butter_butterer->start(), ]) ->catchError($handle_baking_failures) ->timeout($script_load_timeout, $handle_baking_failures) ->catchError($cannot_get_conveyor_belt_running)) ->catchError($cannot_get_conveyor_belt_running) ->restart() ->then($_ ==> $frosting_glazer->start()) ->then($_ ==> Future::wait(varray[ $conveyor_belts->start(), $sprinkle_sprinkler->start(), $sauce_dripper->start(), ])) ->catchError($cannot_get_conveyor_belt_running) ->then($_ ==> $tell_everyone_donuts_are_just_about_done()) ->then($_ ==> Future::wait(varray[ $croissant_factory->start(), $giant_baking_ovens->start(), $butter_butterer->start(), ]) ->catchError($handle_baking_failures) ->timeout($script_load_timeout, $handle_baking_failures) ->catchError($cannot_get_conveyor_belt_running)) ->catchError($cannot_get_conveyor_belt_running) ->then($_ ==> { Logger::info("Let's eat!"); }); } }
PHP
hhvm/hphp/hack/test/hackfmt/tests/shape_structural_subtyping_with_optional_and_non_optional_types.php
<?hh // strict // Only the unprovided 'b' should produce an error. // The unprovided 'a' should not produce an error. type ShapeWithOptionalAndNonOptionalFields = shape( ?'a' => int, 'b' => int, ); function foo(ShapeWithOptionalAndNonOptionalFields $argument): void {} function bar(): void { foo(shape()); }
PHP
hhvm/hphp/hack/test/hackfmt/tests/shape_structural_subtyping_with_optional_type.php
<?hh // strict // Neither the unprovided 'a' nor the unprovided 'b' should produce errors. type ShapeWithOptionalField = shape( ?'a' => int, ?'b' => int, ); function foo(ShapeWithOptionalField $argument): void {} function bar(): void { foo(shape()); }
PHP
hhvm/hphp/hack/test/hackfmt/tests/shape_structural_subtyping_with_optional_type_and_extra_types.php
<?hh // strict // The unprovided 'a' should not produce errors. // The provided 'b' should not produce errors. // The extra 'c' should not produce errors. type ShapeWithOptionalField = shape( ?'a' => int, ?'b' => int, ); function foo(ShapeWithOptionalField $argument): void {} function bar(): void { foo( shape( 'a' => 42, 'c' => "Hello" ) ); }
PHP
hhvm/hphp/hack/test/hackfmt/tests/shape_typedef_with_many_known_and_unknown_fields.php
<?hh // strict type ShapeWithKnownAndUnknownFields = shape( 'field1' => int, 'field2' => int, 'field3' => int, 'field4' => int, 'field5' => int, 'field6' => int, 'field7' => int, ...);
PHP
hhvm/hphp/hack/test/hackfmt/tests/shape_typedef_with_many_optional_fields.php
<?hh // strict type ShapeWithOptionalField = shape( ?'1' => int, ?'2' => int, ?'3' => int, ?'4' => int, ?'5' => int, ?'6' => int, ?'7' => int, ?'8' => int, ?'9' => int, ?'10' => int, ?'11' => int, ?'12' => int, );
PHP
hhvm/hphp/hack/test/hackfmt/tests/single_argument_whitespace.php
<?hh // Single arguments with surrounding whitespace, which end up with line breaks // in the formatted output, are formatted with line breaks between the argument // and the function call parentheses: foo( vec['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut'] ); // This is true even when the argument is not surrounded by line breaks in the // original source: foo( vec['Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana']); // However, single arguments with no surrounding whitespace will stay joined // with the function call parens, when possible, even when they are formatted // with internal line breaks: foo(vec['Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts']); // Here, that isn't possible, since it would result in overflow: veryLongFunctionNameWhichCannotFitOnTheSameLineAs(thisOtherFunctionWithAVeryLongName('Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada')); // Lambda expressions can be formatted this way too: forAllStates($state ==> { visitState($state); }); // But only when the body is a CompoundStatement: forAllStates($long_name_state_variable ==> visitFunctionWithLongName($long_name_state_variable)); // We always break around some constructs: foo($predicate_with_a_very_long_identifier && $other_predicate_with_a_long_identifier); foo($nullable_value_with_a_long_identifier ?? $some_result_with_a_very_long_name); foo($nullable_value_with_a_long_identifier ?? $some_result_with_a_very_long_identifier); foo($predicate_with_a_very_long_identifier ? $some_result_with_long_name : $other_result); dict['dictKeyWithAnExtraordinarilyLongLength' => 'dictValueWhichIsAlsoQuiteLong']; shape('shapeKeyWithAnExtraordinarilyLongLength' => 'shapeValueWhichIsAlsoQuiteLengthy'); type MyShape = shape('shapeTypeSpecifierKeyWithAnExtraordinarilyLongLength' => TypeWhichIsAlsoQuiteLengthy); $my_query = GitHubRepositoryEntity::queryAll($this->context->obtainContextObject()) ->orderBy( GitHubRepositoryEntitySpec::isDeleted(), Ordering::desc(GitHubRepositoryEntitySpec::isManaged()), );
PHP
hhvm/hphp/hack/test/hackfmt/tests/split_after_assignment_operator.php
<?hh function f(): void { $very_long_variable_name_bringing_this_line_over_80_chars = nullthrows($nullable); }
PHP
hhvm/hphp/hack/test/hackfmt/tests/split_after_assignment_operator_v0.php
<?hh function f(): void { $very_long_variable_name_bringing_this_line_over_80_chars = nullthrows($nullable); }
PHP
hhvm/hphp/hack/test/hackfmt/tests/split_after_assignment_operator_v1.php
<?hh function f(): void { $very_long_variable_name_bringing_this_line_over_80_chars = nullthrows($nullable); }
PHP
hhvm/hphp/hack/test/hackfmt/tests/static_initialization.php
<?hh class Tiger { private static vec<string> $tiger; private static vec<string> $symmetry = vec[ 'Tiger, tiger, burning bright', 'In the forests of the night', 'What immortal hand or eye', 'Could frame thy fearful symmetry?', ]; private static vec<string> $fire = vec[ 'In what distant deeps or skies', 'Burnt the fire of thine eyes?', 'On what wings dare he aspire?', 'What the hand dare seize the fire?', ], $heart = vec[ 'And what shoulder and what art', 'Could twist the sinews of thy heart?', 'And when thy heart began to beat,', 'What dread hand and what dread feet?', ]; }
PHP
hhvm/hphp/hack/test/hackfmt/tests/string_literal_embedded_expressions.php
<?hh $sql = "DELETE FROM `foo` WHERE `left` BETWEEN {$res->left} AND {$res->right} ORDER BY `level` DESC"; $str = "embedded: {$a_long_object_name->a_long_property_name->an_array_property_name[0]} <- braced expression"; $str = "embedded: {$a_long_array_name[$some_object is SomeClass ? 0 : 1]} <- braced subscript expression"; $str = "string with $foobararray[$looooooooooooooooooooooooooooooooooooooooooooooooong_index] won't break"; $str = "string with $my_object->looooooooooooooooooooooooooooooooooooooooooooooooong_property won't break either";
PHP
hhvm/hphp/hack/test/hackfmt/tests/switch_case_block.php
<?hh switch ($str) { case 'foo': { logFooEvent(); break; } case 'bar': { $eventDetails = shape('message' => 'bar'); logBarEvent($eventDetails); } logSomethingElse(); break; default: { logOtherEvent(); break; } }
PHP
hhvm/hphp/hack/test/hackfmt/tests/switch_statement.php
<?hh switch ($foo->color) { case FooColor::RED: handleRedFoo($foo); break; case FooColor::GREEN: case FooColor::BLUE: handleGreenOrBlueFoo($foo); break; case FooColor::ORANGE: logOrangeFooEvent($foo); // FALLTHROUGH case FooColor::YELLOW: handleYellowishFoo($foo); break; default: handleOtherFoo($foo); }
PHP
hhvm/hphp/hack/test/hackfmt/tests/switch_statement_comments.php
<?hh switch ($foo->color) { // Red foos handled here case FooColor::RED: // Red foos are best foos handleRedFoo($foo); break; // Green and blue foos are good too case FooColor::GREEN: case FooColor::BLUE: handleGreenOrBlueFoo($foo); break; // no fallthrough case FooColor::ORANGE: logOrangeFooEvent($foo); // We fall through here to also handle this as a yellowish foo. // FALLTHROUGH /* Yellow and yellowish foos handled here */ case FooColor::YELLOW: handleYellowishFoo($foo); break; default: handleOtherFoo($foo); }
PHP
hhvm/hphp/hack/test/hackfmt/tests/switch_statement_in_broken_parent_rule.php
<?hh doThing( $foo ==> { switch ($foo->color) { case FooType::RED: handleRedFoo($foo); break; case FooType::GREEN: case FooType::BLUE: case FooType::VERY_LONG_COLOR_NAME_WHICH_WILL_CAUSE_A_LINE_BREAK_WITHIN_THIS_LABEL: handleNonRedFoo($foo); break; } } );
PHP
hhvm/hphp/hack/test/hackfmt/tests/tparam_with_tparams.php
<?hh function test<Ta, Tb, Tc<Td, Te>>() {} class MyClass<Ta, Tb, Tc<Td as MyClass<Td>, Te> as OthererClassWithVeryLongNameLetsCauseALineBreak<Td>> {} class MyClass2<Ta, Tb<Td as OthererClassWithVeryLongNameLetsCauseALineBreak<Td>, Tf as YetAnothererClassWithVeryLongNameLetsCauseALineBreak>, Tc<Tg as MyClass<Tg>, Te>> {}
PHP
hhvm/hphp/hack/test/hackfmt/tests/trailing_comma_comment.php
<?hh function foo() { return varray[ // array begin: varray[ $long_identifier_one, $long_identifier_two, $long_identifier_three, $long_identifier_four, ] // array end , // comma ]; } function foo() { return varray[ // array begin: varray[ $long_identifier_one, $long_identifier_two, $long_identifier_three, $long_identifier_four, ] // array end // no comma ]; } function foo() { return varray[ /* array begin: */ varray[ $long_identifier_one, $long_identifier_two, $long_identifier_three, $long_identifier_four, ] /* array end */ , /* comma */ ]; }
PHP
hhvm/hphp/hack/test/hackfmt/tests/trailing_line_comments.php
<?hh if ( $predicate // pred 1 || $other_predicate // pred 2 ) { // ... } if ( $first_predicate // 1 || $second_predicate // 2 || $third_predicate // 3 || $fourth_predicate // 4 ) { // ... } if ( $predicate || // pred 1 $other_predicate // pred 2 ) { // ... } if ( $first_predicate || // 1 $second_predicate || // 2 $third_predicate || // 3 $fourth_predicate // 4 ) { // ... } if ( $first_predicate || // UNSAFE $second_predicate // FALLTHROUGH ) { // ... } $sum = $num1 // num1 + $num2; // num2 $sum = $number_with_long_identifier1 // num1 + $number_with_long_identifier2 // num2 + $number_with_long_identifier3; // num3 $sum = $num1 + // num1 $num2; // num2 $sum = $number_with_long_identifier1 + // num1 $number_with_long_identifier2 + // num2 $number_with_long_identifier3; // num3 function_call( $num1 // num1 + $num2, // num2 ); function_call( $number_with_long_identifier1 // num1 + $number_with_long_identifier2 // num2 + $number_with_long_identifier3, // num3 ); function_call( $num1 + // num1 $num2, // num2 ); function_call( $number_with_long_identifier1 + // num1 $number_with_long_identifier2 + // num2 $number_with_long_identifier3, // num3 ); function_call( $num // num ); function_call( $num1, // num1 $num2 // num2 ); function_call( $number_with_incredibly_unbelievably_surprisingly_long_identifier // long! ); function_call( $number_with_long_identifier1, // num1 $number_with_long_identifier2, // num2 $number_with_long_identifier3 // num3 ); function_call ( $num // num ); function_call ( $num1 // num1 , $num2 // num2 ); function_call ( $number_with_incredibly_unbelievably_surprisingly_long_identifier // long! ); function_call ( $number_with_long_identifier1 // num1 , $number_with_long_identifier2 // num2 , $number_with_long_identifier3 // num3 ); $arr[ "idx" // some idx ] = $val; function f( int $a, // arg1 ) { // ... } function f( int $a // arg1 ) { // ... } function f( int $a, // arg1 int $b, // arg2 ) { // ... } function f( int $a, // arg1 int $b // arg2 ) { // ... } function f ( int $a // arg1 ) { // ... } function f ( int $a // arg1 , int $b // arg2 ) { // ... } function getArray( ): array< string, // strings string // strings > { return darray["foo" => "bar"]; } function getArray( ): array< string // strings , string // strings > { return darray["foo" => "bar"]; } function getDict( ): dict< string, // strings string // strings > { return dict["foo" => "bar"]; } function getDict( ): dict< string // strings , string // strings > { return dict["foo" => "bar"]; } function swap< T, // T U // U >( Vector<T> $a, // T Vector<U> $b // U ): Pair< Vector<U>, // U Vector<T> // T > { return Pair { $b, $a }; } function swap < T // T , U // U >( Vector<T> $a // T , Vector<U> $b // U ): Pair< Vector<U> // U , Vector<T> // T > { return Pair { $b, $a }; }
PHP
hhvm/hphp/hack/test/hackfmt/tests/try_catch_clause_overflow.php
<?hh try { foo(); } catch (LongishExceptionType $exception_with_very_long_name_causing_line_breaks) { handleLongishExceptionType($exception_with_very_long_name_causing_line_breaks); } catch (EvenMoreWordilyNamedExceptionType $exception_with_very_long_name_causing_line_breaks) { handleEvenMoreWordilyNamedExceptionType($exception_with_very_long_name_causing_line_breaks); }
PHP
hhvm/hphp/hack/test/hackfmt/tests/try_catch_in_broken_parent_rule.php
<?hh doThing( $_ ==> { try { foo(); } catch (Exception $e) { handleException($e); } }, $some_other_argument, $some_third_argument, );
PHP
hhvm/hphp/hack/test/hackfmt/tests/type-refinements_eq-bounds-non-nested.php
<?hh <<file:__EnableUnstableFeatures('type_const_multiple_bounds')>> interface AVeryLongInterfaceNameThatBarelyFitsIn1Line { abstract const type T; abstract const type TVeryLongTypeConstName; } interface AnInterfaceWithNotSoLengthyName extends AVeryLongInterfaceNameThatBarelyFitsIn1Line { abstract const type TMediumLength; abstract const type TVeryLongTypeConstNameShouldGoOnASeparateLine; } interface AnInterface {} interface Box { abstract const type T; } function param_fits_in_1line(Box with { type T = int } $_): void {} function param_barely_fits_in_1line(Box with { type T = AnInterface } $_): void {} function param_cannot_fit_in_1line( AVeryLongInterfaceNameThatBarelyFitsIn1Line with { type T = AVeryLongInterfaceNameThatBarelyFitsIn1Line } $_, ): void {} function param_refinement_member_split( AnInterfaceWithNotSoLengthyName with { type TVeryLongTypeConstNameShouldGoOnASeparateLine = AVeryLongInterfaceNameThatBarelyFitsIn1Line } $_, ): void {} function param_split_between_members( SomeInterface with { type T1 = int; type T2 = string; type T3 = float; } $_, ): void {} function generic_fits_in_1line< TInner as shape(...), TInterface as AnInterfaceWithNotSoLengthyName with { type T = TInner }, >(TInterface $_): void {} function generic_split_after_with< TInterface as AnInterfaceWithNotSoLengthyName with { type TMediumLength = int }, >(TInterface $_): void {} function generic_split_between_members< TInterface as AnInterfaceWithNotSoLengthyName with { type T = int; type TMediumLength = string; }, >(TInterface $_): void {}
PHP
hhvm/hphp/hack/test/hackfmt/tests/typed_local.php
<?hh let $x : int = 1; $x; let $x : a______________________________________________________________________ = 1; let $x : a = b____________________________________________________________________; let $x : a______________________________________________________________________ = b____________________________________________________________________; let $x : int; let $x : a______________________________________________________________________;
PHP
hhvm/hphp/hack/test/hackfmt/tests/union_types.php
<?hh type Foo = (A | B); type Bar = (A | B | C); type Baz = (A_______________________________________ | B_______________________________________); type Qux = (A_______________________________________ | B_______________________________________ | C_______________________________________);
PHP
hhvm/hphp/hack/test/hackfmt/tests/unset.php
<?hh unset($foo); $baz = $qux; unset( $foo, $bar, ); $baz = $qux; unset( $foo, $bar ); $baz = $qux; unset( $the_quick_brown_fox_jumped_over_the_lazy_dog, $grump_wizards_make_toxic_brew_for_the_evil_queen_and_jack ); $baz = $qux; unset( $the_quick_brown_fox_jumped_over_the_lazy_dog, $grump_wizards_make_toxic_brew_for_the_evil_queen_and_jack, ); $baz = $qux;
PHP
hhvm/hphp/hack/test/hackfmt/tests/variadics.php
<?hh function f($aaaaaaaaaa, $bbbbbbbbbbbbbbbbbbbb, $cccccccccc, $dddddddddd, ...$eee) { return function($aaaaaaaaaa, $bbbbbbbbbbbbbbbbbbbb, $cccccccccc, $dddddddddd, ...$eee) { return 1; }; } class C1 { /* Ensure formatting for ellipsis is: * string ...$args as opposed to * string... $args */ public function meth(string... $args): void {} public function meth2(int $a, int $b,... $args): void {} }
PHP
hhvm/hphp/hack/test/hackfmt/tests/variadic_parameter_trailing_comma.php
<?hh function myPrintfWithANameThatIsSoLongItBreaksTheDeclarationUp(string $format, ...) { // ... } function someOtherFunctionWithALongNameCausingLineBreaksToBeAdded(mixed ...$args) { // ... }
PHP
hhvm/hphp/hack/test/hackfmt/tests/vec_containing_xhp.php
<?hh $items = vec[ <ui:glyph image="foo" />, <ui:glyph image="bar" />, <ui:glyph image="baz" />, 'qux', ]; $x = vec[// <p>x</p>]; $x = vec[<p>{1// }</p>]; $x = vec[<p>{1// }</p>, 2];
PHP
hhvm/hphp/hack/test/hackfmt/tests/where_constraint.php
<?hh interface IFoo<T> { public function foo(T $bar): void where T as int; } class Foo<T> implements IFoo<T> { public function foo(T $bar): void where T as int {} }
PHP
hhvm/hphp/hack/test/hackfmt/tests/xhp.php
<?hh function f() { $a = 1; return <input data-fooooooooooooooooo={$a} data-baaaaaaaaaaaaaaaaaaaaar={$a} baaaaz={$a}/>; } function g() { $a = 1; return <div data-fooooooooooooooooo={$a} data-baaaaaaaaaaaaaaaaaaaaar={$a} baaaaz={$a}>hi</div>; } function h() { $a = 1; return <input data-foo={$a}/>; } function i() { return <a></a>; } function j() { return <a> </a>; } function k() { return <a><a><a><a><a><a><a><a><a><a><a><a></a></a></a></a></a></a></a></a></a></a></a></a>; } function m() { return <b><a href="aaaaaaaaaaaaaaaaaaaaaaaaaa" asdf="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"/><a href="a"/></b>; } function n() { return <a>1 1 1</a>; } function o() { return <a> 1 1 1 </a>; } function p() { return <aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa href="a" href2="a" href3="a" href4="a">1 1 1</aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>; } function q() { return <aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa href="a" href2="a" href3="a" href4="a"> 1 1 1 </aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>; } function r() { return <a><!-- this is a very long comment lorem ipsum ipsum ipsum ipsum ipsum ipsum --></a>; } function s() { return <a><!-- this is a short comment --></a>; } function t() { return <a><a href="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa">1</a><a href="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa">1</a></a>; } function u($x, $y) { return <grid> <item> {$x} {$y} {$x} {$y} </item> <item>bar</item> <item>bar</item> <item>bar</item> </grid>; } function v() { return <a><aaaaaaaaaaa href="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa">1</aaaaaaaaaaa>!</a>; } function v() { return <aaaaaaaaaaaa href="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" name="watttttt"/>; } function w() { return <p> <my:example:tag /> <my:exampel:tag:param param={"Hello, World!"} /> </p>; } function x() { return $this->:is-active ? <span class={cx('myComponent/root', 'myComponent/active')}> {$this->getChildren()} </span> : <a class={cx('myComponent/root')} href={$this->:href}> {$this->getChildren()} </a>; } function y() { return <div class={cx(Map { 'linkWrap' => true, 'hasCount' => $has_count, 'noCount' => !$has_count, })}> foo </div>; } function z() { return <div>foooooooooooooooooooo{$baaaaaaaaaaaaaaaaaar}<span>baaaaaaaaaaaaaaaaaaz</span><span>qux</span></div>; } function aa() { $a = <foo></foo>; $b = <foo> </foo>; $c = <foo> </foo>; $d = <foo></foo>; $e = <foo> </foo>; $f = <foo_______________________________></foo_______________________________>; $g = <foo_______________________________> </foo_______________________________>; $h = <foo_______________________________> </foo_______________________________>; $i = <foo_______________________________></foo_______________________________>; $j = <foo_________________________________></foo_________________________________>; } function ab() { f(() ==> { return <foo___________________>{$bar_______________}</foo___________________>; }); f( () ==> { return <foo___________________> {$bar_________________} </foo___________________>; }, ); } function ac() { return <p> <b>{$foo__________________________}</b> <i>{$bar__________________________}</i> </p>; } function ad() { return <p> <b>{$foo__________________________}</b> <i>{$bar__________________________}</i> </p>; } function ae() { $x = <foo_______________>{$bar__________________________}</foo_______________>; }
PHP
hhvm/hphp/hack/test/hackfmt/tests/xhp_1.php
<?hh // strict // Copyright 2004-present Facebook. All Rights Reserved. final class :MyFancyXHPClass extends :OtherXHPThing { protected async function genXHP(): Awaitable<:xhp> { $button = <x:button use="primary">Click This Extra Extra Extra Long Text</x:button>; $link = <x:link href="#">Click This</x:link>; $clickable_sq = <div style="width: 100px; height: 100px; background: blue;" />; $ret = <x:column-layout-component attr1="attr" attr2={ FakeClassWithReallyLongAttributeStuff::getCreateSomeStaticData(Map { 'key1' => 'value1', }) }> <x:div padding="large"> <x:link href="#">Click Here!</x:link> </x:div> <x:div padding="large"> {$link} </x:div> <x:div padding="large"> <!-- Here is a multiline comment that is very unhelpful. In fact, it is strange that it exists at all, let alone takes up multiple lines --> <x:form id="form" method="post" > <x:text-input name="input" placeholder="Type a message." /> <x:button use="primary">Submit Form</x:button> <x:button use="other">This is a decoy button meant to confuse you</x:button> </x:form> </x:div> </x:column-layout-component>; PostXHPVariableSetLinesToCheckForPartialForamtting::go(Vector { 1, 2, 3, 4}, Vector {5, 6, 7 , 8}); return $ret; } }
PHP
hhvm/hphp/hack/test/hackfmt/tests/xhp_body_breaks_if_open_breaks.php
<?hh $x = <ui:selector:option value={$value________} selected={$label === $selected_value}> {$label} </ui:selector:option>; $x = <p> <ui:selector:option value={$value________} selected={$label === $selected_value}> {$label} </ui:selector:option>; </p>; f( <ui:selector:option value={$value________} selected={$label === $selected_value}> {$label} </ui:selector:option>, ); f(<ui:selector:option value={$value________} selected={$label === $selected_value}> {$label} </ui:selector:option>);
PHP
hhvm/hphp/hack/test/hackfmt/tests/xhp_children_declaration.php
<?hh // Copyright 2004-present Facebook. All Rights Reserved. final class :format-xhp:part1 { children (:fb:fundingsource:data-table:header, :fb:fundingsource:data-table:row*); } final class :format-xhp:part2 { children (:fb:fundingsource:data-table:header // hello , :fb:fundingsource:data-table:row*); } final class :format-xhp:part3 { children ((%image, (pcdata | %phrase)?) | ((pcdata | %phrase), %image?)); } final class :format-xhp:part4 { children empty; } final class :format-xhp:part5 { children (:fb:social-pressure:friend-list-item)*; }
PHP
hhvm/hphp/hack/test/hackfmt/tests/xhp_class_attribute_declarations.php
<?hh // strict final class :m:a extends :m:xui:block { attribute :m:xui:div; } final class :m:b extends :m:xui:block { attribute LongNameCollectionCausingLineBreak my-verbosely-named-collection @required; } final class :m:c extends :m:xui:block { attribute :m:xui:div, HandbagCollection collection @required; } final class :m:d extends :m:xui:block { attribute :m:xui:div, HandbagCollection collection @required, AccessorySet accessories; }
PHP
hhvm/hphp/hack/test/hackfmt/tests/xhp_lambda_body.php
<?hh $items = $items->map( $item ==> <li class={cx('myOrderedListService/item')}> <fb:ordered-list-service:ordered-list:item item={$item} /> </li>, );
PHP
hhvm/hphp/hack/test/hackfmt/tests/xhp_paragraph.php
<?hh $paragraph = <p> Now is the winter of our discontent Made glorious summer by this sun of York; And all the clouds that lour'd upon our house In the deep bosom of the ocean buried. Now are our brows bound with victorious wreaths; Our bruised arms hung up for monuments; Our stern alarums changed to merry meetings, Our dreadful marches to delightful measures. </p>;
PHP
hhvm/hphp/hack/test/hackfmt/tests/atted_attribute/atted_attribute_specifications.php
<?hh // strict class FooIsNotBrokenTest extends FooTest { @Override public function foo(): int { return 5; } @DataProvider('provideFooEnvironment') @ExpectedException('FooIsBrokenException') @ExpectedExceptionCode( 'ErrorCode::FOO_IS_BROKEN_AND_CANNOT_POSSIBLY_BE_FIXED', ) public function testFoo(FooEnvironment $env) { if ($env->isFooBroken()) { throw new FooIsBrokenException(); } } } @Attr1@Attr2 class C { @Attr1@Attr2 public function f<@__Soft reify T>(@__Soft int $x): @__Soft void {} } function f(@ReallyOverlyLongAttributeNameForTest int $reallyOverlyLongVariableNameForTest): void { @Attr() ($x) ==> $x * $x; @AnotherReallyOverlyLongAttributeNameForTest() ($sameXParameterButMuchLongerForTest) ==> multiplyButLonger( $sameXParameterButMuchLongerForTest, $sameXParameterButMuchLongerForTest); @Attr function (@__Soft int $x): @__Soft void { return $x * $x; }; @AnotherReallyOverlyLongAttributeNameForTest function ( @__Soft string $x, @__Soft@YetAnotherEvenMoreOverlyLongAttributeNameForTest int $sameXParameterButMuchLongerForTest, ): @__Soft void { return multiplyButLonger($sameXParameterButMuchLongerForTest, $sameXParameterButMuchLongerForTest); }; }
PHP
hhvm/hphp/hack/test/hackfmt/tests/split_after_assignment_operator_hhconfig/test.php
<?hh function f(): void { $very_long_variable_name_bringing_this_line_over_80_chars = nullthrows($nullable); }
PHP
hhvm/hphp/hack/test/hackfmt/tests/split_after_assignment_operator_hhconfig_v0/test.php
<?hh function f(): void { $very_long_variable_name_bringing_this_line_over_80_chars = nullthrows($nullable); }
PHP
hhvm/hphp/hack/test/hackfmt/tests/split_after_assignment_operator_hhconfig_v1/test.php
<?hh function f(): void { $very_long_variable_name_bringing_this_line_over_80_chars = nullthrows($nullable); }
PHP
hhvm/hphp/hack/test/hackrs/folded_decls/enum_class.php
<?hh abstract enum class A: string { abstract string fred; abstract string ginger; } enum class E : string extends A { string fred = 'fred astaire'; string ginger = 'ginger rogers'; }
PHP
hhvm/hphp/hack/test/hackrs/folded_decls/req_ancestors2.php
<?hh class Z {} trait T1 { require extends Z; } class A {} class B extends A {} trait T { require extends B; use T1; }
PHP
hhvm/hphp/hack/test/hackrs/folded_decls/req_ancestors3.php
<?hh trait T1 { require extends B; } class A {} class B extends A {} trait T { require extends B; use T1; }
PHP
hhvm/hphp/hack/test/hackrs/folded_decls/stringish_object.php
<?hh class A { public function __toString(): string { return "A"; } } abstract class B { public abstract function __toString(): string; } interface SomeOtherC { public function __toString(): string; } trait TA { public function __toString(): string { return "TA"; } }
HTML Help Workshop
hhvm/hphp/hack/test/hhi/coeffects.hhi
<?hh /** * Copyright (c) 2021, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * */ <<file:__EnableUnstableFeatures('union_intersection_type_hints')>> namespace HH\Capabilities { <<__Sealed>> interface Unrelated {} } namespace HH\Contexts { type oldrx = (\HH\Capabilities\Rx & \HH\Capabilities\WriteProperty); type oldrx_shallow = (\HH\Capabilities\RxShallow & \HH\Capabilities\WriteProperty); type oldrx_local = (\HH\Capabilities\RxLocal & \HH\Capabilities\WriteProperty); type unrelated = \HH\Capabilities\Unrelated; namespace Unsafe { type oldrx = mixed; type oldrx_shallow = \HH\Capabilities\RxLocal; type oldrx_local = \HH\Contexts\defaults; type unrelated = mixed; } }
HTML Help Workshop
hhvm/hphp/hack/test/hhi/expr_tree.hhi
<?hh /** * An example DSL for testing expression trees (ETs). * * Any class can be used an an expression tree visitor. It needs to implement * the methods shown here, and expression tree literals MyClass`...` will be * converted (at compile time) to calls on these methods. * * This .hhi file is only used when testing the type checker. Otherwise * every test file would need to include a class with all these methods. */ class ExampleDsl { const type TAst = mixed; // The desugared expression tree literal will call this method. public static function makeTree<<<__Explicit>> TInfer>( ?ExprPos $pos, shape( 'splices' => dict<string, mixed>, 'functions' => vec<mixed>, 'static_methods' => vec<mixed>, ) $metadata, (function(ExampleDsl): ExampleDsl::TAst) $ast, )[]: ExprTree<ExampleDsl, ExampleDsl::TAst, TInfer> { throw new Exception(); } // The fooType() methods are used to typecheck the expression tree literals. // They do not require implementations. public static function intType(): ExampleInt { throw new Exception(); } public static function floatType(): ExampleFloat { throw new Exception(); } public static function boolType(): ExampleBool { throw new Exception(); } public static function stringType(): ExampleString { throw new Exception(); } public static function nullType(): null { throw new Exception(); } public static function voidType(): ExampleVoid { throw new Exception(); } public static function symbolType<T>( (function(ExampleContext): Awaitable<ExprTree<ExampleDsl, ExampleDsl::TAst, T>>) $_, ): T { throw new Exception(); } public static function lambdaType<T>( T $_, ): ExampleFunction<T> { throw new Exception(); } // The visitFoo methods are called at runtime when the expression tree literal // is evaluated. You will need to provide implementations of these methods, // but we've stubbed them for the sake of Hack tests. public function visitInt(?ExprPos $_, int $_): ExampleDsl::TAst { throw new Exception(); } public function visitFloat(?ExprPos $_, float $_): ExampleDsl::TAst { throw new Exception(); } public function visitBool(?ExprPos $_, bool $_): ExampleDsl::TAst { throw new Exception(); } public function visitString(?ExprPos $_, string $_)[]: ExampleDsl::TAst { throw new Exception(); } public function visitNull(?ExprPos $_): ExampleDsl::TAst { throw new Exception(); } public function visitBinop( ?ExprPos $_, ExampleDsl::TAst $lhs, string $op, ExampleDsl::TAst $rhs, ): ExampleDsl::TAst { throw new Exception(); } public function visitUnop( ?ExprPos $_, ExampleDsl::TAst $operand, string $operator, ): ExampleDsl::TAst { throw new Exception(); } public function visitLocal(?ExprPos $_, string $_): ExampleDsl::TAst { throw new Exception(); } public function visitLambda( ?ExprPos $_, vec<string> $_args, vec<ExampleDsl::TAst> $_body, ): ExampleDsl::TAst { throw new Exception(); } public function visitGlobalFunction<T>( ?ExprPos $_, (function(ExampleContext): Awaitable<ExprTree<ExampleDsl, ExampleDsl::TAst, T>>) $_, )[]: ExampleDsl::TAst { throw new Exception(); } public function visitStaticMethod<T>( ?ExprPos $_, (function(ExampleContext): Awaitable<ExprTree<ExampleDsl, ExampleDsl::TAst, T>>) $_, ): ExampleDsl::TAst { throw new Exception(); } public function visitCall( ?ExprPos $_, ExampleDsl::TAst $_callee, vec<ExampleDsl::TAst> $_args, )[]: ExampleDsl::TAst { throw new Exception(); } public function visitAssign( ?ExprPos $_, ExampleDsl::TAst $_, ExampleDsl::TAst $_, ): ExampleDsl::TAst { throw new Exception(); } public function visitTernary( ?ExprPos $_, ExampleDsl::TAst $_condition, ?ExampleDsl::TAst $_truthy, ExampleDsl::TAst $_falsy, ): ExampleDsl::TAst { throw new Exception(); } // Statements. public function visitIf( ?ExprPos $_, ExampleDsl::TAst $_cond, vec<ExampleDsl::TAst> $_then_body, vec<ExampleDsl::TAst> $_else_body, ): ExampleDsl::TAst { throw new Exception(); } public function visitWhile( ?ExprPos $_, ExampleDsl::TAst $_cond, vec<ExampleDsl::TAst> $_body, ): ExampleDsl::TAst { throw new Exception(); } public function visitReturn(?ExprPos $_, ?ExampleDsl::TAst $_): ExampleDsl::TAst { throw new Exception(); } public function visitFor( ?ExprPos $_, vec<ExampleDsl::TAst> $_, ?ExampleDsl::TAst $_, vec<ExampleDsl::TAst> $_, vec<ExampleDsl::TAst> $_, ): ExampleDsl::TAst { throw new Exception(); } public function visitBreak(?ExprPos $_): ExampleDsl::TAst { throw new Exception(); } public function visitContinue(?ExprPos $_): ExampleDsl::TAst { throw new Exception(); } public function visitPropertyAccess( ?ExprPos $_, ExampleDsl::TAst $_, string $_, ): ExampleDsl::TAst { throw new Exception(); } public function visitXhp( ?ExprPos $_, string $_, dict<string, ExampleDsl::TAst> $_, vec<ExampleDsl::TAst> $_, ): ExampleDsl::TAst { throw new Exception(); } public function splice<T>( ?ExprPos $_, string $_key, ExampleDslExpression<T> $_, )[]: ExampleDsl::TAst { throw new Exception(); } } interface Spliceable<TVisitor, TResult, +TInfer> { public function visit(TVisitor $v): TResult; } final class ExprTree<TVisitor, TResult, +TInfer> implements Spliceable<TVisitor, TResult, TInfer> { public function __construct( private ?ExprPos $pos, private shape( 'splices' => dict<string, mixed>, 'functions' => vec<mixed>, 'static_methods' => vec<mixed>, ) $metadata, private (function(TVisitor): TResult) $ast, private (function(): TInfer) $err, ) {} public function visit(TVisitor $v): TResult { return ($this->ast)($v); } } // The type of positions passed to the expression tree visitor. type ExprPos = shape(...); // Type declarations used when checking DSL expressions. interface ExampleMixed { public function __tripleEquals(ExampleMixed $_): ExampleBool; public function __notTripleEquals(ExampleMixed $_): ExampleBool; } interface ExampleInt extends ExampleMixed { public function __plus(ExampleInt $_): ExampleInt; public function __minus(ExampleInt $_): ExampleInt; public function __star(ExampleInt $_): ExampleInt; public function __slash(ExampleInt $_): ExampleInt; public function __percent(ExampleInt $_): ExampleInt; public function __negate(): ExampleInt; public function __lessThan(ExampleInt $_): ExampleBool; public function __lessThanEqual(ExampleInt $_): ExampleBool; public function __greaterThan(ExampleInt $_): ExampleBool; public function __greaterThanEqual(ExampleInt $_): ExampleBool; public function __amp(ExampleInt $_): ExampleInt; public function __bar(ExampleInt $_): ExampleInt; public function __caret(ExampleInt $_): ExampleInt; public function __lessThanLessThan(ExampleInt $_): ExampleInt; public function __greaterThanGreaterThan(ExampleInt $_): ExampleInt; public function __tilde(): ExampleInt; public function __postfixPlusPlus(): void; public function __postfixMinusMinus(): void; } interface ExampleBool extends ExampleMixed { public function __ampamp(ExampleBool $_): ExampleBool; public function __barbar(ExampleBool $_): ExampleBool; public function __bool(): bool; public function __exclamationMark(): ExampleBool; } interface ExampleString extends ExampleMixed, XHPChild { public function __dot(ExampleString $_): ExampleString; } interface ExampleFloat extends ExampleMixed {} final class ExampleContext {} interface ExampleVoid {} interface ExampleFunction<T> { public function __unwrap(): T; } type ExampleDslExpression<T> = Spliceable<ExampleDsl, ExampleDsl::TAst, T>;
HTML Help Workshop
hhvm/hphp/hack/test/hhi/XHPTest.hhi
<?hh abstract class XHPTest { public function __construct( public darray<string,mixed> $_attributes, public varray<mixed> $_children, public string $_filename, public int $_line_number, ); public function getAttribute( string $_attribute, mixed $_default = null ): mixed; }
hhvm/hphp/hack/test/hhi/generate/dune
(rule (alias generate_hhis_test) (deps %{exe:../../../src/hh_parse.exe} %{project_root}/hack/test/verify.py %{project_root}/hack/test/review.sh (glob_files %{project_root}/hack/test/hhi/generate/*.php) (glob_files %{project_root}/hack/test/hhi/generate/*.hack) (glob_files %{project_root}/hack/test/hhi/generate/*.hhi.exp)) (action (run %{project_root}/hack/test/verify.py %{project_root}/hack/test/hhi/generate --out-extension .hhi.out --expect-extension .hhi.exp --program %{exe:../../../src/hh_parse.exe} --flags --generate-hhi))) (alias (name runtest) (deps (alias generate_hhis_test)))
PHP
hhvm/hphp/hack/test/hhi/generate/no_constant_values.php
<?hh <<file:__EnableUnstableFeatures('class_const_default')>> namespace GeneratedHHITest; /** Top level constant doc block */ const int FOO = 42, BAR = -999; abstract class Baz { /** Class constant doc block */ const string QUX = 'placeholder'; /** Abstract class constant doc block */ abstract const bool YES = false; }
PHP
hhvm/hphp/hack/test/hhi/generate/no_function_bodies.php
<?hh // strict namespace GeneratedHHITest; /** Top level function doc block */ function top_level_function(): void { foo(); } class Foo { /** public method doc block */ public function publicMethod(): void { bar(); } /** public static method doc block */ public static function publicStaticMethod(): void { bar(); } }
HTML Help Workshop
hhvm/hphp/hack/test/hhi/pessimised_hhi_1354291/XHPTest.hhi
<?hh <<__SupportDynamicType>> abstract class XHPTest { public function __construct( public ~darray<string,supportdyn<mixed>> $_, // Attributes public ~varray<supportdyn<mixed>> $_, // Children public ~string $_, // Filename public ~int $_, // Line number ); }
Python
hhvm/hphp/hack/test/hh_asdiff/diff_test.py
#!/usr/bin/env python3 # pyre-strict # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the "hack" directory of this source tree. import unittest from typing import Iterator from hphp.hack.src.hh_asdiff import diff def iter_lines(s: str) -> Iterator[str]: return iter(s.splitlines(keepends=True)) class EqualTest(unittest.TestCase): def test_equal_lines_same_len(self) -> None: exp = """\ #starts here .main { Int 1 RetC } #ends here """ act = """\ #starts here .main { Int 2 RetC } #ends here """ self.assertFalse(diff.equal_lines(iter_lines(exp), iter_lines(act))) self.assertTrue( diff.equal_lines(iter_lines(exp), iter_lines(act.replace("2", "1"))) ) def test_infinite_actual_lines_due_to_infinite_loop(self) -> None: COMMON_LINE = "foo\n" # pyre-fixme[53]: Captured variable `COMMON_LINE` is not annotated. def gen_foo_once() -> Iterator[str]: yield COMMON_LINE # pyre-fixme[53]: Captured variable `COMMON_LINE` is not annotated. def gen_foo_indefinitely() -> Iterator[str]: while True: yield COMMON_LINE self.assertFalse(diff.equal_lines(gen_foo_once(), gen_foo_indefinitely())) def test_infinite_actual_lines_due_to_infinite_loop(self) -> None: exp_seq = ("a\n", "b\n") act_seq = ["a\n", "b\n"] self.assertNotEqual(exp_seq, act_seq) # unlike __eq__ (operator ==), equal_lines returns True self.assertTrue(diff.equal_lines(iter(exp_seq), iter(act_seq))) class DiffRankerTest(unittest.TestCase): def test_new_top_smallest_replaces_old_max(self) -> None: ranker = diff.UnifiedDiffRanker(2) ranker("file1", ["line1\n", "line2\n"], ["1\n", "2\n"]) ranker("file2", [], ["1\n", "2\n", "3\n", "4\n", "5\n"]) ranker("file3", ["a\n", "b\n"], ["a\n", "c\n"]) act = [diffsize_filename for diffsize_filename, _, _ in ranker] exp = [(2, "file3"), (4, "file1")] self.assertListEqual(exp, act)
Python
hhvm/hphp/hack/test/hh_asdiff/parsing_test.py
#!/usr/bin/env python3 # pyre-strict # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the "hack" directory of this source tree. import unittest from typing import Iterator from hphp.hack.src.hh_asdiff import parsing def iter_lines(s: str) -> Iterator[str]: return iter(s.splitlines(keepends=True)) class SplitTest(unittest.TestCase): def test_lines_single_marker_pair_no_filename(self) -> None: lines = iter_lines( """\ GARBAGE1 #starts here .main { Int 1 RetC } #ends here GARBAGE2 """ ) line_iter = iter(lines) ignored_lines = [] gen = parsing.split_lines(line_iter, lambda ln: ignored_lines.append(ln)) exp1 = (None, [".main {\n", " Int 1\n", " RetC\n", "}\n"]) self.assertEqual(next(gen, None), exp1) self.assertIsNone(next(gen, None)) self.assertEqual(ignored_lines, ["GARBAGE1\n", "GARBAGE2\n"]) def test_split_multiple_files_with_filenames(self) -> None: line_iter = iter( parsing.split_lines( iter_lines( """\ # dir/file1.php starts here HHAS1 # dir/file1.php ends here # dir/file2.php starts here HHAS2a HHAS2b # dir/file2.php ends here """ ) ) ) self.assertEqual(next(line_iter, None), ("dir/file1.php", ["HHAS1\n"])) self.assertEqual( next(line_iter, None), ("dir/file2.php", ["HHAS2a\n", "HHAS2b\n"]) ) def test_lines_no_markers_ignores_all(self) -> None: count = 0 lines = ["1\n", "2\n", "3\n"] def count_ignored(_) -> None: nonlocal count count += 1 list(parsing.split_lines(iter(lines), count_ignored)) # force evaluation self.assertEqual(count, len(lines))
Python
hhvm/hphp/hack/test/hh_codesynthesis/agentgenerator_test.py
#!/usr/bin/env python3 # pyre-strict # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the "hack" directory of this source tree. import tempfile import unittest from hphp.hack.src.hh_codesynthesis import agentGenerator, hackGenerator from hphp.hack.src.hh_codesynthesis.agentGenerator import ClingoContext class GenerateLogicRulesTest(unittest.TestCase): def test_depth_less_than_nodes(self) -> None: solving_context = ClingoContext(number_of_nodes=12, min_depth=3) exp = [ 'internal_symbols("S0", 0;"S1", 1;"S2", 2;"S3", 3;"S4", 4;"S5", 5;"S6",' ' 6;"S7", 7;"S8", 8;"S9", 9;"S10", 10;"S11", 11).', 'extends_to("S0", "S4").', 'extends_to("S4", "S8").', ] self.assertListEqual(exp, agentGenerator.generate_logic_rules(solving_context)) def test_depth_more_than_nodes(self) -> None: # In this case, the graph has no way to satisfy the min_depth requirement. # The user, or the higher level wrapper should make sure given proper # parameters. Otherwise, we will create the following output. solving_context = ClingoContext(number_of_nodes=3, min_depth=5) with self.assertRaises( expected_exception=RuntimeError, msg="Received unreasonable parameters." ): agentGenerator.generate_logic_rules(solving_context) def test_depth_equals_to_nodes(self) -> None: solving_context = ClingoContext(number_of_nodes=7, min_depth=7) exp = [ 'internal_symbols("S0", 0;"S1", 1;"S2", 2;"S3", 3;"S4", 4;"S5",' ' 5;"S6", 6).', 'extends_to("S0", "S1").', 'extends_to("S1", "S2").', 'extends_to("S2", "S3").', 'extends_to("S3", "S4").', 'extends_to("S4", "S5").', 'extends_to("S5", "S6").', ] self.assertListEqual(exp, agentGenerator.generate_logic_rules(solving_context)) def test_degree_distribution(self) -> None: solving_context = ClingoContext( number_of_nodes=12, degree_distribution=[1, 3, 5] ) exp = [ 'internal_symbols("S0", 0;"S1", 1;"S2", 2;"S3", 3;"S4", 4;"S5", 5;"S6",' ' 6;"S7", 7;"S8", 8;"S9", 9;"S10", 10;"S11", 11).', ":- #count{X : in_degree(X, 0)} < 1.", ":- #count{X : in_degree(X, 1)} < 3.", ":- #count{X : in_degree(X, 2)} < 5.", ] self.assertListEqual(exp, agentGenerator.generate_logic_rules(solving_context)) def test_sum_of_degrees_greater_than_nodes(self) -> None: solving_context = ClingoContext( number_of_nodes=12, degree_distribution=[3, 5, 7] ) with self.assertRaises( expected_exception=RuntimeError, msg="Received unreasonable parameters." ): agentGenerator.generate_logic_rules(solving_context) def test_hack_code_gen(self) -> None: solving_context = ClingoContext( number_of_nodes=12, min_depth=3, min_classes=3, min_interfaces=4, lower_bound=1, higher_bound=5, min_stub_classes=4, min_stub_interfaces=1, degree_distribution=[1, 3, 5], ) hack_codegen = hackGenerator.HackCodeGenerator(solving_context) agentGenerator.do_reasoning( additional_programs=agentGenerator.generate_logic_rules(solving_context), generator=hack_codegen, ) self.assertTrue(hack_codegen.validate()) def test_unsatisfiable_parameters(self) -> None: # Given 5 nodes, but asking for 3 classes + 4 interfaces with solving_context = ClingoContext( number_of_nodes=5, min_classes=3, min_interfaces=4 ) hack_codegen = hackGenerator.HackCodeGenerator(solving_context) with self.assertRaises(expected_exception=RuntimeError, msg="Unsatisfiable."): agentGenerator.do_reasoning( additional_programs=agentGenerator.generate_logic_rules( solving_context ), generator=hack_codegen, ) class ExtractLogicRulesTest(unittest.TestCase): def test_wrong_format(self) -> None: exp = [ 'extends_to("A", "B").', 'extends_to("I", "B").', 'extends_to("T", "A").', 'method("A", "foo", "B").', 'type("A", "B").', 'type("I", "B").', 'type("T", "A").', 'type("T", "B").', 'symbols("A";"B";"I";"T").', ] deps = """\ Extends A -> Type B Extends I -> Type B Extends T -> Type A, Broke Method A::foo -> Type B Type A -> Type B Type I -> Type B Type T -> Type A, Type B""" # pyre-fixme[6]: For 1st param expected `List[str]` but got # `List[typing_extensions.LiteralString]`. self.assertListEqual(exp, agentGenerator.extract_logic_rules(deps.split("\n"))) def test_unexpected_rhs(self) -> None: deps = """\ Type A -> SMethod B::foo """ with self.assertRaises( expected_exception=NotImplementedError, msg="Not supported SMethod on the right hand side.", ): # pyre-fixme[6]: For 1st param expected `List[str]` but got # `List[typing_extensions.LiteralString]`. agentGenerator.extract_logic_rules(deps.split("\n")) def test_multiple_lines(self) -> None: exp = [ 'extends_to("I1", "C1").', 'extends_to("I1", "C2").', 'extends_to("I1", "C3").', 'extends_to("I1", "I2").', 'extends_to("I3", "C4").', 'extends_to("I4", "C5").', 'symbols("C1";"C2";"C3";"C4";"C5";"I1";"I2";"I3";"I4").', ] deps = """\ Extends I1 -> Type C1, Type C2, Type C3, Type I2 Extends I3 -> Type C4, Type C6, Type I5, Type I6, Type I7, Type I8 Extends I4 -> Type C5, Type C6, Type I9, Type I10, Type I11, Type I12, Type I13, Type I14""" # pyre-fixme[6]: For 1st param expected `List[str]` but got # `List[typing_extensions.LiteralString]`. self.assertListEqual(exp, agentGenerator.extract_logic_rules(deps.split("\n"))) def test_multiple_lines_all(self) -> None: # T92303034 Temporary handle for the multiple lines using replace(",\n", ","), exp = [ 'extends_to("I1", "C1").', 'extends_to("I1", "C2").', 'extends_to("I1", "C3").', 'extends_to("I1", "I2").', 'extends_to("I3", "C4").', 'extends_to("I3", "C6").', 'extends_to("I3", "I5").', 'extends_to("I3", "I6").', 'extends_to("I3", "I7").', 'extends_to("I3", "I8").', 'extends_to("I4", "C5").', 'extends_to("I4", "C6").', 'extends_to("I4", "I9").', 'extends_to("I4", "I10").', 'extends_to("I4", "I11").', 'extends_to("I4", "I12").', 'extends_to("I4", "I13").', 'extends_to("I4", "I14").', 'symbols("C1";"C2";"C3";"C4";"C5";"C6";"I1";"I10";"I11";"I12";"I13";"I14";"I2";"I3";"I4";"I5";"I6";"I7";"I8";"I9").', ] deps = """\ Extends I1 -> Type C1, Type C2, Type C3, Type I2 Extends I3 -> Type C4, Type C6, Type I5, Type I6, Type I7, Type I8 Extends I4 -> Type C5, Type C6, Type I9, Type I10, Type I11, Type I12, Type I13, Type I14""" self.assertListEqual( exp, # pyre-fixme[6]: For 1st param expected `List[str]` but got # `List[typing_extensions.LiteralString]`. agentGenerator.extract_logic_rules(deps.replace(",\n", ",").split("\n")), ) def test_extends_type_method_dependency(self) -> None: exp = [ 'extends_to("A", "B").', 'extends_to("I", "B").', 'extends_to("T", "A").', 'method("A", "foo", "B").', 'type("A", "B").', 'type("I", "B").', 'type("T", "A").', 'type("T", "B").', 'symbols("A";"B";"I";"T").', ] deps = """\ Extends A -> Type B Extends I -> Type B Extends T -> Type A Method A::foo -> Type B Type A -> Type B Type I -> Type B Type T -> Type A, Type B""" # pyre-fixme[6]: For 1st param expected `List[str]` but got # `List[typing_extensions.LiteralString]`. self.assertListEqual(exp, agentGenerator.extract_logic_rules(deps.split("\n"))) def test_extends_type_smethod_dependency(self) -> None: exp = [ 'extends_to("I", "A").', 'method("I", "bar", "A").', 'static_method("A", "foo", "B").', 'static_method("A", "foo", "T").', 'type("A", "B").', 'type("A", "T").', 'type("I", "A").', 'symbols("A";"I";"T").', 'funcs("B").', ] deps = """\ Extends I -> Type A Method I::bar -> Type A SMethod A::foo -> Fun B, Type T Type A -> Fun B, Type T Type I -> Type A""" # pyre-fixme[6]: For 1st param expected `List[str]` but got # `List[typing_extensions.LiteralString]`. self.assertListEqual(exp, agentGenerator.extract_logic_rules(deps.split("\n"))) def test_extends_type_fun_dependency(self) -> None: exp = [ 'extends_to("I", "A").', 'method("I", "bar", "A").', 'invoked_by("F", "A").', 'type("A", "B").', 'type("A", "T").', 'type("I", "A").', 'symbols("A";"B";"I";"T").', 'funcs("F").', ] deps = """\ Extends I -> Type A Method I::bar -> Type A Fun F -> Type A Type A -> Type B, Type T Type I -> Type A""" # pyre-fixme[6]: For 1st param expected `List[str]` but got # `List[typing_extensions.LiteralString]`. self.assertListEqual(exp, agentGenerator.extract_logic_rules(deps.split("\n"))) def test_unsupported_type_dependency(self) -> None: # T94428437 Temporary skipping all built-in functions for now. exp = ['extends_to("A", "B").', 'type("A", "B").', 'symbols("A";"B").'] deps = r""" Extends A -> Type B Type A -> Type B Type HH\Capabilities\AccessGlobals -> Type B Type HH\Contexts\Unsafe\globals -> Type A""" # pyre-fixme[6]: For 1st param expected `List[str]` but got # `List[typing_extensions.LiteralString]`. self.assertListEqual(exp, agentGenerator.extract_logic_rules(deps.split("\n"))) class DoReasoningTest(unittest.TestCase): def test_clingo_exception(self) -> None: deps = ["rule_without_period(symbol1, symbol2)"] raw_codegen = agentGenerator.CodeGenerator() with self.assertRaises(expected_exception=RuntimeError, msg="parsing failed"): agentGenerator.do_reasoning(additional_programs=deps, generator=raw_codegen) def test_extends_dependency(self) -> None: exp = [ 'class("B")', 'class("I")', 'extends("A","T")', 'extends("B","I")', 'implements("B","A")', 'interface("A")', 'interface("T")', ] rules = [ 'extends_to("A", "B").', 'extends_to("I", "B").', 'extends_to("T", "A").', 'symbols("A";"B";"I";"T").', ] raw_codegen = agentGenerator.CodeGenerator() agentGenerator.do_reasoning(additional_programs=rules, generator=raw_codegen) self.assertListEqual(sorted(str(raw_codegen).split()), exp) def test_type_dependency(self) -> None: # This one covered the 'has_method_with_parameter'. exp = ['class("B")', 'has_method_with_parameter("C","B")', 'interface("C")'] rules = ['type("B", "C").', 'symbols("B"; "C").'] raw_codegen = agentGenerator.CodeGenerator() agentGenerator.do_reasoning(additional_programs=rules, generator=raw_codegen) self.assertListEqual(sorted(str(raw_codegen).split()), exp) def test_method_dependency(self) -> None: # This one covered the 'invokes_in_method', as well as the # 'has_method_with_parameter', since we need to pass the object as parameter, # then invoke its method. exp = [ 'add_method("B","foo")', 'class("C")', 'has_method_with_parameter("C","B")', 'interface("B")', 'invokes_in_method("C","B","foo")', ] rules = ['method("B", "foo", "C").', 'symbols("B"; "C").'] raw_codegen = agentGenerator.CodeGenerator() agentGenerator.do_reasoning(additional_programs=rules, generator=raw_codegen) self.assertListEqual(sorted(str(raw_codegen).split()), exp) def test_smethod_type_dependencies(self) -> None: # This one covered the 'invokes_static_method' with 'Type', and we don't need to # pass the object as parameter, so that we directly invoke the static method. exp = [ 'add_static_method("B","foo")', 'class("B")', 'class("C")', 'interface("A")', 'invokes_static_method("C","B","foo")', ] rules = ['static_method("B", "foo", "C").', 'symbols("A"; "B"; "C").'] raw_codegen = agentGenerator.CodeGenerator() agentGenerator.do_reasoning(additional_programs=rules, generator=raw_codegen) self.assertListEqual(sorted(str(raw_codegen).split()), exp) def test_smethod_fun_dependencies(self) -> None: # This one covered the 'invokes_static_method' with 'Fun', and we don't need to # pass the object as parameter, so that we directly invoke the static method. exp = [ 'add_static_method("B","foo")', 'class("B")', 'funcs("C")', 'interface("A")', 'invokes_static_method("C","B","foo")', ] rules = ['static_method("B", "foo", "C").', 'symbols("A"; "B").funcs("C").'] raw_codegen = agentGenerator.CodeGenerator() agentGenerator.do_reasoning(additional_programs=rules, generator=raw_codegen) self.assertListEqual(sorted(str(raw_codegen).split()), exp) def test_smethod_dependency_exception(self) -> None: # This one covered the unsatifiable part, that we can't find an answer. # Here we are forcing symbol("B") to get interface("B"). rules = ['static_method("A", "foo", "B").', 'interface("B").symbols("A"; "B").'] raw_codegen = agentGenerator.CodeGenerator() with self.assertRaises(expected_exception=RuntimeError, msg="Unsatisfiable."): agentGenerator.do_reasoning( additional_programs=rules, generator=raw_codegen ) def test_method_type_extends_dependencies(self) -> None: # This one covered the 'override' in the "Extend" and "Method" edge. exp = [ 'add_method("B","foo")', 'add_method("C","foo")', 'class("C")', 'implements("C","B")', 'interface("B")', ] rules = [ 'extends_to("B", "C").', 'method("B", "foo", "C").', 'type("B", "C").', 'symbols("B"; "C").', ] raw_codegen = agentGenerator.CodeGenerator() agentGenerator.do_reasoning(additional_programs=rules, generator=raw_codegen) self.assertListEqual(sorted(str(raw_codegen).split()), exp) def test_fun_type_dependencies(self) -> None: # This one covered the 'invokes_function' with 'Type'. exp = [ 'class("A")', 'funcs("Fn")', 'interface("B")', 'invokes_function("A","Fn")', ] rules = ['invoked_by("Fn", "A").', 'symbols("A"; "B").', 'funcs("Fn").'] raw_codegen = agentGenerator.CodeGenerator() agentGenerator.do_reasoning(additional_programs=rules, generator=raw_codegen) self.assertListEqual(sorted(str(raw_codegen).split()), exp) def test_fun_fun_dependencies(self) -> None: # This one covered the 'invokes_function' with 'Fun'. exp = [ 'class("A")', 'funcs("FnA")', 'funcs("FnB")', 'interface("B")', 'invokes_function("FnA","FnB")', ] rules = [ 'invoked_by("FnB", "FnA").', 'symbols("A"; "B").', 'funcs("FnA"; "FnB").', ] raw_codegen = agentGenerator.CodeGenerator() agentGenerator.do_reasoning(additional_programs=rules, generator=raw_codegen) self.assertListEqual(sorted(str(raw_codegen).split()), exp) def test_fun_dependency_exception(self) -> None: # This one covered the unsatifiable part, that we can't find an answer. # Here we are forcing symbol("A") to get interface("A"). rules = [ 'class("B").', 'invoked_by("Fn", "A").', 'interface("A").', 'symbols("A"; "B").', 'funcs("Fn").', ] raw_codegen = agentGenerator.CodeGenerator() with self.assertRaises(expected_exception=RuntimeError, msg="Unsatisfiable."): agentGenerator.do_reasoning( additional_programs=rules, generator=raw_codegen ) def test_class_method_fun_dependency(self) -> None: # This one covered the 'creates_in_body' with <'Method', 'Fun'>. exp = [ 'add_method("B","foo")', 'class("B")', 'creates_in_body("Fn","B")', 'funcs("Fn")', 'implements("B","A")', 'interface("A")', 'invokes_in_body("Fn","B","foo")', ] rules = [ 'method("B", "foo", "Fn").' 'symbols("A"; "B").' 'funcs("Fn").' 'extends_to("A","B").' ] raw_codegen = agentGenerator.CodeGenerator() agentGenerator.do_reasoning(additional_programs=rules, generator=raw_codegen) self.assertListEqual(sorted(str(raw_codegen).split()), exp) def test_interface_method_fun_dependency(self) -> None: # This one covered the 'has_parameter_and_argument' with <'Method', 'Fun'>. exp = [ 'add_method("A","foo")', 'class("B")', 'funcs("Fn")', 'has_parameter_and_argument("Fn","A","B")', 'implements("B","A")', 'interface("A")', 'invokes_in_body("Fn","A","foo")', ] rules = [ 'method("A", "foo", "Fn").' 'symbols("A"; "B").' 'funcs("Fn").' 'extends_to("A","B").' ] raw_codegen = agentGenerator.CodeGenerator() agentGenerator.do_reasoning(additional_programs=rules, generator=raw_codegen) self.assertListEqual(sorted(str(raw_codegen).split()), exp) def test_class_type_fun_dependency(self) -> None: # This one covered the 'creates_in_body' with <'Type', 'Fun'>. exp = [ 'class("B")', 'creates_in_body("Fn","B")', 'funcs("Fn")', 'implements("B","A")', 'interface("A")', ] rules = [ 'type("B", "Fn").', 'symbols("A"; "B").', 'funcs("Fn").', 'extends_to("A","B").', ] raw_codegen = agentGenerator.CodeGenerator() agentGenerator.do_reasoning(additional_programs=rules, generator=raw_codegen) self.assertListEqual(sorted(str(raw_codegen).split()), exp) def test_interface_type_fun_dependency(self) -> None: # This one covered the 'has_parameter_and_argument' with <'Type', 'Fun'>. exp = [ 'class("B")', 'funcs("Fn")', 'has_parameter_and_argument("Fn","A","B")', 'implements("B","A")', 'interface("A")', ] rules = [ 'type("A", "Fn").', 'symbols("A"; "B").', 'funcs("Fn").', 'extends_to("A","B").', ] raw_codegen = agentGenerator.CodeGenerator() agentGenerator.do_reasoning(additional_programs=rules, generator=raw_codegen) self.assertListEqual(sorted(str(raw_codegen).split()), exp) def test_extends_dependency_with_rule_extraction(self) -> None: exp = [ 'add_method("A","foo")', 'add_method("B","foo")', 'class("B")', 'class("I")', 'extends("A","T")', 'extends("B","I")', 'implements("B","A")', 'interface("A")', 'interface("T")', ] deps = """\ Extends A -> Type B Extends I -> Type B Extends T -> Type A Method A::foo -> Type B Type A -> Type B Type I -> Type B Type T -> Type A, Type B """ raw_codegen = agentGenerator.CodeGenerator() # pyre-fixme[6]: For 1st param expected `List[str]` but got # `List[typing_extensions.LiteralString]`. additional_programs = agentGenerator.extract_logic_rules(deps.split("\n")) agentGenerator.do_reasoning( additional_programs=additional_programs, generator=raw_codegen ) self.assertListEqual(sorted(str(raw_codegen).split()), exp) class CodeEmittingTest(unittest.TestCase): def extract_run_and_compare( self, deps: str, exp: str, generator: agentGenerator.CodeGenerator ) -> None: additional_programs = agentGenerator.extract_logic_rules(deps.split("\n")) agentGenerator.do_reasoning( additional_programs=additional_programs, generator=generator ) self.assertEqual(str(generator), exp) def test_extends_dependency_hack_codegen(self) -> None: exp = """\ <?hh class B extends I implements A {} class I {} interface A extends T {} interface T {} """ rules = [ 'extends_to("A", "B").', 'extends_to("I", "B").', 'extends_to("T", "A").', 'symbols("A";"B";"I";"T").', ] hack_codegen = hackGenerator.HackCodeGenerator() agentGenerator.do_reasoning(additional_programs=rules, generator=hack_codegen) self.assertEqual(str(hack_codegen), exp) def test_extends_dependency_with_rule_extraction_hack_codegen(self) -> None: exp = """\ <?hh class B extends I implements A {} class I {} interface A extends T {} interface T {} """ deps = """\ Extends A -> Type B Extends I -> Type B Extends T -> Type A Type A -> Type B Type I -> Type B Type T -> Type A, Type B """ self.extract_run_and_compare(deps, exp, hackGenerator.HackCodeGenerator()) def test_method_and_extends_dependency_with_rule_extraction_hack_codegen_override( self, ) -> None: exp = """\ <?hh class B implements A { public function foo(): void{} } interface A { public function foo(): void; } """ deps = """\ Extends A -> Type B Method A::foo -> Type B Type A -> Type B """ self.extract_run_and_compare(deps, exp, hackGenerator.HackCodeGenerator()) def test_type_dependency_with_rule_extraction_hack_codegen(self) -> None: exp = """\ <?hh class A {} interface B { public function dummy_B_method(A $A_obj): void; } """ deps = """\ Type A -> Type B """ self.extract_run_and_compare(deps, exp, hackGenerator.HackCodeGenerator()) def test_only_method_dependency_with_rule_extraction_hack_codegen(self) -> None: exp = """\ <?hh class B { public function dummy_B_method(A $A_obj): void{ $A_obj->foo(); } } interface A { public function foo(): void; } """ deps = """\ Method A::foo -> Type B """ self.extract_run_and_compare(deps, exp, hackGenerator.HackCodeGenerator()) def test_smethod_dependency_with_rule_extraction_hack_codegen(self) -> None: exp = """\ <?hh class A implements I { public static function foo(): void{} } class T { public function dummy_T_method(A $A_obj): void{ A::foo(); } } interface I {} function B(): void { A::foo(); } function C(): void { A::foo(); } """ deps = """\ Extends I -> Type A SMethod A::foo -> Fun B, Fun C, Type T Type A -> Fun B, Fun C, Type T Type I -> Type A """ self.extract_run_and_compare(deps, exp, hackGenerator.HackCodeGenerator()) def test_function_with_rule_extraction_hack_codegen(self) -> None: exp = """\ <?hh class A implements I { public static function foo(): void{} public function dummy_A_method(): void{ F0(); } public function bar(): void{} } class B { public function dummy_B_method(A $A_obj): void{ F1(); } } class T { public function dummy_T_method(A $A_obj): void{ A::foo(); } } interface I { public function bar(): void; } function F0(): void { A::foo(); } function F1(): void { F0(); } """ deps = """\ Extends I -> Type A SMethod A::foo -> Fun F0, Type T Method I::bar -> Type A Fun F0 -> Fun F1, Type A Fun F1 -> Type B Type A -> Type B, Type T Type I -> Type A """ self.extract_run_and_compare(deps, exp, hackGenerator.HackCodeGenerator()) def test_function_class_with_rule_extraction_hack_codegen(self) -> None: exp = """\ <?hh class A extends I {} class I {} interface B { public function dummy_B_method(A $A_obj): void; } interface T { public function dummy_T_method(A $A_obj): void; } function F0(): void { $I_obj = new I(); } """ deps = """\ Extends I -> Type A Type A -> Type B, Type T Type I -> Type A, Fun F0 """ self.extract_run_and_compare(deps, exp, hackGenerator.HackCodeGenerator()) def test_function_interface_with_rule_extraction_hack_codegen(self) -> None: exp = """\ <?hh class A implements I { public static function foo(): void{} } class B { public function dummy_B_method(A $A_obj): void{ F1(); } } class T { public function dummy_T_method(A $A_obj): void{ A::foo(); } } interface I {} function F0(I $I_obj): void { A::foo(); } function F1(): void { $A_obj = new A(); F0($A_obj); } """ deps = """\ Extends I -> Type A SMethod A::foo -> Fun F0, Type T Fun F0 -> Fun F1 Fun F1 -> Type B Type A -> Type B, Type T Type I -> Type A, Fun F0 """ self.extract_run_and_compare(deps, exp, hackGenerator.HackCodeGenerator()) def test_function_interface_method_with_rule_extraction_hack_codegen(self) -> None: exp = """\ <?hh class A implements I { public static function foo(): void{} public function bar(): void{} } class B { public function dummy_B_method(): void{ $A_obj = new A(); F0($A_obj); } } class T { public function dummy_T_method(A $A_obj): void{ A::foo(); } } interface I { public function bar(): void; } function F0(I $I_obj): void { A::foo(); $I_obj->bar(); } """ deps = """\ Extends I -> Type A SMethod A::foo -> Fun F0, Type T Method I::bar -> Type A, Fun F0 Fun F0 -> Type B Type A -> Fun F0, Type T Type I -> Fun F0, Type A, Fun F0 """ self.extract_run_and_compare(deps, exp, hackGenerator.HackCodeGenerator()) def test_circular_type_method_dependency_with_rule_extraction_hack_codegen( self, ) -> None: exp = """\ <?hh class C implements Compare { public function dummy_C_method(C $C_obj): void{ $C_obj->content(); } public function content(): void{} public function eq(): void{} } interface Compare { public function dummy_Compare_method(C $C_obj): void; public function eq(): void; } """ deps = """\ Extends Compare -> Type C Method C::content -> Type C Method Compare::eq -> Type C Type C -> Type Compare Type Compare -> Type C """ self.extract_run_and_compare(deps, exp, hackGenerator.HackCodeGenerator()) class ReadFromFileTest(unittest.TestCase): def test_read(self) -> None: exp = [ 'extends_to("A", "B").', 'extends_to("I", "B").', 'extends_to("T", "A").', 'method("A", "foo", "B").', 'static_method("A", "bar", "B").', 'static_method("A", "bar", "F").', 'invoked_by("F", "A").', 'type("A", "B").', 'type("I", "B").', 'type("T", "A").', 'type("T", "B").', 'symbols("A";"B";"I";"T").', 'funcs("F").', ] deps = """\ Extends A -> Type B Extends I -> Type B Extends T -> Type A Method A::foo -> Type B SMethod A::bar -> Type B, Fun F Fun F -> Type A Type A -> Type B Type I -> Type B Type T -> Type A, Type B """ with tempfile.NamedTemporaryFile(mode="w") as fp: fp.write(deps) fp.flush() self.assertListEqual( exp, agentGenerator.extract_logic_rules( agentGenerator.read_from_file_or_stdin(fp.name) ), ) def test_non_exist(self) -> None: test_file = "non_exist.in" with self.assertRaises(expected_exception=FileNotFoundError): agentGenerator.extract_logic_rules( agentGenerator.read_from_file_or_stdin(test_file) ) class WriteToFileTest(unittest.TestCase): def test_hack_output(self) -> None: exp = """\ <?hh class C1 {} class C2 extends C1 implements I1 {} interface I1 {} """ generator = hackGenerator.HackCodeGenerator() generator._add_class("C1") generator._add_class("C2") generator._add_interface("I1") generator._add_extend("C2", "C1") generator._add_implement("C2", "I1") with tempfile.NamedTemporaryFile("r") as fp: agentGenerator.output_to_file_or_stdout(generator, fp.name) lines = fp.readlines() self.assertEqual("".join(lines), exp)
Python
hhvm/hphp/hack/test/hh_codesynthesis/agentgraphgenerator_test.py
#!/usr/bin/env python3 # pyre-strict # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the "hack" directory of this source tree. import unittest from typing import List from clingo.symbol import Number, Symbol from hphp.hack.src.hh_codesynthesis import agentGraphGenerator from hphp.hack.src.hh_codesynthesis.agentGraphGenerator import ( AgentGraphClingoContext, AgentGraphGenerator, ) class GeneratingAgentDistributionTest(unittest.TestCase): def test_single_level(self) -> None: exp = ["agents(0..2, 0)."] self.assertListEqual( exp, agentGraphGenerator.generating_agent_distribution([3]) ) def test_multiple_levels(self) -> None: exp = [ "agents(0..4, 0).", "agents(5..14, 1).", "agents(15..24, 2).", "agents(25..34, 3).", "agents(35..44, 4).", "agents(45..54, 5).", "agents(55..64, 6).", "agents(65..79, 7).", "agents(80..99, 8).", ] self.assertListEqual( exp, agentGraphGenerator.generating_agent_distribution( [5, 10, 10, 10, 10, 10, 10, 15, 20] ), ) def test_negative_distribution(self) -> None: # Given a distribution with non-positive number. with self.assertRaises( expected_exception=RuntimeError, msg="Agent distribution must have all positive integers.", ): agentGraphGenerator.generating_agent_distribution([2, -1, 3]) with self.assertRaises( expected_exception=RuntimeError, msg="Agent distribution must have all positive integers.", ): agentGraphGenerator.generating_agent_distribution([2, 0, 3]) class GeneratingAnAgentGraphTest(unittest.TestCase): def test_small_agent_graph(self) -> None: # We are creating an agent graph with three levels, each level # has 2, 4, 4 agents respectively. The minimum number of infra # agents are 2, the minimum number of product agents are 6. # The number of leaves in the graph are 5. And each agent type # has its profile to describe the relationship boundary. agent_graph_generator = AgentGraphGenerator( agent_distribution=[2, 4, 4], solving_context=AgentGraphClingoContext( number_of_leaves=5, number_of_infra_agents=2, number_of_product_agents=6, infra_agent_profile={"in_degree": [0, 10], "out_degree": [1, 10]}, product_agent_profile={"in_degree": [1, 10], "out_degree": [0, 5]}, ), ) agent_graph_generator.on_model = agent_graph_generator.generate agentGraphGenerator.generating_an_agent_graph(agent_graph_generator) self.assertTrue(agent_graph_generator.validate()) # Change product agent profile, expect a product agent to depend on at # least two other agents. agent_graph_generator.solving_context.product_agent_profile["in_degree"][0] = 2 agentGraphGenerator.generating_an_agent_graph(agent_graph_generator) self.assertTrue(agent_graph_generator.validate()) # Change the number of infra agents to 3, and customize a indegree lower # bound function, so that infra_agent(N), N > 2 must depend on infra_agent(0) # and infra_agent(1). agent_graph_generator.solving_context.number_of_infra_agents = 3 def customize_infra_agent_in_degree_low(agent: Number) -> Symbol: if agent.number < 2: return Number(0) else: return Number(2) def customize_validator( infra_agents: int, product_agents: int, in_degrees: List[int], out_degrees: List[int], ) -> bool: for agent_number, degree in enumerate(in_degrees): if agent_number in infra_agents and agent_number < 2 and degree > 0: return False if agent_number in infra_agents and agent_number >= 2 and degree > 2: return False return True agent_graph_generator.solving_context.infra_agent_in_degree_low = ( customize_infra_agent_in_degree_low ) agentGraphGenerator.generating_an_agent_graph(agent_graph_generator) self.assertTrue(agent_graph_generator.validate(customize_validator)) def test_unsatisfiable_parameters(self) -> None: # The total of infra agents + product agents are greater than sum(agent_distribution). agent_graph_generator = AgentGraphGenerator( agent_distribution=[2, 4, 4], solving_context=AgentGraphClingoContext( number_of_leaves=5, number_of_infra_agents=5, number_of_product_agents=6, infra_agent_profile={"in_degree": [0, 10], "out_degree": [1, 10]}, product_agent_profile={"in_degree": [1, 10], "out_degree": [0, 5]}, ), ) agent_graph_generator.on_model = agent_graph_generator.generate with self.assertRaises(expected_exception=RuntimeError, msg="Unsatisfiable."): agentGraphGenerator.generating_an_agent_graph(agent_graph_generator)
Python
hhvm/hphp/hack/test/hh_codesynthesis/cross_verify.py
#!/usr/bin/env/python3 # pyre-strict import argparse import glob import os import subprocess import tempfile from typing import Dict, List, Set class DependencyEdges(object): """A simple internal representation to categorize DependencyEdges""" edge_types = ["Extends", "Type", "Method", "SMethod", "Fun"] def __init__(self, lines: List[str]) -> None: super(DependencyEdges, self).__init__() self.objs: Dict[str, List[str]] = dict.fromkeys(self.edge_types, []) self.category_edges(lines) def category_edges(self, lines: List[str]) -> None: for line in lines: # Required input formatting to get "Extends A -> Type B, Type C, Type D". # And split get # lhs = "Extends A" # rhs = "Type B, Type C, Type D" # Skip the empty line at the end of the file. if not line: continue result = line.strip().split("->") (lhs, rhs) = result lhs = lhs.split() # The lhs length must be 2. if len(lhs) != 2: raise RuntimeError("Unexpected lhs.") # T94428437 Temporary skipping all built-in functions for now. if lhs[1].startswith("HH\\"): continue if lhs[0] in self.edge_types: self.objs[lhs[0]].append(line) def __le__(self, obj: "DependencyEdges") -> bool: for edges in self.edge_types: compare_result(set(self.objs[edges]), set(obj.objs[edges])) return True def compare_result(lhs: Set[str], rhs: Set[str]) -> None: if not lhs.issubset(rhs): RuntimeError("Unmatched lhs and rhs, expected lhs be a subset of rhs.") def invoke_sub_process(cmd: List[str], std_in: str) -> str: try: output = subprocess.check_output( cmd, stderr=None, cwd=".", universal_newlines=True, input=std_in, timeout=60.0, errors="replace", ) except subprocess.TimeoutExpired as e: output = "Timed out. " + str(e.output) except subprocess.CalledProcessError as e: # we don't care about nonzero exit codes... for instance, type # errors cause hh_single_type_check to produce them output = str(e.output) return output # Cross verify the hh_codesynthesis binary produce the Hack code has identical # dependency graph as the sample Hack code. def cross_verify(args: argparse.Namespace, file_name: str) -> bool: # 0. Skip unsupported cases for now. (ToDo: T92593014) if os.path.exists(file_name + ".skip_synthesis_tests"): return True # 1. Invoke hh_simple_type_checker to produce a dependency graph on sample. with tempfile.NamedTemporaryFile(mode="w") as fp: tmp_file_name = fp.name cmd = [ args.typechecker, file_name, "--dump-deps", "--no-builtins", ] dep_graph = invoke_sub_process(cmd, "") # 2. Invoke hh_codesynthesis binary to produce a Hack code given dep_graph. cmd = [ args.synthesis, "--target_lang=hack", f"--output_file={tmp_file_name}", ] invoke_sub_process(cmd, dep_graph) # 3. Invoke hh_simple_type_checker on cmd = [ args.typechecker, f"{tmp_file_name}", "--dump-deps", "--no-builtins", ] dep_output = invoke_sub_process(cmd, "") # 4. Compare the dep_graph with dep_output. dep_graph = dep_graph.replace(",\n", ",").split("\n") original_extends_edges = DependencyEdges(dep_graph) dep_output = dep_output.replace(",\n", ",").split("\n") generate_extends_edges = DependencyEdges(dep_output) return original_extends_edges <= generate_extends_edges # Cross verify the hh_codesynthesis binary produce the Hack code has identical # dependency graph as the sample parameters. def cross_verify_with_parameters(args: argparse.Namespace) -> bool: with tempfile.NamedTemporaryFile(mode="w") as fp: tmp_file_name = fp.name # 0. Invoke hh_codesynthesis binary to produce a Hack code from parameters. cmd = [ args.synthesis, "--target_lang=hack", "--n=12", "--avg_width=3", "--min_classes=3", "--min_interfaces=4", "--lower_bound=1", "--higher_bound=5", "--min_depth=0", f"--output_file={tmp_file_name}", ] invoke_sub_process(cmd, "") # 1. Reuse cross_verify using tmp_file_name as input. return cross_verify(args, tmp_file_name) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("test_path", help="A file or a directory. ") parser.add_argument("--typechecker", type=os.path.abspath) parser.add_argument("--synthesis", type=os.path.abspath) args: argparse.Namespace = parser.parse_args() # Cross verify synthesized from given raph. for file_name in glob.glob(args.test_path + "/*.php"): cross_verify(args, file_name) # Cross verify synthesized from parameters. cross_verify_with_parameters(args)
Python
hhvm/hphp/hack/test/hh_codesynthesis/hackgenerator_test.py
#!/usr/bin/env python3 # pyre-strict # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the "hack" directory of this source tree. import unittest from hphp.hack.src.hh_codesynthesis.hackGenerator import ( _HackClassGenerator, _HackFunctionGenerator, _HackInterfaceGenerator, HackCodeGenerator, ) class _HackInterfaceGeneratorTest(unittest.TestCase): def setUp(self) -> None: self.obj = _HackInterfaceGenerator("I0") def test_single_interface(self) -> None: self.assertEqual("interface I0 {}", str(self.obj)) def test_multiple_extends_interface(self) -> None: self.obj.add_extend("I1") self.assertEqual("interface I0 extends I1 {}", str(self.obj)) self.obj.add_extend("I2") self.assertEqual("interface I0 extends I1,I2 {}", str(self.obj)) def test_single_method_interface(self) -> None: self.obj.add_method("foo") self.assertEqual( "interface I0 {\npublic function foo(): void;\n}", str(self.obj) ) def test_multiple_methods_interface(self) -> None: self.obj.add_method("foo") self.obj.add_method("bar") self.assertEqual( "interface I0 {\npublic function bar(): void;\n\npublic function foo(): void;\n}", str(self.obj), ) def test_single_parameter_dummy_method_interface(self) -> None: self.obj.add_parameter("C0") self.assertEqual( "interface I0 {\npublic function dummy_I0_method(C0 $C0_obj): void;\n}", str(self.obj), ) def test_multiple_parameters_dummy_method_interface(self) -> None: self.obj.add_parameter("C0") self.obj.add_parameter("C1") self.assertEqual( "interface I0 {\npublic function dummy_I0_method(C0 $C0_obj, C1 $C1_obj): void;\n}", str(self.obj), ) class _HackClassGeneratorTest(unittest.TestCase): def setUp(self) -> None: self.obj = _HackClassGenerator("C0") def test_single_class(self) -> None: self.assertEqual("class C0 {}", str(self.obj)) def test_multiple_implements_interface(self) -> None: self.obj.add_implement("I1") self.assertEqual("class C0 implements I1 {}", str(self.obj)) self.obj.add_implement("I2") self.assertEqual("class C0 implements I1,I2 {}", str(self.obj)) def test_single_extend_class_multiple_implements_interface(self) -> None: self.obj.add_implement("I1") self.assertEqual("class C0 implements I1 {}", str(self.obj)) self.obj.set_extend("C1") self.assertEqual("class C0 extends C1 implements I1 {}", str(self.obj)) self.obj.add_implement("I2") self.assertEqual("class C0 extends C1 implements I1,I2 {}", str(self.obj)) # invoke set_extend again, will overwrite the previous "C1" self.obj.set_extend("C2") self.assertEqual("class C0 extends C2 implements I1,I2 {}", str(self.obj)) def test_single_method_class(self) -> None: self.obj.add_method("bar") self.assertEqual( "class C0 {\npublic function bar(): void{}\n}", str(self.obj) ) def test_multiple_methods_class(self) -> None: self.obj.add_method("bar") self.obj.add_method("foo") self.assertEqual( "class C0 {\npublic function bar(): void{}\n\npublic function foo(): void{}\n}", str(self.obj), ) def test_single_static_method_class(self) -> None: self.obj.add_static_method("bar") self.assertEqual( "class C0 {\npublic static function bar(): void{}\n}", str(self.obj) ) def test_multiple_static_methods_class(self) -> None: self.obj.add_static_method("bar") self.obj.add_static_method("foo") self.assertEqual( "class C0 {\npublic static function bar(): void{}\n\npublic static function foo(): void{}\n}", str(self.obj), ) def test_single_parameter_dummy_method_class(self) -> None: self.obj.add_parameter("C1") self.assertEqual( "class C0 {\npublic function dummy_C0_method(C1 $C1_obj): void{}\n}", str(self.obj), ) def test_multiple_parameters_dummy_method_class(self) -> None: self.obj.add_parameter("C2") self.obj.add_parameter("C1") self.assertEqual( "class C0 {\npublic function dummy_C0_method(C1 $C1_obj, C2 $C2_obj): void{}\n}", str(self.obj), ) def test_invoke_single_parameter_in_dummy_method_class(self) -> None: self.obj.add_parameter("C1") self.obj.add_invoke("C1", "foo") self.assertEqual( "class C0 {\npublic function dummy_C0_method(C1 $C1_obj): void{\n$C1_obj->foo();\n}\n}", str(self.obj), ) def test_invoke_static_method_in_dummy_method_class(self) -> None: # T95861944 Beautify the syntheisized code by removing "C1" from the parameter self.obj.add_parameter("C1") self.obj.add_invoke_static_method("C1", "foo") self.assertEqual( "class C0 {\npublic function dummy_C0_method(C1 $C1_obj): void{\nC1::foo();\n}\n}", str(self.obj), ) def test_invoke_single_function_in_dummy_method_class(self) -> None: fn_obj = _HackFunctionGenerator("F0") self.obj.add_invoke_function(fn_obj) self.assertEqual( "class C0 {\npublic function dummy_C0_method(): void{\nF0();\n}\n}", str(self.obj), ) def test_invoke_multiple_functions_in_dummy_method_class(self) -> None: fn_obj0 = _HackFunctionGenerator("F0") fn_obj1 = _HackFunctionGenerator("F1") self.obj.add_invoke_function(fn_obj1) self.obj.add_invoke_function(fn_obj0) self.assertEqual( "class C0 {\npublic function dummy_C0_method(): void{\nF0();\n\nF1();\n}\n}", str(self.obj), ) def test_invoke_multiple_parameters_in_dummy_method_class(self) -> None: self.obj.add_parameter("C2") self.obj.add_parameter("C1") self.obj.add_invoke("C2", "foo") self.obj.add_invoke("C1", "foo") self.obj.add_invoke("C2", "bar") self.assertEqual( "class C0 {\npublic function dummy_C0_method(C1 $C1_obj, C2 $C2_obj): void{\n$C1_obj->foo();\n\n$C2_obj->bar();\n\n$C2_obj->foo();\n}\n}", str(self.obj), ) class _HackFunctionGeneratorTest(unittest.TestCase): def setUp(self) -> None: self.obj = _HackFunctionGenerator("F0") def test_invoke_static_method(self) -> None: self.obj.add_invoke_static_method("C0", "foo") self.assertEqual( "function F0(): void {\nC0::foo();\n}", str(self.obj), ) def test_invoke_function(self) -> None: fn_obj = _HackFunctionGenerator("F1") self.obj.add_invoke_function(fn_obj) self.assertEqual( "function F0(): void {\nF1();\n}", str(self.obj), ) class HackCodeGeneratorTest(unittest.TestCase): def setUp(self) -> None: self.obj = HackCodeGenerator() def test_single_class(self) -> None: exp = """\ <?hh class C0 {} """ self.obj._add_class("C0") self.assertEqual(exp, str(self.obj)) def test_single_interface(self) -> None: exp = """\ <?hh interface I0 {} """ self.obj._add_interface("I0") self.assertEqual(exp, str(self.obj)) def test_mix_single_class_and_interface(self) -> None: exp = """\ <?hh class C0 {} interface I0 {} """ self.obj._add_class("C0") self.obj._add_interface("I0") self.assertEqual(exp, str(self.obj)) def test_class_extends_class_implements_interface(self) -> None: exp = """\ <?hh class C0 {} class C1 extends C0 implements I1,I2 {} interface I0 {} interface I1 extends I0 {} interface I2 {} """ self.obj._add_class("C0") self.obj._add_class("C1") self.obj._add_interface("I0") self.obj._add_interface("I1") self.obj._add_interface("I2") self.obj._add_extend("C1", "C0") self.obj._add_extend("I1", "I0") self.obj._add_implement("C1", "I1") self.obj._add_implement("C1", "I2") self.assertEqual(exp, str(self.obj)) def test_class_implements_interface_with_method_override(self) -> None: exp = """\ <?hh class C0 implements I0 { public function foo(): void{} } interface I0 { public function foo(): void; } """ self.obj._add_class("C0") self.obj._add_interface("I0") self.obj._add_implement("C0", "I0") self.obj._add_method("I0", "foo") self.obj._add_method("C0", "foo") self.assertEqual(exp, str(self.obj)) def test_class_extends_class_with_method_override(self) -> None: exp = """\ <?hh class C0 extends C1 { public function foo(): void{} } class C1 { public function foo(): void{} } """ self.obj._add_class("C0") self.obj._add_class("C1") self.obj._add_extend("C0", "C1") self.obj._add_method("C1", "foo") self.obj._add_method("C0", "foo") self.assertEqual(exp, str(self.obj)) def test_interface_extends_interface_with_method_override(self) -> None: exp = """\ <?hh interface I0 extends I1 { public function bar(): void; } interface I1 { public function bar(): void; } """ self.obj._add_interface("I0") self.obj._add_interface("I1") self.obj._add_extend("I0", "I1") self.obj._add_method("I1", "bar") self.obj._add_method("I0", "bar") self.assertEqual(exp, str(self.obj)) def test_interface_passed_as_parameter_to_class(self) -> None: exp = """\ <?hh class C0 { public function dummy_C0_method(I0 $I0_obj): void{} } interface I0 {} """ self.obj._add_interface("I0") self.obj._add_class("C0") self.obj._add_to_parameter_set("C0", "I0") self.assertEqual(exp, str(self.obj)) def test_naming_conflict_with_dummy_method(self) -> None: exp = """\ <?hh class C0 { public function dummy_C0_method_(I0 $I0_obj): void{} public function dummy_C0_method(): void{} } interface I0 {} """ self.obj._add_interface("I0") self.obj._add_class("C0") self.obj._add_method("C0", "dummy_C0_method") self.obj._add_to_parameter_set("C0", "I0") self.assertEqual(exp, str(self.obj)) def test_class_with_method_passed_as_parameter_to_another_class(self) -> None: exp = """\ <?hh class C1 { public function foo(): void{} } class C0 { public function dummy_C0_method(C1 $C1_obj): void{ $C1_obj->foo(); } } """ self.obj._add_class("C1") self.obj._add_method("C1", "foo") self.obj._add_class("C0") self.obj._add_to_parameter_set("C0", "C1") self.obj._add_invoke("C0", "C1", "foo") self.assertEqual(exp, str(self.obj)) def test_class_with_static_method_invoked_by_another_class_and_function( self, ) -> None: exp = """\ <?hh class C1 { public static function foo(): void{} } class C0 { public function dummy_C0_method(C1 $C1_obj): void{ C1::foo(); } } function F0(): void { C1::foo(); } """ self.obj._add_class("C1") self.obj._add_static_method("C1", "foo") self.obj._add_class("C0") self.obj._add_to_parameter_set("C0", "C1") self.obj._add_invoke_static_method("C0", "C1", "foo") self.obj._add_function("F0") self.obj._add_invoke_static_method("F0", "C1", "foo") self.assertEqual(exp, str(self.obj)) def test_class_with_function_invoked_by_another_class_and_function( self, ) -> None: exp = """\ <?hh class C0 { public function dummy_C0_method(): void{ F0(); } } function F0(): void {} function F1(): void { F0(); } """ self.obj._add_function("F0") self.obj._add_function("F1") self.obj._add_class("C0") self.obj._add_invoke_function("C0", "F0") self.obj._add_invoke_function("F1", "F0") self.assertEqual(exp, str(self.obj)) def test_function_creates_an_object_of_another_class( self, ) -> None: exp = """\ <?hh class C0 { public function foo(): void{} } function F0(): void { $C0_obj = new C0(); $C0_obj->foo(); } """ self.obj._add_function("F0") self.obj._add_class("C0") self.obj._add_method("C0", "foo") self.obj._add_object_in_function("F0", "C0") self.obj._add_invoke_in_function("F0", "C0", "foo") self.assertEqual(exp, str(self.obj)) def test_function_creates_an_object_invokes_another_function_has_an_interface( self, ) -> None: exp = """\ <?hh class C0 implements I0 { public function foo(): void{} } interface I0 { public function foo(): void; } function F0(I0 $I0_obj): void { $I0_obj->foo(); } function F1(): void { $C0_obj = new C0(); F0($C0_obj); } """ self.obj._add_function("F0") self.obj._add_function("F1") self.obj._add_class("C0") self.obj._add_interface("I0") self.obj._add_method("I0", "foo") self.obj._add_implement("C0", "I0") self.obj._add_method("C0", "foo") self.obj._add_invoke_function("F1", "F0") self.obj._add_parameter_to_function("F0", "I0", "C0") self.obj._add_invoke_in_function("F0", "I0", "foo") self.assertEqual(exp, str(self.obj))