language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
PHP | hhvm/hphp/hack/test/integration/data/holes/call_unpack.php | <?hh
function g(float $x, varray<int> $y, int ...$ys): void {}
function call_unpack((int, float, int, float, int, float) $packed,):void {
/* HH_FIXME[4110] */
g(...$packed);
} |
PHP | hhvm/hphp/hack/test/integration/data/holes/member_call_multiple.php | <?hh
class C {
private static function f(int $x, vec<int> $y): void {}
public static function call_multiple(bool $x, vec<bool> $y): void {
/* HH_FIXME[4110] */
self::f($x,$y);
}
} |
PHP | hhvm/hphp/hack/test/integration/data/holes/return_and_fn_arg.php | <?hh
function return_and_fn_arg(string $x): float {
/* HH_FIXME[4110] */
return return_int($x);
} |
PHP | hhvm/hphp/hack/test/integration/data/holes/return_expr_only.php | <?hh
function return_float(bool $x): float {
/* HH_FIXME[4110] */
return return_int($x);
}
function return_int(bool $x): int {
if ($x) {
return 1;
} else {
return 0;
}
} |
PHP | hhvm/hphp/hack/test/integration/data/implicit_pess_repo/foo_enum.php | <?hh
enum MyEnum: string as string {
A = "A";
}
class MyClass {
public function h(): MyEnum {
return MyEnum::A;
}
}
function top(): void {
$x = new MyClass();
$y = $x->h();
} |
hhvm/hphp/hack/test/integration/data/lsp_exchanges/.hhconfig | # some comment
assume_php = false
auto_namespace_map = {"Herp": "Derp\\Lib\\Herp"}
disable_xhp_element_mangling=false
allowed_fixme_codes_strict = 4110 |
|
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/all_optional_params_completion.php | <?hh
function completion_area_allopt(MyFooCompletionOptional $mfc): void {
}
class MyFooCompletionOptional {
public function doStuff(int $x = 0, int $y = 0): void {}
} |
hhvm/hphp/hack/test/integration/data/lsp_exchanges/bad_call.expected | [
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32002,
"message": "Server not yet initialized"
}
},
{
"jsonrpc": "2.0",
"id": 99,
"result": null
}
] |
|
JSON | hhvm/hphp/hack/test/integration/data/lsp_exchanges/bad_call.json | [
{
"jsonrpc": "2.0",
"id": 1,
"method": "textDocument/didOpen",
"params": {
"textDocument": {
"uri":"${php_file_uri}",
"languageId": "hack",
"version":1,
"text":"${php_file}"
}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForHhServerReady",
"params": {}
},
{
"jsonrpc": "2.0",
"id": 99,
"method": "shutdown",
"params": {}
}
] |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/bad_call.php | <?hh //strict
function a_bad_call(): int {
return b_bad_call();
}
function b_bad_call(): int {
return 42;
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/code_action_missing_method.php | <?hh
class ClassWithFooBar {
public function foobar(): void {}
}
function call_method(ClassWithFooBar $mc): void {
$mc->foobar();
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/completion.php | <?hh //strict
function testing_area(): void {
}
/** test_function docblock. */
function test_function(): void {
}
interface CompletionInterface {
/** Doc block should fall back to interface. */
public function interfaceDocBlockMethod(): void;
}
class CompletionClass {
public function interfaceDocBlockMethod(): void {}
}
function testing_area_for_shapes(): void {
$point1 = shape('x' => -3, 'y' => 6);
}
function call_lambda(int $n, (function(int): int) $param): void {
$param($n);
}
function testing_area_for_lambdas(): void {
$mylambda = ($n) ==> $n * 5;
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/completion_extras.php | <?hh //strict
enum Elsa: string {
Alonso = "hello";
Bard = "world";
}
final class DeprecatedClass {
public static function getName(): void {}
public static function __getLoader(): void {}
public static function getAttributes_DO_NOT_USE(): void {}
public static function test_do_not_use(): void {}
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/coverage.php | <?hh
function f(X $x): void {
$id = $x->getID();
}
class X {
public function getID() : int { return 42; }
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/definition.php | <?hh //strict
function a_definition(): int {
return b_definition();
}
function b_definition(): int {
return 42;
}
class BB {
public function __construct(int $i) {}
}
class CC extends BB {
}
class DD extends CC {
}
class EE extends DD {
public function __construct() {
parent::__construct(1);
}
}
class FF {}
function test(): void {
$bb = new BB(1); // should go to B::__construct
$cc = new CC(1); // should offer choice B::__construct or C
$dd = new DD(1); // should offer choice B::__construct or D
$ee = new EE(); // should go to E::__construct
$ff = new FF(); // should go to F
}
class TakesString {
public function __construct(string $s) {}
}
class HasString {
const MyString = "myString";
}
function testClassMemberInsideConstructorInvocation(): void {
$x = new TakesString(HasString::MyString);
}
class MyEnumClassKind {}
enum class MyEnumClass : MyEnumClassKind {
MyEnumClassKind First = new MyEnumClassKind();
MyEnumClassKind Second = new MyEnumClassKind();
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/didchange.php | <?hh //strict
function a_didchange(): int {
return b_didchange();
}
function b_didchange(): int {
return 42;
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/go_to_implementation.php | <?hh // strict
abstract class Foo {
public function test(): string {
return "a";
}
}
class Bar extends Foo {
public function test(): string {
return "b";
}
}
interface IFoo {
public static function test(Foo $f): string;
}
class Baz implements IFoo {
final public static function test(Foo $f): string {
return $f->test();
}
}
trait BaseTrait {
public static function test(): string {
return "c";
}
}
trait ChildTrait {
use BaseTrait;
final public static function test(): string {
return "d";
}
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/highlight.php | <?hh //strict
function a_highlight(): int {
return b_highlight();
}
function b_highlight(): int {
return 42;
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/hover.php | <?hh //strict
// comment
function a_hover(): int {
return b_hover();
}
// A comment describing b_hover.
function b_hover(): int {
return 42;
}
// A comment describing THE_ANSWER
const int THE_ANSWER = 42;
function return_the_answer(): int {
return THE_ANSWER;
}
// comment describing the "pad_left" function and its parameters
function pad_left(string $s, int $i, string $pad): string {
return $s;
}
// comment describing "return_a_string" function
function return_a_string(): string {
$pad = "hello";
$x = pad_left("StringToPad", 20, $pad);
return $x;
}
// Copyright 2004-present Facebook. All Rights Reserved.
// Testing copyright removal
final class CopyrightClass {
public static function copyrightMethod(): void {}
}
function testing_copyright_autocomplete(): void {
CopyrightClass::copyrightMethod();
}
/**
* This file is generated. Do not modify it manually!
*
* This file was generated by:
* scripts/xcontroller/gencode XIndiaFreeFBPetitionController
* If there is a merge conflict, run
* scripts/xcontroller/gencode XIndiaFreeFBPetitionController --merge
*
* For codegen logic, refer to XControllerCodegenScript.
*
* @generated SignedSource<<foo>>
*/
// Testing generated text removal
final class GeneratedClass {
public static function generatedMethod(): void {}
}
function testing_generated_autocomplete(): void {
GeneratedClass::generatedMethod();
}
function test_xhp_attribute(): void {
<xhp:enum-attribute name="abc" enum-attribute={MyEnum::TYPE_A} />;
<xhp:generic id={EntSomething::getId()} />;
}
// An empty space to add text with textDocument/didChange notifications
// for testing hover on incomplete/uncompilable hack.
function testing_area_hover(): void {
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/hover_with_errors.php | <?hh //strict
class HoverWithErrorsClass {
/** Constructor with doc block */
public function __construct() {}
/**
* During testing, we'll remove the "public" tag from this method
* to ensure that we can still get IDE services
*/
public static function staticMethod(string $z): void {}
/** Static method with doc block */
public function instanceMethod(int $x1, int $x2): void {
HoverWithErrorsClass::staticMethod("Hello");
}
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/incremental_derived.php | <?hh // strict
class DerivedClassIncremental extends BaseClassIncremental {
public function bar(): string { return ''; }
}
function uses_base(DerivedClassIncremental $derived): void {
$derived->foo();
} |
hhvm/hphp/hack/test/integration/data/lsp_exchanges/initialize_shutdown.expected | [
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"capabilities": {
"textDocumentSync": {
"openClose": true,
"change": 2,
"willSave": false,
"willSaveWaitUntil": true,
"save": {
"includeText": false
}
},
"hoverProvider": true,
"completionProvider": {
"resolveProvider": true,
"triggerCharacters": [
"$",
">",
"\\",
":",
"<",
"[",
"'",
"\"",
"{",
"#"
]
},
"signatureHelpProvider": {
"triggerCharacters": [
"(",
","
]
},
"definitionProvider": true,
"typeDefinitionProvider": true,
"referencesProvider": true,
"documentHighlightProvider": true,
"documentSymbolProvider": true,
"workspaceSymbolProvider": true,
"codeActionProvider": {
"resolveProvider": true
},
"documentFormattingProvider": true,
"documentRangeFormattingProvider": true,
"documentOnTypeFormattingProvider": {
"firstTriggerCharacter": ";",
"moreTriggerCharacter": [
"}"
]
},
"renameProvider": true,
"implementationProvider": true,
"rageProvider": true,
"experimental": {"snippetTextEdit": true}
}
}
},
{
"jsonrpc": "2.0",
"id": 2,
"result": null
}
] |
|
JSON | hhvm/hphp/hack/test/integration/data/lsp_exchanges/initialize_shutdown.json | [
{
"jsonrpc":"2.0",
"id": 1,
"method":"initialize",
"params": {
"initializeOptions": {},
"processId": null,
"rootPath": "${root_path}",
"capabilities": {}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForHhServerReady",
"params": {}
},
{
"jsonrpc":"2.0",
"id": 2,
"method":"shutdown",
"params": {}
}
] |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/messy.php | <?hh //strict
function x(): string {
$a = "this";
$b = "is";
$c = "messy";
$d = ".";
return "$a" . "$b" . "$c" . "d";
} |
hhvm/hphp/hack/test/integration/data/lsp_exchanges/nomethod.expected | [
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"capabilities": {
"textDocumentSync": {
"openClose": true,
"change": 2,
"willSave": false,
"willSaveWaitUntil": true,
"save": {
"includeText": false
}
},
"hoverProvider": true,
"completionProvider": {
"resolveProvider": true,
"triggerCharacters": [
"$",
">",
"\\",
":",
"<",
"[",
"'",
"\"",
"{",
"#"
]
},
"signatureHelpProvider": {
"triggerCharacters": [
"(",
","
]
},
"definitionProvider": true,
"typeDefinitionProvider": true,
"referencesProvider": true,
"documentHighlightProvider": true,
"documentSymbolProvider": true,
"workspaceSymbolProvider": true,
"codeActionProvider": {
"resolveProvider": true
},
"documentFormattingProvider": true,
"documentRangeFormattingProvider": true,
"documentOnTypeFormattingProvider": {
"firstTriggerCharacter": ";",
"moreTriggerCharacter": [
"}"
]
},
"renameProvider": true,
"implementationProvider": true,
"rageProvider": true,
"experimental": {
"snippetTextEdit": true
}
}
}
},
{
"jsonrpc": "2.0",
"id": 2,
"error": {
"code": -32601,
"message": "not implemented: textDocument/nonExistingMethod"
}
},
{
"jsonrpc": "2.0",
"id": 3,
"result": null
}
] |
|
JSON | hhvm/hphp/hack/test/integration/data/lsp_exchanges/nomethod.json | [
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params":
{
"initializationOptions":{},
"processId":null,
"rootPath":"${root_path}",
"capabilities":{}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForHhServerReady",
"params": {}
},
{
"jsonrpc": "2.0",
"method": "textDocument/didOpen",
"params": {
"textDocument": {
"uri":"${php_file_uri}",
"languageId": "hack",
"version":1,
"text":"${php_file}"
}
}
},
{
"jsonrpc": "2.0",
"method": "textDocument/nonExistingMethod",
"id": 2,
"params": {
"textDocument": {
"uri":"${php_file_uri}"
},
"position": {"line": 3, "character": 10}
}
},
{
"jsonrpc": "2.0",
"id": 3,
"method": "shutdown",
"params": {}
}
] |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/nomethod.php | <?hh //strict
function a_nomethod(): int {
return b_nomethod();
}
function b_nomethod(): int {
return 42;
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/non_blocking.php | <?hh // strict
function non_blocking_definition(): int {
return 4;
}
function non_blocking(): int {
return non_blocking_definition();
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/ontypeformatting.php | <?hh
function test_otf(mixed ...$_): void {
}
function otf_1(): void {
test_otf(
'1234567890',
'1234567890',
'1234567890','1234567890', '1234567890','1234567890'); // 11: Format on ";"
}
function otf(): void {} // 13: Format on "}" |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/optional_param_completion.php | <?hh
function completion_area(MyFooCompletion $mfc): void {
}
class MyFooCompletion {
public function doStuff(int $x, int $y = 0): void {}
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/override.php | <?hh
class MyParent {
public function foo(): void {}
}
trait MyTrait {
public function foo(): void {}
}
class MyChild extends MyParent {
use MyTrait;
<<__Override>>
public function foo(): void {} // MyTrait should win over MyParent
}
class C1 {
public static function bar(): void {}
}
class C2 extends C1 {
<<__Override>>
public static function bar(): void {}
}
class C3 extends C2 {
<<__Override>>
public static function bar(): void {} // Immediate parent should win.
}
interface I1 {
public function quux(): void;
}
interface I2 extends I1 {
<<__Override>>
public function quux(): void;
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/references.php | <?hh
class C {
private function ref_test_1 (int $x): void { // Should match
$y = $x; // Should not match
//static $x = 123;
$z = $x; // Request ID 11: Looking for this $x // Should match
}
public function ref_test_method(): int {
return 0;
}
}
interface IRefTestRequireExtends {
require extends C;
}
function ref_test_require_extends(IRefTestRequireExtends $req_extends_test): void {
$req_extends_test->ref_test_method(); // Request ID 12
}
function j(int $x): int {
return $x;
}
function h(string $x): int {
return 5;
}
enum RefTestEnum: int { // Request ID 14 on RefTestEnum
SMALL = 0;
MEDIUM = 1;
LARGE = 2;
}
function ref_test_2(int $x): void { // Should match
$x = 3; // Request ID 13: Looking for this $x // Should match
j($x) + $x + h("\$x = $x"); // First, second, and fourth should match
$lambda1 = $x ==> $x + 1; // Should not match
$lambda2 = $a ==> $x + $a; // Should match
$lambda3 = function($x) { // Should not match
return $x + 1; }; // Should not match
$lambda4 = function($b) use($x) { // Should match
return $x + $b; }; // Should match
$size = RefTestEnum::SMALL;
$shape = shape(RefTestEnum::SMALL => 123);
} |
hhvm/hphp/hack/test/integration/data/lsp_exchanges/references_client_cancel.expected | [
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"capabilities": {
"textDocumentSync": {
"openClose": true,
"change": 2,
"willSave": false,
"willSaveWaitUntil": true,
"save": {
"includeText": false
}
},
"hoverProvider": true,
"completionProvider": {
"resolveProvider": true,
"triggerCharacters": [
"$",
">",
"\\",
":",
"<",
"[",
"'",
"\"",
"{",
"#"
]
},
"signatureHelpProvider": {
"triggerCharacters": [
"(",
","
]
},
"definitionProvider": true,
"typeDefinitionProvider": true,
"referencesProvider": true,
"documentHighlightProvider": true,
"documentSymbolProvider": true,
"workspaceSymbolProvider": true,
"codeActionProvider": {
"resolveProvider": true
},
"documentFormattingProvider": true,
"documentRangeFormattingProvider": true,
"documentOnTypeFormattingProvider": {
"firstTriggerCharacter": ";",
"moreTriggerCharacter": [
"}"
]
},
"renameProvider": true,
"implementationProvider": true,
"rageProvider": true,
"experimental": {
"snippetTextEdit": true
}
}
}
},
{
"powered_by": "serverless_ide",
"jsonrpc": "2.0",
"id": 11,
"result": [
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 36,
"character": 9
},
"end": {
"line": 36,
"character": 19
}
},
"title": "ref_test_2"
}
]
},
{
"powered_by": "serverless_ide",
"jsonrpc": "2.0",
"id": 13,
"result": [
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 36,
"character": 9
},
"end": {
"line": 36,
"character": 19
}
},
"title": "ref_test_2"
}
]
},
{
"jsonrpc": "2.0",
"id": 12,
"error": {
"code": -32800,
"message": "Unix.WSIGNALED -7"
}
},
{
"jsonrpc": "2.0",
"id": 999,
"result": null
}
] |
|
JSON | hhvm/hphp/hack/test/integration/data/lsp_exchanges/references_client_cancel.json | [
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"initializationOptions": {
"delayUntilDoneInit": true
},
"processId": null,
"rootPath": "${root_path}",
"capabilities": {}
}
},
{
"jsonrpc": "2.0",
"method": "textDocument/didOpen",
"params": {
"textDocument": {
"uri": "${php_file_uri}",
"languageId": "hack",
"version": 1,
"text": "${php_file}"
}
}
},
{
"jsonrpc": "2.0",
"id": 11,
"method": "textDocument/definition",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 36,
"character": 15
}
}
},
{
"jsonrpc": "2.0",
"id": 12,
"method": "textDocument/references",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 36,
"character": 15
},
"context": {
"includeDeclaration": false
}
}
},
{
"jsonrpc": "2.0",
"id": 13,
"method": "textDocument/definition",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 36,
"character": 15
}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 13
}
},
{
"jsonrpc": "2.0",
"method": "$/cancelRequest",
"params": {
"id": 12
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 12
}
},
{
"jsonrpc": "2.0",
"id": 999,
"method": "shutdown",
"params": {}
},
{
"jsonrpc": "2.0",
"method": "exit",
"params": {}
}
] |
hhvm/hphp/hack/test/integration/data/lsp_exchanges/references_no_server.expected | [
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"capabilities": {
"textDocumentSync": {
"openClose": true,
"change": 2,
"willSave": false,
"willSaveWaitUntil": true,
"save": {
"includeText": false
}
},
"hoverProvider": true,
"completionProvider": {
"resolveProvider": true,
"triggerCharacters": [
"$",
">",
"\\",
":",
"<",
"[",
"'",
"\"",
"{",
"#"
]
},
"signatureHelpProvider": {
"triggerCharacters": [
"(",
","
]
},
"definitionProvider": true,
"typeDefinitionProvider": true,
"referencesProvider": true,
"documentHighlightProvider": true,
"documentSymbolProvider": true,
"workspaceSymbolProvider": true,
"codeActionProvider": {
"resolveProvider": true
},
"documentFormattingProvider": true,
"documentRangeFormattingProvider": true,
"documentOnTypeFormattingProvider": {
"firstTriggerCharacter": ";",
"moreTriggerCharacter": [
"}"
]
},
"renameProvider": true,
"implementationProvider": true,
"rageProvider": true,
"experimental": {
"snippetTextEdit": true
}
}
}
},
{
"jsonrpc": "2.0",
"id": 11,
"error": {
"code": -32603,
"message": "Error: no hh_server running. Either start hh_server yourself or run hh_client without --autostart-server false\nUnix.WEXITED 6"
}
},
{
"jsonrpc": "2.0",
"id": 999,
"result": null
}
] |
|
JSON | hhvm/hphp/hack/test/integration/data/lsp_exchanges/references_no_server.json | [
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"initializationOptions": {
"delayUntilDoneInit": true
},
"processId": null,
"rootPath": "${root_path}",
"capabilities": {}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForHhServerReady",
"params": {}
},
{
"jsonrpc": "2.0",
"method": "textDocument/didOpen",
"params": {
"textDocument": {
"uri": "${php_file_uri}",
"languageId": "hack",
"version": 1,
"text": "${php_file}"
}
}
},
{
"jsonrpc": "2.0",
"id": 11,
"method": "textDocument/references",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 36,
"character": 15
},
"context": {
"includeDeclaration": false
}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 11
}
},
{
"jsonrpc": "2.0",
"id": 999,
"method": "shutdown",
"params": {}
},
{
"jsonrpc": "2.0",
"method": "exit",
"params": {}
}
] |
hhvm/hphp/hack/test/integration/data/lsp_exchanges/references_ok.expected | [
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"capabilities": {
"textDocumentSync": {
"openClose": true,
"change": 2,
"willSave": false,
"willSaveWaitUntil": true,
"save": {
"includeText": false
}
},
"hoverProvider": true,
"completionProvider": {
"resolveProvider": true,
"triggerCharacters": [
"$",
">",
"\\",
":",
"<",
"[",
"'",
"\"",
"{",
"#"
]
},
"signatureHelpProvider": {
"triggerCharacters": [
"(",
","
]
},
"definitionProvider": true,
"typeDefinitionProvider": true,
"referencesProvider": true,
"documentHighlightProvider": true,
"documentSymbolProvider": true,
"workspaceSymbolProvider": true,
"codeActionProvider": {
"resolveProvider": true
},
"documentFormattingProvider": true,
"documentRangeFormattingProvider": true,
"documentOnTypeFormattingProvider": {
"firstTriggerCharacter": ";",
"moreTriggerCharacter": [
"}"
]
},
"renameProvider": true,
"implementationProvider": true,
"rageProvider": true,
"experimental": {"snippetTextEdit": true}
}
}
},
{
"powered_by": "serverless_ide",
"jsonrpc": "2.0",
"id": 11,
"result": [
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 3,
"character": 35
},
"end": {
"line": 3,
"character": 37
}
}
},
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 4,
"character": 9
},
"end": {
"line": 4,
"character": 11
}
}
},
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 6,
"character": 9
},
"end": {
"line": 6,
"character": 11
}
}
}
]
},
{
"jsonrpc": "2.0",
"id": 12,
"result": [
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 9,
"character": 18
},
"end": {
"line": 9,
"character": 33
}
}
},
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 19,
"character": 21
},
"end": {
"line": 19,
"character": 36
}
}
}
]
},
{
"powered_by": "serverless_ide",
"jsonrpc": "2.0",
"id": 13,
"result": [
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 36,
"character": 24
},
"end": {
"line": 36,
"character": 26
}
}
},
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 37,
"character": 2
},
"end": {
"line": 37,
"character": 4
}
}
},
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 38,
"character": 4
},
"end": {
"line": 38,
"character": 6
}
}
},
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 38,
"character": 10
},
"end": {
"line": 38,
"character": 12
}
}
},
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 38,
"character": 24
},
"end": {
"line": 38,
"character": 26
}
}
},
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 40,
"character": 20
},
"end": {
"line": 40,
"character": 22
}
}
},
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 43,
"character": 30
},
"end": {
"line": 43,
"character": 32
}
}
},
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 44,
"character": 11
},
"end": {
"line": 44,
"character": 13
}
}
}
]
},
{
"jsonrpc": "2.0",
"id": 14,
"result": [
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 30,
"character": 5
},
"end": {
"line": 30,
"character": 16
}
}
},
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 45,
"character": 10
},
"end": {
"line": 45,
"character": 21
}
}
},
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 46,
"character": 17
},
"end": {
"line": 46,
"character": 28
}
}
}
]
},
{
"jsonrpc": "2.0",
"id": 999,
"result": null
}
] |
|
JSON | hhvm/hphp/hack/test/integration/data/lsp_exchanges/references_ok.json | [
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"initializationOptions": {
"delayUntilDoneInit": true
},
"processId": null,
"rootPath": "${root_path}",
"capabilities": {}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForHhServerReady",
"params": {}
},
{
"jsonrpc": "2.0",
"method": "textDocument/didOpen",
"params": {
"textDocument": {
"uri": "${php_file_uri}",
"languageId": "hack",
"version": 1,
"text": "${php_file}"
}
}
},
{
"jsonrpc": "2.0",
"id": 11,
"method": "textDocument/references",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 6,
"character": 10
},
"context": {
"includeDeclaration": true
}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 11
}
},
{
"jsonrpc": "2.0",
"id": 12,
"method": "textDocument/references",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 19,
"character": 27
},
"context": {
"includeDeclaration": true
}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 12
}
},
{
"jsonrpc": "2.0",
"id": 13,
"method": "textDocument/references",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 37,
"character": 3
},
"context": {
"includeDeclaration": true
}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 13
}
},
{
"jsonrpc": "2.0",
"id": 14,
"method": "textDocument/references",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 45,
"character": 13
},
"context": {
"includeDeclaration": true
}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 14
}
},
{
"jsonrpc": "2.0",
"id": 999,
"method": "shutdown",
"params": {}
}
] |
hhvm/hphp/hack/test/integration/data/lsp_exchanges/references_server_cancel.expected | [
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"capabilities": {
"textDocumentSync": {
"openClose": true,
"change": 2,
"willSave": false,
"willSaveWaitUntil": true,
"save": {
"includeText": false
}
},
"hoverProvider": true,
"completionProvider": {
"resolveProvider": true,
"triggerCharacters": [
"$",
">",
"\\",
":",
"<",
"[",
"'",
"\"",
"{",
"#"
]
},
"signatureHelpProvider": {
"triggerCharacters": [
"(",
","
]
},
"definitionProvider": true,
"typeDefinitionProvider": true,
"referencesProvider": true,
"documentHighlightProvider": true,
"documentSymbolProvider": true,
"workspaceSymbolProvider": true,
"codeActionProvider": {
"resolveProvider": true
},
"documentFormattingProvider": true,
"documentRangeFormattingProvider": true,
"documentOnTypeFormattingProvider": {
"firstTriggerCharacter": ";",
"moreTriggerCharacter": [
"}"
]
},
"renameProvider": true,
"implementationProvider": true,
"rageProvider": true,
"experimental": {
"snippetTextEdit": true
}
}
}
},
{
"jsonrpc": "2.0",
"id": 11,
"error": {
"code": -32800,
"message": "Cancelled (displaced by another request #12)"
}
},
{
"jsonrpc": "2.0",
"id": 12,
"error": {
"code": -32800,
"message": "Cancelled (displaced by another request #13)"
}
},
{
"jsonrpc": "2.0",
"id": 13,
"result": [
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 36,
"character": 9
},
"end": {
"line": 36,
"character": 19
}
}
},
{
"uri": "file://${root_path}/references2.php",
"range": {
"start": {
"line": 3,
"character": 2
},
"end": {
"line": 3,
"character": 12
}
}
}
]
},
{
"jsonrpc": "2.0",
"id": 999,
"result": null
}
] |
|
JSON | hhvm/hphp/hack/test/integration/data/lsp_exchanges/references_server_cancel.json | [
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"initializationOptions": {
"delayUntilDoneInit": true
},
"processId": null,
"rootPath": "${root_path}",
"capabilities": {}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForHhServerReady",
"params": {}
},
{
"jsonrpc": "2.0",
"method": "textDocument/didOpen",
"params": {
"textDocument": {
"uri": "${php_file_uri}",
"languageId": "hack",
"version": 1,
"text": "${php_file}"
}
}
},
{
"jsonrpc": "2.0",
"id": 11,
"method": "textDocument/references",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 36,
"character": 15
},
"context": {
"includeDeclaration": false
}
}
},
{
"jsonrpc": "2.0",
"id": 12,
"method": "textDocument/references",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 36,
"character": 15
},
"context": {
"includeDeclaration": false
}
}
},
{
"jsonrpc": "2.0",
"id": 13,
"method": "textDocument/references",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 36,
"character": 15
},
"context": {
"includeDeclaration": false
}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 13
}
},
{
"jsonrpc": "2.0",
"id": 999,
"method": "shutdown",
"params": {}
}
] |
hhvm/hphp/hack/test/integration/data/lsp_exchanges/references_with_server.expected | [
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"capabilities": {
"textDocumentSync": {
"openClose": true,
"change": 2,
"willSave": false,
"willSaveWaitUntil": true,
"save": {
"includeText": false
}
},
"hoverProvider": true,
"completionProvider": {
"resolveProvider": true,
"triggerCharacters": [
"$",
">",
"\\",
":",
"<",
"[",
"'",
"\"",
"{",
"#"
]
},
"signatureHelpProvider": {
"triggerCharacters": [
"(",
","
]
},
"definitionProvider": true,
"typeDefinitionProvider": true,
"referencesProvider": true,
"documentHighlightProvider": true,
"documentSymbolProvider": true,
"workspaceSymbolProvider": true,
"codeActionProvider": {
"resolveProvider": true
},
"documentFormattingProvider": true,
"documentRangeFormattingProvider": true,
"documentOnTypeFormattingProvider": {
"firstTriggerCharacter": ";",
"moreTriggerCharacter": [
"}"
]
},
"renameProvider": true,
"implementationProvider": true,
"rageProvider": true,
"experimental": {
"snippetTextEdit": true
}
}
}
},
{
"jsonrpc": "2.0",
"id": 11,
"result": [
{
"uri": "file://${root_path}/references.php",
"range": {
"start": {
"line": 36,
"character": 9
},
"end": {
"line": 36,
"character": 19
}
}
},
{
"uri": "file://${root_path}/references2.php",
"range": {
"start": {
"line": 3,
"character": 2
},
"end": {
"line": 3,
"character": 12
}
}
}
]
},
{
"jsonrpc": "2.0",
"id": 999,
"result": null
}
] |
|
JSON | hhvm/hphp/hack/test/integration/data/lsp_exchanges/references_with_server.json | [
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"initializationOptions": {
"delayUntilDoneInit": true
},
"processId": null,
"rootPath": "${root_path}",
"capabilities": {}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForHhServerReady",
"params": {}
},
{
"jsonrpc": "2.0",
"method": "textDocument/didOpen",
"params": {
"textDocument": {
"uri": "${php_file_uri}",
"languageId": "hack",
"version": 1,
"text": "${php_file}"
}
}
},
{
"jsonrpc": "2.0",
"id": 11,
"method": "textDocument/references",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 36,
"character": 15
},
"context": {
"includeDeclaration": false
}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 11
}
},
{
"jsonrpc": "2.0",
"id": 999,
"method": "shutdown",
"params": {}
},
{
"jsonrpc": "2.0",
"method": "exit",
"params": {}
}
] |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/rename.php | <?hh //strict
class TestClass { // 2. Rename TestClass
const CONSTANT = 5;
const string STR_CONSTANT = "hello";
const vec<int> VEC_INT_CONSTANT = vec [1, 2, 3, 4];
public int $property;
public function __construct(int $i) {
$this->property = $i + TestClass::CONSTANT; // 1. Rename CONSTANT
}
public function test_method(): int {
return $this->property;
}
/**
* Some docblock
*
*
*/
public function deprecated_method(int $x, string $y, int $v, mixed ...$_): int {
return $x;
}
// 8. Rename depr_static
public static function depr_static(int $x, string $y, int $v, mixed ...$_): int {
return $x;
}
// 9. Rename depr_async
public async function depr_async(int $x, int $v, mixed ...$_): Awaitable<int> {
return $x;
}
// 10. Rename depr_static_async
public static async function depr_static_async(int $x): Awaitable<
void,
>
{}
}
enum RenameTestEnum: int {
SMALL = 0;
MEDIUM = 1;
LARGE = 2;
}
function test_rename(): void {
$test_class = new TestClass(1);
// 3. Rename 1st test_method
$test_class->test_method(); $test_class->test_method();
$const = TestClass::CONSTANT;
$str_const = TestClass::STR_CONSTANT; // 4. Rename STR_CONSTANT
$vec_int_const = TestClass::VEC_INT_CONSTANT; // 5. Rename VEC_INT_CONSTANT
// 7. Renaming deprecated_method
$num = $test_class->deprecated_method(5, "", 4, 4, 3, 5, "hello");
$size = RenameTestEnum::SMALL; // 13. Rename TestEnum
}
async function async_test_rename(): Awaitable<int> {
return 5;
}
async function call_test_rename(): Awaitable<int> {
test_rename(); // 11. Rename test_rename
return await async_test_rename(); // 12. Rename async_test_rename
}
function test_rename_localvar(int $local): void { // Should match
$local = 3; // Should match
j($local) + $local + h("\$x = $local"); // 1st, 2nd, and 4th should match
$lambda1 = $x ==> $x + 1; // Should not match
$lambda2 = $a ==> $local + $a; // 6. Renaming this $local // Should match
$lambda3 = function($x) { // Should not match
return $x + 1; }; // Should not match
$lambda4 = function($b) use($local) { // Should match
return $local + $b; }; // Should match
}
type RenameShapeKeyEnum =
shape(RenameTestEnum::SMALL => int); // 4. Rename STR_CONSTANT
type RenameShapeKeyConstant =
shape(TestClass::STR_CONSTANT => int); // 4. Rename STR_CONSTANT
function test_rename_shape_keys(): void {
shape(RenameTestEnum::SMALL => 123); // 4. Rename STR_CONSTANT
shape(TestClass::STR_CONSTANT => 123); // 13. Rename TestEnum
}
function multifile_rename_target(): void { // 14. Rename multifile_rename_target
}
function test_multifile_1(): void {
multifile_rename_target();
} |
hhvm/hphp/hack/test/integration/data/lsp_exchanges/rename_ok.expected | [
{
"jsonrpc": "2.0",
"id": 990,
"result": {
"capabilities": {
"textDocumentSync": {
"openClose": true,
"change": 2,
"willSave": false,
"willSaveWaitUntil": true,
"save": {
"includeText": false
}
},
"hoverProvider": true,
"completionProvider": {
"resolveProvider": true,
"triggerCharacters": [
"$",
">",
"\\",
":",
"<",
"[",
"'",
"\"",
"{",
"#"
]
},
"signatureHelpProvider": {
"triggerCharacters": [
"(",
","
]
},
"definitionProvider": true,
"typeDefinitionProvider": true,
"referencesProvider": true,
"documentHighlightProvider": true,
"documentSymbolProvider": true,
"workspaceSymbolProvider": true,
"codeActionProvider": {
"resolveProvider": true
},
"documentFormattingProvider": true,
"documentRangeFormattingProvider": true,
"documentOnTypeFormattingProvider": {
"firstTriggerCharacter": ";",
"moreTriggerCharacter": [
"}"
]
},
"renameProvider": true,
"implementationProvider": true,
"rageProvider": true,
"experimental": {
"snippetTextEdit": true
}
}
}
},
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"changes": {
"${php_file_uri}": [
{
"range": {
"start": {
"line": 3,
"character": 8
},
"end": {
"line": 3,
"character": 16
}
},
"newText": "NEW_CONSTANT"
},
{
"range": {
"start": {
"line": 9,
"character": 38
},
"end": {
"line": 9,
"character": 46
}
},
"newText": "NEW_CONSTANT"
},
{
"range": {
"start": {
"line": 52,
"character": 22
},
"end": {
"line": 52,
"character": 30
}
},
"newText": "NEW_CONSTANT"
}
]
}
}
},
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"changes": {
"${php_file_uri}": [
{
"range": {
"start": {
"line": 2,
"character": 6
},
"end": {
"line": 2,
"character": 15
}
},
"newText": "HistoryClass"
},
{
"range": {
"start": {
"line": 9,
"character": 27
},
"end": {
"line": 9,
"character": 36
}
},
"newText": "HistoryClass"
},
{
"range": {
"start": {
"line": 49,
"character": 20
},
"end": {
"line": 49,
"character": 29
}
},
"newText": "HistoryClass"
},
{
"range": {
"start": {
"line": 52,
"character": 11
},
"end": {
"line": 52,
"character": 20
}
},
"newText": "HistoryClass"
},
{
"range": {
"start": {
"line": 53,
"character": 15
},
"end": {
"line": 53,
"character": 24
}
},
"newText": "HistoryClass"
},
{
"range": {
"start": {
"line": 54,
"character": 19
},
"end": {
"line": 54,
"character": 28
}
},
"newText": "HistoryClass"
},
{
"range": {
"start": {
"line": 84,
"character": 8
},
"end": {
"line": 84,
"character": 17
}
},
"newText": "HistoryClass"
},
{
"range": {
"start": {
"line": 88,
"character": 8
},
"end": {
"line": 88,
"character": 17
}
},
"newText": "HistoryClass"
}
]
}
}
},
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"changes": {
"${php_file_uri}": [
{
"range": {
"start": {
"line": 11,
"character": 0
},
"end": {
"line": 11,
"character": 0
}
},
"newText": "\n <<__Deprecated(\"Use `some_other_method` instead\")>>\n public function test_method(): int {\n return $this->some_other_method();\n }\n"
},
{
"range": {
"start": {
"line": 12,
"character": 18
},
"end": {
"line": 12,
"character": 29
}
},
"newText": "some_other_method"
},
{
"range": {
"start": {
"line": 51,
"character": 15
},
"end": {
"line": 51,
"character": 26
}
},
"newText": "some_other_method"
},
{
"range": {
"start": {
"line": 51,
"character": 43
},
"end": {
"line": 51,
"character": 54
}
},
"newText": "some_other_method"
}
]
}
}
},
{
"jsonrpc": "2.0",
"id": 4,
"result": {
"changes": {
"${php_file_uri}": [
{
"range": {
"start": {
"line": 4,
"character": 15
},
"end": {
"line": 4,
"character": 27
}
},
"newText": "ANOTHER_STR_CONSTANT"
},
{
"range": {
"start": {
"line": 53,
"character": 26
},
"end": {
"line": 53,
"character": 38
}
},
"newText": "ANOTHER_STR_CONSTANT"
},
{
"range": {
"start": {
"line": 84,
"character": 19
},
"end": {
"line": 84,
"character": 31
}
},
"newText": "ANOTHER_STR_CONSTANT"
},
{
"range": {
"start": {
"line": 88,
"character": 19
},
"end": {
"line": 88,
"character": 31
}
},
"newText": "ANOTHER_STR_CONSTANT"
}
]
}
}
},
{
"jsonrpc": "2.0",
"id": 5,
"result": {
"changes": {
"${php_file_uri}": [
{
"range": {
"start": {
"line": 5,
"character": 17
},
"end": {
"line": 5,
"character": 33
}
},
"newText": "AVOGADRO_CONSTANT"
},
{
"range": {
"start": {
"line": 54,
"character": 30
},
"end": {
"line": 54,
"character": 46
}
},
"newText": "AVOGADRO_CONSTANT"
}
]
}
}
},
{
"jsonrpc": "2.0",
"id": 6,
"result": {
"changes": {
"${php_file_uri}": [
{
"range": {
"start": {
"line": 69,
"character": 34
},
"end": {
"line": 69,
"character": 40
}
},
"newText": "$kittens_and_rainbows"
},
{
"range": {
"start": {
"line": 70,
"character": 2
},
"end": {
"line": 70,
"character": 8
}
},
"newText": "$kittens_and_rainbows"
},
{
"range": {
"start": {
"line": 71,
"character": 4
},
"end": {
"line": 71,
"character": 10
}
},
"newText": "$kittens_and_rainbows"
},
{
"range": {
"start": {
"line": 71,
"character": 14
},
"end": {
"line": 71,
"character": 20
}
},
"newText": "$kittens_and_rainbows"
},
{
"range": {
"start": {
"line": 71,
"character": 32
},
"end": {
"line": 71,
"character": 38
}
},
"newText": "$kittens_and_rainbows"
},
{
"range": {
"start": {
"line": 73,
"character": 20
},
"end": {
"line": 73,
"character": 26
}
},
"newText": "$kittens_and_rainbows"
},
{
"range": {
"start": {
"line": 76,
"character": 30
},
"end": {
"line": 76,
"character": 36
}
},
"newText": "$kittens_and_rainbows"
},
{
"range": {
"start": {
"line": 77,
"character": 11
},
"end": {
"line": 77,
"character": 17
}
},
"newText": "$kittens_and_rainbows"
}
]
}
}
},
{
"jsonrpc": "2.0",
"id": 7,
"result": {
"changes": {
"${php_file_uri}": [
{
"range": {
"start": {
"line": 15,
"character": 0
},
"end": {
"line": 15,
"character": 0
}
},
"newText": "\n <<__Deprecated(\"Use `new_and_improved` instead\")>>\n public function deprecated_method(int $x, string $y, int $v, mixed ...$_): int {\n return $this->new_and_improved($x, $y, $v, ...$_);\n }\n"
},
{
"range": {
"start": {
"line": 21,
"character": 18
},
"end": {
"line": 21,
"character": 35
}
},
"newText": "new_and_improved"
},
{
"range": {
"start": {
"line": 56,
"character": 22
},
"end": {
"line": 56,
"character": 39
}
},
"newText": "new_and_improved"
}
]
}
}
},
{
"jsonrpc": "2.0",
"id": 8,
"result": {
"changes": {
"${php_file_uri}": [
{
"range": {
"start": {
"line": 24,
"character": 0
},
"end": {
"line": 24,
"character": 0
}
},
"newText": "\n <<__Deprecated(\"Use `new_static_method` instead\")>>\n public static function depr_static(int $x, string $y, int $v, mixed ...$_): int {\n return self::new_static_method($x, $y, $v, ...$_);\n }\n"
},
{
"range": {
"start": {
"line": 26,
"character": 25
},
"end": {
"line": 26,
"character": 36
}
},
"newText": "new_static_method"
}
]
}
}
},
{
"jsonrpc": "2.0",
"id": 9,
"result": {
"changes": {
"${php_file_uri}": [
{
"range": {
"start": {
"line": 29,
"character": 0
},
"end": {
"line": 29,
"character": 0
}
},
"newText": "\n <<__Deprecated(\"Use `new_async_method` instead\")>>\n public async function depr_async(int $x, int $v, mixed ...$_): Awaitable<int> {\n return await $this->new_async_method($x, $v, ...$_);\n }\n"
},
{
"range": {
"start": {
"line": 31,
"character": 24
},
"end": {
"line": 31,
"character": 34
}
},
"newText": "new_async_method"
}
]
}
}
},
{
"jsonrpc": "2.0",
"id": 10,
"result": {
"changes": {
"${php_file_uri}": [
{
"range": {
"start": {
"line": 34,
"character": 0
},
"end": {
"line": 34,
"character": 0
}
},
"newText": "\n <<__Deprecated(\"Use `new_static_async_method` instead\")>>\n public static async function depr_static_async(int $x): Awaitable<\n void,\n > {\n await self::new_static_async_method($x);\n }\n"
},
{
"range": {
"start": {
"line": 36,
"character": 31
},
"end": {
"line": 36,
"character": 48
}
},
"newText": "new_static_async_method"
}
]
}
}
},
{
"jsonrpc": "2.0",
"id": 11,
"result": {
"changes": {
"${php_file_uri}": [
{
"range": {
"start": {
"line": 47,
"character": 0
},
"end": {
"line": 47,
"character": 0
}
},
"newText": "\n<<__Deprecated(\"Use `new_test_rename_method` instead\")>>\nfunction test_rename(): void {\n new_test_rename_method();\n}\n"
},
{
"range": {
"start": {
"line": 48,
"character": 9
},
"end": {
"line": 48,
"character": 20
}
},
"newText": "new_test_rename_method"
},
{
"range": {
"start": {
"line": 65,
"character": 2
},
"end": {
"line": 65,
"character": 13
}
},
"newText": "new_test_rename_method"
}
]
}
}
},
{
"jsonrpc": "2.0",
"id": 12,
"result": {
"changes": {
"${php_file_uri}": [
{
"range": {
"start": {
"line": 59,
"character": 0
},
"end": {
"line": 59,
"character": 0
}
},
"newText": "\n<<__Deprecated(\"Use `new_async_test_rename_method` instead\")>>\nasync function async_test_rename(): Awaitable<int> {\n return await new_async_test_rename_method();\n}\n"
},
{
"range": {
"start": {
"line": 60,
"character": 15
},
"end": {
"line": 60,
"character": 32
}
},
"newText": "new_async_test_rename_method"
},
{
"range": {
"start": {
"line": 66,
"character": 15
},
"end": {
"line": 66,
"character": 32
}
},
"newText": "new_async_test_rename_method"
}
]
}
}
},
{
"jsonrpc": "2.0",
"id": 13,
"result": {
"changes": {
"${php_file_uri}": [
{
"range": {
"start": {
"line": 42,
"character": 5
},
"end": {
"line": 42,
"character": 19
}
},
"newText": "TSHIRT_SIZES"
},
{
"range": {
"start": {
"line": 57,
"character": 10
},
"end": {
"line": 57,
"character": 24
}
},
"newText": "TSHIRT_SIZES"
},
{
"range": {
"start": {
"line": 81,
"character": 8
},
"end": {
"line": 81,
"character": 22
}
},
"newText": "TSHIRT_SIZES"
},
{
"range": {
"start": {
"line": 87,
"character": 8
},
"end": {
"line": 87,
"character": 22
}
},
"newText": "TSHIRT_SIZES"
}
]
}
}
},
{
"jsonrpc": "2.0",
"id": 14,
"result": {
"changes": {
"${rename2_file_uri}": [
{
"range": {
"start": {
"line": 3,
"character": 2
},
"end": {
"line": 3,
"character": 25
}
},
"newText": "multifile_newname"
}
],
"${php_file_uri}": [
{
"range": {
"start": {
"line": 90,
"character": 0
},
"end": {
"line": 90,
"character": 0
}
},
"newText": "\n<<__Deprecated(\"Use `multifile_newname` instead\")>>\nfunction multifile_rename_target(): void {\n multifile_newname();\n}\n"
},
{
"range": {
"start": {
"line": 91,
"character": 9
},
"end": {
"line": 91,
"character": 32
}
},
"newText": "multifile_newname"
},
{
"range": {
"start": {
"line": 95,
"character": 2
},
"end": {
"line": 95,
"character": 25
}
},
"newText": "multifile_newname"
}
]
}
}
},
{
"jsonrpc": "2.0",
"id": 999,
"result": null
}
] |
|
JSON | hhvm/hphp/hack/test/integration/data/lsp_exchanges/rename_ok.json | [
{
"jsonrpc": "2.0",
"id": 990,
"method": "initialize",
"params": {
"initializationOptions": {
"delayUntilDoneInit": true
},
"processId": null,
"rootPath": "${root_path}",
"capabilities": {}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForHhServerReady",
"params": {}
},
{
"jsonrpc": "2.0",
"method": "textDocument/didOpen",
"params": {
"textDocument": {
"uri": "${php_file_uri}",
"languageId": "hack",
"version": 1,
"text": "${php_file}"
}
}
},
{
"jsonrpc": "2.0",
"method": "textDocument/didOpen",
"params": {
"textDocument": {
"uri": "${rename2_file_uri}",
"languageId": "hack",
"version": 1,
"text": "${rename2_file}"
}
}
},
{
"jsonrpc": "2.0",
"id": 1,
"method": "textDocument/rename",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 9,
"character": 42
},
"newName": "NEW_CONSTANT"
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 1
}
},
{
"jsonrpc": "2.0",
"id": 2,
"method": "textDocument/rename",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 2,
"character": 11
},
"newName": "HistoryClass"
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 2
}
},
{
"jsonrpc": "2.0",
"id": 3,
"method": "textDocument/rename",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 51,
"character": 18
},
"newName": "some_other_method"
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 3
}
},
{
"jsonrpc": "2.0",
"id": 4,
"method": "textDocument/rename",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 53,
"character": 34
},
"newName": "ANOTHER_STR_CONSTANT"
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 4
}
},
{
"jsonrpc": "2.0",
"id": 5,
"method": "textDocument/rename",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 54,
"character": 39
},
"newName": "AVOGADRO_CONSTANT"
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 5
}
},
{
"jsonrpc": "2.0",
"id": 6,
"method": "textDocument/rename",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 73,
"character": 26
},
"newName": "kittens_and_rainbows"
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 6
}
},
{
"jsonrpc": "2.0",
"id": 7,
"method": "textDocument/rename",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 56,
"character": 29
},
"newName": "new_and_improved"
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 7
}
},
{
"jsonrpc": "2.0",
"id": 8,
"method": "textDocument/rename",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 26,
"character": 33
},
"newName": "new_static_method"
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 8
}
},
{
"jsonrpc": "2.0",
"id": 9,
"method": "textDocument/rename",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 31,
"character": 33
},
"newName": "new_async_method"
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 9
}
},
{
"jsonrpc": "2.0",
"id": 10,
"method": "textDocument/rename",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 36,
"character": 42
},
"newName": "new_static_async_method"
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 10
}
},
{
"jsonrpc": "2.0",
"id": 11,
"method": "textDocument/rename",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 65,
"character": 11
},
"newName": "new_test_rename_method"
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 11
}
},
{
"jsonrpc": "2.0",
"id": 12,
"method": "textDocument/rename",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 66,
"character": 29
},
"newName": "new_async_test_rename_method"
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 12
}
},
{
"jsonrpc": "2.0",
"id": 13,
"method": "textDocument/rename",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 57,
"character": 13
},
"newName": "TSHIRT_SIZES"
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 13
}
},
{
"jsonrpc": "2.0",
"id": 14,
"method": "textDocument/rename",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 91,
"character": 20
},
"newName": "multifile_newname"
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 14
}
},
{
"jsonrpc": "2.0",
"id": 999,
"method": "shutdown",
"params": {}
}
] |
hhvm/hphp/hack/test/integration/data/lsp_exchanges/rename_with_server.expected | [
{
"jsonrpc": "2.0",
"id": 990,
"result": {
"capabilities": {
"textDocumentSync": {
"openClose": true,
"change": 2,
"willSave": false,
"willSaveWaitUntil": true,
"save": {
"includeText": false
}
},
"hoverProvider": true,
"completionProvider": {
"resolveProvider": true,
"triggerCharacters": [
"$",
">",
"\\",
":",
"<",
"[",
"'",
"\"",
"{",
"#"
]
},
"signatureHelpProvider": {
"triggerCharacters": [
"(",
","
]
},
"definitionProvider": true,
"typeDefinitionProvider": true,
"referencesProvider": true,
"documentHighlightProvider": true,
"documentSymbolProvider": true,
"workspaceSymbolProvider": true,
"codeActionProvider": {
"resolveProvider": true
},
"documentFormattingProvider": true,
"documentRangeFormattingProvider": true,
"documentOnTypeFormattingProvider": {
"firstTriggerCharacter": ";",
"moreTriggerCharacter": [
"}"
]
},
"renameProvider": true,
"implementationProvider": true,
"rageProvider": true,
"experimental": {
"snippetTextEdit": true
}
}
}
},
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"changes": {
"file://${root_path}/rename2.php": [
{
"range": {
"start": {
"line": 3,
"character": 2
},
"end": {
"line": 3,
"character": 25
}
},
"newText": "multifile_newname"
}
],
"file://${root_path}/rename.php": [
{
"range": {
"start": {
"line": 90,
"character": 0
},
"end": {
"line": 90,
"character": 0
}
},
"newText": "\n<<__Deprecated(\"Use `multifile_newname` instead\")>>\nfunction multifile_rename_target(): void {\n multifile_newname();\n}\n"
},
{
"range": {
"start": {
"line": 91,
"character": 9
},
"end": {
"line": 91,
"character": 32
}
},
"newText": "multifile_newname"
},
{
"range": {
"start": {
"line": 95,
"character": 2
},
"end": {
"line": 95,
"character": 25
}
},
"newText": "multifile_newname"
}
]
}
}
},
{
"jsonrpc": "2.0",
"id": 999,
"result": null
}
] |
|
JSON | hhvm/hphp/hack/test/integration/data/lsp_exchanges/rename_with_server.json | [
{
"jsonrpc": "2.0",
"id": 990,
"method": "initialize",
"params": {
"initializationOptions": {
"delayUntilDoneInit": true
},
"processId": null,
"rootPath": "${root_path}",
"capabilities": {}
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForHhServerReady",
"params": {}
},
{
"jsonrpc": "2.0",
"method": "textDocument/didOpen",
"params": {
"textDocument": {
"uri": "${php_file_uri}",
"languageId": "hack",
"version": 1,
"text": "${php_file}"
}
}
},
{
"jsonrpc": "2.0",
"id": 1,
"method": "textDocument/rename",
"params": {
"textDocument": {
"uri": "${php_file_uri}"
},
"position": {
"line": 91,
"character": 20
},
"newName": "multifile_newname"
}
},
{
"jsonrpc": "2.0",
"method": "$test/waitForResponse",
"params": {
"id": 1
}
},
{
"jsonrpc": "2.0",
"id": 999,
"method": "shutdown",
"params": {}
}
] |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/signaturehelp.php | <?hh // strict
/** Global function with doc block */
function global_function(string $s, int $x): void {}
class MyClass {
/** Constructor with doc block */
public function __construct() {}
/** Static method with doc block */
public static function staticMethod(string $z): void {}
/** Instance method with doc block */
public function instanceMethod(int $x1, int $x2): void {}
}
function test_signature_help(): void
{
$x = new MyClass();
$x->instanceMethod(1,2);
MyClass::staticMethod("hi");
global_function("hi", 1);
Herp\aliased_global_func("hi");
test_signature_help_params1("hi", "there");
test_signature_help_params2("hi", "there");
test_signature_help_params3("hi", "there");
test_signature_help_highlight("hi", "there", "bootcamp");
}
/* comment describing the method
@param $param1 info1
@param param2 info2
*/
function test_signature_help_params1(string $param1, string $param2): void {}
/* comment describing the method
@param $param1 info1
*/
function test_signature_help_params2(string $param1, string $param2): void {}
/*
* @param $param1 info1
* for param1
* @param $param2 info2
* @return the string
* 'hack'
*/
function test_signature_help_params3(string $param1, string $param2): string {
return 'hack';
}
function test_signature_help_highlight(
string $param1,
string $param2,
string $param3,
): string {
return 'hack';
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/signaturehelp_lambda.php | <?hh // strict
function test_lambda_sighelp(string $str, (function(string): int) $f): int {
return $f($str);
}
function normal_test_func(string $str): void {}
function use_lambda_sighelp(): int {
return test_lambda_sighelp("Hello", $str ==> {
normal_test_func("hi");
return 2 * (1 - 3);
});
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/signaturehelp_namespace.php | <?hh // strict
namespace Derp\Lib\Herp {
/** Namespace-aliased function with doc block */
function aliased_global_func(string $s): void {}
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/type_definition.php | <?hh //strict
class HH {
public function __construct(int $i) {}
}
class II extends HH {
public function __construct() {
parent::__construct(1);
}
}
class LL {}
function hh_from_ii_definition(): HH {
return new II();
}
function ll_type_definition(): LL {
return new LL();
}
function prim_type_definition(): int {
return 42;
}
function test_conditional_type(bool $x): void {
if ($x) {
$y = new LL();
} else {
$y = new HH(2);
}
$y; // returns both LL def and HH def
}
function test_standard_types(): void {
$hh1 = new HH(1); // testing standard class definition
$hh2 = hh_from_ii_definition(); // testing casting + function return type
$prim = 40; // $prim should go nowhere
$hh1; // jump to HH definition
$hh2; // jump to HH definition
$prim; // jump to nowhere
ll_type_definition(); // testing jumping to function return def
prim_type_definition(); // testing jumping to function def
} |
PHP | hhvm/hphp/hack/test/integration/data/lsp_exchanges/xhp_class_definitions.php | <?hh //strict
/** :ab:cd:text docblock */
final class :ab:cd:text implements XHPChild {
attribute string color, int width;
}
/** :ab:cd:alpha docblock */
final class :ab:cd:alpha implements XHPChild {
attribute string name;
}
enum MyEnum: string as string {
TYPE_A = "A value";
TYPE_B = "B value";
TYPE_C = "C value";
}
/** :xhp:enum-attribute docblock */
final class :xhp:enum-attribute implements XHPChild {
attribute
MyEnum enum-attribute,
/** :xhp:enum-attribute::name docblock */
string name;
public function __construct(
public darray<string,mixed> $attributes,
public varray<mixed> $children,
public string $filename,
public int $line,
) {}
}
newtype ID<T> = int;
class EntSomething {
public static function getId(): ID<EntSomething> { return 0; }
}
final class :xhp:generic<T> implements XHPChild {
attribute ID<T> id;
public function __construct(
public darray<string,mixed> $attributes,
public varray<mixed> $children,
public string $filename,
public int $line,
) {}
} |
hhvm/hphp/hack/test/integration/data/repo_with_merge_driver/.hhconfig | # some comment
assume_php = false
auto_namespace_map = {"Herp": "Derp\\Lib\\Herp"}
disable_xhp_element_mangling=false |
|
PHP | hhvm/hphp/hack/test/integration/data/repo_with_merge_driver/foo_3.php | <?hh
function h(): string {
return "a";
}
class Foo {}
function some_long_function_name(): void {
new Foo();
h();
} |
Python | hhvm/hphp/hack/test/integration/data/repo_with_merge_driver/scripts/mergedriver.py | from __future__ import absolute_import, division, print_function
import json
import os
import subprocess
# This merge driver just calls Hack Build. We want to make sure that
# the interdependencies between these pieces doesn't deadlock
# This mergedriver requires a mergedriver_test_env.json to be generated
# by the test runner. That's where the correct HH_TMPDIR gets wired in so
# we locate the correct socket, as well as HH_HOME so we find the
# hh_client binary for this test run.
def preprocess(ui, repo, hooktype, mergestate, wctx, labels):
repo.ui.status("* preprocess called\n")
for f in mergestate:
mergestate.mark(f, "d")
def conclude(ui, repo, hooktype, mergestate, wctx, labels):
repo.ui.status("* conclude called\n")
with open(os.path.join("scripts", "mergedriver_test_env.json"), "r") as f:
env_json = f.read()
test_env = json.loads(env_json)
hh_client = os.environ.get("HH_HOME") + "/hh_client"
build_cmd = [hh_client, "check", "--force-dormant-start", "true", "."]
subprocess.check_call(build_cmd, env=test_env) |
PHP | hhvm/hphp/hack/test/integration/data/repo_with_merge_driver/scripts/build/write_build_checksum.php | #!/usr/local/bin/php
<?hh
// Copyright 2004-present Facebook. All Rights Reserved.
// This is disabled during the Facts DB rollout.
// TODO(t13633682): turn it back on once Facts DB is rolled out everywhere.
function main(): void {
exit(0);
} |
hhvm/hphp/hack/test/integration/data/simple_repo/.hhconfig | # some comment
assume_php = false
allowed_fixme_codes_strict = 4110
allowed_decl_fixme_codes = 4110
disallow_fun_and_cls_meth_pseudo_funcs = true
auto_namespace_map = {"Herp": "Derp\\Lib\\Herp"}
disable_xhp_element_mangling = false |
|
PHP | hhvm/hphp/hack/test/integration/data/simple_repo/auto_ns_2.php | <?hh // strict
function haha(): int {
Derp\Lib\Herp\f();
return 1;
}
class UsesHerpT {
public static function getHerpT(): Herp\T {
return 0;
}
} |
PHP | hhvm/hphp/hack/test/integration/data/simple_repo/bar_1.php | <?hh
/*
* This is a docblock for NoBigTrait
*/
trait NoBigTrait {
public static function justAnotherStaticMethod(): void {}
} |
PHP | hhvm/hphp/hack/test/integration/data/simple_repo/enum_1.php | <?hh // strict
enum FbidMapField: string as string {
FBID = "fbid";
ID1 = "id1";
ID2_TYPE = "id2_type";
ID2 = "id2";
VERSION = "version";
DATA = "data";
SUB_INDICES = 'sub_indices';
} |
PHP | hhvm/hphp/hack/test/integration/data/simple_repo/foo_3.php | <?hh
function h(): string {
return "a";
}
class Foo {}
function some_long_function_name(): void {
new Foo();
h();
} |
PHP | hhvm/hphp/hack/test/integration/data/simple_repo/foo_6.php | <?hh
interface IFoo {
public function i(): int;
}
class FooDependentClass implements IFoo {
public function i(): int {
return 1;
}
} |
PHP | hhvm/hphp/hack/test/integration/data/simple_repo/foo_readonly.php | <?hh
function foo_readonly((readonly function(readonly int):readonly int) $x): void {
$y = $x;
} |
PHP | hhvm/hphp/hack/test/integration/data/simple_repo/long_type_name.php | <?hh
// type name length 230 bytes.
type VeryLongTypeName______________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 231 bytes.
type VeryLongTypeName_______________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 232 bytes.
type VeryLongTypeName________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 233 bytes.
type VeryLongTypeName_________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 234 bytes.
type VeryLongTypeName__________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 235 bytes.
type VeryLongTypeName___________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 236 bytes.
type VeryLongTypeName____________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 237 bytes.
type VeryLongTypeName_____________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 238 bytes.
type VeryLongTypeName______________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 239 bytes.
type VeryLongTypeName_______________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 240 bytes.
type VeryLongTypeName________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 241 bytes.
type VeryLongTypeName_________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 242 bytes.
type VeryLongTypeName__________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 243 bytes.
type VeryLongTypeName___________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 244 bytes.
type VeryLongTypeName____________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 245 bytes.
type VeryLongTypeName_____________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 246 bytes.
type VeryLongTypeName______________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 247 bytes.
type VeryLongTypeName_______________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 248 bytes.
type VeryLongTypeName________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 249 bytes.
type VeryLongTypeName_________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 250 bytes.
type VeryLongTypeName__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 251 bytes.
type VeryLongTypeName___________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 252 bytes.
type VeryLongTypeName____________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 253 bytes.
type VeryLongTypeName_____________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 254 bytes.
type VeryLongTypeName______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 255 bytes.
type VeryLongTypeName_______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 256 bytes.
type VeryLongTypeName________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 257 bytes.
type VeryLongTypeName_________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 258 bytes.
type VeryLongTypeName__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 259 bytes.
type VeryLongTypeName___________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int;
// type name length 260 bytes.
type VeryLongTypeName____________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
= int; |
Hack | hhvm/hphp/hack/test/integration/data/simple_repo/symbol.hack | // This file tests that the symbol index is capturing files with the ".hack" extension
final class SymbolInsideHackFile
{
public function foo(): void {
}
} |
PHP | hhvm/hphp/hack/test/integration/search/basic.php | //// foo_search_3.php
<?hh
function h(): string {
return "a";
}
class Foo {}
function some_long_function_name(): void {
new Foo();
h();
}
//// foo_search_4.php
<?hh
class Alphac {}
function alphaf (): void {}
//// queries
some_lo
// following two are to validate that it's case insensitive
Alpha
alpha |
PHP | hhvm/hphp/hack/test/integration/typing_serde/fun_one-liners.php | <?hh
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
function non_empty(string $s): ?string {
return $s ? $s : null;
} |
PHP | hhvm/hphp/hack/test/integration/typing_serde/shortest_fun-returns-int.php | <?hh
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
function getOne(): int { return 1; } |
PHP | hhvm/hphp/hack/test/integration/typing_serde/shortest_fun-returns-nested-type.php | <?hh
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
function getOptionalDict(): ?dict<int, string> { return null; } |
hhvm/hphp/hack/test/integration_ml/dune | ; As an exception, we directly use test_injector_config here to be sure
; all the tests that depend on this lib are using the test stubs
(library
(name integration_test_base)
(wrapped false)
(modules integration_test_base integration_test_base_types)
(libraries
asserter
client
hh_server_monitor
server
server_client_provider
server_command_types
server_env
test_injector_config)
(preprocess
(pps
ppx_deriving.show
ppx_deriving.eq)))
(library
(name runner_base)
(wrapped false)
(modules runner_base)
(libraries
integration_test_base
errors
server_env
unit_test
test_all_ide))
(executable
(name runner)
(link_flags
(:standard
(:include ../../src/dune_config/ld-opts.sexp)))
(modes exe byte_complete)
(modules
runner
test_added_parent
test_capitalization
test_coeffects
test_decl_decl
test_delete_file
test_duplicate_parent
test_duplicated_file
test_failed_naming
test_funptr
test_gconst_file
test_get_dependent_classes
test_getfundeps
test_identify
test_ignore_fixme_hhi
test_infer_type
test_interrupt
test_interrupt2
test_lazy_decl_idempotence
test_modify_file
test_new_file
test_property_initializer
test_property_initializer2
test_server_hover
test_serverConfig_overrides
test_unbound_name
test_unbound_name_2
test_unbound_name_3)
(libraries runner_base))
(rule
(targets test_all.exe)
(action
(copy runner.exe test_all.exe)))
(rule
(targets test_all.bc.exe)
(action
(copy runner.bc.exe test_all.bc.exe)))
(rule
(alias server_config_overrides)
(deps test_all.exe)
(action
(run ./test_all.exe server_config_overrides)))
(rule
(alias ignore_fixme_hhi)
(deps test_all.exe)
(action
(run ./test_all.exe ignore_fixme_hhi)))
(rule
(alias new_file)
(deps test_all.exe)
(action
(run ./test_all.exe new_file)))
(rule
(alias property_initializer)
(deps test_all.exe)
(action
(run ./test_all.exe property_initializer)))
(rule
(alias property_initializer2)
(deps test_all.exe)
(action
(run ./test_all.exe property_initializer2)))
(rule
(alias capitalization)
(deps test_all.exe)
(action
(run ./test_all.exe capitalization)))
(rule
(alias modify_file)
(deps test_all.exe)
(action
(run ./test_all.exe modify_file)))
(rule
(alias delete_file)
(deps test_all.exe)
(action
(run ./test_all.exe delete_file)))
(rule
(alias duplicated_file)
(deps test_all.exe)
(action
(run ./test_all.exe duplicated_file)))
(rule
(alias duplicate_parent)
(deps test_all.exe)
(action
(run ./test_all.exe duplicate_parent)))
(rule
(alias added_parent)
(deps test_all.exe)
(action
(run ./test_all.exe added_parent)))
(rule
(alias get_dependent_classes)
(deps test_all.exe)
(action
(run ./test_all.exe get_dependent_classes)))
; ":integration_test_base",
; "//hphp/hack/src/decl:decl",
; "//hphp/hack/src/deps:deps",
; "//hphp/hack/src/errors:errors",
; "//hphp/hack/src/naming:naming",
; "//hphp/hack/src/server:server_env", "//hphp/hack/src/server:server_config",
; "//hphp/hack/src/utils/core:core",
; "//hphp/hack/src/utils:relative_path",
; "//hphp/hack/src/utils/collections:collections",
;
(rule
(alias infer_type)
(deps test_all.exe)
(action
(run ./test_all.exe infer_type)))
; ":integration_test_base",
; "//hphp/hack/src/decl:decl",
; "//hphp/hack/src/errors:errors",
; "//hphp/hack/src/hhi:hhi",
; "//hphp/hack/src/options:global_options",
; "//hphp/hack/src/options:tc_options",
; "//hphp/hack/src/server:server",
; "//hphp/hack/src/server:server_command_types",
; "//hphp/hack/src/server:server_env", "//hphp/hack/src/server:server_config",
; "//hphp/hack/src/server:server_services",
; "//hphp/hack/src/typing:typing",
; "//hphp/hack/src/typing:typing_ast",
; "//hphp/hack/src/utils/core:core",
; "//hphp/hack/src/utils/collections:collections",
(rule
(alias getfundeps)
(deps test_all.exe)
(action
(run ./test_all.exe getfundeps)))
(rule
(alias coeffects)
(deps test_all.exe)
(action
(run ./test_all.exe coeffects)))
(rule
(alias identify)
(deps test_all.exe)
(action
(run ./test_all.exe identify)))
(rule
(alias server_hover)
(deps test_all.exe)
(action
(run ./test_all.exe server_hover)))
(rule
(alias failed_naming)
(deps test_all.exe)
(action
(run ./test_all.exe failed_naming)))
; ":integration_test_base",
; "//hphp/hack/src/errors:errors",
; "//hphp/hack/src/server:server_env", "//hphp/hack/src/server:server_config",
(rule
(alias gconst_file)
(deps test_all.exe)
(action
(run ./test_all.exe gconst_file)))
; ":integration_test_base",
; "//hphp/hack/src/decl:decl",
; "//hphp/hack/src/deps:deps",
; "//hphp/hack/src/errors:errors",
; "//hphp/hack/src/heap:heap",
; "//hphp/hack/src/options:tc_options",
; "//hphp/hack/src/server:server_env", "//hphp/hack/src/server:server_config",
; "//hphp/hack/src/server:server_services",
; "//hphp/hack/src/typing:typing",
; "//hphp/hack/src/typing:typing_ast",
; "//hphp/hack/src/utils/core:core",
; "//hphp/hack/src/utils/collections:collections",
(rule
(alias unbound_name)
(deps test_all.exe)
(action
(run ./test_all.exe unbound_name)))
; ":integration_test_base",
; "//hphp/hack/src/errors:errors",
; "//hphp/hack/src/server:server_env", "//hphp/hack/src/server:server_config",
(rule
(alias decl_decl)
(deps test_all.exe)
(action
(run ./test_all.exe decl_decl)))
; ":integration_test_base",
; "//hphp/hack/src/decl:decl",
; "//hphp/hack/src/errors:errors",
; "//hphp/hack/src/server:server_env", "//hphp/hack/src/server:server_config",
; "//hphp/hack/src/utils/core:core",
; "//hphp/hack/src/utils/collections:collections",
(rule
(alias lazy_decl_idempotence)
(deps test_all.exe)
(action
(run ./test_all.exe lazy_decl_idempotence)))
; ":integration_test_base",
; "//hphp/hack/src/decl:decl",
; "//hphp/hack/src/deps:deps",
; "//hphp/hack/src/errors:errors",
; "//hphp/hack/src/heap:heap",
; "//hphp/hack/src/options:global_options",
; "//hphp/hack/src/options:parser_options",
; "//hphp/hack/src/options:tc_options",
; "//hphp/hack/src/server:server_env", "//hphp/hack/src/server:server_config",
; "//hphp/hack/src/server:server_services",
; "//hphp/hack/src/typing:typing_check_service",
; "//hphp/hack/src/utils/core:core",
; "//hphp/hack/src/utils:relative_path",
; "//hphp/hack/src/utils/collections:collections",
(rule
(alias interrupt)
(deps test_all.exe)
(action
(run ./test_all.exe interrupt)))
; ":integration_test_base",
; "//hphp/hack/src/decl:decl",
; "//hphp/hack/src/deps:deps",
; "//hphp/hack/src/errors:errors",
; "//hphp/hack/src/heap:heap",
; "//hphp/hack/src/naming:naming",
; "//hphp/hack/src/options:global_options",
; "//hphp/hack/src/options:parser_options",
; "//hphp/hack/src/options:tc_options",
; "//hphp/hack/src/procs:procs",
; "//hphp/hack/src/server:server",
; "//hphp/hack/src/server:server_env", "//hphp/hack/src/server:server_config",
; "//hphp/hack/src/server:server_services",
; "//hphp/hack/src/typing:typing_check_service",
; "//hphp/hack/src/utils/core:core",
; "//hphp/hack/src/utils:relative_path",
; "//hphp/hack/src/utils/collections:collections",
(rule
(alias interrupt2)
(deps test_all.exe)
(action
(run ./test_all.exe interrupt2)))
; ":integration_test_base",
; "//hphp/hack/src/decl:decl",
; "//hphp/hack/src/deps:deps",
; "//hphp/hack/src/errors:errors",
; "//hphp/hack/src/heap:heap",
; "//hphp/hack/src/options:global_options",
; "//hphp/hack/src/options:parser_options",
; "//hphp/hack/src/options:tc_options",
; "//hphp/hack/src/procs:procs",
; "//hphp/hack/src/server:server",
; "//hphp/hack/src/server:server_extras",
; "//hphp/hack/src/server:server_services",
; "//hphp/hack/src/typing:typing_check_service",
; "//hphp/hack/src/utils/core:core",
; "//hphp/hack/src/utils:relative_path",
; "//hphp/hack/src/utils/collections:collections",
(alias
(name runtest)
(deps
(alias new_file)
(alias capitalization)
(alias coeffects)
(alias modify_file)
(alias delete_file)
(alias duplicated_file)
(alias duplicate_parent)
(alias added_parent)
(alias get_dependent_classes)
(alias infer_type)
(alias getfundeps)
(alias identify)
(alias server_hover)
(alias failed_naming)
(alias gconst_file)
(alias unbound_name)
(alias decl_decl)
(alias property_initializer)
(alias property_initializer2)
(alias lazy_decl_idempotence)
(alias ignore_fixme_hhi)
(alias interrupt)
(alias interrupt2))) |
|
OCaml | hhvm/hphp/hack/test/integration_ml/integration_test_base.ml | (*
* Copyright (c) 2016, 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.
*
*
*)
open Hh_prelude
open Integration_test_base_types
open Reordered_argument_collections
open ServerCommandTypes
open SearchServiceRunner
open Int.Replace_polymorphic_compare
exception Integration_test_failure
module FileMap = SMap
module ErrorSet = SSet
type error_messages_per_file = ErrorSet.t FileMap.t [@@deriving eq, show]
let root = "/"
let hhi = "/hhi"
let tmp = "/tmp"
let () = Folly.ensure_folly_init ()
let () = Hh_logger.Level.set_min_level Hh_logger.Level.Off
let server_config = ServerEnvBuild.default_genv.ServerEnv.config
let global_opts =
GlobalOptions.set
~tco_num_local_workers:1
~tco_saved_state:GlobalOptions.default_saved_state
~po_disable_xhp_element_mangling:false
~po_deregister_php_stdlib:true
GlobalOptions.default
let server_config = ServerConfig.set_tc_options server_config global_opts
let server_config = ServerConfig.set_parser_options server_config global_opts
let genv =
ref { ServerEnvBuild.default_genv with ServerEnv.config = server_config }
let did_init = ref false
let real_hhi_files () = Hhi.get_raw_hhi_contents () |> Array.to_list
(* Init part common to fresh and saved state init *)
let test_init_common ?(hhi_files = []) () =
if !did_init then
failwith
("Initializing the server twice in same process. There is no guarantee of global state "
^ "cleanup between them. Split your test in multiple separate tests, or run individual test "
^ "cases in separate processes using Test.in_daemon.")
else
did_init := true;
Unix.putenv "HH_TEST_MODE" "1";
Printexc.record_backtrace true;
EventLogger.init_fake ();
Relative_path.set_path_prefix Relative_path.Root (Path.make root);
Relative_path.set_path_prefix Relative_path.Hhi (Path.make hhi);
Relative_path.set_path_prefix Relative_path.Tmp (Path.make tmp);
ServerProgress.disable ();
let handle = SharedMem.init ~num_workers:0 SharedMem.default_config in
ignore (handle : SharedMem.handle);
ServerMain.force_break_recheck_loop_for_test true;
List.iter hhi_files ~f:(fun (fn, contents) ->
TestDisk.set (Filename.concat hhi fn) contents);
()
(* Hhi files are loaded during server setup. If given a list of string + contents, we add them
to the test disk and add them to disk_needs_parsing. After one server run loop, they will be loaded.
This isn't exactly the same as how initialization does it, but the purpose is not to test the hhi
files, but to test incremental mode behavior with Hhi files present.
*)
let setup_server ?custom_config ?(hhi_files = []) ?edges_dir () : ServerEnv.env
=
test_init_common () ~hhi_files;
let init_id = Random_id.short_string () in
let deps_mode =
match edges_dir with
| Some edges_dir ->
Typing_deps_mode.SaveToDiskMode
{
graph = None;
new_edges_dir = edges_dir;
human_readable_dep_map_dir = None;
}
| None -> Typing_deps_mode.InMemoryMode None
in
let env =
match custom_config with
| Some config -> ServerEnvBuild.make_env ~init_id ~deps_mode config
| None -> ServerEnvBuild.make_env ~init_id ~deps_mode !genv.ServerEnv.config
in
let hhi_file_list =
List.map hhi_files ~f:(fun (fn, _) ->
Relative_path.create Relative_path.Hhi (Filename.concat hhi fn))
in
let hhi_set = Relative_path.Set.of_list hhi_file_list in
(* Initialize symbol index *)
let sienv =
SymbolIndex.initialize
~gleanopt:env.ServerEnv.gleanopt
~namespace_map:[]
~provider_name:"LocalIndex"
~quiet:true
~savedstate_file_opt:None
~workers:None
in
ServerProgress.disable ();
(* Return environment *)
{
env with
ServerEnv.disk_needs_parsing = hhi_set;
ServerEnv.local_symbol_table = sienv;
}
let default_loop_input =
{ disk_changes = []; new_client = None; persistent_client_request = None }
let run_loop_once :
type a b.
ServerEnv.env -> (a, b) loop_inputs -> ServerEnv.env * (a, b) loop_outputs =
fun env inputs ->
TestClientProvider.clear ();
Option.iter inputs.new_client ~f:(function
| RequestResponse x ->
TestClientProvider.mock_new_client_type Non_persistent;
TestClientProvider.mock_client_request x
| ConnectPersistent -> TestClientProvider.mock_new_client_type Persistent);
Option.iter inputs.persistent_client_request ~f:(function
| Request x -> TestClientProvider.mock_persistent_client_request x
| UncleanDisconect x ->
TestClientProvider.mock_persistent_client_request x;
TestClientProvider.mock_unclean_disconnect ());
let client_provider = ClientProvider.provider_for_test () in
let disk_changes =
List.map inputs.disk_changes ~f:(fun (x, y) -> (root ^ x, y))
in
List.iter disk_changes ~f:(fun (path, contents) -> TestDisk.set path contents);
let did_read_disk_changes_ref = ref false in
let get_changes_sync () =
ServerNotifier.SyncChanges
(if not !did_read_disk_changes_ref then (
did_read_disk_changes_ref := true;
SSet.of_list (List.map disk_changes ~f:fst)
) else
SSet.empty)
in
let get_changes_async () = get_changes_sync () in
let genv =
{
!genv with
ServerEnv.notifier =
ServerNotifier.init_mock ~get_changes_sync ~get_changes_async;
}
in
(* Always pick up disk changes in tests immediately *)
let env = ServerEnv.{ env with last_notifier_check_time = 0.0 } in
let env = ServerMain.serve_one_iteration genv env client_provider in
let ctx = Provider_utils.ctx_from_server_env env in
let env =
{
env with
ServerEnv.local_symbol_table =
SearchServiceRunner.run_completely ctx env.ServerEnv.local_symbol_table;
}
in
let {
ServerEnv.RecheckLoopStats.total_changed_files_count;
total_rechecked_count;
_;
} =
env.ServerEnv.last_recheck_loop_stats
in
( env,
{
did_read_disk_changes = !did_read_disk_changes_ref;
total_changed_files_count;
total_rechecked_count;
last_actual_total_rechecked_count =
(match env.ServerEnv.last_recheck_loop_stats_for_actual_work with
| None -> None
| Some stats ->
Some stats.ServerEnv.RecheckLoopStats.total_rechecked_count);
new_client_response =
TestClientProvider.get_client_response Non_persistent;
persistent_client_response =
TestClientProvider.get_client_response Persistent;
push_messages = TestClientProvider.get_push_messages ();
} )
let prepend_root x = root ^ x
let fail x =
print_endline x;
Caml.Printexc.(get_callstack 100 |> print_raw_backtrace stderr);
raise Integration_test_failure
(******************************************************************************(
* Utility functions to help format/throw errors for informative errors
)******************************************************************************)
let indent_string_with (indent : string) (error : string) : string =
indent ^ String.concat ~sep:("\n" ^ indent) Str.(split (regexp "\n") error)
let indent_strings_with (indent : string) (errors : string list) : string =
String.concat ~sep:"" @@ List.map ~f:(indent_string_with indent) errors
let fail_on_none (error : string) optional_thing =
match optional_thing with
| None -> fail error
| Some _ -> ()
let assert_responded (error : string) loop_output =
fail_on_none error loop_output.persistent_client_response
let assertEqual expected got =
let expected = String.strip expected in
let got = String.strip got in
if String.( <> ) expected got then
fail (Printf.sprintf "Expected:\n%s\n\nBut got:\n%s\n" expected got)
let assert_errors_equal
~(expected : error_messages_per_file) ~(got : error_messages_per_file) :
unit =
if not (equal_error_messages_per_file expected got) then
fail
(Printf.sprintf
"Expected errors:\n%s\n\nBut got:\n%s\n"
(show_error_messages_per_file expected)
(show_error_messages_per_file got))
let change_files env disk_changes =
let (env, loop_output) =
run_loop_once env { default_loop_input with disk_changes }
in
if not loop_output.did_read_disk_changes then
fail "Expected the server to process disk updates";
(env, loop_output)
let setup_disk env disk_changes = fst @@ change_files env disk_changes
let connect_persistent_client env =
let (env, _) =
run_loop_once
env
{ default_loop_input with new_client = Some ConnectPersistent }
in
fail_on_none
"Expected persistent client to be connected"
(Ide_info_store.get_client ());
env
let error_strings err_list =
List.map ~f:(fun x -> Errors.to_string (User_error.to_absolute x)) err_list
let assertSingleError expected err_list =
let error_strings = error_strings err_list in
match error_strings with
| [x] -> assertEqual expected x
| _ ->
let err_count = List.length err_list in
let fmt_expected = indent_string_with " < " expected in
let fmt_actual = indent_strings_with " > " error_strings in
let msg =
Printf.sprintf
"Expected to have exactly one error, namely:
%s
... but got %d errors...
%s
"
fmt_expected
err_count
fmt_actual
in
fail msg
let open_file env ?contents file_name =
let file_name = root ^ file_name in
let contents =
match contents with
| Some contents -> contents
| _ -> TestDisk.get file_name
in
let (env, loop_output) =
run_loop_once
env
{
default_loop_input with
persistent_client_request =
Some (Request (OPEN_FILE (file_name, contents)));
}
in
assert_responded "Expected OPEN_FILE to be processeded" loop_output;
env
let edit_file env name contents =
let (env, loop_output) =
run_loop_once
env
{
default_loop_input with
persistent_client_request =
Some
(Request
(EDIT_FILE
( root ^ name,
[{ Ide_api_types.range = None; text = contents }] )));
}
in
assert_responded "Expected EDIT_FILE to be processed" loop_output;
(env, loop_output)
let save_file env name contents =
let (env, loop_output) =
run_loop_once
env
{ default_loop_input with disk_changes = [(name, contents)] }
in
if not loop_output.did_read_disk_changes then
fail "Expected the server to process disk updates";
(env, loop_output)
let close_file ?(ignore_response = false) env name =
let (env, loop_output) =
run_loop_once
env
{
default_loop_input with
persistent_client_request = Some (Request (CLOSE_FILE (root ^ name)));
}
in
if not ignore_response then
assert_responded "Expected CLOSE_FILE to be processed" loop_output;
(env, loop_output)
let wait env =
(* We simulate waiting a while since last command by manipulating
* last_command_time. Will not work on timers that compare against other
* counters. *)
ServerEnv.{ env with last_command_time = env.last_command_time -. 60.0 }
let ide_autocomplete env (path, line, column) =
let is_manually_invoked = false in
run_loop_once
env
{
default_loop_input with
persistent_client_request =
Some
(Request
(IDE_AUTOCOMPLETE
( root ^ path,
Ide_api_types.{ line; column },
is_manually_invoked )));
}
let status ?(ignore_ide = false) ?(max_errors = None) ?(remote = false) env =
run_loop_once
env
{
default_loop_input with
new_client =
Some
(RequestResponse
(ServerCommandTypes.STATUS { ignore_ide; max_errors; remote }));
}
let full_check_status env =
(* the empty string isn't just a test placeholder - when a file is deleted
or renamed, the content is set to the empty string internally *)
run_loop_once
env
{
default_loop_input with
disk_changes = [("__dummy_file_to_trigger_full_check.php", "")];
}
let start_initial_full_check env =
(match env.ServerEnv.prechecked_files with
| ServerEnv.Initial_typechecking _ -> ()
| _ -> assert false);
let (env, loop_output) = full_check_status env in
(match env.ServerEnv.prechecked_files with
| ServerEnv.Prechecked_files_ready _ -> ()
| _ -> assert false);
let { total_rechecked_count; _ } = loop_output in
(* full_check_status adds a dummy file to trigger a recheck, so we subtract one here
and return the number of rechecked non-dummy files. *)
assert (total_rechecked_count >= 1);
(env, total_rechecked_count - 1)
let assert_has_diagnostics loop_output =
match
List.find loop_output.push_messages ~f:(function
| DIAGNOSTIC _ -> true
| _ -> false)
with
| Some _ -> ()
| None ->
fail
(Printf.sprintf
"Expected at least one DIAGNOSTIC message, but got %s"
(ServerCommandTypes.show_pushes loop_output.push_messages))
let errors_to_string buf x =
List.iter x ~f:(fun error ->
Printf.bprintf buf "%s\n" (Errors.to_string error))
let print_telemetries env =
Printf.eprintf "\n==Telemetries==\n";
List.iter
ServerEnv.(env.last_recheck_loop_stats.RecheckLoopStats.per_batch_telemetry)
~f:(fun t -> Printf.eprintf "%s\n" (Telemetry.to_string ~pretty:true t))
let assert_errors errors expected =
let buf = Buffer.create 1024 in
Errors.get_error_list errors
|> List.map ~f:User_error.to_absolute
|> errors_to_string buf;
assertEqual expected (Buffer.contents buf)
let assert_env_errors env expected = assert_errors env.ServerEnv.errorl expected
let assert_no_errors env = assert_env_errors env ""
let saved_state_filename = "test_saved_state"
let saved_naming_filename = "test_saved_naming"
let in_daemon f =
let handle =
Daemon.fork_FOR_TESTING_ON_UNIX_ONLY
~channel_mode:`socket
Unix.(stdout, stderr)
(fun () _channels -> f ())
()
in
match Unix.waitpid [] handle.Daemon.pid with
| (_, Unix.WEXITED 0) -> ()
| _ -> assert false
let build_dep_graph ~output ~edges_dir =
let hh_fanout = Sys.getenv "HH_FANOUT_BIN" in
let cmd =
Printf.sprintf
"%s build --allow-empty --output %s --edges-dir %s"
(Filename.quote hh_fanout)
(Filename.quote output)
(Filename.quote edges_dir)
in
let () = assert (Sys.command cmd = 0) in
()
let build_dep_graph_incr ~output ~old_graph ~delta =
let hh_fanout = Sys.getenv "HH_FANOUT_BIN" in
let cmd =
Printf.sprintf
"%s build --allow-empty --output %s --incremental %s --delta %s"
(Filename.quote hh_fanout)
(Filename.quote output)
(Filename.quote old_graph)
(Filename.quote delta)
in
let () = assert (Sys.command cmd = 0) in
()
let save_state
?(load_hhi_files = false)
?(store_decls_in_saved_state =
ServerLocalConfig.(default.store_decls_in_saved_state))
?(enable_naming_table_fallback = false)
?custom_config
disk_changes
temp_dir =
in_daemon @@ fun () ->
let hhi_files =
if load_hhi_files then
real_hhi_files ()
else
[]
in
let edges_dir = temp_dir ^ "/edges/" in
RealDisk.mkdir_p edges_dir;
(* We don't support multiple workers! And don't use any *)
Typing_deps.worker_id := Some 0;
let env = setup_server () ~edges_dir ?custom_config ~hhi_files in
let env = setup_disk env disk_changes in
assert_no_errors env;
genv :=
{
!genv with
ServerEnv.local_config =
{
!genv.ServerEnv.local_config with
ServerLocalConfig.store_decls_in_saved_state;
ServerLocalConfig.enable_naming_table_fallback;
};
ServerEnv.config =
Option.value custom_config ~default:!genv.ServerEnv.config;
};
let _edges_added =
ServerInit.save_state !genv env (temp_dir ^ "/" ^ saved_state_filename)
in
let output = temp_dir ^ "/" ^ saved_state_filename ^ ".hhdg" in
build_dep_graph ~output ~edges_dir;
if enable_naming_table_fallback then (
let _rows_added =
SaveStateService.go_naming
env.ServerEnv.naming_table
(temp_dir ^ "/" ^ saved_naming_filename)
|> Result.ok_or_failwith
in
();
()
)
let save_state_incremental
env
?(store_decls_in_saved_state =
ServerLocalConfig.(default.store_decls_in_saved_state))
~old_state_dir
new_state_dir =
assert_no_errors env;
genv :=
{
!genv with
ServerEnv.local_config =
{
!genv.ServerEnv.local_config with
ServerLocalConfig.store_decls_in_saved_state;
};
};
let result =
ServerInit.save_state !genv env (new_state_dir ^ "/" ^ saved_state_filename)
in
let old_graph = old_state_dir ^ "/" ^ saved_state_filename ^ ".hhdg" in
let output = new_state_dir ^ "/" ^ saved_state_filename ^ ".hhdg" in
let delta =
new_state_dir ^ "/" ^ saved_state_filename ^ "_64bit_dep_graph.delta"
in
build_dep_graph_incr ~output ~old_graph ~delta;
result
let save_state_with_errors disk_changes temp_dir expected_error : unit =
in_daemon @@ fun () ->
let edges_dir = temp_dir ^ "/edges/" in
RealDisk.mkdir_p edges_dir;
(* We don't support multiple workers! And don't use any *)
Typing_deps.worker_id := Some 0;
let env = setup_server ~edges_dir () in
let env = setup_disk env disk_changes in
assert_env_errors env expected_error;
let genv =
{
!genv with
ServerEnv.options =
ServerArgs.set_gen_saved_ignore_type_errors !genv.ServerEnv.options true;
}
in
let _edges_added =
ServerInit.save_state genv env (temp_dir ^ "/" ^ saved_state_filename)
in
let output = temp_dir ^ "/" ^ saved_state_filename ^ ".hhdg" in
build_dep_graph ~output ~edges_dir;
()
let load_state
?(master_changes = [])
?(local_changes = [])
?(load_hhi_files = false)
?(use_precheked_files = ServerLocalConfig.(default.prechecked_files))
?(enable_naming_table_fallback = false)
?custom_config
~disk_state
saved_state_dir =
(* In production, saved state is only used in conjunction with lazy init
* right now, and I'm not convinced if it even works in any other
* configuration. *)
genv :=
{
!genv with
ServerEnv.local_config =
{
!genv.ServerEnv.local_config with
ServerLocalConfig.lazy_parse = true;
lazy_init = true;
prechecked_files = use_precheked_files;
predeclare_ide = true;
naming_sqlite_path =
(if enable_naming_table_fallback then
Some (saved_state_dir ^ "/" ^ saved_naming_filename)
else
None);
enable_naming_table_fallback;
};
ServerEnv.config =
Option.value custom_config ~default:!genv.ServerEnv.config;
};
let hhi_files =
if load_hhi_files then
real_hhi_files ()
else
[]
in
test_init_common () ~hhi_files;
let disk_changes = List.map disk_state ~f:(fun (x, y) -> (root ^ x, y)) in
List.iter disk_changes ~f:(fun (path, contents) -> TestDisk.set path contents);
let prechecked_changes =
List.map master_changes ~f:(fun x ->
Relative_path.create_detect_prefix (root ^ x))
in
let changes =
List.map local_changes ~f:(fun x ->
Relative_path.create_detect_prefix (root ^ x))
in
let naming_table_path = saved_state_dir ^ "/" ^ saved_state_filename in
let deptable_fn = saved_state_dir ^ "/" ^ saved_state_filename ^ ".hhdg" in
let load_state_approach =
ServerInit.Precomputed
{
ServerArgs.naming_table_path;
(* in Precomputed scenario, base revision should only be used in logging,
* which is irrelevant in tests *)
corresponding_base_revision = "-1";
deptable_fn;
compressed_deptable_fn = None;
naming_changes = [];
prechecked_changes;
changes;
}
in
let init_id = Random_id.short_string () in
let env =
ServerEnvBuild.make_env
~init_id
~deps_mode:(Typing_deps_mode.InMemoryMode (Some deptable_fn))
!genv.ServerEnv.config
in
match
ServerInit.init
~init_approach:(ServerInit.Saved_state_init load_state_approach)
!genv
env
with
| (env, ServerInit.Load_state_succeeded _) -> env
| (_env, ServerInit.Load_state_declined s) ->
Printf.eprintf "> DECLINED %s\n" s;
assert false
| (_env, ServerInit.Load_state_failed (s, telemetry)) ->
Printf.eprintf "> FAILED %s: %s\n" s (Telemetry.to_string telemetry);
assert false
let diagnostics_to_string (x : ServerCommandTypes.diagnostic_errors) =
let buf = Buffer.create 1024 in
SMap.iter x ~f:(fun path errors ->
Printf.bprintf buf "%s:\n" path;
errors_to_string buf errors);
Buffer.contents buf
let diagnostics_to_strings (diagnostics : ServerCommandTypes.diagnostic_errors)
: error_messages_per_file =
FileMap.map diagnostics ~f:(fun errors ->
errors
|> List.map ~f:(fun err -> err |> Errors.to_string |> String.strip)
|> ErrorSet.of_list)
let errors_to_string x =
let buf = Buffer.create 1024 in
errors_to_string buf x;
Buffer.contents buf
let get_diagnostics loop_output : diagnostic_errors =
List.filter_map loop_output.push_messages ~f:(function
| DIAGNOSTIC { errors; is_truncated = _ } -> Some errors
| _ -> None)
|> List.fold
~init:FileMap.empty
~f:
(SMap.union ~combine:(fun _ err _ ->
(* Only take the most recent diagnostic per file *) Some err))
let assert_no_diagnostics loop_output =
match loop_output.push_messages with
| DIAGNOSTIC _ :: _ ->
let diagnostics = get_diagnostics loop_output in
let diagnostics_as_string = diagnostics_to_string diagnostics in
fail
("Did not expect to receive push diagnostics. Got:\n"
^ diagnostics_as_string)
| NEW_CLIENT_CONNECTED :: _ -> fail "Unexpected push message"
| _ -> ()
let assert_diagnostics loop_output (expected : error_messages_per_file) =
let diagnostics = get_diagnostics loop_output in
let diagnostics_as_strings = diagnostics_to_strings diagnostics in
assert_errors_equal ~expected ~got:diagnostics_as_strings
let assert_diagnostics_string loop_output (expected : string) =
let diagnostics = get_diagnostics loop_output in
let diagnostics_as_string = diagnostics_to_string diagnostics in
assertEqual expected diagnostics_as_string
let assert_diagnostics_in loop_output ~filename expected =
let diagnostics = get_diagnostics loop_output in
let diagnostics =
SMap.filter diagnostics ~f:(fun path _ ->
String.equal path (prepend_root filename))
in
let diagnostics_as_string = diagnostics_to_string diagnostics in
assertEqual expected diagnostics_as_string
let list_to_string l =
let buf = Buffer.create 1024 in
List.iter l ~f:(Printf.bprintf buf "%s ");
Buffer.contents buf
let assert_ide_autocomplete_does_not_contain loop_output not_expected =
let results =
match loop_output.persistent_client_response with
| Some res -> res
| _ -> fail "Expected autocomplete response"
in
let results =
List.map results.AutocompleteTypes.completions ~f:(fun x ->
x.AutocompleteTypes.res_label)
in
let results = SSet.of_list results in
let not_expected = SSet.of_list not_expected in
let occured = SSet.inter results not_expected in
if SSet.is_empty occured |> not then
Printf.sprintf
"unexpected symbol(s) %s occurs in autocomplete list"
(SSet.show occured)
|> fail
else
()
let assert_ide_autocomplete loop_output expected =
let results =
match loop_output.persistent_client_response with
| Some res -> res
| _ -> fail "Expected autocomplete response"
in
let results =
List.map results.AutocompleteTypes.completions ~f:(fun x ->
x.AutocompleteTypes.res_label)
in
let results_as_string = list_to_string results in
let expected_as_string = list_to_string expected in
assertEqual expected_as_string results_as_string
let assert_status loop_output expected =
let { Server_status.error_list; _ } =
match loop_output.new_client_response with
| Some res -> res
| _ -> fail "Expected status response"
in
let results_as_string = errors_to_string error_list in
assertEqual expected results_as_string
let assert_error_count loop_output ~expected_count =
let { Server_status.error_list; _ } =
match loop_output.new_client_response with
| Some res -> res
| _ -> fail "Expected status response"
in
let actual_count = List.length error_list in
Asserter.Int_asserter.assert_equals
expected_count
actual_count
(Printf.sprintf
"Expected %d errors, but got %d"
expected_count
actual_count)
let assert_needs_retry loop_output =
Done_or_retry.(
match loop_output.persistent_client_response with
| Some Retry -> ()
| Some (Done _) -> fail "Expected needing to retry"
| None -> fail "Expected response")
let assert_response loop_output =
Done_or_retry.(
match loop_output.persistent_client_response with
| Some (Done res) -> res
| Some Retry -> fail "Expecteded not needing to retry"
| None -> fail "Expected response")
let assert_find_refs loop_output expected =
let results = assert_response loop_output in
let results =
List.map results ~f:(fun (name, pos) -> name ^ ": " ^ Pos.string pos)
in
let results_as_string = list_to_string results in
let expected_as_string = list_to_string expected in
assertEqual expected_as_string results_as_string
let assert_rename loop_output expected =
let results = assert_response loop_output in
(* We don't have any (better than JSON) human-readable format for rename results,
* and I'm too lazy to write it. Tests will have to compare JSON outputs for now. *)
let results_as_string = ClientRename.patches_to_json_string results in
assertEqual expected results_as_string
let assert_ide_rename loop_output expected =
let results = assert_response loop_output in
let results = Result.ok_or_failwith results in
let results_as_string = ClientRename.patches_to_json_string results in
assertEqual expected results_as_string
let assert_needs_recheck env x =
if
not
Relative_path.(
Set.mem env.ServerEnv.needs_recheck (create_detect_prefix (root ^ x)))
then
let () = Printf.eprintf "Expected %s to need recheck\n" x in
assert false
let assert_needs_no_recheck env x =
if
Relative_path.(
Set.mem env.ServerEnv.needs_recheck (create_detect_prefix (root ^ x)))
then
let () = Printf.eprintf "Expected %s not to need recheck\n" x in
assert false |
OCaml Interface | hhvm/hphp/hack/test/integration_ml/integration_test_base.mli | (*
* Copyright (c) 2016, 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.
*
*
*)
open Reordered_argument_collections
open Integration_test_base_types
module FileMap = SMap
module ErrorSet = SSet
type error_messages_per_file = ErrorSet.t FileMap.t [@@deriving eq, show]
val setup_server :
?custom_config:ServerConfig.t ->
?hhi_files:(string * string) list ->
?edges_dir:string ->
unit ->
ServerEnv.env
val setup_disk : ServerEnv.env -> disk_changes_type -> ServerEnv.env
val change_files :
ServerEnv.env -> disk_changes_type -> ServerEnv.env * ('a, unit) loop_outputs
val save_state :
?load_hhi_files:bool ->
?store_decls_in_saved_state:bool ->
?enable_naming_table_fallback:bool ->
?custom_config:ServerConfig.t ->
disk_changes_type ->
string ->
unit
val save_state_incremental :
ServerEnv.env ->
?store_decls_in_saved_state:bool ->
old_state_dir:string ->
string ->
SaveStateServiceTypes.save_state_result option
val save_state_with_errors : disk_changes_type -> string -> string -> unit
val load_state :
?master_changes:string list ->
?local_changes:string list ->
?load_hhi_files:bool ->
?use_precheked_files:bool ->
?enable_naming_table_fallback:bool ->
?custom_config:ServerConfig.t ->
disk_state:disk_changes_type ->
string (* saved_state_dir *) ->
ServerEnv.env
val in_daemon : (unit -> unit) -> unit
val connect_persistent_client : ServerEnv.env -> ServerEnv.env
val default_loop_input : ('a, 'b) loop_inputs
val run_loop_once :
ServerEnv.env -> ('a, 'b) loop_inputs -> ServerEnv.env * ('a, 'b) loop_outputs
(* wrappers around run_loop_once for most common operations *)
val open_file : ServerEnv.env -> ?contents:string -> string -> ServerEnv.env
val edit_file :
ServerEnv.env -> string -> string -> ServerEnv.env * ('a, unit) loop_outputs
val save_file :
ServerEnv.env -> string -> string -> ServerEnv.env * ('a, unit) loop_outputs
val close_file :
?ignore_response:bool ->
ServerEnv.env ->
string ->
ServerEnv.env * ('a, unit) loop_outputs
val wait : ServerEnv.env -> ServerEnv.env
val ide_autocomplete :
ServerEnv.env ->
string * int * int ->
ServerEnv.env * ('a, AutocompleteTypes.ide_result) loop_outputs
val status :
?ignore_ide:bool ->
?max_errors:int option ->
?remote:bool ->
ServerEnv.env ->
ServerEnv.env * (ServerCommandTypes.Server_status.t, 'a) loop_outputs
val full_check_status : ServerEnv.env -> ServerEnv.env * ('a, unit) loop_outputs
val start_initial_full_check : ServerEnv.env -> ServerEnv.env * int
val prepend_root : string -> string
val errors_to_string : Errors.finalized_error list -> string
val print_telemetries : ServerEnv.env -> unit
(* Helpers for asserting things *)
val fail : string -> 'noreturn
val assertEqual : string -> string -> unit
val assert_no_errors : ServerEnv.env -> unit
val assert_errors : Errors.t -> string -> unit
val assert_env_errors : ServerEnv.env -> string -> unit
val assertSingleError : string -> Errors.error list -> unit
val assert_no_diagnostics : ('a, 'b) loop_outputs -> unit
val assert_has_diagnostics : ('a, 'b) loop_outputs -> unit
val assert_diagnostics :
('a, 'b) loop_outputs -> error_messages_per_file -> unit
val assert_diagnostics_string : ('a, 'b) loop_outputs -> string -> unit
val assert_diagnostics_in :
('a, 'b) loop_outputs -> filename:string -> string -> unit
val get_diagnostics :
('a, 'b) loop_outputs -> Errors.finalized_error list SMap.t
val assert_ide_autocomplete_does_not_contain :
('a, AutocompleteTypes.ide_result) loop_outputs -> string list -> unit
val assert_ide_autocomplete :
('a, AutocompleteTypes.ide_result) loop_outputs -> string list -> unit
val assert_status :
(ServerCommandTypes.Server_status.t, 'a) loop_outputs -> string -> unit
val assert_error_count :
(ServerCommandTypes.Server_status.t, 'a) loop_outputs ->
expected_count:int ->
unit
val assert_needs_retry :
('a, 'b ServerCommandTypes.Done_or_retry.t) loop_outputs -> unit
val assert_find_refs :
('a, ServerCommandTypes.Find_refs.result_or_retry) loop_outputs ->
string list ->
unit
val assert_rename :
('a, ServerCommandTypes.Rename.result_or_retry) loop_outputs -> string -> unit
val assert_ide_rename :
('a, ServerCommandTypes.Rename.ide_result_or_retry) loop_outputs ->
string ->
unit
val assert_needs_recheck : ServerEnv.env -> string -> unit
val assert_needs_no_recheck : ServerEnv.env -> string -> unit
val error_strings : Errors.error list -> string list |
OCaml | hhvm/hphp/hack/test/integration_ml/integration_test_base_types.ml | (*
* Copyright (c) 2016, 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.
*
*
*)
type 'a new_client_type =
| RequestResponse of 'a ServerCommandTypes.t
| ConnectPersistent
type 'a persistent_client_type =
| Request of 'a ServerCommandTypes.t
| UncleanDisconect of 'a ServerCommandTypes.t
type disk_changes_type = (string * string) list
type ('a, 'b) loop_inputs = {
disk_changes: disk_changes_type;
new_client: 'a new_client_type option;
persistent_client_request: 'b persistent_client_type option;
}
type ('a, 'b) loop_outputs = {
did_read_disk_changes: bool;
total_changed_files_count: int;
total_rechecked_count: int;
last_actual_total_rechecked_count: int option;
new_client_response: 'a option;
persistent_client_response: 'b option;
push_messages: ServerCommandTypes.push list;
} |
OCaml | hhvm/hphp/hack/test/integration_ml/runner.ml | (*
* 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.
*
*)
let run = Runner_base.run
let tests =
[
("ide/added_parent", run Test_added_parent.test);
("ide/auto_ns_aliasing", run Test_auto_ns_aliasing.test);
("ide/diagnostics_in_closed_file", run Test_diagnostics_in_closed_file.test);
("ide/error_pos", run Test_error_pos.test);
("ide/error_throttling", run Test_error_throttling.test);
("ide/error_throttling_open_file", run Test_error_throttling_open_file.test);
("ide/exception_handling", run Test_exception_handling.test);
("ide/failed_naming", run Test_failed_naming.test);
("ide/hhi_phpstdlib", run Test_hhi_phpstdlib.test);
("ide/ide_check", run Test_ide_check.test);
("ide/ide_close", run Test_ide_close.test);
("ide/ide_consistency", run Test_ide_consistency.test);
("ide/ide_disk", run Test_ide_disk.test);
("ide/ide_file_sync", run Test_ide_file_sync.test);
("ide/identify_symbol", run Test_identify_symbol.test);
("ide/ide_parsing_errors", run Test_ide_parsing_errors.test);
("ide/ide_redecl", run Test_ide_redecl.test);
("ide/ide_status", run Test_ide_status.test);
("ide/ide_typing_deps", run Test_ide_typing_deps.test);
("ide/max_errors", run Test_max_errors.test);
("ide/naming_errors", run Test_naming_errors.test);
("ide/override", run Test_override.test);
("ide/remove_function", run Test_remove_function.test);
("ide/remove_parent", run Test_remove_parent.test);
("ide/status_single", run Test_status_single.test);
("ide/unsaved_changes", run Test_unsaved_changes.test);
("added_parent", run Test_added_parent.test);
("capitalization", run Test_capitalization.test);
("coeffects", run Test_coeffects.test);
("decl_decl", run Test_decl_decl.test);
("delete_file", run Test_delete_file.test);
("duplicated_file", run Test_duplicated_file.test);
("duplicate_parent", run Test_duplicate_parent.test);
("failed_naming", run Test_failed_naming.test);
("funptr", run Test_funptr.test);
("gconst_file", run Test_gconst_file.test);
("get_dependent_classes", run Test_get_dependent_classes.test);
("getfundeps", run Test_getfundeps.test);
("identify", run Test_identify.test);
("ignore_fixme_hhi", run Test_ignore_fixme_hhi.test);
("infer_type", run Test_infer_type.test);
("interrupt2", run Test_interrupt2.test);
("interrupt", run Test_interrupt.test);
("lazy_decl_idempotence", run Test_lazy_decl_idempotence.test);
("modify_file", run Test_modify_file.test);
("new_file", run Test_new_file.test);
("property_initializer", run Test_property_initializer.test);
("property_initializer2", run Test_property_initializer2.test);
("server_config_overrides", run Test_serverConfig_overrides.test);
("server_hover", run Test_server_hover.test);
("unbound_name", run Test_unbound_name.test);
("unbound_name_2", run Test_unbound_name_2.test);
("unbound_name_3", run Test_unbound_name_3.test);
]
let () = Runner_base.go tests |
OCaml | hhvm/hphp/hack/test/integration_ml/runner_base.ml | (*
* 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.
*
*)
let run (f : unit -> unit) : unit -> bool =
fun () ->
f ();
true
let go tests =
if Array.length Sys.argv != 2 then
failwith "Expecting exactly one test name"
else
let test_name = Sys.argv.(1) in
let tests = List.filter (fun (name, _test) -> test_name = name) tests in
match tests with
| [] -> failwith (Printf.sprintf "Test named '%s' was not found!" test_name)
| [test] -> Unit_test.run_all [test]
| _ :: _ :: _ ->
failwith
(Printf.sprintf "More than one test named '%s' was found!" test_name) |
OCaml | hhvm/hphp/hack/test/integration_ml/server_progress_tests.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Asserter
open Server_progress_test_helpers
let a_php = ("a.php", "<?hh\nfunction test_a(): void {}\n")
let b_php = ("b.php", "<?hh\nfunction test_b(): string {}\n")
let loop_php =
("loop.php", "<?hh\nfunction test_loop(): void {hh_loop_forever();}")
let assert_substring (s : string) ~(substring : string) : unit =
if not (String.is_substring s ~substring) then
let msg =
Printf.sprintf
"Expected to find substring '%s' but only found:\n%s"
substring
s
in
failwith msg
(** Shell out to HH_CLIENT_PATH and return its results once it's finished.
In case of success return stdout; in case of failure return a human-readable
representation that includes exit signal and stderr. *)
let hh ~(tmp : Path.t) ~(root : Path.t) (args : string array) : string Lwt.t =
Sys.chdir (Path.to_string root);
let hh_client_path = Sys.getenv "HH_CLIENT_PATH" in
let env =
Array.append [| "HH_TMPDIR=" ^ Path.to_string tmp |] (Unix.environment ())
in
Printf.eprintf
"[%s] EXECUTE: hh %s\n%!"
(Utils.timestring (Unix.gettimeofday ()))
(Array.to_list args |> String.concat ~sep:" ");
let (cancel, canceller) = Lwt.wait () in
let _ =
Lwt_unix.sleep 120.0 |> Lwt.map (fun () -> Lwt.wakeup_later canceller ())
in
let%lwt result =
Lwt_utils.exec_checked
(Exec_command.For_use_in_testing_only hh_client_path)
~cancel
~env
args
in
match result with
| Error e ->
let e = Lwt_utils.Process_failure.to_string e in
Printf.eprintf "<error> %s\n%!" e;
Lwt.return e
| Ok { Lwt_utils.Process_success.stdout; _ } -> Lwt.return stdout
(** This spawns hh, so you can await output. *)
let hh_open ~(tmp : Path.t) ~(root : Path.t) (args : string array) :
Lwt_process.process Lwt.t =
let hh_client_path = Sys.getenv "HH_CLIENT_PATH" in
let env =
Array.append [| "HH_TMPDIR=" ^ Path.to_string tmp |] (Unix.environment ())
in
Printf.eprintf
"[%s] EXECUTE: hh %s\n%!"
(Utils.timestring (Unix.gettimeofday ()))
(Array.to_list args |> String.concat ~sep:" ");
let process =
Lwt_process.open_process
~env
~cwd:(Path.to_string root)
(hh_client_path, Array.append [| hh_client_path |] args)
in
let%lwt () = Lwt_io.close process#stdin in
Lwt.return process
(** This waits for substring to appear on a line of output.
If the process dies, or if we've gone a long time without a matching line,
then raises an exception. *)
let hh_await_substring (process : Lwt_process.process) ~(substring : string) :
unit Lwt.t =
(* helper, returns Error after a timeout *)
let error_after_timeout () =
let%lwt () = Lwt_unix.sleep 120.0 in
Lwt.return_error ()
in
(* helper, reads a line and returns Ok *)
let ok_after_read_line_opt () =
try%lwt
let%lwt line_opt = Lwt_io.read_line_opt process#stdout in
Printf.eprintf
"[%s] [hh_client] %s\n%!"
(Utils.timestring (Unix.gettimeofday ()))
(Option.value line_opt ~default:"<eof>");
Lwt.return_ok line_opt
with
| exn ->
let e = Exception.wrap exn in
Printf.eprintf
"[%s] [hh_client] exception %s\n%!"
(Utils.timestring (Unix.gettimeofday ()))
(Exception.to_string e);
Lwt.return_ok None
in
let rec wait_for_substring () =
let%lwt line =
Lwt.pick [error_after_timeout (); ok_after_read_line_opt ()]
in
match line with
| Error () -> failwith "timeout"
| Ok None -> failwith "eof"
| Ok (Some s) when String.is_substring s ~substring -> Lwt.return_unit
| Ok (Some _) -> wait_for_substring ()
in
let%lwt () = wait_for_substring () in
Lwt.return_unit
let dump_log ~(name : string) (file : string) : unit =
let contents =
try Sys_utils.cat file with
| _ -> "<No log>"
in
Printf.eprintf "\n\n--> hh %s:\n%s\n\n\n%!" name contents
(** This creates a small repo, ready to run hh in it.
(there'll be no watchman nor informant support). *)
let try_with_server
(files : (string * string) list)
(f : tmp:Path.t -> root:Path.t -> hhi:Path.t -> unit Lwt.t) : unit Lwt.t =
let root = Tempfile.mkdtemp ~skip_mocking:true in
let hhi = Tempfile.mkdtemp ~skip_mocking:true in
let tmp = Tempfile.mkdtemp ~skip_mocking:true in
Lwt_utils.try_finally
~f:(fun () ->
try%lwt
Sys_utils.write_file
~file:(Path.concat root ".hhconfig" |> Path.to_string)
"";
(* we'll put a dummy .hg directory in there to avoid the possibility of hg blowups *)
Sys_utils.mkdir_p
~skip_mocking:true
(Path.concat root ".hg" |> Path.to_string);
List.iter files ~f:(fun (name, content) ->
Sys_utils.write_file
~file:(Path.concat root name |> Path.to_string)
content);
ServerProgress.set_root root;
ServerFiles.set_tmp_FOR_TESTING_ONLY tmp;
let%lwt () = f ~root ~hhi ~tmp in
Lwt.return_unit
with
| exn ->
let e = Exception.wrap exn in
dump_log ~name:"--logname" (ServerFiles.log_link root);
dump_log ~name:"--monitor-logname" (ServerFiles.monitor_log_link root);
dump_log ~name:"--client-logname" (ServerFiles.client_log root);
let%lwt ls =
Lwt_utils.exec_checked
Exec_command.Ls
~timeout:5.0
[| "-l"; Path.to_string tmp |]
in
let ls =
match ls with
| Ok r -> r.Lwt_utils.Process_success.stdout
| Error e -> Lwt_utils.Process_failure.to_string e
in
Printf.eprintf "ls -l %s\n%s\n%!" (Path.to_string tmp) ls;
Exception.reraise e)
~finally:(fun () ->
let%lwt () =
try%lwt
let%lwt _ = hh ~tmp ~root [| "stop" |] in
Lwt.return_unit
with
| _ -> Lwt.return_unit
in
Sys_utils.rm_dir_tree ~skip_mocking:true (Path.to_string root);
Sys_utils.rm_dir_tree ~skip_mocking:true (Path.to_string hhi);
Sys_utils.rm_dir_tree ~skip_mocking:true (Path.to_string tmp);
Lwt.return_unit)
(** Looks for substring 'expected' in the ServerProgress message;
will keep polling the ServerProgress every 0.1s up to 'deadline' until it finds it,
and will raise an exception if it doesn't. *)
let rec wait_for_progress ~(deadline : float) ~(expected : string) : unit Lwt.t
=
let { ServerProgress.message; disposition; _ } = ServerProgress.read () in
let actual =
Printf.sprintf
"[%s] %s"
(ServerProgress.show_disposition disposition)
message
in
if String.is_substring actual ~substring:expected then
Lwt.return_unit
else if Float.(Unix.gettimeofday () > deadline) then
failwith
(Printf.sprintf
"Timeout waiting for status '%s'; got '%s'"
expected
actual)
else
let%lwt () = Lwt_unix.sleep 0.1 in
wait_for_progress ~deadline ~expected
(** Scrapes the monitor log for '...server...pid: 012345' and returns it.
Alas, this is the only means we have to find PIDs. *)
let get_server_pid ~(root : Path.t) : int Lwt.t =
let%lwt result = Lwt_utils.read_all (ServerFiles.monitor_log_link root) in
let monitor_log = Result.ok_or_failwith result in
let re = Str.regexp {|^.*server.*pid: \([0-9]+\).?$|} in
let _pos = Str.search_forward re monitor_log 0 in
let server_pid = Str.matched_group 1 monitor_log |> Int.of_string in
Lwt.return server_pid
let test_start_stop () : bool Lwt.t =
let%lwt () =
try_with_server [a_php] (fun ~tmp ~root ~hhi ->
let%lwt stdout =
hh
~tmp
~root
[|
"start";
"--no-load";
"--config";
"max_workers=1";
"--custom-hhi-path";
Path.to_string hhi;
|]
in
String_asserter.assert_equals "" stdout "hh start doesn't give output";
(* status should eventually reach "ready" *)
let%lwt () =
wait_for_progress
~deadline:(Unix.gettimeofday () +. 60.0)
~expected:"[DReady] ready"
in
let%lwt _ = hh ~root ~tmp [| "stop" |] in
(* The progress file should be cleanly deleted *)
if Sys_utils.file_exists (ServerFiles.server_progress_file root) then
failwith "expected progress file to be deleted";
let%lwt () =
wait_for_progress ~deadline:0. ~expected:"[DStopped] stopped"
in
Lwt.return_unit)
in
Lwt.return_true
let test_typechecking () : bool Lwt.t =
let%lwt () =
try_with_server [a_php; loop_php] (fun ~tmp ~root ~hhi ->
let%lwt stdout =
hh
~root
~tmp
[|
"start";
"--no-load";
"--config";
"max_workers=1";
"--custom-hhi-path";
Path.to_string hhi;
|]
in
String_asserter.assert_equals "" stdout "hh start doesn't give output";
(* the file loop_php causes the typechecker to spin, typechecking, for 10mins! *)
let%lwt () =
wait_for_progress
~deadline:(Unix.gettimeofday () +. 60.0)
~expected:"[DWorking] typechecking"
in
Lwt.return_unit)
in
Lwt.return_true
let test_kill_server () : bool Lwt.t =
let%lwt () =
try_with_server [a_php] (fun ~tmp ~root ~hhi ->
let%lwt stdout =
hh
~root
~tmp
[|
"--no-load";
"--config";
"max_workers=1";
"--custom-hhi-path";
Path.to_string hhi;
|]
in
String_asserter.assert_equals "No errors!\n" stdout "no errors";
let%lwt server_pid = get_server_pid ~root in
Unix.kill server_pid Sys.sigkill;
(* The monitor remains running, hence also the progress file *)
let%lwt () =
wait_for_progress
~deadline:(Unix.gettimeofday () +. 60.0)
~expected:"[DStopped] server stopped"
in
if not (Sys_utils.file_exists (ServerFiles.server_progress_file root))
then
failwith "expected progress file to remain";
Lwt.return_unit)
in
Lwt.return_true
let test_kill_monitor () : bool Lwt.t =
let%lwt () =
try_with_server [a_php] (fun ~tmp ~root ~hhi ->
let%lwt stdout =
hh
~root
~tmp
[|
"--no-load";
"--config";
"max_workers=1";
"--custom-hhi-path";
Path.to_string hhi;
|]
in
String_asserter.assert_equals "No errors!\n" stdout "no errors";
let%lwt server_pid = get_server_pid ~root in
let stat = Proc.get_proc_stat server_pid |> Result.ok_or_failwith in
let monitor_pid = stat.Proc.ppid in
Unix.kill monitor_pid Sys.sigkill;
(* the dead monitor will leave a progress file behind, but its pid is defunct *)
let%lwt () =
wait_for_progress
~deadline:(Unix.gettimeofday () +. 60.0)
~expected:"[DStopped] stopped"
in
if not (Sys_utils.file_exists (ServerFiles.server_progress_file root))
then
failwith "expected progress file to remain";
Lwt.return_unit)
in
Lwt.return_true
let test_errors_complete () : bool Lwt.t =
let%lwt () =
try_with_server [b_php] (fun ~tmp ~root ~hhi ->
let%lwt _stdout =
hh
~root
~tmp
[|
"--no-load";
"--config";
"max_workers=1";
"--config";
"produce_streaming_errors=true";
"--custom-hhi-path";
Path.to_string hhi;
|]
in
(* at this point we should have all errors available *)
let errors_file_path = ServerFiles.errors_file_path root in
let fd = Unix.openfile errors_file_path [Unix.O_RDONLY] 0 in
let { ServerProgress.ErrorsRead.pid; _ } =
ServerProgress.ErrorsRead.openfile fd |> Result.ok |> Option.value_exn
in
let q = ServerProgressLwt.watch_errors_file ~pid fd in
let%lwt () = expect_qitem q "Errors [b.php=1]" in
let%lwt () = expect_qitem q "Complete [complete]" in
let%lwt () = expect_qitem q "closed" in
Unix.close fd;
(* a second client will also observe the files *)
let fd = Unix.openfile errors_file_path [Unix.O_RDONLY] 0 in
let { ServerProgress.ErrorsRead.pid; _ } =
ServerProgress.ErrorsRead.openfile fd |> Result.ok |> Option.value_exn
in
let q = ServerProgressLwt.watch_errors_file ~pid fd in
let%lwt () = expect_qitem q "Errors [b.php=1]" in
let%lwt () = expect_qitem q "Complete [complete]" in
let%lwt () = expect_qitem q "closed" in
Unix.close fd;
(* let's stop the server and verify that errors are absent *)
let%lwt _ = hh ~root ~tmp [| "stop" |] in
assert (not (Sys_utils.file_exists errors_file_path));
Lwt.return_unit)
in
Lwt.return_true
let test_errors_during () : bool Lwt.t =
let%lwt () =
try_with_server [b_php; loop_php] (fun ~tmp ~root ~hhi ->
(* This test will rely upon b.php being typechecked in a separate bucket from loop.php.
To accomplish this:
(1) we pass a custom hhi path to an empty directory so it doesn't
typecheck more than the two files we gave it,
(2) we set max_workers to 4 so the bucket-dividing
algorithm will comfortably separate them. (it seems to have off-by-one oddities to just 2
max workers isn't enough.) *)
let%lwt _stdout =
hh
~root
~tmp
[|
"start";
"--no-load";
"--config";
"max_workers=4";
"--config";
"produce_streaming_errors=true";
"--custom-hhi-path";
Path.to_string hhi;
|]
in
(* the file loop_php causes the typechecker to spin, typechecking, for 10mins! *)
let%lwt () =
wait_for_progress
~deadline:(Unix.gettimeofday () +. 60.0)
~expected:"[DWorking] typechecking"
in
(* at this point we should have one error available *)
let errors_file_path = ServerFiles.errors_file_path root in
let fd1 = Unix.openfile errors_file_path [Unix.O_RDONLY] 0 in
let { ServerProgress.ErrorsRead.pid; _ } =
ServerProgress.ErrorsRead.openfile fd1
|> Result.ok
|> Option.value_exn
in
let q1 = ServerProgressLwt.watch_errors_file ~pid fd1 in
let%lwt () = expect_qitem q1 "Errors [b.php=1]" in
let%lwt () = expect_qitem q1 "nothing" in
(* and a second client should be able to observe it too *)
let fd2 = Unix.openfile errors_file_path [Unix.O_RDONLY] 0 in
let { ServerProgress.ErrorsRead.pid; _ } =
ServerProgress.ErrorsRead.openfile fd2
|> Result.ok
|> Option.value_exn
in
let q2 = ServerProgressLwt.watch_errors_file ~pid fd2 in
let%lwt () = expect_qitem q2 "Errors [b.php=1]" in
let%lwt () = expect_qitem q2 "nothing" in
(* let's stop the server and verify that errors are absent *)
let%lwt _ = hh ~root ~tmp [| "stop" |] in
assert (not (Sys_utils.file_exists errors_file_path));
(* each of the two clients will see that they're done. *)
let%lwt () = expect_qitem q1 "Stopped [unlink]" in
let%lwt () = expect_qitem q1 "closed" in
let%lwt () = expect_qitem q2 "Stopped [unlink]" in
let%lwt () = expect_qitem q2 "closed" in
Unix.close fd1;
Unix.close fd2;
Lwt.return_unit)
in
Lwt.return_true
let test_interrupt () : bool Lwt.t =
let%lwt () =
try_with_server [a_php] (fun ~tmp ~root ~hhi ->
let%lwt _stdout =
hh
~root
~tmp
[|
"--no-load";
"--config";
"produce_streaming_errors=true";
"--config";
"interrupt_on_client=true";
"--custom-hhi-path";
Path.to_string hhi;
|]
in
Sys_utils.write_file ~file:(fst loop_php) (snd loop_php);
(* the file loop_php causes the typechecker to spin, typechecking, for 10mins! *)
let%lwt () =
wait_for_progress
~deadline:(Unix.gettimeofday () +. 60.0)
~expected:"[DWorking] typechecking"
in
let stdout_future =
hh
~root
~tmp
[| "check"; "--config"; "consume_streaming_errors=true" |]
in
(* Once it's in the middle of typechecking, and once we're reading the errors-file,
let's interrupt it with a disk change *)
Sys_utils.write_file
~file:(Path.concat root "c.php" |> Path.to_string)
"<?hh\nfunction f():int {return 1;}\n";
(* Tests use dfind, which don't interrupt upon file-changes. So we'll cause
an interrupt ourselves, one that will prompt it to ask dfind for changes. *)
let%lwt _stdout =
hh
~root
~tmp
[|
"check"; "--search"; "this_is_just_to_check_liveness_of_hh_server";
|]
in
let%lwt stdout = stdout_future in
assert_substring stdout ~substring:"Exit_status.Typecheck_restarted";
assert_substring stdout ~substring:"Files have changed on disk! [";
assert_substring stdout ~substring:"] c.php";
Lwt.return_unit)
in
Lwt.return_true
let test_errors_kill () : bool Lwt.t =
let%lwt () =
try_with_server [b_php; loop_php] (fun ~tmp ~root ~hhi ->
(* This test will rely upon b.php being typechecked in a separate bucket from loop.php.
To accomplish this:
(1) we pass a custom hhi path to an empty directory so it doesn't
typecheck more than the two files we gave it,
(2) we set max_workers to 4 so the bucket-dividing
algorithm will comfortably separate them. (it seems to have off-by-one oddities to just 2
max workers isn't enough.) *)
let%lwt _stdout =
hh
~root
~tmp
[|
"start";
"--no-load";
"--config";
"max_workers=4";
"--config";
"produce_streaming_errors=true";
"--custom-hhi-path";
Path.to_string hhi;
|]
in
(* I was getting timeouts when I tried to "hh check" immediately after start,
because the client's rpc-connect wasn't getting a response until after the ten
minutes it takes to check loop.php.
So instead, I'll wait until the server is at least making some progress... *)
let%lwt () =
wait_for_progress
~deadline:(Unix.gettimeofday () +. 60.0)
~expected:"[DWorking] typechecking"
in
let%lwt hh_client =
hh_open ~root ~tmp [| "check"; "--error-format"; "plain" |]
in
let%lwt () = hh_await_substring hh_client ~substring:"(Typing[" in
(* Now, kill the server! *)
let%lwt server_pid = get_server_pid ~root in
Unix.kill server_pid Sys.sigkill;
(* read the remainding output from hh_client. It should detect the kill. *)
let%lwt stdout = Lwt_io.read hh_client#stdout in
assert_substring stdout ~substring:"Hh_server has terminated. [Killed]";
let errors_file_path = ServerFiles.errors_file_path root in
assert (Sys_utils.file_exists errors_file_path);
Lwt.return_unit)
in
Lwt.return_true
let test_errors_existing () : bool Lwt.t =
let%lwt () =
try_with_server [] (fun ~tmp ~root ~hhi ->
let%lwt _stdout =
hh
~root
~tmp
[|
"--no-load";
"--config";
"produce_streaming_errors=true";
"--custom-hhi-path";
Path.to_string hhi;
|]
in
Sys_utils.write_file
~file:(Path.concat root "a.php" |> Path.to_string)
"<?hh\nfunction f():int {return 1}\n";
let%lwt stdout =
hh ~root ~tmp [| "check"; "--error-format"; "plain" |]
in
Sys_utils.write_file
~file:(Path.concat root "b.php" |> Path.to_string)
"<?hh\nfunction g():int {}\n";
assert_substring
stdout
~substring:"A semicolon `;` is expected here. (Parsing[1002])";
let%lwt stdout =
hh ~root ~tmp [| "check"; "--error-format"; "plain" |]
in
assert_substring
stdout
~substring:"A semicolon `;` is expected here. (Parsing[1002])";
Lwt.return_unit)
in
Lwt.return_true
let test_client_complete () : bool Lwt.t =
let%lwt () =
try_with_server [b_php] (fun ~tmp ~root ~hhi ->
let%lwt _stdout =
hh
~root
~tmp
[|
"start";
"--no-load";
"--config";
"max_workers=1";
"--config";
"produce_streaming_errors=true";
"--custom-hhi-path";
Path.to_string hhi;
|]
in
(* will a client be able to consume streaming errors and see all of them? *)
let%lwt stdout =
hh ~root ~tmp [| "check"; "--error-format"; "plain" |]
in
assert_substring stdout ~substring:"Invalid return type (Typing[4336])";
Lwt.return_unit)
in
Lwt.return_true
let test_client_during () : bool Lwt.t =
let%lwt () =
try_with_server [b_php; loop_php] (fun ~tmp ~root ~hhi ->
(* This test will rely upon b.php being typechecked in a separate bucket from loop.php.
To accomplish this:
(1) we pass a custom hhi path to an empty directory so it doesn't
typecheck more than the two files we gave it,
(2) we set max_workers to 4 so the bucket-dividing
algorithm will comfortably separate them. (it seems to have off-by-one oddities to just 2
max workers isn't enough.) *)
let%lwt _stdout =
hh
~root
~tmp
[|
"start";
"--no-load";
"--config";
"max_workers=4";
"--config";
"produce_streaming_errors=true";
"--custom-hhi-path";
Path.to_string hhi;
|]
in
(* I was getting timeouts when I tried to "hh check" immediately after start,
because the client's rpc-connect wasn't getting a response until after the ten
minutes it takes to check loop.php.
So instead, I'll wait until the server is at least making some progress... *)
let%lwt () =
wait_for_progress
~deadline:(Unix.gettimeofday () +. 60.0)
~expected:"[DWorking] typechecking"
in
let args = [| "check"; "--error-format"; "plain" |] in
let%lwt hh_client = hh_open ~root ~tmp args in
let%lwt () = hh_await_substring hh_client ~substring:"(Typing[" in
hh_client#kill Sys.sigkill;
let%lwt _state = hh_client#close in
(* For our next trick, we'll kick off another hh check.
It will presumably emit the error line pretty quickly (just by reading errors.bin).
Once it has, we'll "hh stop".
This should make our hh check terminate pretty quickly,
and its output should indicate that hh died. *)
let%lwt hh_client = hh_open ~root ~tmp args in
let%lwt () = hh_await_substring hh_client ~substring:"(Typing[" in
let%lwt _ = hh ~root ~tmp [| "stop" |] in
(* read the remainding output from hh_client *)
let%lwt stdout = Lwt_io.read hh_client#stdout in
assert_substring stdout ~substring:"Hh_server has terminated. [Stopped]";
Lwt.return_unit)
in
Lwt.return_true
let test_start () : bool Lwt.t =
let%lwt () =
try_with_server [b_php] (fun ~tmp ~root ~hhi ->
let%lwt stdout =
hh
~root
~tmp
[|
"--no-load";
"--config";
"max_workers=1";
"--config";
"produce_streaming_errors=true";
"--error-format";
"plain";
"--custom-hhi-path";
Path.to_string hhi;
"--autostart-server";
"true";
|]
in
(* This check should cause the server to start up *)
assert_substring stdout ~substring:"Invalid return type (Typing[4336])";
Lwt.return_unit)
in
Lwt.return_true
let test_no_start () : bool Lwt.t =
let%lwt () =
try_with_server [b_php] (fun ~tmp ~root ~hhi ->
let%lwt stdout =
hh
~root
~tmp
[|
"--config";
"max_workers=1";
"--config";
"produce_streaming_errors=true";
"--error-format";
"plain";
"--custom-hhi-path";
Path.to_string hhi;
"--autostart-server";
"false";
|]
in
(* This exercises synchronous failure when clientCheckStatus.go_streaming sees
no errors.bin, determines to call ClientConnect.connect, but the connection
attempt exits fast because of autostart-server false. *)
assert_substring stdout ~substring:"WEXITED";
assert_substring stdout ~substring:"no hh_server running";
Lwt.return_unit)
in
Lwt.return_true
let test_no_load () : bool Lwt.t =
let%lwt () =
try_with_server [b_php] (fun ~tmp ~root ~hhi ->
let%lwt stdout =
hh
~root
~tmp
[|
"--config";
"max_workers=1";
"--config";
"produce_streaming_errors=true";
"--error-format";
"plain";
"--custom-hhi-path";
Path.to_string hhi;
"--autostart-server";
"true";
"--config";
"use_mini_state=true";
"--config";
"load_state_natively_v4=true";
"--config";
"require_saved_state=true";
|]
in
(* This exercises asynchronous failure when clientCheckStatus.go_streaming sees
no errors.bin, determines to call ClientConnect.connect which goes ahead,
then the server fails to load a saved-state (we didn't pass --no-load),
and the server exits, and ClientConnect.connect eventually gets that
server failure and reports it. *)
assert_substring stdout ~substring:"WEXITED";
assert_substring stdout ~substring:"Failed_to_load_should_abort";
assert_substring
stdout
~substring:"LoadError.Find_hh_server_hash_failed";
Lwt.return_unit)
in
Lwt.return_true
let test_hhi_error () : bool Lwt.t =
let%lwt () =
(* This test the ability of streaming-errors to render an error that mentions an hhi file.
It should produce "stdClass::f doesn't exist; see this definition of stdClass in hhi..." *)
let use_hhi_php =
("use_hhi.php", "<?hh\nfunction test_use_hhi(): void { stdClass::f(); }\n")
in
try_with_server [use_hhi_php] (fun ~tmp ~root ~hhi:_ ->
let%lwt stdout =
hh
~root
~tmp
[|
"--no-load";
"--config";
"max_workers=1";
"--config";
"produce_streaming_errors=true";
"--config";
"consume_streaming_errors=true";
"--error-format";
"plain";
|]
in
assert_substring stdout ~substring:"Exit_status.Type_error";
Lwt.return_unit)
in
Lwt.return_true
let () =
Printexc.record_backtrace true;
EventLogger.init_fake ();
let tests =
[
(* ("test_start_stop", test_start_stop);
("test_typechecking", test_typechecking);
("test_kill_server", test_kill_server);
("test_kill_monitor", test_kill_monitor);
("test_errors_complete", test_errors_complete);
("test_errors_during", test_errors_during);
("test_errors_kill", test_errors_kill);
("test_errors_existing", test_errors_existing);
("test_client_complete", test_client_complete);
("test_client_during", test_client_during);
("test_start", test_start);
("test_no_start", test_no_start);
("test_no_load", test_no_load);
("test_hhi_error", test_hhi_error); *)
("test_interrupt", test_interrupt);
]
|> List.map ~f:(fun (name, f) ->
( name,
fun () ->
Printf.eprintf
"\n\n\n\n============================\n%s\n========================\n%!"
name;
Lwt_main.run (f ()) ))
in
Unit_test.run_all tests |
OCaml | hhvm/hphp/hack/test/integration_ml/test_added_parent.ml | (*
* Copyright (c) 2016, 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.
*
*
*)
open Integration_test_base_types
module Test = Integration_test_base
let foo_name = "foo.php"
let foo_contents =
"<?hh // strict
class Foo {
/* HH_FIXME[4336] */
public function f() : string {
}
}
"
let foo_child_name = "foo_child.php"
let foo_child_contents =
"<?hh // strict
/* HH_FIXME[2049] */
/* HH_FIXME[4123] */
class FooChild extends Foo {}
"
let bar_name = "bar.php"
let bar_contents =
"<?hh // strict
function take_int(int $x) : void {}
function test(FooChild $foo_child) : void {
/* HH_FIXME[4053] */
take_int($foo_child->f());
}
"
let bar_errors =
"File \"/bar.php\", line 7, characters 12-26:
Invalid argument (Typing[4110])
File \"/bar.php\", line 3, characters 19-21:
Expected `int`
File \"/foo.php\", line 5, characters 25-30:
But got `string`
"
let root = "/"
let hhconfig_filename = Filename.concat root ".hhconfig"
let hhconfig_contents =
"
allowed_fixme_codes_strict = 2049,4053,4110,4123,4336
allowed_decl_fixme_codes = 2049,4123,4336
"
let test () =
Relative_path.set_path_prefix Relative_path.Root (Path.make root);
TestDisk.set hhconfig_filename hhconfig_contents;
let options = ServerArgs.default_options ~root in
let (custom_config, _) = ServerConfig.load ~silent:false options in
let env = Test.setup_server ~custom_config () in
let env =
Test.setup_disk
env
[
(foo_name, "");
(foo_child_name, foo_child_contents);
(bar_name, bar_contents);
]
in
(* We need to suppress all the errors (see HH_FIXMEs above), otherwise the
* logic that always rechecks the files with errors kicks in and does the
* same job as phase2 fanout. We want to test the latter one in this test. *)
Test.assert_no_errors env;
(* restore parent, but with a mismatching return type of f() *)
let (env, _) =
Test.(
run_loop_once
env
{ default_loop_input with disk_changes = [(foo_name, foo_contents)] })
in
Test.assertSingleError bar_errors (Errors.get_error_list env.ServerEnv.errorl) |
OCaml | hhvm/hphp/hack/test/integration_ml/test_capitalization.ml | (*
* Copyright (c) 2016, 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.
*
*
*)
open Integration_test_base_types
module Test = Integration_test_base
let foo1_contents = "<?hh
class foo {}
"
let foo2_contents = "<?hh
class FOO {}
"
let test () =
let env = Test.setup_server () in
let (env, loop_output) =
Test.(
run_loop_once
env
{
default_loop_input with
disk_changes =
[("foo1.php", foo1_contents); ("foo2.php", foo2_contents)];
})
in
if not loop_output.did_read_disk_changes then
Test.fail "Expected the server to process disk updates";
(* TODO: get rid of repeating errors in error list *)
let expected_error =
"File \"/foo2.php\", line 2, characters 9-11:\n"
^ "Name already bound: `FOO` (Naming[2012])\n"
^ " File \"/foo1.php\", line 2, characters 9-11:\n"
^ " Previous definition is here\n"
in
Test.assert_env_errors env expected_error;
(* Change a wholly unrelated file. *)
let (env, loop_output) =
Test.(
run_loop_once
env
{ default_loop_input with disk_changes = [("bar.php", "")] })
in
if not loop_output.did_read_disk_changes then
Test.fail "Expected the server to process disk updates";
(* The same errors should still be there *)
Test.assert_env_errors env expected_error |
OCaml | hhvm/hphp/hack/test/integration_ml/test_coeffects.ml | (*
* Copyright (c) 2016, 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.
*
*
*)
open Hh_prelude
let source =
"<?hh // strict
namespace HH\\Contexts {
type a = mixed;
namespace Unsafe {
type a = mixed;
}
}
namespace {
function foo()[a]: void {}
// ^ 11:18
}
"
let go_identify expected ~ctx ~entry ~line ~column =
let actual =
ServerIdentifyFunction.go_quarantined_absolute ~ctx ~entry ~line ~column
|> Nuclide_rpc_message_printer.identify_symbol_response_to_json
in
Asserter.Hh_json_json_asserter.assert_equals
(expected |> Hh_json.json_of_string)
actual
(Printf.sprintf "ServerIdentifyFunction at line %d, column %d" line column);
()
let go_hover expected ~ctx ~entry ~line ~column =
let hovers_to_string h =
List.map h ~f:HoverService.string_of_result |> String.concat ~sep:"; "
in
let actual = ServerHover.go_quarantined ~ctx ~entry ~line ~column in
Asserter.String_asserter.assert_equals
(expected |> hovers_to_string)
(actual |> hovers_to_string)
(Printf.sprintf "ServerHover at line %d, column %d" line column);
()
let pos_at (line1, column1) (line2, column2) =
Some
(Pos.make_from_lnum_bol_offset
~pos_file:Relative_path.default
~pos_start:(line1, 0, column1 - 1)
~pos_end:(line2, 0, column2))
let identify_tests =
[
( (11, 18),
go_identify
{| [{
"name":"\\HH\\Contexts\\a",
"result_type":"class",
"pos":{"filename":"/source.php","line":11,"char_start":18,"char_end":18},
"definition_pos":{"filename":"/source.php","line":4,"char_start":8,"char_end":8},
"definition_span":{"filename":"/source.php","line_start":4,"char_start":8,"line_end":4,"char_end":16},
"definition_id":"type_id::HH\\Contexts\\a"}] |}
);
( (11, 18),
go_hover
[
{
HoverService.snippet = "Contexts\\a";
addendum = [];
pos = pos_at (11, 18) (11, 18);
};
] );
]
let test () =
let root = "/" in
let hhconfig_filename = Filename.concat root ".hhconfig" in
let files = [("source.php", source)] in
Relative_path.set_path_prefix Relative_path.Root (Path.make root);
TestDisk.set hhconfig_filename "";
let options = ServerArgs.default_options ~root in
let (custom_config, _) = ServerConfig.load ~silent:false options in
let env =
Integration_test_base.setup_server
()
~custom_config
~hhi_files:(Hhi.get_raw_hhi_contents () |> Array.to_list)
in
let env = Integration_test_base.setup_disk env files in
Integration_test_base.assert_no_errors env;
let path = Relative_path.from_root ~suffix:"source.php" in
let (ctx, entry) =
Provider_context.add_entry_if_missing
~ctx:(Provider_utils.ctx_from_server_env env)
~path
in
List.iter identify_tests ~f:(fun ((line, column), go) ->
Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () ->
go ~ctx ~entry ~line ~column);
());
(* ServerHover.go_quarantined ~ctx ~entry ~line ~column *)
() |
OCaml | hhvm/hphp/hack/test/integration_ml/test_decl_decl.ml | open Integration_test_base_types
module Test = Integration_test_base
(* The bug only occurs when A and B are in different files, are redeclared in
* the same batch, but B (the child) is redeclared before A (so that decl of B
* ends up having to call into decl of A). This is achieved here using an
* implementation detail of files being processed in reverse alphabetical order.
*)
let a_file_name = "A.php"
let b_file_name = "B.php"
let c_file_name = "C.php"
let a_contents =
"<?hh // strict
class A {
/* HH_FIXME[4336] */
/* HH_FIXME[4422] */
final public function f() : C {
}
}
"
let b_contents = "<?hh // strict
class B extends A {}
"
let c_contents = "<?hh // strict
class C {}
"
let errors =
{|
File "/A.php", line 6, characters 31-31:
Unbound name: `C` (Naming[2049])
|}
let root = "/"
let hhconfig_filename = Filename.concat root ".hhconfig"
let hhconfig_contents =
"
allowed_fixme_codes_strict = 4336,4422
allowed_decl_fixme_codes = 4336,4422
"
let test () =
Relative_path.set_path_prefix Relative_path.Root (Path.make root);
TestDisk.set hhconfig_filename hhconfig_contents;
let options = ServerArgs.default_options ~root in
let (custom_config, _) = ServerConfig.load ~silent:false options in
let env = Test.setup_server ~custom_config () in
let env =
Test.setup_disk
env
[(a_file_name, a_contents); (b_file_name, b_contents); (c_file_name, "")]
in
Test.assert_env_errors env errors;
let (env, _) =
Test.(
run_loop_once
env
{ default_loop_input with disk_changes = [(c_file_name, c_contents)] })
in
Test.assert_no_errors env;
() |
OCaml | hhvm/hphp/hack/test/integration_ml/test_delete_file.ml | (* Delete a file that still has dangling references *)
open Integration_test_base_types
open ServerEnv
module Test = Integration_test_base
let foo_contents =
"<?hh
class Foo {
public static function g(): string {
return 'a';
}
}
"
let bar_contents =
"<?hh
function h(): string {
return Foo::g();
}
"
let test () =
let env = Test.setup_server () in
let (env, loop_output) =
Test.(
run_loop_once
env
{
default_loop_input with
disk_changes = [("foo.php", foo_contents); ("bar.php", bar_contents)];
})
in
if not loop_output.did_read_disk_changes then
Test.fail "Expected the server to process disk updates";
(match Errors.get_error_list env.errorl with
| [] -> ()
| _ -> Test.fail "Expected no errors");
let (env, loop_output) =
Test.(
run_loop_once
env
{
default_loop_input with
disk_changes = [("foo.php", ""); ("bar.php", bar_contents)];
})
in
if not loop_output.did_read_disk_changes then
Test.fail "Expected the server to process disk updates";
let expected_error =
"File \"/bar.php\", line 3, characters 20-22:\n"
^ "Unbound name: `Foo` (an object type) (Naming[2049])\n"
in
Test.assertSingleError expected_error (Errors.get_error_list env.errorl) |
OCaml | hhvm/hphp/hack/test/integration_ml/test_duplicated_file.ml | (* Duplicate the same file twice *)
open Integration_test_base_types
open ServerEnv
module Test = Integration_test_base
let foo_contents =
"<?hh //strict
class Foo {
public function g(): string {
return 'a';
}
}
"
let test () =
let env = Test.setup_server () in
let (env, loop_output) =
Test.(
run_loop_once
env
{ default_loop_input with disk_changes = [("foo.php", foo_contents)] })
in
if not loop_output.did_read_disk_changes then
Test.fail "Expected the server to process disk updates";
(match Errors.get_error_list env.errorl with
| [] -> ()
| _ -> Test.fail "Expected no errors");
let (env, loop_output) =
Test.(
run_loop_once
env
{
default_loop_input with
disk_changes = [("foo.php", foo_contents); ("bar.php", foo_contents)];
})
in
if not loop_output.did_read_disk_changes then
Test.fail "Expected the server to process disk updates";
let expected_result =
"File \"/foo.php\", line 2, characters 11-13:\n"
^ "Name already bound: `Foo` (Naming[2012])\n"
^ " File \"/bar.php\", line 2, characters 11-13:\n"
^ " Previous definition is here\n"
in
Test.assertSingleError expected_result (Errors.get_error_list env.errorl) |
OCaml | hhvm/hphp/hack/test/integration_ml/test_duplicate_parent.ml | (*
This checks that we handle duplicate parent classes, i.e. when Bar
extends Foo and there are two declarations of Foo. We want to make sure
that when the duplicate gets removed, we recover correctly by
redeclaring Bar with the remaining parent class.
*)
open Integration_test_base_types
open ServerEnv
open Hh_prelude
module Test = Integration_test_base
let foo_contents = "<?hh
class Foo {
public static ?int $x;
}
"
let qux_contents =
"<?hh
function h(): string {
return 'a';
}
class Foo {}
function setUpClass(): void {
new Foo();
h();
}
"
let bar_contents =
"<?hh
class Bar extends Foo {}
function main(Bar $a): void {
$a::$y;
}
"
let test () =
let env = Test.setup_server () in
let (env, loop_output) =
Test.(
run_loop_once
env
{
default_loop_input with
disk_changes =
[
("foo.php", foo_contents);
("qux.php", qux_contents);
("bar.php", bar_contents);
];
})
in
if not loop_output.did_read_disk_changes then
Test.fail "Expected the server to process disk updates";
let bar_error =
"File \"/bar.php\", line 5, characters 15-16:\n"
^ "No class variable `$y` in `Bar` (Typing[4090])\n"
^ " File \"/foo.php\", line 3, characters 23-26:\n"
^ " Did you mean `$x` instead?\n"
^ " File \"/bar.php\", line 2, characters 13-15:\n"
^ " Declaration of `Bar` is here\n"
in
let qux_error =
"File \"/qux.php\", line 6, characters 7-9:\n"
^ "Name already bound: `Foo` (Naming[2012])\n"
^ " File \"/foo.php\", line 2, characters 11-13:\n"
^ " Previous definition is here\n"
in
(* We should get exactly these two errors *)
match Errors.get_error_list env.errorl with
| [x; y] ->
Test.assertSingleError qux_error [y];
Test.assertSingleError bar_error [x]
| errs ->
Test.fail
@@ "Expected exactly two errors, but got:\n"
^ String.concat ~sep:"\n" (Test.error_strings errs) |
OCaml | hhvm/hphp/hack/test/integration_ml/test_failed_naming.ml | open Integration_test_base_types
module Test = Integration_test_base
let f1 = "f1.php"
let f2 = "f2.php"
let test = "test.php"
let test_contents = "<?hh // strict
function test(C $c) : void {}
"
let contents = Printf.sprintf "<?hh // strict
class %s {}
"
let c_contents = contents "C"
let d_contents = contents "D"
let errors =
"
File \"/test.php\", line 3, characters 15-15:
Unbound name: `C` (Naming[2049])
"
let test () =
let env = Test.setup_server () in
let env =
Test.setup_disk
env
[(test, test_contents); (f1, c_contents); (f2, d_contents)]
in
Test.assert_no_errors env;
(* Rename C to (duplicate of) D *)
let (env, _) =
Test.(
run_loop_once
env
{ default_loop_input with disk_changes = [(f1, d_contents)] })
in
(* Remove the duplicate *)
let (env, _) =
Test.(
run_loop_once env { default_loop_input with disk_changes = [(f1, "")] })
in
Test.assert_env_errors env errors |
OCaml | hhvm/hphp/hack/test/integration_ml/test_funptr.ml | (*
* Copyright (c) 2016, 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.
*
*
*)
open Hh_prelude
let source =
"<?hh // strict
// foo_docblock
function foo(string $s) : string {
return $s;
}
// Cardoor_docblock
class Cardoor {
// bar_docblock
public static function bar<T>(T $x) : T {
return $x;
}
}
function test() : void {
$_ = foo<>;
// ^ 17:9
$_ = Cardoor::bar<string>;
// ^ 20:9 ^ 20:18
}
"
let go_identify expected ~ctx ~entry ~line ~column =
let actual =
ServerIdentifyFunction.go_quarantined_absolute ~ctx ~entry ~line ~column
|> Nuclide_rpc_message_printer.identify_symbol_response_to_json
in
Asserter.Hh_json_json_asserter.assert_equals
(expected |> Hh_json.json_of_string)
actual
(Printf.sprintf "ServerIdentifyFunction at line %d, column %d" line column);
()
let go_hover expected ~ctx ~entry ~line ~column =
let hovers_to_string h =
List.map h ~f:HoverService.string_of_result |> String.concat ~sep:"; "
in
let actual = ServerHover.go_quarantined ~ctx ~entry ~line ~column in
Asserter.String_asserter.assert_equals
(expected |> hovers_to_string)
(actual |> hovers_to_string)
(Printf.sprintf "ServerHover at line %d, column %d" line column);
()
let pos_at (line1, column1) (line2, column2) =
Some
(Pos.make_from_lnum_bol_offset
~pos_file:Relative_path.default
~pos_start:(line1, 0, column1 - 1)
~pos_end:(line2, 0, column2))
let identify_tests =
[
( (17, 9),
go_identify
{| [{
"name":"\\foo",
"result_type":"function",
"pos":{"filename":"/source.php","line":17,"char_start":8,"char_end":10},
"definition_pos":{"filename":"/source.php","line":4,"char_start":10,"char_end":12},
"definition_span":{"filename":"/source.php","line_start":4,"char_start":1,"line_end":6,"char_end":1},
"definition_id":"function::foo"}] |}
);
( (17, 9),
go_hover
[
{
HoverService.snippet = "function foo(string $s): string";
addendum = ["foo_docblock"];
pos = pos_at (17, 8) (17, 10);
};
] );
( (20, 9),
go_identify
{| [{
"name":"\\Cardoor",
"result_type":"class",
"pos":{"filename":"/source.php","line":20,"char_start":8,"char_end":14},
"definition_pos":{"filename":"/source.php","line":9,"char_start":7,"char_end":13},
"definition_span":{"filename":"/source.php","line_start":9,"char_start":1,"line_end":14,"char_end":1},
"definition_id":"type_id::Cardoor"}] |}
);
( (20, 9),
go_hover
[
{
HoverService.snippet = "class Cardoor";
addendum = ["Cardoor_docblock"];
pos = pos_at (20, 8) (20, 14);
};
] );
( (20, 18),
go_identify
{| [{
"name":"\\Cardoor::bar",
"result_type":"method",
"pos":{"filename":"/source.php","line":20,"char_start":17,"char_end":19},
"definition_pos":{"filename":"/source.php","line":11,"char_start":26,"char_end":28},
"definition_span":{"filename":"/source.php","line_start":11,"char_start":3,"line_end":13,"char_end":3},
"definition_id":"method::Cardoor::bar"}] |}
);
( (20, 18),
go_hover
[
{
HoverService.snippet =
"// Defined in Cardoor\npublic static function bar<T>(string $x): string";
addendum = ["bar_docblock"];
pos = pos_at (20, 17) (20, 19);
};
] );
]
let test () =
let root = "/" in
let hhconfig_filename = Filename.concat root ".hhconfig" in
let hhconfig_contents = "" in
let files = [("source.php", source)] in
Relative_path.set_path_prefix Relative_path.Root (Path.make root);
TestDisk.set hhconfig_filename hhconfig_contents;
let options = ServerArgs.default_options ~root in
let (custom_config, _) = ServerConfig.load ~silent:false options in
let env =
Integration_test_base.setup_server
()
~custom_config
~hhi_files:(Hhi.get_raw_hhi_contents () |> Array.to_list)
in
let env = Integration_test_base.setup_disk env files in
Integration_test_base.assert_no_errors env;
let path = Relative_path.from_root ~suffix:"source.php" in
let (ctx, entry) =
Provider_context.add_entry_if_missing
~ctx:(Provider_utils.ctx_from_server_env env)
~path
in
List.iter identify_tests ~f:(fun ((line, column), go) ->
Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () ->
go ~ctx ~entry ~line ~column);
());
(* ServerHover.go_quarantined ~ctx ~entry ~line ~column *)
() |
OCaml | hhvm/hphp/hack/test/integration_ml/test_gconst_file.ml | (*
* Copyright (c) 2016, 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.
*
*
*)
open Integration_test_base_types
open ServerEnv
module Test = Integration_test_base
let foo_contents = "<?hh // strict
const int A = 5;
"
let bar_contents = "<?hh // strict
const int B = A;
"
let foo_new_contents = "<?hh // strict
const string A = '';
"
let test () =
let env = Test.setup_server () in
let (env, loop_output) =
Test.(
run_loop_once
env
{ default_loop_input with disk_changes = [("foo.php", foo_contents)] })
in
if not loop_output.did_read_disk_changes then
Test.fail "Expected the server to process disk updates";
Test.assert_no_errors env;
let (env, loop_output) =
Test.(
run_loop_once
env
{ default_loop_input with disk_changes = [("bar.php", bar_contents)] })
in
if not loop_output.did_read_disk_changes then
Test.fail "Expected the server to process disk updates";
Test.assert_no_errors env;
let (env, loop_output) =
Test.(
run_loop_once
env
{
default_loop_input with
disk_changes = [("foo.php", foo_new_contents)];
})
in
if not loop_output.did_read_disk_changes then
Test.fail "Expected the server to process disk updates";
let expected_error =
"File \"/bar.php\", line 2, characters 9-11:\n"
^ "Wrong type hint (Typing[4110])\n"
^ " File \"/bar.php\", line 2, characters 9-11:\n"
^ " Expected `int`\n"
^ " File \"/foo.php\", line 2, characters 9-14:\n"
^ " But got `string`"
in
Test.assertSingleError expected_error (Errors.get_error_list env.errorl) |
OCaml | hhvm/hphp/hack/test/integration_ml/test_getfundeps.ml | (*
* Copyright (c) 2016, 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.
*
*
*)
open Hh_prelude
module Test = Integration_test_base
let f1 =
( "f1.php",
{|<?hh
function test(F2A $a, F3B $b): int {
return x() + $a->f() + $b->f() + $a->f() + x();
}
function x1(): int {
return 1;
}
function getf3b(): F3B {
return new F3B();
}
|}
)
let f2 =
( "f2.php",
{|<?hh
class F2A {
public function __construct() {
}
public function f(): int {
$f3b1 = getf3b();
$f3b2 = getf3b();
return x()
}
}
|}
)
let f3 =
( "f3.php",
{|<?hh
class F3B {
public function f(): int {
return 100;
}
}
async function g(): Awaitable<void> {
await async {
(new F3B())->f();
};
}
function h(): void {
$a = new F2A();
$a->f();
}
interface IA {}
class A {
public function g(): int {
return 1;
}
}
class B extends A implements IA {
}
function rxshallow1(): int {
return 3;
}
function rx1(): int {
return 4;
}
function ff(A $a): int {
return $a->g() + rxshallow1() + rx1();
}
|}
)
let f4 =
( "f4.php",
{|<?hh
class A1 {
public static function sm(): int {
return 1;
}
}
class B1 extends A1 {
public function m(): int {
return self::sm();
}
}
|}
)
let f5 =
( "f5.php",
{|<?hh
function f4main(): int {
$a = f5f<>;
$c = new C();
$m = () ==> $c->m();
$cm = C::sm<>;
}
function f5f(): int {
return 1;
}
class C {
public static function sm(): int {
return 1;
}
public function m(): int {
return 1;
}
}
function f5g(): int {
return D::getc()->m();
}
class D {
public static function getc(): C {
return new C();
}
}
|}
)
let f6 =
( "f6.php",
{|<?hh
function f6f(): int {
$a = () ==> {
f6g();
};
}
function f6g(): void {
}
|}
)
let f7 =
( "f7.php",
{|<?hh
function f7f((function(): void) $a): void {
$a();
$b = () ==> {
return 1;
};
$b();
}
|}
)
let f8 =
( "f8.php",
{|<?hh
function f8main(): void {
$_ = f8f<>;
$_ = C8::sf8<>;
}
function f8f(): void {}
class C8 { public static function sf8(): void {} }
|}
)
let files = [f1; f2; f3; f4; f5; f6; f7; f8]
let tests =
[
( (fst f1, 2, 11),
{|{"position":{"file":"/f1.php","line":2,"character":11},"deps":[null,null,{"name":"F2A::f","kind":"method","position":{"filename":"/f2.php","line":7,"char_start":19,"char_end":19}},{"name":"F3B::f","kind":"method","position":{"filename":"/f3.php","line":3,"char_start":19,"char_end":19}}]}|}
);
( (fst f2, 7, 19),
{|{"position":{"file":"/f2.php","line":7,"character":19},"deps":[null,{"name":"getf3b","kind":"function","position":{"filename":"/f1.php","line":10,"char_start":10,"char_end":15}}]}|}
);
(* should find class (since constructor is not defined) and method call *)
( (fst f3, 8, 16),
{|{"position":{"file":"/f3.php","line":8,"character":16},"deps":[{"name":"F3B","kind":"class","position":{"filename":"/f3.php","line":2,"char_start":7,"char_end":9}},{"name":"F3B::f","kind":"method","position":{"filename":"/f3.php","line":3,"char_start":19,"char_end":19}}]}|}
);
(* should find constructor and method *)
( (fst f3, 14, 10),
{|{"position":{"file":"/f3.php","line":14,"character":10},"deps":[{"name":"F2A::__construct","kind":"method","position":{"filename":"/f2.php","line":4,"char_start":19,"char_end":29}},{"name":"F2A::f","kind":"method","position":{"filename":"/f2.php","line":7,"char_start":19,"char_end":19}}]}|}
);
(* should find reactive function *)
( (fst f3, 38, 10),
{|{"position":{"file":"/f3.php","line":38,"character":10},"deps":[{"name":"rx1","kind":"function","position":{"filename":"/f3.php","line":34,"char_start":10,"char_end":12}},{"name":"rxshallow1","kind":"function","position":{"filename":"/f3.php","line":30,"char_start":10,"char_end":19}},{"name":"A::g","kind":"method","position":{"filename":"/f3.php","line":22,"char_start":19,"char_end":19}}]}|}
);
(* should find static method*)
( (fst f4, 8, 21),
{|{"position":{"file":"/f4.php","line":8,"character":21},"deps":[{"name":"A1::sm","kind":"method","position":{"filename":"/f4.php","line":3,"char_start":28,"char_end":29}}]}|}
);
(* should find static method pointer, class, methods and function *)
( (fst f5, 3, 10),
{|{"position":{"file":"/f5.php","line":3,"character":10},"deps":[{"name":"f5f","kind":"function","position":{"filename":"/f5.php","line":10,"char_start":10,"char_end":12}},{"name":"C","kind":"class","position":{"filename":"/f5.php","line":13,"char_start":7,"char_end":7}},{"name":"C::m","kind":"method","position":{"filename":"/f5.php","line":17,"char_start":19,"char_end":19}},{"name":"C::sm","kind":"method","position":{"filename":"/f5.php","line":14,"char_start":26,"char_end":27}}]}|}
);
(* handle chained calls *)
( (fst f5, 22, 10),
{|{"position":{"file":"/f5.php","line":22,"character":10},"deps":[{"name":"D::getc","kind":"method","position":{"filename":"/f5.php","line":27,"char_start":26,"char_end":29}},{"name":"C::m","kind":"method","position":{"filename":"/f5.php","line":17,"char_start":19,"char_end":19}}]}|}
);
(* should look into lambdas *)
( (fst f6, 2, 10),
{|{"position":{"file":"/f6.php","line":2,"character":10},"deps":[{"name":"f6g","kind":"function","position":{"filename":"/f6.php","line":7,"char_start":10,"char_end":12}}]}|}
);
(* locals as call targets *)
( (fst f7, 2, 10),
{|{"position":{"file":"/f7.php","line":2,"character":10},"deps":[{"name":"$a","kind":"local","position":{"filename":"/f7.php","line":2,"char_start":33,"char_end":34}},{"name":"$b","kind":"local","position":{"filename":"/f7.php","line":4,"char_start":3,"char_end":4}}]}|}
);
(* first-class function pointers *)
( (fst f8, 3, 10),
{|{"position":{"file":"/f8.php","line":3,"character":10},"deps":[{"name":"f8f","kind":"function","position":{"filename":"/f8.php","line":8,"char_start":10,"char_end":12}},{"name":"C8::sf8","kind":"method","position":{"filename":"/f8.php","line":9,"char_start":35,"char_end":37}}]}|}
);
]
let test () =
let env =
Test.setup_server
()
~hhi_files:(Hhi.get_raw_hhi_contents () |> Array.to_list)
in
let env = Test.setup_disk env files in
let h = ServerFunDepsBatch.handlers in
let do_test ((file, line, col), expected) =
let ctx = Provider_utils.ctx_from_server_env env in
let pos_list = [(Relative_path.from_root ~suffix:file, line, col)] in
let result = ServerRxApiShared.helper h ctx [] pos_list in
if not (List.equal String.equal result [expected]) then
let msg =
"Unexpected test result\nExpected:\n"
^ expected
^ "\nBut got:\n"
^ String.concat ~sep:"\n" result
in
Test.fail msg
in
List.iter tests ~f:do_test |
OCaml | hhvm/hphp/hack/test/integration_ml/test_get_dependent_classes.ml | (*
* Copyright (c) 2016, 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.
*
*
*)
open Hh_prelude
module Test = Integration_test_base
let files =
[
("C", "class C {}");
("D", "class D extends C {}");
("E", "class E extends D {}");
("F", "trait F { require extends E; }");
("G", "trait G { use F; }");
("H", "trait H {}");
("I", "class I { use H; }");
("J", "interface J {}");
("K", "interface K extends J {}");
("L", "trait L { require implements K; }");
("M", "class :M {}");
("N", "class :N { attribute :M; }");
("Unrelated", "class Unrelated {}");
]
|> List.map ~f:(fun (name, contents) -> (name ^ ".php", "<?hh\n" ^ contents))
let test () =
let env = Test.setup_server () in
let env = Test.setup_disk env files in
Test.assert_no_errors env;
let ctx = Provider_utils.ctx_from_server_env env in
let get_classes path =
match Naming_table.get_file_info env.ServerEnv.naming_table path with
| None -> SSet.empty
| Some info ->
SSet.of_list @@ List.map info.FileInfo.classes ~f:(fun (_, x, _) -> x)
in
let dependent_classes =
Decl_redecl_service.get_dependent_classes
ctx
None
~bucket_size:1
get_classes
(SSet.of_list ["\\C"; "\\H"; "\\J"; "\\:M"])
in
let expected_dependent_classes =
List.sort
~compare:String.compare
[
"\\C";
"\\D";
"\\E";
"\\F";
"\\G";
"\\H";
"\\I";
"\\J";
"\\K";
"\\L";
"\\:M";
"\\:N";
]
in
List.iter (SSet.elements dependent_classes) ~f:print_endline;
if
not
(List.equal
String.equal
(SSet.elements dependent_classes)
expected_dependent_classes)
then
Test.fail "Missing dependent classes" |
OCaml | hhvm/hphp/hack/test/integration_ml/test_identify.ml | (*
* Copyright (c) 2016, 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.
*
*
*)
open Hh_prelude
let source_with_errors =
"<?hh // strict
interface I<T> {}
function test(I<NotDefined::Foo> $_): void {}
"
let test () =
let root = "/" in
let hhconfig_filename = Filename.concat root ".hhconfig" in
let hhconfig_contents = "" in
let files = [("source_with_errors.php", source_with_errors)] in
Relative_path.set_path_prefix Relative_path.Root (Path.make root);
TestDisk.set hhconfig_filename hhconfig_contents;
let options = ServerArgs.default_options ~root in
let (custom_config, _) = ServerConfig.load ~silent:false options in
let env =
Integration_test_base.setup_server
()
~custom_config
~hhi_files:(Hhi.get_raw_hhi_contents () |> Array.to_list)
in
let env = Integration_test_base.setup_disk env files in
let path = Relative_path.from_root ~suffix:"source_with_errors.php" in
let (ctx, entry) =
Provider_context.add_entry_if_missing
~ctx:(Provider_utils.ctx_from_server_env env)
~path
in
let { Tast_provider.Compute_tast.tast; _ } =
Tast_provider.compute_tast_quarantined ~ctx ~entry
in
let symbols =
IdentifySymbolService.all_symbols
ctx
tast.Tast_with_dynamic.under_normal_assumptions
in
Asserter.Int_asserter.assert_equals
7
(List.length symbols)
"symbol count for error file";
() |
OCaml | hhvm/hphp/hack/test/integration_ml/test_ignore_fixme_hhi.ml | (*
* 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.
*
*)
module Test = Integration_test_base
let root = "/"
let hhconfig_filename = Filename.concat root ".hhconfig"
let file_name = "f.php"
let hhi_name = "g.hhi"
let file_contents =
"<?hh // strict
function f(): string {
/* HH_FIXME[4110] */
return 4;
}
"
let hhi_contents = "<?hh
/* HH_FIXME[4110] */
const string C = 4;
"
let hhconfig_contents = ""
let errors =
{|
File "/f.php", line 5, characters 10-10:
Invalid return type (Typing[4110])
File "/f.php", line 3, characters 15-20:
Expected `string`
File "/f.php", line 5, characters 10-10:
But got `int`
File "/f.php", line 4, characters 3-22:
You cannot use `HH_FIXME` or `HH_IGNORE_ERROR` comments to suppress error 4110 (Typing[4110])
|}
let test () =
Relative_path.set_path_prefix Relative_path.Root (Path.make root);
TestDisk.set hhconfig_filename hhconfig_contents;
let options = ServerArgs.default_options ~root in
let (config, _) = ServerConfig.load ~silent:false options in
let env =
Test.setup_server
~custom_config:config
~hhi_files:[(hhi_name, hhi_contents)]
()
in
let env = Test.setup_disk env [(file_name, file_contents)] in
Test.assert_env_errors env errors |
OCaml | hhvm/hphp/hack/test/integration_ml/test_infer_type.ml | (*
* Copyright (c) 2016, 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.
*
*
*)
open Hh_prelude
module Test = Integration_test_base
let id =
"<?hh // strict
function id(int $x): int {
return $x;
// ^3:10
}
"
let id_cases = [(("id.php", 3, 10), "int")]
let class_A =
"<?hh // strict
class A {
public function __construct(
private int $id,
) {}
public function getId(): int {
return $this->id;
// ^7:12 ^7:19
}
public static function foo(): int { return 3; }
public static int $foo = 3;
const int foo = 5;
}
"
let class_A_cases = [(("A.php", 7, 12), "this"); (("A.php", 7, 19), "int")]
let mypair =
"<?hh // strict
class MyPair<T> {
private T $fst;
private T $snd;
public function __construct(T $fst, T $snd) {
$this->fst = $fst;
$this->snd = $snd;
}
public function getFst(): T {
return $this->fst;
}
public function setFst(T $fst): void {
$this->fst = $fst;
}
public function getSnd(): T {
return $this->snd;
}
public function setSnd(T $snd): void {
$this->snd = $snd;
}
}
"
let test_mypair =
"<?hh // strict
class B extends A {}
class C extends A {}
function test_mypair(MyPair<A> $v): MyPair<A> {
$c = $v->getSnd();
// ^6:8 ^6:15
$v = new MyPair(new B(1), new C(2));
// ^8:4 ^8:19
$v->setFst($c);
// ^10:14
return test_mypair($v);
// ^12:10 ^12:22
}
"
let test_mypair_cases =
[
(("test_mypair.php", 6, 8), "MyPair<A>");
(("test_mypair.php", 6, 15), "(function(): A)");
(("test_mypair.php", 6, 19), "A");
(("test_mypair.php", 8, 4), "MyPair<A>");
(("test_mypair.php", 8, 19), "B");
(("test_mypair.php", 10, 14), "A");
(("test_mypair.php", 12, 10), "(function(MyPair<A> $v): MyPair<A>)");
(("test_mypair.php", 12, 21), "MyPair<A>");
(("test_mypair.php", 12, 22), "MyPair<A>");
]
let loop_assignment =
"<?hh // strict
function douse(mixed $item): void {}
function cond(): bool { return true; }
function loop_assignment(): void {
$x = 1;
// ^5:4
while (cond()) {
douse($x);
// ^8:11
if (cond())
$x = 'foo';
// ^11:7
}
douse($x);
// ^14:9
}
"
let loop_assignment_cases =
[
(("loop_assignment.php", 5, 4), "int");
(("loop_assignment.php", 8, 11), "(int | string)");
(("loop_assignment.php", 11, 7), "string");
(("loop_assignment.php", 14, 9), "(int | string)");
]
let callback =
"<?hh // strict
function test_callback((function(int): string) $cb): void {
$cb;
//^3:3
$cb(5);
//^5:3 ^5:8
}
"
let callback_cases =
[
(("callback.php", 3, 3), "(function(int): string)");
(("callback.php", 5, 3), "(function(int): string)");
(("callback.php", 5, 8), "string");
]
let nullthrows =
"<?hh // strict
function nullthrows<T>(?T $x): T {
invariant($x !== null, 'got null');
// ^3:13
return $x;
// ^5:10
}
"
let nullthrows_cases =
[
(("nullthrows.php", 3, 13), "?T");
(("nullthrows.php", 5, 10), "(nonnull & T)");
]
let nullvec =
"<?hh // strict
function foo() : vec<?int> {
$x = vec[1, null];
$x;
//^4:3
$y = vec[1, 'hi', null];
$y;
//^7:3
$z = vec[null];
$z;
//^10:3
}
"
let nullvec_cases =
[
(("nullvec.php", 4, 3), "vec<?int>");
(("nullvec.php", 7, 3), "vec<?(int | string)>");
(("nullvec.php", 10, 3), "vec<null>");
]
let curried =
"<?hh // strict
function curried(): (function(int): (function(bool): string)) {
return $i ==> $b ==> $i > 0 && $b ? 'true' : 'false';
}
function test_curried(bool $cond): void {
$f = () ==> curried();
$f()(5)(true);
//^7:3
}
"
let curried_cases =
[
( ("curried.php", 6, 3),
"(function(): (function(int): (function(bool): string)))" );
( ("curried.php", 7, 3),
"(function(): (function(int): (function(bool): string)))" );
]
let multiple_type =
"<?hh // strict
class C1 { public function foo(): int { return 5; } }
class C2 { public function foo(): string { return 's'; } }
function test_multiple_type(C1 $c1, C2 $c2, bool $cond): arraykey {
$x = $cond ? $c1 : $c2;
return $x->foo();
// ^6:10
}
"
let multiple_type_cases =
[
(("multiple_type.php", 6, 10), "(C1 | C2)");
(("multiple_type.php", 6, 14), "(function(): (int | string))");
]
let lambda_param =
"<?hh // strict
function takes_func((function (int): num) $f): void {}
function lambda_param(): void {
$f1 = $s ==> 3;
// ^4:9
takes_func($x ==> $x);
// ^6:14
}
"
let lambda_param_cases =
[
(("lambda_param.php", 4, 9), "mixed");
(("lambda_param.php", 6, 14), "int");
(("lambda_param.php", 4, 12), "(function(mixed $s): int)");
(("lambda_param.php", 6, 17), "(function(int $x): num)");
]
let class_id =
"<?hh // strict
function class_id(): void {
$x = new A(5);
// ^3:12
A::foo();
//^5:3
A::$foo;
//^7:3
A::foo;
//^9:3
$cls = A::class;
$cls;
// ^12:4
}
"
let class_id_cases =
[
(("class_id.php", 3, 12), "A");
(("class_id.php", 5, 3), "A");
(("class_id.php", 7, 3), "A");
(("class_id.php", 9, 3), "A");
(("class_id.php", 12, 4), "classname<A>");
]
let files =
[
("id.php", id);
("A.php", class_A);
("MyPair.php", mypair);
("test_mypair.php", test_mypair);
("loop_assignment.php", loop_assignment);
("callback.php", callback);
("nullthrows.php", nullthrows);
("nullvec.php", nullvec);
("curried.php", curried);
("multiple_type.php", multiple_type);
("lambda_param.php", lambda_param);
("class_id.php", class_id);
]
let cases =
id_cases
@ class_A_cases
@ test_mypair_cases
@ loop_assignment_cases
@ callback_cases
@ nullthrows_cases
@ nullvec_cases
@ curried_cases
@ multiple_type_cases
@ lambda_param_cases
@ class_id_cases
let test () =
let env =
Test.setup_server
()
~hhi_files:(Hhi.get_raw_hhi_contents () |> Array.to_list)
in
let env = Test.setup_disk env files in
let test_case ((file, line, col), expected_type) =
let compare_type expected type_at =
let ty_str =
match type_at with
| Some (env, ty) -> Tast_env.print_ty env ty
| None ->
Test.fail
(Printf.sprintf "No type inferred at %s:%d:%d" file line col)
in
let fmt = Printf.sprintf "%s:%d:%d %s" file line col in
Test.assertEqual (fmt expected) (fmt ty_str)
in
let ctx = Provider_utils.ctx_from_server_env env in
let (ctx, entry) =
Provider_context.add_entry_if_missing
~ctx
~path:(Relative_path.from_root ~suffix:file)
in
let { Tast_provider.Compute_tast.tast; _ } =
Tast_provider.compute_tast_unquarantined ~ctx ~entry
in
let ty = ServerInferType.type_at_pos ctx tast line col in
compare_type expected_type ty
in
List.iter cases ~f:test_case |
OCaml | hhvm/hphp/hack/test/integration_ml/test_interrupt.ml | module Test = Integration_test_base
let foo_name = "foo.php"
let bar_name = Printf.sprintf "bar%d.php"
let foo_contents =
"<?hh //strict
/* HH_FIXME[4336] */
function foo() : string {
}
"
let bar_contents =
Printf.sprintf "<?hh //strict
function bar%d() : int {
return foo();
}
"
let expected_errors =
{|
File "/bar2.php", line 4, characters 10-14:
Invalid return type (Typing[4110])
File "/bar2.php", line 3, characters 19-21:
Expected `int`
File "/foo.php", line 3, characters 18-23:
But got `string`
|}
let root = "/"
let hhconfig_filename = Filename.concat root ".hhconfig"
let hhconfig_contents =
"
allowed_fixme_codes_strict = 4336
allowed_decl_fixme_codes = 4336
"
let test () =
Relative_path.set_path_prefix Relative_path.Root (Path.make root);
TestDisk.set hhconfig_filename hhconfig_contents;
let options = ServerArgs.default_options ~root in
let (custom_config, _) = ServerConfig.load ~silent:false options in
let env = Test.setup_server ~custom_config () in
(* There are errors in both bar files *)
let env =
Test.setup_disk
env
[
(foo_name, foo_contents);
(bar_name 1, bar_contents 1);
(bar_name 2, bar_contents 2);
]
in
(* Prepare rechecking of all files *)
let ctx = Provider_utils.ctx_from_server_env env in
let workers = None in
let defs_per_file =
Naming_table.to_defs_per_file env.ServerEnv.naming_table
in
(* Pretend that this rechecking will be cancelled before we get to bar1 *)
let bar1_path =
Relative_path.(create Root (Test.prepend_root (bar_name 1)))
in
Typing_check_service.TestMocking.set_is_cancelled bar1_path;
(* Run the recheck *)
let interrupt = MultiThreadedCall.no_interrupt () in
let fnl = Relative_path.Map.keys defs_per_file in
let check_info =
{
Typing_service_types.init_id = "";
check_reason = "test_interrupt";
log_errors = false;
recheck_id = Some "";
use_max_typechecker_worker_memory_for_decl_deferral = false;
per_file_profiling = HackEventLogger.PerFileProfilingConfig.default;
memtrace_dir = None;
}
in
let ( ( (),
{
Typing_check_service.errors;
diagnostic_pusher = (diag_pusher, _);
_;
} ),
cancelled ) =
Typing_check_service.go_with_interrupt
ctx
workers
(Telemetry.create ())
fnl
~root:None
~interrupt
~memory_cap:None
~longlived_workers:false
~use_hh_distc_instead_of_hulk:false
~hh_distc_fanout_threshold:None
~check_info
in
assert (Option.is_none diag_pusher);
(* Assert that we got the errors in bar2 only... *)
Test.assert_errors errors expected_errors;
(* ...while bar1 is among cancelled jobs*)
(match cancelled with
| Some ([x], _) when x = bar1_path -> ()
| _ -> assert false);
() |
OCaml | hhvm/hphp/hack/test/integration_ml/test_interrupt2.ml | open Integration_test_base_types
module Test = Integration_test_base
let foo_name = "foo.php"
let bar_name = Printf.sprintf "bar%d.php"
let foo_contents =
Printf.sprintf "<?hh //strict
/* HH_FIXME[4336] */
function foo() : %s {
}
"
let bar_contents =
Printf.sprintf "<?hh //strict
function bar%d() : int {
return foo();
}
"
let expected_errors =
{|
File "/bar1.php", line 4, characters 10-14:
Invalid return type (Typing[4110])
File "/bar1.php", line 3, characters 19-21:
Expected `int`
File "/foo.php", line 3, characters 18-23:
But got `string`
File "/bar2.php", line 4, characters 10-14:
Invalid return type (Typing[4110])
File "/bar2.php", line 3, characters 19-21:
Expected `int`
File "/foo.php", line 3, characters 18-23:
But got `string`
|}
let root = "/"
let hhconfig_filename = Filename.concat root ".hhconfig"
let hhconfig_contents =
"
allowed_fixme_codes_strict = 4336
allowed_decl_fixme_codes = 4336
"
let test () =
Relative_path.set_path_prefix Relative_path.Root (Path.make root);
TestDisk.set hhconfig_filename hhconfig_contents;
let options = ServerArgs.default_options ~root in
let (custom_config, _) = ServerConfig.load ~silent:false options in
let env = Test.setup_server ~custom_config () in
ServerMain.force_break_recheck_loop_for_test false;
(* There are initially no errors *)
let env =
Test.setup_disk
env
[
(foo_name, foo_contents "int");
(bar_name 1, bar_contents 1);
(bar_name 2, bar_contents 2);
]
in
Test.assert_no_errors env;
(* This change will recheck all files and reveal errors in bar1 and bar2 *)
let loop_input =
Test.
{
default_loop_input with
disk_changes = [(foo_name, foo_contents "string")];
}
in
(* ... but we'll pretend that this recheck will be cancelled before getting
* to bar1 *)
let bar1_path =
Relative_path.(create Root (Test.prepend_root (bar_name 1)))
in
Typing_check_service.TestMocking.set_is_cancelled bar1_path;
let (env, _) = Test.run_loop_once env loop_input in
(* We'll get all the errors anyway due to server looping until check is
* fully finished *)
Test.assert_env_errors env expected_errors |
OCaml | hhvm/hphp/hack/test/integration_ml/test_lazy_decl_idempotence.ml | module Test = Integration_test_base
let foo_name = "\\Foo"
let bar_name = "\\Bar"
let foo_file_name = "foo.php"
let bar_file_name = "bar.php"
let foo_contents =
{|<?hh //strict
const string GLOBAL_X = "X";
class Foo {
// this is an error (lack of typehint) revealed during declaration only
const X = GLOBAL_X;
}
|}
let bar_contents =
{|<?hh //strict
class Bar {
public function test(Foo $x) : void {}
}
|}
let expected_errors =
{|
File "/foo.php", line 7, characters 9-9:
Please add a type hint (Naming[2035])
|}
let test () =
let env = Test.setup_server () in
let env =
Test.setup_disk
env
[(foo_file_name, foo_contents); (bar_file_name, bar_contents)]
in
let ctx = Provider_utils.ctx_from_server_env env in
let classes = [foo_name; bar_name] in
let foo_path = Relative_path.from_root ~suffix:foo_file_name in
let bar_path = Relative_path.from_root ~suffix:bar_file_name in
(* Remove things from shared memory (that were put there by Test.setup_disk)
* to simulate lazy saved state init. *)
let defs =
{ FileInfo.empty_names with FileInfo.n_classes = SSet.of_list classes }
in
let elems = Decl_class_elements.get_for_classes ~old:false classes in
Decl_redecl_service.remove_defs ctx ~collect_garbage:false defs elems;
SharedMem.invalidate_local_caches ();
(* Local caches need to be invalidated whenever things are removed from shared
* memory (to avoid getting cached old versions of declarations) *)
let memory_cap = None in
let check_info =
{
Typing_service_types.init_id = "";
check_reason = "test";
log_errors = false;
recheck_id = Some "";
use_max_typechecker_worker_memory_for_decl_deferral = false;
per_file_profiling = HackEventLogger.PerFileProfilingConfig.default;
memtrace_dir = None;
}
in
let { Typing_check_service.errors; telemetry; _ } =
Typing_check_service.go
ctx
None
(Telemetry.create ())
[bar_path]
~root:None
~memory_cap
~longlived_workers:false
~use_hh_distc_instead_of_hulk:false
~hh_distc_fanout_threshold:None
~check_info
in
Test.assert_errors errors "";
let { Typing_check_service.errors; telemetry; _ } =
Typing_check_service.go
ctx
None
telemetry
[bar_path]
~root:None
~memory_cap
~longlived_workers:false
~use_hh_distc_instead_of_hulk:false
~hh_distc_fanout_threshold:None
~check_info
in
Test.assert_errors errors "";
let { Typing_check_service.errors; telemetry; _ } =
Typing_check_service.go
ctx
None
telemetry
[foo_path]
~root:None
~memory_cap
~longlived_workers:false
~use_hh_distc_instead_of_hulk:false
~hh_distc_fanout_threshold:None
~check_info
in
Test.assert_errors errors expected_errors;
let { Typing_check_service.errors; _ } =
Typing_check_service.go
ctx
None
telemetry
[foo_path]
~root:None
~memory_cap
~longlived_workers:false
~use_hh_distc_instead_of_hulk:false
~hh_distc_fanout_threshold:None
~check_info
in
Test.assert_errors errors expected_errors;
ignore env;
() |
OCaml | hhvm/hphp/hack/test/integration_ml/test_modify_file.ml | open Integration_test_base_types
open ServerEnv
module Test = Integration_test_base
let foo_contents =
"<?hh
function g(): string {
return 'a';
}
"
let foo_changes =
"<?hh
function g(): int {
return 'a';
}
"
let test () =
let env = Test.setup_server () in
let (env, loop_output) =
Test.(
run_loop_once
env
{ default_loop_input with disk_changes = [("foo.php", foo_contents)] })
in
if not loop_output.did_read_disk_changes then
Test.fail "Expected the server to process disk updates";
(match Errors.get_error_list env.errorl with
| [] -> ()
| _ -> Test.fail "Expected no errors");
let (env, loop_output) =
Test.(
run_loop_once
env
{ default_loop_input with disk_changes = [("foo.php", foo_changes)] })
in
if not loop_output.did_read_disk_changes then
Test.fail "Expected the server to process disk updates";
let expected_error =
"File \"/foo.php\", line 3, characters 20-22:\n"
^ "Invalid return type (Typing[4110])\n"
^ " File \"/foo.php\", line 2, characters 23-25:\n"
^ " Expected `int`\n"
^ " File \"/foo.php\", line 3, characters 20-22:\n"
^ " But got `string`\n"
in
Test.assertSingleError expected_error (Errors.get_error_list env.errorl) |
OCaml | hhvm/hphp/hack/test/integration_ml/test_new_file.ml | (*
* Copyright (c) 2016, 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.
*
*
*)
open Integration_test_base_types
open ServerEnv
open Hh_prelude
module Test = Integration_test_base
let foo_contents = "<?hh
function f(): int {
return 3
}
"
let test () =
let env = Test.setup_server () in
let (env, loop_output) =
Test.(
run_loop_once
env
{ default_loop_input with disk_changes = [("foo.php", foo_contents)] })
in
if not loop_output.did_read_disk_changes then
Test.fail "Expected the server to process disk updates";
let expected_errors =
[
"File \"/foo.php\", line 4, characters 11-11:\n"
^ "A semicolon `;` is expected here. (Parsing[1002])";
]
in
match List.zip expected_errors (Errors.get_error_list env.errorl) with
| List.Or_unequal_lengths.Ok errs ->
List.iter
~f:(fun (expected, err) -> Test.assertSingleError expected [err])
errs
| List.Or_unequal_lengths.Unequal_lengths -> Test.fail "Expected 1 error." |
OCaml | hhvm/hphp/hack/test/integration_ml/test_property_initializer.ml | module Test = Integration_test_base
let a_file_name = "A.php"
let b_file_name = "B.php"
let a_contents = "<?hh // strict
abstract class A {
protected ?int $x;
}
"
let a_contents_require_init =
"<?hh // strict
abstract class A {
protected int $x;
}
"
let b_contents = "<?hh // strict
class B extends A {}
"
let errors =
{|
File "/B.php", line 3, characters 7-7:
Class `B` has properties that cannot be null and aren't always set in `__construct`. (NastCheck[3015])
File "/A.php", line 4, characters 17-18:
`$this->x` is not initialized.
|}
let test () =
let env = Test.setup_server () in
let env =
Test.setup_disk env [(a_file_name, a_contents); (b_file_name, b_contents)]
in
Test.assert_no_errors env;
let (env, _) =
Test.change_files env [(a_file_name, a_contents_require_init)]
in
Test.assert_env_errors env errors;
() |
OCaml | hhvm/hphp/hack/test/integration_ml/test_property_initializer2.ml | module Test = Integration_test_base
let a_file_name = "A.php"
let b_file_name = "B.php"
let c_file_name = "C.php"
let a_contents = "<?hh // strict
abstract class A {
public X $x;
}
"
let b_contents = "<?hh // strict
type X = int;
"
let b_contents_after = "<?hh // strict
type X = ?int;
"
let c_contents = "<?hh // strict
class C extends A {}
"
let errors =
{|
File "/C.php", line 3, characters 7-7:
Class `C` has properties that cannot be null and aren't always set in `__construct`. (NastCheck[3015])
File "/A.php", line 4, characters 12-13:
`$this->x` is not initialized.
|}
let test () =
let env = Test.setup_server () in
let env =
Test.setup_disk
env
[
(a_file_name, a_contents);
(b_file_name, b_contents);
(c_file_name, c_contents);
]
in
Test.assert_env_errors env errors;
let (env, _) = Test.change_files env [(b_file_name, b_contents_after)] in
Test.assert_no_errors env;
() |
OCaml | hhvm/hphp/hack/test/integration_ml/test_serverConfig_overrides.ml | (*
* 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.
*
*)
module Test = Integration_test_base
let root = "/"
let hhconfig_filename = Filename.concat root ".hhconfig"
let test () =
Relative_path.set_path_prefix Relative_path.Root (Path.make root);
TestDisk.set hhconfig_filename "timeout = 737";
let options = ServerArgs.default_options ~root in
let (options : ServerArgs.options) =
ServerArgs.set_config
options
[("timeout", "747"); ("informant_min_distance_restart", "711")]
in
let (config, local_config) = ServerConfig.load ~silent:false options in
let timeout =
TypecheckerOptions.timeout (ServerConfig.typechecker_options config)
in
if not (timeout = 747) then Test.fail "Global config value not overridden!";
let informant_min_distance_restart =
local_config.ServerLocalConfig.informant_min_distance_restart
in
if not (informant_min_distance_restart = 711) then
Test.fail "Local config value not overridden!" |
OCaml | hhvm/hphp/hack/test/integration_ml/test_server_hover.ml | (*
* Copyright (c) 2016, 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.
*
*
*)
open Hh_prelude
open HoverService
module Test = Integration_test_base
let pos_at (line1, column1) (line2, column2) =
Some
(Pos.make_from_lnum_bol_offset
~pos_file:Relative_path.default
~pos_start:(line1, 0, column1 - 1)
~pos_end:(line2, 0, column2))
let class_members =
"<?hh // strict
abstract class ClassMembers {
public async function genDoStuff(): Awaitable<void> {}
public string $public = 'public';
protected string $protected = 'protected';
private string $private = 'private';
public static string $staticVar = 'staticVar';
public abstract function abstractMethod(): string;
public final function finalMethod(string $arg): void {}
protected final static async function genLotsOfModifiers(): Awaitable<void> {}
public async function exerciseClassMembers(): Awaitable<void> {
await $this->genDoStuff();
// ^18:18
$this->public;
// ^20:12
$this->protected;
// ^22:12
$this->private;
// ^24:12
ClassMembers::$staticVar;
// ^26:19
$this->abstractMethod();
// ^28:12
$this->finalMethod(\"arg\");
// ^30:12
await ClassMembers::genLotsOfModifiers();
// ^32:11 ^32:25
$this->calculateDistance(5, -6, 12, 1);
// ^34:28
}
/** Another method doc block */
public function calculateDistance(
int $originalPositionX,
int $finalPositionX,
int $originalPositionY,
int $finalPositionY,
): int {
return sqrt(
pow($originalPositionX - $finalPositionX, 2) +
pow($originalPositionY - $finalPositionY, 2),
);
}
}
"
let class_members_cases =
[
( ("class_members.php", 18, 18),
[
{
snippet =
"// Defined in ClassMembers\npublic async function genDoStuff(): Awaitable<void>";
addendum = [];
pos = pos_at (18, 18) (18, 27);
};
] );
( ("class_members.php", 20, 12),
[
{
snippet = "// Defined in ClassMembers\npublic string $public";
addendum = [];
pos = pos_at (20, 12) (20, 17);
};
] );
( ("class_members.php", 22, 12),
[
{
snippet = "// Defined in ClassMembers\nprotected string $protected";
addendum = [];
pos = pos_at (22, 12) (22, 20);
};
] );
( ("class_members.php", 24, 12),
[
{
snippet = "// Defined in ClassMembers\nprivate string $private";
addendum = [];
pos = pos_at (24, 12) (24, 18);
};
] );
( ("class_members.php", 26, 19),
[
{
snippet = "// Defined in ClassMembers\npublic static string $staticVar";
addendum = [];
pos = pos_at (26, 19) (26, 28);
};
] );
( ("class_members.php", 28, 12),
[
{
snippet =
"// Defined in ClassMembers\npublic abstract function abstractMethod(): string";
addendum = [];
pos = pos_at (28, 12) (28, 25);
};
] );
( ("class_members.php", 30, 12),
[
{
snippet =
"// Defined in ClassMembers\npublic final function finalMethod(string $arg): void";
addendum = [];
pos = pos_at (30, 12) (30, 22);
};
] );
( ("class_members.php", 32, 11),
[
{
snippet = "abstract class ClassMembers";
addendum = [];
pos = pos_at (32, 11) (32, 22);
};
] );
( ("class_members.php", 32, 25),
[
{
snippet =
"// Defined in ClassMembers\nprotected final static async\nfunction genLotsOfModifiers(): Awaitable<void>";
addendum = [];
pos = pos_at (32, 25) (32, 42);
};
] );
( ("class_members.php", 34, 28),
[
{
snippet =
"// Defined in ClassMembers\n"
^ "public function calculateDistance(\n"
^ " int $originalPositionX,\n"
^ " int $finalPositionX,\n"
^ " int $originalPositionY,\n"
^ " int $finalPositionY\n"
^ "): int";
addendum = ["Another method doc block"];
pos = pos_at (34, 12) (34, 28);
};
] );
]
let classname_call =
"<?hh // strict
class ClassnameCall {
public static function foo(): int {
return 0;
}
}
function call_foo(): void {
ClassnameCall::foo();
// ^9:4 ^9:18
}"
let classname_call_cases =
[
( ("classname_call.php", 9, 4),
[
{
snippet = "class ClassnameCall";
addendum = [];
pos = pos_at (9, 3) (9, 15);
};
] );
( ("classname_call.php", 9, 18),
[
{
snippet =
"// Defined in ClassnameCall\npublic static function foo(): int";
addendum = [];
pos = pos_at (9, 18) (9, 20);
};
] );
]
let chained_calls =
"<?hh // strict
class ChainedCalls {
public function foo(): this {
return $this;
}
}
function test(): void {
$myItem = new ChainedCalls();
$myItem
->foo()
->foo()
->foo();
// ^13:8
}"
let chained_calls_cases =
[
( ("chained_calls.php", 13, 8),
[
{
snippet =
"// Defined in ChainedCalls\npublic function foo(): ChainedCalls";
addendum = [];
pos = pos_at (13, 7) (13, 9);
};
] );
]
let multiple_potential_types =
"<?hh // strict
class C1 { public function foo(): int { return 5; } }
class C2 { public function foo(): string { return 's'; } }
function test_multiple_type(C1 $c1, C2 $c2, bool $cond): arraykey {
$x = $cond ? $c1 : $c2;
return $x->foo();
// ^6:11^6:16
}"
let multiple_potential_types_cases =
[
( ("multiple_potential_types.php", 6, 11),
[{ snippet = "(C1 | C2)"; addendum = []; pos = None }] );
( ("multiple_potential_types.php", 6, 16),
[
{
snippet = "((function(): string) | (function(): int))";
addendum = [];
pos = None;
};
{
snippet = "((function(): string) | (function(): int))";
addendum = [];
pos = None;
};
] );
]
let classname_variable =
"<?hh // strict
class ClassnameVariable {
public static function foo(): void {}
}
function test_classname(): void {
$cls = ClassnameVariable::class;
$cls::foo();
// ^8:4 ^8:10
}"
let classname_variable_cases =
[
( ("classname_variable.php", 8, 4),
[
{
snippet = "classname<ClassnameVariable>";
addendum = [];
pos = pos_at (8, 3) (8, 6);
};
] );
( ("classname_variable.php", 8, 10),
[
{
snippet =
"// Defined in ClassnameVariable\npublic static function foo(): void";
addendum = [];
pos = pos_at (8, 9) (8, 11);
};
] );
]
let docblock =
"<?hh // strict
// Multiline
// function
// doc block.
function queryDocBlocks(): void {
DocBlock::doStuff();
//^7:3 ^7:13
queryDocBlocks();
//^9:3
DocBlock::preserveIndentation();
// ^11:13
DocBlock::leadingStarsAndMDList();
// ^13:13
DocBlock::manyLineBreaks();
// ^15:13
$x = new DocBlockOnClassButNotConstructor();
// ^17:12
DocBlockOnClassButNotConstructor::nonConstructorMethod();
// ^19:37
}
function docblockReturn(): DocBlockBase {
// ^23:28
$x = new DocBlockBase();
// ^25:12
return new DocBlockDerived();
// ^27:14
}
/* Class doc block.
This
doc
block
has
multiple
lines. */
class DocBlock {
/** Method doc block with double star. */
public static function doStuff(): void {}
/** Multiline doc block with
a certain amount of
indentation
we want to preserve. */
public static function preserveIndentation(): void {}
/** Multiline doc block with
* leading stars, as well as
* * a Markdown list!
* and we'd really like to preserve the Markdown list while getting rid of
* the other stars. */
public static function leadingStarsAndMDList(): void {}
// This method has many line breaks, which
//
// someone might use if they wanted
//
// to have separate paragraphs
//
// in Markdown.
public static function manyLineBreaks(): void {}
}
/**
* Class doc block for a class whose constructor doesn't have a doc block.
*/
final class DocBlockOnClassButNotConstructor {
public function __construct() {}
/* Docblock for non-constructor method in DocBlockOnClassButNotConstructor */
public static function nonConstructorMethod(): void {}
}
/* DocBlockBase: class doc block. */
class DocBlockBase {
/* DocBlockBase: constructor doc block. */
public function __construct() {}
}
/* DocBlockDerived: extends a class with a constructor, but doesn't have one of
its own. */
class DocBlockDerived extends DocBlockBase {}
// Line comments with breaks
// We don't want the line comment above to be part of this docblock.
// We do want both these lines though.
function line_comment_with_break(): void { line_comment_with_break(); }
// 89^:44
// This is another special case.
/** Only this should be part of the docblock. */
function two_comment_types(): void { two_comment_types(); }
// ^94:38
// There are too many blank lines between this comment and what it's commenting
// on.
function too_many_blank_lines(): void { too_many_blank_lines(); }
// ^101:41
/** A function with an HH_FIXME. */
/* HH_FIXME[4030] Missing return type hint. */
function needs_fixing() { needs_fixing(); }
// ^106:27
"
let docblock_cases =
[
( ("docblock.php", 7, 3),
[
{
snippet = "class DocBlock";
addendum =
["Class doc block.\nThis\ndoc\nblock\nhas\nmultiple\nlines."];
pos = pos_at (7, 3) (7, 10);
};
] );
( ("docblock.php", 7, 13),
[
{
snippet =
"// Defined in DocBlock\npublic static function doStuff(): void";
addendum = ["Method doc block with double star."];
pos = pos_at (7, 13) (7, 19);
};
] );
( ("docblock.php", 9, 3),
[
{
snippet = "function queryDocBlocks(): void";
addendum = ["Multiline\nfunction\ndoc block."];
pos = pos_at (9, 3) (9, 16);
};
] );
( ("docblock.php", 11, 13),
[
{
snippet =
"// Defined in DocBlock\npublic static function preserveIndentation(): void";
addendum =
[
"Multiline doc block with
a certain amount of
indentation
we want to preserve.";
];
pos = pos_at (11, 13) (11, 31);
};
] );
( ("docblock.php", 13, 13),
[
{
snippet =
"// Defined in DocBlock\npublic static function leadingStarsAndMDList(): void";
addendum =
[
"Multiline doc block with
leading stars, as well as
* a Markdown list!
and we'd really like to preserve the Markdown list while getting rid of
the other stars.";
];
pos = pos_at (13, 13) (13, 33);
};
] );
( ("docblock.php", 15, 13),
[
{
snippet =
"// Defined in DocBlock\npublic static function manyLineBreaks(): void";
addendum =
[
"This method has many line breaks, which\n\nsomeone might use if they wanted\n\nto have separate paragraphs\n\nin Markdown.";
];
pos = pos_at (15, 13) (15, 26);
};
] );
( ("docblock.php", 17, 12),
[
{
snippet =
"// Defined in DocBlockOnClassButNotConstructor\npublic function __construct(): void";
addendum =
[
"Class doc block for a class whose constructor doesn't have a doc block.";
];
pos = pos_at (17, 12) (17, 43);
};
] );
( ("docblock.php", 19, 37),
[
{
snippet =
"// Defined in DocBlockOnClassButNotConstructor\npublic static function nonConstructorMethod(): void";
addendum =
[
"Docblock for non-constructor method in DocBlockOnClassButNotConstructor";
];
pos = pos_at (19, 37) (19, 56);
};
] );
( ("docblock.php", 23, 28),
[
{
snippet = "DocBlockBase";
addendum = ["DocBlockBase: class doc block."];
pos = pos_at (23, 28) (23, 39);
};
] );
( ("docblock.php", 25, 12),
[
{
snippet =
"// Defined in DocBlockBase\npublic function __construct(): void";
addendum = ["DocBlockBase: constructor doc block."];
pos = pos_at (25, 12) (25, 23);
};
] );
( ("docblock.php", 27, 14),
[
{
snippet =
"// Defined in DocBlockBase\npublic function __construct(): void";
addendum = ["DocBlockBase: constructor doc block."];
pos = pos_at (27, 14) (27, 28);
};
] );
( ("docblock.php", 89, 44),
[
{
snippet = "function line_comment_with_break(): void";
addendum =
[
"We don't want the line comment above to be part of this docblock.\nWe do want both these lines though.";
];
pos = pos_at (89, 44) (89, 66);
};
] );
( ("docblock.php", 94, 38),
[
{
snippet = "function two_comment_types(): void";
addendum = ["Only this should be part of the docblock."];
pos = pos_at (94, 38) (94, 54);
};
] );
( ("docblock.php", 101, 41),
[
{
snippet = "function too_many_blank_lines(): void";
addendum = [];
pos = pos_at (101, 41) (101, 60);
};
] );
( ("docblock.php", 106, 27),
[
{
snippet = "function needs_fixing(): _";
addendum = ["A function with an HH_FIXME."];
pos = pos_at (106, 27) (106, 38);
};
] );
]
let special_cases =
"<?hh // strict
function special_cases(): void {
idx(varray[1, 2, 3], 1);
//^3:3
}
"
let special_cases_cases =
[
( ("special_cases.php", 3, 3),
[
{
snippet =
"function idx<Tk as arraykey, Tv>(
?KeyedContainer<int, int> $collection,
?int $index
)[]: ?int";
addendum =
[
"Index into the given KeyedContainer using the provided key.\n\nIf the key doesn't exist, the key is `null`, or the collection is `null`,\nreturn the provided default value instead, or `null` if no default value was\nprovided. If the key is `null`, the default value will be returned even if\n`null` is a valid key in the container.";
];
pos = pos_at (3, 3) (3, 5);
};
] );
]
let bounded_generic_fun =
"<?hh // strict
abstract class Base {}
final class C extends Base {}
function bounded_generic_fun<T as Base>(T $x): void {
$x;
//^5:3
if ($x is C) {
// ^7:7
$x;
// ^9:5
}
$x;
//^12:3
}
"
let bounded_generic_fun_cases =
[
( ("bounded_generic_fun.php", 5, 3),
[{ snippet = "T as Base"; addendum = []; pos = pos_at (5, 3) (5, 4) }] );
( ("bounded_generic_fun.php", 7, 7),
[{ snippet = "T as Base"; addendum = []; pos = pos_at (7, 7) (7, 8) }] );
( ("bounded_generic_fun.php", 9, 5),
[
{
snippet = "(T & C)\nwhere T as Base";
addendum = [];
pos = pos_at (9, 5) (9, 6);
};
] );
( ("bounded_generic_fun.php", 12, 3),
[{ snippet = "T as Base"; addendum = []; pos = pos_at (12, 3) (12, 4) }]
);
]
let doc_block_fallback =
"<?hh // strict
function dbfb_func(DBFBClass2 $c, DBFBClass3 $d): void {
$c->doTheThing();
// ^3:7
$c->docBlockInClass();
// ^5:7
$c->identical();
// ^7:7
$c->slightlyDifferent();
// ^9:7
$c->noDocBlock();
// ^11:7
$d->docBlockInClass2();
// ^13:7
$c->traitFunction();
// ^15:7
$d->traitFunction2();
// ^17:7
}
interface DBFBInterface1 {
/** DBFBInterface1. */
public function doTheThing(): void;
/** Identical. */
public function identical(): void;
/** Slightly different. */
public function slightlyDifferent(): void;
public function noDocBlock(): void;
}
interface DBFBInterface2 {
/** DBFBInterface2. */
public function doTheThing(): void;
/** DBFBInterface2. */
public function docBlockInClass(): void;
/** DBFBInterface2. */
public function docBlockInClass2(): void;
/** Identical. */
public function identical(): void;
/** Slightly different. */
public function slightlyDifferent(): void;
public function noDocBlock(): void;
}
interface DBFBInterface3 {
/** Slightly more different. */
public function slightlyDifferent(): void;
}
trait DBFBTrait {
/** DBFBTrait. */
public function traitFunction(): void {}
/** DBFBTrait. */
public function traitFunction2(): void {}
}
class DBFBClass1 implements DBFBInterface1 {
use DBFBTrait;
public function doTheThing(): void {}
/** DBFBClass1. */
public function docBlockInClass(): void {}
/** DBFBClass1. */
public function docBlockInClass2(): void {}
public function identical(): void {}
public function slightlyDifferent(): void {}
public function noDocBlock(): void {}
/** DBFBClass1. */
public function traitFunction2(): void {}
}
class DBFBClass2 extends DBFBClass1 implements DBFBInterface2, DBFBInterface3 {
public function docBlockInClass2(): void {}
}
class DBFBClass3 extends DBFBClass2 {
public function docBlockInClass2(): void {}
public function traitFunction2(): void {}
}
"
let doc_block_fallback_cases =
[
( ("doc_block_fallback.php", 3, 7),
[
{
snippet =
"// Defined in DBFBClass1\npublic function doTheThing(): void";
addendum =
[
"DBFBInterface2.\n(from DBFBInterface2)\n\n---\n\nDBFBInterface1.\n(from DBFBInterface1)";
];
pos = pos_at (3, 7) (3, 16);
};
] );
( ("doc_block_fallback.php", 5, 7),
[
{
snippet =
"// Defined in DBFBClass1\npublic function docBlockInClass(): void";
addendum = ["DBFBClass1."];
pos = pos_at (5, 7) (5, 21);
};
] );
( ("doc_block_fallback.php", 7, 7),
[
{
snippet = "// Defined in DBFBClass1\npublic function identical(): void";
addendum = ["Identical."];
pos = pos_at (7, 7) (7, 15);
};
] );
( ("doc_block_fallback.php", 9, 7),
[
{
snippet =
"// Defined in DBFBClass1\npublic function slightlyDifferent(): void";
addendum =
[
"Slightly more different.\n(from DBFBInterface3)\n\n---\n\nSlightly different.\n(from DBFBInterface1, DBFBInterface2)";
];
pos = pos_at (9, 7) (9, 23);
};
] );
( ("doc_block_fallback.php", 11, 7),
[
{
snippet =
"// Defined in DBFBClass1\npublic function noDocBlock(): void";
addendum = [];
pos = pos_at (11, 7) (11, 16);
};
] );
(* When falling back, if any class/trait ancestors have a doc block don't show
any doc blocks from interface ancestors. *)
( ("doc_block_fallback.php", 13, 7),
[
{
snippet =
"// Defined in DBFBClass3\npublic function docBlockInClass2(): void";
addendum = ["DBFBClass1."];
pos = pos_at (13, 7) (13, 22);
};
] );
( ("doc_block_fallback.php", 15, 7),
[
{
snippet =
"// Defined in DBFBTrait\npublic function traitFunction(): void";
addendum = ["DBFBTrait."];
pos = pos_at (15, 7) (15, 19);
};
] );
( ("doc_block_fallback.php", 17, 7),
[
{
snippet =
"// Defined in DBFBClass3\npublic function traitFunction2(): void";
addendum = ["DBFBClass1."];
pos = pos_at (17, 7) (17, 20);
};
] );
]
let class_id_positions =
"<?hh // strict
function create_class_id_positions(): void {
$x = new CIPos(CIPos2::MyConstInt);
// ^3:18 ^3:26
$x = new CIPos(CIPos2::$myStaticInt);
// ^5:18 ^5:26
$x = new CIPos(CIPos2::returnConstInt());
// ^7:18 ^7:26
}
class CIPos {
public function __construct(private int $x) {}
}
class CIPos2 {
const int MyConstInt = 0;
public static int $myStaticInt = 1;
public static function returnConstInt(): int {
return 2;
}
}
"
let class_id_positions_cases =
[
( ("class_id_positions.php", 3, 18),
[
{ snippet = "class CIPos2"; addendum = []; pos = pos_at (3, 18) (3, 23) };
] );
( ("class_id_positions.php", 3, 26),
[
{
snippet = "// Defined in CIPos2\nconst int MyConstInt";
addendum = [];
pos = pos_at (3, 26) (3, 35);
};
{
snippet = "Parameter: $x";
addendum = [];
pos = pos_at (3, 18) (3, 35);
};
] );
( ("class_id_positions.php", 5, 18),
[
{ snippet = "class CIPos2"; addendum = []; pos = pos_at (5, 18) (5, 23) };
] );
( ("class_id_positions.php", 5, 26),
[
{
snippet = "// Defined in CIPos2\npublic static int $myStaticInt";
addendum = [];
pos = pos_at (5, 26) (5, 37);
};
{
snippet = "Parameter: $x";
addendum = [];
pos = pos_at (5, 18) (5, 37);
};
] );
( ("class_id_positions.php", 7, 18),
[
{ snippet = "class CIPos2"; addendum = []; pos = pos_at (7, 18) (7, 23) };
] );
( ("class_id_positions.php", 7, 26),
[
{
snippet =
"// Defined in CIPos2\npublic static function returnConstInt(): int";
addendum = [];
pos = pos_at (7, 26) (7, 39);
};
] );
]
let duplicate_results =
"<?hh // strict
trait DuplicateResultTrait {
/** Doc block. */
public function foo(): void {}
}
class DuplicateResultClass1 {
use DuplicateResultTrait;
}
class DuplicateResultClass2 {
use DuplicateResultTrait;
}
function test_duplicate_result_class(bool $x): void {
if ($x) {
$y = new DuplicateResultClass1();
} else {
$y = new DuplicateResultClass2();
}
$y->foo();
// ^22:7
}
"
let hhconfig = "
allowed_fixme_codes_strict = 4030
"
let files =
[
("class_members.php", class_members);
("classname_call.php", classname_call);
("chained_calls.php", chained_calls);
("classname_variable.php", classname_variable);
("docblock.php", docblock);
("special_cases.php", special_cases);
("bounded_generic_fun.php", bounded_generic_fun);
("doc_block_fallback.php", doc_block_fallback);
("class_id_positions.php", class_id_positions);
]
let root = "/"
let hhconfig_filename = Filename.concat root ".hhconfig"
let hhconfig_contents =
"
allowed_fixme_codes_strict = 4030
allowed_decl_fixme_codes = 4030
"
let cases =
class_id_positions_cases
@ doc_block_fallback_cases
@ special_cases_cases
@ docblock_cases
@ class_members_cases
@ classname_call_cases
@ chained_calls_cases
@ classname_variable_cases
@ bounded_generic_fun_cases
let test () =
Relative_path.set_path_prefix Relative_path.Root (Path.make root);
TestDisk.set hhconfig_filename hhconfig_contents;
let options = ServerArgs.default_options ~root in
let (custom_config, _) = ServerConfig.load ~silent:false options in
let env =
Test.setup_server
()
~custom_config
~hhi_files:(Hhi.get_raw_hhi_contents () |> Array.to_list)
in
let env = Test.setup_disk env files in
Test.assert_no_errors env;
let failed_cases =
List.filter_map cases ~f:(fun ((file, line, column), expectedHover) ->
let list_to_string hover_list =
let string_list =
hover_list |> List.map ~f:HoverService.string_of_result
in
let inner =
match string_list |> List.reduce ~f:(fun a b -> a ^ "; " ^ b) with
| None -> ""
| Some s -> s
in
Printf.sprintf "%s:%d:%d: [%s]" file line column inner
in
let path = Relative_path.from_root ~suffix:file in
let (ctx, entry) =
Provider_context.add_entry_if_missing
~ctx:(Provider_utils.ctx_from_server_env env)
~path
in
let hover =
Provider_utils.respect_but_quarantine_unsaved_changes
~ctx
~f:(fun () -> ServerHover.go_quarantined ~ctx ~entry ~line ~column)
in
let expected = list_to_string expectedHover in
let actual = list_to_string hover in
if not (String.equal expected actual) then
Some (expected, actual)
else
None)
in
match failed_cases with
| [] -> ()
| cases ->
let display_case (expected, actual) =
Printf.sprintf "Expected:\n%s\nGot:\n%s" expected actual
in
Test.fail @@ String.concat ~sep:"\n\n" (List.map ~f:display_case cases) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.