language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
OCaml | hhvm/hphp/hack/src/annotated_ast/aast.ml | (*
* Copyright (c) 2015, 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.
*
*)
include Aast_defs
let is_erased = function
| Erased -> true
| SoftReified
| Reified ->
false
let is_reified = function
| Reified -> true
| Erased
| SoftReified ->
false
let is_soft_reified = function
| SoftReified -> true
| Erased
| Reified ->
false
(* Splits the methods on a class into the constructor, statics, dynamics *)
(**
* Methods, properties, and requirements are order dependent in bytecode
* emission, which is observable in user code via `ReflectionClass`.
*)
let split_methods c_methods =
let (constr, statics, res) =
List.fold_left
(fun (constr, statics, rest) m ->
if snd m.m_name = "__construct" then
(Some m, statics, rest)
else if m.m_static then
(constr, m :: statics, rest)
else
(constr, statics, m :: rest))
(None, [], [])
c_methods
in
(constr, List.rev statics, List.rev res)
(* Splits class properties into statics, dynamics *)
let split_vars c_vars =
let (statics, res) =
List.fold_left
(fun (statics, rest) v ->
if v.cv_is_static then
(v :: statics, rest)
else
(statics, v :: rest))
([], [])
c_vars
in
(List.rev statics, List.rev res)
(* Splits `require`s into extends, implements, class *)
let split_reqs c_reqs =
let (extends, implements, class_) =
List.fold_left
(fun (extends, implements, class_) (h, require_kind) ->
match require_kind with
| RequireExtends -> (h :: extends, implements, class_)
| RequireImplements -> (extends, h :: implements, class_)
| RequireClass -> (extends, implements, h :: class_))
([], [], [])
c_reqs
in
(List.rev extends, List.rev implements, List.rev class_)
let partition_map_require_kind ~f trait_reqs =
let rec partition req_extends req_implements req_class c_reqs =
match c_reqs with
| [] -> (List.rev req_extends, List.rev req_implements, List.rev req_class)
| ((_, RequireExtends) as req) :: tl ->
partition (f req :: req_extends) req_implements req_class tl
| ((_, RequireImplements) as req) :: tl ->
partition req_extends (f req :: req_implements) req_class tl
| ((_, RequireClass) as req) :: tl ->
partition req_extends req_implements (f req :: req_class) tl
in
partition [] [] [] trait_reqs
(* extract the hint from a type annotation *)
let hint_of_type_hint : 'ex. 'ex type_hint -> type_hint_ = snd
(* extract the type from a type annotation *)
let type_of_type_hint : 'ex. 'ex type_hint -> 'ex = fst
(* map a function over the second part of a type annotation *)
let type_hint_option_map ~f ta =
let mapped_hint =
match hint_of_type_hint ta with
| Some hint -> Some (f hint)
| None -> None
in
(type_of_type_hint ta, mapped_hint)
(* helper function to access the list of enums included by an enum *)
let enum_includes_map ?(default = []) ~f includes =
match includes with
| None -> default
| Some includes -> f includes
let is_enum_class c = Ast_defs.is_c_enum_class c.c_kind
let module_name_kind_to_string = function
| MDNameExact md -> Ast_defs.get_id md
| MDNamePrefix md -> Ast_defs.get_id md ^ ".*"
| MDNameGlobal _ -> "global"
(* Combinators for folding / iterating over all of a switch statement *)
module GenCase : sig
val map :
f:(('ex, 'en) gen_case -> 'a) ->
('ex, 'en) case list ->
('ex, 'en) default_case option ->
'a list
val fold_left :
init:'state ->
f:('state -> ('ex, 'en) gen_case -> 'state) ->
('ex, 'en) case list ->
('ex, 'en) default_case option ->
'state
val fold_right :
init:'state ->
f:(('ex, 'en) gen_case -> 'state -> 'state) ->
('ex, 'en) case list ->
('ex, 'en) default_case option ->
'state
val fold_left_mem :
init:'state ->
f:('state -> ('ex, 'en) gen_case -> 'state) ->
('ex, 'en) case list ->
('ex, 'en) default_case option ->
'state list
end = struct
let map ~f cases odfl =
let rec doit cases =
match cases with
| [] -> Option.to_list (Option.map (fun x -> f (Default x)) odfl)
| case :: cases -> f (Case case) :: doit cases
in
doit cases
let fold_left ~init:state ~f cases odfl =
let state =
List.fold_left (fun state case -> f state (Case case)) state cases
in
let state =
let some dfl = f state (Default dfl) in
Option.fold ~none:state ~some odfl
in
state
let fold_right ~init:state ~f cases odfl =
let state =
let some dfl = f (Default dfl) state in
Option.fold ~none:state ~some odfl
in
let state =
List.fold_right (fun case state -> f (Case case) state) cases state
in
state
let fold_left_mem ~init ~f cases odfl =
let f (state, acc) case =
let state = f state case in
(state, state :: acc)
in
snd (fold_left ~init:(init, []) ~f cases odfl)
end |
OCaml | hhvm/hphp/hack/src/annotated_ast/aast_defs.ml | (*
* Copyright (c) 2017, 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.
*
*)
(* Ensure that doc comments are always on a separate line by
* requiring a lot of padding for inline doc comments. *)
[@@@ocamlformat "doc-comments-padding=80"]
(* We could open Hh_prelude here, but then we get errors about using ==,
which some visitor below uses. *)
open Base.Export
type 'a local_id_map = 'a Local_id.Map.t [@@deriving eq, hash, ord, map, show]
let pp_local_id_map _ fmt map =
Format.fprintf fmt "@[<hov 2>{";
ignore
(Local_id.Map.fold
(fun key _ sep ->
if sep then Format.fprintf fmt "@ ";
Local_id.pp fmt key;
true)
map
false);
Format.fprintf fmt "}@]"
type pos = Ast_defs.pos [@@deriving eq, hash, show, ord] [@@transform.opaque]
let hash_pos hsv _pos = hsv
type byte_string = Ast_defs.byte_string
[@@deriving eq, hash, show, ord] [@@transform.opaque]
type visibility = Ast_defs.visibility =
| Private
| Public
| Protected
| Internal
[@@deriving eq, hash, ord, show { with_path = false }] [@@transform.opaque]
type tprim = Ast_defs.tprim =
| Tnull
| Tvoid
| Tint
| Tbool
| Tfloat
| Tstring
| Tresource
| Tnum
| Tarraykey
| Tnoreturn
[@@deriving eq, hash, ord, show { with_path = false }] [@@transform.opaque]
type typedef_visibility = Ast_defs.typedef_visibility =
| Transparent
| Opaque
| OpaqueModule
| CaseType
[@@deriving eq, hash, ord, show { with_path = false }] [@@transform.opaque]
type reify_kind = Ast_defs.reify_kind =
| Erased
| SoftReified
| Reified
[@@deriving eq, hash, ord, show { with_path = false }] [@@transform.opaque]
type pstring = Ast_defs.pstring
[@@deriving eq, hash, ord, hash, show] [@@transform.opaque]
type positioned_byte_string = Ast_defs.positioned_byte_string
[@@deriving eq, ord, show]
type og_null_flavor = Ast_defs.og_null_flavor =
| OG_nullthrows
| OG_nullsafe
[@@deriving eq, hash, ord, show { with_path = false }] [@@transform.opaque]
type prop_or_method = Ast_defs.prop_or_method =
| Is_prop
| Is_method
[@@deriving eq, hash, ord, show { with_path = false }] [@@transform.opaque]
type local_id = (Local_id.t[@visitors.opaque]) [@@transform.opaque]
and lid = pos * local_id [@@transform.opaque]
and sid = Ast_defs.id [@@transform.opaque]
and class_name = sid [@@transform.opaque]
(** Aast.program represents the top-level definitions in a Hack program.
* ex: Expression annotation type (when typechecking, the inferred type)
* en: Environment (tracking state inside functions and classes)
*)
and ('ex, 'en) program = ('ex, 'en) def list
and ('ex, 'en) stmt = (pos[@transform.opaque]) * ('ex, 'en) stmt_
and ('ex, 'en) stmt_ =
| Fallthrough
(** Marker for a switch statement that falls through.
*
* // FALLTHROUGH *)
| Expr of ('ex, 'en) expr
(** Standalone expression.
*
* 1 + 2; *)
| Break
(** Break inside a loop or switch statement.
*
* break; *)
| Continue
(** Continue inside a loop or switch statement.
*
* continue; *)
| Throw of ('ex, 'en) expr
(** Throw an exception.
*
* throw $foo; *)
| Return of ('ex, 'en) expr option
(** Return, with an optional value.
*
* return;
* return $foo; *)
| Yield_break
(** Yield break, terminating the current generator. This behaves like
* return; but is more explicit, and ensures the function is treated
* as a generator.
*
* yield break; *)
| Awaitall of
(* Temporaries assigned when running awaits. *)
(lid option * ('ex, 'en) expr) list
* (* Block assigning temporary to relevant locals. *)
('ex, 'en) block
(** Concurrent block. All the await expressions are awaited at the
* same time, similar to genva().
*
* We store the desugared form. In the below example, the list is:
* [('__tmp$1', f()), (__tmp$2, g()), (None, h())]
* and the block assigns the temporary variables back to the locals.
* { $foo = __tmp$1; $bar = __tmp$2; }
*
* concurrent {
* $foo = await f();
* $bar = await g();
* await h();
* } *)
| If of ('ex, 'en) expr * ('ex, 'en) block * ('ex, 'en) block
(** If statement.
*
* if ($foo) { ... } else { ... } *)
| Do of ('ex, 'en) block * ('ex, 'en) expr
(** Do-while loop.
*
* do {
* bar();
* } while($foo) *)
| While of ('ex, 'en) expr * ('ex, 'en) block
(** While loop.
*
* while ($foo) {
* bar();
* } *)
| Using of ('ex, 'en) using_stmt
(** Initialize a value that is automatically disposed of.
*
* using $foo = bar(); // disposed at the end of the function
* using ($foo = bar(), $baz = quux()) {} // disposed after the block *)
| For of
('ex, 'en) expr list
* ('ex, 'en) expr option
* ('ex, 'en) expr list
* ('ex, 'en) block
(** For loop. The initializer and increment parts can include
* multiple comma-separated statements. The termination condition is
* optional.
*
* for ($i = 0; $i < 100; $i++) { ... }
* for ($x = 0, $y = 0; ; $x++, $y++) { ... } *)
| Switch of
('ex, 'en) expr * ('ex, 'en) case list * ('ex, 'en) default_case option
(** Switch statement.
*
* switch ($foo) {
* case X:
* bar();
* break;
* default:
* baz();
* break;
* } *)
| Match of ('ex, 'en) stmt_match
(** Match statement.
*
* match ($x) {
* _: FooClass => {
* foo($x);
* }
* _ => {
* bar();
* }
* } *)
| Foreach of ('ex, 'en) expr * ('ex, 'en) as_expr * ('ex, 'en) block
(** For-each loop.
*
* foreach ($items as $item) { ... }
* foreach ($items as $key => value) { ... }
* foreach ($items await as $item) { ... } // AsyncIterator<_>
* foreach ($items await as $key => value) { ... } // AsyncKeyedIterator<_> *)
| Try of ('ex, 'en) block * ('ex, 'en) catch list * ('ex, 'en) finally_block
(** Try statement, with catch blocks and a finally block.
*
* try {
* foo();
* } catch (SomeException $e) {
* bar();
* } finally {
* baz();
* } *)
| Noop
(** No-op, the empty statement.
*
* {}
* while (true) ;
* if ($foo) {} // the else is Noop here *)
| Declare_local of lid * hint * ('ex, 'en) expr option
(** Declare a local variable with the given type and optional initial value *)
| Block of ('ex, 'en) block
(** Block, a list of statements in curly braces.
*
* { $foo = 42; } *)
| Markup of pstring
[@transform.opaque]
(** The mode tag at the beginning of a file.
* TODO: this really belongs in def.
*
* <?hh *)
| AssertEnv of env_annot * ((pos * 'ex) local_id_map[@map.opaque])
[@transform.opaque]
(** Used in IFC to track type inference environments. Not user
* denotable. *)
and env_annot =
| Join
| Refinement
[@@transform.opaque]
and ('ex, 'en) using_stmt = {
us_is_block_scoped: bool;
us_has_await: bool;
us_exprs: (pos[@transform.opaque]) * ('ex, 'en) expr list;
us_block: ('ex, 'en) block;
}
and ('ex, 'en) as_expr =
| As_v of ('ex, 'en) expr
| As_kv of ('ex, 'en) expr * ('ex, 'en) expr
| Await_as_v of (pos[@transform.opaque]) * ('ex, 'en) expr
| Await_as_kv of (pos[@transform.opaque]) * ('ex, 'en) expr * ('ex, 'en) expr
and ('ex, 'en) block = ('ex, 'en) stmt list
and ('ex, 'en) finally_block = ('ex, 'en) stmt list
and ('ex, 'en) stmt_match = {
sm_expr: ('ex, 'en) expr;
sm_arms: ('ex, 'en) stmt_match_arm list;
}
and ('ex, 'en) stmt_match_arm = {
sma_pat: pattern;
sma_body: ('ex, 'en) block;
}
and pattern =
| PVar of pat_var
(** Variable patterns *)
| PRefinement of pat_refinement
(** Refinement patterns *)
and pat_var = {
pv_pos: pos; [@transform.opaque]
pv_id: lid option;
}
and pat_refinement = {
pr_pos: pos; [@transform.opaque]
pr_id: lid option;
pr_hint: hint;
}
and ('ex, 'en) class_id = 'ex * (pos[@transform.opaque]) * ('ex, 'en) class_id_
(** Class ID, used in things like instantiation and static property access. *)
and ('ex, 'en) class_id_ =
| CIparent
(** The class ID of the parent of the lexically scoped class.
*
* In a trait, it is the parent class ID of the using class.
*
* parent::some_meth()
* parent::$prop = 1;
* new parent(); *)
| CIself
(** The class ID of the lexically scoped class.
*
* In a trait, it is the class ID of the using class.
*
* self::some_meth()
* self::$prop = 1;
* new self(); *)
| CIstatic
(** The class ID of the late static bound class.
*
* https://www.php.net/manual/en/language.oop5.late-static-bindings.php
*
* In a trait, it is the late static bound class ID of the using class.
*
* static::some_meth()
* static::$prop = 1;
* new static(); *)
| CIexpr of ('ex, 'en) expr
(** Dynamic class name.
*
* TODO: Syntactically this can only be an Lvar/This/Lplaceholder.
* We should use lid rather than expr.
*
* // Assume $d has type dynamic.
* $d::some_meth();
* $d::$prop = 1;
* new $d(); *)
| CI of class_name
(** Explicit class name. This is the common case.
*
* Foo::some_meth()
* Foo::$prop = 1;
* new Foo(); *)
and ('ex, 'en) expr = 'ex * (pos[@transform.opaque]) * ('ex, 'en) expr_
and 'ex collection_targ =
| CollectionTV of 'ex targ
| CollectionTKV of 'ex targ * 'ex targ
and ('ex, 'en) function_ptr_id =
| FP_id of sid
| FP_class_const of ('ex, 'en) class_id * (pstring[@transform.opaque])
(** An expression tree literal consists of a hint, splices, and
* expressions. Consider this example:
*
* Foo`1 + ${$x} + ${bar()}` *)
and ('ex, 'en) expression_tree = {
et_hint: hint;
(** The hint before the backtick, so Foo in this example. *)
et_splices: ('ex, 'en) stmt list;
(** The values spliced into expression tree at runtime are assigned
* to temporaries.
*
* $0tmp1 = $x; $0tmp2 = bar(); *)
et_function_pointers: ('ex, 'en) stmt list;
(** The list of global functions and static methods assigned to
* temporaries.
*
* $0fp1 = foo<>; *)
et_virtualized_expr: ('ex, 'en) expr;
(** The expression that gets type checked.
*
* 1 + $0tmp1 + $0tmp2 *)
et_runtime_expr: ('ex, 'en) expr;
(** The expression that's executed at runtime.
*
* Foo::makeTree($v ==> $v->visitBinOp(...)) *)
et_dollardollar_pos: pos option; [@transform.opaque]
(** Position of the first $$ in a splice that refers
* to a variable outside the Expression Tree
*
* $x |> Code`${ $$ }` // Pos of the $$
* Code`${ $x |> foo($$) }` // None *)
}
and ('ex, 'en) expr_ =
| Darray of
('ex targ * 'ex targ) option * (('ex, 'en) expr * ('ex, 'en) expr) list
(** darray literal.
*
* darray['x' => 0, 'y' => 1]
* darray<string, int>['x' => 0, 'y' => 1] *)
| Varray of 'ex targ option * ('ex, 'en) expr list
(** varray literal.
*
* varray['hello', 'world']
* varray<string>['hello', 'world'] *)
| Shape of
((Ast_defs.shape_field_name[@transform.opaque]) * ('ex, 'en) expr) list
(** Shape literal.
*
* shape('x' => 1, 'y' => 2)*)
| ValCollection of
((pos * vc_kind)[@transform.opaque])
* 'ex targ option
* ('ex, 'en) expr list
(** Collection literal for indexable structures.
*
* Vector {1, 2}
* ImmVector {}
* Set<string> {'foo', 'bar'}
* vec[1, 2]
* keyset[] *)
| KeyValCollection of
((pos * kvc_kind)[@transform.opaque])
* ('ex targ * 'ex targ) option
* ('ex, 'en) field list
(** Collection literal for key-value structures.
*
* dict['x' => 1, 'y' => 2]
* Map<int, string> {}
* ImmMap {} *)
| Null
(** Null literal.
*
* null *)
| This
(** The local variable representing the current class instance.
*
* $this *)
| True
(** Boolean literal.
*
* true *)
| False
(** Boolean literal.
*
* false *)
| Omitted
(** The empty expression.
*
* list(, $y) = vec[1, 2] // Omitted is the first expression inside list() *)
| Invalid of ('ex, 'en) expr option
(** Invalid expression marker generated during elaboration / validation phases
*
* class MyFoo {
* const int BAR = calls_are_invalid_here();
* }
*)
| Id of sid
(** An identifier. Used for method names and global constants.
*
* SOME_CONST
* $x->foo() // id: "foo" *)
| Lvar of lid
(** Local variable.
*
* $foo *)
| Dollardollar of lid
(** The extra variable in a pipe expression.
*
* $$ *)
| Clone of ('ex, 'en) expr
(** Clone expression.
*
* clone $foo *)
| Array_get of ('ex, 'en) expr * ('ex, 'en) expr option
(** Array indexing.
*
* $foo[]
* $foo[$bar] *)
| Obj_get of
('ex, 'en) expr
* ('ex, 'en) expr
* (og_null_flavor[@transform.opaque])
* (prop_or_method[@transform.opaque])
(** Instance property or method access.
*
* $foo->bar // OG_nullthrows, Is_prop: access named property
* ($foo->bar)() // OG_nullthrows, Is_prop: call lambda stored in named property
* $foo?->bar // OG_nullsafe, Is_prop
* ($foo?->bar)() // OG_nullsafe, Is_prop
*
* $foo->bar() // OG_nullthrows, Is_method: call named method
* $foo->$bar() // OG_nullthrows, Is_method: dynamic call, method name stored in local $bar
* $foo?->bar() // OG_nullsafe, Is_method
* $foo?->$bar() // OG_nullsafe, Is_method
*
* prop_or_method is:
* - Is_prop for property access
* - Is_method for method call, only possible when the node is the receiver in a Call node.
*
*)
| Class_get of
('ex, 'en) class_id
* ('ex, 'en) class_get_expr
* (prop_or_method[@transform.opaque])
(** Static property or dynamic method access. The rhs of the :: begins
* with $ or is some non-name expression appearing within braces {}.
*
* Foo::$bar // Is_prop: access named static property
* Foo::{$bar} // Is_prop
* (Foo::$bar)(); // Is_prop: call lambda stored in static property Foo::$bar
* $classname::$bar // Is_prop
*
* Foo::$bar(); // Is_method: dynamic call, method name stored in local $bar
* Foo::{$bar}(); // Is_method
*)
| Class_const of ('ex, 'en) class_id * (pstring[@transform.opaque])
(** Class constant or static method call. As a standalone expression,
* this is a class constant. Inside a Call node, this is a static
* method call. The rhs of the :: does not begin with $ or is a name
* appearing within braces {}.
*
* This is not ambiguous, because constants are not allowed to
* contain functions.
*
* Foo::some_const // Const
* Foo::{another_const} // Const: braces are elided
* Foo::class // Const: fully qualified class name of Foo
* Foo::staticMeth() // Call
* $classname::staticMeth() // Call
*
* This syntax is used for both static and instance methods when
* calling the implementation on the superclass.
*
* parent::someStaticMeth()
* parent::someInstanceMeth()
*)
| Call of ('ex, 'en) call_expr
(** Function or method call.
*
* foo()
* $x()
* foo<int>(1, 2, ...$rest)
* $x->foo()
* bar(inout $x);
* foobar(inout $x[0])
*
* async { return 1; }
* // lowered to:
* (async () ==> { return 1; })() *)
| FunctionPointer of ('ex, 'en) function_ptr_id * 'ex targ list
(** A reference to a function or method.
*
* foo_fun<>
* FooCls::meth<int> *)
| Int of string
(** Integer literal.
*
* 42
* 0123 // octal
* 0xBEEF // hexadecimal
* 0b11111111 // binary *)
| Float of string
(** Float literal.
*
* 1.0
* 1.2e3
* 7E-10 *)
| String of byte_string
[@transform.opaque]
(** String literal.
*
* "foo"
* 'foo'
*
* <<<DOC
* foo
* DOC
*
* <<<'DOC'
* foo
* DOC *)
| String2 of ('ex, 'en) expr list
(** Interpolated string literal.
*
* "hello $foo $bar"
*
* <<<DOC
* hello $foo $bar
* DOC *)
| PrefixedString of string * ('ex, 'en) expr
(** Prefixed string literal. Only used for regular expressions.
*
* re"foo" *)
| Yield of ('ex, 'en) afield
(** Yield expression. The enclosing function should have an Iterator
* return type.
*
* yield $foo // enclosing function returns an Iterator
* yield $foo => $bar // enclosing function returns a KeyedIterator *)
| Await of ('ex, 'en) expr
(** Await expression.
*
* await $foo *)
| ReadonlyExpr of ('ex, 'en) expr
(** Readonly expression.
*
* readonly $foo *)
| Tuple of ('ex, 'en) expr list
(** Tuple expression.
*
* tuple("a", 1, $foo) *)
| List of ('ex, 'en) expr list
(** List expression, only used in destructuring. Allows any arbitrary
* lvalue as a subexpression. May also nest.
*
* list($x, $y) = vec[1, 2];
* list(, $y) = vec[1, 2]; // skipping items
* list(list($x)) = vec[vec[1]]; // nesting
* list($v[0], $x[], $y->foo) = $blah; *)
| Cast of hint * ('ex, 'en) expr
(** Cast expression, converting a value to a different type. Only
* primitive types are supported in the hint position.
*
* (int)$foo
* (string)$foo *)
| Unop of (Ast_defs.uop[@transform.opaque]) * ('ex, 'en) expr
(** Unary operator.
*
* !$foo
* -$foo
* +$foo
* $foo++ *)
| Binop of ('ex, 'en) binop
(** Binary operator.
*
* $foo + $bar *)
| Pipe of lid * ('ex, 'en) expr * ('ex, 'en) expr
(** Pipe expression. The lid is the ID of the $$ that is implicitly
* declared by this pipe.
*
* See also Dollardollar.
*
* foo() |> bar(1, $$) // equivalent: bar(1, foo())
*
* $$ is not required on the RHS of pipe expressions, but it's
* pretty pointless to use pipes without $$.
*
* foo() |> bar(); // equivalent: foo(); bar(); *)
| Eif of ('ex, 'en) expr * ('ex, 'en) expr option * ('ex, 'en) expr
(** Ternary operator, or elvis operator.
*
* $foo ? $bar : $baz // ternary
* $foo ?: $baz // elvis *)
| Is of ('ex, 'en) expr * hint
(** Is operator.
*
* $foo is SomeType *)
| As of ('ex, 'en) expr * hint * (* is nullable *) bool
(** As operator.
*
* $foo as int
* $foo ?as int *)
| Upcast of ('ex, 'en) expr * hint
(** Upcast operator.
*
* $foo : int *)
| New of
('ex, 'en) class_id
* 'ex targ list
* ('ex, 'en) expr list
* ('ex, 'en) expr option
* (* constructor *)
'ex
(** Instantiation.
*
* new Foo(1, 2);
* new Foo<int, T>();
* new Foo('blah', ...$rest); *)
| Efun of ('ex, 'en) efun
(** PHP-style lambda. Does not capture variables unless explicitly
* specified.
*
* Mnemonic: 'expanded lambda', since we can desugar Lfun to Efun.
*
* function($x) { return $x; }
* function(int $x): int { return $x; }
* function($x) use ($y) { return $y; }
* function($x): int use ($y, $z) { return $x + $y + $z; } *)
| Lfun of ('ex, 'en) fun_ * 'ex capture_lid list
(** Hack lambda. Captures variables automatically.
*
* $x ==> $x
* (int $x): int ==> $x + $other
* ($x, $y) ==> { return $x + $y; } *)
| Xml of
(class_name[@transform.opaque])
* ('ex, 'en) xhp_attribute list
* ('ex, 'en) expr list
(** XHP expression. May contain interpolated expressions.
*
* <foo x="hello" y={$foo}>hello {$bar}</foo> *)
| Import of (import_flavor[@transform.opaque]) * ('ex, 'en) expr
(** Include or require expression.
*
* require('foo.php')
* require_once('foo.php')
* include('foo.php')
* include_once('foo.php') *)
| Collection of
(class_name[@transform.opaque])
* 'ex collection_targ option
* ('ex, 'en) afield list
(** Collection literal.
*
* TODO: T38184446 this is redundant with ValCollection/KeyValCollection.
*
* Vector {} *)
| ExpressionTree of ('ex, 'en) expression_tree
(** Expression tree literal. Expression trees are not evaluated at
* runtime, but desugared to an expression representing the code.
*
* Foo`1 + bar()`
* Foo`(() ==> { while(true) {} })()` // not an infinite loop at runtime
*
* Splices are evaluated as normal Hack code. The following two expression trees
* are equivalent. See also `ET_Splice`.
*
* Foo`1 + ${do_stuff()}`
*
* $x = do_stuff();
* Foo`1 + ${$x}` *)
| Lplaceholder of pos
[@transform.opaque]
(** Placeholder local variable.
*
* $_ *)
| Method_caller of class_name * (pstring[@transform.opaque])
(** Instance method reference that can be called with an instance.
*
* meth_caller(FooClass::class, 'some_meth')
* meth_caller('FooClass', 'some_meth')
*
* These examples are equivalent to:
*
* (FooClass $f, ...$args) ==> $f->some_meth(...$args) *)
| Pair of ('ex targ * 'ex targ) option * ('ex, 'en) expr * ('ex, 'en) expr
(** Pair literal.
*
* Pair {$foo, $bar} *)
| ET_Splice of ('ex, 'en) expr
(** Expression tree splice expression. Only valid inside an
* expression tree literal (backticks). See also `ExpressionTree`.
*
* ${$foo} *)
| EnumClassLabel of class_name option * string
(** Label used for enum classes.
*
* enum_name#label_name or #label_name *)
| Hole of ('ex, 'en) expr * 'ex * 'ex * hole_source
(** Annotation used to record failure in subtyping or coercion of an
* expression and calls to [unsafe_cast] or [enforced_cast].
*
* The [hole_source] indicates whether this came from an
* explicit call to [unsafe_cast] or [enforced_cast] or was
* generated during typing.
*
* Given a call to [unsafe_cast]:
* ```
* function f(int $x): void { /* ... */ }
*
* function g(float $x): void {
* f(unsafe_cast<float,int>($x));
* }
* ```
* After typing, this is represented by the following TAST fragment
* ```
* Call
* ( ( (..., function(int $x): void), Id (..., "\f"))
* , []
* , [ ( (..., int)
* , Hole
* ( ((..., float), Lvar (..., $x))
* , float
* , int
* , UnsafeCast
* )
* )
* ]
* , None
* )
* ```
*)
| Package of sid
(** Expression used to check whether a package exists.
*
* package package-name *)
and hole_source =
| Typing
| UnsafeCast of hint list
| UnsafeNonnullCast
| EnforcedCast of hint list
and ('ex, 'en) binop = {
bop: Ast_defs.bop; [@transform.opaque]
lhs: ('ex, 'en) expr; [@transform.explicit]
rhs: ('ex, 'en) expr; [@transform.explicit]
}
and ('ex, 'en) class_get_expr =
| CGstring of (pstring[@transform.opaque])
| CGexpr of ('ex, 'en) expr
and ('ex, 'en) case = ('ex, 'en) expr * ('ex, 'en) block
and ('ex, 'en) default_case = (pos[@transform.opaque]) * ('ex, 'en) block
and ('ex, 'en) gen_case =
| Case of ('ex, 'en) case
| Default of ('ex, 'en) default_case
and ('ex, 'en) catch = class_name * lid * ('ex, 'en) block
and ('ex, 'en) field = ('ex, 'en) expr * ('ex, 'en) expr
and ('ex, 'en) afield =
| AFvalue of ('ex, 'en) expr
| AFkvalue of ('ex, 'en) expr * ('ex, 'en) expr
and ('ex, 'en) xhp_simple = {
xs_name: pstring; [@transform.opaque]
xs_type: 'ex;
xs_expr: ('ex, 'en) expr;
}
and ('ex, 'en) xhp_attribute =
| Xhp_simple of ('ex, 'en) xhp_simple
| Xhp_spread of ('ex, 'en) expr
and is_variadic = bool [@@transform.opaque]
and ('ex, 'en) fun_param = {
param_annotation: 'ex;
param_type_hint: 'ex type_hint;
param_is_variadic: is_variadic;
param_pos: pos; [@transform.opaque]
param_name: string;
param_expr: ('ex, 'en) expr option;
param_readonly: Ast_defs.readonly_kind option; [@transform.opaque]
param_callconv: Ast_defs.param_kind; [@transform.opaque]
param_user_attributes: ('ex, 'en) user_attributes;
param_visibility: visibility option; [@transform.opaque]
}
and ('ex, 'en) fun_ = {
f_span: pos; [@transform.opaque]
f_readonly_this: Ast_defs.readonly_kind option; [@transform.opaque]
f_annotation: 'en;
f_readonly_ret: Ast_defs.readonly_kind option; [@transform.opaque]
(** Whether the return value is readonly *)
f_ret: 'ex type_hint; [@transform.explicit]
f_params: ('ex, 'en) fun_param list;
f_ctxs: contexts option;
f_unsafe_ctxs: contexts option;
f_body: ('ex, 'en) func_body;
f_fun_kind: Ast_defs.fun_kind; [@transform.opaque]
f_user_attributes: ('ex, 'en) user_attributes;
f_external: bool;
(** true if this declaration has no body because it is an
* external function declaration (e.g. from an HHI file) *)
f_doc_comment: doc_comment option;
}
and 'ex capture_lid = 'ex * lid
and ('ex, 'en) efun = {
ef_fun: ('ex, 'en) fun_;
ef_use: 'ex capture_lid list;
ef_closure_class_name: string option;
}
(**
* Naming has two phases and the annotation helps to indicate the phase.
* In the first pass, it will perform naming on everything except for function
* and method bodies and collect information needed. Then, another round of
* naming is performed where function bodies are named.
*)
and ('ex, 'en) func_body = { fb_ast: ('ex, 'en) block }
(** A type annotation is two things:
* - the localized hint, or if the hint is missing, the inferred type
* - The typehint associated to this expression if it exists *)
and 'ex type_hint = 'ex * type_hint_
(** Explicit type argument to function, constructor, or collection literal.
* 'ex = unit in NAST
* 'ex = Typing_defs.(locl ty) in TAST,
* and is used to record inferred type arguments, with wildcard hint.
*)
and 'ex targ = 'ex * hint
and type_hint_ = hint option
and ('ex, 'en) call_expr = {
func: ('ex, 'en) expr;
(** function *)
targs: 'ex targ list;
(** explicit type annotations *)
args: ((Ast_defs.param_kind[@transform.opaque]) * ('ex, 'en) expr) list;
(** positional args, plus their calling convention *)
unpacked_arg: ('ex, 'en) expr option;
(** unpacked arg *)
}
and ('ex, 'en) user_attribute = {
ua_name: sid;
ua_params: ('ex, 'en) expr list;
(** user attributes are restricted to scalar values *)
}
and ('ex, 'en) file_attribute = {
fa_user_attributes: ('ex, 'en) user_attributes;
fa_namespace: nsenv;
}
and ('ex, 'en) tparam = {
tp_variance: Ast_defs.variance; [@transform.opaque]
tp_name: sid;
tp_parameters: ('ex, 'en) tparam list;
tp_constraints: ((Ast_defs.constraint_kind[@transform.opaque]) * hint) list;
tp_reified: reify_kind; [@transform.opaque]
tp_user_attributes: ('ex, 'en) user_attributes;
}
and require_kind =
| RequireExtends
| RequireImplements
| RequireClass
[@@transform.opaque]
and emit_id =
| Emit_id of int
(** For globally defined type, the ID used in the .main function. *)
| Anonymous
(** Closures are hoisted to classes, but they don't get an entry in .main. *)
[@@transform.opaque]
and ('ex, 'en) class_ = {
c_span: pos; [@transform.opaque]
c_annotation: 'en;
c_mode: FileInfo.mode; [@visitors.opaque] [@transform.opaque]
c_final: bool;
c_is_xhp: bool;
c_has_xhp_keyword: bool;
c_kind: Ast_defs.classish_kind; [@transform.opaque]
c_name: class_name;
c_tparams: ('ex, 'en) tparam list; [@transform.explicit]
(** The type parameters of a class A<T> (T is the parameter) *)
c_extends: class_hint list; [@transform.explicit]
c_uses: trait_hint list; [@transform.explicit]
c_xhp_attr_uses: xhp_attr_hint list; [@transform.explicit]
c_xhp_category: (pos * pstring list) option; [@transform.opaque]
c_reqs: class_req list; [@transform.explicit]
c_implements: class_hint list; [@transform.explicit]
c_where_constraints: where_constraint_hint list;
c_consts: ('ex, 'en) class_const list; [@transform.explicit]
c_typeconsts: ('ex, 'en) class_typeconst_def list;
c_vars: ('ex, 'en) class_var list;
c_methods: ('ex, 'en) method_ list;
c_xhp_children: ((pos[@transform.opaque]) * xhp_child) list;
c_xhp_attrs: ('ex, 'en) xhp_attr list; [@transform.explicit]
c_namespace: nsenv;
c_user_attributes: ('ex, 'en) user_attributes; [@transform.explicit]
c_file_attributes: ('ex, 'en) file_attribute list;
c_docs_url: string option;
c_enum: enum_ option;
c_doc_comment: doc_comment option;
c_emit_id: emit_id option;
c_internal: bool;
c_module: sid option;
}
and class_req = class_hint * require_kind
and class_hint = hint
and trait_hint = hint
and xhp_attr_hint = hint
and xhp_attr_tag =
| Required
| LateInit
[@@transform.opaque]
and ('ex, 'en) xhp_attr =
'ex type_hint
* ('ex, 'en) class_var
* xhp_attr_tag option
* ((pos[@transform.opaque]) * ('ex, 'en) expr list) option
and ('ex, 'en) class_const_kind =
| CCAbstract of ('ex, 'en) expr option
(** CCAbstract represents the states
* abstract const int X;
* abstract const int Y = 4;
* The expr option is a default value
*)
| CCConcrete of ('ex, 'en) expr
(** CCConcrete represents
* const int Z = 4;
* The expr is the value of the constant. It is not optional
*)
and ('ex, 'en) class_const = {
cc_user_attributes: ('ex, 'en) user_attributes;
cc_type: hint option;
cc_id: sid;
cc_kind: ('ex, 'en) class_const_kind;
cc_span: pos; [@transform.opaque]
cc_doc_comment: doc_comment option;
}
(** This represents a type const definition. If a type const is abstract then
* then the type hint acts as a constraint. Any concrete definition of the
* type const must satisfy the constraint.
*
* If the type const is not abstract then a type must be specified.
*)
and class_abstract_typeconst = {
c_atc_as_constraint: hint option;
c_atc_super_constraint: hint option;
c_atc_default: hint option; [@transform.explicit]
}
and class_concrete_typeconst = { c_tc_type: hint }
and class_typeconst =
| TCAbstract of class_abstract_typeconst
| TCConcrete of class_concrete_typeconst
and ('ex, 'en) class_typeconst_def = {
c_tconst_user_attributes: ('ex, 'en) user_attributes;
c_tconst_name: sid;
c_tconst_kind: class_typeconst;
c_tconst_span: pos; [@transform.opaque]
c_tconst_doc_comment: doc_comment option;
c_tconst_is_ctx: bool;
}
and xhp_attr_info = {
xai_like: pos option; [@transform.opaque]
xai_tag: xhp_attr_tag option;
xai_enum_values: Ast_defs.xhp_enum_value list; [@transform.opaque]
}
and ('ex, 'en) class_var = {
cv_final: bool;
cv_xhp_attr: xhp_attr_info option;
cv_abstract: bool;
cv_readonly: bool;
cv_visibility: visibility; [@transform.opaque]
cv_type: 'ex type_hint; [@transform.explicit]
cv_id: sid;
cv_expr: ('ex, 'en) expr option;
cv_user_attributes: ('ex, 'en) user_attributes;
cv_doc_comment: doc_comment option;
cv_is_promoted_variadic: bool;
cv_is_static: bool;
cv_span: pos; [@transform.opaque]
}
and ('ex, 'en) method_ = {
m_span: pos; [@transform.opaque]
m_annotation: 'en;
m_final: bool;
m_abstract: bool;
m_static: bool;
m_readonly_this: bool;
m_visibility: visibility; [@transform.opaque]
m_name: sid;
m_tparams: ('ex, 'en) tparam list;
m_where_constraints: where_constraint_hint list;
m_params: ('ex, 'en) fun_param list;
m_ctxs: contexts option;
m_unsafe_ctxs: contexts option;
m_body: ('ex, 'en) func_body;
m_fun_kind: Ast_defs.fun_kind; [@transform.opaque]
m_user_attributes: ('ex, 'en) user_attributes;
m_readonly_ret: Ast_defs.readonly_kind option; [@transform.opaque]
m_ret: 'ex type_hint; [@transform.explicit]
m_external: bool;
(** true if this declaration has no body because it is an external method
* declaration (e.g. from an HHI file) *)
m_doc_comment: doc_comment option;
}
and nsenv = (Namespace_env.env[@visitors.opaque]) [@@transform.opaque]
and ('ex, 'en) typedef = {
t_annotation: 'en;
t_name: sid;
t_tparams: ('ex, 'en) tparam list;
t_as_constraint: hint option;
t_super_constraint: hint option;
t_kind: hint; [@transform.explicit]
t_user_attributes: ('ex, 'en) user_attributes;
t_file_attributes: ('ex, 'en) file_attribute list;
t_mode: FileInfo.mode; [@visitors.opaque] [@transform.opaque]
t_vis: typedef_visibility; [@transform.opaque]
t_namespace: nsenv;
t_span: pos; [@transform.opaque]
t_emit_id: emit_id option;
t_is_ctx: bool;
t_internal: bool;
t_module: sid option;
t_docs_url: string option;
t_doc_comment: doc_comment option;
}
and ('ex, 'en) gconst = {
cst_annotation: 'en;
cst_mode: FileInfo.mode; [@visitors.opaque] [@transform.opaque]
cst_name: sid;
cst_type: hint option;
cst_value: ('ex, 'en) expr; [@transform.explicit]
cst_namespace: nsenv;
cst_span: pos; [@transform.opaque]
cst_emit_id: emit_id option;
}
and ('ex, 'en) fun_def = {
fd_namespace: nsenv;
fd_file_attributes: ('ex, 'en) file_attribute list;
fd_mode: FileInfo.mode; [@visitors.opaque] [@transform.opaque]
fd_name: sid;
fd_fun: ('ex, 'en) fun_;
fd_internal: bool;
fd_module: sid option;
fd_tparams: ('ex, 'en) tparam list;
fd_where_constraints: where_constraint_hint list;
}
and ('ex, 'en) module_def = {
md_annotation: 'en;
md_name: Ast_defs.id; [@transform.opaque]
md_user_attributes: ('ex, 'en) user_attributes;
md_file_attributes: ('ex, 'en) file_attribute list;
md_span: pos; [@transform.opaque]
md_mode: FileInfo.mode; [@visitors.opaque] [@transform.opaque]
md_doc_comment: doc_comment option;
md_exports: md_name_kind list option;
md_imports: md_name_kind list option;
}
and md_name_kind =
| MDNameGlobal of pos
| MDNamePrefix of sid
| MDNameExact of sid
[@@transform.opaque]
and ('ex, 'en) def =
| Fun of ('ex, 'en) fun_def
| Class of ('ex, 'en) class_
| Stmt of ('ex, 'en) stmt
| Typedef of ('ex, 'en) typedef
| Constant of ('ex, 'en) gconst
| Namespace of sid * ('ex, 'en) def list
| NamespaceUse of (ns_kind * sid * sid) list
| SetNamespaceEnv of nsenv
| FileAttributes of ('ex, 'en) file_attribute
| Module of ('ex, 'en) module_def
| SetModule of sid
and ns_kind =
| NSNamespace
| NSClass
| NSClassAndNamespace
| NSFun
| NSConst
[@@transform.opaque]
and doc_comment = (Ast_defs.pstring[@visitors.opaque]) [@@transform.opaque]
and import_flavor =
| Include
| Require
| IncludeOnce
| RequireOnce
[@@transform.opaque]
and xhp_child =
| ChildName of sid
| ChildList of xhp_child list
| ChildUnary of xhp_child * xhp_child_op
| ChildBinary of xhp_child * xhp_child
and xhp_child_op =
| ChildStar
| ChildPlus
| ChildQuestion
[@@transform.opaque]
and hint = (pos[@transform.opaque]) * hint_
and variadic_hint = hint option
and ('ex, 'en) user_attributes = ('ex, 'en) user_attribute list
and contexts = (pos[@transform.opaque]) * context list
and context = hint
and hf_param_info = {
hfparam_kind: Ast_defs.param_kind;
hfparam_readonlyness: Ast_defs.readonly_kind option;
}
[@@transform.opaque]
and hint_fun = {
hf_is_readonly: Ast_defs.readonly_kind option; [@transform.opaque]
hf_param_tys: hint list;
(* hf_param_info is None when all three are none, for perf optimization reasons.
It is not semantically incorrect for the record to appear with 3 None values,
but in practice we shouldn't lower to that, since it wastes CPU/space *)
hf_param_info: hf_param_info option list;
hf_variadic_ty: variadic_hint;
hf_ctxs: contexts option;
hf_return_ty: hint; [@transform.explicit]
hf_is_readonly_return: Ast_defs.readonly_kind option; [@transform.opaque]
}
and hint_ =
| Hoption of hint
| Hlike of hint
| Hfun of hint_fun
| Htuple of hint list
| Happly of class_name * hint list
| Hshape of nast_shape_info
| Haccess of hint * sid list
(** Accessing a type constant. Type constants are accessed like normal
* class constants, but in type positions.
*
* SomeClass::TFoo
* self::TFoo
* this::TFoo
*
* Type constants can be also be chained, hence the list as the second
* argument:
*
* SomeClass::TFoo::TBar // Haccess (Happly "SomeClass", ["TFoo", "TBar"])
*
* When using contexts, the receiver may be a variable rather than a
* specific type:
*
* function uses_const_ctx(SomeClassWithConstant $t)[$t::C]: void {}
*)
| Hsoft of hint
| Hrefinement of hint * refinement list
(* The following constructors don't exist in the AST hint type *)
| Hany
| Herr
| Hmixed
| Hwildcard
| Hnonnull
| Habstr of string * hint list
| Hvec_or_dict of hint option * hint
| Hprim of (tprim[@transform.opaque])
| Hthis
| Hdynamic
| Hnothing
| Hunion of hint list
| Hintersection of hint list
| Hfun_context of string
| Hvar of string
and refinement =
| Rctx of sid * ctx_refinement
| Rtype of sid * type_refinement
and type_refinement =
| TRexact of hint
| TRloose of type_refinement_bounds
and type_refinement_bounds = {
tr_lower: hint list;
tr_upper: hint list;
}
and ctx_refinement =
| CRexact of hint
| CRloose of ctx_refinement_bounds
and ctx_refinement_bounds = {
cr_lower: hint option;
cr_upper: hint option;
}
and shape_field_info = {
sfi_optional: bool;
sfi_hint: hint;
sfi_name: Ast_defs.shape_field_name; [@transform.opaque]
}
and nast_shape_info = {
nsi_allows_unknown_fields: bool;
nsi_field_map: shape_field_info list;
}
and kvc_kind =
| Map
| ImmMap
| Dict
[@@visitors.opaque] [@@transform.opaque]
and vc_kind =
| Vector
| ImmVector
| Vec
| Set
| ImmSet
| Keyset
[@@visitors.opaque] [@@transform.opaque]
and enum_ = {
e_base: hint;
e_constraint: hint option;
e_includes: hint list;
}
and where_constraint_hint =
hint * (Ast_defs.constraint_kind[@transform.opaque]) * hint
[@@deriving
show { with_path = false },
eq,
hash,
ord,
map,
transform ~restart:(`Disallow `Encode_as_result),
visitors
{
variety = "iter";
nude = true;
visit_prefix = "on_";
ancestors =
["Visitors_runtime.iter"; "Aast_defs_visitors_ancestors.iter"];
},
visitors
{
variety = "reduce";
nude = true;
visit_prefix = "on_";
ancestors =
["Visitors_runtime.reduce"; "Aast_defs_visitors_ancestors.reduce"];
},
visitors
{
variety = "map";
nude = true;
visit_prefix = "on_";
ancestors = ["Visitors_runtime.map"; "Aast_defs_visitors_ancestors.map"];
},
visitors
{
variety = "endo";
nude = true;
visit_prefix = "on_";
ancestors =
["Visitors_runtime.endo"; "Aast_defs_visitors_ancestors.endo"];
}]
let string_of_tprim prim =
match prim with
| Tnull -> "null"
| Tvoid -> "void"
| Tint -> "int"
| Tnum -> "num"
| Tfloat -> "float"
| Tstring -> "string"
| Tarraykey -> "arraykey"
| Tresource -> "resource"
| Tnoreturn -> "noreturn"
| Tbool -> "bool"
let string_of_visibility vis =
match vis with
| Private -> "private"
| Public -> "public"
| Protected -> "protected"
| Internal -> "internal"
let is_wildcard_hint h =
match h with
| (_, Hwildcard) -> true
| _ -> false |
OCaml | hhvm/hphp/hack/src/annotated_ast/aast_defs_visitors_ancestors.ml | (*
* Copyright (c) 2017, 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.
*
*)
module SM = Ast_defs.ShapeMap
module LM = Local_id.Map
class virtual ['self] iter =
object (_ : 'self)
inherit [_] Ast_defs.iter
method private on_local_id_map
: 'a. ('env -> 'a -> unit) -> 'env -> 'a LM.t -> unit =
(fun f env -> LM.iter (fun _ -> f env))
method on_'ex _ _ = ()
method on_'en _ _ = ()
end
class virtual ['self] reduce =
object (self : 'self)
inherit [_] Ast_defs.reduce
method private on_local_id_map
: 'a. ('env -> 'a -> 'acc) -> 'env -> 'a LM.t -> 'acc =
fun f env x ->
LM.fold (fun _ d acc -> self#plus acc (f env d)) x self#zero
method on_'ex _env _ = self#zero
method on_'en _env _ = self#zero
end
class virtual ['self] map =
object (_ : 'self)
inherit [_] Ast_defs.map
method private on_local_id_map
: 'a 'b. ('env -> 'a -> 'b) -> 'env -> 'a LM.t -> 'b LM.t =
(fun f env -> LM.map (f env))
end
class virtual ['self] endo =
object (_ : 'self)
inherit [_] Ast_defs.endo
method private on_local_id_map
: 'a 'b. ('env -> 'a -> 'b) -> 'env -> 'a LM.t -> 'b LM.t =
(fun f env -> LM.map (f env))
end |
OCaml | hhvm/hphp/hack/src/annotated_ast/aast_utils.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.
*
*)
let rec can_be_captured =
let open Aast_defs in
function
| Darray _
| Varray _
| Shape _
| ValCollection _
| KeyValCollection _
| Null
| This
| True
| False
| Omitted
| Id _
| Lvar _
| Dollardollar _
| Array_get _
| Obj_get _
| Class_get _
| Class_const _
| Call _
| FunctionPointer _
| Int _
| Float _
| String _
| String2 _
| PrefixedString _
| Tuple _
| List _
| Xml _
| Import _
| Lplaceholder _
| Method_caller _
| EnumClassLabel _
| Invalid None ->
false
| Yield _
| Clone _
| Await _
| ReadonlyExpr _
| Cast _
| Unop _
| Binop _
| Pipe _
| Eif _
| Is _
| As _
| Upcast _
| New _
| Efun _
| Lfun _
| Collection _
| ExpressionTree _
| Pair _
| ET_Splice _
| Package _ ->
true
| Invalid (Some (_, _, exp))
| Hole ((_, _, exp), _, _, _) ->
can_be_captured exp |
OCaml Interface | hhvm/hphp/hack/src/annotated_ast/aast_utils.mli | (*
* 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.
*
*)
(** Conservatively determines if an expression can be captured. This is useful
for deciding when to paranthesise an expression.
For example,
`identity(1 + 2) * 3` -> `1 + 2 * 3`
would be wrong because binary operations can be captured, but
`identity($foo->bar) * 3` -> `$foo->bar * 3`
is not wrong and cannot be wrong in any context because `$foo->bar` cannot
be captured.
*)
val can_be_captured : ('a, 'b) Aast_defs.expr_ -> bool |
hhvm/hphp/hack/src/annotated_ast/dune | (library
(name annotated_ast)
(modules aast aast_defs aast_defs_visitors_ancestors)
(wrapped false)
(libraries ast namespace_env)
(preprocess
(pps visitors.ppx ppx_transform ppx_deriving.std ppx_hash)))
(library
(name namespace_env)
(wrapped false)
(modules namespace_env)
(libraries collections core_kernel hh_autoimport parser_options)
(preprocess
(pps ppx_hash visitors.ppx ppx_deriving.std)))
(library
(name annotated_ast_utils)
(modules aast_utils)
(wrapped false)
(libraries annotated_ast)) |
|
OCaml | hhvm/hphp/hack/src/annotated_ast/namespace_env.ml | (*
* Copyright (c) 2015, 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
type env = {
ns_ns_uses: string SMap.t; [@opaque]
ns_class_uses: string SMap.t; [@opaque]
ns_fun_uses: string SMap.t; [@opaque]
ns_const_uses: string SMap.t; [@opaque]
ns_name: string option;
ns_is_codegen: bool;
ns_disable_xhp_element_mangling: bool;
}
[@@deriving eq, hash, show, ord]
let hh_autoimport_map_of_list ids =
List.map ids ~f:(fun id -> (id, "HH\\" ^ id)) |> SMap.of_list
let default_class_uses = hh_autoimport_map_of_list Hh_autoimport.types
let default_fun_uses = hh_autoimport_map_of_list Hh_autoimport.funcs
let default_const_uses = hh_autoimport_map_of_list Hh_autoimport.consts
let default_ns_uses = hh_autoimport_map_of_list Hh_autoimport.namespaces
let empty_with_default : env =
let popt = ParserOptions.default in
let auto_ns_map = ParserOptions.auto_namespace_map popt in
let ns_is_codegen = ParserOptions.codegen popt in
let ns_disable_xhp_element_mangling =
ParserOptions.disable_xhp_element_mangling popt
in
{
ns_ns_uses = SMap.union (SMap.of_list auto_ns_map) default_ns_uses;
ns_class_uses = default_class_uses;
ns_fun_uses = default_fun_uses;
ns_const_uses = default_const_uses;
ns_name = None;
ns_is_codegen;
ns_disable_xhp_element_mangling;
} |
OCaml Interface | hhvm/hphp/hack/src/annotated_ast/namespace_env.mli | (*
* 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.
*
*)
type env = {
ns_ns_uses: string SMap.t;
ns_class_uses: string SMap.t;
ns_fun_uses: string SMap.t;
ns_const_uses: string SMap.t;
ns_name: string option;
ns_is_codegen: bool;
ns_disable_xhp_element_mangling: bool;
}
[@@deriving eq, hash, show, ord]
val empty_with_default : env |
Rust | hhvm/hphp/hack/src/arena_collections/alist.rs | // 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.
//! Associative array types.
//!
//! At the moment, we are using the bumpalo allocator for arena allocation.
//! Because the stdlib types do not yet provide the ability to choose the
//! allocator used when they are allocated or resized, the bumpalo library
//! provides its own growable Vec and String types. Since bumpalo does not
//! provide its own map or set types, we must define our own if we want to
//! control where they are allocated.
//!
//! This module defines map types backed by bumpalo's Vec. It is useful for maps
//! which are built all at once, and never modified thereafter (e.g., maps in
//! ASTs). When immutable semantics are desired, but updating is necessary,
//! consider the `arena_collections::map` submodule instead, for an immutable
//! balanced binary tree. The Vec-backed maps in this module may benefit from
//! better cache efficiency, and so may outperform the balanced tree
//! implementation in some circumstances.
use std::borrow::Borrow;
use std::fmt::Debug;
use arena_trait::TrivialDrop;
use bumpalo::Bump;
use ocamlrep::FromOcamlRepIn;
use ocamlrep::ToOcamlRep;
use serde::Deserialize;
use serde::Serialize;
/// Perform a linear search for the last entry in the slice with the given key.
#[inline(always)]
fn get_last_entry<'a, K, V, Q: ?Sized>(entries: &'a [(K, V)], key: &Q) -> Option<&'a (K, V)>
where
K: Borrow<Q>,
Q: PartialEq,
{
entries.iter().rev().find(|(k, _)| key == k.borrow())
}
/// Perform a linear search for the last entry in the slice with the given key
/// and return its index in the slice.
#[inline(always)]
fn get_last_index<'a, K, V, Q: ?Sized>(entries: &'a [(K, V)], key: &Q) -> Option<usize>
where
K: Borrow<Q>,
Q: PartialEq,
{
entries
.iter()
.enumerate()
.rev()
.find(|(_, (k, _))| key == k.borrow())
.map(|(idx, _)| idx)
}
/// A readonly associative array.
///
/// * Lookups run in linear time
/// * Entries with duplicate keys are permitted (but only observable using iterators)
#[derive(Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct AssocList<'a, K, V> {
entries: &'a [(K, V)],
}
impl<'a, K, V> AssocList<'a, K, V> {
/// Make a new `AssocList` containing the given key-value pairs.
///
/// # Examples
///
/// ```
/// use arena_collections::AssocList;
///
/// let entries = [(1, "a")];
/// let alist = AssocList::new(&entries[..]);
/// ```
#[inline]
pub const fn new(entries: &'a [(K, V)]) -> Self {
Self { entries }
}
/// Returns a reference to the value corresponding to the key.
///
/// The key may be any borrowed form of the list's key type, but the
/// ordering on the borrowed form *must* match the ordering on the key type.
///
/// If multiple entries in the map have keys equal to the given key, the
/// value corresponding to the last entry (the one with the larger index in
/// the slice passed to `AssocList::new`) will be returned.
///
/// # Examples
///
/// ```
/// use arena_collections::AssocList;
///
/// let entries = [(1, "a")];
/// let alist = AssocList::new(&entries[..]);
/// assert_eq!(alist.get(&1), Some(&"a"));
/// assert_eq!(alist.get(&2), None);
/// ```
pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: PartialEq,
{
get_last_entry(self.entries, key).map(|(_, v)| v)
}
/// Returns the key-value pair corresponding to the supplied key.
///
/// The key may be any borrowed form of the list's key type, but the
/// ordering on the borrowed form *must* match the ordering on the key type.
///
/// If multiple entries in the map have keys equal to the given key, the
/// last entry (the one with the larger index in the slice passed to
/// `AssocList::new`) will be returned.
///
/// # Examples
///
/// ```
/// use arena_collections::AssocList;
///
/// let entries = [(1, "a")];
/// let alist = AssocList::new(&entries[..]);
/// assert_eq!(alist.get_key_value(&1), Some((&1, &"a")));
/// assert_eq!(alist.get_key_value(&2), None);
/// ```
pub fn get_key_value<Q: ?Sized>(&self, key: &Q) -> Option<(&K, &V)>
where
K: Borrow<Q>,
Q: PartialEq,
{
get_last_entry(self.entries, key).map(|(k, v)| (k, v))
}
/// Returns `true` if the list contains a value for the specified key.
///
/// The key may be any borrowed form of the list's key type, but the
/// ordering on the borrowed form *must* match the ordering on the key type.
///
/// # Examples
///
/// ```
/// use arena_collections::AssocList;
///
/// let entries = [(1, "a")];
/// let alist = AssocList::new(&entries[..]);
/// assert_eq!(alist.contains_key(&1), true);
/// assert_eq!(alist.contains_key(&2), false);
/// ```
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: PartialEq,
{
get_last_entry(self.entries, key).is_some()
}
/// Gets an iterator over the entries of the association list.
///
/// # Examples
///
/// ```
/// use arena_collections::AssocList;
///
/// let entries = [(1, "a"), (2, "b")];
/// let alist = AssocList::new(&entries[..]);
///
/// for (key, value) in alist.iter() {
/// println!("{}: {}", key, value);
/// }
///
/// let (first_key, first_value) = alist.iter().next().unwrap();
/// assert_eq!((*first_key, *first_value), (1, "a"));
/// ```
pub fn iter(&self) -> impl Iterator<Item = (&K, &V)> {
self.entries.iter().map(|(k, v)| (k, v))
}
/// Gets an iterator over the keys of the association list.
///
/// # Examples
///
/// ```
/// use arena_collections::AssocList;
///
/// let entries = [(1, "a"), (2, "b")];
/// let alist = AssocList::new(&entries[..]);
///
/// let keys: Vec<_> = alist.keys().copied().collect();
/// assert_eq!(keys, [1, 2]);
/// ```
pub fn keys(&self) -> impl Iterator<Item = &K> {
self.entries.iter().map(|(k, _)| k)
}
/// Gets an iterator over the values of the association list.
///
/// # Examples
///
/// ```
/// use arena_collections::AssocList;
///
/// let entries = [(1, "hello"), (2, "goodbye")];
/// let alist = AssocList::new(&entries[..]);
///
/// let values: Vec<&str> = alist.values().copied().collect();
/// assert_eq!(values, ["hello", "goodbye"]);
/// ```
pub fn values(&self) -> impl Iterator<Item = &V> {
self.entries.iter().map(|(_, v)| v)
}
/// Returns the number of entries in the list.
///
/// # Examples
///
/// ```
/// use arena_collections::AssocList;
///
/// let entries = [(1, "a")];
/// let alist = AssocList::new(&entries[0..entries]);
/// assert_eq!(alist.len(), 0);
/// let alist = AssocList::new(&entries[0..1]);
/// assert_eq!(alist.len(), 1);
/// ```
pub fn len(&self) -> usize {
self.entries.len()
}
/// Returns `true` if the list contains no entries.
///
/// # Examples
///
/// ```
/// use arena_collections::AssocList;
///
/// let entries = [(1, "a")];
/// let alist = AssocList::new(&entries[0..entries]);
/// assert!(alist.is_empty());
/// let alist = AssocList::new(&entries[0..1]);
/// assert!(!alist.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
impl<K, V> TrivialDrop for AssocList<'_, K, V> {}
impl<K, V> Copy for AssocList<'_, K, V> {}
impl<K, V> Clone for AssocList<'_, K, V> {
fn clone(&self) -> Self {
*self
}
}
impl<K: Debug, V: Debug> Debug for AssocList<'_, K, V> {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt.debug_map().entries(self.iter()).finish()
}
}
impl<'a, K, V> From<AssocListMut<'a, K, V>> for AssocList<'a, K, V> {
#[inline]
fn from(alist: AssocListMut<'a, K, V>) -> Self {
AssocList::new(alist.entries.into_bump_slice())
}
}
/// A mutable associative array, allocated in a given arena.
///
/// * Lookups, replacements, and removals run in linear time
/// * Insertions run in constant time
/// * Entries with duplicate keys are permitted (but only observable using iterators)
#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct AssocListMut<'bump, K, V> {
entries: bumpalo::collections::Vec<'bump, (K, V)>,
}
impl<'bump, K, V> AssocListMut<'bump, K, V> {
/// Constructs a new, empty `AssocListMut`.
///
/// The list will not allocate until entries are inserted.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::AssocListMut;
///
/// let b = Bump::new();
/// let mut alist: AssocListMut<i32> = AssocListMut::new_in(&b);
/// ```
#[inline]
pub fn new_in(bump: &'bump Bump) -> Self {
AssocListMut {
entries: bumpalo::collections::Vec::new_in(bump),
}
}
/// Constructs a new, empty `AssocListMut` with the specified capacity.
///
/// The list will be able to hold exactly `capacity` elements without
/// reallocating. If `capacity` is 0, the list will not allocate.
///
/// It is important to note that although the returned list has the
/// *capacity* specified, the list will have a zero *length*.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::AssocListMut;
///
/// let b = Bump::new();
///
/// let mut alist = AssocListMut::with_capacity_in(10, &b);
///
/// // The list contains no items, even though it has capacity for more
/// assert_eq!(alist.len(), 0);
///
/// // These are all done without reallocating...
/// for i in 0..10 {
/// alist.insert(i, i);
/// }
///
/// // ...but this may make the list reallocate
/// alist.insert(11, 11);
/// ```
#[inline]
pub fn with_capacity_in(capacity: usize, bump: &'bump Bump) -> Self {
AssocListMut {
entries: bumpalo::collections::Vec::with_capacity_in(capacity, bump),
}
}
/// Insert the given key-value pair into the association list.
///
/// If an entry with the given key already exists in the list, it will
/// remain there, but future calls to `AssocListMut::get` will return the
/// newly-inserted value instead of the extant one.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::AssocListMut;
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// alist.insert(1, "a");
/// assert_eq!(alist.get(&1), Some(&"a"));
/// alist.insert(1, "b");
/// assert_eq!(alist.get(&1), Some(&"b"));
/// assert_eq!(alist.len(), 2);
/// ```
#[inline]
pub fn insert(&mut self, key: K, value: V) {
self.entries.push((key, value))
}
/// Insert the given key-value pair into the association list.
///
/// If one entry with the given key already exists in the list, it will be
/// removed, and its value will be returned. If multiple entries with the
/// given key already exist in the list, only the most recently inserted one
/// will be removed.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::AssocListMut;
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// alist.insert_or_replace(1, "a");
/// assert_eq!(alist.get(&1), Some(&"a"));
/// alist.insert_or_replace(1, "b");
/// assert_eq!(alist.get(&1), Some(&"b"));
/// assert_eq!(alist.len(), 1);
/// ```
pub fn insert_or_replace(&mut self, key: K, value: V) -> Option<V>
where
K: PartialEq,
{
match get_last_index(&self.entries, &key) {
None => {
self.insert(key, value);
None
}
Some(idx) => {
let mut entry = (key, value);
std::mem::swap(&mut self.entries[idx], &mut entry);
Some(entry.1)
}
}
}
/// Remove a key from the list, returning the value at the key if the key
/// was previously in the list.
///
/// The key may be any borrowed form of the list's key type, but the
/// ordering on the borrowed form *must* match the ordering on the key type.
///
/// If multiple entries with the given key exist in the list, only the last
/// will be removed (the one which would b returned by
/// `AssocListMut::get`).
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::AssocListMut;
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// alist.insert(1, "a");
/// alist.insert(1, "b");
/// assert_eq!(alist.get(&1), Some(&"b"));
/// alist.remove(&1);
/// assert_eq!(alist.get(&1), Some(&"a"));
/// alist.remove(&1);
/// assert_eq!(alist.get(&1), None);
/// ```
pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
where
K: Borrow<Q>,
Q: PartialEq,
{
match get_last_index(&self.entries, key) {
None => None,
Some(idx) => Some(self.entries.remove(idx).1),
}
}
/// Removes all entries with the given key from the list. Returns true if
/// any entries were removed.
///
/// The key may be any borrowed form of the list's key type, but the
/// ordering on the borrowed form *must* match the ordering on the key type.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::AssocListMut;
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// alist.insert(1, "a");
/// alist.insert(1, "b");
/// assert_eq!(alist.get(&1), Some(&"b"));
/// alist.remove_all(&1);
/// assert_eq!(alist.get(&1), None);
/// ```
pub fn remove_all<Q: ?Sized>(&mut self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: PartialEq,
{
let len_before = self.len();
self.entries.retain(|(k, _)| key != k.borrow());
let len_after = self.len();
len_before != len_after
}
/// Returns a reference to the value corresponding to the key.
///
/// The key may be any borrowed form of the list's key type, but the
/// ordering on the borrowed form *must* match the ordering on the key type.
///
/// If multiple entries in the map have keys equal to the given key, the
/// value in the most recently inserted entry will be returned.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::AssocListMut;
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// alist.insert(1, "a");
/// assert_eq!(alist.get(&1), Some(&"a"));
/// assert_eq!(alist.get(&2), None);
/// ```
pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: PartialEq,
{
get_last_entry(&self.entries, key).map(|(_, v)| v)
}
/// Returns the key-value pair corresponding to the supplied key.
///
/// The key may be any borrowed form of the list's key type, but the
/// ordering on the borrowed form *must* match the ordering on the key type.
///
/// If multiple entries in the map have keys equal to the given key, the
/// most recently inserted entry will be returned.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::AssocListMut;
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// alist.insert(1, "a");
/// assert_eq!(alist.get_key_value(&1), Some((&1, &"a")));
/// assert_eq!(alist.get_key_value(&2), None);
/// ```
pub fn get_key_value<Q: ?Sized>(&self, key: &Q) -> Option<(&K, &V)>
where
K: Borrow<Q>,
Q: PartialEq,
{
get_last_entry(&self.entries, key).map(|(k, v)| (k, v))
}
/// Returns `true` if the list contains a value for the specified key.
///
/// The key may be any borrowed form of the list's key type, but the
/// ordering on the borrowed form *must* match the ordering on the key type.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::AssocListMut;
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// alist.insert(1, "a");
/// assert_eq!(alist.contains_key(&1), true);
/// assert_eq!(alist.contains_key(&2), false);
/// ```
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: PartialEq,
{
self.get(key).is_some()
}
/// Gets an iterator over the entries of the association list.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::AssocListMut;
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// alist.insert(1, "a");
/// alist.insert(2, "b");
///
/// for (key, value) in alist.iter() {
/// println!("{}: {}", key, value);
/// }
///
/// let (first_key, first_value) = alist.iter().next().unwrap();
/// assert_eq!((*first_key, *first_value), (1, "a"));
/// ```
pub fn iter(&self) -> impl Iterator<Item = (&K, &V)> {
self.entries.iter().map(|(k, v)| (k, v))
}
/// Gets an iterator over the keys of the association list.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::AssocListMut;
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// alist.insert(1, "a");
/// alist.insert(2, "b");
///
/// let keys: Vec<_> = alist.keys().copied().collect();
/// assert_eq!(keys, [1, 2]);
/// ```
pub fn keys(&self) -> impl Iterator<Item = &K> {
self.entries.iter().map(|(k, _)| k)
}
/// Gets an iterator over the values of the association list.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::AssocListMut;
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// alist.insert(1, "hello");
/// alist.insert(2, "goodbye");
///
/// let values: Vec<&str> = alist.values().copied().collect();
/// assert_eq!(values, ["hello", "goodbye"]);
/// ```
pub fn values(&self) -> impl Iterator<Item = &V> {
self.entries.iter().map(|(_, v)| v)
}
/// Returns the number of entries in the list.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::AssocListMut;
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// assert_eq!(alist.len(), 0);
/// alist.insert(1, "a");
/// assert_eq!(alist.len(), 1);
/// ```
pub fn len(&self) -> usize {
self.entries.len()
}
/// Returns `true` if the list contains no entries.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::AssocListMut;
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// assert!(alist.is_empty());
/// alist.insert(1, "a");
/// assert!(!alist.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
impl<K: Debug, V: Debug> Debug for AssocListMut<'_, K, V> {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt.debug_map().entries(self.iter()).finish()
}
}
/// Get an entry in the slice with the given key. Performs a linear search on
/// small slices, and a binary search otherwise.
#[inline(always)]
fn get_sorted_entry<'a, K, V, Q: ?Sized>(entries: &'a [(K, V)], key: &Q) -> Option<&'a (K, V)>
where
K: Borrow<Q>,
Q: Ord,
{
// TODO: tune this threshold based on perf results
const BINARY_SEARCH_LEN_THRESHOLD: usize = 32;
if entries.len() < BINARY_SEARCH_LEN_THRESHOLD {
entries.iter().find(|(k, _)| key == k.borrow())
} else {
let index = entries
.binary_search_by(|(k, _)| k.borrow().cmp(key))
.ok()?;
Some(&entries[index])
}
}
/// A readonly associative array, sorted by key, containing no duplicate keys.
///
/// * Lookups run in log(n) time
/// * Entries with duplicate keys are not permitted. When constructing a
/// `SortedAssocList` from an `AssocListMut`, entries will be deduplicated by
/// key, and only the most recently inserted entry for each key will be
/// retained.
#[derive(Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(bound(
deserialize = "K: 'de + arena_deserializer::DeserializeInArena<'de>, V: 'de + arena_deserializer::DeserializeInArena<'de>"
))]
pub struct SortedAssocList<'a, K, V> {
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
entries: &'a [(K, V)],
}
arena_deserializer::impl_deserialize_in_arena!(SortedAssocList<'arena, K, V>);
impl<'a, K, V> SortedAssocList<'a, K, V> {
/// Returns the empty association list.
pub fn empty() -> Self {
SortedAssocList { entries: &[] }
}
/// Returns a reference to the value corresponding to the key.
///
/// The key may be any borrowed form of the list's key type, but the
/// ordering on the borrowed form *must* match the ordering on the key type.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{AssocListMut, SortedAssocList};
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// alist.insert(1, "a");
/// let alist = SortedAssocList::from(alist);
/// assert_eq!(alist.get(&1), Some(&"a"));
/// assert_eq!(alist.get(&2), None);
/// ```
pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: Ord,
{
get_sorted_entry(self.entries, key).map(|(_, v)| v)
}
/// Returns the key-value pair corresponding to the supplied key.
///
/// The key may be any borrowed form of the list's key type, but the
/// ordering on the borrowed form *must* match the ordering on the key type.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{AssocListMut, SortedAssocList};
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// alist.insert(1, "a");
/// let alist = SortedAssocList::from(alist);
/// assert_eq!(alist.get_key_value(&1), Some((&1, &"a")));
/// assert_eq!(alist.get_key_value(&2), None);
/// ```
pub fn get_key_value<Q: ?Sized>(&self, key: &Q) -> Option<(&K, &V)>
where
K: Borrow<Q>,
Q: Ord,
{
get_sorted_entry(self.entries, key).map(|(k, v)| (k, v))
}
/// Returns `true` if the list contains a value for the specified key.
///
/// The key may be any borrowed form of the list's key type, but the
/// ordering on the borrowed form *must* match the ordering on the key type.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{AssocListMut, SortedAssocList};
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// alist.insert(1, "a");
/// let alist = SortedAssocList::from(alist);
/// assert_eq!(alist.contains_key(&1), true);
/// assert_eq!(alist.contains_key(&2), false);
/// ```
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: Ord,
{
get_sorted_entry(self.entries, key).is_some()
}
/// Gets an iterator over the entries of the association list, sorted by
/// key.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{AssocListMut, SortedAssocList};
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
///
/// alist.insert(1, "a");
/// alist.insert(2, "b");
///
/// let alist = SortedAssocList::from(alist);
///
/// for (key, value) in alist.iter() {
/// println!("{}: {}", key, value);
/// }
///
/// let (first_key, first_value) = alist.iter().next().unwrap();
/// assert_eq!((*first_key, *first_value), (1, "a"));
/// ```
pub fn iter(&self) -> impl Iterator<Item = (&K, &V)> {
self.entries.iter().map(|(k, v)| (k, v))
}
/// Gets an iterator over the keys of the association list, in sorted order.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{AssocListMut, SortedAssocList};
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
///
/// alist.insert(1, "a");
/// alist.insert(2, "b");
///
/// let alist = SortedAssocList::from(alist);
/// let keys: Vec<_> = alist.keys().copied().collect();
/// assert_eq!(keys, [1, 2]);
/// ```
pub fn keys(&self) -> impl Iterator<Item = &K> {
self.entries.iter().map(|(k, _)| k)
}
/// Gets an iterator over the values of the association list, in order by
/// key.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{AssocListMut, SortedAssocList};
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
///
/// alist.insert(1, "hello");
/// alist.insert(2, "goodbye");
///
/// let alist = SortedAssocList::from(alist);
/// let values: Vec<&str> = alist.values().copied().collect();
/// assert_eq!(values, ["hello", "goodbye"]);
/// ```
pub fn values(&self) -> impl Iterator<Item = &V> {
self.entries.iter().map(|(_, v)| v)
}
/// Returns the number of entries in the list.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{AssocListMut, SortedAssocList};
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// alist.insert(1, "a");
/// alist.insert(1, "b");
/// let alist = SortedAssocList::from(alist);
/// assert_eq!(alist.len(), 1);
/// ```
pub fn len(&self) -> usize {
self.entries.len()
}
/// Returns `true` if the list contains no entries.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{AssocListMut, SortedAssocList};
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
/// let alist = SortedAssocList::from(alist);
/// assert!(alist.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
/// Make a new `SortedAssocList` containing the given key-value pairs.
///
/// Provided for the sake of creating empty const lists. Passing non-empty
/// slices is not recommended.
///
/// The values in the slice must be in ascending sorted order (by `K`'s
/// implementation of `Ord`). There must be no duplicate keys in the slice.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{AssocListMut, SortedAssocList};
///
/// let b = Bump::new();
/// let mut alist = AssocListMut::new_in(&b);
///
/// const EMPTY_ALIST: SortedAssocList<'_, usize> = SortedAssocList::from_slice(&[]);
/// assert!(EMPTY_ALIST.is_empty());
/// ```
pub const fn from_slice(entries: &'a [(K, V)]) -> Self {
Self { entries }
}
}
impl<K, V> TrivialDrop for SortedAssocList<'_, K, V> {}
impl<K, V> Copy for SortedAssocList<'_, K, V> {}
impl<K, V> Clone for SortedAssocList<'_, K, V> {
fn clone(&self) -> Self {
*self
}
}
impl<K, V> Default for SortedAssocList<'_, K, V> {
fn default() -> Self {
Self::from_slice(&[])
}
}
impl<K: Debug, V: Debug> Debug for SortedAssocList<'_, K, V> {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt.debug_map().entries(self.iter()).finish()
}
}
impl<'a, K: Ord, V> From<AssocListMut<'a, K, V>> for SortedAssocList<'a, K, V> {
#[inline]
fn from(mut alist: AssocListMut<'a, K, V>) -> Self {
let entries_mut = alist.entries.as_mut_slice();
// Reverse the slice so the most recently inserted pairs appear first.
entries_mut.reverse();
// Keep recently-inserted pairs first with a stable sort. Allocates
// temporary storage half the size of the slice using the global
// allocator if the slice is larger than some threshold (20 elements at
// time of writing).
entries_mut.sort_by(|(k1, _), (k2, _)| k1.cmp(k2));
// Remove all but the most recently inserted pair for each key.
alist.entries.dedup_by(|(k1, _), (k2, _)| k1 == k2);
SortedAssocList {
entries: alist.entries.into_bump_slice(),
}
}
}
impl<K: ToOcamlRep + Ord, V: ToOcamlRep> ToOcamlRep for SortedAssocList<'_, K, V> {
fn to_ocamlrep<'a, A: ocamlrep::Allocator>(&'a self, alloc: &'a A) -> ocamlrep::Value<'a> {
let len = self.len();
let mut iter = self
.iter()
.map(|(k, v)| (k.to_ocamlrep(alloc), v.to_ocamlrep(alloc)));
let (value, _) = ocamlrep::sorted_iter_to_ocaml_map(&mut iter, alloc, len);
value
}
}
impl<'a, K, V> FromOcamlRepIn<'a> for SortedAssocList<'a, K, V>
where
K: FromOcamlRepIn<'a> + Ord,
V: FromOcamlRepIn<'a>,
{
fn from_ocamlrep_in(
value: ocamlrep::Value<'_>,
alloc: &'a bumpalo::Bump,
) -> Result<Self, ocamlrep::FromError> {
let mut entries = bumpalo::collections::Vec::new_in(alloc);
ocamlrep::vec_from_ocaml_map_in(value, &mut entries, alloc)?;
let entries = entries.into_bump_slice();
Ok(Self { entries })
}
} |
TOML | hhvm/hphp/hack/src/arena_collections/Cargo.toml | # @generated by autocargo
[package]
name = "arena_collections"
version = "0.0.0"
edition = "2021"
[lib]
path = "lib.rs"
[dependencies]
arena_deserializer = { version = "0.0.0", path = "../utils/arena_deserializer" }
arena_trait = { version = "0.0.0", path = "../arena_trait" }
bumpalo = { version = "3.11.1", features = ["collections"] }
ocamlrep = { version = "0.1.0", git = "https://github.com/facebook/ocamlrep/", branch = "main" }
serde = { version = "1.0.176", features = ["derive", "rc"] }
[dev-dependencies]
quickcheck = "1.0" |
Rust | hhvm/hphp/hack/src/arena_collections/lib.rs | // 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.
mod alist;
mod multiset;
pub mod map;
pub mod set;
#[macro_use]
pub mod vec;
#[macro_use]
pub mod list;
pub use alist::AssocList;
pub use alist::AssocListMut;
pub use alist::SortedAssocList;
pub use arena_trait::Arena;
pub use list::List;
pub use multiset::MultiSet;
pub use multiset::MultiSetMut;
pub use multiset::SortedSet;
#[cfg(test)]
mod test_list;
#[cfg(test)]
mod test_alist;
#[cfg(test)]
mod test_alist_mut;
#[cfg(test)]
mod test_sorted_alist;
#[cfg(test)]
mod test_multiset; |
Rust | hhvm/hphp/hack/src/arena_collections/list.rs | // 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.
use std::fmt::Debug;
use std::marker::PhantomData;
use arena_deserializer::ArenaSeed;
use arena_deserializer::DeserializeInArena;
use arena_trait::Arena;
use arena_trait::TrivialDrop;
use bumpalo::Bump;
use ocamlrep::FromOcamlRepIn;
use ocamlrep::ToOcamlRep;
use serde::de::Deserializer;
use serde::de::SeqAccess;
use serde::de::Visitor;
use serde::Serialize;
#[derive(Eq, Hash, PartialEq, PartialOrd, Ord)]
#[derive(FromOcamlRepIn, ToOcamlRep)]
pub enum List<'a, T> {
Nil,
Cons(&'a (T, List<'a, T>)),
}
use List::*;
impl<'a, T> List<'a, T> {
/// Return the empty list.
pub const fn empty() -> Self {
Nil
}
/// Prepend the given element to the given list.
#[inline]
pub fn cons<A: Arena>(element: T, list: Self, arena: &'a A) -> Self
where
T: TrivialDrop,
{
Cons(arena.alloc((element, list)))
}
/// Return the length (number of elements) of the given list.
pub fn len(self) -> usize {
let mut node = self;
let mut len = 0;
while let Cons(&(_, next)) = node {
node = next;
len += 1;
}
len
}
/// Return `true` if the list contains no elements.
#[inline]
pub fn is_empty(self) -> bool {
match self {
Nil => true,
Cons(..) => false,
}
}
/// Return the first element of the list.
#[inline]
pub fn hd(self) -> Option<&'a T> {
match self {
Nil => None,
Cons((x, _)) => Some(x),
}
}
/// Return the list without its first element.
#[inline]
pub fn tl(self) -> Option<Self> {
match self {
Nil => None,
Cons(&(_, l)) => Some(l),
}
}
/// Return the `n`-th element of the given list. The first element (head of
/// the list) is at position 0. Return `None` if the list is too short.
pub fn nth(self, n: usize) -> Option<&'a T> {
let mut node = self;
let mut idx = 0;
while let Cons((x, next)) = node {
if n == idx {
return Some(x);
}
node = *next;
idx += 1;
}
None
}
/// List reversal.
pub fn rev<A: Arena>(self, arena: &'a A) -> Self
where
T: Clone + TrivialDrop,
{
self.rev_append(Nil, arena)
}
/// Concatenate two lists by cloning all elements from `self` into a list
/// which points to `other` as a suffix.
pub fn append<A: Arena>(self, other: Self, arena: &'a A) -> Self
where
T: Clone + TrivialDrop,
{
self.count_append(other, 0, arena)
}
/// `count_append` is borrowed from Jane Street Base, and applies two
/// optimizations for `append`: loop unrolling, and dynamic switching
/// between stack and arena allocation.
///
/// The loop-unrolling is straightforward, we just unroll 5 levels of the
/// loop. This should make each iteration faster, and also reduces the
/// number of stack frames consumed per list element.
///
/// The dynamic switching is done by counting the number of stack frames,
/// and then switching to the "slow" implementation when we exceed a given
/// limit. This means that short lists use the fast stack-allocation method,
/// and long lists use a slower one that doesn't require stack space.
fn count_append<A: Arena>(self, other: Self, count: usize, arena: &'a A) -> Self
where
T: Clone + TrivialDrop,
{
if other.is_empty() {
return self;
}
let a = arena;
match self {
Nil => other,
Cons((x1, Nil)) => Self::cons(x1.clone(), other, a),
Cons((x1, Cons((x2, Nil)))) => {
let x1 = x1.clone();
let x2 = x2.clone();
Self::cons(x1, Self::cons(x2, other, a), a)
}
Cons((x1, Cons((x2, Cons((x3, Nil)))))) => {
let x1 = x1.clone();
let x2 = x2.clone();
let x3 = x3.clone();
Self::cons(x1, Self::cons(x2, Self::cons(x3, other, a), a), a)
}
Cons((x1, Cons((x2, Cons((x3, Cons((x4, Nil)))))))) => {
let x1 = x1.clone();
let x2 = x2.clone();
let x3 = x3.clone();
let x4 = x4.clone();
Self::cons(
x1,
Self::cons(x2, Self::cons(x3, Self::cons(x4, other, a), a), a),
a,
)
}
Cons((x1, Cons((x2, Cons((x3, Cons((x4, Cons((x5, tl)))))))))) => {
let tl = if count > 1000 {
tl.slow_append(other, a)
} else {
tl.count_append(other, count + 1, a)
};
let x1 = x1.clone();
let x2 = x2.clone();
let x3 = x3.clone();
let x4 = x4.clone();
let x5 = x5.clone();
Self::cons(
x1,
Self::cons(
x2,
Self::cons(x3, Self::cons(x4, Self::cons(x5, tl, a), a), a),
a,
),
a,
)
}
}
}
/// Helper for `append`. See comment on `count_append`.
fn slow_append<A: Arena>(self, other: Self, arena: &'a A) -> Self
where
T: Clone + TrivialDrop,
{
let temp_arena = bumpalo::Bump::new();
self.rev(&temp_arena).rev_append(other, arena)
}
/// `l1.rev_append(l2)` reverses `l1` and concatenates it to `l2`. This is
/// equivalent to `l1.rev().append(l2)`, but `rev_append` is more efficient.
pub fn rev_append<'b, A: Arena>(self, other: List<'b, T>, arena: &'b A) -> List<'b, T>
where
'b: 'a,
T: Clone + TrivialDrop + 'b,
{
let mut node = self;
let mut result = other;
while let Cons((x, next)) = node {
node = *next;
result = Cons(arena.alloc((x.clone(), result)));
}
result
}
/// `List::init(len, f, arena)` is `list![in arena; f(0), f(1), ..., f(len-1)]`,
/// evaluated right to left.
pub fn init<A: Arena>(len: usize, mut f: impl FnMut(usize) -> T, arena: &'a A) -> Self
where
T: TrivialDrop,
{
let mut node = Nil;
for i in (0..len).rev() {
node = Cons(arena.alloc((f(i), node)));
}
node
}
/// Return an iterator over the elements of the list.
pub fn iter(self) -> Iter<'a, T> {
Iter(self)
}
/// Returns `true` if the `List` contains an element equal to the given value.
pub fn contains(self, value: &T) -> bool
where
T: PartialEq,
{
self.iter().any(|x| x == value)
}
/// `l.find(p)` returns the first element of the list `l` that satisfies the
/// predicate `p`, or `None` if there is no value that satisfies `p` in the
/// list `l`.
pub fn find(self, mut f: impl FnMut(&T) -> bool) -> Option<&'a T> {
self.iter().find(|&x| f(x))
}
/// Produce a List containing the elements yielded by the given iterator, in
/// reverse order.
pub fn rev_from_iter_in<I: IntoIterator<Item = T>, A: Arena>(iter: I, arena: &'a A) -> Self
where
T: TrivialDrop,
{
let mut node = Nil;
for x in iter {
node = Cons(arena.alloc((x, node)));
}
node
}
/// Prepend the given element to the list in-place.
pub fn push_front<A: Arena>(&mut self, element: T, arena: &'a A)
where
T: TrivialDrop,
{
*self = Cons(arena.alloc((element, *self)));
}
/// Remove the first element of the list in-place and return a reference to
/// it, or `None` if the list is empty.
pub fn pop_front(&mut self) -> Option<&'a T> {
match self {
Nil => None,
Cons((x, l)) => {
*self = *l;
Some(x)
}
}
}
}
// The derived implementations of Copy and Clone require `T` to be Copy/Clone.
// We have no such requirement, since List is just a pointer, so we manually
// implement them here.
impl<'a, T> Clone for List<'a, T> {
fn clone(&self) -> Self {
*self
}
}
impl<'a, T> Copy for List<'a, T> {}
impl<'a, T: TrivialDrop> TrivialDrop for List<'a, T> {}
impl<T: Debug> Debug for List<'_, T> {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt.debug_list().entries(self.iter()).finish()
}
}
pub struct Iter<'a, T>(List<'a, T>);
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
match self.0 {
Nil => None,
Cons((x, l)) => {
self.0 = *l;
Some(x)
}
}
}
}
impl<'a, T> IntoIterator for List<'a, T> {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<T: Serialize> Serialize for List<'_, T> {
fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeSeq;
let mut seq = ser.serialize_seq(Some(self.len()))?;
let mut node = self;
while let Cons((e, next)) = node {
node = next;
seq.serialize_element(e)?;
}
seq.end()
}
}
impl<'arena, T> DeserializeInArena<'arena> for List<'arena, T>
where
T: DeserializeInArena<'arena>,
{
fn deserialize_in_arena<D>(arena: &'arena Bump, deser: D) -> Result<Self, D::Error>
where
D: Deserializer<'arena>,
{
struct ListVisitor<'arena, T> {
arena: &'arena Bump,
marker: PhantomData<fn() -> T>,
}
impl<'arena, T> Visitor<'arena> for ListVisitor<'arena, T>
where
T: DeserializeInArena<'arena> + 'arena,
{
type Value = List<'arena, T>;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("a sequence")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'arena>,
{
let mut vec = Vec::with_capacity(seq.size_hint().unwrap_or(0));
let seed = ArenaSeed::new();
while let Some(value) = seq.next_element_seed(seed)? {
vec.push(value);
}
Ok(vec
.into_iter()
.rev()
.fold(List::empty(), |list, e| Cons(self.arena.alloc((e, list)))))
}
}
deser.deserialize_seq(ListVisitor {
arena,
marker: PhantomData,
})
}
}
#[macro_export]
macro_rules! list {
() => {
$crate::list::List::Nil
};
(in $arena:expr; $x:expr $(,)?) => {{
use $crate::Arena;
$crate::list::List::Cons($arena.alloc(($x, $crate::list::List::Nil)))
}};
(in $arena:expr; $x:expr, $($xs:expr $(,)?)+) => {{
use $crate::Arena;
let arena = $arena;
$crate::list::List::Cons(arena.alloc(($x, l![in arena; $($xs,)*])))
}};
(in $arena:expr; $elem:expr; $n:expr) => {{
let elem = $elem;
$crate::list::List::init($n, |_| elem.clone(), $arena)
}};
}
#[macro_export]
macro_rules! stack_list {
() => {
$crate::list::List::Nil
};
($x:expr $(,)?) => {
$crate::list::List::Cons(&($x, $crate::list::List::Nil))
};
($x:expr, $($xs:expr $(,)?)+) => {
$crate::list::List::Cons(&($x, stack_list![$($xs,)*]))
};
} |
Rust | hhvm/hphp/hack/src/arena_collections/map.rs | // 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.
use std::cmp::Ordering;
use std::fmt::Debug;
use std::hash::Hash;
use std::hash::Hasher;
use arena_deserializer::impl_deserialize_in_arena;
use arena_trait::Arena;
use arena_trait::TrivialDrop;
use ocamlrep::FromOcamlRepIn;
use ocamlrep::ToOcamlRep;
use serde::Deserialize;
use serde::Serialize;
/// The maximum height difference (or balance factor) that is allowed
/// in the implementation of the AVL tree.
const MAX_DELTA: usize = 2;
/// An arena-allocated map.
///
/// The underlying is a balanced tree in which all tree
/// nodes are allocated inside an arena.
///
/// Currently the underlying tree is equivalent to the
/// one used in OCaml's `Map` type.
///
/// Note that the `Option<&'a T>` is optimized to have a size of 1 word.
///
/// Since the whole Map is just a 1 word pointer, it implements the
/// `Copy` trait.
#[derive(Deserialize, Serialize)]
#[serde(bound(
deserialize = "K: 'de + arena_deserializer::DeserializeInArena<'de>, V: 'de + arena_deserializer::DeserializeInArena<'de>"
))]
#[must_use]
pub struct Map<'a, K, V>(
#[serde(deserialize_with = "arena_deserializer::arena", borrow)] Option<&'a Node<'a, K, V>>,
);
impl_deserialize_in_arena!(Map<'arena, K, V>);
impl<'a, K, V> TrivialDrop for Map<'a, K, V> {}
impl<'a, K: Debug, V: Debug> Debug for Map<'a, K, V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
/// The derived implementations of Copy and Clone require that K and V be
/// Copy/Clone. We have no such requirement, since Map is just a pointer, so we
/// manually implement them here.
impl<'a, K, V> Clone for Map<'a, K, V> {
fn clone(&self) -> Self {
let Map(opt) = self;
Map(opt.clone())
}
}
impl<'a, K, V> Copy for Map<'a, K, V> {}
impl<'a, K: PartialEq, V: PartialEq> PartialEq for Map<'a, K, V> {
fn eq(&self, other: &Self) -> bool {
self.iter().eq(other.iter())
}
}
impl<'a, K: Eq, V: Eq> Eq for Map<'a, K, V> {}
impl<K: PartialOrd, V: PartialOrd> PartialOrd for Map<'_, K, V> {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.iter().partial_cmp(other.iter())
}
}
impl<K: Ord, V: Ord> Ord for Map<'_, K, V> {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
self.iter().cmp(other.iter())
}
}
impl<K: Hash, V: Hash> Hash for Map<'_, K, V> {
fn hash<H: Hasher>(&self, state: &mut H) {
for elt in self {
elt.hash(state);
}
}
}
impl<K, V> Default for Map<'_, K, V> {
fn default() -> Self {
Map(None)
}
}
impl<K: ToOcamlRep, V: ToOcamlRep> ToOcamlRep for Map<'_, K, V> {
fn to_ocamlrep<'a, A: ocamlrep::Allocator>(&'a self, alloc: &'a A) -> ocamlrep::Value<'a> {
match self.0 {
None => alloc.add(&()),
Some(val) => alloc.add(val),
}
}
}
impl<'a, K, V> FromOcamlRepIn<'a> for Map<'a, K, V>
where
K: FromOcamlRepIn<'a> + TrivialDrop,
V: FromOcamlRepIn<'a> + TrivialDrop,
{
fn from_ocamlrep_in(
value: ocamlrep::Value<'_>,
alloc: &'a bumpalo::Bump,
) -> Result<Self, ocamlrep::FromError> {
if value.is_int() {
let _ = ocamlrep::from::expect_nullary_variant(value, 0)?;
Ok(Map(None))
} else {
Ok(Map(Some(
alloc.alloc(<Node<'a, K, V>>::from_ocamlrep_in(value, alloc)?),
)))
}
}
}
#[derive(Deserialize, Serialize, ToOcamlRep)]
#[serde(bound(
deserialize = "K: 'de + arena_deserializer::DeserializeInArena<'de>, V: 'de + arena_deserializer::DeserializeInArena<'de>"
))]
struct Node<'a, K, V>(
#[serde(deserialize_with = "arena_deserializer::arena", borrow)] Map<'a, K, V>,
#[serde(deserialize_with = "arena_deserializer::arena")] K,
#[serde(deserialize_with = "arena_deserializer::arena")] V,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)] Map<'a, K, V>,
usize,
);
impl_deserialize_in_arena!(Node<'arena, K, V>);
impl<'a, K, V> FromOcamlRepIn<'a> for Node<'a, K, V>
where
K: FromOcamlRepIn<'a> + TrivialDrop,
V: FromOcamlRepIn<'a> + TrivialDrop,
{
fn from_ocamlrep_in(
value: ocamlrep::Value<'_>,
alloc: &'a bumpalo::Bump,
) -> std::result::Result<Self, ocamlrep::FromError> {
let block = ocamlrep::from::expect_tuple(value, 5)?;
Ok(Node(
ocamlrep::from::field_in(block, 0, alloc)?,
ocamlrep::from::field_in(block, 1, alloc)?,
ocamlrep::from::field_in(block, 2, alloc)?,
ocamlrep::from::field_in(block, 3, alloc)?,
ocamlrep::from::field_in(block, 4, alloc)?,
))
}
}
impl<'a, K: TrivialDrop, V: TrivialDrop> TrivialDrop for Node<'a, K, V> {}
#[macro_export]
macro_rules! map {
( ) => ({ Map::empty() });
( $arena:expr; $($x:expr => $y:expr),* ) => ({
let mut temp_map = Map::empty();
$(
temp_map = temp_map.add($arena, $x, $y);
)*
temp_map
});
}
impl<'a, K, V> Map<'a, K, V> {
pub fn keys(&self) -> impl Iterator<Item = &'a K> {
self.iter().map(|(k, _v)| k)
}
}
impl<'a, K: Ord, V> Map<'a, K, V> {
/// Check whether a key is present in the map.
pub fn mem(self, x: &K) -> bool {
match self {
Map(None) => false,
Map(Some(Node(l, v, _d, r, _h))) => match x.cmp(v) {
Ordering::Equal => true,
Ordering::Less => l.mem(x),
Ordering::Greater => r.mem(x),
},
}
}
}
impl<'a, K, V> Map<'a, K, V> {
/// Create a new empty map.
///
/// Note that this does not require heap allocation,
/// as it is equivalent to a 1 word null pointer.
pub const fn empty() -> Self {
Map(None)
}
/// Compute the number of entries in a map.
///
/// Note that this function takes linear time and logarithmic
/// stack space in the size of the map.
pub fn count(self) -> usize {
match self {
Map(None) => 0,
Map(Some(Node(l, _, _, r, _))) => l.count() + 1 + r.count(),
}
}
}
impl<'a, K: Ord, V> Map<'a, K, V> {
/// Check whether the map is empty.
pub fn is_empty(self) -> bool {
match self {
Map(None) => true,
Map(Some(_)) => false,
}
}
}
impl<'a, K: TrivialDrop + Clone + Ord, V: TrivialDrop + Clone> Map<'a, K, V> {
/// Returns a one-element map.
pub fn singleton<A: Arena>(arena: &'a A, x: K, d: V) -> Self {
let node = Node(Map(None), x, d, Map(None), 1);
return Map(Some(arena.alloc(node)));
}
/// Create a map from an iterator.
pub fn from<A: Arena, I>(arena: &'a A, i: I) -> Self
where
I: IntoIterator<Item = (K, V)>,
{
let mut m = Self::empty();
for (k, v) in i {
m = m.add(arena, k, v);
}
m
}
/// Returns a pointer the current entry belonging to the key,
/// or returns None, if no such entry exists.
pub fn get(self, x: &K) -> Option<&'a V> {
match self {
Map(None) => None,
Map(Some(Node(l, v, d, r, _h))) => match x.cmp(v) {
Ordering::Equal => Some(d),
Ordering::Less => l.get(x),
Ordering::Greater => r.get(x),
},
}
}
/// Return a map containing the same entries as before,
/// plus a new entry. If the key was already bound,
/// its previous entry disappears.
pub fn add<A: Arena>(self, arena: &'a A, x: K, data: V) -> Self {
match self {
Map(None) => {
let node = Node(Self::empty(), x, data, Self::empty(), 1);
Map(Some(arena.alloc(node)))
}
Map(Some(Node(ref l, v, d, r, h))) => match x.cmp(v) {
Ordering::Equal => {
let node = Node(*l, x, data, *r, *h);
Map(Some(arena.alloc(node)))
}
Ordering::Less => bal(arena, l.add(arena, x, data), v.clone(), d.clone(), *r),
Ordering::Greater => bal(arena, *l, v.clone(), d.clone(), r.add(arena, x, data)),
},
}
}
/// Returns a map containing the same entries as before,
/// except for the key, which is unbound in the returned map.
pub fn remove<A: Arena>(self, arena: &'a A, x: &K) -> Self {
match self {
Map(None) => Map(None),
Map(Some(Node(l, v, d, r, _))) => match x.cmp(v) {
Ordering::Equal => merge(arena, *l, *r),
Ordering::Less => bal(arena, l.remove(arena, x), v.clone(), d.clone(), *r),
Ordering::Greater => bal(arena, *l, v.clone(), d.clone(), r.remove(arena, x)),
},
}
}
pub fn add_all<A: Arena>(self, arena: &'a A, other: Self) -> Self {
other
.iter()
.fold(self, |m, (k, v)| m.add(arena, k.clone(), v.clone()))
}
/// Find the minimal key-value entry.
pub fn min_entry(self) -> Option<(&'a K, &'a V)> {
match self {
Map(None) => None,
Map(Some(Node(l, x, d, _r, _))) => match l {
Map(None) => Some((x, d)),
l => l.min_entry(),
},
}
}
/// Remove the minimal key-value entry.
pub fn remove_min_entry<A: Arena>(self, arena: &'a A) -> Self {
match self {
Map(None) => Map(None),
Map(Some(Node(l, x, d, r, _))) => match l {
Map(None) => *r,
l => bal(arena, l.remove_min_entry(arena), x.clone(), d.clone(), *r),
},
}
}
/// Find the maximum key-value entry.
pub fn max_entry(self) -> Option<(&'a K, &'a V)> {
match self {
Map(None) => None,
Map(Some(Node(_l, x, d, r, _))) => match r {
Map(None) => Some((x, d)),
r => r.max_entry(),
},
}
}
/// Remove the maximum key-value entry.
pub fn remove_max_entry<A: Arena>(self, arena: &'a A) -> Self {
match self {
Map(None) => Map(None),
Map(Some(Node(l, x, d, r, _))) => match r {
Map(None) => *l,
r => bal(arena, *l, x.clone(), d.clone(), r.remove_max_entry(arena)),
},
}
}
/// Set difference. O(n*log(n))
pub fn diff<A: Arena>(self, arena: &'a A, other: Self) -> Self {
other
.into_iter()
.fold(self, |set, (k, _v)| set.remove(arena, k))
}
}
impl<'a, K: Clone + Ord, V: Copy> Map<'a, K, V> {
/// Returns a copy of the current entry belonging to the key,
/// or returns None, if no such entry exists.
pub fn find(self, x: &K) -> Option<V> {
match self {
Map(None) => None,
Map(Some(Node(l, v, d, r, _h))) => match x.cmp(v) {
Ordering::Equal => Some(*d),
Ordering::Less => l.find(x),
Ordering::Greater => r.find(x),
},
}
}
}
fn height<'a, K, V>(l: Map<'a, K, V>) -> usize {
match l {
Map(None) => 0,
Map(Some(Node(_, _, _, _, h))) => *h,
}
}
fn create<'a, A: Arena, K: TrivialDrop, V: TrivialDrop>(
arena: &'a A,
l: Map<'a, K, V>,
x: K,
v: V,
r: Map<'a, K, V>,
) -> Map<'a, K, V> {
let hl = height(l);
let hr = height(r);
let h = if hl >= hr { hl + 1 } else { hr + 1 };
let node = Node(l, x, v, r, h);
Map(Some(arena.alloc(node)))
}
fn bal<'a, A: Arena, K: TrivialDrop + Clone, V: TrivialDrop + Clone>(
arena: &'a A,
l: Map<'a, K, V>,
x: K,
d: V,
r: Map<'a, K, V>,
) -> Map<'a, K, V> {
let hl = height(l);
let hr = height(r);
if hl > hr + MAX_DELTA {
match l {
Map(None) => panic!("impossible"),
Map(Some(Node(ll, lv, ld, lr, _))) => {
if height(*ll) >= height(*lr) {
create(
arena,
*ll,
lv.clone(),
ld.clone(),
create(arena, *lr, x, d, r),
)
} else {
match lr {
Map(None) => panic!("impossible"),
Map(Some(Node(lrl, lrv, lrd, lrr, _))) => create(
arena,
create(arena, *ll, lv.clone(), ld.clone(), *lrl),
lrv.clone(),
lrd.clone(),
create(arena, *lrr, x, d, r),
),
}
}
}
}
} else if hr > hl + MAX_DELTA {
match r {
Map(None) => panic!("impossible"),
Map(Some(Node(rl, rv, rd, rr, _))) => {
if height(*rr) >= height(*rl) {
create(
arena,
create(arena, l, x, d, *rl),
rv.clone(),
rd.clone(),
*rr,
)
} else {
match rl {
Map(None) => panic!("impossible"),
Map(Some(Node(rll, rlv, rld, rlr, _))) => create(
arena,
create(arena, l, x, d, *rll),
rlv.clone(),
rld.clone(),
create(arena, *rlr, rv.clone(), rd.clone(), *rr),
),
}
}
}
}
} else {
create(arena, l, x, d, r)
}
}
fn merge<'a, A: Arena, K: TrivialDrop + Clone + Ord, V: TrivialDrop + Clone>(
arena: &'a A,
t1: Map<'a, K, V>,
t2: Map<'a, K, V>,
) -> Map<'a, K, V> {
if t1.is_empty() {
t2
} else if t2.is_empty() {
t1
} else {
let (x, d) = t2.min_entry().unwrap();
bal(arena, t1, x.clone(), d.clone(), t2.remove_min_entry(arena))
}
}
/// Iterator state for map.
pub struct MapIter<'a, K, V> {
stack: Vec<NodeIter<'a, K, V>>,
}
struct NodeIter<'a, K, V> {
left_done: bool,
node: &'a Node<'a, K, V>,
}
impl<'a, K, V> Map<'a, K, V> {
pub fn iter(&self) -> MapIter<'a, K, V> {
let stack = match self {
Map(None) => Vec::new(),
Map(Some(root)) => vec![NodeIter {
left_done: false,
node: root,
}],
};
MapIter { stack }
}
}
impl<'a, K, V> IntoIterator for &Map<'a, K, V> {
type Item = (&'a K, &'a V);
type IntoIter = MapIter<'a, K, V>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a, K, V> Iterator for MapIter<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<Self::Item> {
let recurse_left = {
match self.stack.last_mut() {
None => None,
Some(n) => {
if n.left_done {
None
} else {
n.left_done = true;
let Node(Map(l), _, _, _, _) = n.node;
*l
}
}
}
};
match recurse_left {
Some(n) => {
self.stack.push(NodeIter {
left_done: false,
node: n,
});
self.next()
}
None => match self.stack.pop() {
None => None,
Some(n) => {
if let Node(_, _, _, Map(Some(n)), _) = n.node {
self.stack.push(NodeIter {
left_done: false,
node: n,
});
}
let Node(_, k, v, _, _) = n.node;
Some((k, v))
}
},
}
}
}
#[cfg(test)]
mod tests {
use bumpalo::Bump;
use super::*;
#[test]
fn test_is_empty() {
let arena = Bump::new();
assert!(Map::<i64, i64>::empty().is_empty());
assert!(!map![&arena; 4 => 9].is_empty());
}
#[test]
fn test_singleton() {
let a1 = Bump::new();
let a2 = Bump::new();
assert_eq!(map![&a1; 1 => 2], map![&a2; 1 => 2]);
}
#[test]
fn test_from() {
let a = Bump::new();
assert_eq!(Map::<i64, i64>::from(&a, Vec::new()), map![]);
assert_eq!(
Map::<i64, i64>::from(&a, vec![(6, 7), (8, 9)]),
map![&a; 8 => 9, 6 => 7]
);
}
}
#[cfg(test)]
mod tests_arbitrary {
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::hash::Hash;
use bumpalo::Bump;
use quickcheck::*;
use super::*;
quickcheck! {
fn prop_mem_find(xs: Vec<(u32, u32)>, ys: Vec<u32>) -> bool {
let a = Bump::new();
let m = Map::from(&a, xs.clone());
let o: HashMap<u32, u32> = xs.into_iter().collect();
for (k, v) in o.iter() {
assert!(m.mem(k));
assert_eq!(m.get(k), Some(v));
}
for k in ys {
let f = o.contains_key(&k);
assert_eq!(m.mem(&k), f);
assert_eq!(m.get(&k).is_some(), f);
}
true
}
}
#[derive(Clone, Debug)]
enum Action<T, V> {
Add(T, V),
Remove(T),
}
#[derive(Clone, Debug)]
struct ActionSequence<T, V>(Vec<Action<T, V>>);
struct ActionSequenceShrinker<T, V> {
seed: ActionSequence<T, V>,
index: usize,
}
impl<T: Arbitrary + Ord + Hash, V: Arbitrary + Eq + Hash> Arbitrary for ActionSequence<T, V> {
fn arbitrary(g: &mut Gen) -> Self {
let size = {
let s = g.size();
usize::arbitrary(g) % s
};
let mut elements: BTreeSet<T> = BTreeSet::new();
let mut actions: Vec<Action<T, V>> = Vec::with_capacity(size);
for _ in 0..size {
let r = f64::arbitrary(g);
if r < 0.1 {
let key: T = Arbitrary::arbitrary(g);
elements.remove(&key);
actions.push(Action::Remove(key));
} else if !elements.is_empty() && r < 0.3 {
let index = usize::arbitrary(g) % elements.len();
let key: T = elements.iter().nth(index).unwrap().clone();
elements.remove(&key);
actions.push(Action::Remove(key));
} else {
let key: T = Arbitrary::arbitrary(g);
elements.insert(key.clone());
actions.push(Action::Add(key, Arbitrary::arbitrary(g)));
}
}
ActionSequence(actions)
}
fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
Box::new(ActionSequenceShrinker {
seed: self.clone(),
index: 0,
})
}
}
impl<T: Clone, V: Clone> Iterator for ActionSequenceShrinker<T, V> {
type Item = ActionSequence<T, V>;
fn next(&mut self) -> Option<ActionSequence<T, V>> {
let ActionSequence(ref actions) = self.seed;
if self.index > actions.len() {
None
} else {
let actions = actions[..self.index].to_vec();
self.index += 1;
Some(ActionSequence(actions))
}
}
}
fn check_height_invariant<'a, K, V>(m: Map<'a, K, V>) -> bool {
match m {
Map(None) => true,
Map(Some(Node(l, _, _, r, h))) => {
let lh = height(*l);
let rh = height(*r);
let h_exp = if lh > rh { lh + 1 } else { rh + 1 };
if *h != h_exp {
println!("incorrect node height");
return false;
}
if lh > rh + MAX_DELTA || rh > lh + MAX_DELTA {
println!("height difference invariant violated");
return false;
}
check_height_invariant(*l) && check_height_invariant(*r)
}
}
}
quickcheck! {
fn prop_action_seq(actions: ActionSequence<u32, u32>) -> bool {
let ActionSequence(ref actions) = actions;
let a = Bump::new();
let mut m: Map<'_, u32, u32> = Map::empty();
let mut o: BTreeMap<u32, u32> = BTreeMap::new();
for action in actions {
match action {
Action::Add(key, value) => {
m = m.add(&a, *key, *value);
o.insert(*key, *value);
}
Action::Remove(key) => {
m = m.remove(&a, key);
o.remove(key);
}
}
}
if !m.into_iter().eq(o.iter()) {
println!("EXPECTED {:?} GOT {:?}", o, m);
false
} else {
check_height_invariant(m)
}
}
}
}
#[cfg(test)]
mod tests_iter {
use bumpalo::Bump;
use super::*;
#[test]
fn test_iter_manual() {
assert_eq!(
Map::<i64, i64>::empty()
.into_iter()
.map(|(k, v)| (*k, *v))
.collect::<Vec<(i64, i64)>>(),
vec![]
);
// ,5.
// ,2. `6.
// 1' 4 `7
// 3'
let arena = Bump::new();
let a = &arena;
let empty = Map::empty();
let map = create(
a,
create(
a,
create(a, empty, 1, (), empty),
2,
(),
create(a, create(a, empty, 3, (), empty), 4, (), empty),
),
5,
(),
create(a, empty, 6, (), create(a, empty, 7, (), empty)),
);
assert_eq!(
map.into_iter().map(|(k, ())| *k).collect::<Vec<i64>>(),
vec![1, 2, 3, 4, 5, 6, 7]
);
}
} |
Rust | hhvm/hphp/hack/src/arena_collections/multiset.rs | // 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.
//! Array-backed set types.
//!
//! At the moment, we are using the bumpalo allocator for arena allocation.
//! Because the stdlib types do not yet provide the ability to choose the
//! allocator used when they are allocated or resized, the bumpalo library
//! provides its own growable Vec and String types. Since bumpalo does not
//! provide its own map or set types, we must define our own if we want to
//! control where they are allocated.
//!
//! This module defines set types backed by bumpalo's Vec. It is useful for sets
//! which are built all at once, and never modified thereafter (e.g., sets in
//! ASTs). When immutable semantics are desired, but updating is necessary,
//! consider the `arena_collections::set` submodule instead, for a set type
//! backed by an immutable balanced binary tree. The Vec-backed sets in this
//! module may benefit from better cache efficiency, and so may outperform the
//! balanced tree implementation in some circumstances.
use std::borrow::Borrow;
use std::fmt::Debug;
use arena_trait::TrivialDrop;
use bumpalo::Bump;
use ocamlrep::FromOcamlRepIn;
use ocamlrep::ToOcamlRep;
use serde::Serialize;
use crate::AssocList;
use crate::AssocListMut;
use crate::SortedAssocList;
/// A readonly array-based multiset.
///
/// * Lookups run in linear time
/// * Duplicate elements are permitted
#[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct MultiSet<'a, T> {
list: AssocList<'a, T, ()>,
}
impl<'a, T: 'a> MultiSet<'a, T> {
/// Returns `true` if the set contains a value.
///
/// The value may be any borrowed form of the set's value type,
/// but the ordering on the borrowed form *must* match the
/// ordering on the value type.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{MultiSet, MultiSetMut};
///
/// let b = Bump::new();
/// let mut set = MultiSetMut::new_in(&b);
/// set.insert(1);
/// let set = MultiSet::from(set);
/// assert!(set.contains(&1));
/// ```
pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
where
T: Borrow<Q>,
Q: Ord,
{
self.list.contains_key(value)
}
/// Get an iterator over the elements of the set.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{MultiSet, MultiSetMut};
///
/// let b = Bump::new();
/// let mut set = MultiSetMut::new_in(&b);
/// set.insert(3);
/// set.insert(1);
/// set.insert(2);
/// let set = MultiSet::from(set);
/// let mut set_iter = set.iter();
/// assert_eq!(set_iter.next(), Some(&3));
/// assert_eq!(set_iter.next(), Some(&1));
/// assert_eq!(set_iter.next(), Some(&2));
/// assert_eq!(set_iter.next(), None);
/// ```
pub fn iter(&self) -> impl Iterator<Item = &T> {
self.list.keys()
}
/// Returns the number of elements in the set. Duplicate elements are
/// counted.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{MultiSet, MultiSetMut};
///
/// let b = Bump::new();
/// let mut set = MultiSetMut::new_in(&b);
/// set.insert(1);
/// set.insert(1);
/// let set = MultiSet::from(set);
/// assert_eq!(set.len(), 2);
/// ```
pub fn len(&self) -> usize {
self.list.len()
}
/// Returns `true` if the set contains no elements.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{MultiSet, MultiSetMut};
///
/// let b = Bump::new();
/// let mut set = MultiSetMut::new_in(&b);
/// let set = MultiSet::from(set);
/// assert_eq!(set.is_empty(), true);
/// let mut set = MultiSetMut::new_in(&b);
/// set.insert(1);
/// let set = MultiSet::from(set);
/// assert_eq!(set.is_empty(), false);
/// ```
pub fn is_empty(&self) -> bool {
self.list.is_empty()
}
/// Make a new `MultiSet` containing the values in the given slice.
///
/// Provided for the sake of creating empty const sets. Passing non-empty
/// slices is not recommended.
///
/// # Examples
///
/// ```
/// use arena_collections::{AssocList, MultiSet};
///
/// const EMPTY_MULTISET: MultiSet<'_, i32> = MultiSet::from_slice(&[]);
/// assert!(EMPTY_MULTISET.is_empty());
/// ```
pub const fn from_slice(slice: &'a [(T, ())]) -> Self {
Self {
list: AssocList::new(slice),
}
}
}
impl<T> TrivialDrop for MultiSet<'_, T> {}
impl<T: Debug> Debug for MultiSet<'_, T> {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt.debug_set().entries(self.iter()).finish()
}
}
impl<'a, T> From<MultiSetMut<'a, T>> for MultiSet<'a, T> {
#[inline]
fn from(set: MultiSetMut<'a, T>) -> Self {
MultiSet {
list: set.list.into(),
}
}
}
/// A mutable array-based multiset, allocated in a given arena.
///
/// * Lookups and removals run in linear time
/// * Insertions run in constant time
/// * Duplicate elements are permitted
#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct MultiSetMut<'bump, T> {
list: AssocListMut<'bump, T, ()>,
}
impl<'bump, T> MultiSetMut<'bump, T> {
/// Constructs a new, empty `MultiSetMut`.
///
/// The set will not allocate until an element is inserted.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::MultiSetMut;
///
/// let b = Bump::new();
/// let mut set: MultiSetMut<i32> = MultiSetMut::new_in(&b);
/// ```
#[inline]
pub fn new_in(bump: &'bump Bump) -> Self {
MultiSetMut {
list: AssocListMut::new_in(bump),
}
}
/// Constructs a new, empty `MultiSetMut` with the specified capacity.
///
/// The set will be able to hold exactly `capacity` elements without
/// reallocating. If `capacity` is 0, the set will not allocate.
///
/// It is important to note that although the returned set has the
/// *capacity* specified, the set will have a zero *length*.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::MultiSetMut;
///
/// let b = Bump::new();
///
/// let mut set = MultiSetMut::with_capacity_in(10, &b);
///
/// // The set contains no items, even though it has capacity for more
/// assert_eq!(set.len(), 0);
///
/// // These are all done without reallocating...
/// for i in 0..10 {
/// set.insert(i);
/// }
///
/// // ...but this may make the set reallocate
/// set.insert(11);
/// ```
#[inline]
pub fn with_capacity_in(capacity: usize, bump: &'bump Bump) -> Self {
MultiSetMut {
list: AssocListMut::with_capacity_in(capacity, bump),
}
}
/// Returns `true` if the set contains a value.
///
/// The value may be any borrowed form of the set's value type,
/// but the ordering on the borrowed form *must* match the
/// ordering on the value type.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::MultiSetMut;
///
/// let b = Bump::new();
/// let mut set = MultiSetMut::new_in(&b);
/// set.insert(1);
/// assert!(set.contains(&1));
/// ```
pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
where
T: Borrow<Q>,
Q: Ord,
{
self.list.contains_key(value)
}
/// Add a value to the set.
///
/// The value is added even if the set already contains the given value.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::MultiSetMut;
///
/// let b = Bump::new();
/// let mut set = MultiSetMut::new_in(&b);
/// assert_eq!(set.contains(&1), false);
/// set.insert(1);
/// assert_eq!(set.contains(&1), true);
/// ```
pub fn insert(&mut self, value: T) {
self.list.insert(value, ());
}
/// Removes a value from the set. Returns true if the value was present in
/// the set.
///
/// If the set contains multiple values equal to the given value, only the
/// most recently inserted is removed.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::MultiSetMut;
///
/// let b = Bump::new();
/// let mut set = MultiSetMut::new_in(&b);
///
/// set.insert(2);
/// assert_eq!(set.remove(&2), true);
/// assert_eq!(set.remove(&2), false);
/// ```
pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
where
T: Borrow<Q>,
Q: Ord,
{
self.list.remove(value).is_some()
}
/// Removes all values equal to the given value from the set. Returns true
/// if any values were removed.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::MultiSetMut;
///
/// let b = Bump::new();
/// let mut set = MultiSetMut::new_in(&b);
///
/// set.insert(2);
/// set.insert(2);
/// assert_eq!(set.remove_all(&2), true);
/// assert_eq!(set.remove_all(&2), false);
/// ```
pub fn remove_all<Q: ?Sized>(&mut self, value: &Q) -> bool
where
T: Borrow<Q>,
Q: Ord,
{
self.list.remove_all(value)
}
/// Get an iterator over the elements of the set.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{MultiSet, MultiSetMut};
///
/// let b = Bump::new();
/// let mut set = MultiSetMut::new_in(&b);
/// set.insert(3);
/// set.insert(1);
/// set.insert(2);
/// let mut set_iter = set.iter();
/// assert_eq!(set_iter.next(), Some(&3));
/// assert_eq!(set_iter.next(), Some(&1));
/// assert_eq!(set_iter.next(), Some(&2));
/// assert_eq!(set_iter.next(), None);
/// ```
pub fn iter(&self) -> impl Iterator<Item = &T> {
self.list.keys()
}
/// Returns the number of elements in the set. Duplicate elements are
/// counted.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{MultiSet, MultiSetMut};
///
/// let b = Bump::new();
/// let mut set = MultiSetMut::new_in(&b);
/// assert_eq!(set.len(), 0);
/// set.insert(1);
/// assert_eq!(set.len(), 1);
/// set.insert(1);
/// assert_eq!(set.len(), 2);
/// set.insert(2);
/// assert_eq!(set.len(), 3);
/// ```
pub fn len(&self) -> usize {
self.list.len()
}
/// Returns `true` if the set contains no elements.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{MultiSet, MultiSetMut};
///
/// let b = Bump::new();
/// let mut set = MultiSetMut::new_in(&b);
/// let set = MultiSet::from(set);
/// assert_eq!(set.is_empty(), true);
/// let mut set = MultiSetMut::new_in(&b);
/// set.insert(1);
/// let set = MultiSet::from(set);
/// assert_eq!(set.is_empty(), false);
/// ```
pub fn is_empty(&self) -> bool {
self.list.is_empty()
}
}
impl<T: Debug> Debug for MultiSetMut<'_, T> {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt.debug_set().entries(self.iter()).finish()
}
}
/// A readonly array-based set.
///
/// * Lookups run in log(n) time
/// * Duplicate elements are not permitted. When constructing a `SortedSet` from
/// a `MultiSetMut`, elements will be deduplicated.
#[derive(Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct SortedSet<'a, T> {
list: SortedAssocList<'a, T, ()>,
}
impl<T> TrivialDrop for SortedSet<'_, T> {}
impl<T> Copy for SortedSet<'_, T> {}
impl<T> Clone for SortedSet<'_, T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Default for SortedSet<'_, T> {
fn default() -> Self {
Self::from_slice(&[])
}
}
impl<'a, T> SortedSet<'a, T> {
/// Returns the empty set
pub fn empty() -> Self {
SortedSet {
list: SortedAssocList::empty(),
}
}
/// Returns `true` if the set contains a value.
///
/// The value may be any borrowed form of the set's value type,
/// but the ordering on the borrowed form *must* match the
/// ordering on the value type.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{MultiSetMut, SortedSet};
///
/// let b = Bump::new();
/// let mut set = MultiSetMut::new_in(&b);
/// set.insert(1);
/// let set = SortedSet::from(set);
/// assert!(set.contains(&1));
/// ```
pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
where
T: Borrow<Q>,
Q: Ord,
{
self.list.contains_key(value)
}
/// Get an iterator over the elements of the set in ascending order.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{MultiSetMut, SortedSet};
///
/// let b = Bump::new();
/// let mut set = MultiSetMut::new_in(&b);
/// set.insert(3);
/// set.insert(1);
/// set.insert(2);
/// let set = SortedSet::from(set);
/// let mut set_iter = set.iter();
/// assert_eq!(set_iter.next(), Some(&1));
/// assert_eq!(set_iter.next(), Some(&2));
/// assert_eq!(set_iter.next(), Some(&3));
/// assert_eq!(set_iter.next(), None);
/// ```
pub fn iter(&self) -> impl Iterator<Item = &T> {
self.list.keys()
}
/// Returns the number of elements in the set.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{MultiSetMut, SortedSet};
///
/// let b = Bump::new();
/// let mut set = MultiSetMut::new_in(&b);
/// set.insert(1);
/// set.insert(2);
/// set.insert(1);
/// let set = SortedSet::from(set);
/// assert_eq!(set.len(), 2);
/// ```
pub fn len(&self) -> usize {
self.list.len()
}
/// Returns `true` if the set contains no elements.
///
/// # Examples
///
/// ```
/// use bumpalo::Bump;
/// use arena_collections::{MultiSetMut, SortedSet};
///
/// let b = Bump::new();
/// let mut set = MultiSetMut::new_in(&b);
/// let set = SortedSet::from(set);
/// assert_eq!(set.is_empty(), true);
/// let mut set = MultiSetMut::new_in(&b);
/// set.insert(1);
/// let set = SortedSet::from(set);
/// assert_eq!(set.is_empty(), false);
/// ```
pub fn is_empty(&self) -> bool {
self.list.is_empty()
}
/// Make a new `SortedSet` containing the values in the given slice.
///
/// Provided for the sake of creating empty const sets. Passing non-empty
/// slices is not recommended.
///
/// The values in the slice must be in ascending sorted order (by `T`'s
/// implementation of `Ord`). There must be no duplicate values in the
/// slice.
///
/// # Examples
///
/// ```
/// use arena_collections::SortedSet;
///
/// const EMPTY_SORTED_SET: SortedSet<'_, i32> = SortedSet::from_slice(&[]);
/// assert!(EMPTY_SORTED_SET.is_empty());
/// ```
pub const fn from_slice(list: &'a [(T, ())]) -> Self {
Self {
list: SortedAssocList::from_slice(list),
}
}
}
impl<T: Debug> Debug for SortedSet<'_, T> {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt.debug_set().entries(self.iter()).finish()
}
}
impl<'a, T: Ord> From<MultiSetMut<'a, T>> for SortedSet<'a, T> {
#[inline]
fn from(set: MultiSetMut<'a, T>) -> Self {
SortedSet {
list: set.list.into(),
}
}
}
impl<T: ToOcamlRep + Ord> ToOcamlRep for SortedSet<'_, T> {
fn to_ocamlrep<'a, A: ocamlrep::Allocator>(&'a self, alloc: &'a A) -> ocamlrep::Value<'a> {
let len = self.len();
let mut iter = self.iter().map(|x| x.to_ocamlrep(alloc));
let (value, _) = ocamlrep::sorted_iter_to_ocaml_set(&mut iter, alloc, len);
value
}
}
impl<'a, T: FromOcamlRepIn<'a> + Ord> FromOcamlRepIn<'a> for SortedSet<'a, T> {
fn from_ocamlrep_in(
value: ocamlrep::Value<'_>,
alloc: &'a bumpalo::Bump,
) -> Result<Self, ocamlrep::FromError> {
let mut list = bumpalo::collections::Vec::new_in(alloc);
ocamlrep::vec_from_ocaml_set_in(value, &mut list, alloc)?;
let list = SortedAssocList::from_slice(list.into_bump_slice());
Ok(Self { list })
}
} |
Rust | hhvm/hphp/hack/src/arena_collections/set.rs | // 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.
use arena_trait::Arena;
use arena_trait::TrivialDrop;
use ocamlrep::FromOcamlRepIn;
use ocamlrep::ToOcamlRep;
use serde::Deserialize;
use serde::Serialize;
use crate::map::Map;
use crate::map::MapIter;
/// An arena-allocated set.
///
/// See `Map` for more info.
#[derive(Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(bound(deserialize = "K: 'de + arena_deserializer::DeserializeInArena<'de>"))]
#[must_use]
pub struct Set<'a, K>(
#[serde(deserialize_with = "arena_deserializer::arena", borrow)] Map<'a, K, ()>,
);
impl<'a, K> Clone for Set<'a, K> {
fn clone(&self) -> Self {
Set(self.0.clone())
}
}
arena_deserializer::impl_deserialize_in_arena!(Set<'arena, K>);
impl<'a, K> Copy for Set<'a, K> {}
impl<'a, K> TrivialDrop for Set<'a, K> {}
impl<K> Default for Set<'_, K> {
fn default() -> Self {
Set(Map::default())
}
}
impl<K: ToOcamlRep + Ord> ToOcamlRep for Set<'_, K> {
fn to_ocamlrep<'a, A: ocamlrep::Allocator>(&'a self, alloc: &'a A) -> ocamlrep::Value<'a> {
let len = self.count();
let mut iter = self.iter().map(|x| x.to_ocamlrep(alloc));
let (value, _) = ocamlrep::sorted_iter_to_ocaml_set(&mut iter, alloc, len);
value
}
}
impl<'a, K> FromOcamlRepIn<'a> for Set<'a, K>
where
K: FromOcamlRepIn<'a> + Ord + TrivialDrop + Clone,
{
fn from_ocamlrep_in(
value: ocamlrep::Value<'_>,
alloc: &'a bumpalo::Bump,
) -> Result<Self, ocamlrep::FromError> {
// TODO: This is a bit wasteful. If we had iter_from_ocaml_set_in
// instead, we wouldn't need the extra vec.
let mut elements = bumpalo::collections::Vec::new_in(alloc);
ocamlrep::vec_from_ocaml_set_in(value, &mut elements, alloc)?;
let mut set = Set::empty();
for element in elements {
set = set.add(alloc, element);
}
Ok(set)
}
}
#[macro_export]
macro_rules! set {
( ) => ({ Set::empty() });
( $arena:expr; $($x:expr),* ) => ({
let mut temp_map = Set::empty();
$(
temp_map = temp_map.add($arena, $x);
)*
temp_map
});
}
impl<'a, K: Ord> Set<'a, K> {
pub fn mem(self, x: &K) -> bool {
self.0.mem(x)
}
pub fn intersection(self, other: Self) -> Intersection<'a, K> {
Intersection {
iter: self.iter(),
other,
}
}
}
impl<'a, K> Set<'a, K> {
pub const fn empty() -> Self {
Set(Map::empty())
}
pub fn count(self) -> usize {
self.0.count()
}
}
impl<'a, K: Ord> Set<'a, K> {
pub fn is_empty(self) -> bool {
self.0.is_empty()
}
}
impl<'a, K: TrivialDrop + Clone + Ord> Set<'a, K> {
pub fn singleton<A: Arena>(arena: &'a A, x: K) -> Self {
Set(Map::singleton(arena, x, ()))
}
pub fn from<A: Arena, I>(arena: &'a A, i: I) -> Self
where
I: IntoIterator<Item = K>,
{
let mut s = Self::empty();
for k in i {
s = s.add(arena, k);
}
s
}
pub fn add<A: Arena>(self, arena: &'a A, x: K) -> Self {
Set(self.0.add(arena, x, ()))
}
pub fn remove<A: Arena>(self, arena: &'a A, x: &K) -> Self {
Set(self.0.remove(arena, x))
}
pub fn min_entry(self) -> Option<&'a K> {
let v = self.0.min_entry();
v.map(|(k, _)| k)
}
pub fn remove_min_entry<A: Arena>(self, arena: &'a A) -> Self {
Set(self.0.remove_min_entry(arena))
}
pub fn max_entry(self) -> Option<&'a K> {
let v = self.0.max_entry();
v.map(|(k, _)| k)
}
/// Remove the maximum key-value entry.
pub fn remove_max_entry<A: Arena>(self, arena: &'a A) -> Self {
Set(self.0.remove_max_entry(arena))
}
pub fn diff<A: Arena>(self, arena: &'a A, other: Self) -> Self {
Set(self.0.diff(arena, other.0))
}
}
impl<'a, T> Set<'a, T> {
pub fn iter(&self) -> SetIter<'a, T> {
SetIter {
iter: self.0.iter(),
}
}
}
/// Iterator state for set.
pub struct SetIter<'a, K> {
iter: MapIter<'a, K, ()>,
}
impl<'a, K> IntoIterator for &Set<'a, K> {
type Item = &'a K;
type IntoIter = SetIter<'a, K>;
fn into_iter(self) -> Self::IntoIter {
SetIter {
iter: self.0.into_iter(),
}
}
}
impl<'a, K> Iterator for SetIter<'a, K> {
type Item = &'a K;
fn next(&mut self) -> Option<Self::Item> {
match self.iter.next() {
None => None,
Some((k, _)) => Some(k),
}
}
}
pub struct Intersection<'a, T> {
iter: SetIter<'a, T>,
other: Set<'a, T>,
}
impl<'a, T: Ord> Iterator for Intersection<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.iter.by_ref().find(|&x| self.other.mem(x))
}
}
#[cfg(test)]
pub mod tests_macro {
use bumpalo::Bump;
use super::*;
#[test]
fn test_empty() {
assert_eq!(set![], Set::<i32>::empty());
}
#[test]
fn test_non_empty() {
let a = Bump::new();
assert_eq!(set![&a; 5, 3, 9, 4], Set::<i32>::from(&a, vec![3, 4, 5, 9]));
}
}
#[cfg(test)]
pub mod tests_iter {
use bumpalo::Bump;
use super::*;
#[test]
fn test_empty() {
let s: Set<'_, i32> = set![];
assert!(s.into_iter().copied().eq(vec![].into_iter()));
}
#[test]
fn test_non_empty() {
let a = Bump::new();
let s: Set<'_, i32> = set![&a; 6, 4, 5];
assert!(s.into_iter().copied().eq(vec![4, 5, 6].into_iter()));
}
} |
Rust | hhvm/hphp/hack/src/arena_collections/test_alist.rs | // 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.
use crate::AssocList;
#[test]
fn get_with_duplicate_keys() {
let entries = [(1, "a"), (1, "b")];
let alist = AssocList::new(&entries[..]);
assert_eq!(alist.get(&1), Some(&"b"));
}
#[test]
fn get_key_value_with_duplicate_keys() {
let entries = [(1, "a"), (1, "b")];
let alist = AssocList::new(&entries[..]);
assert_eq!(alist.get_key_value(&1), Some((&1, &"b")));
}
#[test]
fn len_with_duplicate_keys() {
let entries = [(1, "a"), (1, "b"), (2, "c")];
let alist = AssocList::new(&entries[..]);
assert_eq!(alist.len(), 3);
}
// Doctests ////////////////////////////////////////////////////////////////////
// The tests below are copied from doc comments. We should eventually be able to
// run doctests as Buck tests, and at that time we can remove these test cases.
#[test]
fn get() {
let entries = [(1, "a")];
let alist = AssocList::new(&entries[..]);
assert_eq!(alist.get(&1), Some(&"a"));
assert_eq!(alist.get(&2), None);
}
#[test]
fn get_key_value() {
let entries = [(1, "a")];
let alist = AssocList::new(&entries[..]);
assert_eq!(alist.get_key_value(&1), Some((&1, &"a")));
assert_eq!(alist.get_key_value(&2), None);
}
#[test]
fn contains_key() {
let entries = [(1, "a")];
let alist = AssocList::new(&entries[..]);
assert!(alist.contains_key(&1));
assert!(!alist.contains_key(&2));
}
#[test]
fn iter() {
let entries = [(1, "a"), (2, "b")];
let alist = AssocList::new(&entries[..]);
let (first_key, first_value) = alist.iter().next().unwrap();
assert_eq!((*first_key, *first_value), (1, "a"));
}
#[test]
fn keys() {
let entries = [(1, "a"), (2, "b")];
let alist = AssocList::new(&entries[..]);
let keys: Vec<_> = alist.keys().copied().collect();
assert_eq!(keys, [1, 2]);
}
#[test]
fn values() {
let entries = [(1, "hello"), (2, "goodbye")];
let alist = AssocList::new(&entries[..]);
let values: Vec<&str> = alist.values().copied().collect();
assert_eq!(values, ["hello", "goodbye"]);
}
#[test]
fn len() {
let entries = [(1, "a")];
let alist = AssocList::new(&entries[0..0]);
assert_eq!(alist.len(), 0);
let alist = AssocList::new(&entries[0..1]);
assert_eq!(alist.len(), 1);
}
#[test]
fn is_empty() {
let entries = [(1, "a")];
let alist = AssocList::new(&entries[0..0]);
assert!(alist.is_empty());
let alist = AssocList::new(&entries[0..1]);
assert!(!alist.is_empty());
} |
Rust | hhvm/hphp/hack/src/arena_collections/test_alist_mut.rs | // 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.
use bumpalo::Bump;
use crate::AssocList;
use crate::AssocListMut;
use crate::SortedAssocList;
// Doctests ////////////////////////////////////////////////////////////////////
// The tests below are copied from doc comments. We should eventually be able to
// run doctests as Buck tests, and at that time we can remove these test cases.
#[test]
fn with_capacity_in() {
let b = Bump::new();
let mut alist = AssocListMut::with_capacity_in(10, &b);
// The list contains no items, even though it has capacity for more
assert_eq!(alist.len(), 0);
// These are all done without reallocating...
for i in 0..10 {
alist.insert(i, i);
}
// ...but this may make the list reallocate
alist.insert(11, 11);
}
#[test]
fn insert() {
let b = Bump::new();
let mut alist = AssocListMut::new_in(&b);
alist.insert(1, "a");
assert_eq!(alist.get(&1), Some(&"a"));
alist.insert(1, "b");
assert_eq!(alist.get(&1), Some(&"b"));
assert_eq!(alist.len(), 2);
}
#[test]
fn insert_or_replace() {
let b = Bump::new();
let mut alist = AssocListMut::new_in(&b);
alist.insert_or_replace(1, "a");
assert_eq!(alist.get(&1), Some(&"a"));
alist.insert_or_replace(1, "b");
assert_eq!(alist.get(&1), Some(&"b"));
assert_eq!(alist.len(), 1);
}
#[test]
fn remove() {
let b = Bump::new();
let mut alist = AssocListMut::new_in(&b);
alist.insert(1, "a");
alist.insert(1, "b");
assert_eq!(alist.get(&1), Some(&"b"));
alist.remove(&1);
assert_eq!(alist.get(&1), Some(&"a"));
alist.remove(&1);
assert_eq!(alist.get(&1), None);
}
#[test]
fn remove_all() {
let b = Bump::new();
let mut alist = AssocListMut::new_in(&b);
alist.insert(1, "a");
alist.insert(1, "b");
assert_eq!(alist.get(&1), Some(&"b"));
alist.remove_all(&1);
assert_eq!(alist.get(&1), None);
}
#[test]
fn into() {
let b = Bump::new();
let mut alist = AssocListMut::new_in(&b);
alist.insert(1, "a");
let alist: AssocList<'_, _, _> = alist.into();
let entries = [(1, "a")];
assert_eq!(alist, AssocList::new(&entries[..]));
}
#[test]
fn get() {
let b = Bump::new();
let mut alist = AssocListMut::new_in(&b);
alist.insert(1, "a");
assert_eq!(alist.get(&1), Some(&"a"));
assert_eq!(alist.get(&2), None);
let alist = SortedAssocList::from(alist);
assert_eq!(alist.get(&1), Some(&"a"));
assert_eq!(alist.get(&2), None);
}
#[test]
fn get_key_value() {
let b = Bump::new();
let mut alist = AssocListMut::new_in(&b);
alist.insert(1, "a");
assert_eq!(alist.get_key_value(&1), Some((&1, &"a")));
assert_eq!(alist.get_key_value(&2), None);
let alist = SortedAssocList::from(alist);
assert_eq!(alist.get_key_value(&1), Some((&1, &"a")));
assert_eq!(alist.get_key_value(&2), None);
}
#[test]
fn contains_key() {
let b = Bump::new();
let mut alist = AssocListMut::new_in(&b);
alist.insert(1, "a");
assert!(alist.contains_key(&1));
assert!(!alist.contains_key(&2));
let alist = SortedAssocList::from(alist);
assert!(alist.contains_key(&1));
assert!(!alist.contains_key(&2));
}
#[test]
fn iter() {
let b = Bump::new();
let mut alist = AssocListMut::new_in(&b);
alist.insert(1, "a");
alist.insert(2, "b");
let (first_key, first_value) = alist.iter().next().unwrap();
assert_eq!((*first_key, *first_value), (1, "a"));
let alist = SortedAssocList::from(alist);
let (first_key, first_value) = alist.iter().next().unwrap();
assert_eq!((*first_key, *first_value), (1, "a"));
}
#[test]
fn keys() {
let b = Bump::new();
let mut alist = AssocListMut::new_in(&b);
alist.insert(1, "a");
alist.insert(2, "b");
let keys: Vec<_> = alist.keys().copied().collect();
assert_eq!(keys, [1, 2]);
let alist = SortedAssocList::from(alist);
let keys: Vec<_> = alist.keys().copied().collect();
assert_eq!(keys, [1, 2]);
}
#[test]
fn values() {
let b = Bump::new();
let mut alist = AssocListMut::new_in(&b);
alist.insert(1, "hello");
alist.insert(2, "goodbye");
let values: Vec<&str> = alist.values().copied().collect();
assert_eq!(values, ["hello", "goodbye"]);
let alist = SortedAssocList::from(alist);
let values: Vec<&str> = alist.values().copied().collect();
assert_eq!(values, ["hello", "goodbye"]);
}
#[test]
fn len() {
let b = Bump::new();
let alist: AssocListMut<'_, i32, i32> = AssocListMut::new_in(&b);
assert_eq!(alist.len(), 0);
let alist = SortedAssocList::from(alist);
assert_eq!(alist.len(), 0);
let mut alist = AssocListMut::new_in(&b);
alist.insert(1, "a");
assert_eq!(alist.len(), 1);
let alist = SortedAssocList::from(alist);
assert_eq!(alist.len(), 1);
}
#[test]
fn is_empty() {
let b = Bump::new();
let alist: AssocListMut<'_, i32, i32> = AssocListMut::new_in(&b);
assert!(alist.is_empty());
let alist = SortedAssocList::from(alist);
assert!(alist.is_empty());
let mut alist = AssocListMut::new_in(&b);
alist.insert(1, "a");
assert!(!alist.is_empty());
let alist = SortedAssocList::from(alist);
assert!(!alist.is_empty());
} |
Rust | hhvm/hphp/hack/src/arena_collections/test_list.rs | // 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.
use bumpalo::Bump;
use crate::list::List;
macro_rules! sl {
() => { List::Nil::<i32> };
($($xs:expr $(,)?)+) => { stack_list![$($xs,)*] };
}
#[test]
fn test_size() {
// List's variants are Nil and Cons(&_). Since there's only one nullary
// variant (Nil), and only one variant with an argument (Cons), and Cons
// contains a (non-nullable) reference, List benefits from the
// null-pointer-optimization. Cons is represented with just a reference, and
// Nil is represented with the null pointer. As a result, any List is the
// size of a pointer.
assert_eq!(
std::mem::size_of::<List<'_, i32>>(),
std::mem::size_of::<*const u8>()
);
}
#[test]
fn cons() {
let a = &Bump::new();
assert_eq!(List::cons(3, List::Nil, a), sl![3]);
assert_eq!(List::cons(3, sl![2, 1], a), sl![3, 2, 1]);
}
#[test]
fn len() {
assert_eq!(sl![].len(), 0);
assert_eq!(sl![1].len(), 1);
assert_eq!(sl![1, 2].len(), 2);
assert_eq!(sl![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].len(), 10);
}
#[test]
fn is_empty() {
assert!(sl![].is_empty());
assert!(!sl![1].is_empty());
assert!(!sl![1, 2].is_empty());
assert!(!sl![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].is_empty());
}
#[test]
fn hd() {
assert_eq!(sl![].hd(), None);
assert_eq!(sl![42].hd(), Some(&42));
assert_eq!(sl![19, 84].hd(), Some(&19));
}
#[test]
fn tl() {
assert_eq!(sl![].tl(), None);
assert_eq!(sl![42].tl(), Some(sl![]));
assert_eq!(sl![19, 84].tl(), Some(sl![84]));
}
#[test]
fn nth() {
assert_eq!(sl![].nth(0), None);
assert_eq!(sl![].nth(1), None);
assert_eq!(sl![1].nth(0), Some(&1));
assert_eq!(sl![1].nth(1), None);
assert_eq!(sl![1, 2].nth(0), Some(&1));
assert_eq!(sl![1, 2].nth(1), Some(&2));
assert_eq!(sl![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].nth(9), Some(&10));
assert_eq!(sl![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].nth(10), None);
}
#[test]
fn rev() {
let a = &Bump::new();
assert_eq!(sl![].rev(a), sl![]);
assert_eq!(sl![1].rev(a), sl![1]);
assert_eq!(sl![1, 2].rev(a), sl![2, 1]);
assert_eq!(
sl![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].rev(a),
sl![10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
);
}
#[test]
fn append() {
let a = &Bump::new();
assert_eq!(sl![].append(sl![], a), sl![]);
assert_eq!(sl![].append(sl![42], a), sl![42]);
assert_eq!(sl![42].append(sl![], a), sl![42]);
assert_eq!(sl![19].append(sl![84], a), sl![19, 84]);
assert_eq!(sl![19, 84].append(sl![22, 66], a), sl![19, 84, 22, 66]);
assert_eq!(List::init(2, |x| x, a).append(sl![42], a), sl![0, 1, 42]);
assert_eq!(List::init(3, |x| x, a).append(sl![42], a), sl![0, 1, 2, 42]);
assert_eq!(
List::init(4, |x| x, a).append(sl![42], a),
sl![0, 1, 2, 3, 42]
);
assert_eq!(
List::init(5, |x| x, a).append(sl![42], a),
sl![0, 1, 2, 3, 4, 42]
);
assert_eq!(
List::init(6, |x| x, a).append(sl![42], a),
sl![0, 1, 2, 3, 4, 5, 42]
);
assert_eq!(
List::init(7, |x| x, a).append(sl![42], a),
sl![0, 1, 2, 3, 4, 5, 6, 42]
);
assert_eq!(
List::init(8, |x| x, a).append(sl![42], a),
sl![0, 1, 2, 3, 4, 5, 6, 7, 42]
);
assert_eq!(
List::init(9, |x| x, a).append(sl![42], a),
sl![0, 1, 2, 3, 4, 5, 6, 7, 8, 42]
);
assert_eq!(
List::init(10, |x| x, a).append(sl![42], a),
sl![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 42]
);
// After appending l1, l2 physically points to l1 as a suffix
// (i.e., append does not clone the elements of l1).
let l1 = sl![22, 66];
let l2 = sl![42].append(l1, a);
assert_eq!(
l1.nth(0).unwrap() as *const i32,
l2.nth(1).unwrap() as *const i32
);
// A naive recursive implementation of `append` would blow the stack here.
assert_eq!(
List::init(1_000_000, |x| x, a)
.append(sl![1, 2, 3, 4, 5, 6, 7], a)
.len(),
1_000_007
);
}
#[test]
fn rev_append() {
let a = &Bump::new();
assert_eq!(sl![].rev_append(sl![], a), sl![]);
assert_eq!(sl![].rev_append(sl![42], a), sl![42]);
assert_eq!(sl![42].rev_append(sl![], a), sl![42]);
assert_eq!(sl![19].rev_append(sl![84], a), sl![19, 84]);
assert_eq!(sl![19, 84].rev_append(sl![22, 66], a), sl![84, 19, 22, 66]);
// After appending l1, l2 physically points to l1 as a suffix
// (i.e., rev_append does not clone the elements of l1).
let l1 = sl![22, 66];
let l2 = sl![42].rev_append(l1, a);
assert_eq!(
l1.nth(0).unwrap() as *const i32,
l2.nth(1).unwrap() as *const i32
);
}
#[test]
fn init() {
let a = &Bump::new();
assert_eq!(List::init(0, |_| 42, a), sl![]);
assert_eq!(List::init(1, |_| 42, a), sl![42]);
assert_eq!(List::init(2, |x| x as i32, a), sl![0, 1]);
assert_eq!(List::init(3, |x| x as i32, a), sl![0, 1, 2]);
assert_eq!(List::init(100_000, |x| x, a).len(), 100_000);
// Evaluation order is right to left (i.e., the last element of the list is
// produced first).
let mut n = 0;
#[rustfmt::skip]
assert_eq!(List::init(0, |_| { n += 1; n }, a), sl![]);
assert_eq!(n, 0);
#[rustfmt::skip]
assert_eq!(List::init(3, |_| { n += 1; n }, a), sl![3, 2, 1]);
assert_eq!(n, 3);
assert_eq!(list![in a; 42; 3], sl![42, 42, 42]);
}
#[test]
fn iter() {
let mut iter = sl![].iter().map(|x| x * x);
assert_eq!(iter.next(), None);
let mut iter = sl![1, 2, 3].iter().map(|x| x * x);
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(4));
assert_eq!(iter.next(), Some(9));
assert_eq!(iter.next(), None);
}
#[test]
fn contains() {
assert!(!sl![].contains(&42));
assert!(sl![42].contains(&42));
assert!(!sl![42].contains(&66));
assert!(sl![19, 84].contains(&19));
assert!(sl![19, 84].contains(&84));
assert!(!sl![19, 84].contains(&42));
}
#[test]
fn find() {
assert_eq!(sl![].find(|&x| x == 42), None);
assert_eq!(sl![42].find(|&x| x == 42), Some(&42));
assert_eq!(sl![42].find(|&x| x == 66), None);
assert_eq!(sl![19, 84].find(|&x| x == 19), Some(&19));
assert_eq!(sl![19, 84].find(|&x| x == 84), Some(&84));
assert_eq!(sl![19, 84].find(|&x| x == 42), None);
}
#[test]
fn rev_from_iter_in() {
let a = &Bump::new();
assert_eq!(List::rev_from_iter_in(vec![], a), sl![]);
assert_eq!(List::rev_from_iter_in(vec![1], a), sl![1]);
assert_eq!(List::rev_from_iter_in(vec![1, 2], a), sl![2, 1]);
assert_eq!(List::rev_from_iter_in(vec![1, 2, 3], a), sl![3, 2, 1]);
}
#[test]
fn into_iter() {
let mut expected = 1;
for &x in sl![1, 2, 3] {
assert_eq!(x, expected);
expected += 1;
}
}
#[test]
fn debug() {
assert_eq!(format!("{:?}", sl![]), "[]");
assert_eq!(format!("{:?}", sl![1, 2, 3]), "[1, 2, 3]");
} |
Rust | hhvm/hphp/hack/src/arena_collections/test_multiset.rs | // 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.
use bumpalo::Bump;
use crate::MultiSet;
use crate::MultiSetMut;
use crate::SortedSet;
// Doctests ////////////////////////////////////////////////////////////////////
// The tests below are copied from doc comments. We should eventually be able to
// run doctests as Buck tests, and at that time we can remove these test cases.
#[test]
fn contains() {
let b = Bump::new();
let mut set = MultiSetMut::new_in(&b);
set.insert(1);
assert!(set.contains(&1));
let set = MultiSet::from(set);
assert!(set.contains(&1));
}
#[test]
fn iter() {
let b = Bump::new();
let mut set = MultiSetMut::new_in(&b);
set.insert(3);
set.insert(1);
set.insert(2);
{
let mut set_iter = set.iter();
assert_eq!(set_iter.next(), Some(&3));
assert_eq!(set_iter.next(), Some(&1));
assert_eq!(set_iter.next(), Some(&2));
assert_eq!(set_iter.next(), None);
}
let set = MultiSet::from(set);
let mut set_iter = set.iter();
assert_eq!(set_iter.next(), Some(&3));
assert_eq!(set_iter.next(), Some(&1));
assert_eq!(set_iter.next(), Some(&2));
assert_eq!(set_iter.next(), None);
}
#[test]
fn iter_sorted() {
let b = Bump::new();
let mut set = MultiSetMut::new_in(&b);
set.insert(3);
set.insert(1);
set.insert(2);
let set = SortedSet::from(set);
let mut set_iter = set.iter();
assert_eq!(set_iter.next(), Some(&1));
assert_eq!(set_iter.next(), Some(&2));
assert_eq!(set_iter.next(), Some(&3));
assert_eq!(set_iter.next(), None);
}
#[test]
fn len() {
let b = Bump::new();
let mut set = MultiSetMut::new_in(&b);
assert_eq!(set.len(), 0);
set.insert(1);
assert_eq!(set.len(), 1);
set.insert(1);
assert_eq!(set.len(), 2);
set.insert(2);
assert_eq!(set.len(), 3);
let set = MultiSet::from(set);
assert_eq!(set.len(), 3);
}
#[test]
fn len_sorted() {
let b = Bump::new();
let mut set = MultiSetMut::new_in(&b);
set.insert(1);
set.insert(2);
set.insert(1);
let set = SortedSet::from(set);
assert_eq!(set.len(), 2);
}
#[test]
fn from_slice() {
const EMPTY_MULTISET: MultiSet<'_, i32> = MultiSet::from_slice(&[]);
assert!(EMPTY_MULTISET.is_empty());
const EMPTY_SORTED_SET: SortedSet<'_, i32> = SortedSet::from_slice(&[]);
assert!(EMPTY_SORTED_SET.is_empty());
}
#[test]
fn insert() {
let b = Bump::new();
let mut set = MultiSetMut::new_in(&b);
assert!(!set.contains(&1));
set.insert(1);
assert!(set.contains(&1));
}
#[test]
fn remove() {
let b = Bump::new();
let mut set = MultiSetMut::new_in(&b);
set.insert(2);
assert!(set.remove(&2));
assert!(!set.remove(&2));
}
#[test]
fn remove_all() {
let b = Bump::new();
let mut set = MultiSetMut::new_in(&b);
set.insert(2);
set.insert(2);
assert!(set.remove_all(&2));
assert!(!set.remove_all(&2));
} |
Rust | hhvm/hphp/hack/src/arena_collections/test_sorted_alist.rs | // 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.
use bumpalo::Bump;
use crate::AssocListMut;
use crate::SortedAssocList;
fn new<'a, K: Copy + Ord, V: Copy>(
b: &'a Bump,
entries: &'a [(K, V)],
) -> SortedAssocList<'a, K, V> {
let mut alist = AssocListMut::new_in(b);
for (key, value) in entries {
alist.insert(*key, *value);
}
alist.into()
}
#[test]
fn get_with_duplicate_keys() {
let b = Bump::new();
let alist = new(
&b,
&[(1, "a"), (2, "x"), (1, "b"), (0, "y"), (1, "c"), (3, "z")],
);
assert_eq!(alist.get(&1), Some(&"c"));
}
#[test]
fn get_key_value_with_duplicate_keys() {
let b = Bump::new();
let alist = new(
&b,
&[(1, "a"), (2, "x"), (1, "b"), (0, "y"), (1, "c"), (3, "z")],
);
assert_eq!(alist.get_key_value(&1), Some((&1, &"c")));
}
#[test]
fn len_with_duplicate_keys() {
let b = Bump::new();
let alist = new(&b, &[(1, "a"), (1, "b"), (2, "z")]);
assert_eq!(alist.len(), 2);
}
#[test]
fn get_with_many_entries() {
let b = &Bump::new();
let mut entries = bumpalo::collections::Vec::new_in(b);
for i in 0..1024 {
entries.push((i, &*b.alloc_str(i.to_string().as_str())))
}
let alist = new(b, &entries[..]);
for i in 0..1024 {
assert_eq!(alist.get(&i), Some(&i.to_string().as_str()));
}
}
// Doctests ////////////////////////////////////////////////////////////////////
// The tests below are copied from doc comments. We should eventually be able to
// run doctests as Buck tests, and at that time we can remove these test cases.
// Other doctests for SortedAssocList are located in the test_alist_mut module.
#[test]
fn from_slice() {
const EMPTY_ALIST: SortedAssocList<'_, i32, i32> = SortedAssocList::from_slice(&[]);
assert!(EMPTY_ALIST.is_empty());
} |
Rust | hhvm/hphp/hack/src/arena_collections/vec.rs | // 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.
use std::ops::Deref;
use std::slice;
use bumpalo::collections::vec::IntoIter;
use bumpalo::collections::Vec as BVec;
use bumpalo::Bump;
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Vec<'a, T>(BVec<'a, T>);
#[macro_export]
macro_rules! pvec {
(in $arena: expr) => {
Vec::new_in($arena);
};
(in $arena: expr; $($x:expr),*) => {{
let mut v = bumpalo::collections::Vec::new_in($arena);
$(v.push($x);)*
Vec::from(v)
}};
}
impl<'a, T: 'a> Deref for Vec<'a, T> {
type Target = [T];
fn deref(&self) -> &<Self as Deref>::Target {
self.0.deref()
}
}
impl<'a, T: 'a> IntoIterator for Vec<'a, T> {
type Item = T;
type IntoIter = IntoIter<'a, T>;
fn into_iter(self) -> IntoIter<'a, T> {
self.0.into_iter()
}
}
impl<'a, 'bump, T> IntoIterator for &'a Vec<'bump, T> {
type Item = &'a T;
type IntoIter = slice::Iter<'a, T>;
fn into_iter(self) -> slice::Iter<'a, T> {
self.iter()
}
}
impl<'a, T> From<BVec<'a, T>> for Vec<'a, T> {
fn from(v: BVec<'a, T>) -> Self {
Vec(v)
}
}
impl<'a, T: 'a> Vec<'a, T> {
pub fn new_in(arena: &'a Bump) -> Self {
Vec(BVec::new_in(arena))
}
}
impl<'a, T: 'a + Copy> Vec<'a, T> {
pub fn append(&self, arena: &'a Bump, other: &Self) -> Self {
Vec(BVec::from_iter_in(
self.0.iter().chain(other.0.iter()).copied(),
arena,
))
}
} |
TOML | hhvm/hphp/hack/src/arena_trait/Cargo.toml | # @generated by autocargo
[package]
name = "arena_trait"
version = "0.0.0"
edition = "2021"
[lib]
path = "lib.rs"
[dependencies]
bumpalo = { version = "3.11.1", features = ["collections"] } |
Rust | hhvm/hphp/hack/src/arena_trait/lib.rs | // 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.
#![deny(clippy::mut_from_ref)]
use bumpalo::Bump;
pub trait Arena {
#[allow(clippy::mut_from_ref)]
fn alloc<T: TrivialDrop>(&self, val: T) -> &mut T;
}
impl Arena for Bump {
#[allow(clippy::mut_from_ref)]
#[inline(always)]
fn alloc<T: TrivialDrop>(&self, val: T) -> &mut T {
self.alloc(val)
}
}
/// Marker trait for types whose implementation of `Drop` is a no-op.
///
/// Used to denote types which can be moved into an arena (which does not drop
/// its contents) without leaking memory.
///
/// Must not be implemented for any type which owns heap memory or otherwise
/// needs to run cleanup in its `Drop` implementation (e.g., `Box`, `Vec`,
/// `std::fs::File`, etc.), or any type containing a field with such a
/// nontrivial `Drop` implementation.
pub trait TrivialDrop {}
impl TrivialDrop for () {}
impl TrivialDrop for bool {}
impl TrivialDrop for usize {}
impl TrivialDrop for u8 {}
impl TrivialDrop for u16 {}
impl TrivialDrop for u32 {}
impl TrivialDrop for u64 {}
impl TrivialDrop for u128 {}
impl TrivialDrop for isize {}
impl TrivialDrop for i8 {}
impl TrivialDrop for i16 {}
impl TrivialDrop for i32 {}
impl TrivialDrop for i64 {}
impl TrivialDrop for i128 {}
impl TrivialDrop for f32 {}
impl TrivialDrop for f64 {}
impl TrivialDrop for str {}
impl TrivialDrop for &str {}
impl<T: TrivialDrop> TrivialDrop for [T] {}
impl<T> TrivialDrop for &[T] {}
impl<T: Sized> TrivialDrop for &T {}
impl<T: TrivialDrop> TrivialDrop for Option<T> {}
impl<T: TrivialDrop, E: TrivialDrop> TrivialDrop for Result<T, E> {}
impl<T0, T1> TrivialDrop for (T0, T1)
where
T0: TrivialDrop,
T1: TrivialDrop,
{
}
impl<T0, T1, T2> TrivialDrop for (T0, T1, T2)
where
T0: TrivialDrop,
T1: TrivialDrop,
T2: TrivialDrop,
{
}
impl<T0, T1, T2, T3> TrivialDrop for (T0, T1, T2, T3)
where
T0: TrivialDrop,
T1: TrivialDrop,
T2: TrivialDrop,
T3: TrivialDrop,
{
}
impl<T0, T1, T2, T3, T4> TrivialDrop for (T0, T1, T2, T3, T4)
where
T0: TrivialDrop,
T1: TrivialDrop,
T2: TrivialDrop,
T3: TrivialDrop,
T4: TrivialDrop,
{
}
impl<T0, T1, T2, T3, T4, T5> TrivialDrop for (T0, T1, T2, T3, T4, T5)
where
T0: TrivialDrop,
T1: TrivialDrop,
T2: TrivialDrop,
T3: TrivialDrop,
T4: TrivialDrop,
T5: TrivialDrop,
{
}
impl<T0, T1, T2, T3, T4, T5, T6> TrivialDrop for (T0, T1, T2, T3, T4, T5, T6)
where
T0: TrivialDrop,
T1: TrivialDrop,
T2: TrivialDrop,
T3: TrivialDrop,
T4: TrivialDrop,
T5: TrivialDrop,
T6: TrivialDrop,
{
}
impl<T0, T1, T2, T3, T4, T5, T6, T7> TrivialDrop for (T0, T1, T2, T3, T4, T5, T6, T7)
where
T0: TrivialDrop,
T1: TrivialDrop,
T2: TrivialDrop,
T3: TrivialDrop,
T4: TrivialDrop,
T5: TrivialDrop,
T6: TrivialDrop,
T7: TrivialDrop,
{
} |
Rust | hhvm/hphp/hack/src/asdl_to_rust/asdl/asdl.rs | // 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.
// The files generated by lrgen rely on this now-discouraged elision feature
#![allow(elided_lifetimes_in_paths)]
pub mod lexer;
pub mod parser; |
Rust | hhvm/hphp/hack/src/asdl_to_rust/asdl/lexer.rs | // 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.
include!(concat!(env!("ASDL_GEN_OUT_DIR"), "/", "asdl_l.rs"));
pub use asdl_l::*; |
Rust | hhvm/hphp/hack/src/asdl_to_rust/asdl/parser.rs | // 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.
include!(concat!(env!("ASDL_GEN_OUT_DIR"), "/", "asdl_y.rs"));
pub use asdl_y::*; |
Rust | hhvm/hphp/hack/src/asdl_to_rust/asdl_to_rust/asdl_to_rust.rs | // 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.
// e.g. cd ~/fbsource && buck2 run fbcode//hphp/hack/src/asdl_to_rust:asdl_to_rust -- --rustfmt-path $(which rustfmt) fbcode/hphp/hack/src/asdl_to_rust/python/v3.10.0.asdl
use std::io::Read;
use std::io::Write;
use convert_case::Case;
use convert_case::Casing;
/// Generate Rust datatypes for abstract syntax defined by ASDL.
#[derive(Debug, clap::Parser)]
struct Opts {
src: std::path::PathBuf,
#[clap(short, long)]
rustfmt_path: std::path::PathBuf,
}
fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
let opts = parse_opts()?;
let lexerdef = asdl::lexer::lexerdef();
let asdl = std::fs::read_to_string(&opts.src)?;
let lexer = lexerdef.lexer(&asdl);
let (res, errs) = asdl::parser::parse(&lexer);
for e in errs {
println!("{}", e.pp(&lexer, &asdl::parser::token_epp));
}
let mut out_file = tempfile::NamedTempFile::new()?;
match res {
Some(modu) => {
//println!("Result: {:#?}", r),
types_of_asdl(&modu.ok().unwrap(), &mut out_file)?;
let _status = std::process::Command::new(&opts.rustfmt_path)
.arg(out_file.path())
.status()
.expect("failed to execute rustfmt");
let mut in_file = out_file.reopen()?;
let mut buf = String::new();
in_file.read_to_string(&mut buf)?;
std::io::stdout().write_all(buf.as_bytes())?;
}
_ => eprintln!("Unable to evaluate expression."),
}
Ok(())
}
fn parse_opts() -> Result<Opts, std::io::Error> {
let opts = <Opts as clap::Parser>::parse();
let src = &opts.src;
std::fs::metadata(src)?;
Ok(opts)
}
fn types_of_asdl(
modu: &asdl::parser::ast::Module,
w: &mut dyn std::io::Write,
) -> std::io::Result<()> {
for def in &modu.definitions {
type_declaration_of_definition(def, w)?;
}
Ok(())
}
fn type_declaration_of_definition(
def: &asdl::parser::ast::Definition,
w: &mut dyn std::io::Write,
) -> std::io::Result<()> {
let s: &str = &def.type_id;
let typename: String = make_valid_type_name(s);
match &def.desc {
asdl::parser::ast::Desc::Product(asdl::parser::ast::Product(fields)) => {
w.write_all(TYPE_HERALD)?;
write!(w, "pub struct {} {{", typename)?;
for f in fields {
label_declaration_of_field(f, w)?;
}
write!(w, "}}\n")?;
}
asdl::parser::ast::Desc::Sum(_) => {}
};
Ok(())
}
fn label_declaration_of_field(
field: &asdl::parser::ast::Field,
w: &mut dyn std::io::Write,
) -> std::io::Result<()> {
let id = make_valid_label(&field.id);
let typ_id = type_of_field(field);
match field.modifier {
Some(ref u) => match u {
asdl::parser::ast::Modifier::Star => write!(w, "pub {id}: Vec<{typ_id}>,"),
asdl::parser::ast::Modifier::Question => write!(w, "pub {id}: Option<{typ_id}>,"),
},
None => write!(w, "pub {id}: {typ_id},\n"),
}?;
Ok(())
}
fn type_of_field(field: &asdl::parser::ast::Field) -> String {
match kind_of_field(field) {
Kind::String => "String".to_owned(),
Kind::Int => "isize".to_owned(),
Kind::Bool => "bool".to_owned(),
Kind::Type(s) => s,
}
}
enum Kind {
String,
Bool,
Int,
Type(String),
}
fn kind_of_field(field: &asdl::parser::ast::Field) -> Kind {
match field.type_id.as_str() {
"string" | "bytes" | "identifier" => Kind::String,
"int" => match field.id.as_str() {
"is_async" => Kind::Bool,
_ => Kind::Int,
},
"bool" => Kind::Bool,
_ => Kind::Type(make_valid_type_name(&field.type_id)),
}
}
// ---
fn make_valid_label(s: &str) -> String {
let t = s.to_case(Case::Snake);
match t.as_str() {
s if RUST_KEYWORDS.contains(&s) => s.to_owned() + "_",
_ => t,
}
}
fn make_valid_type_name(s: &str) -> String {
s.to_case(Case::Pascal)
}
static TYPE_HERALD: &[u8] = b"
#[derive(Clone, Debug, PartialEq, PartialOrd)]\n
#[derive(Serialize, Deserialize, ToOcamlRep, FromOcamlRep)]\n
#[rust_to_ocaml(and)]";
static RUST_KEYWORDS: &[&str] = &[
"as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for",
"if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return",
"self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where",
"while", "dyn", "abstract", "become", "box", "do", "final", "macro", "override", "priv",
"typeof", "unsized", "virtual", "yield", "async", "await", "try", "union",
]; |
hhvm/hphp/hack/src/asdl_to_rust/grammar/asdl.l | %%
module "MODULE"
attributes "ATTRIBUTES"
version "VERSION"
[a-zA-Z_][a-zA-Z_0-9]* "IDENTIFIER"
, "COMMA"
\* "STAR"
\? "QUESTION_MARK"
= "EQUAL"
\| "PIPE"
\( "LPAREN"
\) "RPAREN"
\{ "LBRACE"
\} "RBRACE"
"(?:\\\\|\\"|[^"\n])*" "STRING_LITERAL"
--[^\n]*$ ;
[ \t\n\r]+ ; |
|
hhvm/hphp/hack/src/asdl_to_rust/grammar/asdl.y | %start Module
%avoid_insert "IDENTIFIER"
%avoid_insert "STRING_LITERAL"
%%
Module -> Result<ast::Module, ()>:
'MODULE' Identifier Version_opt 'LBRACE' Definitions 'RBRACE' {
let id = $2?;
let version = $3?;
let definitions = $5?;
Ok(ast::Module{id, version, definitions})
}
;
Identifier -> Result<String, ()>:
'IDENTIFIER' {
let v = $1.map_err(|_| ())?;
Ok($lexer.span_str(v.span()).to_owned())
}
;
Version_opt -> Result<Option<String>, ()>:
'VERSION' String_ {
let v = $2.map_err(|_| ())?;
Ok(Some(v))
}
| { Ok(None) }
;
Definition -> Result<ast::Definition, ()>:
Identifier 'EQUAL' Desc Attributes_opt {
let type_id = $1?;
let desc = $3?;
let attributes = $4?.unwrap_or_default();
Ok(ast::Definition{type_id, desc, attributes})
}
;
Definitions -> Result<Vec<ast::Definition>, ()>:
{ Ok(vec![]) }
| Definitions Definition {
let mut defs = $1?;
defs.push($2?);
Ok(defs)
}
;
Desc -> Result<ast::Desc, ()>:
Product { Ok(ast::Desc::Product($1?)) }
| Sum { Ok(ast::Desc::Sum($1?)) }
;
Product -> Result<ast::Product, ()>:
'LPAREN' Fields 'RPAREN' {
Ok(ast::Product($2?))
}
;
Sum -> Result<ast::Sum, ()>:
Constructors {
$1
}
;
Constructors -> Result<Vec<ast::Constructor>, ()>:
Constructor { Ok(vec![$1?]) }
| Constructors 'PIPE' Constructor {
let mut ctors = $1?;
ctors.push($3?);
Ok(ctors)
}
;
Constructor -> Result<ast::Constructor, ()>:
Identifier Fields_opt {
let constructor_id = $1?;
let fields = $2?.unwrap_or_default();
Ok(ast::Constructor{constructor_id, fields})
}
;
Fields_opt -> Result< Option<Vec<ast::Field>> , ()>:
{ Ok(None) }
| 'LPAREN' Fields 'RPAREN' {
Ok(Some($2?))
}
;
Fields -> Result< Vec<ast::Field>, ()>:
Field {
Ok(vec![$1?])
}
| Fields 'COMMA' Field {
let mut fields = $1?;
fields.push($3?);
Ok(fields)
}
;
Field -> Result <ast::Field, ()>:
Identifier Opt_modifier FieldId {
let type_id = $1?;
let modifier = $2?;
let id = $3?;
Ok(ast::Field{type_id, modifier, id})
}
;
FieldId -> Result<String, ()>:
'MODULE' { Ok("module".to_string()) }
| 'ATTRIBUTES' { Ok("attributes".to_string()) }
| Identifier { $1 }
;
Attributes_opt -> Result<Option<ast::Attributes>, ()>:
{ Ok(None) }
| 'ATTRIBUTES' 'LPAREN' Fields 'RPAREN' {
Ok(Some(ast::Attributes($3?)))
}
;
Opt_modifier -> Result<Option<ast::Modifier>, ()>:
{ Ok(None) }
| 'QUESTION_MARK' {
Ok(Some(ast::Modifier::Question))
}
| 'STAR' {
Ok(Some(ast::Modifier::Star))
}
;
String_ -> Result<String, ()>:
'STRING_LITERAL' {
let v = $1.map_err(|_| ())?;
let s = $lexer.span_str(v.span());
Ok(s[1..s.len()-1].to_owned())
}
;
%%
pub mod ast {
#[derive(Debug)]
pub enum Modifier {
Question,
Star,
}
#[derive(Debug)]
pub struct Field {
pub type_id: String,
pub modifier: Option<Modifier>,
pub id: String,
}
#[derive(Debug)]
pub struct Constructor {
pub constructor_id: String,
pub fields: Vec<Field>,
}
#[derive(Debug)]
pub struct Product(pub Vec<Field>);
pub type Sum = Vec<Constructor>;
#[derive(Debug)]
pub enum Desc {
Product(Product),
Sum(Sum)
}
#[derive(Debug, Default)]
pub struct Attributes(pub Vec<Field>);
#[derive(Debug)]
pub struct Definition {
pub type_id: String,
pub desc: Desc,
pub attributes: Attributes,
}
#[derive(Debug)]
pub struct Module {
pub id: String,
pub version: Option<String>,
pub definitions: Vec<Definition>,
}
} |
|
TOML | hhvm/hphp/hack/src/asdl_to_rust/lrgen/Cargo.toml | # @generated by autocargo
[package]
name = "lrgen"
version = "0.0.0"
edition = "2021"
[[bin]]
name = "lrgen"
path = "lrgen.rs"
[dependencies]
cfgrammar = { version = "0.12", features = ["serde"] }
clap = { version = "3.2.25", features = ["derive", "env", "regex", "unicode", "wrap_help"] }
lrlex = "0.12" |
Rust | hhvm/hphp/hack/src/asdl_to_rust/lrgen/lrgen.rs | // 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.
/// A `lex`/`yacc` like parser generator tool built around
/// [softdevteam/grmtools](https://github.com/softdevteam/grmtools).
#[derive(Debug, clap::Parser)]
struct Opts {
/// Lexer definition ('.l' file)
#[clap(short, long)]
lexer: std::path::PathBuf,
/// Parser definition ('.y' file)
#[clap(short, long)]
parser: std::path::PathBuf,
/// The output directory
#[clap(short, long)]
outdir: std::path::PathBuf,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut opts = <Opts as clap::Parser>::parse();
let lexer_in = std::mem::take(&mut opts.lexer);
let parser_in = std::mem::take(&mut opts.parser);
let outdir_in = std::mem::take(&mut opts.outdir);
let outdir_out = outdir_in.display();
let lexer_out = format!(
"{}/{}_l.rs",
outdir_out,
lexer_in.file_stem().unwrap().to_str().unwrap()
);
let parser_out = format!(
"{}/{}_y.rs",
outdir_out,
parser_in.file_stem().unwrap().to_str().unwrap()
);
lrlex::CTLexerBuilder::<lrlex::DefaultLexeme<u32>, u32>::new()
.lrpar_config(move |ctp| {
ctp.yacckind(cfgrammar::yacc::YaccKind::Grmtools)
.grammar_path(parser_in.clone())
.output_path(parser_out.clone())
})
.lexer_path(lexer_in)
.output_path(lexer_out)
.build()?;
Ok(())
} |
hhvm/hphp/hack/src/asdl_to_rust/python/v3.10.0.asdl | -- ASDL's 4 builtin types are:
-- identifier, int, string, constant
module Python
{
mod = Module(stmt* body, type_ignore* type_ignores)
| Interactive(stmt* body)
| Expression(expr body)
| FunctionType(expr* argtypes, expr returns)
stmt = FunctionDef(identifier name, arguments args,
stmt* body, expr* decorator_list, expr? returns,
string? type_comment)
| AsyncFunctionDef(identifier name, arguments args,
stmt* body, expr* decorator_list, expr? returns,
string? type_comment)
| ClassDef(identifier name,
expr* bases,
keyword* keywords,
stmt* body,
expr* decorator_list)
| Return(expr? value)
| Delete(expr* targets)
| Assign(expr* targets, expr value, string? type_comment)
| AugAssign(expr target, operator op, expr value)
-- 'simple' indicates that we annotate simple name without parens
| AnnAssign(expr target, expr annotation, expr? value, int simple)
-- use 'orelse' because else is a keyword in target languages
| For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
| AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
| While(expr test, stmt* body, stmt* orelse)
| If(expr test, stmt* body, stmt* orelse)
| With(withitem* items, stmt* body, string? type_comment)
| AsyncWith(withitem* items, stmt* body, string? type_comment)
| Match(expr subject, match_case* cases)
| Raise(expr? exc, expr? cause)
| Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
| Assert(expr test, expr? msg)
| Import(alias* names)
| ImportFrom(identifier? module, alias* names, int? level)
| Global(identifier* names)
| Nonlocal(identifier* names)
| Expr(expr value)
| Pass | Break | Continue
-- col_offset is the byte offset in the utf8 string the parser uses
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
-- BoolOp() can use left & right?
expr = BoolOp(boolop op, expr* values)
| NamedExpr(expr target, expr value)
| BinOp(expr left, operator op, expr right)
| UnaryOp(unaryop op, expr operand)
| Lambda(arguments args, expr body)
| IfExp(expr test, expr body, expr orelse)
| Dict(expr* keys, expr* values)
| Set(expr* elts)
| ListComp(expr elt, comprehension* generators)
| SetComp(expr elt, comprehension* generators)
| DictComp(expr key, expr value, comprehension* generators)
| GeneratorExp(expr elt, comprehension* generators)
-- the grammar constrains where yield expressions can occur
| Await(expr value)
| Yield(expr? value)
| YieldFrom(expr value)
-- need sequences for compare to distinguish between
-- x < 4 < 3 and (x < 4) < 3
| Compare(expr left, cmpop* ops, expr* comparators)
| Call(expr func, expr* args, keyword* keywords)
| FormattedValue(expr value, int? conversion, expr? format_spec)
| JoinedStr(expr* values)
| Constant(constant value, string? kind)
-- the following expression can appear in assignment context
| Attribute(expr value, identifier attr, expr_context ctx)
| Subscript(expr value, expr slice, expr_context ctx)
| Starred(expr value, expr_context ctx)
| Name(identifier id, expr_context ctx)
| List(expr* elts, expr_context ctx)
| Tuple(expr* elts, expr_context ctx)
-- can appear only in Subscript
| Slice(expr? lower, expr? upper, expr? step)
-- col_offset is the byte offset in the utf8 string the parser uses
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
expr_context = Load | Store | Del
boolop = And | Or
operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift
| RShift | BitOr | BitXor | BitAnd | FloorDiv
unaryop = Invert | Not | UAdd | USub
cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn
comprehension = (expr target, expr iter, expr* ifs, int is_async)
excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
arguments = (arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs,
expr* kw_defaults, arg? kwarg, expr* defaults)
arg = (identifier arg, expr? annotation, string? type_comment)
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
-- keyword arguments supplied to call (NULL identifier for **kwargs)
keyword = (identifier? arg, expr value)
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
-- import name with optional 'as' alias.
alias = (identifier name, identifier? asname)
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
withitem = (expr context_expr, expr? optional_vars)
match_case = (pattern pattern, expr? guard, stmt* body)
pattern = MatchValue(expr value)
| MatchSingleton(constant value)
| MatchSequence(pattern* patterns)
| MatchMapping(expr* keys, pattern* patterns, identifier? rest)
| MatchClass(expr cls, pattern* patterns, identifier* kwd_attrs, pattern* kwd_patterns)
| MatchStar(identifier? name)
-- The optional "rest" MatchMapping parameter handles capturing extra mapping keys
| MatchAs(pattern? pattern, identifier? name)
| MatchOr(pattern* patterns)
attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)
type_ignore = TypeIgnore(int lineno, string tag)
} |
|
OCaml | hhvm/hphp/hack/src/ast/ast_defs.ml | (*
* Copyright (c) 2017, 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.
*
*)
(* We could open Hh_prelude here, but then we get errors about using ==,
which some visitor below uses. *)
open Base.Export
(*****************************************************************************)
(* The Abstract Syntax Tree *)
(*****************************************************************************)
type pos = (Pos.t[@visitors.opaque]) [@@transform.opaque]
and id_ = string
and id = pos * id_
and pstring = pos * string
and byte_string = string
and positioned_byte_string = pos * byte_string
and shape_field_name =
| SFlit_int of pstring
| SFlit_str of positioned_byte_string
| SFclass_const of id * pstring
[@@transform.opaque]
and variance =
| Covariant
| Contravariant
| Invariant
[@@transform.opaque]
and constraint_kind =
| Constraint_as
| Constraint_eq
| Constraint_super
[@@transform.opaque]
and abstraction =
| Concrete
| Abstract
[@@transform.opaque]
and classish_kind =
| Cclass of abstraction (** Kind for `class` and `abstract class` *)
| Cinterface (** Kind for `interface` *)
| Ctrait (** Kind for `trait` *)
| Cenum (** Kind for `enum` *)
| Cenum_class of abstraction
(** Kind for `enum class` and `abstract enum class`.
See https://docs.hhvm.com/hack/built-in-types/enum-class
*)
[@@transform.opaque]
and param_kind =
| Pinout of pos
(**
* Contains the position for an entire `inout` annotated expression, e.g.:
*
* foo(inout $bar);
* ^^^^^^^^^^
*)
| Pnormal
[@@transform.opaque]
and readonly_kind = Readonly [@@transform.opaque]
and og_null_flavor =
| OG_nullthrows
| OG_nullsafe
[@@transform.opaque]
and prop_or_method =
| Is_prop
| Is_method
[@@transform.opaque]
and fun_kind =
| FSync
| FAsync
| FGenerator
| FAsyncGenerator
[@@transform.opaque]
and bop =
| Plus (** Addition: x + y *)
| Minus (** Subtraction: x - y *)
| Star (** Multiplication: x * y *)
| Slash (** Division: x / y *)
| Eqeq (** Value/coercing equality: x == y *)
| Eqeqeq (** Same-type-and-value equality: x === y *)
| Starstar (** Exponent: x ** y *)
| Diff (** Value inquality: x != y *)
| Diff2 (** Not-same-type-and-value-equality: x !== y *)
| Ampamp (** Logical AND: x && y *)
| Barbar (** Logical OR: x || y *)
| Lt (** Less than: x < y *)
| Lte (** Less than or equal to: x <= y *)
| Gt (** Greater than: x > y *)
| Gte (** Greater than or equal to: x >= y *)
| Dot (** String concatenation: x . y *)
| Amp (** Bitwise AND: x & y *)
| Bar (** Bitwise OR: x | y *)
| Ltlt (** Bitwise left shift: x << y *)
| Gtgt (** Bitwise right shift: x >> y *)
| Percent (** Modulo: x % y *)
| Xor (** Bitwise XOR: x ^ y *)
| Cmp (** Spaceship operator: x <=> y *)
| QuestionQuestion (** Coalesce: x ?? y *)
| Eq of bop option (** =, +=, -=, ... *)
[@@transform.opaque]
and uop =
| Utild (** Bitwise negation: ~x *)
| Unot (** Logical not: !b *)
| Uplus (** Unary plus: +x *)
| Uminus (** Unary minus: -x *)
| Uincr (** Unary increment: ++i *)
| Udecr (** Unary decrement: --i *)
| Upincr (** Unary postfix increment: i++ *)
| Updecr (** Unary postfix decrement: i-- *)
| Usilence (** Error control/Silence (ignore) expections: @e *)
[@@transform.opaque]
and visibility =
| Private [@visitors.name "visibility_Private"]
| Public [@visitors.name "visibility_Public"]
| Protected [@visitors.name "visibility_Protected"]
| Internal [@visitors.name "visibility_Internal"]
[@@transform.opaque]
(** Literal values that can occur in XHP enum properties.
*
* class :my-xhp-class {
* attribute enum {'big', 'small'} my-prop;
* }
*)
and xhp_enum_value =
| XEV_Int of int
| XEV_String of string
[@@transform.opaque]
(** Hack's primitive types (as the typechecker understands them).
*
* Used in the AST of typehints (Aast_defs.Hprim) and in the representation of
* types (Typing_defs.Tprim).
*)
and tprim =
| Tnull
| Tvoid
| Tint
| Tbool
| Tfloat
| Tstring
| Tresource
| Tnum
| Tarraykey
| Tnoreturn
[@@transform.opaque]
and typedef_visibility =
| Transparent
| Opaque
| OpaqueModule
| CaseType
[@@transform.opaque]
and reify_kind =
| Erased
| SoftReified
| Reified
[@@transform.opaque]
[@@deriving
show { with_path = false },
eq,
hash,
ord,
transform ~restart:(`Disallow `Encode_as_result),
visitors
{
variety = "iter";
nude = true;
visit_prefix = "on_";
ancestors = ["Visitors_runtime.iter_base"];
},
visitors
{
variety = "endo";
nude = true;
visit_prefix = "on_";
ancestors = ["Visitors_runtime.endo_base"];
},
visitors
{
variety = "reduce";
nude = true;
visit_prefix = "on_";
ancestors = ["Visitors_runtime.reduce_base"];
},
visitors
{
variety = "map";
nude = true;
visit_prefix = "on_";
ancestors = ["Visitors_runtime.map_base"];
}]
(*****************************************************************************)
(* Helpers *)
(*****************************************************************************)
let get_pos : type a. Pos.t * a -> Pos.t = (fun (p, _) -> p)
let get_id : id -> id_ = (fun (_p, id) -> id)
let is_concrete = function
| Concrete -> true
| Abstract -> false
let is_abstract = function
| Abstract -> true
| Concrete -> false
let is_c_class = function
| Cclass _ -> true
| Cenum
| Cenum_class _
| Ctrait
| Cinterface ->
false
let is_c_normal = function
| Cclass c -> is_concrete c
| Cenum
| Cenum_class _
| Ctrait
| Cinterface ->
false
let is_c_concrete = function
| Cclass k
| Cenum_class k ->
is_concrete k
| Cinterface
| Ctrait
| Cenum ->
false
let is_c_abstract = function
| Cclass c -> is_abstract c
| Cinterface
| Cenum_class _
| Ctrait
| Cenum ->
false
let is_classish_abstract = function
| Cenum_class c
| Cclass c ->
is_abstract c
| Cinterface
| Ctrait
| Cenum ->
false
let is_c_enum = function
| Cenum -> true
| Cenum_class _
| Cclass _
| Ctrait
| Cinterface ->
false
let is_c_enum_class = function
| Cenum_class _ -> true
| Cenum
| Cclass _
| Ctrait
| Cinterface ->
false
let is_c_interface = function
| Cinterface -> true
| Cclass _
| Cenum_class _
| Ctrait
| Cenum ->
false
let is_c_trait = function
| Ctrait -> true
| Cinterface
| Cenum_class _
| Cclass _
| Cenum ->
false
let is_f_async = function
| FAsync -> true
| _ -> false
let is_f_async_or_generator = function
| FAsync
| FAsyncGenerator ->
true
| _ -> false
let string_of_classish_kind kind =
match kind with
| Cclass c ->
(match c with
| Abstract -> "an abstract class"
| Concrete -> "a class")
| Cinterface -> "an interface"
| Ctrait -> "a trait"
| Cenum -> "an enum"
| Cenum_class c ->
(match c with
| Abstract -> "an abstract enum class"
| Concrete -> "an enum class")
let swap_variance = function
| Covariant -> Contravariant
| Contravariant -> Covariant
| Invariant -> Invariant
module ShapeField = struct
type t = shape_field_name
(* We include span information in shape_field_name to improve error
* messages, but we don't want it being used in the comparison, so
* we have to write our own compare. *)
let compare x y =
match (x, y) with
| (SFlit_int (_, s1), SFlit_int (_, s2)) -> String.compare s1 s2
| (SFlit_str (_, s1), SFlit_str (_, s2)) -> String.compare s1 s2
| (SFclass_const ((_, s1), (_, s1')), SFclass_const ((_, s2), (_, s2'))) ->
Core.Tuple.T2.compare
~cmp1:String.compare
~cmp2:String.compare
(s1, s1')
(s2, s2')
| (SFlit_int _, _) -> -1
| (SFlit_str _, SFlit_int _) -> 1
| (SFlit_str _, _) -> -1
| (SFclass_const _, _) -> 1
let equal x y = Core.Int.equal 0 (compare x y)
end
module ShapeMap = struct
include WrappedMap.Make (ShapeField)
let map_and_rekey m f1 f2 =
fold (fun k v acc -> add (f1 k) (f2 v) acc) m empty
let pp
(pp_val : Format.formatter -> 'a -> unit)
(fmt : Format.formatter)
(map : 'a t) : unit =
make_pp pp_shape_field_name pp_val fmt map
end
module ShapeSet = Caml.Set.Make (ShapeField) |
hhvm/hphp/hack/src/ast/dune | (library
(name ast)
(wrapped false)
(modules ast_defs)
(libraries file_info namespace_env naming_special_names visitors_runtime)
(preprocess
(pps visitors.ppx ppx_hash ppx_transform ppx_deriving.std))) |
|
OCaml | hhvm/hphp/hack/src/batch/batch_global_state.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.
*
*)
type batch_state = {
saved_root: Path.t;
saved_hhi: Path.t;
saved_tmp: Path.t;
trace: bool;
paths_to_ignore: Str.regexp list;
allowed_fixme_codes_strict: ISet.t;
code_agnostic_fixme: bool;
}
let worker_id_str ~(worker_id : int) =
if worker_id = 0 then
"batch master"
else
Printf.sprintf "batch worker-%d" worker_id
let restore
({
saved_root;
saved_hhi;
saved_tmp;
trace;
paths_to_ignore;
allowed_fixme_codes_strict;
code_agnostic_fixme;
} :
batch_state)
~(worker_id : int) : unit =
Hh_logger.set_id (worker_id_str ~worker_id);
Relative_path.(set_path_prefix Root saved_root);
Relative_path.(set_path_prefix Hhi saved_hhi);
Relative_path.(set_path_prefix Tmp saved_tmp);
Typing_deps.trace := trace;
FilesToIgnore.set_paths_to_ignore paths_to_ignore;
Errors.allowed_fixme_codes_strict := allowed_fixme_codes_strict;
Errors.code_agnostic_fixme := code_agnostic_fixme;
Errors.set_allow_errors_in_default_path false
let save ~(trace : bool) : batch_state =
{
saved_root = Path.make Relative_path.(path_of_prefix Root);
saved_hhi = Path.make Relative_path.(path_of_prefix Hhi);
saved_tmp = Path.make Relative_path.(path_of_prefix Tmp);
trace;
paths_to_ignore = FilesToIgnore.get_paths_to_ignore ();
allowed_fixme_codes_strict = !Errors.allowed_fixme_codes_strict;
code_agnostic_fixme = !Errors.code_agnostic_fixme;
} |
OCaml Interface | hhvm/hphp/hack/src/batch/batch_global_state.mli | (*
* 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.
*
*)
type batch_state
val save : trace:bool -> batch_state
val worker_id_str : worker_id:int -> string
val restore : batch_state -> worker_id:int -> unit |
OCaml | hhvm/hphp/hack/src/batch/batch_init.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.
*
*)
open Hh_prelude
(* This should stay at toplevel in order to be executed before [Daemon.check_entry_point]. *)
let entry =
WorkerControllerEntryPoint.register ~restore:Batch_global_state.restore
let catch_and_classify_exceptions : 'x 'b. ('x -> 'b) -> 'x -> 'b =
fun f x ->
try f x with
| Decl_class.Decl_heap_elems_bug _ ->
Exit.exit Exit_status.Decl_heap_elems_bug
| File_provider.File_provider_stale ->
Exit.exit Exit_status.File_provider_stale
| Decl_defs.Decl_not_found x ->
Hh_logger.log "Decl_not_found %s" x;
Exit.exit Exit_status.Decl_not_found
| Not_found_s _
| Caml.Not_found ->
Exit.exit Exit_status.Worker_not_found_exception
let make_tmp_dir () =
let tmpdir = Path.make (Tmp.temp_dir GlobalConfig.tmp_dir "files") in
Relative_path.set_path_prefix Relative_path.Tmp tmpdir
let make_hhi_dir () =
let hhi_root = Hhi.get_hhi_root () in
Relative_path.set_path_prefix Relative_path.Hhi hhi_root
let init_state
~(root : Path.t)
~(popt : ParserOptions.t)
~(tcopt : TypecheckerOptions.t)
~(deps_mode : Typing_deps_mode.t) :
Provider_context.t * Batch_global_state.batch_state =
Relative_path.(set_path_prefix Root root);
make_tmp_dir ();
make_hhi_dir ();
let ctx =
Provider_context.empty_for_tool
~popt
~tcopt
~backend:Provider_backend.Shared_memory
~deps_mode
in
let batch_state = Batch_global_state.save ~trace:true in
(ctx, batch_state)
let init
~(root : Path.t)
~(shmem_config : SharedMem.config)
~(popt : ParserOptions.t)
~(tcopt : TypecheckerOptions.t)
~(deps_mode : Typing_deps_mode.t)
?(gc_control : Gc.control option)
(t : float) : Provider_context.t * MultiWorker.worker list * float =
let nbr_procs = Sys_utils.nbr_procs in
let heap_handle = SharedMem.init ~num_workers:nbr_procs shmem_config in
let gc_control =
match gc_control with
| Some c -> c
| None -> Core.Gc.get ()
in
let (ctx, state) = init_state ~root ~popt ~tcopt ~deps_mode in
let workers =
MultiWorker.make
~call_wrapper:{ WorkerController.wrap = catch_and_classify_exceptions }
~longlived_workers:false
~saved_state:state
~entry
nbr_procs
~gc_control
~heap_handle
in
( ctx,
workers,
Hh_logger.Level.log_duration Hh_logger.Level.Debug "make_workers" t )
let init_with_defaults =
init
~root:(Path.make "/")
~shmem_config:SharedMem.default_config
~popt:ParserOptions.default
~tcopt:TypecheckerOptions.default
~deps_mode:(Typing_deps_mode.InMemoryMode None)
?gc_control:None |
OCaml Interface | hhvm/hphp/hack/src/batch/batch_init.mli | (*
* 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.
*
*)
open Hh_prelude
val init :
root:Path.t ->
shmem_config:SharedMem.config ->
popt:ParserOptions.t ->
tcopt:TypecheckerOptions.t ->
deps_mode:Typing_deps_mode.t ->
?gc_control:Gc.control ->
float ->
Provider_context.t * MultiWorker.worker list * float
val init_with_defaults :
float -> Provider_context.t * MultiWorker.worker list * float |
hhvm/hphp/hack/src/batch/dune | (library
(name batch_global_state)
(wrapped false)
(modules batch_global_state)
(libraries
collections
errors
hhi
ignore
relative_path
sys_utils
typing_deps))
(library
(name batch_init)
(modules batch_init)
(wrapped false)
(libraries
batch_global_state
decl
file_provider
global_config
heap_shared_mem
hhi
naming
package_info
procs_entry_point
relative_path
typechecker_options
utils_core
utils_exit)) |
|
OCaml | hhvm/hphp/hack/src/client/clientArgs.ml | (*
* Copyright (c) 2015, 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 ClientCommand
open ClientEnv
(** Arg specs shared across more than 1 arg parser. *)
module Common_argspecs = struct
let config value_ref =
( "--config",
Arg.String
(fun s -> value_ref := String_utils.split2_exn '=' s :: !value_ref),
" override arbitrary value from hh.conf and .hhconfig (format: <key>=<value>)"
)
let custom_hhi_path value_ref =
( "--custom-hhi-path",
Arg.String (fun s -> value_ref := Some s),
" use custom hhi files" )
let custom_telemetry_data value_ref =
( "--custom-telemetry-data",
Arg.String
(fun s -> value_ref := String_utils.split2_exn '=' s :: !value_ref),
"Add a custom column to all logged telemetry samples (format: <column>=<value>)"
)
let force_dormant_start value_ref =
( "--force-dormant-start",
Arg.Bool (fun x -> value_ref := x),
" If server is dormant, force start a new one instead of waiting for"
^ " the next one to start up automatically (default: false)" )
let from value_ref =
( "--from",
Arg.Set_string value_ref,
" so we know who's calling hh_client - e.g. nuclide, vim, emacs, vscode"
(* This setting also controls whether spinner is displayed, and whether
clientCheckStatus.ml uses error-formatting. *) )
let no_prechecked value_ref =
( "--no-prechecked",
Arg.Unit (fun () -> value_ref := Some false),
" override value of \"prechecked_files\" flag from hh.conf" )
let prechecked value_ref =
( "--prechecked",
Arg.Unit (fun () -> value_ref := Some true),
" override value of \"prechecked_files\" flag from hh.conf" )
let with_mini_state (value_ref : string option ref) =
( "--with-mini-state",
Arg.String (fun s -> value_ref := Some s),
" Init with the given saved state instead of the one based on current repo version."
)
let watchman_debug_logging value_ref =
( "--watchman-debug-logging",
Arg.Set value_ref,
" Logs full Watchman requests and responses. This is very noisy" )
let allow_non_opt_build value_ref =
( "--allow-non-opt-build",
Arg.Set value_ref,
" Override build mode check triggered by warn_on_non_opt_build .hhconfig option"
)
let ignore_hh_version value_ref =
( "--ignore-hh-version",
Arg.Set value_ref,
" ignore hh_version check when loading saved states (default: false)" )
let saved_state_ignore_hhconfig value_ref =
( "--saved-state-ignore-hhconfig",
Arg.Set value_ref,
" ignore hhconfig hash when loading saved states (default: false)" )
let naming_table value_ref =
( "--naming-table",
Arg.String (fun s -> value_ref := Some s),
" use the provided naming table instead of fetching it from a saved state"
)
end
let parse_command () =
if Array.length Sys.argv < 2 then
CKNone
else
match String.lowercase Sys.argv.(1) with
| "check" -> CKCheck
| "start" -> CKStart
| "stop" -> CKStop
| "restart" -> CKRestart
| "lsp" -> CKLsp
| "saved-state-project-metadata" -> CKSavedStateProjectMetadata
| "download-saved-state" -> CKDownloadSavedState
| "rage" -> CKRage
| _ -> CKNone
let parse_without_command options usage command =
let args = ref [] in
Arg.parse (Arg.align options) (fun x -> args := x :: !args) usage;
match List.rev !args with
| x :: rest when String.(lowercase x = lowercase command) -> rest
| args -> args
(* *** *** NB *** *** ***
* Commonly-used options are documented in hphp/hack/man/hh_client.1 --
* if you are making significant changes you need to update the manpage as
* well. Experimental or otherwise volatile options need not be documented
* there, but keep what's there up to date please. *)
let parse_check_args cmd ~from_default =
(* arg parse output refs *)
let autostart = ref true in
let config = ref [] in
let custom_telemetry_data = ref [] in
let custom_hhi_path = ref None in
let error_format = ref Errors.Highlighted in
let force_dormant_start = ref false in
let from = ref from_default in
let show_spinner = ref None in
let gen_saved_ignore_type_errors = ref false in
let ignore_hh_version = ref false in
let save_64bit = ref None in
let save_human_readable_64bit_dep_map = ref None in
let saved_state_ignore_hhconfig = ref false in
let log_inference_constraints = ref false in
let max_errors = ref None in
let mode = ref None in
let logname = ref false in
let monitor_logname = ref false in
let client_logname = ref false in
let ide_logname = ref false in
let lsp_logname = ref false in
let lock_file = ref false in
let no_load = ref false in
let output_json = ref false in
let prechecked = ref None in
let mini_state : string option ref = ref None in
let rename_before = ref "" in
let remote = ref false in
let sort_results = ref false in
let stdin_name = ref None in
let timeout = ref None in
let version = ref false in
let watchman_debug_logging = ref false in
let allow_non_opt_build = ref false in
let desc = ref (ClientCommand.command_name cmd) in
(* custom behaviors *)
let current_option = ref None in
let set_from x () = from := x in
let single_files = ref [] in
let set_mode ?(validate = true) x =
if validate && Option.is_some !mode then
raise (Arg.Bad "only a single mode should be specified")
else begin
mode := Some x;
Option.iter !current_option ~f:(fun option -> desc := option);
()
end
in
let add_single x = single_files := x :: !single_files in
let set_mode_from_single_files () =
match !single_files with
| [] -> ()
| single_files ->
(match !mode with
| Some (MODE_POPULATE_REMOTE_DECLS None) ->
mode := Some (MODE_POPULATE_REMOTE_DECLS (Some single_files))
| _ -> set_mode (MODE_STATUS_SINGLE single_files))
in
(* parse args *)
let usage =
match cmd with
| CKCheck ->
Printf.sprintf
"Usage: %s check [OPTION]... [WWW-ROOT]\n\nWWW-ROOT is assumed to be current directory if unspecified\n"
Sys.argv.(0)
| CKNone ->
Printf.sprintf
("Usage: %s [COMMAND] [OPTION]... [WWW-ROOT]\n\nValid values for COMMAND:\n"
^^ "\tcheck\t\tShows current Hack errors\n"
^^ "\tstart\t\tStarts a Hack server\n"
^^ "\tstop\t\tStops a Hack server\n"
^^ "\trestart\t\tRestarts a Hack server\n"
^^ "\tlsp\t\tRuns a persistent language service\n"
^^ "\trage\t\tReport a bug\n"
^^ "\nDefault values if unspecified:\n"
^^ "\tCOMMAND\t\tcheck\n"
^^ "\tWWW-ROOT\tCurrent directory\n\nCheck command options:\n")
Sys.argv.(0)
| CKSavedStateProjectMetadata ->
Printf.sprintf
"Usage: %s saved-state-project-metadata [OPTION]... [WWW-ROOT]\nOutput the project metadata for the current saved state\n\nWWW-ROOT is assumed to be current directory if unspecified\n"
Sys.argv.(0)
| CKDownloadSavedState
| CKLsp
| CKRage
| CKRestart
| CKStart
| CKStop ->
failwith "No other keywords should make it here"
in
let options =
[
(* Please keep these sorted in the alphabetical order *)
Common_argspecs.allow_non_opt_build allow_non_opt_build;
( "--autostart-server",
Arg.Bool (( := ) autostart),
" automatically start hh_server if it's not running (default: true)" );
( "--codemod-sdt",
(let path_to_jsonl = ref "" in
let log_remotely = ref false in
let tag = ref "" in
Arg.Tuple
[
Arg.String (( := ) path_to_jsonl);
Arg.Bool (( := ) log_remotely);
(* arbitrary description used to distinguish this run *)
Arg.String (( := ) tag);
Arg.String
(fun raw_strategy ->
let strategy =
match raw_strategy with
| "cumulative-groups" -> `CodemodSdtCumulative
| "independent-groups" -> `CodemodSdtIndependent
| s ->
raise
@@ Arg.Bad
(Format.sprintf "invalid --codemod-sdt mode: %s" s)
in
set_mode
@@ MODE_CODEMOD_SDT
{
csdt_path_to_jsonl = !path_to_jsonl;
csdt_strategy = strategy;
csdt_log_remotely = !log_remotely;
csdt_tag = !tag;
});
]),
"apply codemod for adding <<__NoAutoDynamic>>" );
Common_argspecs.config config;
( "--create-checkpoint",
Arg.String (fun x -> set_mode (MODE_CREATE_CHECKPOINT x)),
(* Create a checkpoint which can be used to retrieve changed files later *)
"" );
( "--cst-search",
Arg.Unit (fun () -> set_mode (MODE_CST_SEARCH None)),
" (mode) Search the concrete syntax trees of files in the codebase"
^ " for a given pattern" );
( "--cst-search-files",
Arg.Rest
begin
fun fn ->
set_mode
~validate:false
(match !mode with
| None
| Some (MODE_CST_SEARCH None) ->
MODE_CST_SEARCH (Some [fn])
| Some (MODE_CST_SEARCH (Some fnl)) ->
MODE_CST_SEARCH (Some (fn :: fnl))
| _ -> raise (Arg.Bad "only a single mode should be specified"))
end,
" Run CST search on this set of files,"
^ " rather than all the files in the codebase." );
Common_argspecs.custom_hhi_path custom_hhi_path;
Common_argspecs.custom_telemetry_data custom_telemetry_data;
(* Delete an existing checkpoint.
* Exitcode will be non-zero if no checkpoint is found *)
( "--delete-checkpoint",
Arg.String (fun x -> set_mode (MODE_DELETE_CHECKPOINT x)),
"" );
( "--deps-out-at-pos-batch",
Arg.Rest
begin
fun position ->
set_mode
~validate:false
(match !mode with
| None -> MODE_DEPS_OUT_AT_POS_BATCH [position]
| Some (MODE_DEPS_OUT_AT_POS_BATCH positions) ->
MODE_FUN_DEPS_AT_POS_BATCH (position :: positions)
| _ -> raise (Arg.Bad "only a single mode should be specified"))
end,
" (mode) for each entry in input list get list of what it depends on [file:line:character list]"
);
( "--deps-in-at-pos-batch",
Arg.Rest
begin
fun position ->
set_mode
~validate:false
(match !mode with
| None -> MODE_DEPS_IN_AT_POS_BATCH [position]
| Some (MODE_DEPS_IN_AT_POS_BATCH positions) ->
MODE_DEPS_IN_AT_POS_BATCH (position :: positions)
| _ -> raise (Arg.Bad "only a single mode should be specified"))
end,
" (mode) for each entry in input list get list of what depends on it [file:line:character list]"
);
( "--dump-full-fidelity-parse",
Arg.String (fun x -> set_mode (MODE_FULL_FIDELITY_PARSE x)),
"" );
( "--dump-symbol-info",
Arg.String (fun files -> set_mode (MODE_DUMP_SYMBOL_INFO files)),
(* Input format:
* The file list can either be "-" which accepts the input from stdin
* separated by newline(for long list) or directly from command line
* separated by semicolon.
* Output format:
* [
* "function_calls": list of fun_calls;
* ]
* Note: results list can be in any order *)
"" );
( "--error-format",
Arg.String
(fun s ->
match s with
| "raw" -> error_format := Errors.Raw
| "plain" -> error_format := Errors.Plain
| "context" -> error_format := Errors.Context
| "highlighted" -> error_format := Errors.Highlighted
| _ -> print_string "Warning: unrecognized error format.\n"),
"<raw|context|highlighted|plain> Error formatting style; (default: highlighted)"
);
( "--extract-standalone",
Arg.String (fun name -> set_mode (MODE_EXTRACT_STANDALONE name)),
" extract a given function / method together with its dependencies as a standalone file. Usage: --extract-standalone Classname::methodName or function_name"
);
( "--concatenate-all",
Arg.Unit (fun () -> set_mode MODE_CONCATENATE_ALL),
"(mode) create a single file containing all Hack code in the specified prefix"
);
( "--file-dependents",
Arg.Unit
(fun () ->
let () = prechecked := Some false in
set_mode MODE_FILE_LEVEL_DEPENDENCIES),
" (mode) Given a list of filepaths, shows list of (possibly) dependent files"
);
( "--find-class-refs",
Arg.String (fun x -> set_mode (MODE_FIND_CLASS_REFS x)),
" (mode) finds references of the provided class name" );
( "--find-refs",
Arg.String (fun x -> set_mode (MODE_FIND_REFS x)),
" (mode) finds references of the provided method name" );
Common_argspecs.force_dormant_start force_dormant_start;
( "--format",
(let format_from = ref 0 in
Arg.Tuple
[
Arg.Int (( := ) format_from);
Arg.Int (fun x -> set_mode (MODE_FORMAT (!format_from, x)));
]),
"" );
Common_argspecs.from from;
( "--from-arc-diff",
Arg.Unit (set_from "arc_diff"),
" (deprecated) equivalent to --from arc_diff" );
( "--from-arc-land",
Arg.Unit (set_from "arc_land"),
" (deprecated) equivalent to --from arc_land" );
( "--from-check-trunk",
Arg.Unit (set_from "check_trunk"),
" (deprecated) equivalent to --from check_trunk" );
( "--from-emacs",
Arg.Unit (set_from "emacs"),
" (deprecated) equivalent to --from emacs" );
( "--from-vim",
Arg.Unit (fun () -> from := "vim"),
" (deprecated) equivalent to --from vim" );
( "--full-fidelity-schema",
Arg.Unit (fun () -> set_mode MODE_FULL_FIDELITY_SCHEMA),
"" );
( "--fun-deps-at-pos-batch",
Arg.Rest
begin
fun position ->
set_mode
~validate:false
(match !mode with
| None -> MODE_FUN_DEPS_AT_POS_BATCH [position]
| Some (MODE_FUN_DEPS_AT_POS_BATCH positions) ->
MODE_FUN_DEPS_AT_POS_BATCH (position :: positions)
| _ -> raise (Arg.Bad "only a single mode should be specified"))
end,
" (mode) for each entry in input list get list of function dependencies [file:line:character list]"
);
( "--gen-prefetch-dir",
Arg.String (fun _x -> set_mode (MODE_POPULATE_REMOTE_DECLS None)),
" Compute all decls for the repo and upload them to the remote decl service."
^ " Usage: --gen-prefetch-dir unused" );
( "--populate-remote-decls",
Arg.Unit (fun () -> set_mode (MODE_POPULATE_REMOTE_DECLS None)),
" Compute all decls for the repo and upload them to the remote decl service."
);
( "--gen-saved-ignore-type-errors",
Arg.Set gen_saved_ignore_type_errors,
" generate a saved state even if there are type errors (default: false)."
);
( "--get-method-name",
Arg.String (fun x -> set_mode (MODE_IDENTIFY_SYMBOL3 x)),
(* alias for --identify-function *) "" );
( "--go-to-impl-class",
Arg.String (fun x -> set_mode (MODE_GO_TO_IMPL_CLASS x)),
" (mode) goes to implementation of the provided class/trait/interface/etc. with the given name"
);
( "--go-to-impl-method",
Arg.String (fun x -> set_mode (MODE_GO_TO_IMPL_METHOD x)),
" (mode) goes to implementation of the provided method name" );
( "--ide-find-refs-by-symbol",
Arg.String
(fun x ->
set_mode
(MODE_IDE_FIND_REFS_BY_SYMBOL
(FindRefsWireFormat.CliArgs.from_string_exn x))),
"(mode) similar to IDE_FIND_REFS, but takes a symbol name rather than position"
);
( "--ide-find-refs-by-symbol3",
(let action = ref "" in
let stream_file = ref "-" in
Arg.Tuple
[
Arg.String (fun s -> action := s);
Arg.String (fun s -> stream_file := s);
Arg.String
(fun hints ->
set_mode
(MODE_IDE_FIND_REFS_BY_SYMBOL
(FindRefsWireFormat.CliArgs.from_string_triple_exn
(!action, !stream_file, hints))));
]),
"(mode) similar to FIND_REFS, but takes [action stream_file hints]" );
( "--ide-go-to-impl-by-symbol",
Arg.String
(fun x ->
set_mode
(MODE_IDE_GO_TO_IMPL_BY_SYMBOL
(FindRefsWireFormat.CliArgs.from_string_exn x))),
"(mode) similar to IDE_GO_TO_IMPL, but takes a symbol name rather than position"
);
( "--ide-get-definition",
Arg.String (fun x -> set_mode (MODE_IDENTIFY_SYMBOL2 x)),
(* alias for --identify-function *) "" );
("--ide-outline", Arg.Unit (fun () -> set_mode MODE_OUTLINE2), "");
( "--ide-rename-by-symbol",
Arg.String (fun x -> set_mode (MODE_IDE_RENAME_BY_SYMBOL x)),
" (mode) renames, but takes a Find_refs.action. Usage: "
^ " <new name>|<comma_separated_action>" );
( "--identify-function",
Arg.String (fun x -> set_mode (MODE_IDENTIFY_SYMBOL1 x)),
" (mode) print the full function name at the position "
^ "[line:character] of the text on stdin" );
( "--identify",
Arg.String (fun x -> set_mode (MODE_IDENTIFY_SYMBOL x)),
" (mode) identify the named symbol" );
Common_argspecs.ignore_hh_version ignore_hh_version;
( "--in-memory-dep-table-size",
Arg.Unit (fun () -> set_mode MODE_IN_MEMORY_DEP_TABLE_SIZE),
" number of entries in the in-memory dependency table" );
( "--inheritance-ancestor-classes",
Arg.String (fun x -> set_mode (MODE_METHOD_JUMP_ANCESTORS (x, "Class"))),
" (mode) prints a list of classes that this class extends" );
( "--inheritance-ancestor-classes-batch",
Arg.Rest
begin
fun class_ ->
set_mode
~validate:false
(match !mode with
| None -> MODE_METHOD_JUMP_ANCESTORS_BATCH ([class_], "Class")
| Some (MODE_METHOD_JUMP_ANCESTORS_BATCH (classes, "Class")) ->
MODE_METHOD_JUMP_ANCESTORS_BATCH (class_ :: classes, "Class")
| _ -> raise (Arg.Bad "only a single mode should be specified"))
end,
" (mode) prints a list of classes that these classes extend" );
( "--inheritance-ancestor-interfaces",
Arg.String
(fun x -> set_mode (MODE_METHOD_JUMP_ANCESTORS (x, "Interface"))),
" (mode) prints a list of interfaces that this class implements" );
( "--inheritance-ancestor-interfaces-batch",
Arg.Rest
begin
fun class_ ->
set_mode
~validate:false
(match !mode with
| None ->
MODE_METHOD_JUMP_ANCESTORS_BATCH ([class_], "Interface")
| Some (MODE_METHOD_JUMP_ANCESTORS_BATCH (classes, "Interface"))
->
MODE_METHOD_JUMP_ANCESTORS_BATCH
(class_ :: classes, "Interface")
| _ -> raise (Arg.Bad "only a single mode should be specified"))
end,
" (mode) prints a list of interfaces that these classes implement" );
( "--inheritance-ancestor-traits",
Arg.String (fun x -> set_mode (MODE_METHOD_JUMP_ANCESTORS (x, "Trait"))),
" (mode) prints a list of traits that this class uses" );
( "--inheritance-ancestor-traits-batch",
Arg.Rest
begin
fun class_ ->
set_mode
~validate:false
(match !mode with
| None -> MODE_METHOD_JUMP_ANCESTORS_BATCH ([class_], "Trait")
| Some (MODE_METHOD_JUMP_ANCESTORS_BATCH (classes, "Trait")) ->
MODE_METHOD_JUMP_ANCESTORS_BATCH (class_ :: classes, "Trait")
| _ -> raise (Arg.Bad "only a single mode should be specified"))
end,
" (mode) prints a list of traits that these classes use" );
( "--inheritance-ancestors",
Arg.String
(fun x -> set_mode (MODE_METHOD_JUMP_ANCESTORS (x, "No_filter"))),
" (mode) prints a list of all related classes or methods"
^ " to the given class" );
( "--inheritance-children",
Arg.String (fun x -> set_mode (MODE_METHOD_JUMP_CHILDREN x)),
" (mode) prints a list of all related classes or methods"
^ " to the given class" );
( "--json",
Arg.Set output_json,
" output json for machine consumption. (default: false)" );
( "--lint",
Arg.Unit (fun () -> set_mode MODE_LINT),
" (mode) lint the given list of files" );
( "--lint-all",
Arg.Int (fun x -> set_mode (MODE_LINT_ALL x)),
" (mode) find all occurrences of lint with the given error code" );
( "--lint-stdin",
Arg.String (fun filename -> set_mode (MODE_LINT_STDIN filename)),
" (mode) lint a file given on stdin; the filename should be the"
^ " argument to this option" );
( "--list-files",
Arg.Unit (fun () -> set_mode MODE_LIST_FILES),
" (mode) list files with errors" );
("--lock-file", Arg.Set lock_file, " (mode) show lock file name and exit");
( "--log-inference-constraints",
Arg.Set log_inference_constraints,
" (for hh debugging purpose only) log type"
^ " inference constraints into external logger (e.g. Scuba)" );
( "--max-errors",
Arg.Int (fun num_errors -> max_errors := Some num_errors),
" Maximum number of errors to display" );
("--logname", Arg.Set logname, " (mode) show log filename and exit");
( "--monitor-logname",
Arg.Set monitor_logname,
" (mode) show monitor log filename and exit" );
( "--client-logname",
Arg.Set client_logname,
" (mode) show client log filename and exit" );
( "--ide-logname",
Arg.Set ide_logname,
" (mode) show client ide log filename and exit" );
( "--lsp-logname",
Arg.Set lsp_logname,
" (mode) show client lsp log filename and exit" );
("--no-load", Arg.Set no_load, " start from a fresh state");
( "--outline",
Arg.Unit (fun () -> set_mode MODE_OUTLINE),
" (mode) prints an outline of the text on stdin" );
Common_argspecs.prechecked prechecked;
Common_argspecs.no_prechecked prechecked;
Common_argspecs.with_mini_state mini_state;
( "--pause",
Arg.Unit (fun () -> set_mode (MODE_PAUSE true)),
" (mode) pause recheck-on-file-change [EXPERIMENTAL]" );
( "--profile-log",
Arg.Unit (fun () -> config := ("profile_log", "true") :: !config),
" enable profile logging" );
( "--refactor",
(let rename_mode = ref Unspecified in
Arg.Tuple
[
Arg.Symbol
( ["Class"; "Function"; "Method"],
(fun x -> rename_mode := string_to_rename_mode x) );
Arg.String (fun x -> rename_before := x);
Arg.String
(fun x ->
set_mode (MODE_RENAME (!rename_mode, !rename_before, x)));
]),
" (mode) rename a symbol, Usage: --refactor "
^ "[\"Class\", \"Function\", \"Method\"] <Current Name> <New Name>" );
("--remote", Arg.Set remote, " force remote type checking");
( "--remove-dead-fixme",
Arg.Int
begin
fun code ->
set_mode
~validate:false
(match !mode with
| None -> MODE_REMOVE_DEAD_FIXMES [code]
| Some (MODE_REMOVE_DEAD_FIXMES codel) ->
MODE_REMOVE_DEAD_FIXMES (code :: codel)
| _ -> raise (Arg.Bad "only a single mode should be specified"))
end,
" (mode) remove dead HH_FIXME for specified error code "
^ "(first do hh_client restart --no-load)" );
( "--remove-dead-fixmes",
Arg.Unit (fun () -> set_mode (MODE_REMOVE_DEAD_FIXMES [])),
" (mode) remove dead HH_FIXME for any error code < 5000 "
^ "(first do hh_client restart --no-load)" );
( "--remove-dead-unsafe-casts",
Arg.Unit (fun () -> set_mode MODE_REMOVE_DEAD_UNSAFE_CASTS),
" (mode) remove dead UNSAFE_CASTS (first do hh_client restart --no-load)"
);
( "--resume",
Arg.Unit (fun () -> set_mode (MODE_PAUSE false)),
" (mode) resume recheck-on-file-change [EXPERIMENTAL]" );
( "--retries",
Arg.Int (fun n -> timeout := Some (float_of_int (max 5 n))),
" (deprecated) same as --timeout" );
(* Retrieve changed files since input checkpoint.
* Output is separated by newline.
* Exit code will be non-zero if no checkpoint is found *)
( "--retrieve-checkpoint",
Arg.String (fun x -> set_mode (MODE_RETRIEVE_CHECKPOINT x)),
"" );
("--retry-if-init", Arg.Bool (fun _ -> ()), " (deprecated and ignored)");
( "--rewrite-lambda-parameters",
Arg.Rest
begin
fun fn ->
set_mode
~validate:false
(match !mode with
| None -> MODE_REWRITE_LAMBDA_PARAMETERS [fn]
| Some (MODE_REWRITE_LAMBDA_PARAMETERS fnl) ->
MODE_REWRITE_LAMBDA_PARAMETERS (fn :: fnl)
| _ -> raise (Arg.Bad "only a single mode should be specified"))
end,
" (mode) rewrite lambdas in the files from the given list"
^ " with suggested parameter types" );
( "--save-naming",
Arg.String (fun x -> set_mode (MODE_SAVE_NAMING x)),
" (mode) Save the naming table to the given file."
^ " Returns the number of files and symbols written to disk." );
( "--save-state",
Arg.String (fun x -> set_mode (MODE_SAVE_STATE x)),
" (mode) Save a saved state to the given file."
^ " Returns number of edges dumped from memory to the database." );
( "--save-64bit",
Arg.String (fun x -> save_64bit := Some x),
" save discovered 64-bit to the given directory" );
( "--save-human-readable-64bit-dep-map",
Arg.String (fun x -> save_human_readable_64bit_dep_map := Some x),
" save map of 64bit hashes to names to files in the given directory" );
Common_argspecs.saved_state_ignore_hhconfig saved_state_ignore_hhconfig;
( "--search",
Arg.String (fun x -> set_mode (MODE_SEARCH (x, ""))),
" (mode) fuzzy search symbol definitions" );
( "--search-class",
Arg.String (fun x -> set_mode (MODE_SEARCH (x, "class"))),
" (mode) fuzzy search class definitions" );
( "--search-constant",
Arg.String (fun x -> set_mode (MODE_SEARCH (x, "constant"))),
" (mode) fuzzy search constant definitions" );
( "--search-function",
Arg.String (fun x -> set_mode (MODE_SEARCH (x, "function"))),
" (mode) fuzzy search function definitions" );
( "--search-typedef",
Arg.String (fun x -> set_mode (MODE_SEARCH (x, "typedef"))),
" (mode) fuzzy search typedef definitions" );
( "--server-rage",
Arg.Unit (fun () -> set_mode MODE_SERVER_RAGE),
" (mode) dumps internal state of hh_server" );
( "--show-spinner",
Arg.Bool (fun x -> show_spinner := Some x),
" shows a spinner while awaiting the typechecker" );
( "--single",
Arg.String add_single,
"<path> Return errors in file with provided name (give '-' for stdin)"
);
("--sort-results", Arg.Set sort_results, " sort output for CST search.");
( "--stats",
Arg.Unit (fun () -> set_mode MODE_STATS),
" display some server statistics" );
( "--stdin-name",
Arg.String (fun x -> stdin_name := Some x),
" substitute stdin for contents of file with specified name" );
( "--status",
Arg.Unit (fun () -> set_mode MODE_STATUS),
" (mode) show a human readable list of errors (default)" );
( "--timeout",
Arg.Float (fun x -> timeout := Some (Float.max 5. x)),
" set the timeout in seconds (default: no timeout)" );
( "--type-at-pos",
Arg.String (fun x -> set_mode (MODE_TYPE_AT_POS x)),
" (mode) show type at a given position in file [file:line:character]" );
( "--type-at-pos-batch",
Arg.Rest
begin
fun position ->
set_mode
~validate:false
(match !mode with
| None -> MODE_TYPE_AT_POS_BATCH [position]
| Some (MODE_TYPE_AT_POS_BATCH positions) ->
MODE_TYPE_AT_POS_BATCH (position :: positions)
| _ -> raise (Arg.Bad "only a single mode should be specified"))
end,
" (mode) show types at multiple positions [file:line:character list]" );
( "--type-error-at-pos",
Arg.String (fun x -> set_mode (MODE_TYPE_ERROR_AT_POS x)),
" (mode) show type error at a given position in file [line:character]"
);
( "--is-subtype",
Arg.Unit (fun () -> set_mode MODE_IS_SUBTYPE),
" (mode) take a JSON list of subtype queries via stdin" );
( "--tast-holes",
Arg.String (fun x -> set_mode (MODE_TAST_HOLES x)),
" (mode) return all TAST Holes in a given file" );
( "--tast-holes-batch",
Arg.String (fun x -> set_mode (MODE_TAST_HOLES_BATCH x)),
" (mode) return all TAST Holes for a set of files. Argument is a file containing a newline-separated list of files"
);
( "--verbose-on",
Arg.Unit (fun () -> set_mode (MODE_VERBOSE true)),
" (mode) turn on verbose server log" );
( "--verbose-off",
Arg.Unit (fun () -> set_mode (MODE_VERBOSE false)),
" (mode) turn off verbose server log" );
("--version", Arg.Set version, " (mode) show version and exit");
Common_argspecs.watchman_debug_logging watchman_debug_logging;
( "--xhp-autocomplete-snippet",
Arg.String (fun x -> set_mode (MODE_XHP_AUTOCOMPLETE_SNIPPET x)),
"(mode) Look up for XHP component and return its snippet" );
(* Please keep these sorted in the alphabetical order *)
]
in
(* If the user typed an option like "--type-at-pos" which set a mode which triggered
a command, we want to be able to show "hh_server is busy [--type-at-pos]" to show that
hh_server is currently busy with something that the user typed. The string
description that appears inside the square brackets must go into args.desc.
Unfortunately this isn't well supported by the Arg library, so we have to hack it up
ourselves: (1) For any option that takes say Arg.Unit(callback), we'll change it into
Arg.Unit(modified_callback) where modified_callback sets 'current_option' to the
option string being handled and then calls the original callback. (2) If the original
callback calls set_mode, then set_mode will take the opportunity to do desc := current_option.
*)
let modify_callback : type a. string -> (a -> unit) -> a -> unit =
fun option callback value ->
current_option := Some option;
callback value;
current_option := None
in
let rec modify_spec ~option spec =
match spec with
| Arg.Unit callback -> Arg.Unit (modify_callback option callback)
| Arg.Bool callback -> Arg.Bool (modify_callback option callback)
| Arg.String callback -> Arg.String (modify_callback option callback)
| Arg.Int callback -> Arg.Int (modify_callback option callback)
| Arg.Float callback -> Arg.Float (modify_callback option callback)
| Arg.Rest callback -> Arg.Rest (modify_callback option callback)
| Arg.Tuple specs -> Arg.Tuple (List.map specs ~f:(modify_spec ~option))
| spec -> spec
in
let options =
List.map options ~f:(fun (option, spec, text) ->
(option, modify_spec ~option spec, text))
in
let args =
parse_without_command options usage (ClientCommand.command_name cmd)
in
if !version then (
if !output_json then
ServerArgs.print_json_version ()
else
print_endline Hh_version.version;
exit 0
);
set_mode_from_single_files ();
let mode = Option.value !mode ~default:MODE_STATUS in
(* fixups *)
let (root, paths) =
match (mode, args) with
| (MODE_LINT, _)
| (MODE_CONCATENATE_ALL, _)
| (MODE_FILE_LEVEL_DEPENDENCIES, _) ->
(Wwwroot.interpret_command_line_root_parameter [], args)
| (_, _) -> (Wwwroot.interpret_command_line_root_parameter args, [])
in
if !lock_file then (
let lock_file_link = ServerFiles.lock_file root in
Printf.printf "%s\n%!" lock_file_link;
exit 0
);
if !ide_logname then (
let ide_log_link = ServerFiles.client_ide_log root in
Printf.printf "%s\n%!" ide_log_link;
exit 0
);
if !lsp_logname then (
let lsp_log_link = ServerFiles.client_lsp_log root in
Printf.printf "%s\n%!" lsp_log_link;
exit 0
);
if !monitor_logname then (
let monitor_log_link = ServerFiles.monitor_log_link root in
Printf.printf "%s\n%!" monitor_log_link;
exit 0
);
if !client_logname then (
let client_log_link = ServerFiles.client_log root in
Printf.printf "%s\n%!" client_log_link;
exit 0
);
if !logname then (
let log_link = ServerFiles.log_link root in
Printf.printf "%s\n%!" log_link;
exit 0
);
if String.equal !from "emacs" then
Printf.fprintf stdout "-*- mode: compilation -*-\n%!";
{
autostart = !autostart;
config = !config;
custom_hhi_path = !custom_hhi_path;
custom_telemetry_data = !custom_telemetry_data;
error_format = !error_format;
force_dormant_start = !force_dormant_start;
from = !from;
show_spinner =
Option.value
~default:(String.is_empty !from || String.equal !from "[sh]")
!show_spinner;
gen_saved_ignore_type_errors = !gen_saved_ignore_type_errors;
ignore_hh_version = !ignore_hh_version;
saved_state_ignore_hhconfig = !saved_state_ignore_hhconfig;
paths;
log_inference_constraints = !log_inference_constraints;
max_errors = !max_errors;
mode;
no_load =
(!no_load
||
match mode with
| MODE_REMOVE_DEAD_FIXMES _ -> true
| _ -> false);
save_64bit = !save_64bit;
save_human_readable_64bit_dep_map = !save_human_readable_64bit_dep_map;
output_json = !output_json;
prechecked = !prechecked;
mini_state = !mini_state;
remote = !remote;
root;
sort_results = !sort_results;
stdin_name = !stdin_name;
deadline = Option.map ~f:(fun t -> Unix.time () +. t) !timeout;
watchman_debug_logging = !watchman_debug_logging;
allow_non_opt_build = !allow_non_opt_build;
desc = !desc;
}
let parse_start_env command ~from_default =
let usage =
Printf.sprintf
"Usage: %s %s [OPTION]... [WWW-ROOT]\n%s a Hack server\n\nWWW-ROOT is assumed to be current directory if unspecified\n"
Sys.argv.(0)
command
(String.capitalize command)
in
let log_inference_constraints = ref false in
let no_load = ref false in
let watchman_debug_logging = ref false in
let ignore_hh_version = ref false in
let saved_state_ignore_hhconfig = ref false in
let prechecked = ref None in
let mini_state = ref None in
let from = ref from_default in
let config = ref [] in
let custom_hhi_path = ref None in
let custom_telemetry_data = ref [] in
let allow_non_opt_build = ref false in
let wait_deprecation_msg () =
Printf.eprintf
"WARNING: --wait is deprecated, does nothing, and will be going away soon!\n%!"
in
let options =
[
(* Please keep these sorted in the alphabetical order *)
Common_argspecs.allow_non_opt_build allow_non_opt_build;
Common_argspecs.config config;
Common_argspecs.custom_hhi_path custom_hhi_path;
Common_argspecs.custom_telemetry_data custom_telemetry_data;
Common_argspecs.from from;
Common_argspecs.ignore_hh_version ignore_hh_version;
( "--log-inference-constraints",
Arg.Set log_inference_constraints,
" (for hh debugging purpose only) log type"
^ " inference constraints into external logger (e.g. Scuba)" );
("--no-load", Arg.Set no_load, " start from a fresh state");
Common_argspecs.no_prechecked prechecked;
Common_argspecs.prechecked prechecked;
Common_argspecs.with_mini_state mini_state;
( "--profile-log",
Arg.Unit (fun () -> config := ("profile_log", "true") :: !config),
" enable profile logging" );
Common_argspecs.saved_state_ignore_hhconfig saved_state_ignore_hhconfig;
( "--wait",
Arg.Unit wait_deprecation_msg,
" this flag is deprecated and does nothing!" );
Common_argspecs.watchman_debug_logging watchman_debug_logging;
(* Please keep these sorted in the alphabetical order *)
]
in
let args = parse_without_command options usage command in
let root = Wwwroot.interpret_command_line_root_parameter args in
{
ClientStart.config = !config;
custom_hhi_path = !custom_hhi_path;
custom_telemetry_data = !custom_telemetry_data;
exit_on_failure = true;
from = !from;
ignore_hh_version = !ignore_hh_version;
saved_state_ignore_hhconfig = !saved_state_ignore_hhconfig;
save_64bit = None;
save_human_readable_64bit_dep_map = None;
log_inference_constraints = !log_inference_constraints;
no_load = !no_load;
prechecked = !prechecked;
mini_state = !mini_state;
root;
silent = false;
watchman_debug_logging = !watchman_debug_logging;
allow_non_opt_build = !allow_non_opt_build;
}
let parse_saved_state_project_metadata_args ~from_default : command =
CSavedStateProjectMetadata
(parse_check_args CKSavedStateProjectMetadata ~from_default)
let parse_start_args ~from_default =
CStart (parse_start_env "start" ~from_default)
let parse_restart_args ~from_default =
CRestart (parse_start_env "restart" ~from_default)
let parse_stop_args ~from_default =
let usage =
Printf.sprintf
"Usage: %s stop [OPTION]... [WWW-ROOT]\nStop a hack server\n\nWWW-ROOT is assumed to be current directory if unspecified\n"
Sys.argv.(0)
in
let from = ref from_default in
let options = [Common_argspecs.from from] in
let args = parse_without_command options usage "stop" in
let root = Wwwroot.interpret_command_line_root_parameter args in
CStop { ClientStop.root; from = !from }
let parse_lsp_args () =
let usage =
Printf.sprintf
"Usage: %s lsp [OPTION]...\nRuns a persistent language service\n"
Sys.argv.(0)
in
let from = ref "" in
let config = ref [] in
let verbose = ref false in
let ignore_hh_version = ref false in
let naming_table = ref None in
let options =
[
Common_argspecs.from from;
Common_argspecs.config config;
(* Please keep these sorted in the alphabetical order *)
("--enhanced-hover", Arg.Unit (fun () -> ()), " [legacy] no-op");
("--ffp-autocomplete", Arg.Unit (fun () -> ()), " [legacy] no-op");
Common_argspecs.ignore_hh_version ignore_hh_version;
Common_argspecs.naming_table naming_table;
("--ranked-autocomplete", Arg.Unit (fun () -> ()), " [legacy] no-op");
("--serverless-ide", Arg.Unit (fun () -> ()), " [legacy] no-op");
( "--verbose",
Arg.Set verbose,
" verbose logs to stderr and `hh --ide-logname` and `--lsp-logname`" );
(* Please keep these sorted in the alphabetical order *)
]
in
let args = parse_without_command options usage "lsp" in
let root = Wwwroot.interpret_command_line_root_parameter args in
CLsp
{
ClientLsp.from = !from;
config = !config;
ignore_hh_version = !ignore_hh_version;
naming_table = !naming_table;
verbose = !verbose;
root_from_cli = root;
}
let parse_rage_args () =
let usage =
Printf.sprintf "Usage: %s rage [OPTION]... [WWW-ROOT]\n" Sys.argv.(0)
in
let from = ref "" in
let desc = ref None in
let rageid = ref None in
let lsp_log = ref None in
let options =
[
Common_argspecs.from from;
("--desc", Arg.String (fun s -> desc := Some s), " description of problem");
( "--rageid",
Arg.String (fun s -> rageid := Some s),
" (optional) use this id, and finish even if parent process dies" );
( "--lsp-log",
Arg.String (fun s -> lsp_log := Some s),
" (optional) gather lsp logs from this filename" );
]
in
let args = parse_without_command options usage "rage" in
let root = Wwwroot.interpret_command_line_root_parameter args in
(* hh_client normally handles Ctrl+C by printing an exception-stack.
But for us, in an interactive prompt, Ctrl+C is an unexceptional way to quit. *)
Sys_utils.set_signal Sys.sigint Sys.Signal_default;
let desc =
match !desc with
| Some desc -> desc
| None ->
Printf.printf
("Sorry that hh isn't working. What's wrong?\n"
^^ "0. There's something wrong relating to VSCode or IDE\n"
^^ "1. hh_server takes ages to initialize\n"
^^ "2. hh is stuck in an infinite loop\n"
^^ "3. hh gives some error message about the monitor\n"
^^ "4. hack says it has an internal typecheck bug and asked me to report it\n"
^^ "5. hack is reporting errors that are clearly incorrect [please elaborate]\n"
^^ "6. I'm not sure how to write my code to avoid these hack errors\n"
^^ "7. hh says something about unsaved changes from an editor even after I've quit my editor\n"
^^ "8. something's wrong with hack VS Code or other editor\n"
^^ "[other] Please type either one of the above numbers, or a freeform description\n"
^^ "\nrage> %!");
let response = In_channel.input_line_exn In_channel.stdin in
let (response, info) =
if String.equal response "0" then
let () =
Printf.printf
"Please use the VSCode bug nub (at the right of the status bar) instead of hh rage.\n"
in
exit 0
else if String.equal response "1" then
("hh_server slow initialize", `Verbose_hh_start)
else if String.equal response "2" then
("hh stuck in infinite loop", `Verbose_hh_start)
else if String.equal response "3" then
("hh monitor problem", `Verbose_hh_start)
else if String.equal response "4" then begin
ClientRage.verify_typechecker_err_src ();
("internal typecheck bug", `No_info)
end else if String.equal response "5" then
let () =
Printf.printf
"Please elaborate on which errors are incorrect...\nrage> %!"
in
(In_channel.input_line_exn In_channel.stdin, `No_info)
else if String.equal response "6" then
let () =
Printf.printf
("Please ask in the appropriate support groups for advice on coding in Hack; "
^^ "`hh rage` is solely for reporting bugs in the tooling, not for reporting typechecker or "
^^ "language issues.\n")
in
exit 0
else if String.equal response "7" then
("unsaved editor changes", `Unsaved)
else if String.equal response "8" then
let () =
Printf.printf
("Please file the bug from within your editor to capture the right logs. "
^^ "Note: you can do Preferences > Settings > Hack > Verbose, then `pkill hh_client`, "
^^ "then reproduce the error, then file the bug. This way we'll get even richer logs.\n"
)
in
exit 0
else
(response, `Verbose_hh_start)
in
begin
match info with
| `No_info -> ()
| `Verbose_hh_start ->
Printf.printf
("\nPOWER USERS ONLY: Sometimes the normal logging from hh_server isn't "
^^ "enough to diagnose an issue, and we'll ask you to switch hh_server to "
^^ "write verbose logs, then have you repro the issue, then use `hh rage` to "
^^ "gather up those now-verbose logs. To restart hh_server with verbose logs, "
^^ "do `hh stop && hh start --config min_log_level=debug`. "
^^ "Once done, then you can repro the issue, and then do rage again.\n\n%!"
)
| `Unsaved ->
Printf.printf
"\nNote: you can often work around this issue yourself by quitting your editor, then `pkill hh_client`.\n%!"
end;
response
in
CRage
{
ClientRage.root;
from = !from;
desc;
rageid = !rageid;
lsp_log = !lsp_log;
}
let parse_download_saved_state_args () =
let usage =
Printf.sprintf
{|Usage: %s download-saved-state [OPTION]... [WWW-ROOT]
Download a saved-state to disk for the given repository, to make future
invocations of `hh` faster.|}
Sys.argv.(0)
in
let valid_types_message =
"Valid values are: naming-and-dep-table, naming-table"
in
let from = ref "" in
let saved_state_type = ref None in
let should_save_replay = ref false in
let replay_token = ref None in
let saved_state_manifold_api_key = ref None in
let options =
Arg.align
[
Common_argspecs.from from;
( "--type",
Arg.String (fun arg -> saved_state_type := Some arg),
Printf.sprintf
" The type of saved-state to download. %s"
valid_types_message );
( "--save-replay",
Arg.Set should_save_replay,
" Produce a token that can be later consumed by --replay-token to replay the same saved-state download."
);
( "--saved-state-manifold-api-key",
Arg.String (fun arg -> saved_state_manifold_api_key := Some arg),
" An API key for Manifold to use when downloading the specified saved state."
);
( "--replay-token",
Arg.String (fun arg -> replay_token := Some arg),
" A token produced from a previous invocation of this command with --save-replay."
);
]
in
let args = parse_without_command options usage "download-saved-state" in
let root =
match args with
| [] ->
print_endline usage;
exit 2
| _ -> Wwwroot.interpret_command_line_root_parameter args
in
let from =
match !from with
| "" ->
print_endline "The '--from' option is required.";
exit 2
| from -> from
in
let saved_state_type =
match !saved_state_type with
| None ->
Printf.printf "The '--type' option is required. %s\n" valid_types_message;
exit 2
| Some "naming-and-dep-table" ->
ClientDownloadSavedState.Naming_and_dep_table
| Some saved_state_type ->
Printf.printf
"Unrecognized value '%s' for '--type'. %s\n"
saved_state_type
valid_types_message;
exit 2
in
CDownloadSavedState
{
ClientDownloadSavedState.root;
from;
saved_state_type;
saved_state_manifold_api_key = !saved_state_manifold_api_key;
should_save_replay = !should_save_replay;
replay_token = !replay_token;
}
let parse_args ~(from_default : string) : command =
match parse_command () with
| CKNone
| CKCheck ->
CCheck (parse_check_args CKCheck ~from_default)
| CKStart -> parse_start_args ~from_default
| CKStop -> parse_stop_args ~from_default
| CKRestart -> parse_restart_args ~from_default
| CKLsp -> parse_lsp_args ()
| CKRage -> parse_rage_args ()
| CKSavedStateProjectMetadata ->
parse_saved_state_project_metadata_args ~from_default
| CKDownloadSavedState -> parse_download_saved_state_args ()
let root = function
| CCheck { ClientEnv.root; _ }
| CStart { ClientStart.root; _ }
| CRestart { ClientStart.root; _ }
| CStop { ClientStop.root; _ }
| CRage { ClientRage.root; _ }
| CSavedStateProjectMetadata { ClientEnv.root; _ }
| CDownloadSavedState { ClientDownloadSavedState.root; _ } ->
Some root
| CLsp _ -> None
let config = function
| CCheck { ClientEnv.config; _ }
| CStart { ClientStart.config; _ }
| CRestart { ClientStart.config; _ }
| CLsp { ClientLsp.config; _ }
| CSavedStateProjectMetadata { ClientEnv.config; _ } ->
Some config
| CStop _
| CDownloadSavedState _
| CRage _ ->
None
let from = function
| CCheck { ClientEnv.from; _ }
| CStart { ClientStart.from; _ }
| CRestart { ClientStart.from; _ }
| CLsp { ClientLsp.from; _ }
| CSavedStateProjectMetadata { ClientEnv.from; _ }
| CStop { ClientStop.from; _ }
| CDownloadSavedState { ClientDownloadSavedState.from; _ }
| CRage { ClientRage.from; _ } ->
from |
OCaml | hhvm/hphp/hack/src/client/clientAutocomplete.ml | (*
* Copyright (c) 2015, 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 go results output_json =
if output_json then
let results =
List.map results ~f:AutocompleteService.autocomplete_result_to_json
in
print_endline (Hh_json.json_to_string (Hh_json.JSON_Array results))
else
List.iter results ~f:(fun res ->
let name = res.AutocompleteTypes.res_label in
let ty = res.AutocompleteTypes.res_detail in
print_endline (name ^ " " ^ ty)) |
OCaml | hhvm/hphp/hack/src/client/clientCheck.ml | (*
* Copyright (c) 2015, 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 ClientEnv
open Utils
open ClientRename
open Ocaml_overrides
module Rpc = ServerCommandTypes
module SyntaxTree =
Full_fidelity_syntax_tree.WithSyntax (Full_fidelity_positioned_syntax)
(** This is initialized at the start of [main] *)
let ref_local_config : ServerLocalConfig.t option ref = ref None
module SaveStateResultPrinter = ClientResultPrinter.Make (struct
type t = SaveStateServiceTypes.save_state_result
let to_string t =
Printf.sprintf
"Dependency table edges added: %d"
t.SaveStateServiceTypes.dep_table_edges_added
let to_json t =
Hh_json.JSON_Object (ServerError.get_save_state_result_props_json t)
end)
module SaveNamingResultPrinter = ClientResultPrinter.Make (struct
type t = SaveStateServiceTypes.save_naming_result
let to_string t =
Printf.sprintf
"Files added: %d, symbols added: %d"
t.SaveStateServiceTypes.nt_files_added
t.SaveStateServiceTypes.nt_symbols_added
let to_json t =
Hh_json.JSON_Object
[
( "files_added",
Hh_json.JSON_Number
(string_of_int t.SaveStateServiceTypes.nt_files_added) );
( "symbols_added",
Hh_json.JSON_Number
(string_of_int t.SaveStateServiceTypes.nt_symbols_added) );
]
end)
let print_refs (results : (string * Pos.absolute) list) ~(json : bool) : unit =
if json then
FindRefsWireFormat.HackAst.to_string results |> print_endline
else
FindRefsWireFormat.CliHumanReadable.print_results results
let parse_function_or_method_id ~func_action ~meth_action name =
let pieces = Str.split (Str.regexp "::") name in
let default_namespace str =
match Str.first_chars str 1 with
| "\\" -> str
| _ -> "\\" ^ str
in
try
match pieces with
| class_name :: method_name :: _ ->
meth_action (default_namespace class_name) method_name
| fun_name :: _ -> func_action (default_namespace fun_name)
| _ -> raise Exit
with
| _ ->
Printf.eprintf "Invalid input\n";
raise Exit_status.(Exit_with Input_error)
let expand_path file =
let path = Path.make file in
if Path.file_exists path then
Path.to_string path
else
let file = Filename.concat (Sys.getcwd ()) file in
let path = Path.make file in
if Path.file_exists path then
Path.to_string path
else (
Printf.printf "File not found: %s\n" file;
exit 2
)
let parse_position_string ~(split_on : string) arg =
let tpos = Str.split (Str.regexp split_on) arg in
try
match tpos with
| [line; char] -> (int_of_string line, int_of_string char)
| _ -> raise Exit
with
| _ ->
Printf.eprintf "Invalid position\n";
raise Exit_status.(Exit_with Input_error)
let connect ?(use_priority_pipe = false) args =
let {
root;
from;
autostart;
force_dormant_start;
deadline;
no_load;
watchman_debug_logging;
log_inference_constraints;
remote;
show_spinner;
ignore_hh_version;
save_64bit;
save_human_readable_64bit_dep_map;
saved_state_ignore_hhconfig;
prechecked;
mini_state;
config;
allow_non_opt_build;
custom_hhi_path;
custom_telemetry_data;
error_format = _;
gen_saved_ignore_type_errors = _;
paths = _;
max_errors = _;
mode = _;
output_json = _;
sort_results = _;
stdin_name = _;
desc = _;
} =
args
in
let local_config = Option.value_exn !ref_local_config in
ClientConnect.(
connect
{
root;
from;
local_config;
autostart;
force_dormant_start;
deadline;
no_load;
watchman_debug_logging;
log_inference_constraints;
remote;
progress_callback =
ClientSpinner.report
~to_stderr:show_spinner
~angery_reaccs_only:(ClientMessages.angery_reaccs_only ());
do_post_handoff_handshake = true;
ignore_hh_version;
save_64bit;
save_human_readable_64bit_dep_map;
saved_state_ignore_hhconfig;
use_priority_pipe;
prechecked;
mini_state;
config;
custom_hhi_path;
custom_telemetry_data;
allow_non_opt_build;
})
(* This is a function, because server closes the connection after each command,
* so we need to be able to reconnect to retry. *)
type connect_fun = unit -> ClientConnect.conn Lwt.t
let connect_then_close (args : ClientEnv.client_check_env) : unit Lwt.t =
let%lwt ClientConnect.{ channels = (_ic, oc); _ } =
connect args ~use_priority_pipe:true
in
Out_channel.close oc;
(* The connection is derived from [Unix.open_connection]. Its docs explain:
"The two channels returned by [open_connection] share a descriptor
to a socket. Therefore, when the connection is over, you should
call {!Stdlib.close_out} on the output channel, which will also close
the underlying socket. Do not call {!Stdlib.close_in} on the input
channel; it will be collected by the GC eventually." *)
Lwt.return_unit
let rpc_with_connection
(args : ClientEnv.client_check_env)
(command : 'a ServerCommandTypes.t)
(call : connect_fun -> desc:string -> 'a ServerCommandTypes.t -> 'b Lwt.t) :
'b Lwt.t =
let use_priority_pipe = ServerCommand.use_priority_pipe command in
let conn () = connect args ~use_priority_pipe in
let%lwt result = call conn ~desc:args.desc @@ command in
Lwt.return result
let rpc_with_retry
(args : ClientEnv.client_check_env)
(command : 'a ServerCommandTypes.Done_or_retry.t ServerCommandTypes.t) :
'a Lwt.t =
let%lwt result =
rpc_with_connection args command ClientConnect.rpc_with_retry
in
Lwt.return result
let rpc_with_retry_list
(args : ClientEnv.client_check_env)
(command : 'a ServerCommandTypes.Done_or_retry.t list ServerCommandTypes.t)
: 'a list Lwt.t =
let%lwt result =
rpc_with_connection args command ClientConnect.rpc_with_retry_list
in
Lwt.return result
let rpc
(args : ClientEnv.client_check_env) (command : 'result ServerCommandTypes.t)
: ('result * Telemetry.t) Lwt.t =
rpc_with_connection args command (fun conn_f ~desc command ->
let%lwt conn = conn_f () in
let%lwt (result, telemetry) = ClientConnect.rpc conn ~desc command in
Lwt.return (result, telemetry))
let parse_positions positions =
List.map positions ~f:(fun pos ->
try
match Str.split (Str.regexp ":") pos with
| [filename; line; char] ->
(expand_path filename, int_of_string line, int_of_string char)
| _ -> raise Exit
with
| _ ->
Printf.eprintf "Invalid position\n";
raise Exit_status.(Exit_with Input_error))
(* Filters and prints errors when a path is not a realpath *)
let filter_real_paths paths =
List.filter_map paths ~f:(fun fn ->
match Sys_utils.realpath fn with
| Some path -> Some path
| None ->
prerr_endlinef "Could not find file '%s'" fn;
None)
let main_internal
(args : client_check_env)
(local_config : ServerLocalConfig.t)
(partial_telemetry_ref : Telemetry.t option ref) :
(Exit_status.t * Telemetry.t) Lwt.t =
match args.mode with
| MODE_LIST_FILES ->
let%lwt (infol, telemetry) = rpc args @@ Rpc.LIST_FILES_WITH_ERRORS in
List.iter infol ~f:(Printf.printf "%s\n");
Lwt.return (Exit_status.No_error, telemetry)
| MODE_FIND_CLASS_REFS name ->
let%lwt results =
rpc_with_retry args
@@ Rpc.FIND_REFS (ServerCommandTypes.Find_refs.Class name)
in
print_refs results ~json:args.output_json;
Lwt.return (Exit_status.No_error, Telemetry.create ())
| MODE_FIND_REFS name ->
let open ServerCommandTypes.Find_refs in
let action =
parse_function_or_method_id
~meth_action:(fun class_name method_name ->
Member (class_name, Method method_name))
~func_action:(fun fun_name -> Function fun_name)
name
in
let%lwt results = rpc_with_retry args @@ Rpc.FIND_REFS action in
print_refs results ~json:args.output_json;
Lwt.return (Exit_status.No_error, Telemetry.create ())
| MODE_POPULATE_REMOTE_DECLS files ->
let files =
Option.map
files
~f:
(List.map ~f:(fun path ->
Relative_path.create_detect_prefix (expand_path path)))
in
let%lwt (_, telemetry) = rpc args (Rpc.POPULATE_REMOTE_DECLS files) in
Lwt.return (Exit_status.No_error, telemetry)
| MODE_GO_TO_IMPL_CLASS class_name ->
let%lwt results =
rpc_with_retry args
@@ Rpc.GO_TO_IMPL (ServerCommandTypes.Find_refs.Class class_name)
in
print_refs results ~json:args.output_json;
Lwt.return (Exit_status.No_error, Telemetry.create ())
| MODE_GO_TO_IMPL_METHOD name ->
let action =
parse_function_or_method_id
~meth_action:(fun class_name method_name ->
ServerCommandTypes.Find_refs.Member
(class_name, ServerCommandTypes.Find_refs.Method method_name))
~func_action:(fun fun_name ->
ServerCommandTypes.Find_refs.Function fun_name)
name
in
(match action with
| ServerCommandTypes.Find_refs.Member _ ->
let%lwt results = rpc_with_retry args @@ Rpc.GO_TO_IMPL action in
print_refs results ~json:args.output_json;
Lwt.return (Exit_status.No_error, Telemetry.create ())
| _ ->
Printf.eprintf "Invalid input\n";
Lwt.return (Exit_status.Input_error, Telemetry.create ()))
| MODE_IDE_FIND_REFS_BY_SYMBOL arg ->
let%lwt results = rpc_with_retry args @@ Rpc.IDE_FIND_REFS_BY_SYMBOL arg in
FindRefsWireFormat.IdeShellout.to_string results |> print_endline;
Lwt.return (Exit_status.No_error, Telemetry.create ())
| MODE_IDE_GO_TO_IMPL_BY_SYMBOL arg ->
let%lwt results = rpc_with_retry args @@ Rpc.IDE_GO_TO_IMPL_BY_SYMBOL arg in
FindRefsWireFormat.IdeShellout.to_string results |> print_endline;
Lwt.return (Exit_status.No_error, Telemetry.create ())
| MODE_DUMP_SYMBOL_INFO files ->
let%lwt conn = connect args in
let%lwt () = ClientSymbolInfo.go conn ~desc:args.desc files expand_path in
Lwt.return (Exit_status.No_error, Telemetry.create ())
| MODE_RENAME ((ref_mode : rename_mode), before, after) ->
let conn () = connect args in
let%lwt () =
ClientRename.go conn ~desc:args.desc args ref_mode ~before ~after
in
Lwt.return (Exit_status.No_error, Telemetry.create ())
| MODE_IDE_RENAME_BY_SYMBOL arg ->
let open ServerCommandTypes in
let (new_name, action, symbol_definition) = Rename.string_to_args arg in
let%lwt results =
rpc_with_retry args
@@ Rpc.IDE_RENAME_BY_SYMBOL (action, new_name, symbol_definition)
in
begin
match results with
| Ok patches ->
ClientRename.go_ide_from_patches patches args.output_json;
Lwt.return (Exit_status.No_error, Telemetry.create ())
| Error _msg -> raise Exit_status.(Exit_with Input_error)
end
| MODE_EXTRACT_STANDALONE name ->
let open ServerCommandTypes.Extract_standalone in
let target =
parse_function_or_method_id
~meth_action:(fun class_name method_name ->
Method (class_name, method_name))
~func_action:(fun fun_name -> Function fun_name)
name
in
let%lwt (pretty_printed_dependencies, telemetry) =
rpc args @@ Rpc.EXTRACT_STANDALONE target
in
print_endline pretty_printed_dependencies;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_CONCATENATE_ALL ->
let paths = filter_real_paths args.paths in
let%lwt (single_file, telemetry) = rpc args @@ Rpc.CONCATENATE_ALL paths in
print_endline single_file;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_IDENTIFY_SYMBOL arg ->
if not args.output_json then begin
Printf.eprintf "Must use --json\n%!";
raise Exit_status.(Exit_with Input_error)
end;
let%lwt (result, telemetry) = rpc args @@ Rpc.IDENTIFY_SYMBOL arg in
let definition_to_json (d : string SymbolDefinition.t) : Hh_json.json =
Hh_json.JSON_Object
[
("full_name", d.SymbolDefinition.full_name |> Hh_json.string_);
("pos", d.SymbolDefinition.pos |> Pos.json);
( "kind",
d.SymbolDefinition.kind
|> SymbolDefinition.string_of_kind
|> Hh_json.string_ );
]
in
let definitions = List.map result ~f:definition_to_json in
Hh_json.json_to_string (Hh_json.JSON_Array definitions) |> print_endline;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_IDENTIFY_SYMBOL1 arg
| MODE_IDENTIFY_SYMBOL2 arg
| MODE_IDENTIFY_SYMBOL3 arg ->
let (line, char) = parse_position_string ~split_on:":" arg in
let file =
match args.stdin_name with
| None -> ""
| Some f -> expand_path f
in
let content =
ServerCommandTypes.FileContent (Sys_utils.read_stdin_to_string ())
in
let%lwt (result, telemetry) =
rpc args @@ Rpc.IDENTIFY_FUNCTION (file, content, line, char)
in
ClientGetDefinition.go result args.output_json;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_TYPE_AT_POS arg ->
let tpos = Str.split (Str.regexp ":") arg in
let (fn, line, char) =
try
match tpos with
| [filename; line; char] ->
let fn = expand_path filename in
( ServerCommandTypes.FileName fn,
int_of_string line,
int_of_string char )
| [line; char] ->
let content = Sys_utils.read_stdin_to_string () in
( ServerCommandTypes.FileContent content,
int_of_string line,
int_of_string char )
| _ -> raise Exit
with
| _ ->
Printf.eprintf "Invalid position\n";
raise Exit_status.(Exit_with Input_error)
in
let%lwt (ty, telemetry) = rpc args @@ Rpc.INFER_TYPE (fn, line, char) in
ClientTypeAtPos.go ty args.output_json;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_TYPE_AT_POS_BATCH positions ->
let positions =
List.map positions ~f:(fun pos ->
try
match Str.split (Str.regexp ":") pos with
| [filename; line; char] ->
( expand_path filename,
int_of_string line,
int_of_string char,
None )
| [filename; start_line; start_char; end_line; end_char] ->
let filename = expand_path filename in
let start_line = int_of_string start_line in
let start_char = int_of_string start_char in
let end_line = int_of_string end_line in
let end_char = int_of_string end_char in
(filename, start_line, start_char, Some (end_line, end_char))
| _ -> raise Exit
with
| _ ->
Printf.eprintf "Invalid position\n";
raise Exit_status.(Exit_with Input_error))
in
let%lwt (responses, telemetry) =
rpc args @@ Rpc.INFER_TYPE_BATCH positions
in
List.iter responses ~f:print_endline;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_IS_SUBTYPE ->
let stdin = Sys_utils.read_stdin_to_string () in
let%lwt (response, telemetry) = rpc args @@ Rpc.IS_SUBTYPE stdin in
(match response with
| Ok str ->
Printf.printf "%s" str;
Lwt.return (Exit_status.No_error, telemetry)
| Error str ->
Printf.eprintf "%s" str;
raise Exit_status.(Exit_with Input_error))
| MODE_TYPE_ERROR_AT_POS arg ->
let tpos = Str.split (Str.regexp ":") arg in
let (fn, line, char) =
try
match tpos with
| [filename; line; char] ->
let fn = expand_path filename in
( ServerCommandTypes.FileName fn,
int_of_string line,
int_of_string char )
| [line; char] ->
let content = Sys_utils.read_stdin_to_string () in
( ServerCommandTypes.FileContent content,
int_of_string line,
int_of_string char )
| _ -> raise Exit
with
| _ ->
Printf.eprintf
"Invalid position; expected an argument of the form [filename]:[line]:[column] or [line]:[column]\n";
raise Exit_status.(Exit_with Input_error)
in
let%lwt (ty, telemetry) =
rpc args @@ Rpc.INFER_TYPE_ERROR (fn, line, char)
in
ClientTypeErrorAtPos.go ty args.output_json;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_TAST_HOLES arg ->
let parse_hole_filter = function
| "any" -> Some Rpc.Tast_hole.Any
| "typing" -> Some Rpc.Tast_hole.Typing
| "cast" -> Some Rpc.Tast_hole.Cast
| _ -> None
in
let (filename, hole_src_opt) =
try
match Str.(split (regexp ":") arg) with
| [filename; filter_str] ->
let fn = expand_path filename in
(match parse_hole_filter filter_str with
| Some filter -> (ServerCommandTypes.FileName fn, filter)
| _ -> raise Exit)
| [part] ->
(match parse_hole_filter part with
| Some src_opt ->
let content = Sys_utils.read_stdin_to_string () in
(ServerCommandTypes.FileContent content, src_opt)
| _ ->
let fn = expand_path part in
(* No hole source specified; default to `Typing` *)
(ServerCommandTypes.FileName fn, Rpc.Tast_hole.Typing))
| _ -> raise Exit
with
| Exit ->
Printf.eprintf
"Invalid argument; expected an argument of the form [filename](:[any|typing|cast])? or [any|typing|cast]\n";
raise Exit_status.(Exit_with Input_error)
| exn ->
let e = Exception.wrap exn in
Printf.eprintf
"An unexpected error occured: %s"
(Exception.get_ctor_string e);
Exception.reraise e
in
let%lwt (ty, telemetry) =
rpc args @@ Rpc.TAST_HOLES (filename, hole_src_opt)
in
ClientTastHoles.go ty ~print_file:false args.output_json;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_TAST_HOLES_BATCH (file : string) ->
let files =
expand_path file
|> Sys_utils.read_file
|> Bytes.to_string
|> String.strip
|> String.split ~on:'\n'
|> List.map ~f:expand_path
in
let%lwt (holes, telemetry) = rpc args @@ Rpc.TAST_HOLES_BATCH files in
ClientTastHoles.go holes ~print_file:true args.output_json;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_FUN_DEPS_AT_POS_BATCH positions ->
let positions = parse_positions positions in
let%lwt (responses, telemetry) = rpc args @@ Rpc.FUN_DEPS_BATCH positions in
List.iter responses ~f:print_endline;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_DEPS_OUT_AT_POS_BATCH positions ->
let positions = parse_positions positions in
let%lwt (responses, telemetry) = rpc args @@ Rpc.DEPS_OUT_BATCH positions in
List.iter responses ~f:print_endline;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_XHP_AUTOCOMPLETE_SNIPPET cls ->
let%lwt (result, telemetry) =
rpc args @@ Rpc.XHP_AUTOCOMPLETE_SNIPPET cls
in
let _ =
match result with
| Some str -> print_endline str
| None -> print_endline "<null>"
in
Lwt.return (Exit_status.No_error, telemetry)
| MODE_OUTLINE
| MODE_OUTLINE2 ->
let (_handle : SharedMem.handle) =
SharedMem.init ~num_workers:0 SharedMem.default_config
in
let content = Sys_utils.read_stdin_to_string () in
let results =
FileOutline.outline
(*
* TODO: Don't use default parser options.
*
* Parser options enables certain features (such as namespace aliasing)
* Thus, for absolute correctness of outlining, we need to use the same
* parser options that the server uses. But this client request doesn't
* hit the server at all. So either change this to a server RPC, or
* ask the server what its parser options are, or parse the
* options from the .hhconfig file (needs to be the same hhconfig file the
* server used).
* *)
ParserOptions.default
content
in
ClientOutline.go results args.output_json;
Lwt.return (Exit_status.No_error, Telemetry.create ())
| MODE_METHOD_JUMP_CHILDREN class_ ->
let filter = ServerCommandTypes.Method_jumps.No_filter in
let%lwt (results, telemetry) =
rpc args @@ Rpc.METHOD_JUMP (class_, filter, true)
in
ClientMethodJumps.go results true args.output_json;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_METHOD_JUMP_ANCESTORS (class_, filter) ->
let filter =
match MethodJumps.string_filter_to_method_jump_filter filter with
| Some filter -> filter
| None ->
Printf.eprintf "Invalid method jump filter %s\n" filter;
raise Exit_status.(Exit_with Input_error)
in
let%lwt (results, telemetry) =
rpc args @@ Rpc.METHOD_JUMP (class_, filter, false)
in
ClientMethodJumps.go results false args.output_json;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_METHOD_JUMP_ANCESTORS_BATCH (classes, filter) ->
let filter =
match MethodJumps.string_filter_to_method_jump_filter filter with
| Some filter -> filter
| None ->
Printf.eprintf "Invalid method jump filter %s\n" filter;
raise Exit_status.(Exit_with Input_error)
in
let%lwt (results, telemetry) =
rpc args @@ Rpc.METHOD_JUMP_BATCH (classes, filter)
in
ClientMethodJumps.go results false args.output_json;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_IN_MEMORY_DEP_TABLE_SIZE ->
let%lwt (result, telemetry) = rpc args @@ Rpc.IN_MEMORY_DEP_TABLE_SIZE in
ClientResultPrinter.Int_printer.go result args.output_json;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_SAVE_NAMING path ->
let () = Sys_utils.mkdir_p (Filename.dirname path) in
let path = Path.make path in
let%lwt (result, telemetry) =
rpc args @@ Rpc.SAVE_NAMING (Path.to_string path)
in
SaveNamingResultPrinter.go result args.output_json;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_SAVE_STATE path ->
let () = Sys_utils.mkdir_p (Filename.dirname path) in
(* Convert to real path because Client and Server may have
* different cwd and we want to use the client processes' cwd. *)
let path = Path.make path in
let%lwt (result, telemetry) =
rpc args
@@ Rpc.SAVE_STATE (Path.to_string path, args.gen_saved_ignore_type_errors)
in
SaveStateResultPrinter.go result args.output_json;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_STATUS ->
let ignore_ide = ClientMessages.ignore_ide_from args.from in
let prechecked = Option.value args.prechecked ~default:true in
let%lwt ((), telemetry1) =
if prechecked then
Lwt.return ((), Telemetry.create ())
else
rpc args Rpc.NO_PRECHECKED_FILES
in
(* We don't do streaming errors under [output_json]: our contract
with the outside world is that if a caller uses [output_json] then they
will never see [Exit_status.Typecheck_restarted], which streaming might show.
We don't do streaming errors under [not prechecked]. That's because the
[go_streaming] contract is to report on a typecheck that reflects all *file*
changes up until now; it has no guarantee that the typecheck will reflects our
preceding call to Rpc.NO_PRECHECKED_FILES. *)
let use_streaming =
local_config.ServerLocalConfig.consume_streaming_errors
&& (not args.output_json)
&& prechecked
in
if use_streaming then
let%lwt (exit_status, telemetry) =
ClientCheckStatus.go_streaming
args
~partial_telemetry_ref
~connect_then_close:(fun () -> connect_then_close args)
in
Lwt.return (exit_status, telemetry)
else
let%lwt (status, telemetry) =
rpc
args
(Rpc.STATUS
{ ignore_ide; max_errors = args.max_errors; remote = args.remote })
in
let exit_status =
ClientCheckStatus.go
status
args.output_json
args.from
args.error_format
args.max_errors
in
let telemetry =
telemetry
|> Telemetry.bool_ ~key:"streaming" ~value:false
|> Telemetry.object_ ~key:"no_prechecked" ~value:telemetry1
|> Telemetry.object_opt
~key:"last_recheck_stats"
~value:status.Rpc.Server_status.last_recheck_stats
in
Lwt.return (exit_status, telemetry)
| MODE_STATUS_SINGLE filenames ->
let file_input filename =
match filename with
| "-" ->
ServerCommandTypes.FileContent (Sys_utils.read_stdin_to_string ())
| _ -> ServerCommandTypes.FileName (expand_path filename)
in
let file_inputs = List.map ~f:file_input filenames in
let%lwt ((error_list, dropped_count), telemetry) =
rpc
args
(Rpc.STATUS_SINGLE
{ file_names = file_inputs; max_errors = args.max_errors })
in
let status =
{
error_list;
dropped_count;
Rpc.Server_status.liveness = Rpc.Live_status;
has_unsaved_changes = false;
last_recheck_stats = None;
}
in
let exit_status =
ClientCheckStatus.go
status
args.output_json
args.from
args.error_format
args.max_errors
in
Lwt.return (exit_status, telemetry)
| MODE_SEARCH (query, type_) ->
let%lwt (results, telemetry) = rpc args @@ Rpc.SEARCH (query, type_) in
ClientSearch.go results args.output_json;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_LINT ->
let fnl = filter_real_paths args.paths in
begin
match args.paths with
| [] ->
prerr_endline "No lint errors (0 files checked)!";
prerr_endline "Note: --lint expects a list of filenames to check.";
Lwt.return (Exit_status.No_error, Telemetry.create ())
| _ ->
let%lwt (results, telemetry) = rpc args @@ Rpc.LINT fnl in
ClientLint.go results args.output_json args.error_format;
Lwt.return (Exit_status.No_error, telemetry)
end
| MODE_SERVER_RAGE ->
let open ServerRageTypes in
let open Hh_json in
if not args.output_json then begin
Printf.eprintf "Must use --json\n%!";
raise Exit_status.(Exit_with Input_error)
end;
(* Our json output format is read by clientRage.ml *)
let make_item { title; data } =
JSON_Object [("name", JSON_String title); ("contents", JSON_String data)]
in
let%lwt (items, telemetry) = rpc args Rpc.RAGE in
json_to_string (JSON_Array (List.map items ~f:make_item)) |> print_endline;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_LINT_STDIN filename -> begin
match Sys_utils.realpath filename with
| None ->
prerr_endlinef "Could not find file '%s'" filename;
Lwt.return (Exit_status.Input_error, Telemetry.create ())
| Some filename ->
let contents = Sys_utils.read_stdin_to_string () in
let%lwt (results, telemetry) =
rpc args @@ Rpc.LINT_STDIN { ServerCommandTypes.filename; contents }
in
ClientLint.go results args.output_json args.error_format;
Lwt.return (Exit_status.No_error, telemetry)
end
| MODE_LINT_ALL code ->
let%lwt (results, telemetry) = rpc args @@ Rpc.LINT_ALL code in
ClientLint.go results args.output_json args.error_format;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_CREATE_CHECKPOINT x ->
let%lwt ((), telemetry) = rpc args @@ Rpc.CREATE_CHECKPOINT x in
Lwt.return (Exit_status.No_error, telemetry)
| MODE_RETRIEVE_CHECKPOINT x ->
let%lwt (results, telemetry) = rpc args @@ Rpc.RETRIEVE_CHECKPOINT x in
begin
match results with
| Some results ->
List.iter results ~f:print_endline;
Lwt.return (Exit_status.No_error, telemetry)
| None -> Lwt.return (Exit_status.Checkpoint_error, telemetry)
end
| MODE_DELETE_CHECKPOINT x ->
let%lwt (results, telemetry) = rpc args @@ Rpc.DELETE_CHECKPOINT x in
let exit_status =
if results then
Exit_status.No_error
else
Exit_status.Checkpoint_error
in
Lwt.return (exit_status, telemetry)
| MODE_STATS ->
let%lwt (stats, telemetry) = rpc args @@ Rpc.STATS in
print_string @@ Hh_json.json_to_multiline (Stats.to_json stats);
Lwt.return (Exit_status.No_error, telemetry)
| MODE_REMOVE_DEAD_FIXMES codes ->
(* we need to confirm that the server is not already started
* in a non-no-load (yes-load) state
*)
let%lwt conn = connect args in
let%lwt (response, telemetry) =
ClientConnect.rpc conn ~desc:args.desc @@ Rpc.REMOVE_DEAD_FIXMES codes
in
begin
match response with
| `Error msg ->
Printf.eprintf "%s\n" msg;
Lwt.return (Exit_status.Type_error, telemetry)
| `Ok patches ->
if args.output_json then
print_patches_json patches
else
apply_patches patches;
Lwt.return (Exit_status.No_error, telemetry)
end
| MODE_REMOVE_DEAD_UNSAFE_CASTS ->
let status_cmd =
Rpc.STATUS
{ ignore_ide = true; max_errors = args.max_errors; remote = false }
in
let rec go () =
let%lwt (response, telemetry) =
rpc args @@ Rpc.REMOVE_DEAD_UNSAFE_CASTS
in
match response with
| `Error msg ->
Printf.eprintf "%s\n" msg;
Lwt.return (Exit_status.Type_error, telemetry)
| `Ok patches ->
apply_patches patches;
if List.is_empty patches then
Lwt.return (Exit_status.No_error, telemetry)
else
let%lwt _ = rpc args status_cmd in
go ()
in
go ()
| MODE_CODEMOD_SDT
{ csdt_path_to_jsonl; csdt_strategy; csdt_log_remotely; csdt_tag } ->
let status_cmd =
Rpc.STATUS
{ ignore_ide = true; max_errors = args.max_errors; remote = false }
in
let get_error_count () =
let%lwt (status, telemetry) = rpc args status_cmd in
let error_count =
status.ServerCommandTypes.Server_status.error_list |> List.length
in
Lwt.return (error_count, telemetry)
in
let get_patches codemod_line = rpc args (Rpc.CODEMOD_SDT codemod_line) in
Sdt_analysis.ClientCheck.apply_all
~get_error_count
~get_patches
~apply_patches
~path_to_jsonl:csdt_path_to_jsonl
~strategy:csdt_strategy
~log_remotely:csdt_log_remotely
~tag:csdt_tag
| MODE_REWRITE_LAMBDA_PARAMETERS files ->
let%lwt conn = connect args in
let%lwt (patches, telemetry) =
ClientConnect.rpc conn ~desc:args.desc
@@ Rpc.REWRITE_LAMBDA_PARAMETERS files
in
if args.output_json then
print_patches_json patches
else
apply_patches patches;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_FORMAT (from, to_) ->
let content = Sys_utils.read_stdin_to_string () in
let%lwt (result, telemetry) = rpc args @@ Rpc.FORMAT (content, from, to_) in
ClientFormat.go result args.output_json;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_FULL_FIDELITY_PARSE file ->
(* We can cheaply do this on the client today, but we might want to
do it on the server and cache the results in the future. *)
let do_it_on_server = false in
let%lwt (results, telemetry) =
if do_it_on_server then
rpc args @@ Rpc.DUMP_FULL_FIDELITY_PARSE file
else
let file = Relative_path.create Relative_path.Dummy file in
let source_text = Full_fidelity_source_text.from_file file in
let syntax_tree = SyntaxTree.make source_text in
let json = SyntaxTree.to_json syntax_tree in
Lwt.return (Hh_json.json_to_string json, Telemetry.create ())
in
ClientFullFidelityParse.go results;
Lwt.return (Exit_status.No_error, telemetry)
| MODE_FULL_FIDELITY_SCHEMA ->
let schema = Full_fidelity_schema.schema_as_json () in
print_string schema;
Lwt.return (Exit_status.No_error, Telemetry.create ())
| MODE_CST_SEARCH files_to_search ->
let sort_results = args.sort_results in
let input = Sys_utils.read_stdin_to_string () |> Hh_json.json_of_string in
let%lwt (result, telemetry) =
rpc args @@ Rpc.CST_SEARCH { Rpc.sort_results; input; files_to_search }
in
begin
match result with
| Ok result ->
print_endline (Hh_json.json_to_string result);
Lwt.return (Exit_status.No_error, telemetry)
| Error error ->
print_endline error;
raise Exit_status.(Exit_with Input_error)
end
| MODE_FILE_LEVEL_DEPENDENCIES ->
let paths = filter_real_paths args.paths in
let%lwt (responses, telemetry) = rpc args @@ Rpc.FILE_DEPENDENTS paths in
if args.output_json then
Hh_json.(
let json_path_list =
List.map responses ~f:(fun path -> JSON_String path)
in
let output = JSON_Object [("dependents", JSON_Array json_path_list)] in
print_endline @@ json_to_string output)
else
List.iter responses ~f:(Printf.printf "%s\n");
Lwt.return (Exit_status.No_error, telemetry)
| MODE_PAUSE pause ->
let%lwt ((), telemetry) = rpc args @@ Rpc.PAUSE pause in
if pause then (
print_endline
"Paused the automatic triggering of full checks upon file changes.";
print_endline "To manually trigger a full check, do `hh check`.";
print_endline "***PAUSE MODE CURRENTLY GETS RESET UPON REBASES.***";
print_endline "***PAUSE MODE IS EXPERIMENTAL. USE AT YOUR OWN RISK.***"
) else
print_endline
"Resumed the automatic triggering of full checks upon file changes.";
Lwt.return (Exit_status.No_error, telemetry)
| MODE_VERBOSE verbose ->
let%lwt ((), telemetry) = rpc args @@ Rpc.VERBOSE verbose in
Lwt.return (Exit_status.No_error, telemetry)
| MODE_DEPS_IN_AT_POS_BATCH positions ->
let positions = parse_positions positions in
let%lwt results = rpc_with_retry_list args @@ Rpc.DEPS_IN_BATCH positions in
List.iter results ~f:(fun s -> print_refs s ~json:true);
Lwt.return (Exit_status.No_error, Telemetry.create ())
let rec flush_event_logger () : unit Lwt.t =
let%lwt () = Lwt_unix.sleep 1.0 in
let%lwt () = EventLoggerLwt.flush () in
flush_event_logger ()
let main
(args : client_check_env)
(local_config : ServerLocalConfig.t)
~(init_proc_stack : string list option) : 'a =
ref_local_config := Some local_config;
(* That's a hack, just to avoid having to pass local_config into loads of callsites
in this module. *)
let mode_s = ClientEnv.Variants_of_client_mode.to_name args.mode in
HackEventLogger.set_from args.from;
HackEventLogger.client_set_mode mode_s;
HackEventLogger.client_check_start ();
ClientSpinner.start_heartbeat_telemetry ();
Lwt.dont_wait flush_event_logger (fun _exn -> ());
let partial_telemetry_ref = ref None in
try
(* Note: SIGINT exception handler is typically raised from [run_main], not from
the lwt code that's running in [main_internal]. Thus, [Lwt_utils.run_main]'s caller is
the only place that we can deal with it. This also motivates the use of a reference
[partial_telemetry_ref], since there's no way for a return value to survive SIGINT. *)
let (exit_status, telemetry) =
Lwt_utils.run_main (fun () ->
main_internal args local_config partial_telemetry_ref)
in
let spinner = ClientSpinner.get_latest_report () in
HackEventLogger.client_check exit_status telemetry ~init_proc_stack ~spinner;
Hh_logger.log "CLIENT_CHECK %s" (Exit_status.show exit_status);
Exit.exit exit_status
with
| exn ->
let e = Exception.wrap exn in
let spinner = ClientSpinner.get_latest_report () in
(* hide the spinner *)
ClientSpinner.report ~to_stderr:false ~angery_reaccs_only:false None;
let exit_status =
match exn with
| Exit_status.Exit_with exit_status ->
(* we assume that whoever raised [Exit_with] had the decency to print an explanation *)
exit_status
| _ ->
(* if it was uncaught, then presumably no one else has printed it, so it's up to us.
Let's include lots of details, including stack trace. *)
let exit_status = Exit_status.Uncaught_exception e in
Printf.eprintf "%s\n%!" (Exit_status.show_expanded exit_status);
exit_status
in
begin
match (exit_status, !partial_telemetry_ref) with
| (Exit_status.(Interrupted | Client_broken_pipe), Some telemetry) ->
(* [Interrupted] is raised by a SIGINT exit-handler installed in hh_client.
[Client_broken_pipe] is raised in [clientCheckStatus.go_streaming] when
it can't write errors to the pipe. *)
HackEventLogger.client_check_partial
exit_status
telemetry
~init_proc_stack
~spinner;
Hh_logger.log
"CLIENT_CHECK_PARTIAL [%s] %s"
(Option.value_map spinner ~f:fst ~default:"")
(Exit_status.show exit_status)
| _ ->
HackEventLogger.client_check_bad_exit
exit_status
e
~init_proc_stack
~spinner;
Hh_logger.log
"CLIENT_CHECK_EXIT [%s] %s"
(Option.value_map spinner ~f:fst ~default:"")
(Exit_status.show_expanded exit_status)
end;
Exit.exit exit_status |
OCaml Interface | hhvm/hphp/hack/src/client/clientCheck.mli | (*
* 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.
*
*)
(** This function never returns; it always calls [Exit.exit] *)
val main :
ClientEnv.client_check_env ->
ServerLocalConfig.t ->
init_proc_stack:string list option ->
'a |
OCaml | hhvm/hphp/hack/src/client/clientCheckStatus.ml | (*
* Copyright (c) 2015, 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 ServerCommandTypes
let print_error_raw e = Printf.printf "%s" (Raw_error_formatter.to_string e)
let print_error_plain e = Printf.printf "%s" (Errors.to_string e)
let print_error_contextual e =
Printf.printf "%s" (Contextual_error_formatter.to_string e)
let print_error_highlighted e =
Printf.printf "%s" (Highlighted_error_formatter.to_string e)
let print_error ~(error_format : Errors.format) (e : Errors.finalized_error) :
unit =
match error_format with
| Errors.Raw -> print_error_raw e
| Errors.Plain -> print_error_plain e
| Errors.Context -> print_error_contextual e
| Errors.Highlighted -> print_error_highlighted e
let is_stale_msg liveness =
match liveness with
| Stale_status ->
Some
("(but this may be stale, probably due to"
^ " watchman being unresponsive)\n")
| Live_status -> None
let warn_unsaved_changes () =
(* Make sure any buffered diagnostics are printed before printing this
warning. *)
Out_channel.flush stdout;
Tty.cprintf (Tty.Bold Tty.Yellow) "Warning: " ~out_channel:stderr;
prerr_endline
{|there is an editor connected to the Hack server.
The errors above may reflect your unsaved changes in the editor.|}
let go status output_json from error_format max_errors =
let {
Server_status.liveness;
has_unsaved_changes;
error_list;
dropped_count;
last_recheck_stats;
} =
status
in
let stale_msg = is_stale_msg liveness in
if
output_json
|| (not (String.equal from "" || String.equal from "[sh]"))
|| List.is_empty error_list
then
ServerError.print_error_list
stdout
~stale_msg
~output_json
~error_list
~save_state_result:None
~recheck_stats:last_recheck_stats
else begin
List.iter error_list ~f:(print_error ~error_format);
Option.iter
(Errors.format_summary
error_format
~displayed_count:(List.length error_list)
~dropped_count:(Some dropped_count)
~max_errors)
~f:(fun msg -> Printf.printf "%s" msg);
(* [stale_msg] ultimately comes from [ServerMain.query_notifier], and says whether the check
reflects data from a watchman sync, or just whatever has arrived so far over the watchman
subscription. *)
Option.iter stale_msg ~f:(fun msg -> Printf.printf "%s" msg);
(* [has_unsaved_changes] ultimately comes from whether clientLsp has a persistent
connection to hh_server, and has done IDE_OPEN/IDE_CHANGE rpc messages which are now
different from what's on disk. *)
if has_unsaved_changes then warn_unsaved_changes ()
end;
if List.is_empty error_list then
Exit_status.No_error
else
Exit_status.Type_error
(** This function produces streaming errors: it reads the errors.bin opened
as [fd], displays errors as they come using the [args.error_format] over stdout, and
displays a progress-spinner over stderr if [args.show_spinner]. It keeps "tailing"
[fd] until eventually the producing process writes an end-sentinel in it (signalling
that the typecheck has been completed or restarted or aborted), or until the producing
process terminates. *)
let go_streaming_on_fd
~(pid : int)
(fd : Unix.file_descr)
(args : ClientEnv.client_check_env)
~(partial_telemetry_ref : Telemetry.t option ref)
~(progress_callback : string option -> unit) :
(Exit_status.t * Telemetry.t) Lwt.t =
let ClientEnv.{ max_errors; error_format; _ } = args in
let errors_stream = ServerProgressLwt.watch_errors_file ~pid fd in
let start_time = Unix.gettimeofday () in
let first_error_time = ref None in
let latest_progress = ref None in
let errors_file_telemetry = ref (Telemetry.create ()) in
(* This constructs a telemetry that we'll use for both partial-progress
and completed events. *)
let telemetry_so_far displayed_count =
!errors_file_telemetry
|> Telemetry.bool_ ~key:"streaming" ~value:true
|> Telemetry.int_opt ~key:"max_errors" ~value:max_errors
|> Telemetry.float_opt
~key:"first_error_time"
~value:(Option.map !first_error_time ~f:(fun t -> t -. start_time))
|> Telemetry.int_ ~key:"displayed_count" ~value:displayed_count
in
(* If the user does Ctrl+C, it generates SIGINT and we can't run any code in response.
But we'd still like to report telemetry in that case. So we pre-emptively store
telemetry in [partial_telemetry_ref] which the SIGINT handler will be able to read:
if it finds [Some], then the SIGINT handler will deem the operation a success
and will log CLIENT_CHECK_PARTIAL instead of CLIENT_CHECK_BAD_EXIT. *)
let update_partial_telemetry displayed_count =
if displayed_count > 0 then
partial_telemetry_ref := Some (telemetry_so_far displayed_count)
in
(* this lwt process reads the progress.json file once a second and displays a spinner;
it never terminates *)
let rec show_progress () : 'a Lwt.t =
let message =
try (ServerProgress.read ()).ServerProgress.message with
| _ -> "unknown"
in
latest_progress := Some message;
progress_callback !latest_progress;
let%lwt () = Lwt_unix.sleep 1.0 in
show_progress ()
in
(* this lwt process consumes errors from the errors.bin file by polling
every 0.2s, and displays them. It terminates once the errors.bin file has an "end"
sentinel written to it, or the process that was writing errors.bin terminates. *)
let rec consume (displayed_count : int) :
(int * ServerProgress.errors_file_error * string) Lwt.t =
let%lwt errors = Lwt_stream.get errors_stream in
match errors with
| None ->
(* The contract of [errors_stream] (from [ServerProgressLwt.watch_errors_file]) is
that it will always have a single [Some error] item as its last item, before the
stream is closed and hence subsequent [Lwt_stream.get] return [None].
If we're here, it means that contract has been violated. *)
failwith "Expected end_sentinel before end of stream"
| Some (Error (end_sentinel, log_message)) ->
Lwt.return (displayed_count, end_sentinel, log_message)
| Some (Ok (ServerProgress.Telemetry telemetry_item)) ->
errors_file_telemetry :=
Telemetry.merge !errors_file_telemetry telemetry_item;
update_partial_telemetry displayed_count;
consume displayed_count
| Some (Ok (ServerProgress.Errors { errors; timestamp = _ })) ->
first_error_time :=
Option.first_some !first_error_time (Some (Unix.gettimeofday ()));
(* We'll clear the spinner, print errs to stdout, flush stdout, and restore the spinner *)
progress_callback None;
let found_new = ref 0 in
begin
try
Relative_path.Map.iter errors ~f:(fun _path errors_in_file ->
List.iter errors_in_file ~f:(fun error ->
incr found_new;
print_error ~error_format error));
Printf.printf "%!"
with
| Sys_error msg when String.equal msg "Broken pipe" ->
(* We catch this error very locally, as small as we can around [printf],
since if we caught it more globally then we'd not know which pipe raised it --
the pipe to stdout, or stderr, or the pipe used to connect to monitor/server. *)
let backtrace = Stdlib.Printexc.get_raw_backtrace () in
Stdlib.Printexc.raise_with_backtrace
Exit_status.(Exit_with Client_broken_pipe)
backtrace
end;
progress_callback !latest_progress;
let displayed_count = displayed_count + !found_new in
update_partial_telemetry displayed_count;
if displayed_count >= Option.value max_errors ~default:Int.max_value then
Lwt.return
( displayed_count,
ServerProgress.Complete (Telemetry.create ()),
"max-errors" )
else
consume displayed_count
in
(* We will show progress indefinitely until "consume" finishes,
at which Lwt.pick will cancel show_progress. *)
let%lwt (displayed_count, end_sentinel, _log_message) =
Lwt.pick [consume 0; show_progress ()]
in
(* Clear the spinner *)
progress_callback None;
let (exit_status, telemetry) =
match end_sentinel with
| ServerProgress.Complete telemetry ->
(* complete either because the server completed, or we truncated early *)
Option.iter
(Errors.format_summary
error_format
~displayed_count
~dropped_count:None
~max_errors)
~f:(fun msg -> Printf.printf "%s" msg);
let telemetry =
Telemetry.merge (telemetry_so_far displayed_count) telemetry
in
if displayed_count = 0 then
(Exit_status.No_error, telemetry)
else
(Exit_status.Type_error, telemetry)
| ServerProgress.Restarted { user_message; log_message } ->
Hh_logger.log
"Errors-file: on %s, read Restarted(%s,%s)"
(Sys_utils.show_inode fd)
user_message
log_message;
HackEventLogger.client_check_errors_file_restarted
(user_message ^ "\n" ^ log_message);
(* All errors, warnings, informationals go to stdout. *)
let msg =
Tty.apply_color (Tty.Bold Tty.Red) (user_message ^ "\nPlease re-run hh.")
in
Printf.printf "\n%s\n%!" msg;
raise Exit_status.(Exit_with Exit_status.Typecheck_restarted)
| _ ->
Hh_logger.log
"Errors-file: on %s, read %s"
(Sys_utils.show_inode fd)
(ServerProgress.show_errors_file_error end_sentinel);
Printf.printf
"Hh_server has terminated. [%s]\n%!"
(ServerProgress.show_errors_file_error end_sentinel);
raise Exit_status.(Exit_with Exit_status.Typecheck_abandoned)
in
Lwt.return (exit_status, telemetry)
(** Gets all files-changed since [clock] which match the standard hack
predicate [FilesToIgnore.watchman_server_expression_terms].
The returns are relative to the watchman root.
CARE! This is not the same as a Relative_path.t. For instance if root
contains a symlink root/a.php ~> /tmp/b.php and the symlink itself
changed, then watchman would report a change on "a.php" but Relative_path.t
by definition only refers to paths after symlinks have been resolved
which in this case would be (Relative_path.Tmp,"b.php").
The caller must explicitly pass in [~fail_on_new_instance:false]
and [~fail_during_state:false] so that the callsite is self-documenting
about what it will do during these two scenarios. (no other options
are currently supported.) *)
let watchman_get_raw_updates_since
~(root : Path.t)
~(clock : Watchman.clock)
~(fail_on_new_instance : bool)
~(fail_during_state : bool) : (string list, string) result Lwt.t =
if fail_on_new_instance then
failwith "Not yet implemented: fail_on_new_instance";
if fail_during_state then failwith "Not yet implemented: fail_during_state";
let query =
Hh_json.(
JSON_Array
[
JSON_String "query";
JSON_String (Path.to_string root);
JSON_Object
[
("since", JSON_String clock);
("fields", JSON_Array [JSON_String "name"]);
( "expression",
Hh_json_helpers.AdhocJsonHelpers.pred
"allof"
FilesToIgnore.watchman_server_expression_terms );
];
])
|> Hh_json.json_to_string
in
Hh_logger.log "watchman query: %s" query;
let%lwt result =
Lwt_utils.exec_checked Exec_command.Watchman ~input:query [| "-j" |]
in
match result with
| Error e ->
let msg = Lwt_utils.Process_failure.to_string e in
Hh_logger.log "watchman response: %s" msg;
Lwt.return_error msg
| Ok { Lwt_utils.Process_success.stdout; _ } -> begin
let files =
try
let json = Hh_json.json_of_string stdout in
Ok (json, Hh_json_helpers.Jget.string_array_exn (Some json) "files")
with
| exn -> Error (Exception.wrap exn)
in
match files with
| Error e ->
let msg = Exception.to_string e in
Hh_logger.log "watchman parse failure: %s\nRESPONSE:%s\n" msg stdout;
Lwt.return_error msg
| Ok (json, files) ->
let has_changed = ref false in
let json_str =
Hh_json.json_truncate ~max_array_elt_count:10 ~has_changed json
|> Hh_json.json_to_string
in
let has_changed =
if !has_changed then
" [truncated]"
else
""
in
Hh_logger.log "watchman response:%s %s" has_changed json_str;
Lwt.return_ok files
end
(** This helper will trying to open the errors.bin file.
There is a whole load of ceremony to do with what happens when you want to open errors.bin,
e.g. start the server if necessary, check for version mismatch, report failures to the user.
Concrete examples:
* There is no server running. "hh check" must start up a server, before it can stream errors from it.
* There is no server running, but our attempt to start the server failed, either
synchronously (e.g. we had `--autostart-server false`)
or asynchronously (e.g. saved-state failed to load).
"hh check" must detect that no streaming errors are forthcoming.
* There is a server running, and it has already written errors.bin, but it is the wrong binary version.
"hh check" must cause it to shut down, and a new server start up, before it can stream errors.
* There is an errors.bin from an existing server, and its typecheck started 20s ago, but moments
before "hh check" a file was changed on disk. "hh check" must detect this,
learn that it cannot use the existing errors.bin, and instead use the new errors.bin that will be forthcoming.
How this function fulfills those cases:
* It of course has to check whether files on disk have changed since this errors.bin was started.
It does this with a synchronous watchman query,
and displays "hh_server is busy [watchman sync]".
* If there is a fault like "errors.bin was started too long ago and files have changed
in the meantime" which can be rectified by waiting and trying again on the assumption
that a server is running and will pick up the changes, then this will wait and try
again indefinitely. It will display "hh_server is busy [hh_server sync]".
The parameter [already_checked_clock] indicates that we have already done a
(costly) watchman query for this clock, and will not do another watchman query until
we see a new errors.bin which started at a different (newer) clock.
* If there is a fault like "missing errors.bin" or "binary mismatch" which can
be rectified by connecting to the monitor+server, this will do so at most once
with the [connect_then_close] callback parameter, then resume looking for a
suitable errors.bin again with "hh_server is busy [hh_server sync]".
If it already tried once with no effect, then it will raise Exit_status.Exit_with.
Here's a really subtle example involving precise details of the errors.bin clock:
1. server starts a check at clock0, hence starts errors.bin as of clock0
2. modify file A
3. modify file B
4. user does "hh", sees that files have changed since clock0, so repeats [keep_trying_to_open]
5. server picks up change to file A and restarts errors.bin as of clockA
6. repeat of [keep_trying_to_open] must NOT use errors.bin since that would miss "B"
There are two implementations we could imagine for the repeat of [keep_trying_to_open]:
(A) on subsequent repeats, it could either keep waiting until an errors.bin comes about
which has a clock that's more recent than the start time of "hh"; or (B) it could keep
waiting until an errors.bin comes about where there are no changed files between
errors.bin's start time and "now". Both are correct; the former is more principled,
would result in more "files changed under your feet", but alas there doesn't exist
the ability in watchman to compare two clocks so we can't use it. Therefore we use (B).
How do we know that (B) will eventually terminate? Well if the user keeps modifying
files then it never will! But if the user stops, then hh_server is guaranteed to
do a final recheck, hence guaranteed to write an errors.bin with no files changed
after it, and hence [keep_trying_to_open] is guaranteed to eventually terminate.
The semantics of the [deadline] parameter are that this is how long we'll wait
until we open an errors.bin file (i.e. until the typecheck has started). We don't
expose a parameter to control how long the typecheck must last.
SPINNER! This is surprisingly delicate. If we leave our spinner up and then
the process exits, the user sees a dead spinner in the line above their bash prompt.
If we leave our spinner up and then print an error message to stderr, the user
sees a dead spinner above the error message (and perhaps even another spinner down
below if we continued work). In summary it's crucial to clear out the spinner at the right time:
* [connect_then_close] is assumed to clear the spinner in case it writes to stderr
* This function clears the spinner in case of exceptions
* But it leaves the spinner at "watchman sync" in case of success, in the expectation
that subsequent code will update the spinner. *)
let rec keep_trying_to_open
~(has_already_attempted_connect : bool)
~(connect_then_close : unit -> unit Lwt.t)
~(already_checked_clock : Watchman.clock option)
~(progress_callback : string option -> unit)
~(deadline : float option)
~(root : Path.t) : (int * Unix.file_descr) Lwt.t =
Option.iter deadline ~f:(fun deadline ->
if Float.(Unix.gettimeofday () > deadline) then begin
progress_callback None;
raise (Exit_status.Exit_with Exit_status.Out_of_time)
end);
progress_callback (Some "hh_server sync");
let fd_opt =
try
Some
(Unix.openfile
(ServerFiles.errors_file_path root)
[Unix.O_RDONLY; Unix.O_NONBLOCK]
0)
with
| _ -> None
in
match fd_opt with
| None ->
(* If no existing file, then there must not yet be a server up and running.
So, connect to the monitor and wait for server "hello" as proof that the server
started okay. Our call might fail, e.g. in case of --autostart false or failure to
load saved-state. In these cases, it will raise an ExitStatus exception which
bubbles up to our caller. *)
let%lwt () =
if not has_already_attempted_connect then begin
Hh_logger.log "Errors-file: absent, so connecting then trying again";
let%lwt () = connect_then_close () in
Lwt.return_unit
end else begin
(* Retry opening errors file every 0.1 second from now on. *)
let%lwt () = Lwt_unix.sleep 0.1 in
Lwt.return_unit
end
in
keep_trying_to_open
~has_already_attempted_connect:true
~connect_then_close
~already_checked_clock
~progress_callback
~deadline
~root
| Some fd -> begin
match ServerProgress.ErrorsRead.openfile fd with
| Error (end_sentinel, log_message) when not has_already_attempted_connect
->
Hh_logger.log
"Errors-file: on %s, read sentinel %s [%s], so connecting then trying again"
(Sys_utils.show_inode fd)
(ServerProgress.show_errors_file_error end_sentinel)
log_message;
(* If there was an existing file but it was bad -- e.g. came from a dead server,
or binary mismatch, then we will connect as before. In the case of binary mismatch,
we rely on the standard codepaths in clientConnect and monitorConnect: namely, it will
either succeed in starting and connecting to a new server of the correct binary, or
(e.g. without autostart) it will raise Exit_status.(Exit_with Exit_status.Build_id_mismatch).
The exception will bubble up to our caller; here we need only handle success. *)
Unix.close fd;
let%lwt () = connect_then_close () in
keep_trying_to_open
~has_already_attempted_connect:true
~connect_then_close
~already_checked_clock
~progress_callback
~deadline
~root
| Error (end_sentinel, log_message) -> begin
(* But if there was an existing file that's still bad even after our connection
attempt, there's not much we can do *)
Hh_logger.log
"Errors-file: on %s, read sentinel %s [%s], and already connected once, so giving up."
(Sys_utils.show_inode fd)
(ServerProgress.show_errors_file_error end_sentinel)
log_message;
progress_callback None;
match end_sentinel with
| ServerProgress.Build_id_mismatch ->
raise (Exit_status.Exit_with Exit_status.Build_id_mismatch)
| ServerProgress.Killed finale_data ->
raise
(Exit_status.Exit_with
(Exit_status.Server_hung_up_should_abort finale_data))
| _ ->
failwith
(Printf.sprintf
"Unexpected error from openfile: %s [%s]"
(ServerProgress.show_errors_file_error end_sentinel)
log_message)
end
| Ok { ServerProgress.ErrorsRead.pid; clock = None; _ } ->
(* If there's an existing file, but it's not using watchman, then we cannot offer
consistency guarantees. We'll just go with it. This happens for instance
if the server was started using dfind instead of watchman. *)
Hh_logger.log
"Errors-file: %s is present, without watchman, so just going with it."
(Sys_utils.show_inode fd);
Lwt.return (pid, fd)
| Ok { ServerProgress.ErrorsRead.clock = Some clock; _ }
when Option.equal String.equal (Some clock) already_checked_clock ->
(* we've already checked this clock! so just wait a short time, then re-open the file
so we soon discover when it has a new clock. *)
let%lwt () = Lwt_unix.sleep 0.1 in
keep_trying_to_open
~has_already_attempted_connect
~connect_then_close
~already_checked_clock:(Some clock)
~progress_callback
~deadline
~root
| Ok { ServerProgress.ErrorsRead.pid; clock = Some clock; _ } -> begin
Hh_logger.log
"Errors-file: %s is present, was started at clock %s, so querying watchman..."
(Sys_utils.show_inode fd)
clock;
(* Watchman doesn't support "what files have changed from error.bin's clock until
hh-invocation clock?". We'll instead use the (less permissive, still correct) query
"what files have changed from error.bin's clock until now?". *)
progress_callback (Some "watchman sync");
let%lwt since_result =
watchman_get_raw_updates_since
~root
~clock
~fail_on_new_instance:false
~fail_during_state:false
in
progress_callback (Some "hh_server sync");
match since_result with
| Error e ->
Hh_logger.log "Errors-file: watchman failure:\n%s\n" e;
progress_callback None;
Printf.eprintf "Watchman failure.\n%s\n%!" e;
raise Exit_status.(Exit_with Exit_status.Watchman_failed)
| Ok relative_raw_updates ->
let raw_updates =
relative_raw_updates
|> List.map ~f:(fun file ->
Filename.concat (Path.to_string root) file)
|> SSet.of_list
in
let updates =
FindUtils.post_watchman_filter_from_fully_qualified_raw_updates
~root
~raw_updates
in
if Relative_path.Set.is_empty updates then begin
(* If there was an existing errors.bin, and no files have changed since then,
then use it! *)
Hh_logger.log
"Errors-file: %s is present, was started at clock %s and watchman reports no updates since then, so using it!"
(Sys_utils.show_inode fd)
clock;
Lwt.return (pid, fd)
end else begin
(* But if files have changed since the errors.bin, then we will keep spinning
under trust that hh_server will eventually recognize those changes and create
a new errors.bin file, which we'll then pick up on another iteration.
CARE! This only works if hh_server's test for "are there new files" is at least
as strict as our own.
They're identical, in fact, because they both use the same watchman filter
[FilesToIgnore.watchman_server_expression_terms] and the same [FindUtils.post_watchman_filter]. *)
Hh_logger.log
"Errors-file: %s is present, was started at clock %s, but watchman reports updates since then, so trying again. %d updates, for example %s"
(Sys_utils.show_inode fd)
clock
(Relative_path.Set.cardinal updates)
(Relative_path.Set.choose updates |> Relative_path.suffix);
let%lwt () = Lwt_unix.sleep 0.1 in
keep_trying_to_open
~has_already_attempted_connect
~connect_then_close
~already_checked_clock:(Some clock)
~progress_callback
~deadline
~root
end
end
end
(** Provides typechecker errors by displaying them to stdout.
Errors are printed soon after they are known instead of all at once at the end. *)
let go_streaming
(args : ClientEnv.client_check_env)
~(partial_telemetry_ref : Telemetry.t option ref)
~(connect_then_close : unit -> unit Lwt.t) :
(Exit_status.t * Telemetry.t) Lwt.t =
let ClientEnv.{ root; show_spinner; deadline; _ } = args in
let progress_callback : string option -> unit =
ClientSpinner.report ~to_stderr:show_spinner ~angery_reaccs_only:false
in
let connect_then_close () =
(* must clear spinner in case [connect_then_close] writes to stderr *)
progress_callback None;
connect_then_close ()
in
let%lwt (pid, fd) =
keep_trying_to_open
~has_already_attempted_connect:false
~already_checked_clock:None
~connect_then_close
~progress_callback
~deadline
~root
in
let%lwt (exit_status, telemetry) =
go_streaming_on_fd ~pid fd args ~partial_telemetry_ref ~progress_callback
in
Lwt.return (exit_status, telemetry) |
OCaml | hhvm/hphp/hack/src/client/clientCommand.ml | (*
* Copyright (c) 2015, 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 command =
| CCheck of ClientEnv.client_check_env
| CStart of ClientStart.env
| CStop of ClientStop.env
| CRestart of ClientStart.env
| CLsp of ClientLsp.args
| CSavedStateProjectMetadata of ClientEnv.client_check_env
| CDownloadSavedState of ClientDownloadSavedState.env
| CRage of ClientRage.env
type command_keyword =
| CKCheck
| CKStart
| CKStop
| CKRestart
| CKNone
| CKLsp
| CKSavedStateProjectMetadata
| CKDownloadSavedState
| CKRage
let get_custom_telemetry_data command =
match command with
| CCheck { ClientEnv.custom_telemetry_data; _ }
| CStart { ClientStart.custom_telemetry_data; _ }
| CRestart { ClientStart.custom_telemetry_data; _ } ->
custom_telemetry_data
| CStop _
| CLsp _
| CSavedStateProjectMetadata _
| CDownloadSavedState _
| CRage _ ->
[]
let command_name = function
| CKCheck -> "check"
| CKStart -> "start"
| CKStop -> "stop"
| CKRestart -> "restart"
| CKLsp -> "lsp"
| CKSavedStateProjectMetadata -> "saved-state-project-metadata"
| CKDownloadSavedState -> "download-saved-state"
| CKRage -> "rage"
| CKNone -> "" |
OCaml | hhvm/hphp/hack/src/client/clientConnect.ml | (*
* Copyright (c) 2015, 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 log ?tracker ?connection_log_id s =
let id =
match tracker with
| Some tracker -> Some (Connection_tracker.log_id tracker)
| None -> connection_log_id
in
match id with
| Some id -> Hh_logger.log ("[%s] [client-connect] " ^^ s) id
| None -> Hh_logger.log ("[client-connect] " ^^ s)
type env = {
root: Path.t;
from: string;
local_config: ServerLocalConfig.t;
autostart: bool;
force_dormant_start: bool;
deadline: float option;
no_load: bool;
watchman_debug_logging: bool;
log_inference_constraints: bool;
remote: bool;
progress_callback: string option -> unit;
do_post_handoff_handshake: bool;
ignore_hh_version: bool;
save_64bit: string option;
save_human_readable_64bit_dep_map: string option;
saved_state_ignore_hhconfig: bool;
mini_state: string option;
use_priority_pipe: bool;
prechecked: bool option;
config: (string * string) list;
custom_hhi_path: string option;
custom_telemetry_data: (string * string) list;
allow_non_opt_build: bool;
}
type conn = {
connection_log_id: string;
t_connected_to_monitor: float;
t_received_hello: float;
t_sent_connection_type: float;
channels: Timeout.in_channel * Out_channel.t;
server_specific_files: ServerCommandTypes.server_specific_files;
conn_progress_callback: string option -> unit;
conn_root: Path.t;
conn_deadline: float option;
from: string;
}
let read_and_show_progress (progress_callback : string option -> unit) : unit =
let { ServerProgress.message; _ } = ServerProgress.read () in
progress_callback (Some message);
()
let check_for_deadline progress_callback deadline_opt =
let now = Unix.time () in
match deadline_opt with
| Some deadline when Float.(now > deadline) ->
log
"check_for_deadline expired: %s > %s"
(Utils.timestring now)
(Utils.timestring deadline);
(* must hide the spinner prior to printing output or exiting *)
progress_callback None;
Printf.eprintf "\nError: hh_client hit timeout, giving up!\n%!";
raise Exit_status.(Exit_with Out_of_time)
| _ -> ()
(** Sleeps until the server sends a message. While waiting, prints out spinner
and progress information using the argument callback. *)
let rec wait_for_server_message
~(connection_log_id : string)
~(expected_message : 'a ServerCommandTypes.message_type option)
~(ic : Timeout.in_channel)
~(deadline : float option)
~(server_specific_files : ServerCommandTypes.server_specific_files)
~(progress_callback : string option -> unit)
~(root : Path.t) : _ ServerCommandTypes.message_type Lwt.t =
check_for_deadline progress_callback deadline;
let%lwt (readable, _, _) =
Lwt_utils.select
[Timeout.descr_of_in_channel ic]
[]
[Timeout.descr_of_in_channel ic]
1.0
in
if List.is_empty readable then (
read_and_show_progress progress_callback;
wait_for_server_message
~connection_log_id
~expected_message
~ic
~deadline
~server_specific_files
~progress_callback
~root
) else
(* an inline module to define this exception type, used internally in the function *)
let module M = struct
exception Monitor_failed_to_handoff
end in
try%lwt
let fd = Timeout.descr_of_in_channel ic in
let msg : 'a ServerCommandTypes.message_type =
Marshal_tools.from_fd_with_preamble fd
in
let (is_ping, is_handoff_failed) =
match msg with
| ServerCommandTypes.Ping -> (true, false)
| ServerCommandTypes.Monitor_failed_to_handoff -> (false, true)
| _ -> (false, false)
in
let matches_expected =
Option.value_map ~default:true ~f:(Poly.( = ) msg) expected_message
in
if is_handoff_failed then
raise M.Monitor_failed_to_handoff
else if matches_expected && not is_ping then (
log
~connection_log_id
"wait_for_server_message: got expected %s"
(ServerCommandTypesUtils.debug_describe_message_type msg);
progress_callback None;
Lwt.return msg
) else (
log
~connection_log_id
"wait_for_server_message: didn't want %s"
(ServerCommandTypesUtils.debug_describe_message_type msg);
if not is_ping then read_and_show_progress progress_callback;
wait_for_server_message
~connection_log_id
~expected_message
~ic
~deadline
~server_specific_files
~progress_callback
~root
)
with
| (End_of_file | Sys_error _ | M.Monitor_failed_to_handoff) as exn ->
let e = Exception.wrap exn in
let finale_data =
Exit_status.get_finale_data
server_specific_files.ServerCommandTypes.server_finale_file
in
let client_exn = Exception.get_ctor_string e in
let client_stack =
e |> Exception.get_backtrace_string |> Exception.clean_stack
in
(* must hide the spinner prior to printing output or exiting *)
progress_callback None;
(* stderr *)
let msg =
match (exn, finale_data) with
| (M.Monitor_failed_to_handoff, None) -> "Hack server is too busy."
| (_, None) ->
"Hack server disconnected suddenly. It might have crashed."
| (_, Some finale_data) ->
Printf.sprintf
"Hack server disconnected suddenly [%s]\n%s"
(Exit_status.show finale_data.Exit_status.exit_status)
(Option.value ~default:"" finale_data.Exit_status.msg)
in
Printf.eprintf "%s\n" msg;
(* exception, caught by hh_client.ml and logged.
In most cases we report that find_hh.sh should simply retry the failed command.
There are only two cases where we say it shouldn't. *)
let server_exit_status =
Option.map finale_data ~f:(fun d -> d.Exit_status.exit_status)
in
let external_exit_status =
match server_exit_status with
| Some
Exit_status.(
Failed_to_load_should_abort | Server_non_opt_build_mode) ->
Exit_status.Server_hung_up_should_abort finale_data
| _ -> Exit_status.Server_hung_up_should_retry finale_data
in
(* log to telemetry *)
HackEventLogger.server_hung_up
~external_exit_status
~server_exit_status
~client_exn
~client_stack
~server_stack:
(Option.map
finale_data
~f:(fun { Exit_status.stack = Utils.Callstack stack; _ } -> stack))
~server_msg:(Option.bind finale_data ~f:(fun d -> d.Exit_status.msg));
raise (Exit_status.Exit_with external_exit_status)
let wait_for_server_hello
(connection_log_id : string)
(ic : Timeout.in_channel)
(deadline : float option)
(server_specific_files : ServerCommandTypes.server_specific_files)
(progress_callback : string option -> unit)
(root : Path.t) : unit Lwt.t =
let%lwt (_ : 'a ServerCommandTypes.message_type) =
wait_for_server_message
~connection_log_id
~expected_message:(Some ServerCommandTypes.Hello)
~ic
~deadline
~server_specific_files
~progress_callback
~root
in
Lwt.return_unit
let describe_mismatch (mismatch_info : MonitorUtils.build_mismatch_info option)
: string =
match mismatch_info with
| None -> ""
| Some
{ MonitorUtils.existing_version; existing_argv; existing_launch_time; _ }
->
Printf.sprintf
" hh_server '%s', version '%s', launched %s\n hh_client '%s', version '%s', launched [just now]\n"
(String.concat ~sep:" " existing_argv)
existing_version
(Utils.timestring existing_launch_time)
(String.concat ~sep:" " (Array.to_list Sys.argv))
Build_id.build_revision
let rec connect ?(allow_macos_hack = true) (env : env) (start_time : float) :
conn Lwt.t =
env.progress_callback (Some "connecting");
check_for_deadline env.progress_callback env.deadline;
let handoff_options =
{
MonitorRpc.force_dormant_start = env.force_dormant_start;
pipe_name =
ServerController.pipe_type_to_string
(if env.force_dormant_start then
ServerController.Force_dormant_start_only
else if env.use_priority_pipe then
ServerController.Priority
else
ServerController.Default);
}
in
let tracker = Connection_tracker.create () in
let connection_log_id = Connection_tracker.log_id tracker in
(* We'll attempt to connect, with timeout up to [env.deadline]. Effectively, the
unix process list will be where we store our (unbounded) queue of incoming client requests,
each of them waiting for the monitor's incoming socket to become available; if there's a backlog
in the monitor->server pipe and the monitor's incoming queue is full, then the monitor's incoming
socket will become only available after the server has finished a request, and the monitor gets to
send its next handoff, and take the next item off its incoming queue.
If the deadline is infinite, I arbitrarily picked 60s as the timeout coupled with "will retry..."
if it timed out. That's because I distrust infinite timeouts, just in case something got stuck for
unknown causes, and maybe retrying the connection attempt will get it unstuck? -- a sort of
"try turning it off then on again". This timeout must be comfortably longer than the monitor's
own 30s timeout in MonitorMain.hand_off_client_connection_wrapper to handoff to the server;
if it were shorter, then the monitor's incoming queue would be entirely full of requests that
were all stale by the time it got to handle them. *)
let timeout =
match env.deadline with
| None -> 60
| Some deadline ->
Int.max 1 (int_of_float (deadline -. Unix.gettimeofday ()))
in
log
~connection_log_id
"ClientConnect.connect: attempting MonitorConnection.connect_once (%ds)"
timeout;
let terminate_monitor_on_version_mismatch = env.autostart in
(* We've put our money where our mouth is -- only ask the monitor to terminate
if we're prepared to start it again afterwards! *)
let conn =
MonitorConnection.connect_once
~tracker
~timeout
~terminate_monitor_on_version_mismatch
env.root
handoff_options
in
let t_connected_to_monitor = Unix.gettimeofday () in
match conn with
| Ok (ic, oc, server_specific_files) ->
log
~connection_log_id
"ClientConnect.connect: successfully connected to monitor.";
let%lwt () =
if env.do_post_handoff_handshake then
wait_for_server_hello
connection_log_id
ic
env.deadline
server_specific_files
env.progress_callback
env.root
else
Lwt.return_unit
in
let t_received_hello = Unix.gettimeofday () in
let threshold = 2.0 in
if
Sys_utils.is_apple_os ()
&& allow_macos_hack
&& Float.(Unix.gettimeofday () -. t_connected_to_monitor > threshold)
then (
(*
HACK: on MacOS, re-establish the connection if it took a long time
during the initial attempt.
The MacOS implementation of the server monitor does not appear to make a
graceful handoff of the client connection to the server main process.
If, after the handoff, the monitor closes its connection fd before the
server main attempts any reads, the server main's connection will go
stale for reads (i.e., reading will generate an EOF). This is the case
if the server needs to run a long typecheck phase before communication
with the client, e.g. for cold starts.
For shorter startup times, MonitorMain.Sent_fds_collector attempts to
compensate for this issue by having the monitor wait a few seconds after
handoff before attempting to close its connection fd.
For longer startup times, a sufficient (if not exactly clean) workaround
is simply to have the client re-establish a connection.
*)
(* must hide the spinner prior to printing output or exiting *)
env.progress_callback None;
Printf.eprintf
"Server connection took over %.1f seconds. Refreshing...\n"
threshold;
(try Timeout.shutdown_connection ic with
| _ -> ());
Timeout.close_in_noerr ic;
Stdlib.close_out_noerr oc;
(* allow_macos_hack:false is a defensive measure against infinite connection loops *)
connect ~allow_macos_hack:false env start_time
) else (
env.progress_callback (Some "connected");
Lwt.return
{
connection_log_id = Connection_tracker.log_id tracker;
t_connected_to_monitor;
t_received_hello;
t_sent_connection_type = 0.;
(* placeholder, until we actually send it *)
channels = (ic, oc);
server_specific_files;
conn_progress_callback = env.progress_callback;
conn_root = env.root;
conn_deadline = env.deadline;
from = env.from;
}
)
| Error e ->
(* must hide the spinner prior to printing output or exiting *)
env.progress_callback None;
(match e with
| MonitorUtils.Server_died
| MonitorUtils.(Connect_to_monitor_failure { server_exists = true; _ }) ->
log ~tracker "connect: no response yet from server; will retry...";
Unix.sleepf 0.1;
connect env start_time
| MonitorUtils.(Connect_to_monitor_failure { server_exists = false; _ }) ->
log ~tracker "connect: autostart=%b" env.autostart;
if env.autostart then (
let {
root;
from;
local_config = _;
autostart = _;
force_dormant_start = _;
deadline = _;
no_load;
watchman_debug_logging;
log_inference_constraints;
remote = _;
progress_callback = _;
do_post_handoff_handshake = _;
ignore_hh_version;
save_64bit;
save_human_readable_64bit_dep_map;
saved_state_ignore_hhconfig;
use_priority_pipe = _;
prechecked;
mini_state;
config;
custom_hhi_path;
custom_telemetry_data;
allow_non_opt_build;
} =
env
in
HackEventLogger.client_connect_autostart ();
ClientStart.(
start_server
{
root;
from;
no_load;
watchman_debug_logging;
log_inference_constraints;
silent = false;
exit_on_failure = false;
ignore_hh_version;
save_64bit;
save_human_readable_64bit_dep_map;
saved_state_ignore_hhconfig;
prechecked;
mini_state;
config;
custom_hhi_path;
custom_telemetry_data;
allow_non_opt_build;
});
connect env start_time
) else (
Printf.eprintf
("Error: no hh_server running. Either start hh_server"
^^ " yourself or run hh_client without --autostart-server false\n%!");
raise Exit_status.(Exit_with No_server_running_should_retry)
)
| MonitorUtils.Server_dormant_out_of_retries ->
Printf.eprintf
("Ran out of retries while waiting for Mercurial to finish rebase. Starting "
^^ "the server in the middle of rebase is strongly not recommended and you should "
^^ "first finish the rebase before retrying. If you really "
^^ "know what you're doing, maybe try --force-dormant-start true\n%!");
raise Exit_status.(Exit_with Out_of_retries)
| MonitorUtils.Server_dormant ->
Printf.eprintf
("Error: No server running and connection limit reached for waiting"
^^ " on next server to be started. Please wait patiently. If you really"
^^ " know what you're doing, maybe try --force-dormant-start true\n%!");
raise Exit_status.(Exit_with No_server_running_should_retry)
| MonitorUtils.Build_id_mismatched_client_must_terminate mismatch_info ->
Printf.eprintf
"Error: version mismatch.\nUse --autostart-server true if you want it to restart.\n%s"
(describe_mismatch (Some mismatch_info));
raise Exit_status.(Exit_with Build_id_mismatch)
| MonitorUtils.Build_id_mismatched_monitor_will_terminate mismatch_info_opt
->
Printf.eprintf
"hh_server's version doesn't match the client's, so it will exit.\n%s"
(describe_mismatch mismatch_info_opt);
if env.autostart then begin
(* The new server is definitely not running yet, adjust the
* start time and deadline to absorb the server startup time.
*)
let now = Unix.time () in
let deadline =
Option.map ~f:(fun d -> d +. (now -. start_time)) env.deadline
in
Printf.eprintf "Going to launch a new one.\n%!";
connect { env with deadline } now
end else
raise Exit_status.(Exit_with Build_id_mismatch))
let connect (env : env) : conn Lwt.t =
let start_time = Unix.time () in
let%lwt ({ channels = (_, oc); _ } as conn) = connect env start_time in
HackEventLogger.client_established_connection start_time;
if env.do_post_handoff_handshake then
ServerCommandLwt.send_connection_type oc ServerCommandTypes.Non_persistent;
Lwt.return { conn with t_sent_connection_type = Unix.gettimeofday () }
let rpc :
type a.
conn -> desc:string -> a ServerCommandTypes.t -> (a * Telemetry.t) Lwt.t =
fun {
connection_log_id;
t_connected_to_monitor;
t_received_hello;
t_sent_connection_type;
channels = (ic, oc);
server_specific_files;
conn_progress_callback = progress_callback;
conn_root;
conn_deadline = deadline;
from;
}
~desc
cmd ->
let t_ready_to_send_cmd = Unix.gettimeofday () in
let metadata = { ServerCommandTypes.from; desc } in
Marshal.to_channel oc (ServerCommandTypes.Rpc (metadata, cmd)) [];
Out_channel.flush oc;
let t_sent_cmd = Unix.gettimeofday () in
let%lwt res =
wait_for_server_message
~connection_log_id
~expected_message:None
~ic
~deadline
~server_specific_files
~progress_callback
~root:conn_root
in
match res with
| ServerCommandTypes.Response (response, tracker) ->
let open Connection_tracker in
let telemetry =
tracker
|> track ~key:Client_ready_to_send_cmd ~time:t_ready_to_send_cmd
|> track ~key:Client_sent_cmd ~time:t_sent_cmd
|> track ~key:Client_received_response
(* now we can fill in missing information in tracker, which we couldn't fill in earlier
because we'd already transferred ownership of the tracker to the monitor... *)
|> track ~key:Client_connected_to_monitor ~time:t_connected_to_monitor
|> track ~key:Client_received_hello ~time:t_received_hello
|> track ~key:Client_sent_connection_type ~time:t_sent_connection_type
|> get_telemetry
in
Lwt.return (response, telemetry)
| ServerCommandTypes.Push _ -> failwith "unexpected 'push' RPC response"
| ServerCommandTypes.Hello -> failwith "unexpected 'hello' RPC response"
| ServerCommandTypes.Ping -> failwith "unexpected 'ping' RPC response"
| ServerCommandTypes.Monitor_failed_to_handoff ->
failwith "unexpected 'monitor_failed_to_handoff' RPC response"
let rpc_with_retry
(conn_f : unit -> conn Lwt.t)
~(desc : string)
(cmd : 'a ServerCommandTypes.Done_or_retry.t ServerCommandTypes.t) :
'a Lwt.t =
ServerCommandTypes.Done_or_retry.call ~f:(fun () ->
let%lwt conn = conn_f () in
let%lwt (result, _telemetry) = rpc conn ~desc cmd in
Lwt.return result)
let rpc_with_retry_list
(conn_f : unit -> conn Lwt.t)
~(desc : string)
(cmd : 'a ServerCommandTypes.Done_or_retry.t list ServerCommandTypes.t) :
'a list Lwt.t =
let call_here s =
ServerCommandTypes.Done_or_retry.call ~f:(fun () -> Lwt.return s)
in
let%lwt conn = conn_f () in
let%lwt (job_list, _) = rpc conn ~desc cmd in
List.map job_list ~f:call_here |> Lwt.all |
OCaml Interface | hhvm/hphp/hack/src/client/clientConnect.mli | (*
* 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.
*
*)
(** Used solely as an argument to [connect] *)
type env = {
root: Path.t;
from: string;
local_config: ServerLocalConfig.t;
autostart: bool;
force_dormant_start: bool;
deadline: float option;
no_load: bool;
watchman_debug_logging: bool;
log_inference_constraints: bool;
remote: bool;
progress_callback: string option -> unit;
do_post_handoff_handshake: bool;
ignore_hh_version: bool;
save_64bit: string option;
save_human_readable_64bit_dep_map: string option;
saved_state_ignore_hhconfig: bool;
mini_state: string option;
use_priority_pipe: bool;
prechecked: bool option;
config: (string * string) list;
custom_hhi_path: string option;
custom_telemetry_data: (string * string) list;
allow_non_opt_build: bool;
}
(* [connect] returns this record, which contains everything needed for subsequent rpc calls *)
type conn = {
connection_log_id: string;
t_connected_to_monitor: float;
t_received_hello: float;
t_sent_connection_type: float;
channels: Timeout.in_channel * out_channel;
server_specific_files: ServerCommandTypes.server_specific_files;
conn_progress_callback: string option -> unit;
conn_root: Path.t;
conn_deadline: float option;
from: string;
}
(** Establishes a connection to the server: (1) connects to the monitor and exchanges
messages, (2) has the monitor handoff the FD to the server, (3) if env.do_post_handoff_handshake
is true then also waits for the server to send back ServerCommandTypes.Hello. *)
val connect : env -> conn Lwt.t
(** Sends a request to the server, and waits for the response *)
val rpc :
conn -> desc:string -> 'a ServerCommandTypes.t -> ('a * Telemetry.t) Lwt.t
(** A handful of rpc commands (find-refs, go-to-impl, refactor), for grotty implementation
details, don't return an answer but instead return the message "Done_or_retry.Retry"
indicating that ClientConnect should make the exact same request a second time.
Which, through this API, it does. *)
val rpc_with_retry :
(unit -> conn Lwt.t) ->
desc:string ->
'a ServerCommandTypes.Done_or_retry.t ServerCommandTypes.t ->
'a Lwt.t
(**For batch commands, retries each result in turn **)
val rpc_with_retry_list :
(unit -> conn Lwt.t) ->
desc:string ->
'a ServerCommandTypes.Done_or_retry.t list ServerCommandTypes.t ->
'a list Lwt.t |
OCaml | hhvm/hphp/hack/src/client/clientDownloadSavedState.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.
*
*)
open Hh_prelude
type saved_state_type = Naming_and_dep_table
type env = {
root: Path.t;
from: string;
saved_state_type: saved_state_type;
saved_state_manifold_api_key: string option;
should_save_replay: bool;
replay_token: string option;
}
type 'additional_info replay_info = {
manifold_path: string;
changed_files: Saved_state_loader.changed_files;
corresponding_rev: Hg.hg_rev;
mergebase_rev: Hg.hg_rev;
is_cached: bool;
additional_info: 'additional_info;
}
let changed_files_to_absolute_paths_json
(changed_files : Saved_state_loader.changed_files) : Hh_json.json =
changed_files
|> List.map ~f:Relative_path.to_absolute
|> Hh_json_helpers.Jprint.string_array
let changed_files_to_relative_paths_json
(changed_files : Saved_state_loader.changed_files) : Hh_json.json =
changed_files
|> List.map ~f:Relative_path.suffix
|> Hh_json_helpers.Jprint.string_array
let print_load_error (load_error : Saved_state_loader.LoadError.t) : unit =
let json =
Hh_json.JSON_Object
[
( "error",
Hh_json.string_
(Saved_state_loader.LoadError.debug_details_of_error load_error) );
]
in
Hh_json.json_to_multiline_output stdout json
let additional_info_of_json
(type main_artifacts additional_info)
~(saved_state_type :
(main_artifacts * additional_info) Saved_state_loader.saved_state_type)
(json : Hh_json.json option) : additional_info =
let open Hh_json_helpers in
match saved_state_type with
| Saved_state_loader.Naming_and_dep_table_distc ->
let mergebase_global_rev = Jget.int_opt json "mergebase_global_rev" in
let dirty_files = Jget.obj_exn json "dirty_files" in
let master_changes =
Jget.string_array_exn dirty_files "master_changes"
|> List.map ~f:(fun suffix -> Relative_path.from_root ~suffix)
|> Relative_path.Set.of_list
in
let local_changes =
Jget.string_array_exn dirty_files "local_changes"
|> List.map ~f:(fun suffix -> Relative_path.from_root ~suffix)
|> Relative_path.Set.of_list
in
Saved_state_loader.Naming_and_dep_table_info.
{
mergebase_global_rev;
dirty_files_promise = Future.of_value { master_changes; local_changes };
saved_state_distance = None;
saved_state_age = None;
}
let replay_info_of_json
(type main_artifacts additional_info)
~(saved_state_type :
(main_artifacts * additional_info) Saved_state_loader.saved_state_type)
(json : Hh_json.json option) : additional_info replay_info =
let open Hh_json_helpers in
let manifold_path = Jget.string_exn json "manifold_path" in
let changed_files =
Jget.string_array_exn json "changed_files"
|> List.map ~f:(fun suffix -> Relative_path.from_root ~suffix)
in
let corresponding_rev = Jget.string_exn json "corresponding_rev" in
let mergebase_rev = Jget.string_exn json "mergebase_rev" in
let is_cached = Jget.bool_exn json "is_cached" in
let additional_info =
additional_info_of_json
~saved_state_type
(Jget.obj_opt json "additional_info")
in
{
manifold_path;
changed_files;
corresponding_rev;
mergebase_rev;
is_cached;
additional_info;
}
let get_replay_info
(type main_artifacts additional_info)
~(saved_state_type :
(main_artifacts * additional_info) Saved_state_loader.saved_state_type)
(replay_token : string) : additional_info replay_info Lwt.t =
let%lwt replay_info = Clowder_paste.clowder_download replay_token in
match replay_info with
| Ok stdout ->
let json = Some (Hh_json.json_of_string stdout) in
Lwt.return (replay_info_of_json ~saved_state_type json)
| Error message ->
failwith
(Printf.sprintf
"Could not get replay info from Clowder handle %s: %s"
replay_token
message)
let make_replay_token_of_additional_info
(type main_artifacts additional_info)
~(saved_state_type :
(main_artifacts * additional_info) Saved_state_loader.saved_state_type)
~(additional_info : additional_info) : Hh_json.json =
match saved_state_type with
| Saved_state_loader.Naming_and_dep_table_distc ->
let Saved_state_loader.Naming_and_dep_table_info.
{
mergebase_global_rev;
dirty_files_promise;
saved_state_distance = _;
saved_state_age = _;
} =
additional_info
in
let Saved_state_loader.Naming_and_dep_table_info.
{ master_changes; local_changes } =
Future.get_exn dirty_files_promise
in
let open Hh_json in
JSON_Object
[
("mergebase_global_rev", opt_int_to_json mergebase_global_rev);
( "dirty_files",
JSON_Object
[
( "master_changes",
changed_files_to_relative_paths_json
@@ Relative_path.Set.elements master_changes );
( "local_changes",
changed_files_to_relative_paths_json
@@ Relative_path.Set.elements local_changes );
] );
]
let make_replay_token_json
(type main_artifacts additional_info)
~(saved_state_type :
(main_artifacts * additional_info) Saved_state_loader.saved_state_type)
~(manifold_path : string)
~(changed_files : Saved_state_loader.changed_files)
~(corresponding_rev : Hg.hg_rev)
~(mergebase_rev : Hg.hg_rev)
~(is_cached : bool)
~(additional_info : additional_info) : Hh_json.json =
let open Hh_json in
JSON_Object
[
("manifold_path", JSON_String manifold_path);
("changed_files", changed_files_to_relative_paths_json changed_files);
("corresponding_rev", JSON_String corresponding_rev);
("mergebase_rev", JSON_String mergebase_rev);
("is_cached", JSON_Bool is_cached);
( "additional_info",
make_replay_token_of_additional_info ~saved_state_type ~additional_info
);
]
let make_replay_token
(type main_artifacts additional_info)
~(env : env)
~(saved_state_type :
(main_artifacts * additional_info) Saved_state_loader.saved_state_type)
~(manifold_path : string)
~(changed_files : Saved_state_loader.changed_files)
~(corresponding_rev : Hg.hg_rev)
~(mergebase_rev : Hg.hg_rev)
~(is_cached : bool)
~(additional_info : additional_info) : string option Lwt.t =
match (env.should_save_replay, env.replay_token) with
| (false, (Some _ | None)) -> Lwt.return_none
| (true, Some replay_token) ->
(* No need to generate a new replay token in this case, as it would
contain the same data as we already have. *)
Lwt.return_some replay_token
| (true, None) ->
let json =
make_replay_token_json
~saved_state_type
~manifold_path
~changed_files
~corresponding_rev
~mergebase_rev
~is_cached
~additional_info
in
let%lwt clowder_result =
Clowder_paste.clowder_upload_and_get_handle
(Hh_json.json_to_multiline json)
in
(match clowder_result with
| Ok handle -> Lwt.return_some handle
| Error message ->
Hh_logger.error "Failed to generate replay token from Clowder: %s" message;
Lwt.return_none)
let load_saved_state :
type main_artifacts additional_info.
env:env ->
local_config:ServerLocalConfig.t ->
saved_state_type:
(main_artifacts * additional_info) Saved_state_loader.saved_state_type ->
( (main_artifacts, additional_info) Saved_state_loader.load_result,
Saved_state_loader.LoadError.t )
Lwt_result.t =
fun ~env ~local_config ~saved_state_type ->
let ssopt =
{
local_config.ServerLocalConfig.saved_state with
GlobalOptions.loading =
{
local_config.ServerLocalConfig.saved_state.GlobalOptions.loading with
GlobalOptions.log_saved_state_age_and_distance = false;
saved_state_manifold_api_key = env.saved_state_manifold_api_key;
};
}
in
match env.replay_token with
| None ->
let watchman_opts =
Saved_state_loader.Watchman_options.{ root = env.root; sockname = None }
in
let%lwt result =
State_loader_lwt.load
~ssopt
~progress_callback:(fun _ -> ())
~watchman_opts
~ignore_hh_version:false
~saved_state_type
in
Lwt.return result
| Some replay_token ->
let%lwt {
manifold_path;
changed_files;
corresponding_rev;
mergebase_rev;
is_cached;
additional_info;
} =
get_replay_info ~saved_state_type replay_token
in
let download_dir =
State_loader_lwt.prepare_download_dir ~saved_state_type
in
let target_path =
State_loader_lwt.get_saved_state_target_path ~download_dir ~manifold_path
in
let%lwt result =
State_loader_lwt.download_and_unpack_saved_state_from_manifold
~ssopt:ssopt.GlobalOptions.loading
~progress_callback:(fun _ -> ())
~manifold_path
~target_path
~saved_state_type
in
(match result with
| Ok (main_artifacts, _telemetry) ->
let load_result =
{
Saved_state_loader.main_artifacts;
additional_info;
changed_files;
manifold_path;
corresponding_rev;
mergebase_rev;
is_cached;
}
in
Lwt.return_ok load_result
| Error (load_error, _telemetry) -> Lwt.return_error load_error)
let main (env : env) (local_config : ServerLocalConfig.t) : Exit_status.t Lwt.t
=
Relative_path.set_path_prefix Relative_path.Root env.root;
match env.saved_state_type with
| Naming_and_dep_table ->
let saved_state_type = Saved_state_loader.Naming_and_dep_table_distc in
let%lwt result = load_saved_state ~env ~local_config ~saved_state_type in
(match result with
| Error load_error ->
print_load_error load_error;
Lwt.return Exit_status.Failed_to_load_should_abort
| Ok
Saved_state_loader.
{
main_artifacts =
{
Naming_and_dep_table_info.naming_table_path;
Naming_and_dep_table_info.naming_sqlite_table_path;
dep_table_path;
compressed_dep_table_path;
errors_path;
};
additional_info;
changed_files;
manifold_path;
corresponding_rev;
mergebase_rev;
is_cached;
} ->
let%lwt replay_token =
make_replay_token
~env
~saved_state_type
~manifold_path
~changed_files
~corresponding_rev
~mergebase_rev
~is_cached
~additional_info
in
let json =
Hh_json.JSON_Object
[
("changed_files", changed_files_to_absolute_paths_json changed_files);
( "naming_table_path",
naming_table_path |> Path.to_string |> Hh_json.string_ );
( "naming_sqlite_table_path",
naming_sqlite_table_path |> Path.to_string |> Hh_json.string_ );
( "dep_table_path",
dep_table_path |> Path.to_string |> Hh_json.string_ );
( "compressed_dep_table_path",
compressed_dep_table_path |> Path.to_string |> Hh_json.string_ );
("errors_path", errors_path |> Path.to_string |> Hh_json.string_);
( "replay_token",
Option.value_map
replay_token
~f:Hh_json.string_
~default:Hh_json.JSON_Null );
]
in
Hh_json.json_to_multiline_output stdout json;
Out_channel.output_char stdout '\n';
Lwt.return Exit_status.No_error) |
OCaml Interface | hhvm/hphp/hack/src/client/clientDownloadSavedState.mli | (*
* 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.
*
*)
type saved_state_type = Naming_and_dep_table
type env = {
root: Path.t;
from: string;
saved_state_type: saved_state_type;
saved_state_manifold_api_key: string option;
should_save_replay: bool;
replay_token: string option;
}
val main : env -> ServerLocalConfig.t -> Exit_status.t Lwt.t |
OCaml | hhvm/hphp/hack/src/client/clientEnv.ml | (*
* Copyright (c) 2015, 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 rename_mode =
| Function
| Class
| Method
| Unspecified
type client_mode =
| MODE_XHP_AUTOCOMPLETE_SNIPPET of string
| MODE_CODEMOD_SDT of {
csdt_path_to_jsonl: string;
csdt_strategy: [ `CodemodSdtCumulative | `CodemodSdtIndependent ];
csdt_log_remotely: bool;
csdt_tag: string;
}
| MODE_CREATE_CHECKPOINT of string
| MODE_CST_SEARCH of string list option
| MODE_DELETE_CHECKPOINT of string
| MODE_DUMP_SYMBOL_INFO of string
| MODE_EXTRACT_STANDALONE of string
| MODE_CONCATENATE_ALL
| MODE_FIND_CLASS_REFS of string
| MODE_FIND_REFS of string
| MODE_FORMAT of int * int
| MODE_FULL_FIDELITY_PARSE of string
| MODE_FULL_FIDELITY_SCHEMA
| MODE_POPULATE_REMOTE_DECLS of string list option
| MODE_GO_TO_IMPL_CLASS of string
| MODE_GO_TO_IMPL_METHOD of string
| MODE_IDE_FIND_REFS_BY_SYMBOL of FindRefsWireFormat.CliArgs.t
| MODE_IDE_GO_TO_IMPL_BY_SYMBOL of FindRefsWireFormat.CliArgs.t
| MODE_IDE_RENAME_BY_SYMBOL of string
| MODE_IDENTIFY_SYMBOL1 of string
| MODE_IDENTIFY_SYMBOL2 of string
| MODE_IDENTIFY_SYMBOL3 of string
| MODE_IDENTIFY_SYMBOL of string
| MODE_IN_MEMORY_DEP_TABLE_SIZE
| MODE_LINT
| MODE_LINT_ALL of int
| MODE_LINT_STDIN of string
| MODE_LIST_FILES
| MODE_METHOD_JUMP_ANCESTORS of string * string
| MODE_METHOD_JUMP_ANCESTORS_BATCH of string list * string
| MODE_METHOD_JUMP_CHILDREN of string
| MODE_OUTLINE
| MODE_OUTLINE2
| MODE_PAUSE of bool
| MODE_RENAME of rename_mode * string * string
| MODE_REMOVE_DEAD_FIXMES of int list
| MODE_REMOVE_DEAD_UNSAFE_CASTS
| MODE_REWRITE_LAMBDA_PARAMETERS of string list
| MODE_RETRIEVE_CHECKPOINT of string
| MODE_SAVE_NAMING of string
| MODE_SAVE_STATE of string
(* TODO figure out why we can't reference FuzzySearchService from here *)
| MODE_SEARCH of string * string
| MODE_SERVER_RAGE
| MODE_STATS
| MODE_STATUS
| MODE_STATUS_SINGLE of string list (* filenames *)
| MODE_TYPE_AT_POS of string
| MODE_TYPE_AT_POS_BATCH of string list
| MODE_TYPE_ERROR_AT_POS of string
| MODE_IS_SUBTYPE
| MODE_TAST_HOLES of string
| MODE_TAST_HOLES_BATCH of string
| MODE_FUN_DEPS_AT_POS_BATCH of string list
| MODE_FILE_LEVEL_DEPENDENCIES
| MODE_VERBOSE of bool
| MODE_DEPS_OUT_AT_POS_BATCH of string list
| MODE_DEPS_IN_AT_POS_BATCH of string list
[@@deriving variants]
type client_check_env = {
autostart: bool;
config: (string * string) list;
custom_hhi_path: string option;
custom_telemetry_data: (string * string) list;
error_format: Errors.format;
force_dormant_start: bool;
from: string;
show_spinner: bool;
gen_saved_ignore_type_errors: bool;
ignore_hh_version: bool;
saved_state_ignore_hhconfig: bool;
paths: string list;
log_inference_constraints: bool;
max_errors: int option;
mode: client_mode;
no_load: bool;
save_64bit: string option;
save_human_readable_64bit_dep_map: string option;
output_json: bool;
prechecked: bool option;
mini_state: string option;
remote: bool;
root: Path.t;
sort_results: bool;
stdin_name: string option;
deadline: float option;
watchman_debug_logging: bool;
allow_non_opt_build: bool;
(** desc is a human-readable string description, to appear in "hh_server busy [desc]" *)
desc: string;
}
let string_to_rename_mode = function
| "Function" -> Function
| "Class" -> Class
| "Method" -> Method
| _ ->
Printf.fprintf
stderr
"Error: please provide one of the following rename modes: Function, Class, or Method. \n%!";
exit 1 |
OCaml | hhvm/hphp/hack/src/client/clientFormat.ml | (*
* Copyright (c) 2015, 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 Hh_json
let to_json result =
let (error, result, internal_error) =
match result with
| Ok s -> ("", s, false)
| Error s -> (s, "", true)
in
JSON_Object
[
("error_message", JSON_String error);
("result", JSON_String result);
("internal_error", JSON_Bool internal_error);
]
let print_json res = print_endline (Hh_json.json_to_string (to_json res))
let print_readable = function
| Ok res -> print_string res
| _ -> ()
let go res output_json =
if output_json then
print_json res
else
print_readable res |
OCaml | hhvm/hphp/hack/src/client/clientFullFidelityParse.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 go result = print_endline result |
OCaml | hhvm/hphp/hack/src/client/clientGetDefinition.ml | (*
* Copyright (c) 2015, 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 print_json res =
Nuclide_rpc_message_printer.(
identify_symbol_response_to_json res |> print_json)
let print_readable ?(short_pos = false) x =
List.iter x ~f:(function (occurrence, definition) ->
SymbolOccurrence.(
let { name; type_; pos; is_declaration } = occurrence in
Printf.printf
"name: %s, kind: %s, span: %s, is_declaration: %b\n"
name
(kind_to_string type_)
(Pos.string_no_file pos)
is_declaration;
Printf.printf "definition:";
begin
match definition with
| None -> Printf.printf " None\n"
| Some definition ->
Out_channel.newline stdout;
FileOutline.print_def ~short_pos " " definition
end;
Out_channel.newline stdout))
let go res output_json =
if output_json then
print_json res
else
print_readable res |
OCaml | hhvm/hphp/hack/src/client/clientHighlightRefs.ml | (*
* Copyright (c) 2015, 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 print_json res =
Nuclide_rpc_message_printer.(
highlight_references_response_to_json res |> print_json)
let print_result pos =
Printf.printf "%s\n" (Ide_api_types.range_to_string_single_line pos)
let print_readable res =
List.iter res ~f:print_result;
print_endline (string_of_int (List.length res) ^ " total results")
let go res ~output_json =
if output_json then
print_json res
else
print_readable res |
OCaml | hhvm/hphp/hack/src/client/clientLint.ml | (*
* Copyright (c) 2015, 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 go (results : ServerLintTypes.result) output_json error_format =
if output_json then
ServerLintTypes.output_json stdout results
else
ServerLintTypes.output_text stdout results error_format |
OCaml | hhvm/hphp/hack/src/client/clientLogCommand.ml | (*
* Copyright (c) 2015, 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.
*
*)
(* The full type ClientCommand.command refers to environment types in
* other client modules like ClientStart.env, ClientBuild.env, etc. If
* we want to do logging from, e.g. inside ClientBuild, then the fact
* that EventLogger's logging functions take the current client
* command as an argument, this creates a circular dependency
*
* ClientBuild -> EventLogger -> ClientCommand
* ^-------------------------------v
*
* To avoid this, we have here a stripped-down version of
* ClientCommand.command where the data carried by each branch is only
* the data required for logging. *)
type log_command =
| LCCheck of Path.t * (* from *) string * (* mode *) string
| LCStart of Path.t
| LCStop of Path.t
| LCRestart of Path.t
| LCBuild of
Path.t
* [ `Push | `Full | `Incremental | `Steps ]
* (* random id *) string |
OCaml | hhvm/hphp/hack/src/client/clientLsp.ml | (*
* Copyright (c) 2015, 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 Lsp
open Lsp_fmt
open Hh_json_helpers
(* All hack-specific code relating to LSP goes in here. *)
type args = {
from: string;
config: (string * string) list;
ignore_hh_version: bool;
naming_table: string option;
verbose: bool;
root_from_cli: Path.t;
}
type env = {
args: args;
init_id: string;
}
(** When did this binary start? *)
let binary_start_time = Unix.gettimeofday ()
(** This gets initialized to env.from, but maybe modified in the light of the initialize request *)
let from = ref "[init]"
(************************************************************************)
(* Protocol orchestration & helpers *)
(************************************************************************)
let see_output_hack = " See Output\xE2\x80\xBAHack for details." (* chevron *)
let fix_by_running_hh = "Try running `hh` at the command-line."
type incoming_metadata = {
timestamp: float; (** time this message arrived at stdin *)
tracking_id: string;
(** a unique random string of our own creation, which we can use for logging *)
}
type errors_from =
| Errors_from_clientIdeDaemon of {
errors: Errors.finalized_error list;
validated: bool;
}
(** TEMPORARY, FOR VALIDATION ONLY. The validated flag says whether we've validated that
errors-file contained the exact same errors as this list. Once we've done validation,
we'll need neither. *)
| Errors_from_errors_file
[@@deriving show { with_path = false }]
(** This type describes our connection to the errors.bin file, where hh_server writes
errors discovered during its current typecheck.
Here's an overview of how errors_conn works:
1. [handle_tick] attempts to update the global mutable [errors_conn] from [SeekingErrors] to [TailingErrors]
every (idle) second, by trying to open the errors file.
2. If the global [errors_conn] is [TailingErrors q], when getting next event for any state,
an [Errors_file of read_result] event may be produced if there were new errors (read_result) in q
(and not other higher pri events).
3. handling the [Errors_file] event consists in calling [handle_errors_file_item].
4. [handle_errors_file_item] takes a [read_result] and updates the diagnostic map [Lost_env.uris_with_standalone_diagnostics],
or switches the global mutable [error_conn] from [TrailingErrors] to [SeekingErrors] in case of error or end of file. *)
type errors_conn =
| SeekingErrors of {
prev_st_ino: int option;
(** The inode of the last errors.bin file we have dealt with, if any --
we'll only attempt another seek (hence, update [seek_reason] or switch to [TailingErrors])
once we find a new, different errors.bin file. *)
seek_reason:
ServerProgress.errors_file_error * ServerProgress.ErrorsRead.log_message;
(** This contains the latest explanation of why we entered or remain in [SeekingErrors] state.
"Latest" in the sense that every time [handle_tick] is unable to open or find a new errors-file,
or when [handle_errors_file_item] enters [SeekingErrors] mode, then it will will update [seek_reason].
* [ServerProgress.NothingYet] is used at initialization, before anything's yet been tried.
* [ServerProgress.NothingYet] is also used when [handle_tick] couldn't open an errors-file.
* [ServerProgress.Completed] is used when we were in [TailingErrors], and then [handle_errors_file_item]
discovered that the errors-file was complete, and so switched over to [SeekingErrors]
* Other cases are used when [handle_tick] calls [ServerProgress.ErrorsRead.openfile]
and gets an error. The only possibilities are [ServerProgress.{Killed,Build_id_mismatch}].
It's a bit naughty of us to report our own "seek reasons" (completed/nothing-yet) through
the error codes that properly belong to [ServerProgress.ErrorsRead]. But they fit so well... *)
} (** Haven't yet found a suitable errors.bin, but looking! *)
| TailingErrors of {
start_time: float;
fd: Unix.file_descr;
q: ServerProgress.ErrorsRead.read_result Lwt_stream.t;
} (** We are tailing this errors.bin file *)
module Lost_env = struct
type t = {
editor_open_files: Lsp.TextDocumentItem.t UriMap.t;
uris_with_unsaved_changes: UriSet.t;
(** see comment in get_uris_with_unsaved_changes *)
uris_with_standalone_diagnostics: (float * errors_from) UriMap.t;
(** these are diagnostics which arrived from serverless-ide or shelling out to hh check,
each with a timestamp of when they were discovered. The timestamp lets us calculate
for instance whether a diagnostic discovered by clientIdeDaemon is more recent
than one discovered by hh check. *)
current_hh_shell: current_hh_shell option;
(** If a shell-out to "hh --ide-find-refs" or similar is currently underway.
Invariant: if this is Some, then an LSP response will be delivered for it;
when it is turned to None, either the LSP response has been sent, or the
obligation has been handed off to a method that will assuredly respond. *)
}
and current_hh_shell = {
process:
(Lwt_utils.Process_success.t, Lwt_utils.Process_failure.t) Lwt_result.t;
cancellation_token: unit Lwt.u;
triggering_request: triggering_request;
shellable_type: shellable_type;
}
and triggering_request = {
id: lsp_id;
metadata: incoming_metadata;
start_time_local_handle: float;
request: lsp_request;
}
[@@warning "-69"]
and stream_file = {
file: Path.t;
q: FindRefsWireFormat.half_open_one_based list Lwt_stream.t;
partial_result_token: Lsp.partial_result_token;
}
and shellout_standard_response = {
symbol: string;
find_refs_action: ServerCommandTypes.Find_refs.action;
ide_calculated_positions: Pos.absolute list UriMap.t;
(** These are results calculated by clientIdeDaemon from its open files, one entry for each open file *)
stream_file: stream_file option;
(** If we want streaming results out of a shellout, go here *)
hint_suffixes: string list;
(** We got this list of hints from clientIdeDaemon, and pass it on to our shellout *)
}
and shellable_type =
| FindRefs of shellout_standard_response
| GoToImpl of shellout_standard_response
| Rename of {
symbol_definition: Relative_path.t SymbolDefinition.t;
find_refs_action: ServerCommandTypes.Find_refs.action;
new_name: string;
ide_calculated_patches: ServerRenameTypes.patch list;
}
end
type state =
| Pre_init (** Pre_init: we haven't yet received the initialize request. *)
| Lost_server of Lost_env.t
(** Lost_server: this is the main state that we'll be in (after initialize request,
before shutdown request) under ide_standalone. TODO(ljw): rename it.
DEPRECATED: it's also used for modes other than ide_standalone, modes
which do want a connection to hh_server, but either we failed to
start hh_server up, or someone stole the persistent connection from us
and we might choose to grab it back.
We use the optional [Lost_env.params.new_hh_server_state] as a way of storing
within Lost_env whether it's being used for ide_standalone (None)
or for other deprecated modes (Some). *)
| Post_shutdown
(** Post_shutdown: we received a shutdown request from the client, and
therefore shut down our connection to the server. We can't handle
any more requests from the client and will close as soon as it
notifies us that we can exit. *)
let is_post_shutdown (state : state) : bool =
match state with
| Post_shutdown -> true
| Pre_init
| Lost_server _ ->
false
type result_handler = lsp_result -> state -> state Lwt.t
type result_telemetry = {
result_count: int; (** how many results did we send back to the user? *)
result_extra_data: Telemetry.t option; (** other message-specific data *)
log_immediately: bool;
(** Should we log telemetry about this response to an LSP action immediately?
(default true, in case result_telemetry isn't provided.)
Or should we defer logging until some later time, e.g. [handle_shell_out_complete]? *)
}
let make_result_telemetry
?(result_extra_data : Telemetry.t option)
?(log_immediately : bool = true)
(count : int) : result_telemetry =
{ result_count = count; result_extra_data; log_immediately }
(* --ide-rename-by-symbol returns a list of patches *)
type ide_refactor_patch = {
filename: string;
line: int;
char_start: int;
char_end: int;
patch_type: string;
replacement: string;
}
let initialize_params_ref : Lsp.Initialize.params option ref = ref None
let initialize_params_exc () : Lsp.Initialize.params =
match !initialize_params_ref with
| None -> failwith "initialize_params not yet received"
| Some initialize_params -> initialize_params
(** root only becomes available after the initialize message *)
let get_root_opt () : Path.t option =
match !initialize_params_ref with
| None -> None
| Some initialize_params ->
let paths = [Lsp_helpers.get_root initialize_params] in
Some (Wwwroot.interpret_command_line_root_parameter paths)
(** root only becomes available after the initialize message *)
let get_root_exn () : Path.t = Option.value_exn (get_root_opt ())
(** We remember the last version of .hhconfig, and hack_rc_mode switch,
so that if they change then we know we must terminate and be restarted. *)
let hhconfig_version_and_switch : string ref = ref "[NotYetInitialized]"
(** This flag is used to control how much will be written
to log-files. It can be turned on initially by --verbose at the command-line or
setting "trace:Verbose" in initializationParams. Thereafter, it can
be changed by the user dynamically via $/setTraceNotification.
Don't alter this reference directly; instead use [set_verbose_to_file]
so as to pass the message on to ide_service as well.
Note: control for how much will be written to stderr is solely
controlled by --verbose at the command-line, stored in env.verbose. *)
let verbose_to_file : bool ref = ref false
let requests_outstanding : (lsp_request * result_handler) IdMap.t ref =
ref IdMap.empty
let get_outstanding_request_exn (id : lsp_id) : lsp_request =
match IdMap.find_opt id !requests_outstanding with
| Some (request, _) -> request
| None -> failwith "response id doesn't correspond to an outstanding request"
(** hh_server pushes errors to an errors.bin file, which we tail along.
(Only in ide_standalone mode; we don't do anything in other modes.)
This variable is where we store our progress in seeking an errors.bin, or tailing
one we already found. It's updated
(1) by [handle_tick] which runs every second and may call [try_open_errors_file] to seek errors.bin;
(2) by [handle_errors_file_item] which tails an errors.bin file. *)
let latest_hh_server_errors : errors_conn ref =
ref
(SeekingErrors
{ prev_st_ino = None; seek_reason = (ServerProgress.NothingYet, "init") })
(** This is the latest state of the progress.json file, updated once a second
in a background Lwt process [background_status_refresher]. This file is where the
monitor reports its status like "starting up", and hh_server reports its status
like "typechecking". If there is no hh_server or monitor, the state is reported
as "Stopped". *)
let latest_hh_server_progress : ServerProgress.t option ref = ref None
(** Have we already sent a status message over LSP? If so, and our new
status will be just the same as the previous one, we won't need to send it
again. This stores the most recent status that the LSP client has. *)
let showStatus_outstanding : string ref = ref ""
let log s = Hh_logger.log ("[client-lsp] " ^^ s)
let log_debug s = Hh_logger.debug ("[client-lsp] " ^^ s)
let log_error s = Hh_logger.error ("[client-lsp] " ^^ s)
let set_up_hh_logger_for_client_lsp (root : Path.t) : unit =
(* Log to a file on disk. Note that calls to `Hh_logger` will always write to
`stderr`; this is in addition to that. *)
let client_lsp_log_fn = ServerFiles.client_lsp_log root in
begin
try Sys.rename client_lsp_log_fn (client_lsp_log_fn ^ ".old") with
| _e -> ()
end;
Hh_logger.set_log client_lsp_log_fn;
log "Starting clientLsp at %s" client_lsp_log_fn
let to_stdout (json : Hh_json.json) : unit =
let s = Hh_json.json_to_string json ^ "\r\n\r\n" in
Http_lite.write_message stdout s
let get_editor_open_files (state : state) :
Lsp.TextDocumentItem.t UriMap.t option =
match state with
| Pre_init
| Post_shutdown ->
None
| Lost_server lenv -> Some lenv.Lost_env.editor_open_files
(** The architecture of clientLsp is a single-threaded message loop inside
[ClientLsp.main]. The loop calls [get_next_event] to wait for the next
event from a variety of sources, dispatches it according to what kind of event
it is, and repeats until it finally receives an event that an "exit" lsp notification
has been received from the client. *)
type event =
| Client_message of incoming_metadata * lsp_message
(** The editor e.g. VSCode might send a request or notification LSP message to us
at any time. This event represents those LSP messages. The fields store
raw json as well as the parsed form of it. Handled by [handle_client_message]. *)
| Daemon_notification of ClientIdeMessage.notification
(** This event represents whenever clientIdeDaemon
pushes a notification to us, e.g. a progress or status update.
Handled by [handle_client_ide_notification]. *)
| Errors_file of ServerProgress.ErrorsRead.read_result option
(** Under [--config ide_standalone=true], we once a second seek out a new errors.bin
file that the server has produced to accumulate errors in the current typecheck.
Once we have one, we "tail -f" it until it's finished. This event signals
with [Some Ok _] that new errors have been appended to the file in the current typecheck,
or [Some Error _] that either the typecheck completed or hh_server failed.
The [None] case never arises; it represents a logic bug, an unexpected close
of the underlying [Lwt_stream.t]. All handled in [handle_errors_file_item]. *)
| Refs_file of FindRefsWireFormat.half_open_one_based list option
(** If the editor sent a find-refs-request with a partialResultsToken, then
we create a partial-results file and "tail -f" it until the shell-out to "hh --ide-find-refs-by-symbol3"
has finished. This event signals with [Some] that new refs have been appended to the file.
The [None] case never arises; it represents a logic bug, an unexpected close
of the underlying [Lwt_stream.t]. *)
| Shell_out_complete of
((Lwt_utils.Process_success.t, Lwt_utils.Process_failure.t) result
* Lost_env.triggering_request
* Lost_env.shellable_type)
(** Under [--config ide_standlone=true], LSP requests for rename or
find-refs are accomplished by kicking off an asynchronous shell-out to
"hh --refactor" or "hh --ide-find-refs". This event signals that the
shell-out has completed and it's now time to process the results.
Handled in [handle_shell_out_complete].
Invariant: if we have one of these events, then we must eventually produce
an LSP response for it. *)
| Tick
(** Once a second, if no other events are pending, we synthesize a Tick
event. Handled in [handle_tick]. It does things like send IDE_IDLE if
needed to hh_server, see if there's a new errors.bin streaming-error file
to tail, and flush HackEventLogger telemetry. *)
let event_to_string (event : event) : string =
match event with
| Client_message (metadata, m) ->
Printf.sprintf
"Client_message(#%s: %s)"
metadata.tracking_id
(Lsp_fmt.denorm_message_to_string m)
| Daemon_notification n ->
Printf.sprintf
"Daemon_notification(%s)"
(ClientIdeMessage.notification_to_string n)
| Tick -> "Tick"
| Refs_file None -> "Refs_file(anomalous end-of-stream)"
| Refs_file (Some refs) ->
Printf.sprintf "Refs_file(%d refs)" (List.length refs)
| Errors_file None -> "Errors_file(anomalous end-of-stream)"
| Errors_file (Some (Ok (ServerProgress.Telemetry _))) ->
"Errors_file: telemetry"
| Errors_file (Some (Ok (ServerProgress.Errors { errors; timestamp = _ }))) ->
begin
match Relative_path.Map.choose_opt errors with
| None -> "Errors_file(anomalous empty report)"
| Some (file, errors_in_file) ->
Printf.sprintf
"Errors_file(%d errors in %s, ...)"
(List.length errors_in_file)
(Relative_path.suffix file)
end
| Errors_file (Some (Error (e, log_message))) ->
Printf.sprintf
"Errors_file: %s [%s]"
(ServerProgress.show_errors_file_error e)
log_message
| Shell_out_complete _ -> "Shell_out_complete"
let is_tick (event : event) : bool =
match event with
| Tick -> true
| Errors_file _
| Refs_file _
| Shell_out_complete _
| Client_message _
| Daemon_notification _ ->
false
(* Here are some exit points. *)
let exit_ok () = exit 0
let exit_fail () = exit 1
(* The following connection exceptions inform the main LSP event loop how to
respond to an exception: was the exception a connection-related exception
(one of these) or did it arise during other logic (not one of these)? Can
we report the exception to the LSP client? Can we continue handling
further LSP messages or must we quit? If we quit, can we do so immediately
or must we delay? -- Separately, they also help us marshal callstacks
across daemon- and process-boundaries. *)
exception
Client_fatal_connection_exception of Marshal_tools.remote_exception_data
exception
Client_recoverable_connection_exception of Marshal_tools.remote_exception_data
exception Daemon_nonfatal_exception of Lsp.Error.t
(** Helper function to construct an Lsp.Error. Its goal is to gather
useful information in the optional freeform 'data' field. It assembles
that data out of any data already provided, the provided stack, and the
current stack. A typical scenario is that we got an error marshalled
from a remote server with its remote stack where the error was generated,
and we also want to record the stack where we received it. *)
let make_lsp_error
?(data : Hh_json.json option = None)
?(stack : string option)
?(current_stack : bool = true)
?(code : Lsp.Error.code = Lsp.Error.UnknownErrorCode)
(message : string) : Lsp.Error.t =
let elems =
match data with
| None -> []
| Some (Hh_json.JSON_Object elems) -> elems
| Some json -> [("data", json)]
in
let elems =
match stack with
| Some stack when not (List.Assoc.mem ~equal:String.equal elems "stack") ->
("stack", stack |> Exception.clean_stack |> Hh_json.string_) :: elems
| _ -> elems
in
let elems =
match current_stack with
| true when not (List.Assoc.mem ~equal:String.equal elems "current_stack")
->
( "current_stack",
Exception.get_current_callstack_string 99
|> Exception.clean_stack
|> Hh_json.string_ )
:: elems
| _ -> elems
in
{ Lsp.Error.code; message; data = Some (Hh_json.JSON_Object elems) }
(** Use ignore_promise_but_handle_failure when you want don't care about awaiting
results of an async piece of work, but still want any exceptions to be logged.
This is similar to Lwt.async except (1) it logs to our HackEventLogger and
Hh_logger rather than stderr, (2) it you can decide on a case-by-case basis what
should happen to exceptions rather than having them all share the same
Lwt.async_exception_hook, (3) while Lwt.async takes a lambda for creating the
promise and so catches exceptions during promise creation, this function takes
an already-existing promise and so the caller has to handle such exceptions
themselves - I resent using lambdas as a control-flow primitive.
You can think of this function as similar to [ignore], but enhanced because
it's poor practice to ignore a promise. *)
let ignore_promise_but_handle_failure
~(desc : string) ~(terminate_on_failure : bool) (promise : unit Lwt.t) :
unit =
Lwt.async (fun () ->
try%lwt
let%lwt () = promise in
Lwt.return_unit
with
| exn ->
let open Hh_json in
let exn = Exception.wrap exn in
let message = "Unhandled exception: " ^ Exception.get_ctor_string exn in
let stack =
Exception.get_backtrace_string exn |> Exception.clean_stack
in
let data =
JSON_Object
[
("description", string_ desc);
("message", string_ message);
("stack", string_ stack);
]
in
HackEventLogger.client_lsp_exception
~root:(get_root_opt ())
~message:"Unhandled exception"
~data_opt:(Some data)
~source:"lsp_misc";
log_error "%s\n%s\n%s" message desc stack;
if terminate_on_failure then
(* exit 2 is the same as used by Lwt.async *)
exit 2;
Lwt.return_unit)
let state_to_string (state : state) : string =
match state with
| Pre_init -> "Pre_init"
| Lost_server _ -> "Lost_server"
| Post_shutdown -> "Post_shutdown"
(** This conversion is imprecise. Comments indicate potential gaps *)
let completion_kind_to_si_kind
(completion_kind : Completion.completionItemKind option) :
SearchTypes.si_kind =
let open Lsp in
let open SearchTypes in
match completion_kind with
| Some Completion.Class -> SI_Class
| Some Completion.Method -> SI_ClassMethod
| Some Completion.Function -> SI_Function
| Some Completion.Variable ->
SI_LocalVariable (* or SI_Mixed, but that's never used *)
| Some Completion.Property -> SI_Property
| Some Completion.Constant -> SI_GlobalConstant (* or SI_ClassConstant *)
| Some Completion.Interface -> SI_Interface (* or SI_Trait *)
| Some Completion.Enum -> SI_Enum
| Some Completion.Module -> SI_Namespace
| Some Completion.Constructor -> SI_Constructor
| Some Completion.Keyword -> SI_Keyword
| Some Completion.Value -> SI_Literal
| Some Completion.TypeParameter -> SI_Typedef
(* The completion enum includes things we don't really support *)
| _ -> SI_Unknown
let si_kind_to_completion_kind (kind : SearchTypes.si_kind) :
Completion.completionItemKind option =
match kind with
| SearchTypes.SI_XHP
| SearchTypes.SI_Class ->
Some Completion.Class
| SearchTypes.SI_ClassMethod -> Some Completion.Method
| SearchTypes.SI_Function -> Some Completion.Function
| SearchTypes.SI_Mixed
| SearchTypes.SI_LocalVariable ->
Some Completion.Variable
| SearchTypes.SI_Property -> Some Completion.Field
| SearchTypes.SI_ClassConstant -> Some Completion.Constant
| SearchTypes.SI_Interface
| SearchTypes.SI_Trait ->
Some Completion.Interface
| SearchTypes.SI_Enum -> Some Completion.Enum
| SearchTypes.SI_Namespace -> Some Completion.Module
| SearchTypes.SI_Constructor -> Some Completion.Constructor
| SearchTypes.SI_Keyword -> Some Completion.Keyword
| SearchTypes.SI_Literal -> Some Completion.Value
| SearchTypes.SI_GlobalConstant -> Some Completion.Constant
| SearchTypes.SI_Typedef -> Some Completion.TypeParameter
| SearchTypes.SI_Unknown -> None
let read_hhconfig_version () : string Lwt.t =
match get_root_opt () with
| None -> Lwt.return "[NoRoot]"
| Some root ->
let file = Filename.concat (Path.to_string root) ".hhconfig" in
let%lwt config = Config_file_lwt.parse_hhconfig file in
(match config with
| Ok (_hash, config) ->
let version =
config
|> Config_file.Getters.string_opt "version"
|> Config_file_lwt.parse_version
|> Config_file_lwt.version_to_string_opt
|> Option.value ~default:"[NoVersion]"
in
Lwt.return version
| Error message -> Lwt.return (Printf.sprintf "[NoHhconfig:%s]" message))
let read_hhconfig_version_and_switch () : string Lwt.t =
let%lwt hack_rc_mode_result =
Lwt_utils.read_all (Sys_utils.expanduser "~/.hack_rc_mode")
in
let hack_rc_mode =
match hack_rc_mode_result with
| Ok s -> " hack_rc_mode=" ^ s
| Error _ -> ""
in
let hh_home =
match Sys.getenv_opt "HH_HOME" with
| Some s -> " HH_HOME=" ^ s
| None -> ""
in
let%lwt hhconfig_version = read_hhconfig_version () in
Lwt.return (hhconfig_version ^ hack_rc_mode ^ hh_home)
let terminate_if_version_changed_since_start_of_lsp () : unit Lwt.t =
let%lwt current_version_and_switch = read_hhconfig_version_and_switch () in
let is_ok =
String.equal !hhconfig_version_and_switch current_version_and_switch
in
if is_ok then
Lwt.return_unit
else
(* In these cases we have to terminate our LSP server, and trust
VSCode to restart us. Note that we can't do clientStart because that
would start our (old) version of hh_server, not the new one! *)
let message =
""
^ "Version in hhconfig+switch that spawned the current hh_client: "
^ !hhconfig_version_and_switch
^ "\nVersion in hhconfig+switch currently: "
^ current_version_and_switch
^ "\n"
in
Lsp_helpers.telemetry_log to_stdout message;
exit_fail ()
(** get_uris_with_unsaved_changes is the set of files for which we've
received didChange but haven't yet received didSave/didClose. *)
let get_uris_with_unsaved_changes (state : state) : UriSet.t =
match state with
| Lost_server lenv -> lenv.Lost_env.uris_with_unsaved_changes
| Pre_init
| Post_shutdown ->
UriSet.empty
(** This cancellable async function will block indefinitely until a notification is
available from ide_service, and return. *)
let pop_from_ide_service (ide_service : ClientIdeService.t ref) : event Lwt.t =
let%lwt notification_opt =
Lwt_message_queue.pop (ClientIdeService.get_notifications !ide_service)
in
match notification_opt with
| None -> Lwt.task () |> fst (* a never-fulfilled, cancellable promise *)
| Some notification -> Lwt.return (Daemon_notification notification)
(** This cancellable async function will block indefinitely until data is
available from the client, but won't read from it. If there's no client
then it awaits indefinitely. *)
let wait_until_client_has_data (client : Jsonrpc.t option) : unit Lwt.t =
match client with
| None -> Lwt.task () |> fst (* a never-fulfilled, cancellable promise *)
| Some client ->
let%lwt () =
match Jsonrpc.await_until_message client with
| `Already_has_message -> Lwt.return_unit
| `Wait_for_data_here fd ->
let fd = Lwt_unix.of_unix_file_descr fd in
let%lwt () = Lwt_unix.wait_read fd in
Lwt.return_unit
in
Lwt.return_unit
(** Determine whether to read a message from the client (the editor) if
we've yet received an initialize message, or from
clientIdeDaemon, or whether neither is ready within 1s. *)
let get_client_message_source
(client : Jsonrpc.t option)
(ide_service : ClientIdeService.t ref)
(q_opt : ServerProgress.ErrorsRead.read_result Lwt_stream.t option)
(refs_q_opt :
FindRefsWireFormat.half_open_one_based list Lwt_stream.t option) :
[ `From_client
| `From_ide_service of event
| `From_q of ServerProgress.ErrorsRead.read_result option
| `From_refs_q of FindRefsWireFormat.half_open_one_based list option
| `No_source
]
Lwt.t =
if Option.value_map client ~default:false ~f:Jsonrpc.has_message then
Lwt.return `From_client
else
let%lwt message_source =
Lwt.pick
([
(let%lwt () = Lwt_unix.sleep 1.0 in
Lwt.return `No_source);
(let%lwt () = wait_until_client_has_data client in
Lwt.return `From_client);
(let%lwt notification = pop_from_ide_service ide_service in
Lwt.return (`From_ide_service notification));
]
@ Option.value_map q_opt ~default:[] ~f:(fun q ->
[Lwt_stream.get q |> Lwt.map (fun item -> `From_q item)])
@ Option.value_map refs_q_opt ~default:[] ~f:(fun q ->
[Lwt_stream.get q |> Lwt.map (fun item -> `From_refs_q item)]))
in
Lwt.return message_source
(** get_next_event: picks up the next available message.
The way it's implemented, at the first character of a message,
we block until that message is completely received. *)
let get_next_event
(state : state ref)
(client : Jsonrpc.t)
(ide_service : ClientIdeService.t ref) : event Lwt.t =
let can_use_client =
match !initialize_params_ref with
| Some { Initialize.initializationOptions; _ }
when initializationOptions.Initialize.delayUntilDoneInit -> begin
match ClientIdeService.get_status !ide_service with
| ClientIdeService.Status.(Initializing | Processing_files _ | Rpc _) ->
false
| ClientIdeService.Status.(Ready | Stopped _) -> true
end
| _ -> true
in
let client = Option.some_if can_use_client client in
let from_client (client : Jsonrpc.t) : event Lwt.t =
let%lwt message = Jsonrpc.get_message client in
match message with
| `Message { Jsonrpc.json; timestamp } -> begin
try
let message = Lsp_fmt.parse_lsp json get_outstanding_request_exn in
let rnd = Random_id.short_string () in
let tracking_id =
match message with
| RequestMessage (id, _) -> rnd ^ "." ^ Lsp_fmt.id_to_string id
| _ -> rnd
in
Lwt.return (Client_message ({ tracking_id; timestamp }, message))
with
| e ->
let e = Exception.wrap e in
let edata =
{
Marshal_tools.stack = Exception.get_backtrace_string e;
message = Exception.get_ctor_string e;
}
in
raise (Client_recoverable_connection_exception edata)
end
| `Fatal_exception edata -> raise (Client_fatal_connection_exception edata)
| `Recoverable_exception edata ->
raise (Client_recoverable_connection_exception edata)
in
match !state with
| Lost_server ({ Lost_env.current_hh_shell = Some sh; _ } as lenv)
when not (Lwt.is_sleeping sh.Lost_env.process) ->
(* Invariant is that if current_hh_shell is Some, then we will eventually
produce an LSP response for it. We're turning it into None here;
the obligation to return an LSP response has been transferred onto
our Shell_out_complete result. *)
state := Lost_server { lenv with Lost_env.current_hh_shell = None };
let%lwt result = sh.Lost_env.process in
Lwt.return
(Shell_out_complete
(result, sh.Lost_env.triggering_request, sh.Lost_env.shellable_type))
| Pre_init
| Lost_server _
| Post_shutdown ->
(* invariant used by [handle_tick_event]: Errors_file events solely arise
in state [Lost_server] in conjunction with [TailingErrors]. *)
let q_opt =
match (!latest_hh_server_errors, !state) with
| (TailingErrors { q; _ }, Lost_server _) -> Some q
| _ -> None
in
let refs_q_opt =
match !state with
| Lost_server
Lost_env.
{
current_hh_shell =
Some
{
shellable_type = FindRefs { stream_file = Some { q; _ }; _ };
_;
};
_;
} ->
Some q
| _ -> None
in
let%lwt message_source =
get_client_message_source client ide_service q_opt refs_q_opt
in
(match message_source with
| `From_client ->
let%lwt message = from_client (Option.value_exn client) in
Lwt.return message
| `From_ide_service message -> Lwt.return message
| `From_q message -> Lwt.return (Errors_file message)
| `From_refs_q message -> Lwt.return (Refs_file message)
| `No_source -> Lwt.return Tick)
type powered_by =
| Hh_server
| Language_server
| Serverless_ide
let add_powered_by ~(powered_by : powered_by) (json : Hh_json.json) :
Hh_json.json =
let open Hh_json in
match (json, powered_by) with
| (JSON_Object props, Serverless_ide) ->
JSON_Object (("powered_by", JSON_String "serverless_ide") :: props)
| (_, _) -> json
let respond_jsonrpc
~(powered_by : powered_by) (id : lsp_id) (result : lsp_result) : unit =
print_lsp_response id result |> add_powered_by ~powered_by |> to_stdout
let notify_jsonrpc ~(powered_by : powered_by) (notification : lsp_notification)
: unit =
print_lsp_notification notification |> add_powered_by ~powered_by |> to_stdout
(** respond_to_error: if we threw an exception during the handling of a request,
report the exception to the client as the response to their request. *)
let respond_to_error (event : event option) (e : Lsp.Error.t) : unit =
let result = ErrorResult e in
match event with
| Some (Client_message (_, RequestMessage (id, _request))) ->
respond_jsonrpc ~powered_by:Language_server id result
| _ ->
(* We want to report LSP error 'e' over jsonrpc. But jsonrpc only allows
errors to be reported in response to requests. So we'll stick the information
in a telemetry/event. The format of this event isn't defined. We're going to
roll our own, using ad-hoc json fields to emit all the data out of 'e' *)
let open Lsp.Error in
let extras =
("code", e.code |> Error.show_code |> Hh_json.string_)
:: Option.value_map e.data ~default:[] ~f:(fun data -> [("data", data)])
in
Lsp_helpers.telemetry_error to_stdout e.message ~extras
(** request_showStatusFB: pops up a dialog *)
let request_showStatusFB (params : ShowStatusFB.params) : unit =
let initialize_params = initialize_params_exc () in
if not (Lsp_helpers.supports_status initialize_params) then
()
else
(* We try not to send duplicate statuses.
That means: if you call request_showStatus but your message is the same as
what's already up, then you won't be shown, and your callbacks won't be shown. *)
let msg = params.ShowStatusFB.request.ShowStatusFB.message in
if String.equal msg !showStatus_outstanding then
()
else (
showStatus_outstanding := msg;
let id = NumberId (Jsonrpc.get_next_request_id ()) in
let request = ShowStatusRequestFB params in
to_stdout (print_lsp_request id request);
let handler (_ : lsp_result) (state : state) : state Lwt.t =
Lwt.return state
in
requests_outstanding :=
IdMap.add id (request, handler) !requests_outstanding
)
(** Dismiss all diagnostics. *)
let dismiss_diagnostics (state : state) : state =
match state with
| Lost_server lenv ->
let open Lost_env in
(* [uris_with_standalone_diagnostics] are the files-with-squiggles that we've reported
to the editor; these came either from clientIdeDaemon or from tailing
the errors.bin file in which hh_server accumulates diagnostics for the current typecheck. *)
UriMap.iter
(fun uri _time ->
let params =
{ PublishDiagnostics.uri; diagnostics = []; isStatusFB = false }
in
let notification = PublishDiagnosticsNotification params in
notification |> print_lsp_notification |> to_stdout)
lenv.uris_with_standalone_diagnostics;
Lost_server { lenv with uris_with_standalone_diagnostics = UriMap.empty }
| Pre_init -> Pre_init
| Post_shutdown -> Post_shutdown
(************************************************************************)
(* Conversions - ad-hoc ones written as needed them, not systematic *)
(************************************************************************)
let lsp_uri_to_path = Lsp_helpers.lsp_uri_to_path
let path_to_lsp_uri = Lsp_helpers.path_to_lsp_uri
let lsp_position_to_ide (position : Lsp.position) : Ide_api_types.position =
{ Ide_api_types.line = position.line + 1; column = position.character + 1 }
let lsp_file_position_to_hack (params : Lsp.TextDocumentPositionParams.t) :
string * int * int =
let open Lsp.TextDocumentPositionParams in
let { Ide_api_types.line; column } = lsp_position_to_ide params.position in
let filename =
Lsp_helpers.lsp_textDocumentIdentifier_to_filename params.textDocument
in
(filename, line, column)
let rename_params_to_document_position (params : Lsp.Rename.params) :
Lsp.TextDocumentPositionParams.t =
Rename.
{
TextDocumentPositionParams.textDocument = params.textDocument;
position = params.position;
}
let ide_shell_out_pos_to_lsp_location
(pos : FindRefsWireFormat.half_open_one_based) : Lsp.Location.t =
let open FindRefsWireFormat in
Lsp.Location.
{
uri = path_to_lsp_uri pos.filename ~default_path:pos.filename;
range =
{
start = { line = pos.line - 1; character = pos.char_start - 1 };
end_ = { line = pos.line - 1; character = pos.char_end - 1 };
};
}
let hack_pos_to_lsp_location (pos : Pos.absolute) ~(default_path : string) :
Lsp.Location.t =
Lsp.Location.
{
uri = path_to_lsp_uri (Pos.filename pos) ~default_path;
range = Lsp_helpers.hack_pos_to_lsp_range ~equal:String.equal pos;
}
let ide_range_to_lsp (range : Ide_api_types.range) : Lsp.range =
{
Lsp.start =
{
Lsp.line = range.Ide_api_types.st.Ide_api_types.line - 1;
character = range.Ide_api_types.st.Ide_api_types.column - 1;
};
end_ =
{
Lsp.line = range.Ide_api_types.ed.Ide_api_types.line - 1;
character = range.Ide_api_types.ed.Ide_api_types.column - 1;
};
}
let lsp_range_to_ide (range : Lsp.range) : Ide_api_types.range =
Ide_api_types.
{
st = lsp_position_to_ide range.start;
ed = lsp_position_to_ide range.end_;
}
let hack_symbol_definition_to_lsp_construct_location
(symbol : string SymbolDefinition.t) ~(default_path : string) :
Lsp.Location.t =
let open SymbolDefinition in
hack_pos_to_lsp_location symbol.span ~default_path
let hack_pos_definition_to_lsp_identifier_location
(sid : Pos.absolute * string) ~(default_path : string) :
Lsp.DefinitionLocation.t =
let (pos, title) = sid in
let location = hack_pos_to_lsp_location pos ~default_path in
Lsp.DefinitionLocation.{ location; title = Some title }
let hack_symbol_definition_to_lsp_identifier_location
(symbol : string SymbolDefinition.t) ~(default_path : string) :
Lsp.DefinitionLocation.t =
let open SymbolDefinition in
let location = hack_pos_to_lsp_location symbol.pos ~default_path in
Lsp.DefinitionLocation.
{
location;
title = Some (Utils.strip_ns symbol.SymbolDefinition.full_name);
}
let hack_errors_to_lsp_diagnostic
(filename : string) (errors : Errors.finalized_error list) :
PublishDiagnostics.params =
let open Lsp.Location in
let location_message (message : Pos.absolute * string) :
Lsp.Location.t * string =
let (pos, message) = message in
(* It's known and expected that hh_server sometimes sends an error
with empty filename in its list of messages. These implicitly
refer to the file in which the error is reported. *)
let pos =
if String.is_empty (Pos.filename pos) then
Pos.set_file filename pos
else
pos
in
let { uri; range } = hack_pos_to_lsp_location pos ~default_path:filename in
({ Location.uri; range }, Markdown_lite.render message)
in
let hack_error_to_lsp_diagnostic (error : Errors.finalized_error) =
let all_messages =
User_error.to_list error |> List.map ~f:location_message
in
let (first_message, additional_messages) =
match all_messages with
| hd :: tl -> (hd, tl)
| [] -> failwith "Expected at least one error in the error list"
in
let ( {
range;
uri =
(* This is the file of the first message of the error which is supposed to correspond to [filename] *)
_;
},
message ) =
first_message
in
let relatedInformation =
additional_messages
|> List.map ~f:(fun (location, message) ->
{
PublishDiagnostics.relatedLocation = location;
relatedMessage = message;
})
in
let first_loc = fst first_message in
let custom_errors =
List.map error.User_error.custom_msgs ~f:(fun relatedMessage ->
PublishDiagnostics.{ relatedLocation = first_loc; relatedMessage })
in
let relatedInformation = relatedInformation @ custom_errors in
{
Lsp.PublishDiagnostics.range;
severity = Some Lsp.PublishDiagnostics.Error;
code = PublishDiagnostics.IntCode (User_error.get_code error);
source = Some "Hack";
message;
relatedInformation;
relatedLocations = relatedInformation (* legacy FB extension *);
}
in
(* The caller is required to give us a non-empty filename. If it is empty,
the following path_to_lsp_uri will fall back to the default path - which
is also empty - and throw, logging appropriate telemetry. *)
{
Lsp.PublishDiagnostics.uri = path_to_lsp_uri filename ~default_path:"";
isStatusFB = false;
diagnostics = List.map errors ~f:hack_error_to_lsp_diagnostic;
}
(** Retrieves a TextDocumentItem for a given URI from editor_open_files,
or raises LSP [InvalidRequest] if not open *)
let get_text_document_item
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t) (uri : documentUri) :
TextDocumentItem.t =
match UriMap.find_opt uri editor_open_files with
| Some document -> document
| None ->
raise
(Error.LspException
{
Error.code = Error.InvalidRequest;
message = "action on a file not open in LSP server";
data = None;
})
(** Retrieves the content of this file, or raises an LSP [InvalidRequest] exception
if the file isn't currently open *)
let get_document_contents
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t) (uri : documentUri) :
string =
let document = get_text_document_item editor_open_files uri in
document.TextDocumentItem.text
(** Converts a single TextDocumentItem (an element in editor_open_files, for example) into a document that ClientIdeDaemon uses*)
let lsp_document_to_ide (text_document : TextDocumentItem.t) :
ClientIdeMessage.document =
let fn = text_document.TextDocumentItem.uri in
{
ClientIdeMessage.file_path = Path.make @@ Lsp_helpers.lsp_uri_to_path fn;
file_contents = text_document.TextDocumentItem.text;
}
(** Turns the complete set of editor_open_files into a format
suitable for clientIdeDaemon *)
let get_documents_from_open_files
(editor_open_files : TextDocumentItem.t UriMap.t) :
ClientIdeMessage.document list =
editor_open_files |> UriMap.values |> List.map ~f:lsp_document_to_ide
(** Turns this Lsp uri+line+col into a format suitable for clientIdeDaemon.
Raises an LSP [InvalidRequest] exception if the file isn't currently open. *)
let get_document_location
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : Lsp.TextDocumentPositionParams.t) :
ClientIdeMessage.document * ClientIdeMessage.location =
let (file_path, line, column) = lsp_file_position_to_hack params in
let uri =
params.TextDocumentPositionParams.textDocument.TextDocumentIdentifier.uri
in
let file_path = Path.make file_path in
let file_contents = get_document_contents editor_open_files uri in
( { ClientIdeMessage.file_path; file_contents },
{ ClientIdeMessage.line; column } )
(** Parses output of "hh --ide-find-references" and "hh --ide-go-to-impl".
If the output is malformed, raises an exception. *)
let shellout_locations_to_lsp_locations_exn (stdout : string) :
Lsp.Location.t list =
FindRefsWireFormat.IdeShellout.from_string_exn stdout
|> List.map ~f:ide_shell_out_pos_to_lsp_location
(** Parses output of "hh --ide-rename-by-symbol".
If the output is malformed, raises an exception. *)
let shellout_patch_list_to_lsp_edits_exn (stdout : string) : Lsp.WorkspaceEdit.t
=
let json = Yojson.Safe.from_string stdout in
match json with
| `List positions ->
let patch_locations =
List.map positions ~f:(fun pos ->
let open Yojson.Basic.Util in
let lst_json = Yojson.Safe.to_basic pos in
let filename = lst_json |> member "filename" |> to_string in
let patches = lst_json |> member "patches" |> to_list in
let patches =
List.map
~f:(fun x ->
let char_start = x |> member "col_start" |> to_int in
let char_end = x |> member "col_end" |> to_int in
let line = x |> member "line" |> to_int in
let patch_type = x |> member "patch_type" |> to_string in
let replacement = x |> member "replacement" |> to_string in
{
filename;
char_start;
char_end;
line;
patch_type;
replacement;
})
patches
in
patches)
in
let locations = List.concat patch_locations in
let patch_to_workspace_edit_change patch =
let ide_shell_out_pos =
{
FindRefsWireFormat.filename = patch.filename;
char_start = patch.char_start;
char_end = patch.char_end + 1;
(* This end is inclusive for range replacement *)
line = patch.line;
}
in
match patch.patch_type with
| "insert"
| "replace" ->
let loc = ide_shell_out_pos_to_lsp_location ide_shell_out_pos in
( File_url.create patch.filename,
{
TextEdit.range = loc.Lsp.Location.range;
newText = patch.replacement;
} )
| "remove" ->
let loc = ide_shell_out_pos_to_lsp_location ide_shell_out_pos in
( File_url.create patch.filename,
{ TextEdit.range = loc.Lsp.Location.range; newText = "" } )
| e -> failwith ("invalid patch type: " ^ e)
in
let changes = List.map ~f:patch_to_workspace_edit_change locations in
let changes =
List.fold changes ~init:SMap.empty ~f:(fun acc (uri, text_edit) ->
let current_edits =
Option.value ~default:[] (SMap.find_opt uri acc)
in
let new_edits = text_edit :: current_edits in
SMap.add uri new_edits acc)
in
{ WorkspaceEdit.changes }
| `Int _
| `Tuple _
| `Bool _
| `Intlit _
| `Null
| `Variant _
| `Assoc _
| `Float _
| `String _ ->
failwith ("Expected list, got json like " ^ stdout)
(************************************************************************)
(* Connection and rpc *)
(************************************************************************)
let start_server ~(env : env) (root : Path.t) : unit =
(* This basically does "hh_client start": a single attempt to open the *)
(* socket, send+read version and compare for mismatch, send handoff and *)
(* read response. It will print information to stderr. If the server is in *)
(* an unresponsive or invalid state then it will kill the server. Next if *)
(* necessary it tries to spawn the server and wait until the monitor is *)
(* responsive enough to print "ready". It will do a hard program exit if *)
(* there were spawn problems. *)
let env_start =
{
ClientStart.root;
from = !from;
no_load = false;
watchman_debug_logging = false;
log_inference_constraints = false;
silent = true;
exit_on_failure = false;
ignore_hh_version = false;
saved_state_ignore_hhconfig = false;
mini_state = None;
save_64bit = None;
save_human_readable_64bit_dep_map = None;
prechecked = None;
config = env.args.config;
custom_hhi_path = None;
custom_telemetry_data = [];
allow_non_opt_build = false;
}
in
let _exit_status = ClientStart.main env_start in
()
let announce_ide_failure (error_data : ClientIdeMessage.rich_error) : unit Lwt.t
=
let open ClientIdeMessage in
let debug_details =
Printf.sprintf
"%s - %s"
error_data.category
(Option.value_map error_data.data ~default:"" ~f:Hh_json.json_to_string)
in
log
"IDE services could not be initialized.\n%s\n%s"
error_data.long_user_message
debug_details;
let input =
Printf.sprintf "%s\n\n%s" error_data.long_user_message debug_details
in
let%lwt upload_result =
Clowder_paste.clowder_upload_and_get_url ~timeout:10. input
in
let append_to_log =
match upload_result with
| Ok url -> Printf.sprintf "\nMore details: %s" url
| Error message ->
Printf.sprintf
"\n\nMore details:\n%s\n\nTried to upload those details but it didn't work...\n%s"
debug_details
message
in
Lsp_helpers.log_error to_stdout (error_data.long_user_message ^ append_to_log);
if error_data.is_actionable then
Lsp_helpers.showMessage_error
to_stdout
(error_data.medium_user_message ^ see_output_hack);
Lwt.return_unit
(** Like all async methods, this method has a synchronous preamble up
to its first await point, at which point it returns a promise to its
caller; the rest of the method will be scheduled asynchronously.
The synchronous preamble sends an "initialize" request to the ide_service.
The asynchronous continuation is triggered when the response comes back;
it then pumps messages to and from the ide service.
Note: the fact that the request is sent in the synchronous preamble, is
important for correctness - the rest of the codebase can send other requests
to the ide_service at any time, safe in the knowledge that such requests will
necessarily be delivered after the initialize request. *)
let run_ide_service
(env : env)
(ide_service : ClientIdeService.t)
(initialize_params : Lsp.Initialize.params)
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t option) : unit Lwt.t =
let open Lsp.Initialize in
let root =
[Lsp_helpers.get_root initialize_params]
|> Wwwroot.interpret_command_line_root_parameter
in
if
not
initialize_params.client_capabilities.workspace.didChangeWatchedFiles
.dynamicRegistration
then
log_error "client doesn't support file-watching";
let naming_table_load_info =
match
( initialize_params.initializationOptions.namingTableSavedStatePath,
env.args.naming_table )
with
| (Some _, Some _) ->
log_error
"naming table path supplied from both LSP initialization param and command line";
exit_fail ()
| (Some path, _)
| (_, Some path) ->
Some
{
ClientIdeMessage.Initialize_from_saved_state.path = Path.make path;
test_delay =
initialize_params.initializationOptions
.namingTableSavedStateTestDelay;
}
| (None, None) -> None
in
let open_files =
editor_open_files
|> Option.value ~default:UriMap.empty
|> UriMap.keys
|> List.map ~f:(fun uri -> uri |> lsp_uri_to_path |> Path.make)
in
log_debug "initialize_from_saved_state";
let%lwt result =
ClientIdeService.initialize_from_saved_state
ide_service
~root
~naming_table_load_info
~config:env.args.config
~ignore_hh_version:env.args.ignore_hh_version
~open_files
in
log_debug "initialize_from_saved_state.done";
match result with
| Ok () ->
let%lwt () = ClientIdeService.serve ide_service in
Lwt.return_unit
| Error error_data ->
let%lwt () = announce_ide_failure error_data in
Lwt.return_unit
let stop_ide_service
(ide_service : ClientIdeService.t)
~(tracking_id : string)
~(stop_reason : ClientIdeService.Stop_reason.t) : unit Lwt.t =
log
"Stopping IDE service process: %s"
(ClientIdeService.Stop_reason.to_log_string stop_reason);
let%lwt () =
ClientIdeService.stop ide_service ~tracking_id ~stop_reason ~e:None
in
Lwt.return_unit
(** This function looks at three sources of information (1) hh_server progress.json file,
(2) whether we're currently tailing an errors.bin file or whether we failed to open one,
(3) status of clientIdeDaemon. It synthesizes a status message suitable for display
in the VSCode status bar. *)
let merge_statuses_standalone
(server : ServerProgress.t)
(errors : errors_conn)
(ide : ClientIdeService.t) : Lsp.ShowStatusFB.params =
let ( (client_ide_disposition, client_ide_is_initializing),
client_ide_message,
client_ide_tooltip ) =
match ClientIdeService.get_status ide with
| ClientIdeService.Status.Initializing ->
( (ServerProgress.DWorking, true),
"Hack: initializing",
"Hack IDE support is initializing (loading saved state)" )
| ClientIdeService.Status.Processing_files p ->
( (ServerProgress.DWorking, false),
"Hack: indexing",
Printf.sprintf
"Hack IDE support is indexing %d files"
p.ClientIdeMessage.Processing_files.total )
| ClientIdeService.Status.Rpc _ ->
( (ServerProgress.DWorking, false),
"Hack",
"Hack is working on IDE requests" )
| ClientIdeService.Status.Ready ->
((ServerProgress.DReady, false), "Hack", "Hack IDE support is ready")
| ClientIdeService.Status.Stopped s ->
( (ServerProgress.DStopped, false),
"Hack: " ^ s.ClientIdeMessage.short_user_message,
s.ClientIdeMessage.medium_user_message ^ see_output_hack )
in
let (hh_server_disposition, hh_server_message, hh_server_tooltip) =
let open ServerProgress in
match (server, errors) with
| ({ disposition = DStopped; message; _ }, _) ->
( DStopped,
"Hack: hh_server " ^ message,
Printf.sprintf "hh_server is %s. %s" message fix_by_running_hh )
| ( _,
SeekingErrors
{ seek_reason = (ServerProgress.Build_id_mismatch, log_message); _ }
) ->
( DStopped,
"Hack: hh_server wrong version",
Printf.sprintf
"hh_server is the wrong version [%s]. %s"
log_message
fix_by_running_hh )
| ({ disposition = DWorking; message; _ }, _) ->
( DWorking,
(* following is little hack because "Hack: typechecking 1234/5678" is too big to fit
in the VSCode status bar. So we shorten this special case. *)
(if String.is_substring message ~substring:"typechecking" then
message
else
"Hack: " ^ message),
Printf.sprintf "hh_server is busy [%s]" message )
| ( { disposition = DReady; _ },
SeekingErrors
{
seek_reason = (ServerProgress.(NothingYet | Killed _), log_message);
_;
} ) ->
( DStopped,
"Hack: hh_server stopped",
Printf.sprintf
"hh_server is stopped. [%s]. %s"
log_message
fix_by_running_hh )
| ( { disposition = DReady; _ },
SeekingErrors { seek_reason = (e, log_message); _ } )
when not (ServerProgress.is_complete e) ->
let e = ServerProgress.show_errors_file_error e in
( DStopped,
"Hack: hh_server " ^ e,
Printf.sprintf
"hh_server error %s [%s]. %s"
e
log_message
fix_by_running_hh )
| ({ disposition = DReady; _ }, TailingErrors _) ->
(DWorking, "Hack: typechecking", "hh_server is busy [typechecking].")
| ({ disposition = DReady; _ }, _) -> (DReady, "Hack", "hh_server is ready")
in
let (disposition, message) =
match
(client_ide_disposition, client_ide_is_initializing, hh_server_disposition)
with
| (ServerProgress.DWorking, true, _) ->
(ServerProgress.DWorking, client_ide_message)
| (_, _, ServerProgress.DWorking) ->
(ServerProgress.DWorking, hh_server_message)
| (ServerProgress.DWorking, false, ServerProgress.DStopped) ->
(ServerProgress.DWorking, hh_server_message)
| (ServerProgress.DWorking, false, _) ->
(ServerProgress.DWorking, client_ide_message)
| (ServerProgress.DStopped, _, _) ->
(ServerProgress.DStopped, client_ide_message)
| (_, _, ServerProgress.DStopped) ->
(ServerProgress.DStopped, hh_server_message)
| (ServerProgress.DReady, _, ServerProgress.DReady) ->
(ServerProgress.DReady, "Hack")
in
let root_tooltip =
if Sys_utils.deterministic_behavior_for_tests () then
"<ROOT>"
else
get_root_exn () |> Path.to_string
in
let tooltip =
Printf.sprintf
"%s\n\n%s\n\n%s"
root_tooltip
client_ide_tooltip
hh_server_tooltip
in
let type_ =
match disposition with
| ServerProgress.DStopped -> MessageType.ErrorMessage
| ServerProgress.DWorking -> MessageType.WarningMessage
| ServerProgress.DReady -> MessageType.InfoMessage
in
{
ShowStatusFB.shortMessage = Some message;
request = { ShowStatusFB.type_; message = tooltip };
progress = None;
total = None;
telemetry = None;
}
let refresh_status ~(ide_service : ClientIdeService.t ref) : unit =
match !latest_hh_server_progress with
| Some latest_hh_server_progress ->
let status =
merge_statuses_standalone
latest_hh_server_progress
!latest_hh_server_errors
!ide_service
in
request_showStatusFB status
| None ->
(* [latest_hh_server_progress] gets set in [background_status_refresher]. The only way it might
be None is if root hasn't yet been set, in which case declining to refresh status is
the right thing to do. *)
()
(** This kicks off a permanent process which, once a second, reads progress.json
and calls [refresh_status]. Because it's an Lwt process, it's able to update
status even when we're stuck waiting for RPC. *)
let background_status_refresher (ide_service : ClientIdeService.t ref) : unit =
let rec loop () =
(* Currently clientLsp does not know root until after the Initialize request.
That's a bit of a pain and should be changed to assume current-working-directory.
The "initialize" handler both sets root and calls ServerProgress.set_root,
and we use the former as a proxy for the latter... *)
if Option.is_some (get_root_opt ()) then
latest_hh_server_progress := Some (ServerProgress.read ());
refresh_status ~ide_service;
let%lwt () = Lwt_unix.sleep 1.0 in
loop ()
in
let _future = loop () in
()
(** A thin wrapper around ClientIdeMessage which turns errors into exceptions *)
let ide_rpc
(ide_service : ClientIdeService.t ref)
~(env : env)
~(tracking_id : string)
~(ref_unblocked_time : float ref)
(message : 'a ClientIdeMessage.t) : 'a Lwt.t =
let (_ : env) = env in
let%lwt result =
ClientIdeService.rpc
!ide_service
~tracking_id
~ref_unblocked_time
~progress:(fun () -> refresh_status ~ide_service)
message
in
match result with
| Ok result -> Lwt.return result
| Error error_data -> raise (Daemon_nonfatal_exception error_data)
(** This sets up a background watcher which polls the file for size changes due
to it being appended to; each sie change, it writes to a stream everything that
has been appended since last append. The background watcher will terminate
and the stream be closed once the file has been unlinked. *)
let watch_refs_stream_file
(file : Path.t)
~(open_file_results : (string * Pos.absolute) list Lsp.UriMap.t) :
FindRefsWireFormat.half_open_one_based list Lwt_stream.t =
let (q, add) = Lwt_stream.create () in
let fd = Unix.openfile (Path.to_string file) [Unix.O_RDONLY] 0o666 in
let rec watch file_pos =
match (Unix.fstat fd).Unix.st_size with
| size when file_pos = size && Path.file_exists file ->
let%lwt () = Lwt_unix.sleep 0.2 in
watch file_pos
| size when file_pos = size ->
add None;
Lwt.return_unit
| _ ->
let (results, file_pos) =
FindRefsWireFormat.Ide_stream.read fd ~pos:file_pos
in
let results =
List.filter results ~f:(fun { FindRefsWireFormat.filename; _ } ->
let uri = path_to_lsp_uri filename ~default_path:filename in
not (UriMap.mem uri open_file_results))
in
if List.length results > 0 then add (Some results);
watch file_pos
in
let (_watcher_future : unit Lwt.t) = watch 0 in
q
(** Historical quirk: we log kind and method-name a bit idiosyncratically... *)
let get_message_kind_and_method_for_logging (message : lsp_message) :
string * string =
match message with
| ResponseMessage (_id, result) ->
("Response", Lsp.lsp_result_to_log_string result)
| RequestMessage (_id, r) -> ("Request", Lsp_fmt.request_name_to_string r)
| NotificationMessage n ->
("Notification", Lsp_fmt.notification_name_to_string n)
let get_filename_in_message_for_logging (message : lsp_message) :
Relative_path.t option =
let uri_opt = Lsp_fmt.get_uri_opt message in
match uri_opt with
| None -> None
| Some uri ->
(try
let path = Lsp_helpers.lsp_uri_to_path uri in
Some (Relative_path.create_detect_prefix path)
with
| _ ->
Some (Relative_path.create Relative_path.Dummy (Lsp.string_of_uri uri)))
let log_response_if_necessary
(event : event)
(result_telemetry_opt : result_telemetry option)
(unblocked_time : float) : unit =
let (result_count, result_extra_telemetry, log_immediately) =
match result_telemetry_opt with
| None -> (None, None, true)
| Some { result_count; result_extra_data; log_immediately } ->
(Some result_count, result_extra_data, log_immediately)
in
let to_log =
match event with
| _ when not log_immediately -> None
| Client_message (metadata, message) ->
Some (metadata, unblocked_time, message)
| Shell_out_complete (_result, triggering_request, _shellable_type) ->
let { Lost_env.id; metadata; start_time_local_handle; request } =
triggering_request
in
Some (metadata, start_time_local_handle, RequestMessage (id, request))
| Tick
| Daemon_notification _
| Errors_file _
| Refs_file _ ->
None
in
match to_log with
| None -> ()
| Some ({ timestamp; tracking_id }, start_handle_time, message) ->
let (kind, method_) = get_message_kind_and_method_for_logging message in
HackEventLogger.client_lsp_method_handled
~root:(get_root_opt ())
~method_
~kind
~path_opt:(get_filename_in_message_for_logging message)
~result_count
~result_extra_telemetry
~tracking_id
~start_queue_time:timestamp
~start_hh_server_state:""
~start_handle_time
~serverless_ide_flag:"Ide_standalone"
type error_source =
| Error_from_client_fatal
| Error_from_client_recoverable
| Error_from_daemon_recoverable
| Error_from_lsp_cancelled
| Error_from_lsp_misc
let hack_log_error
(event : event option)
(e : Lsp.Error.t)
(source : error_source)
(unblocked_time : float) : unit =
let root = get_root_opt () in
let is_expected =
match source with
| Error_from_lsp_cancelled -> true
| Error_from_client_fatal
| Error_from_client_recoverable
| Error_from_daemon_recoverable
| Error_from_lsp_misc ->
false
in
let source =
match source with
| Error_from_client_fatal -> "client_fatal"
| Error_from_client_recoverable -> "client_recoverable"
| Error_from_daemon_recoverable -> "daemon_recoverable"
| Error_from_lsp_cancelled -> "lsp_cancelled"
| Error_from_lsp_misc -> "lsp_misc"
in
if not is_expected then log "%s" (Lsp_fmt.error_to_log_string e);
match event with
| Some (Client_message (metadata, message)) ->
let (kind, method_) = get_message_kind_and_method_for_logging message in
HackEventLogger.client_lsp_method_exception
~root
~method_
~kind
~path_opt:(get_filename_in_message_for_logging message)
~tracking_id:metadata.tracking_id
~start_queue_time:metadata.timestamp
~start_hh_server_state:""
~start_handle_time:unblocked_time
~message:e.Error.message
~data_opt:e.Error.data
~source
| _ ->
HackEventLogger.client_lsp_exception
~root
~message:e.Error.message
~data_opt:e.Error.data
~source
let kickoff_shell_out_and_maybe_cancel
(state : state)
(shellable_type : Lost_env.shellable_type)
~(triggering_request : Lost_env.triggering_request) :
(state * result_telemetry) Lwt.t =
let%lwt () = terminate_if_version_changed_since_start_of_lsp () in
let compose_shellout_cmd ~(from : string) (args : string list) : string array
=
args
@ [
"--from";
Printf.sprintf "clientLsp:%s" from;
"--json";
"--autostart-server";
"false";
get_root_exn () |> Path.to_string;
]
|> Array.of_list
in
match state with
| Lost_server ({ Lost_env.current_hh_shell; _ } as lenv) ->
(* Cancel any existing shell-out, if there is one. *)
Option.iter
current_hh_shell
~f:(fun
{
Lost_env.cancellation_token;
triggering_request =
{
Lost_env.id = prev_id;
metadata = prev_metadata;
request = prev_request;
start_time_local_handle = prev_start_time_local_handle;
};
_;
}
->
(* Send SIGTERM to the underlying process.
We won't wait for it -- that'd make it too hard to reason about concurrency. *)
Lwt.wakeup_later cancellation_token ();
(* We still have to respond to the LSP's prev request. We'll do so now
without waiting for the underlying process to finish. In this way we fulfill
the invariant that "current_hh_shell must always give rise to an LSP response".
(Later in the function we overwrite current_hh_shell with the new shellout, so right here
right now is the only place that can fulfill that invariant for the prev shellout). *)
let message =
Printf.sprintf
"Cancelled (displaced by another request #%s)"
(Lsp_fmt.id_to_string triggering_request.Lost_env.id)
in
let lsp_error =
make_lsp_error ~code:Lsp.Error.RequestCancelled message
in
respond_jsonrpc
~powered_by:Language_server
prev_id
(ErrorResult lsp_error);
hack_log_error
(Some
(Client_message
(prev_metadata, RequestMessage (prev_id, prev_request))))
lsp_error
Error_from_daemon_recoverable
prev_start_time_local_handle;
());
let (cancel, cancellation_token) = Lwt.wait () in
let cmd =
begin
let open Lost_env in
match shellable_type with
| FindRefs
{
symbol;
find_refs_action;
hint_suffixes;
stream_file;
ide_calculated_positions = _;
} ->
let (action, stream_file, hints) =
FindRefsWireFormat.CliArgs.to_string_triple
{
FindRefsWireFormat.CliArgs.symbol_name = symbol;
action = find_refs_action;
stream_file =
Option.map stream_file ~f:(fun sf -> sf.Lost_env.file);
hint_suffixes;
}
in
let cmd =
compose_shellout_cmd
~from:"find-refs-by-symbol"
["--ide-find-refs-by-symbol3"; action; stream_file; hints]
in
cmd
| GoToImpl { symbol; find_refs_action; _ } ->
let symbol_action_arg =
FindRefsWireFormat.CliArgs.to_string
{
FindRefsWireFormat.CliArgs.symbol_name = symbol;
action = find_refs_action;
stream_file = None;
hint_suffixes = [];
}
in
let cmd =
compose_shellout_cmd
~from:"go-to-impl-by-symbol"
["--ide-go-to-impl-by-symbol"; symbol_action_arg]
in
cmd
| Rename { symbol_definition; find_refs_action; new_name; _ } ->
let name_action_definition_string =
ServerCommandTypes.Rename.arguments_to_string_exn
new_name
find_refs_action
symbol_definition
in
let cmd =
compose_shellout_cmd
~from:"rename"
["--ide-rename-by-symbol"; name_action_definition_string]
in
cmd
end
in
(* Two environment variables FIND_HH_START_TIME and FIND_HH_RETRIED are
used in HackEventLogger.ml for telemetry, expected to be set by the
caller find_hh.sh, but [Exec_command.Current_executable] bypasses
find_hh.sh and hence we need to override them ourselves. There's no
need for removing existing definitions from [Unix.environment ()]
because glibc putenv/getenv will grab the first one. *)
let env =
Array.append
[|
Printf.sprintf "FIND_HH_START_TIME=%0.3f" (Unix.gettimeofday ());
"FIND_HH_RETRIED=0";
|]
(Unix.environment ())
in
let process =
Lwt_utils.exec_checked Exec_command.Current_executable cmd ~cancel ~env
in
log "kickoff_shell_out: %s" (String.concat ~sep:" " (Array.to_list cmd));
let state =
Lost_server
{
lenv with
Lost_env.current_hh_shell =
Some
{
Lost_env.process;
cancellation_token;
shellable_type;
triggering_request;
};
}
in
let result_telemetry = make_result_telemetry 0 ~log_immediately:false in
Lwt.return (state, result_telemetry)
| _ ->
HackEventLogger.invariant_violation_bug "kickoff when not in Lost_env";
Lwt.return (state, make_result_telemetry 0)
(** If there's a current_hh_shell with [id], then send it a SIGTERM.
All we're doing is triggering the cancellation; we rely upon normal
[handle_shell_out_complete] for once the process has terminated. *)
let cancel_shellout_if_applicable (state : state) (id : lsp_id) : unit =
match state with
| Lost_server
{
Lost_env.current_hh_shell =
Some
{
Lost_env.cancellation_token;
triggering_request = { Lost_env.id = peek_id; _ };
_;
};
_;
}
when Lsp.IdKey.compare id peek_id = 0 ->
Lwt.wakeup_later cancellation_token ()
| _ -> ()
(************************************************************************)
(* Protocol *)
(************************************************************************)
let do_shutdown
(state : state)
(ide_service : ClientIdeService.t ref)
(tracking_id : string) : state Lwt.t =
log "Received shutdown request";
let _state = dismiss_diagnostics state in
let%lwt () =
stop_ide_service
!ide_service
~tracking_id
~stop_reason:ClientIdeService.Stop_reason.Editor_exited
in
Lwt.return Post_shutdown
let state_to_rage (state : state) : string =
let uris_to_string uris =
List.map uris ~f:(fun (DocumentUri uri) -> uri) |> String.concat ~sep:","
in
let timestamped_uris_to_string uris =
List.map uris ~f:(fun (DocumentUri uri, (timestamp, errors_from)) ->
Printf.sprintf
"%s [%s] @ %0.2f"
(show_errors_from errors_from)
uri
timestamp)
|> String.concat ~sep:","
in
let details =
match state with
| Pre_init -> ""
| Post_shutdown -> ""
| Lost_server lenv ->
let open Lost_env in
Printf.sprintf
("editor_open_files: %s\n"
^^ "uris_with_unsaved_changes: %s\n"
^^ "urs_with_standalone_diagnostics: %s\n")
(lenv.editor_open_files |> UriMap.keys |> uris_to_string)
(lenv.uris_with_unsaved_changes |> UriSet.elements |> uris_to_string)
(lenv.uris_with_standalone_diagnostics
|> UriMap.elements
|> timestamped_uris_to_string)
in
Printf.sprintf "clientLsp state: %s\n%s\n" (state_to_string state) details
let do_rageFB (state : state) : RageFB.result Lwt.t =
let%lwt current_version_and_switch = read_hhconfig_version_and_switch () in
let data =
Printf.sprintf
("%s\n\n"
^^ "version previously read from .hhconfig and switch: %s\n"
^^ "version in .hhconfig and switch: %s\n\n")
(state_to_rage state)
!hhconfig_version_and_switch
current_version_and_switch
in
Lwt.return [{ RageFB.title = None; data }]
let do_hover_common (infos : HoverService.hover_info list) : Hover.result =
let contents =
infos
|> List.map ~f:(fun hoverInfo ->
(* Hack server uses None to indicate absence of a result. *)
(* We're also catching the non-result "" just in case... *)
match hoverInfo with
| { HoverService.snippet = ""; _ } -> []
| { HoverService.snippet; addendum; _ } ->
MarkedCode ("hack", snippet)
:: List.map ~f:(fun s -> MarkedString s) addendum)
|> List.concat
in
(* We pull the position from the SymbolOccurrence.t record, so I would be
surprised if there were any different ones in here. Just take the first
non-None one. *)
let range =
infos
|> List.filter_map ~f:(fun { HoverService.pos; _ } -> pos)
|> List.hd
|> Option.map
~f:(Lsp_helpers.hack_pos_to_lsp_range ~equal:Relative_path.equal)
in
if List.is_empty contents then
None
else
Some { Hover.contents; range }
let do_hover_local
(ide_service : ClientIdeService.t ref)
(env : env)
(tracking_id : string)
(ref_unblocked_time : float ref)
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : Hover.params) : Hover.result Lwt.t =
let (document, location) = get_document_location editor_open_files params in
let%lwt infos =
ide_rpc
ide_service
~env
~tracking_id
~ref_unblocked_time
(ClientIdeMessage.Hover (document, location))
in
Lwt.return (do_hover_common infos)
let do_typeDefinition_local
(ide_service : ClientIdeService.t ref)
(env : env)
(tracking_id : string)
(ref_unblocked_time : float ref)
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : Definition.params) : TypeDefinition.result Lwt.t =
let (document, location) = get_document_location editor_open_files params in
let%lwt results =
ide_rpc
ide_service
~env
~tracking_id
~ref_unblocked_time
(ClientIdeMessage.Type_definition (document, location))
in
let file = Path.to_string document.ClientIdeMessage.file_path in
let results =
List.map results ~f:(fun nast_sid ->
hack_pos_definition_to_lsp_identifier_location
nast_sid
~default_path:file)
in
Lwt.return results
let do_definition_local
(ide_service : ClientIdeService.t ref)
(env : env)
(tracking_id : string)
(ref_unblocked_time : float ref)
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : Definition.params) : (Definition.result * bool) Lwt.t =
let (document, location) = get_document_location editor_open_files params in
let%lwt results =
ide_rpc
ide_service
~env
~tracking_id
~ref_unblocked_time
(ClientIdeMessage.Definition (document, location))
in
let locations =
List.map results ~f:(fun (_, definition) ->
hack_symbol_definition_to_lsp_identifier_location
definition
~default_path:(document.ClientIdeMessage.file_path |> Path.to_string))
in
let has_xhp_attribute =
List.exists results ~f:(fun (occurence, _) ->
SymbolOccurrence.is_xhp_literal_attr occurence)
in
Lwt.return (locations, has_xhp_attribute)
let make_ide_completion_response
(result : AutocompleteTypes.ide_result) (filename : string) :
Completion.completionList Lwt.t =
let open AutocompleteTypes in
let open Completion in
let p = initialize_params_exc () in
let hack_to_insert (completion : autocomplete_item) :
TextEdit.t * Completion.insertTextFormat * TextEdit.t list =
let additional_edits =
List.map completion.res_additional_edits ~f:(fun (text, range) ->
TextEdit.{ range = ide_range_to_lsp range; newText = text })
in
let range = ide_range_to_lsp completion.res_replace_pos in
match completion.res_insert_text with
| InsertAsSnippet { snippet; fallback } ->
if Lsp_helpers.supports_snippets p then
(TextEdit.{ range; newText = snippet }, SnippetFormat, additional_edits)
else
(TextEdit.{ range; newText = fallback }, PlainText, additional_edits)
| InsertLiterally text ->
(TextEdit.{ range; newText = text }, PlainText, additional_edits)
in
let hack_completion_to_lsp (completion : autocomplete_item) :
Completion.completionItem =
let (textEdit, insertTextFormat, additionalTextEdits) =
hack_to_insert completion
in
let pos =
if String.equal (Pos.filename completion.res_decl_pos) "" then
Pos.set_file filename completion.res_decl_pos
else
completion.res_decl_pos
in
let data =
let (line, start, _) = Pos.info_pos pos in
let filename = Pos.filename pos in
let base_class =
match completion.res_base_class with
| Some base_class -> [("base_class", Hh_json.JSON_String base_class)]
| None -> []
in
(* If we do not have a correct file position, skip sending that data *)
if Int.equal line 0 && Int.equal start 0 then
Some
(Hh_json.JSON_Object
([("fullname", Hh_json.JSON_String completion.res_fullname)]
@ base_class))
else
Some
(Hh_json.JSON_Object
([
(* Fullname is needed for namespaces. We often trim namespaces to make
* the results more readable, such as showing "ad__breaks" instead of
* "Thrift\Packages\cf\ad__breaks".
*)
("fullname", Hh_json.JSON_String completion.res_fullname);
(* Filename/line/char/base_class are used to handle class methods.
* We could unify this with fullname in the future.
*)
("filename", Hh_json.JSON_String filename);
("line", Hh_json.int_ line);
("char", Hh_json.int_ start);
]
@ base_class))
in
let hack_to_sort_text (completion : autocomplete_item) : string option =
let label = completion.res_label in
let should_downrank label =
String.length label > 2
&& String.equal (Str.string_before label 2) "__"
|| Str.string_match (Str.regexp_case_fold ".*do_not_use.*") label 0
in
let downranked_result_prefix_character = "~" in
if should_downrank label then
Some (downranked_result_prefix_character ^ label)
else
Some label
in
{
label = completion.res_label;
kind = si_kind_to_completion_kind completion.AutocompleteTypes.res_kind;
detail = Some completion.res_detail;
documentation =
Option.map completion.res_documentation ~f:(fun s ->
MarkedStringsDocumentation [MarkedString s]);
(* This will be filled in by completionItem/resolve. *)
sortText = hack_to_sort_text completion;
filterText = completion.res_filter_text;
insertText = None;
insertTextFormat = Some insertTextFormat;
textEdit = Some textEdit;
additionalTextEdits;
command = None;
data;
}
in
Lwt.return
{
isIncomplete = not result.is_complete;
items = List.map result.completions ~f:hack_completion_to_lsp;
}
let do_completion_local
(ide_service : ClientIdeService.t ref)
(env : env)
(tracking_id : string)
(ref_unblocked_time : float ref)
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : Completion.params) : Completion.result Lwt.t =
let open Completion in
let (document, location) =
get_document_location editor_open_files params.loc
in
(* Other parameters *)
let is_manually_invoked =
match params.context with
| None -> false
| Some c -> is_invoked c.triggerKind
in
(* this is what I want to fix *)
let request =
ClientIdeMessage.Completion
(document, location, { ClientIdeMessage.is_manually_invoked })
in
let%lwt infos =
ide_rpc ide_service ~env ~tracking_id ~ref_unblocked_time request
in
let filename = document.ClientIdeMessage.file_path |> Path.to_string in
let%lwt response = make_ide_completion_response infos filename in
Lwt.return response
exception NoLocationFound
let docblock_to_markdown (raw_docblock : DocblockService.result) :
Completion.completionDocumentation option =
match raw_docblock with
| [] -> None
| docblock ->
Some
(Completion.MarkedStringsDocumentation
(Core.List.fold docblock ~init:[] ~f:(fun acc elt ->
match elt with
| DocblockService.Markdown txt -> MarkedString txt :: acc
| DocblockService.HackSnippet txt ->
MarkedCode ("hack", txt) :: acc
| DocblockService.XhpSnippet txt ->
MarkedCode ("html", txt) :: acc)))
let docblock_with_ranking_detail
(raw_docblock : DocblockService.result) (ranking_detail : string option) :
DocblockService.result =
match ranking_detail with
| Some detail -> raw_docblock @ [DocblockService.Markdown detail]
| None -> raw_docblock
let resolve_ranking_source
(kind : SearchTypes.si_kind) (ranking_source : int option) :
SearchTypes.si_kind =
match ranking_source with
| Some x -> SearchTypes.int_to_kind x
| None -> kind
(*
* Note that resolve does not depend on having previously executed completion in
* the same process. The LSP resolve request takes, as input, a single item
* produced by any previously executed completion request. So it's okay for
* one process to respond to another, because they'll both know the answers
* to the same symbol requests.
*
* And it's totally okay to mix and match requests to serverless IDE and
* hh_server.
*)
let do_resolve_local
(ide_service : ClientIdeService.t ref)
(env : env)
(tracking_id : string)
(ref_unblocked_time : float ref)
(params : CompletionItemResolve.params) : CompletionItemResolve.result Lwt.t
=
if Option.is_some params.Completion.documentation then
Lwt.return params
else
let raw_kind = params.Completion.kind in
let kind = completion_kind_to_si_kind raw_kind in
(* Some docblocks are for class methods. Class methods need to know
* file/line/column/base_class to find the docblock. *)
let%lwt result =
try
match params.Completion.data with
| None -> raise NoLocationFound
| Some _ as data ->
let filename = Jget.string_exn data "filename" in
let file_path = Path.make filename in
let line = Jget.int_exn data "line" in
let column = Jget.int_exn data "char" in
let ranking_detail = Jget.string_opt data "ranking_detail" in
let ranking_source = Jget.int_opt data "ranking_source" in
if line = 0 && column = 0 then failwith "NoFileLineColumnData";
let request =
ClientIdeMessage.Completion_resolve_location
( file_path,
{ ClientIdeMessage.line; column },
resolve_ranking_source kind ranking_source )
in
let%lwt raw_docblock =
ide_rpc ide_service ~env ~tracking_id ~ref_unblocked_time request
in
let documentation =
docblock_with_ranking_detail raw_docblock ranking_detail
|> docblock_to_markdown
in
Lwt.return { params with Completion.documentation }
(* If that fails, next try using symbol *)
with
| _ ->
(* The "fullname" value includes the fully qualified namespace, so
* we want to use that. However, if it's missing (it shouldn't be)
* let's default to using the label which doesn't include the
* namespace. *)
let symbolname =
try Jget.string_exn params.Completion.data "fullname" with
| _ -> params.Completion.label
in
let ranking_source =
try Jget.int_opt params.Completion.data "ranking_source" with
| _ -> None
in
let request =
ClientIdeMessage.Completion_resolve
(symbolname, resolve_ranking_source kind ranking_source)
in
let%lwt raw_docblock =
ide_rpc ide_service ~env ~tracking_id ~ref_unblocked_time request
in
let documentation = docblock_to_markdown raw_docblock in
Lwt.return { params with Completion.documentation }
in
Lwt.return result
let hack_symbol_to_lsp (symbol : SearchUtils.symbol) =
(* Hack sometimes gives us back items with an empty path, by which it
intends "whichever path you asked me about". That would be meaningless
here. If it does, then it'll pick up our default path (also empty),
which will throw and go into our telemetry. That's the best we can do. *)
let hack_to_lsp_kind = function
| SearchTypes.SI_Class -> SymbolInformation.Class
| SearchTypes.SI_Interface -> SymbolInformation.Interface
| SearchTypes.SI_Trait -> SymbolInformation.Interface
(* LSP doesn't have traits, so we approximate with interface *)
| SearchTypes.SI_Enum -> SymbolInformation.Enum
(* TODO(T36697624): Add SymbolInformation.Record *)
| SearchTypes.SI_ClassMethod -> SymbolInformation.Method
| SearchTypes.SI_Function -> SymbolInformation.Function
| SearchTypes.SI_Typedef -> SymbolInformation.Class
(* LSP doesn't have typedef, so we approximate with class *)
| SearchTypes.SI_GlobalConstant -> SymbolInformation.Constant
| SearchTypes.SI_Namespace -> SymbolInformation.Namespace
| SearchTypes.SI_Mixed -> SymbolInformation.Variable
| SearchTypes.SI_XHP -> SymbolInformation.Class
| SearchTypes.SI_Literal -> SymbolInformation.Variable
| SearchTypes.SI_ClassConstant -> SymbolInformation.Constant
| SearchTypes.SI_Property -> SymbolInformation.Property
| SearchTypes.SI_LocalVariable -> SymbolInformation.Variable
| SearchTypes.SI_Constructor -> SymbolInformation.Constructor
(* Do these happen in practice? *)
| SearchTypes.SI_Keyword
| SearchTypes.SI_Unknown ->
failwith "Unknown symbol kind"
in
{
SymbolInformation.name = Utils.strip_ns symbol.SearchUtils.name;
kind = hack_to_lsp_kind symbol.SearchUtils.result_type;
location = hack_pos_to_lsp_location symbol.SearchUtils.pos ~default_path:"";
containerName = None;
}
let do_workspaceSymbol_local
(ide_service : ClientIdeService.t ref)
(env : env)
(tracking_id : string)
(ref_unblocked_time : float ref)
(params : WorkspaceSymbol.params) : WorkspaceSymbol.result Lwt.t =
let query = params.WorkspaceSymbol.query in
let request = ClientIdeMessage.Workspace_symbol query in
let%lwt results =
ide_rpc ide_service ~env ~tracking_id ~ref_unblocked_time request
in
Lwt.return (List.map results ~f:hack_symbol_to_lsp)
let rec hack_symbol_tree_to_lsp
~(filename : string)
~(accu : Lsp.SymbolInformation.t list)
~(container_name : string option)
(defs : FileOutline.outline) : Lsp.SymbolInformation.t list =
let open SymbolDefinition in
let hack_to_lsp_kind = function
| SymbolDefinition.Function -> SymbolInformation.Function
| SymbolDefinition.Class -> SymbolInformation.Class
| SymbolDefinition.Method -> SymbolInformation.Method
| SymbolDefinition.Property -> SymbolInformation.Property
| SymbolDefinition.ClassConst -> SymbolInformation.Constant
| SymbolDefinition.GlobalConst -> SymbolInformation.Constant
| SymbolDefinition.Enum -> SymbolInformation.Enum
| SymbolDefinition.Interface -> SymbolInformation.Interface
| SymbolDefinition.Trait -> SymbolInformation.Interface
(* LSP doesn't have traits, so we approximate with interface *)
| SymbolDefinition.LocalVar -> SymbolInformation.Variable
| SymbolDefinition.TypeVar -> SymbolInformation.TypeParameter
| SymbolDefinition.Typeconst -> SymbolInformation.Class
(* e.g. "const type Ta = string;" -- absent from LSP *)
| SymbolDefinition.Typedef -> SymbolInformation.Class
(* e.g. top level type alias -- absent from LSP *)
| SymbolDefinition.Param -> SymbolInformation.Variable
(* We never return a param from a document-symbol-search *)
| SymbolDefinition.Module -> SymbolInformation.Module
in
let hack_symbol_to_lsp definition containerName =
{
SymbolInformation.name = definition.name;
kind = hack_to_lsp_kind definition.kind;
location =
hack_symbol_definition_to_lsp_construct_location
definition
~default_path:filename;
containerName;
}
in
match defs with
(* Flattens the recursive list of symbols *)
| [] -> List.rev accu
| def :: defs ->
let children = Option.value def.children ~default:[] in
let accu = hack_symbol_to_lsp def container_name :: accu in
let accu =
hack_symbol_tree_to_lsp
~filename
~accu
~container_name:(Some def.name)
children
in
hack_symbol_tree_to_lsp ~filename ~accu ~container_name defs
let do_documentSymbol_local
(ide_service : ClientIdeService.t ref)
(env : env)
(tracking_id : string)
(ref_unblocked_time : float ref)
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : DocumentSymbol.params) : DocumentSymbol.result Lwt.t =
let open DocumentSymbol in
let open TextDocumentIdentifier in
let filename = lsp_uri_to_path params.textDocument.uri in
let text_document =
get_text_document_item editor_open_files params.textDocument.uri
in
let document = lsp_document_to_ide text_document in
let request = ClientIdeMessage.Document_symbol document in
let%lwt outline =
ide_rpc ide_service ~env ~tracking_id ~ref_unblocked_time request
in
let converted =
hack_symbol_tree_to_lsp ~filename ~accu:[] ~container_name:None outline
in
Lwt.return converted
let do_findReferences_local
(state : state)
(ide_service : ClientIdeService.t ref)
(env : env)
(metadata : incoming_metadata)
(ref_unblocked_time : float ref)
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : FindReferences.params)
(id : lsp_id) : (state * result_telemetry) Lwt.t =
let start_time_local_handle = Unix.gettimeofday () in
let (document, location) =
get_document_location editor_open_files params.FindReferences.loc
in
let all_open_documents = get_documents_from_open_files editor_open_files in
let%lwt response =
ide_rpc
ide_service
~env
~tracking_id:metadata.tracking_id
~ref_unblocked_time
(ClientIdeMessage.Find_references (document, location, all_open_documents))
in
match response with
| ClientIdeMessage.Invalid_symbol ->
respond_jsonrpc ~powered_by:Serverless_ide id (FindReferencesResult []);
let result_telemetry = make_result_telemetry (-1) in
Lwt.return (state, result_telemetry)
| ClientIdeMessage.Find_refs_success
{
full_name = _;
action = None;
hint_suffixes = _;
open_file_results = ide_calculated_positions;
} ->
let positions =
match UriMap.values ide_calculated_positions with
(*
UriMap.values returns [Pos.absolute list list] and if we're here,
we should only have one element - the list of positions in the file the localvar is defined.
*)
| positions :: [] -> positions
| _ -> assert false (* Explicitly handled in ClientIdeDaemon *)
in
let filename =
Lsp_helpers.lsp_textDocumentIdentifier_to_filename
params.FindReferences.loc.TextDocumentPositionParams.textDocument
in
let positions =
List.map positions ~f:(fun (_name, pos) ->
hack_pos_to_lsp_location ~default_path:filename pos)
in
respond_jsonrpc
~powered_by:Serverless_ide
id
(FindReferencesResult positions);
let result_telemetry = make_result_telemetry (List.length positions) in
Lwt.return (state, result_telemetry)
| ClientIdeMessage.Find_refs_success
{ full_name; action = Some action; hint_suffixes; open_file_results } ->
let stream_file =
Option.map
params.FindReferences.partialResultToken
~f:(fun partial_result_token ->
let file =
Caml.Filename.temp_file
~temp_dir:(get_root_exn () |> Path.to_string)
"find_refs_stream"
".jsonl"
in
(* We want the [ide_calculated_positions] at the start of the streaming file so they
will get displayed first. *)
let fd = Unix.openfile file [Unix.O_WRONLY; Unix.O_APPEND] 0o666 in
FindRefsWireFormat.Ide_stream.append
fd
(open_file_results |> UriMap.values |> List.concat);
Unix.close fd;
let file = Path.make file in
let q = watch_refs_stream_file file ~open_file_results in
Lost_env.{ file; partial_result_token; q })
in
(* The [open_file_results] included the SymbolOccurrence text for each ref. We won't need that... *)
let ide_calculated_positions =
UriMap.map (List.map ~f:snd) open_file_results
in
let shellable_type =
Lost_env.FindRefs
{
Lost_env.symbol = full_name;
find_refs_action = action;
stream_file;
hint_suffixes;
ide_calculated_positions;
}
in
(* If we reach kickoff a shell-out to hh_server, processing that response
also invokes respond_jsonrpc *)
let%lwt (state, result_telemetry) =
kickoff_shell_out_and_maybe_cancel
state
shellable_type
~triggering_request:
{
Lost_env.id;
metadata;
start_time_local_handle;
request = FindReferencesRequest params;
}
in
Lwt.return (state, result_telemetry)
(** This is called when a shell-out to "hh --ide-find-refs-by-symbol" completes successfully *)
let do_findReferences2 ~ide_calculated_positions ~hh_locations ~stream_file :
Lsp.lsp_result * int =
(* lsp_locations return a file for each position. To support unsaved, edited files
let's discard locations for files that we previously fetched from ClientIDEDaemon.
First: filter out locations for any where the documentUri matches a relative_path
in the returned map
Second: augment above list with values in `ide_calculated_positions`
*)
let hh_locations =
List.filter
~f:(fun location ->
let uri = location.Lsp.Location.uri in
not @@ UriMap.mem uri ide_calculated_positions)
hh_locations
in
let ide_locations =
UriMap.bindings ide_calculated_positions
|> List.map ~f:(fun (lsp_uri, pos_list) ->
let filename = Lsp.string_of_uri lsp_uri in
let lsp_locations =
List.map
~f:(hack_pos_to_lsp_location ~default_path:filename)
pos_list
in
lsp_locations)
|> List.concat
in
let all_locations = List.rev_append ide_locations hh_locations in
(* LSP spec explains: "If a server reports partial result via a corresponding $/progress, the whole result
must be reported using n $/progress notifications. The final response has to be empty in terms of result values."
Thus, if we were using a streaming file and partial results, we'll give an empty response now. *)
match stream_file with
| Some { Lost_env.file; _ } ->
Unix.unlink (Path.to_string file);
(FindReferencesResult [], List.length all_locations)
| None -> (FindReferencesResult all_locations, List.length all_locations)
let do_goToImplementation_local
(state : state)
(ide_service : ClientIdeService.t ref)
(env : env)
(metadata : incoming_metadata)
(tracking_id : string)
(ref_unblocked_time : float ref)
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : Implementation.params)
(id : lsp_id) : (state * result_telemetry) Lwt.t =
let (document, location) = get_document_location editor_open_files params in
let all_open_documents = get_documents_from_open_files editor_open_files in
let%lwt response =
ide_rpc
ide_service
~env
~tracking_id
~ref_unblocked_time
(ClientIdeMessage.Go_to_implementation
(document, location, all_open_documents))
in
match response with
| ClientIdeMessage.Invalid_symbol_impl ->
respond_jsonrpc ~powered_by:Serverless_ide id (ImplementationResult []);
let result_telemetry = make_result_telemetry 0 in
Lwt.return (state, result_telemetry)
| ClientIdeMessage.Go_to_impl_success
(symbol, find_refs_action, ide_calculated_positions) ->
let open Lost_env in
let shellable_type =
GoToImpl
{
symbol;
find_refs_action;
stream_file = None;
hint_suffixes = [];
ide_calculated_positions;
}
in
let start_time_local_handle = Unix.gettimeofday () in
let%lwt (state, result_telemetry) =
kickoff_shell_out_and_maybe_cancel
state
shellable_type
~triggering_request:
{
id;
metadata;
start_time_local_handle;
request = ImplementationRequest params;
}
in
Lwt.return (state, result_telemetry)
(** This is called when a shellout to "hh --ide-go-to-impl" completes successfully *)
let do_goToImplementation2 ~ide_calculated_positions ~hh_locations :
Lsp.lsp_result * int =
(* reject all server-supplied locations for files that we calculated in ClientIdeDaemon, then join the lists *)
let filtered_list =
List.filter hh_locations ~f:(fun loc ->
not @@ UriMap.mem loc.Lsp.Location.uri ide_calculated_positions)
in
let ide_supplied_positions =
UriMap.elements ide_calculated_positions
|> List.concat_map ~f:(fun (_uri, pos_list) ->
List.map pos_list ~f:(fun pos ->
hack_pos_to_lsp_location pos ~default_path:(Pos.filename pos)))
in
let locations = filtered_list @ ide_supplied_positions in
(ImplementationResult locations, List.length locations)
(** Shared function for hack range conversion *)
let hack_range_to_lsp_highlight range =
{ DocumentHighlight.range = ide_range_to_lsp range; kind = None }
let do_highlight_local
(ide_service : ClientIdeService.t ref)
(env : env)
(tracking_id : string)
(ref_unblocked_time : float ref)
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : DocumentHighlight.params) : DocumentHighlight.result Lwt.t =
let (document, location) = get_document_location editor_open_files params in
let%lwt ranges =
ide_rpc
ide_service
~env
~tracking_id
~ref_unblocked_time
(ClientIdeMessage.Document_highlight (document, location))
in
Lwt.return (List.map ranges ~f:hack_range_to_lsp_highlight)
let do_formatting_common
(uri : Lsp.documentUri)
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(action : ServerFormatTypes.ide_action)
(options : DocumentFormatting.formattingOptions) : TextEdit.t list =
let open ServerFormatTypes in
let filename_for_logging = lsp_uri_to_path uri in
(* Following line will throw if the document isn't already open, so we'll *)
(* return an error code to the LSP client. The spec doesn't spell out if we *)
(* should be expected to handle formatting requests on unopened files. *)
let lsp_doc = UriMap.find uri editor_open_files in
let content = lsp_doc.Lsp.TextDocumentItem.text in
let response =
ServerFormat.go_ide ~filename_for_logging ~content ~action ~options
in
match response with
| Error "File failed to parse without errors" ->
(* If LSP issues a formatting request at a given line+char, but we can't *)
(* calculate a better format for the file due to syntax errors in it, *)
(* then we should return "success and there are no edits to apply" *)
(* rather than "error". *)
(* TODO: let's eliminate hh_format, and incorporate hackfmt into the *)
(* hh_client binary itself, and make make "hackfmt" just a wrapper for *)
(* "hh_client format", and then make it return proper error that we can *)
(* pattern-match upon, rather than hard-coding the string... *)
[]
| Error message ->
raise
(Error.LspException
{ Error.code = Error.UnknownErrorCode; message; data = None })
| Ok r ->
let range = ide_range_to_lsp r.range in
let newText = r.new_text in
[{ TextEdit.range; newText }]
let do_documentRangeFormatting
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : DocumentRangeFormatting.params) : DocumentRangeFormatting.result =
let open DocumentRangeFormatting in
let open TextDocumentIdentifier in
let action = ServerFormatTypes.Range (lsp_range_to_ide params.range) in
do_formatting_common
params.textDocument.uri
editor_open_files
action
params.options
let do_documentOnTypeFormatting
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : DocumentOnTypeFormatting.params) : DocumentOnTypeFormatting.result
=
let open DocumentOnTypeFormatting in
let open TextDocumentIdentifier in
(*
In LSP, positions do not point directly to characters, but to spaces in between characters.
Thus, the LSP position that the cursor points to after typing a character is the space
immediately after the character.
For example:
Character positions: 0 1 2 3 4 5 6
f o o ( ) { }
LSP positions: 0 1 2 3 4 5 6 7
The cursor is at LSP position 7 after typing the "}" of "foo(){}"
But the character position of "}" is 6.
Nuclide currently sends positions according to LSP, but everything else in the server
and in hack formatting assumes that positions point directly to characters.
Thus, to send the position of the character itself for formatting,
we must subtract one.
*)
let position =
{ params.position with character = params.position.character - 1 }
in
let action = ServerFormatTypes.Position (lsp_position_to_ide position) in
do_formatting_common
params.textDocument.uri
editor_open_files
action
params.options
let do_documentFormatting
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : DocumentFormatting.params) : DocumentFormatting.result =
let open DocumentFormatting in
let open TextDocumentIdentifier in
let action = ServerFormatTypes.Document in
do_formatting_common
params.textDocument.uri
editor_open_files
action
params.options
let do_willSaveWaitUntil
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : WillSaveWaitUntil.params) : WillSaveWaitUntil.result =
let { WillSaveWaitUntil.textDocument; reason } = params in
let is_autosave =
match reason with
| AfterDelay -> true
| Manual
| FocusOut ->
false
in
let uri = textDocument.TextDocumentIdentifier.uri in
let lsp_doc = UriMap.find uri editor_open_files in
let content = lsp_doc.Lsp.TextDocumentItem.text in
if (not is_autosave) && Formatting.is_formattable content then
let open DocumentFormatting in
do_documentFormatting
editor_open_files
{
textDocument = params.WillSaveWaitUntil.textDocument;
options = { tabSize = 2; insertSpaces = true };
}
else
[]
let should_use_snippet_edits (initialize_params : Initialize.params option) :
bool =
initialize_params
|> Option.map
~f:
Initialize.(
fun { client_capabilities = caps; _ } ->
caps.client_experimental
.ClientExperimentalCapabilities.snippetTextEdit)
|> Option.value ~default:false
let do_codeAction_local
(ide_service : ClientIdeService.t ref)
(env : env)
(tracking_id : string)
(ref_unblocked_time : float ref)
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : CodeActionRequest.params) :
(CodeAction.command_or_action list
* Path.t
* Errors.finalized_error list option)
Lwt.t =
let text_document =
get_text_document_item
editor_open_files
params.CodeActionRequest.textDocument.TextDocumentIdentifier.uri
in
let document = lsp_document_to_ide text_document in
let file_path = document.ClientIdeMessage.file_path in
let range = lsp_range_to_ide params.CodeActionRequest.range in
let%lwt (actions, errors_opt) =
ide_rpc
ide_service
~env
~tracking_id
~ref_unblocked_time
(ClientIdeMessage.Code_action (document, range))
in
Lwt.return (actions, file_path, errors_opt)
let do_codeAction_resolve_local
(ide_service : ClientIdeService.t ref)
(env : env)
(tracking_id : string)
(ref_unblocked_time : float ref)
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : CodeActionRequest.params)
~(resolve_title : string) : CodeActionResolve.result Lwt.t =
let text_document =
get_text_document_item
editor_open_files
params.CodeActionRequest.textDocument.TextDocumentIdentifier.uri
in
let document = lsp_document_to_ide text_document in
let range = lsp_range_to_ide params.CodeActionRequest.range in
let use_snippet_edits = should_use_snippet_edits !initialize_params_ref in
ide_rpc
ide_service
~env
~tracking_id
~ref_unblocked_time
(ClientIdeMessage.Code_action_resolve
{ document; range; resolve_title; use_snippet_edits })
let do_signatureHelp_local
(ide_service : ClientIdeService.t ref)
(env : env)
(tracking_id : string)
(ref_unblocked_time : float ref)
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : SignatureHelp.params) : SignatureHelp.result Lwt.t =
let (document, location) = get_document_location editor_open_files params in
let%lwt signatures =
ide_rpc
ide_service
~env
~tracking_id
~ref_unblocked_time
(ClientIdeMessage.Signature_help (document, location))
in
Lwt.return signatures
let patch_to_workspace_edit_change (patch : ServerRenameTypes.patch) :
string * TextEdit.t =
let open ServerRenameTypes in
let open Pos in
let text_edit =
match patch with
| Insert insert_patch
| Replace insert_patch ->
{
TextEdit.range =
Lsp_helpers.hack_pos_to_lsp_range ~equal:String.equal insert_patch.pos;
newText = insert_patch.text;
}
| Remove pos ->
{
TextEdit.range =
Lsp_helpers.hack_pos_to_lsp_range ~equal:String.equal pos;
newText = "";
}
in
let uri =
match patch with
| Insert insert_patch
| Replace insert_patch ->
File_url.create (filename insert_patch.pos)
| Remove pos -> File_url.create (filename pos)
in
(uri, text_edit)
let patches_to_workspace_edit (patches : ServerRenameTypes.patch list) :
WorkspaceEdit.t =
let changes = List.map patches ~f:patch_to_workspace_edit_change in
let changes =
List.fold changes ~init:SMap.empty ~f:(fun acc (uri, text_edit) ->
let current_edits = Option.value ~default:[] (SMap.find_opt uri acc) in
let new_edits = text_edit :: current_edits in
SMap.add uri new_edits acc)
in
{ WorkspaceEdit.changes }
let do_documentRename_local
(state : state)
(ide_service : ClientIdeService.t ref)
(env : env)
(metadata : incoming_metadata)
(ref_unblocked_time : float ref)
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : Rename.params)
(id : lsp_id) : (state * result_telemetry) Lwt.t =
let start_time_local_handle = Unix.gettimeofday () in
let document_position = rename_params_to_document_position params in
let (document, location) =
get_document_location editor_open_files document_position
in
let new_name = params.Rename.newName in
let all_open_documents = get_documents_from_open_files editor_open_files in
let%lwt response =
ide_rpc
ide_service
~env
~tracking_id:metadata.tracking_id
~ref_unblocked_time
(ClientIdeMessage.Rename (document, location, new_name, all_open_documents))
in
match response with
| ClientIdeMessage.Not_renameable_position ->
let message = "Tried to rename a non-renameable symbol" in
raise
(Error.LspException
{ Error.code = Error.InvalidRequest; message; data = None })
| ClientIdeMessage.Rename_success { shellout = None; local } ->
let patches = patches_to_workspace_edit local in
respond_jsonrpc ~powered_by:Hh_server id (RenameResult patches);
let result_telemetry = make_result_telemetry (List.length local) in
Lwt.return (state, result_telemetry)
| ClientIdeMessage.Rename_success
{
shellout = Some (symbol_definition, find_refs_action);
local = ide_calculated_patches;
} ->
let shellable_type =
Lost_env.Rename
{
symbol_definition;
find_refs_action;
new_name;
ide_calculated_patches;
}
in
let%lwt (state, result_telemetry) =
kickoff_shell_out_and_maybe_cancel
state
shellable_type
~triggering_request:
{
Lost_env.id;
metadata;
start_time_local_handle;
request = RenameRequest params;
}
in
Lwt.return (state, result_telemetry)
(** This is called when a shell-out to "hh --ide-rename-by-symbol" completes successfully *)
let do_documentRename2 ~ide_calculated_patches ~hh_edits : Lsp.lsp_result * int
=
(* The list of patches we receive from shelling out reflect the state
of files on disk, which is incorrect for edited files. To fix,
1) Filter out all changes for files that are open
2) add the list of ide_calculated changes
*)
let hh_changes = hh_edits.WorkspaceEdit.changes in
let ide_changes = patches_to_workspace_edit ide_calculated_patches in
let changes =
SMap.fold
(fun file ide combined -> SMap.add file ide combined)
ide_changes.WorkspaceEdit.changes
hh_changes
in
let result_count =
SMap.fold (fun _file changes tot -> tot + List.length changes) changes 0
in
(RenameResult { WorkspaceEdit.changes }, result_count)
let hack_type_hierarchy_to_lsp
(filename : string) (type_hierarchy : ServerTypeHierarchyTypes.result) :
Lsp.TypeHierarchy.result =
let hack_member_kind_to_lsp = function
| ServerTypeHierarchyTypes.Method -> Lsp.TypeHierarchy.Method
| ServerTypeHierarchyTypes.SMethod -> Lsp.TypeHierarchy.SMethod
| ServerTypeHierarchyTypes.Property -> Lsp.TypeHierarchy.Property
| ServerTypeHierarchyTypes.SProperty -> Lsp.TypeHierarchy.SProperty
| ServerTypeHierarchyTypes.Const -> Lsp.TypeHierarchy.Const
in
let hack_member_entry_to_Lsp (entry : ServerTypeHierarchyTypes.memberEntry) :
Lsp.TypeHierarchy.memberEntry =
let Lsp.Location.{ uri; range } =
hack_pos_to_lsp_location
entry.ServerTypeHierarchyTypes.pos
~default_path:filename
in
let open ServerTypeHierarchyTypes in
Lsp.TypeHierarchy.
{
name = entry.name;
snippet = entry.snippet;
uri;
range;
kind = hack_member_kind_to_lsp entry.kind;
origin = entry.origin;
}
in
let hack_enty_kind_to_lsp = function
| ServerTypeHierarchyTypes.Class -> Lsp.TypeHierarchy.Class
| ServerTypeHierarchyTypes.Interface -> Lsp.TypeHierarchy.Interface
| ServerTypeHierarchyTypes.Trait -> Lsp.TypeHierarchy.Trait
| ServerTypeHierarchyTypes.Enum -> Lsp.TypeHierarchy.Enum
in
let hack_ancestor_entry_to_Lsp
(entry : ServerTypeHierarchyTypes.ancestorEntry) :
Lsp.TypeHierarchy.ancestorEntry =
match entry with
| ServerTypeHierarchyTypes.AncestorName name ->
Lsp.TypeHierarchy.AncestorName name
| ServerTypeHierarchyTypes.AncestorDetails entry ->
let Lsp.Location.{ uri; range } =
hack_pos_to_lsp_location entry.pos ~default_path:filename
in
Lsp.TypeHierarchy.AncestorDetails
{
name = entry.name;
uri;
range;
kind = hack_enty_kind_to_lsp entry.kind;
}
in
let hack_hierarchy_entry_to_Lsp
(entry : ServerTypeHierarchyTypes.hierarchyEntry) :
Lsp.TypeHierarchy.hierarchyEntry =
let Lsp.Location.{ uri; range } =
hack_pos_to_lsp_location
entry.ServerTypeHierarchyTypes.pos
~default_path:filename
in
let open ServerTypeHierarchyTypes in
Lsp.TypeHierarchy.
{
name = entry.name;
uri;
range;
kind = hack_enty_kind_to_lsp entry.kind;
ancestors = List.map entry.ancestors ~f:hack_ancestor_entry_to_Lsp;
members = List.map entry.members ~f:hack_member_entry_to_Lsp;
}
in
match type_hierarchy with
| None -> None
| Some h -> Some (hack_hierarchy_entry_to_Lsp h)
let do_typeHierarchy_local
(ide_service : ClientIdeService.t ref)
(env : env)
(tracking_id : string)
(ref_unblocked_time : float ref)
(editor_open_files : Lsp.TextDocumentItem.t UriMap.t)
(params : TypeHierarchy.params) : TypeHierarchy.result Lwt.t =
let (document, location) = get_document_location editor_open_files params in
let filename =
lsp_uri_to_path
params.TextDocumentPositionParams.textDocument.TextDocumentIdentifier.uri
in
let%lwt result =
ide_rpc
ide_service
~env
~tracking_id
~ref_unblocked_time
(ClientIdeMessage.Type_Hierarchy (document, location))
in
let converted = hack_type_hierarchy_to_lsp filename result in
Lwt.return converted
(** TEMPORARY VALIDATION FOR IDE_STANDALONE. TODO(ljw): delete this once ide_standalone ships T92870399 *)
let validate_error_TEMPORARY
(uri : documentUri)
(lenv : Lost_env.t)
(actual : float * errors_from)
~(expected : Errors.finalized_error list)
~(start_time : float) : (float * errors_from) * string list =
(* helper to diff two sorted lists: "list_diff ([],[]) xs ys" will return a pair
(only_xs, only_ys) with those elements that are only in xs, and those only in ys. *)
let rec list_diff (only_xs, only_ys) xs ys ~compare =
match (xs, ys) with
| ([], ys) -> (only_xs, ys @ only_ys)
| (xs, []) -> (xs @ only_xs, only_ys)
| (x :: xs, y :: ys) ->
let c = compare x y in
if c < 0 then
list_diff (x :: only_xs, ys) xs (y :: ys) ~compare
else if c > 0 then
list_diff (only_xs, y :: only_ys) (x :: xs) ys ~compare
else
list_diff (only_xs, only_ys) xs ys ~compare
in
(* helper to accumulate log output into [diff] *)
let format_diff (disposition : string) (errors : Errors.finalized_error list)
: string list =
List.map errors ~f:(fun { User_error.claim = (pos, msg); code; _ } ->
let (line, start, end_) = Pos.info_pos pos in
Printf.sprintf
"%s: [%d] %s(%d:%d-%d) %s"
disposition
code
(Pos.filename pos)
line
start
end_
msg)
in
match actual with
| (_timestamp, Errors_from_errors_file) ->
(* What was most recently published for [uri] came from a previous errors-file *)
(actual, [])
| (timestamp, Errors_from_clientIdeDaemon _)
when Float.(timestamp > start_time) ->
(* What was most recently published for [uri] came from clientIdeDaemon, but
came from something (e.g. a didChange) that happened after the start of the typecheck,
so it might reflect something that hh_server wasn't aware of, so we can't make a useful check. *)
(actual, [])
| (_timestamp, Errors_from_clientIdeDaemon _)
when UriSet.mem uri lenv.Lost_env.uris_with_unsaved_changes ->
(* What was most recently published for [uri] came from clientIdeDaemon, but it
reflects unsaved changes, and hence reflects something that hh_server isn't aware of,
so we can't make a useful check *)
(actual, [])
| (_timestamp, Errors_from_clientIdeDaemon _)
when Option.is_none (UriMap.find_opt uri lenv.Lost_env.editor_open_files) ->
(* What was most recently published for [uri] came from clientIdeDaemon before the start of the
typecheck, but it was closed prior to the start of the typecheck, so we don't know if hh_server
is looking at file-changes to it after it had been closed and we can't make a useful check. *)
(actual, [])
| (_timestamp, Errors_from_clientIdeDaemon { validated = true; _ }) ->
(* Here is an open file whose errors were published from clientIdeDaemon prior to the start of not only this
current typecheck, but also prior to the start of the *previous* typecheck. We need no further validation. *)
(actual, [])
| (timestamp, Errors_from_clientIdeDaemon { errors; _ }) ->
let (absent_from_clientIdeDaemon, extra_in_clientIdeDaemon) =
list_diff ([], []) expected errors ~compare:Errors.compare_finalized
in
let diff =
format_diff "absent_from_clientIdeDaemon" absent_from_clientIdeDaemon
@ format_diff "extra_in_clientIdeDaemon" extra_in_clientIdeDaemon
in
((timestamp, Errors_from_clientIdeDaemon { errors; validated = true }), diff)
(** TEMPORARY VALIDATION FOR IDE_STANDALONE. TODO(ljw): delete this once ide_standalone ships T92870399
Validates that errors reported by clientIdeDaemon are same as what was reported by hh_server.
This function is called by [handle_errors_file_item] when it receives a new report
of errors from the errors-file. It validates that, if there are any open unmodified files
which had last received errors from clientIdeDaemon prior the start of the typecheck, then
are those clientIdeDaemon errors identical to the ones reported in the errors file?
It also has the side effect of storing, in [lenv.uris_with_standalone_diagnostics],
that these particular clientIdeDaemon have been validated against the errors-file;
this fact is used in [validate_error_absence].
Why do we only look at unmodified files whose last received clientIdeDaemon errors were from
prior to the start of the typecheck? -- because for sure clientIdeDaemon and hh_server
both saw the same source text for them. Why can't we look at closed files? -- because
they might have been modified on disk after they were closed. *)
let validate_error_item_TEMPORARY
(lenv : Lost_env.t)
(ide_service : ClientIdeService.t ref)
(expected : Errors.finalized_error list Relative_path.Map.t)
~(start_time : float) : Lost_env.t =
(* helper to do logging *)
let log_diff uri reason ~expected diff =
HackEventLogger.live_squiggle_diff
~uri:(string_of_uri uri)
~reason
~expected_error_count:(List.length expected)
diff;
if not (List.is_empty diff) then
Hh_logger.log
"LIVE_SQUIGGLE_DIFF_ERROR[item] %s\n%s"
(string_of_uri uri)
(String.concat ~sep:"\n" diff)
in
let lenv =
Relative_path.Map.fold expected ~init:lenv ~f:(fun path expected lenv ->
let path = Relative_path.to_absolute path in
let uri = path_to_lsp_uri path ~default_path:path in
let actual_opt =
UriMap.find_opt uri lenv.Lost_env.uris_with_standalone_diagnostics
in
let status = ClientIdeService.get_status !ide_service in
(* We use [Option.value_exn] because this function [validate_error_item_TEMPORARY]
is only ever called under ide_standalone=true, which implies ide_serverless=true,
so hence there must be an ide_service. *)
match (actual_opt, status) with
| (Some actual, _) ->
(* If we got a report of errors in [uri] from the errors-file, and we've
previously published diagnostics for [uri], we'll validate that what
we previously published is correct... *)
let (actual, diff) =
validate_error_TEMPORARY uri lenv actual ~expected ~start_time
in
log_diff uri "item-reported" ~expected diff;
let uris_with_standalone_diagnostics =
UriMap.add uri actual lenv.Lost_env.uris_with_standalone_diagnostics
in
{ lenv with Lost_env.uris_with_standalone_diagnostics }
| (None, ClientIdeService.Status.Ready) ->
(* We got a report of errors in [uri] from the errors-file, but we don't
currently have any diagnostics published [uri]. I wonder why not? ...
The following function only validates at files which are open and unmodified
in the editor. If an open and unmodified file has no published diagnostics,
we don't know when it claimed to have no diagnostics, whether that was
before the typecheck started (in which case errors-file should agree that it has
no diagnostics), or following a didSave after the typecheck started (in which case
we can't tell). Let's pretend, for sake of "good-enough" telemetry, that it
was before the typecheck started and see whether errors-file agrees. *)
let pretend_actual =
( start_time,
Errors_from_clientIdeDaemon { validated = false; errors = [] } )
in
let (_pretend_actual, diff) =
validate_error_TEMPORARY
uri
lenv
pretend_actual
~expected
~start_time
in
log_diff uri "item-unreported" ~expected diff;
lenv
| ( None,
ClientIdeService.Status.(
Initializing | Processing_files _ | Rpc _ | Stopped _) ) ->
(* We got a report of errors in [uri] from the errors-file, but we don't
currently have any diagnostics published for [uri] because clientIdeDaemon
isn't even ready yet. Nothing worth checking. *)
lenv)
in
lenv
(** TEMPORARY VALIDATION FOR IDE_STANDALONE. TODO(ljw): delete this once ide_standalone ships T92870399
Validates that clientIdeDaemon didn't report additional errors beyond what was reported
by hh_server.
This function is called when [handle_errors_file_item] is told that the errors-file is
completed. It validates that, if there are any unmodified files which had last received
errors from clientIdeDaemon prior to the start of the typecheck, then all of them
have [Errors_from.validated] flag true, meaning that they have been checked against
the errors-file by [validate_error_presence]. If a file hasn't, then it's a false
positive reported by clientIdeStandalone. *)
let validate_error_complete_TEMPORARY (lenv : Lost_env.t) ~(start_time : float)
: Lost_env.t =
let uris_with_standalone_diagnostics =
UriMap.mapi
(fun uri actual ->
let (actual, diff) =
validate_error_TEMPORARY uri lenv actual ~expected:[] ~start_time
in
HackEventLogger.live_squiggle_diff
~uri:(string_of_uri uri)
~reason:"complete"
~expected_error_count:0
diff;
if not (List.is_empty diff) then
Hh_logger.log
"LIVE_SQUIGGLE_DIFF_ERROR[complete] %s\n%s"
(string_of_uri uri)
(String.concat ~sep:"\n" diff);
actual)
lenv.Lost_env.uris_with_standalone_diagnostics
in
{ lenv with Lost_env.uris_with_standalone_diagnostics }
(** Used to publish clientIdeDaemon errors in [ide_standalone] mode. *)
let publish_errors_if_standalone
(state : state) (file_path : Path.t) (errors : Errors.finalized_error list)
: state =
match state with
| Pre_init -> failwith "how we got errors before initialize?"
| Post_shutdown -> state (* no-op *)
| Lost_server lenv ->
let file_path = Path.to_string file_path in
let uri = path_to_lsp_uri file_path ~default_path:file_path in
let uris = lenv.Lost_env.uris_with_standalone_diagnostics in
let uris_with_standalone_diagnostics =
if List.is_empty errors then
UriMap.remove uri uris
else
UriMap.add
uri
( Unix.gettimeofday (),
Errors_from_clientIdeDaemon { errors; validated = false } )
uris
in
let params = hack_errors_to_lsp_diagnostic file_path errors in
let notification = PublishDiagnosticsNotification params in
notify_jsonrpc ~powered_by:Serverless_ide notification;
let new_state =
Lost_server { lenv with Lost_env.uris_with_standalone_diagnostics }
in
new_state
(** When the errors-file gets new items or is closed, this function updates diagnostics as necessary,
and switches from TailingErrors to SeekingErrors if it's closed.
Principles: (1) don't touch open files, since they are governed solely by clientIdeDaemon;
(2) only update an existing diagnostic if the scrape's start_time is newer than it,
since these will have come recently from clientIdeDaemon, to which we grant primacy. *)
let handle_errors_file_item
~(state : state ref)
~(ide_service : ClientIdeService.t ref)
(item : ServerProgress.ErrorsRead.read_result option) :
result_telemetry option Lwt.t =
(* a small helper, to send the actual lsp message *)
let publish params =
notify_jsonrpc ~powered_by:Hh_server (PublishDiagnosticsNotification params)
in
(* a small helper, to construct empty diagnostic params *)
let empty_diagnostics uri =
Lsp.PublishDiagnostics.{ uri; diagnostics = []; isStatusFB = false }
in
(* We must be in this state, else how could we have gotten an item from the errors-file q?
See code in [get_next_event]. *)
let (lenv, fd, start_time) =
match (!state, !latest_hh_server_errors) with
| (Lost_server lenv, TailingErrors { fd; start_time; _ }) ->
(lenv, fd, start_time)
| _ -> failwith "unexpected state when processing handle_errors_file_item"
in
match item with
| None ->
(* We must have an item, because the errors-stream always ends with a sentinel, and we stop tailing upon the sentinel. *)
log "Errors-file: unexpected end of stream";
HackEventLogger.invariant_violation_bug
"errors-file unexpected end of stream";
latest_hh_server_errors :=
SeekingErrors
{
prev_st_ino = None;
seek_reason = (ServerProgress.NothingYet, "eof-error");
};
Lwt.return_none
| Some (Error (end_sentinel, log_message)) ->
(* Close the errors-file, and switch to "seeking mode" for the next errors-file to come along. *)
let stat = Unix.fstat fd in
Unix.close fd;
latest_hh_server_errors :=
SeekingErrors
{
prev_st_ino = Some stat.Unix.st_ino;
seek_reason = (end_sentinel, log_message);
};
begin
match end_sentinel with
| ServerProgress.NothingYet
| ServerProgress.Build_id_mismatch ->
failwith
("not possible out of q: "
^ ServerProgress.show_errors_file_error end_sentinel
^ " "
^ log_message)
| ServerProgress.Stopped
| ServerProgress.Killed _ ->
(* At this point we'd like to erase all the squiggles that came from hh_server.
All we'll do is leave the errors for now, and then a subsequent [try_open_errors_file]
will determine that we've transitioned from an ok state (like we leave it in right now)
to an error state, and it takes that opportunity to erase all squiggles. *)
()
| ServerProgress.Restarted _ ->
(* If the typecheck restarted, we'll just leave all existing errors as they are.
We have no evidence upon which to add or erase anything.
It will all be fixed in the next typecheck to complete. *)
()
| ServerProgress.Complete _telemetry ->
let lenv = validate_error_complete_TEMPORARY lenv ~start_time in
(* If the typecheck completed, then we can erase all diagnostics (from closed-files)
that were reported prior to the start of the typecheck - regardless of whether that
diagnostic had most recently been reported from errors-file or from clientIdeDaemon.
Why only from closed-files? ... because diagnostics for open files are produced live by clientIdeDaemon,
and our information from errors-file is necessarily more stale than that from clientIdeDaemon. *)
let uris_with_standalone_diagnostics =
lenv.Lost_env.uris_with_standalone_diagnostics
|> UriMap.filter_map (fun uri (existing_time, errors_from) ->
if
UriMap.mem uri lenv.Lost_env.editor_open_files
|| Float.(existing_time > start_time)
then begin
Some (existing_time, errors_from)
end else begin
publish (empty_diagnostics uri);
None
end)
in
state :=
Lost_server { lenv with Lost_env.uris_with_standalone_diagnostics };
()
end;
Lwt.return_none
| Some (Ok (ServerProgress.Telemetry _)) -> Lwt.return_none
| Some (Ok (ServerProgress.Errors { errors; timestamp })) ->
let lenv =
validate_error_item_TEMPORARY lenv ide_service errors ~start_time
in
(* If the php file is closed and has no diagnostics newer than start_time, replace or add.
Why only for closed files? well, if the file is currently open in the IDE, then
clientIdeDaemon-generated diagnostics (1) reflect unsaved changes which the errors-file
doesn't, (2) is more up-to-date than the errors-file, or at least no older.
Why only newer than start time? There are a lot of scenarios but all boil down to this
simple rule. (1) Existing diagnostics might have come from a previous errors-file, and hence
are older than the start of the current errors-file, and should be replaced. (2) Existing
diagnostics might have come from a file still open in the editor, discussed above.
(3) Existing diagnostics might have come from a file that was open in the editor but
got closed before the current errors-file started, and hence the errors-file is more up-to-date.
(4) Existing diagnostics might have come from a file that was open in the editor but
got closed after the current errors-file started; hence the latest we received from
clientIdeDaemon is more up to date. (5) Existing diagnostics might have come from
the current errors-file, per the comment in ServerProgress.mli: 'Currently we make
one report for all "duplicate name" errors across the project if any, followed by
one report per batch that had errors. This means that a file might be mentioned
twice, once in a "duplicate name" report, once later. This will change in future
so that each file is reported only once.'. The behavior right now is that clientLsp
will only show the "duplicate name" errors for a file, suppressing future errors
that came from parsing+typechecking. It's not ideal, but it will change shortly,
and is an acceptable compromise for sake of code cleanliness. *)
let uris_with_standalone_diagnostics =
Relative_path.Map.fold
errors
~init:lenv.Lost_env.uris_with_standalone_diagnostics
~f:(fun path file_errors acc ->
let path = Relative_path.to_absolute path in
let uri = path_to_lsp_uri path ~default_path:path in
if UriMap.mem uri lenv.Lost_env.editor_open_files then
acc
else
match UriMap.find_opt uri acc with
| Some (existing_timestamp, _errors_from)
when Float.(existing_timestamp > start_time) ->
acc
| _ ->
publish (hack_errors_to_lsp_diagnostic path file_errors);
UriMap.add uri (timestamp, Errors_from_errors_file) acc)
in
state := Lost_server { lenv with Lost_env.uris_with_standalone_diagnostics };
Lwt.return_none
(** If we're in [errors_conn = SeekingErrors], then this function will try to open the
current errors-file. If success then we'll set [latest_hh_server_errors] to [TailingErrors].
If failure then we'll set it to [SeekingErrors], which includes error explanation for why
the attempt failed. We'll also clear out all squiggles.
If the failure was due to a version mismatch, we also take the opportunity
to check: has the version changed under our feet since we ourselves started?
If it has, then we exit with an error code (so that VSCode will relaunch
the correct version of lsp afterwards). If it hasn't, then we continue,
and the version mismatch must necessarily indicate that hh_server is the
wrong version.
If we're in [errors_conn = TrailingErrors] already, this function is a no-op.
If we're called before even having received the initialize request from LSP client
(hence before we even know the project root), this is a no-op. *)
let try_open_errors_file ~(state : state ref) : unit Lwt.t =
match (!latest_hh_server_errors, get_root_opt ()) with
| (TailingErrors _, _) -> Lwt.return_unit
| (SeekingErrors _, None) ->
(* we haven't received initialize request yet *)
Lwt.return_unit
| (SeekingErrors { prev_st_ino; seek_reason }, Some root) ->
let errors_file_path = ServerFiles.errors_file_path root in
(* 1. can we open the file? *)
let result =
try
Ok (Unix.openfile errors_file_path [Unix.O_RDONLY; Unix.O_NONBLOCK] 0)
with
| Unix.Unix_error (Unix.ENOENT, _, _) ->
Error
(SeekingErrors
{
prev_st_ino;
seek_reason = (ServerProgress.NothingYet, "absent");
})
| exn ->
Error
(SeekingErrors
{
prev_st_ino;
seek_reason = (ServerProgress.NothingYet, Exn.to_string exn);
})
in
(* 2. is it different from the previous time we looked? *)
let result =
match (prev_st_ino, result) with
| (Some st_ino, Ok fd) when st_ino = (Unix.fstat fd).Unix.st_ino ->
Unix.close fd;
Error (SeekingErrors { prev_st_ino; seek_reason })
| _ -> result
in
(* 3. can we [ServerProgress.ErrorsRead.openfile] on it? *)
let%lwt errors_conn =
match result with
| Error errors_conn -> Lwt.return errors_conn
| Ok fd -> begin
match ServerProgress.ErrorsRead.openfile fd with
| Error (e, log_message) ->
let prev_st_ino = Some (Unix.fstat fd).Unix.st_ino in
Unix.close fd;
log
"Errors-file: failed to open. %s [%s]"
(ServerProgress.show_errors_file_error e)
log_message;
let%lwt () = terminate_if_version_changed_since_start_of_lsp () in
Lwt.return
(SeekingErrors { prev_st_ino; seek_reason = (e, log_message) })
| Ok { ServerProgress.ErrorsRead.timestamp; pid; _ } ->
log
"Errors-file: opened and tailing the check from %s"
(Utils.timestring timestamp);
let q = ServerProgressLwt.watch_errors_file ~pid fd in
Lwt.return (TailingErrors { fd; start_time = timestamp; q })
end
in
(* If we've transitioned to failure, then we'll have to erase all outstanding squiggles.
It'd be nice to leave the ones produced by clientIdeDaemon.
But that's too much book-keeping to be worth complicating the code for an edge case,
so in the words of c3po "shut them all down. hurry!" *)
let is_ok conn =
match conn with
| TailingErrors _ -> true
| SeekingErrors
{ seek_reason = (ServerProgress.(Restarted _ | Complete _), _); _ } ->
true
| SeekingErrors
{
seek_reason =
( ServerProgress.(
NothingYet | Stopped | Killed _ | Build_id_mismatch),
_ );
_;
} ->
false
in
let has_transitioned_to_failure =
is_ok !latest_hh_server_errors && not (is_ok errors_conn)
in
if has_transitioned_to_failure then state := dismiss_diagnostics !state;
latest_hh_server_errors := errors_conn;
Lwt.return_unit
let handle_refs_file_items
~(state : state ref)
(items : FindRefsWireFormat.half_open_one_based list option) :
result_telemetry option =
match (items, !state) with
| ( Some refs,
Lost_server
Lost_env.
{
current_hh_shell =
Some
{
shellable_type =
FindRefs
{ stream_file = Some { partial_result_token; _ }; _ };
_;
};
_;
} ) ->
let notification =
FindReferencesPartialResultNotification
( partial_result_token,
List.map refs ~f:ide_shell_out_pos_to_lsp_location )
in
notification |> print_lsp_notification |> to_stdout;
None
| (None, _) ->
(* This signals that the stream has been closed. The function [watch_refs_stream_file] only closes
the stream when the stream-file has been unlinked. We only unlink the file in [handle_shell_out_complete],
which also updates [state] to no longer be watching this file. Therefore, we should never encounter
a closed stream. *)
log "Refs-file: unexpected end of stream";
HackEventLogger.invariant_violation_bug "refs-file unexpected end of stream";
None
| (Some _, _) ->
log "Refs-file: unexpected items when stream isn't open";
HackEventLogger.invariant_violation_bug "refs-file unexpected items";
None
(** This function handles the success/failure of a shell-out.
It is guaranteed to produce an LSP response for [shellable_type]. *)
let handle_shell_out_complete
(result : (Lwt_utils.Process_success.t, Lwt_utils.Process_failure.t) result)
(triggering_request : Lost_env.triggering_request)
(shellable_type : Lost_env.shellable_type) : result_telemetry option =
let start_postprocess_time = Unix.gettimeofday () in
let make_duration_telemetry ~start_time ~end_time =
let end_postprocess_time = Unix.gettimeofday () in
let start_time_local_handle =
triggering_request.Lost_env.start_time_local_handle
in
Telemetry.create ()
|> Telemetry.duration
~key:"local_duration"
~start_time:start_time_local_handle
~end_time:start_time
|> Telemetry.duration ~key:"shellout_duration" ~start_time ~end_time
|> Telemetry.duration
~key:"post_shellout_wait"
~start_time:end_time
~end_time:start_postprocess_time
|> Telemetry.duration
~key:"postprocess_duration"
~start_time:start_postprocess_time
~end_time:end_postprocess_time
in
let (lsp_result, result_count, result_extra_data) =
match result with
| Error
({
Lwt_utils.Process_failure.start_time;
end_time;
stderr;
stdout;
command_line;
process_status;
exn = _;
} as failure) ->
let code =
match process_status with
| Unix.WSIGNALED -7 -> Lsp.Error.RequestCancelled
| _ -> Lsp.Error.InternalError
in
let process_status = Process.status_to_string process_status in
log "shell-out failure: %s" (Lwt_utils.Process_failure.to_string failure);
let message =
[stderr; stdout; process_status]
|> List.map ~f:String.strip
|> List.filter ~f:(fun s -> not (String.is_empty s))
|> String.concat ~sep:"\n"
in
let telemetry =
make_duration_telemetry ~start_time ~end_time
|> Telemetry.string_ ~key:"command_line" ~value:command_line
|> Telemetry.string_ ~key:"status" ~value:process_status
|> Telemetry.error ~e:message
in
let lsp_error =
make_lsp_error
~code
~data:(Some (Telemetry.to_json telemetry))
~current_stack:false
message
in
(ErrorResult lsp_error, 0, None)
| Ok { Lwt_utils.Process_success.stdout; start_time; end_time; _ } -> begin
log
"shell-out completed. %s"
(String_utils.split_into_lines stdout
|> List.hd
|> Option.value ~default:""
|> String_utils.truncate 80);
try
let (lsp_result, result_count) =
let open Lost_env in
match shellable_type with
| FindRefs { ide_calculated_positions; stream_file; _ } ->
let hh_locations = shellout_locations_to_lsp_locations_exn stdout in
do_findReferences2
~ide_calculated_positions
~hh_locations
~stream_file
| GoToImpl { ide_calculated_positions; _ } ->
let hh_locations = shellout_locations_to_lsp_locations_exn stdout in
do_goToImplementation2 ~ide_calculated_positions ~hh_locations
| Rename { ide_calculated_patches; _ } ->
let hh_edits = shellout_patch_list_to_lsp_edits_exn stdout in
do_documentRename2 ~ide_calculated_patches ~hh_edits
in
( lsp_result,
result_count,
Some (make_duration_telemetry ~start_time ~end_time) )
with
| exn ->
let e = Exception.wrap exn in
let stack = Exception.get_backtrace_string e |> Exception.clean_stack in
let message = Exception.get_ctor_string e in
let telemetry = make_duration_telemetry ~start_time ~end_time in
let lsp_error =
make_lsp_error
~code:Lsp.Error.InternalError
~data:(Some (Telemetry.to_json telemetry))
~stack
~current_stack:false
message
in
(ErrorResult lsp_error, 0, None)
end
in
let { Lost_env.id; metadata; start_time_local_handle; request } =
triggering_request
in
(* The normal error-response-and-logging flow isn't easy for us to fit into,
because it handles errors+exceptions thinking they come from the current event.
So we'll do our json response and error-logging ourselves. *)
respond_jsonrpc ~powered_by:Hh_server id lsp_result;
match lsp_result with
| ErrorResult lsp_error ->
hack_log_error
(Some (Client_message (metadata, RequestMessage (id, request))))
lsp_error
Error_from_daemon_recoverable
start_time_local_handle;
Some (make_result_telemetry 0 ~log_immediately:false)
| _ -> Some (make_result_telemetry result_count ?result_extra_data)
let do_initialize (local_config : ServerLocalConfig.t) : Initialize.result =
let initialize_params = initialize_params_exc () in
Initialize.
{
server_capabilities =
{
textDocumentSync =
{
want_openClose = true;
want_change = IncrementalSync;
want_willSave = false;
want_willSaveWaitUntil = true;
want_didSave = Some { includeText = false };
};
hoverProvider = true;
completionProvider =
Some
CompletionOptions.
{
resolveProvider = true;
completion_triggerCharacters =
["$"; ">"; "\\"; ":"; "<"; "["; "'"; "\""; "{"; "#"];
};
signatureHelpProvider =
Some { sighelp_triggerCharacters = ["("; ","] };
definitionProvider = true;
typeDefinitionProvider = true;
referencesProvider = true;
callHierarchyProvider = true;
documentHighlightProvider = true;
documentSymbolProvider = true;
workspaceSymbolProvider = true;
codeActionProvider = Some CodeActionOptions.{ resolveProvider = true };
codeLensProvider = None;
documentFormattingProvider = true;
documentRangeFormattingProvider = true;
documentOnTypeFormattingProvider =
(* TODO(T155870670) always set to `None` *)
Option.some_if
(not
initialize_params.initializationOptions
.skipLspServerOnTypeFormatting)
{ firstTriggerCharacter = ";"; moreTriggerCharacter = ["}"] };
renameProvider = true;
documentLinkProvider = None;
executeCommandProvider = None;
implementationProvider =
local_config.ServerLocalConfig.go_to_implementation;
rageProviderFB = true;
server_experimental =
Some ServerExperimentalCapabilities.{ snippetTextEdit = true };
};
}
let do_didChangeWatchedFiles_registerCapability () : Lsp.lsp_request =
(* We want a glob-pattern like "**/*.{php,phpt,hack,hackpartial,hck,hh,hhi,xhp}".
I'm constructing it from FindUtils.extensions so our glob-pattern doesn't get out
of sync with FindUtils.file_filter. *)
let extensions =
List.map FindUtils.extensions ~f:(fun s -> String_utils.lstrip s ".")
in
let globPattern =
Printf.sprintf "**/*.{%s}" (extensions |> String.concat ~sep:",")
in
let registration_options =
DidChangeWatchedFilesRegistrationOptions
{
DidChangeWatchedFiles.watchers = [{ DidChangeWatchedFiles.globPattern }];
}
in
let registration =
Lsp.RegisterCapability.make_registration registration_options
in
Lsp.RegisterCapabilityRequest
{ RegisterCapability.registrations = [registration] }
let track_open_and_recent_files (state : state) (event : event) : state =
(* We'll keep track of which files are opened by the editor. *)
let prev_opened_files =
Option.value (get_editor_open_files state) ~default:UriMap.empty
in
let editor_open_files =
match event with
| Client_message (_, NotificationMessage (DidOpenNotification params)) ->
let doc = params.DidOpen.textDocument in
let uri = params.DidOpen.textDocument.TextDocumentItem.uri in
UriMap.add uri doc prev_opened_files
| Client_message (_, NotificationMessage (DidChangeNotification params)) ->
let uri =
params.DidChange.textDocument.VersionedTextDocumentIdentifier.uri
in
let doc = UriMap.find_opt uri prev_opened_files in
let open Lsp.TextDocumentItem in
(match doc with
| Some doc ->
let doc' =
{
doc with
version =
params.DidChange.textDocument
.VersionedTextDocumentIdentifier.version;
text =
Lsp_helpers.apply_changes_unsafe
doc.text
params.DidChange.contentChanges;
}
in
UriMap.add uri doc' prev_opened_files
| None -> prev_opened_files)
| Client_message (_, NotificationMessage (DidCloseNotification params)) ->
let uri = params.DidClose.textDocument.TextDocumentIdentifier.uri in
UriMap.remove uri prev_opened_files
| _ -> prev_opened_files
in
match state with
| Lost_server lenv -> Lost_server { lenv with Lost_env.editor_open_files }
| Pre_init
| Post_shutdown ->
state
let track_edits_if_necessary (state : state) (event : event) : state =
(* We'll keep track of which files have unsaved edits. Note that not all
* clients send didSave messages; for those we only rely on didClose. *)
let previous = get_uris_with_unsaved_changes state in
let uris_with_unsaved_changes =
match event with
| Client_message (_, NotificationMessage (DidChangeNotification params)) ->
let uri =
params.DidChange.textDocument.VersionedTextDocumentIdentifier.uri
in
UriSet.add uri previous
| Client_message (_, NotificationMessage (DidCloseNotification params)) ->
let uri = params.DidClose.textDocument.TextDocumentIdentifier.uri in
UriSet.remove uri previous
| Client_message (_, NotificationMessage (DidSaveNotification params)) ->
let uri = params.DidSave.textDocument.TextDocumentIdentifier.uri in
UriSet.remove uri previous
| _ -> previous
in
match state with
| Lost_server lenv ->
Lost_server { lenv with Lost_env.uris_with_unsaved_changes }
| Pre_init
| Post_shutdown ->
state
let short_timeout = 2.5
let long_timeout = 15.0
(** If a message is stale, throw the necessary exception to cancel it. A message is
considered stale if it's sufficiently old and there are other messages in the queue
that are newer than it. *)
let cancel_if_stale (client : Jsonrpc.t) (timestamp : float) (timeout : float) :
unit Lwt.t =
let time_elapsed = Unix.gettimeofday () -. timestamp in
if
Float.(time_elapsed >= timeout)
&& Jsonrpc.has_message client
&& not (Sys_utils.deterministic_behavior_for_tests ())
then
let message =
if Float.(timestamp < binary_start_time) then
"binary took too long to launch"
else
"request timed out"
in
raise
(Error.LspException
{ Error.code = Error.RequestCancelled; message; data = None })
else
Lwt.return_unit
(** This is called before we even start processing a message. Its purpose:
if the Jsonrpc queue has already previously read off stdin a cancellation
request for the message we're about to handle, then throw an exception.
There are races, e.g. we might start handling this request because we haven't
yet gotten around to reading a cancellation message off stdin. But
that's inevitable. Think of this only as best-effort. *)
let cancel_if_has_pending_cancel_request
(client : Jsonrpc.t) (message : lsp_message) : unit =
match message with
| ResponseMessage _ -> ()
| NotificationMessage _ -> ()
| RequestMessage (id, _request) ->
(* Scan the queue for any pending (future) cancellation messages that are requesting
cancellation of the same id as our current request *)
let pending_cancel_request_opt =
Jsonrpc.find_already_queued_message client ~f:(fun { Jsonrpc.json; _ } ->
try
let peek =
Lsp_fmt.parse_lsp json (fun _ ->
failwith "not resolving responses")
in
match peek with
| NotificationMessage
(CancelRequestNotification { Lsp.CancelRequest.id = peek_id })
->
Lsp.IdKey.compare id peek_id = 0
| _ -> false
with
| _ -> false)
in
(* If there is a future cancellation request, we won't even embark upon this message *)
if Option.is_some pending_cancel_request_opt then
raise
(Error.LspException
{
Error.code = Error.RequestCancelled;
message = "request cancelled";
data = None;
})
else
()
(** Sends the file to [ide_service], which will respond by registering this file
as one of the "open files" (hence with persistent cached TAST until such time as
it receives Did_close).
We ask it to calculate that TAST and send us back errors which we then publish.
Unless there are subsequent didChange events for this uri already in the queue
(e.g. because the user is typing). In this case we don't ask for TAST/errors;
the work can be deferred until that next didChange. *)
let send_file_to_ide_and_get_errors_if_needed
~env
~client
~ide_service
~state
~uri
~file_contents
~tracking_id
~ref_unblocked_time : state Lwt.t =
let file_path = uri |> lsp_uri_to_path |> Path.make in
let subsequent_didchange_for_this_uri =
Jsonrpc.find_already_queued_message client ~f:(fun { Jsonrpc.json; _ } ->
let message =
try
Lsp_fmt.parse_lsp json (fun _ -> UnknownRequest ("response", None))
with
| _ ->
NotificationMessage (UnknownNotification ("cannot parse", None))
in
match message with
| NotificationMessage
(DidChangeNotification
{
DidChange.textDocument =
{ VersionedTextDocumentIdentifier.uri = uri2; _ };
_;
})
when Lsp.equal_documentUri uri uri2 ->
true
| _ -> false)
in
let should_calculate_errors =
Option.is_none subsequent_didchange_for_this_uri
in
let%lwt errors =
ide_rpc
ide_service
~env
~tracking_id
~ref_unblocked_time
ClientIdeMessage.(
Did_open_or_change
({ file_path; file_contents }, { should_calculate_errors }))
in
let new_state =
match errors with
| None -> !state
| Some errors -> publish_errors_if_standalone !state file_path errors
in
Lwt.return new_state
(************************************************************************)
(* Message handling *)
(************************************************************************)
(** send DidOpen/Close/Change/Save ide_service as needed *)
let handle_editor_buffer_message
~(env : env)
~(state : state ref)
~(client : Jsonrpc.t)
~(ide_service : ClientIdeService.t ref)
~(metadata : incoming_metadata)
~(ref_unblocked_time : float ref)
~(message : lsp_message) : unit Lwt.t =
let uri_to_path uri = uri |> lsp_uri_to_path |> Path.make in
match message with
| NotificationMessage
( DidOpenNotification
{ DidOpen.textDocument = { TextDocumentItem.uri; _ }; _ }
| DidChangeNotification
{
DidChange.textDocument = { VersionedTextDocumentIdentifier.uri; _ };
_;
} ) ->
let editor_open_files =
match get_editor_open_files !state with
| Some files -> files
| None -> UriMap.empty
in
let file_contents = get_document_contents editor_open_files uri in
let%lwt new_state =
send_file_to_ide_and_get_errors_if_needed
~env
~client
~ide_service
~state
~uri
~file_contents
~ref_unblocked_time
~tracking_id:metadata.tracking_id
in
state := new_state;
Lwt.return_unit
| NotificationMessage (DidCloseNotification params) ->
let file_path =
uri_to_path params.DidClose.textDocument.TextDocumentIdentifier.uri
in
let%lwt errors =
ide_rpc
ide_service
~env
~tracking_id:metadata.tracking_id
~ref_unblocked_time
(ClientIdeMessage.Did_close file_path)
in
state := publish_errors_if_standalone !state file_path errors;
Lwt.return_unit
| _ ->
(* Don't handle other events for now. When we show typechecking errors for
the open file, we'll start handling them. *)
ref_unblocked_time := Unix.gettimeofday ();
Lwt.return_unit
let set_verbose_to_file
~(ide_service : ClientIdeService.t ref)
~(env : env)
~(tracking_id : string)
(value : bool) : unit =
verbose_to_file := value;
if !verbose_to_file then
Hh_logger.Level.set_min_level_file Hh_logger.Level.Debug
else
Hh_logger.Level.set_min_level_file Hh_logger.Level.Info;
let ref_unblocked_time = ref 0. in
let (promise : unit Lwt.t) =
ide_rpc
ide_service
~env
~tracking_id
~ref_unblocked_time
(ClientIdeMessage.Verbose_to_file !verbose_to_file)
in
ignore_promise_but_handle_failure
promise
~desc:"verbose-ide-rpc"
~terminate_on_failure:false;
()
(* Process and respond to a message from VSCode, and update [state] accordingly. *)
let handle_client_message
~(env : env)
~(state : state ref)
~(client : Jsonrpc.t)
~(ide_service : ClientIdeService.t ref)
~(metadata : incoming_metadata)
~(message : lsp_message)
~(ref_unblocked_time : float ref) : result_telemetry option Lwt.t =
cancel_if_has_pending_cancel_request client message;
let%lwt result_telemetry_opt =
(* make sure to wrap any exceptions below in the promise *)
let tracking_id = metadata.tracking_id in
let timestamp = metadata.timestamp in
let editor_open_files =
match get_editor_open_files !state with
| Some files -> files
| None -> UriMap.empty
in
match (!state, message) with
(* response *)
| (_, ResponseMessage (id, response)) ->
let (_, handler) = IdMap.find id !requests_outstanding in
let%lwt new_state = handler response !state in
state := new_state;
Lwt.return_none
(* shutdown request *)
| (_, RequestMessage (id, ShutdownRequest)) ->
let%lwt new_state = do_shutdown !state ide_service tracking_id in
state := new_state;
respond_jsonrpc ~powered_by:Language_server id ShutdownResult;
Lwt.return_none
(* cancel notification *)
| (_, NotificationMessage (CancelRequestNotification { CancelRequest.id }))
->
(* Most requests are handled in-order here in clientLsp:
our loop gets around to pickup up request ID "x" off the queue,
before doing anything else it does [cancel_if_has_pending_cancel_request]
to see if there's a CancelRequestNotification ahead of it in the queue
and if so just sends a cancellation response rather than handling it.
Thus, we'll still get around to picking the CancelRequestNotification
off the queue right here and now, which is fine!
A few requests are handled asynchronously, though -- those that shell out
to hh. In these cases, upon receipt of the CancelRequestNotification,
we should actively SIGTERM the shell-out... *)
cancel_shellout_if_applicable !state id;
Lwt.return_none
(* exit notification *)
| (_, NotificationMessage ExitNotification) ->
if is_post_shutdown !state then
exit_ok ()
else
exit_fail ()
(* setTrace notification *)
| (_, NotificationMessage (SetTraceNotification params)) ->
let value =
match params with
| SetTraceNotification.Verbose -> true
| SetTraceNotification.Off -> false
in
set_verbose_to_file ~ide_service ~env ~tracking_id value;
Lwt.return_none
(* test entrypoint: shutdown client_ide_service *)
| (_, RequestMessage (id, HackTestShutdownServerlessRequestFB)) ->
let%lwt () =
stop_ide_service
!ide_service
~tracking_id
~stop_reason:ClientIdeService.Stop_reason.Testing
in
respond_jsonrpc
~powered_by:Serverless_ide
id
HackTestShutdownServerlessResultFB;
Lwt.return_none
(* test entrypoint: stop hh_server *)
| (_, RequestMessage (id, HackTestStopServerRequestFB)) ->
let root_folder =
Path.make (Relative_path.path_of_prefix Relative_path.Root)
in
ClientStop.kill_server root_folder !from;
respond_jsonrpc ~powered_by:Serverless_ide id HackTestStopServerResultFB;
Lwt.return_none
(* test entrypoint: start hh_server *)
| (_, RequestMessage (id, HackTestStartServerRequestFB)) ->
let root_folder =
Path.make (Relative_path.path_of_prefix Relative_path.Root)
in
start_server ~env root_folder;
respond_jsonrpc ~powered_by:Serverless_ide id HackTestStartServerResultFB;
Lwt.return_none
(* initialize request *)
| (Pre_init, RequestMessage (id, InitializeRequest initialize_params)) ->
let open Initialize in
initialize_params_ref := Some initialize_params;
(* There's a lot of global-mutable-variable initialization we can only do after
we get root, here in the handler of the initialize request. The function
[get_root_exn] becomes available after we've set up initialize_params_ref, above. *)
let root = get_root_exn () in
ServerProgress.set_root root;
set_up_hh_logger_for_client_lsp root;
Relative_path.set_path_prefix Relative_path.Root root;
if not (Path.equal root env.args.root_from_cli) then
HackEventLogger.invariant_violation_bug
~data:
(Printf.sprintf
"root_from_cli=%s initialize.root=%s"
(Path.to_string env.args.root_from_cli)
(Path.to_string root))
"lsp initialize.root differs from launch arg";
Hh_logger.log "cmd: %s" (String.concat ~sep:" " (Array.to_list Sys.argv));
Hh_logger.log "LSP Init id: %s" env.init_id;
(* Following is a hack. Atom incorrectly passes '--from vscode', rendering us
unable to distinguish Atom from VSCode. But Atom is now frozen at vscode client
v3.14. So by looking at the version, we can at least distinguish that it's old. *)
if
(not
initialize_params.client_capabilities.textDocument.declaration
.declarationLinkSupport)
&& String.equal env.args.from "vscode"
then begin
from := "vscode_pre314";
HackEventLogger.set_from !from
end;
let server_args =
ServerArgs.default_options ~root:(Path.to_string root)
in
let server_args = ServerArgs.set_config server_args env.args.config in
let local_config = snd @@ ServerConfig.load ~silent:true server_args in
HackEventLogger.set_rollout_flags
(ServerLocalConfig.to_rollout_flags local_config);
HackEventLogger.set_rollout_group
local_config.ServerLocalConfig.rollout_group;
let%lwt version = read_hhconfig_version () in
HackEventLogger.set_hhconfig_version
(Some (String_utils.lstrip version "^"));
let%lwt version_and_switch = read_hhconfig_version_and_switch () in
hhconfig_version_and_switch := version_and_switch;
state :=
Lost_server
{
Lost_env.editor_open_files = UriMap.empty;
uris_with_unsaved_changes = UriSet.empty;
uris_with_standalone_diagnostics = UriMap.empty;
current_hh_shell = None;
};
(* If editor sent 'trace: on' then that will turn on verbose_to_file. But we won't turn off
verbose here, since the command-line argument --verbose trumps initialization params. *)
begin
match initialize_params.Initialize.trace with
| Initialize.Off -> ()
| Initialize.Messages
| Initialize.Verbose ->
set_verbose_to_file ~ide_service ~env ~tracking_id true
end;
let result = do_initialize local_config in
respond_jsonrpc ~powered_by:Language_server id (InitializeResult result);
let (promise : unit Lwt.t) =
run_ide_service env !ide_service initialize_params None
in
ignore_promise_but_handle_failure
promise
~desc:"run-ide-after-init"
~terminate_on_failure:true;
(* Invariant: at all times after InitializeRequest, ide_service has
already been sent an "initialize" message. *)
let id = NumberId (Jsonrpc.get_next_request_id ()) in
let request = do_didChangeWatchedFiles_registerCapability () in
to_stdout (print_lsp_request id request);
(* TODO: our handler should really handle an error response properly *)
let handler _response state = Lwt.return state in
requests_outstanding :=
IdMap.add id (request, handler) !requests_outstanding;
if not (Sys_utils.deterministic_behavior_for_tests ()) then
Lsp_helpers.telemetry_log
to_stdout
("Version in hhconfig and switch=" ^ !hhconfig_version_and_switch);
Lwt.return_none
(* any request/notification if we haven't yet initialized *)
| (Pre_init, _) ->
raise
(Error.LspException
{
Error.code = Error.ServerNotInitialized;
message = "Server not yet initialized";
data = None;
})
| (Post_shutdown, _c) ->
raise
(Error.LspException
{
Error.code = Error.InvalidRequest;
message = "already received shutdown request";
data = None;
})
(* initialized notification *)
| (_, NotificationMessage InitializedNotification) -> Lwt.return_none
(* rage request *)
| (_, RequestMessage (id, RageRequestFB)) ->
let%lwt result = do_rageFB !state in
respond_jsonrpc ~powered_by:Language_server id (RageResultFB result);
Lwt.return_some (make_result_telemetry (List.length result))
| (_, NotificationMessage (DidChangeWatchedFilesNotification notification))
->
let changes =
List.filter_map
notification.DidChangeWatchedFiles.changes
~f:(fun change ->
let path = lsp_uri_to_path change.DidChangeWatchedFiles.uri in
(* This is just the file:///foo/bar uri turned into a string path /foo/bar.
There's nothing in VSCode/LSP spec to stipulate that the uris are
canonical paths file:///data/users/ljw/www-hg/foo.php or to
symlinked paths file:///home/ljw/www/foo.php (where ~/www -> /data/users/ljw/www-hg)
but experimentally the uris seem to be canonical paths. That's lucky
because if we had to turn a symlink of a deleted file file:///home/ljw/www/foo.php
into the actual canonical path /data/users/ljw/www-hg/foo.php then it'd be hard!
Anyway, because they refer to canonical paths, we can safely use [FindUtils.file_filter]
and [Relative_path.create_detect_prefix], both of which match string prefix on the
canonical root. *)
if FindUtils.file_filter path then
Some (Relative_path.create_detect_prefix path)
else
None)
|> Relative_path.Set.of_list
in
let%lwt () =
ide_rpc
ide_service
~env
~tracking_id
~ref_unblocked_time
(ClientIdeMessage.Did_change_watched_files changes)
in
Lwt.return_some
(make_result_telemetry (Relative_path.Set.cardinal changes))
(* Text document completion: "AutoComplete!" *)
| (_, RequestMessage (id, CompletionRequest params)) ->
let%lwt () = cancel_if_stale client timestamp short_timeout in
let%lwt result =
do_completion_local
ide_service
env
tracking_id
ref_unblocked_time
editor_open_files
params
in
respond_jsonrpc ~powered_by:Serverless_ide id (CompletionResult result);
Lwt.return_some
(make_result_telemetry (List.length result.Completion.items))
(* Resolve documentation for a symbol: "Autocomplete Docblock!" *)
| (_, RequestMessage (id, CompletionItemResolveRequest params)) ->
let%lwt () = cancel_if_stale client timestamp short_timeout in
let%lwt result =
do_resolve_local ide_service env tracking_id ref_unblocked_time params
in
respond_jsonrpc
~powered_by:Serverless_ide
id
(CompletionItemResolveResult result);
Lwt.return_none
(* Document highlighting in serverless IDE *)
| (_, RequestMessage (id, DocumentHighlightRequest params)) ->
let%lwt () = cancel_if_stale client timestamp short_timeout in
let%lwt result =
do_highlight_local
ide_service
env
tracking_id
ref_unblocked_time
editor_open_files
params
in
respond_jsonrpc
~powered_by:Serverless_ide
id
(DocumentHighlightResult result);
Lwt.return_some (make_result_telemetry (List.length result))
(* Hover docblocks in serverless IDE *)
| (_, RequestMessage (id, HoverRequest params)) ->
let%lwt () = cancel_if_stale client timestamp short_timeout in
let%lwt result =
do_hover_local
ide_service
env
tracking_id
ref_unblocked_time
editor_open_files
params
in
respond_jsonrpc ~powered_by:Serverless_ide id (HoverResult result);
let result_count =
match result with
| None -> 0
| Some { Hover.contents; _ } -> List.length contents
in
Lwt.return_some (make_result_telemetry result_count)
| (_, RequestMessage (id, DocumentSymbolRequest params)) ->
let%lwt () = cancel_if_stale client timestamp short_timeout in
let%lwt result =
do_documentSymbol_local
ide_service
env
tracking_id
ref_unblocked_time
editor_open_files
params
in
respond_jsonrpc
~powered_by:Serverless_ide
id
(DocumentSymbolResult result);
Lwt.return_some (make_result_telemetry (List.length result))
| (_, RequestMessage (id, WorkspaceSymbolRequest params)) ->
let%lwt () = cancel_if_stale client timestamp long_timeout in
let%lwt result =
do_workspaceSymbol_local
ide_service
env
tracking_id
ref_unblocked_time
params
in
respond_jsonrpc
~powered_by:Serverless_ide
id
(WorkspaceSymbolResult result);
Lwt.return_some (make_result_telemetry (List.length result))
| (_, RequestMessage (id, DefinitionRequest params)) ->
let%lwt () = cancel_if_stale client timestamp short_timeout in
let%lwt (result, _has_xhp_attribute) =
do_definition_local
ide_service
env
tracking_id
ref_unblocked_time
editor_open_files
params
in
respond_jsonrpc ~powered_by:Serverless_ide id (DefinitionResult result);
Lwt.return_some (make_result_telemetry (List.length result))
| (_, RequestMessage (id, TypeDefinitionRequest params)) ->
let%lwt () = cancel_if_stale client timestamp short_timeout in
let%lwt result =
do_typeDefinition_local
ide_service
env
tracking_id
ref_unblocked_time
editor_open_files
params
in
respond_jsonrpc
~powered_by:Serverless_ide
id
(TypeDefinitionResult result);
Lwt.return_some (make_result_telemetry (List.length result))
(* textDocument/references request *)
| (_, RequestMessage (id, FindReferencesRequest params)) ->
let%lwt () = cancel_if_stale client timestamp long_timeout in
let%lwt (new_state, result_telemetry) =
do_findReferences_local
!state
ide_service
env
metadata
ref_unblocked_time
editor_open_files
params
id
in
state := new_state;
Lwt.return_some result_telemetry
(* textDocument/implementation request *)
| (_, RequestMessage (id, ImplementationRequest params)) ->
let%lwt () = cancel_if_stale client timestamp long_timeout in
let%lwt (new_state, result_telemetry) =
do_goToImplementation_local
!state
ide_service
env
metadata
tracking_id
ref_unblocked_time
editor_open_files
params
id
in
state := new_state;
Lwt.return_some result_telemetry
(* textDocument/rename request *)
| (_, RequestMessage (id, RenameRequest params)) ->
let%lwt () = cancel_if_stale client timestamp long_timeout in
let%lwt (new_state, result_telemetry) =
do_documentRename_local
!state
ide_service
env
metadata
ref_unblocked_time
editor_open_files
params
id
in
state := new_state;
Lwt.return_some result_telemetry
(* Resolve documentation for a symbol: "Autocomplete Docblock!" *)
| (_, RequestMessage (id, SignatureHelpRequest params)) ->
let%lwt () = cancel_if_stale client timestamp short_timeout in
let%lwt result =
do_signatureHelp_local
ide_service
env
tracking_id
ref_unblocked_time
editor_open_files
params
in
respond_jsonrpc ~powered_by:Serverless_ide id (SignatureHelpResult result);
let result_count =
match result with
| None -> 0
| Some { SignatureHelp.signatures; _ } -> List.length signatures
in
Lwt.return_some (make_result_telemetry result_count)
(* textDocument/codeAction request *)
| (_, RequestMessage (id, CodeActionRequest params)) ->
let%lwt () = cancel_if_stale client timestamp short_timeout in
let%lwt (result, file_path, errors_opt) =
do_codeAction_local
ide_service
env
tracking_id
ref_unblocked_time
editor_open_files
params
in
respond_jsonrpc
~powered_by:Serverless_ide
id
(CodeActionResult (result, params));
begin
match errors_opt with
| None -> ()
| Some errors ->
state := publish_errors_if_standalone !state file_path errors
end;
Lwt.return_some (make_result_telemetry (List.length result))
(* codeAction/resolve request *)
| (_, RequestMessage (id, CodeActionResolveRequest params)) ->
let CodeActionResolveRequest.{ data = code_action_request_params; title }
=
params
in
let%lwt () = cancel_if_stale client timestamp short_timeout in
let%lwt result =
do_codeAction_resolve_local
ide_service
env
tracking_id
ref_unblocked_time
editor_open_files
code_action_request_params
~resolve_title:title
in
respond_jsonrpc
~powered_by:Serverless_ide
id
(CodeActionResolveResult result);
let result_extra_data =
Telemetry.create () |> Telemetry.string_ ~key:"title" ~value:title
in
Lwt.return_some (make_result_telemetry 1 ~result_extra_data)
(* textDocument/formatting *)
| (_, RequestMessage (id, DocumentFormattingRequest params)) ->
let result = do_documentFormatting editor_open_files params in
respond_jsonrpc
~powered_by:Language_server
id
(DocumentFormattingResult result);
Lwt.return_some (make_result_telemetry (List.length result))
(* textDocument/rangeFormatting *)
| (_, RequestMessage (id, DocumentRangeFormattingRequest params)) ->
let result = do_documentRangeFormatting editor_open_files params in
respond_jsonrpc
~powered_by:Language_server
id
(DocumentRangeFormattingResult result);
Lwt.return_some (make_result_telemetry (List.length result))
(* textDocument/onTypeFormatting. TODO(T155870670): remove this *)
| (_, RequestMessage (id, DocumentOnTypeFormattingRequest params)) ->
let%lwt () = cancel_if_stale client timestamp short_timeout in
let result = do_documentOnTypeFormatting editor_open_files params in
respond_jsonrpc
~powered_by:Language_server
id
(DocumentOnTypeFormattingResult result);
Lwt.return_some (make_result_telemetry (List.length result))
(* textDocument/willSaveWaitUntil request *)
| (_, RequestMessage (id, WillSaveWaitUntilRequest params)) ->
let result = do_willSaveWaitUntil editor_open_files params in
respond_jsonrpc
~powered_by:Language_server
id
(WillSaveWaitUntilResult result);
Lwt.return_some (make_result_telemetry (List.length result))
(* editor buffer events *)
| ( _,
NotificationMessage
( DidOpenNotification _ | DidChangeNotification _
| DidCloseNotification _ | DidSaveNotification _ ) ) ->
let%lwt () =
handle_editor_buffer_message
~env
~state
~client
~ide_service
~metadata
~ref_unblocked_time
~message
in
Lwt.return_none
(* typeHierarchy request *)
| (_, RequestMessage (id, TypeHierarchyRequest params)) ->
let%lwt () = cancel_if_stale client timestamp short_timeout in
let%lwt result =
do_typeHierarchy_local
ide_service
env
tracking_id
ref_unblocked_time
editor_open_files
params
in
respond_jsonrpc ~powered_by:Serverless_ide id (TypeHierarchyResult result);
let result_count =
match result with
| None -> 0
| Some _result -> 1
in
Lwt.return_some (make_result_telemetry result_count)
(* unhandled *)
| (Lost_server _, _) ->
raise
(Error.LspException
{
Error.code = Error.MethodNotFound;
message =
"not implemented: " ^ Lsp_fmt.message_name_to_string message;
data = None;
})
in
Lwt.return result_telemetry_opt
(** Process and respond to a notification from clientIdeDaemon, and update [state] accordingly. *)
let handle_daemon_notification
~(env : env)
~(state : state ref)
~(client : Jsonrpc.t)
~(ide_service : ClientIdeService.t ref)
~(notification : ClientIdeMessage.notification)
~(ref_unblocked_time : float ref) : result_telemetry option Lwt.t =
(* In response to ide_service notifications we have these goals:
* in case of Done_init failure, we have to announce the failure to the user
* in case of Done_init success, we need squiggles for open files
* in a few other cases, we send telemetry events so that test harnesses
get insight into the internal state of the ide_service
* after every single event, including client_ide_notification events,
our caller queries the ide_service for what status it wants to display to
the user, so these notifications have the goal of triggering that refresh. *)
match notification with
| ClientIdeMessage.Done_init (Ok p) ->
Lsp_helpers.telemetry_log to_stdout "[client-ide] Finished init: ok";
Lsp_helpers.telemetry_log
to_stdout
(Printf.sprintf
"[client-ide] Initialized; %d file changes to process"
p.ClientIdeMessage.Processing_files.total);
let editor_open_files =
(match get_editor_open_files !state with
| Some files -> files
| None -> UriMap.empty)
|> UriMap.elements
in
let%lwt () =
Lwt_list.iter_s
(fun (uri, { TextDocumentItem.text = file_contents; _ }) ->
let%lwt new_state =
send_file_to_ide_and_get_errors_if_needed
~env
~client
~ide_service
~state
~uri
~file_contents
~ref_unblocked_time
~tracking_id:(Random_id.short_string ())
in
state := new_state;
Lwt.return_unit)
editor_open_files
in
Lwt.return_none
| ClientIdeMessage.Done_init (Error error_data) ->
log_debug "<-- done_init";
Lsp_helpers.telemetry_log to_stdout "[client-ide] Finished init: failure";
let%lwt () = announce_ide_failure error_data in
Lwt.return_none
| ClientIdeMessage.Processing_files _ ->
(* used solely for triggering a refresh of status by our caller; nothing
for us to do here. *)
Lwt.return_none
| ClientIdeMessage.Done_processing ->
Lsp_helpers.telemetry_log
to_stdout
"[client-ide] Done processing file changes";
Lwt.return_none
(** Called once a second but only when there are no pending messages from client,
hh_server, or clientIdeDaemon. *)
let handle_tick ~(state : state ref) : result_telemetry option Lwt.t =
EventLogger.recheck_disk_files ();
HackEventLogger.Memory.profile_if_needed ();
let%lwt () = try_open_errors_file ~state in
let (promise : unit Lwt.t) = EventLoggerLwt.flush () in
ignore_promise_but_handle_failure
promise
~desc:"tick-event-flush"
~terminate_on_failure:false;
Lwt.return_none
let main (args : args) ~(init_id : string) : Exit_status.t Lwt.t =
Printexc.record_backtrace true;
from := args.from;
HackEventLogger.set_from !from;
let env = { args; init_id } in
if env.args.verbose then begin
Hh_logger.Level.set_min_level_stderr Hh_logger.Level.Debug;
Hh_logger.Level.set_min_level_file Hh_logger.Level.Debug
end else begin
Hh_logger.Level.set_min_level_stderr Hh_logger.Level.Error;
Hh_logger.Level.set_min_level_file Hh_logger.Level.Info
end;
(* The --verbose flag in env.verbose is the only thing that controls verbosity
to stderr. Meanwhile, verbosity-to-file can be altered dynamically by the user.
Why are they different? because we should write to stderr under a test harness,
but we should never write to stderr when invoked by VSCode - it's not even guaranteed
to drain the stderr pipe.
WARNING: we can't log yet, since until we've received "initialize" request,
we don't yet know which path to log to. *)
let ide_service =
ref
(ClientIdeService.make
{
ClientIdeMessage.init_id = env.init_id;
verbose_to_stderr = env.args.verbose;
verbose_to_file = env.args.verbose;
})
in
background_status_refresher ide_service;
let client = Jsonrpc.make_t () in
let deferred_action : (unit -> unit Lwt.t) option ref = ref None in
let state = ref Pre_init in
let ref_event = ref None in
let ref_unblocked_time = ref (Unix.gettimeofday ()) in
(* ref_unblocked_time is the time at which we're no longer blocked on either
* clientLsp message-loop or hh_server, and can start actually handling.
* Everything that blocks will update this variable. *)
let process_next_event () : unit Lwt.t =
try%lwt
let%lwt () =
match !deferred_action with
| Some deferred_action ->
let%lwt () = deferred_action () in
Lwt.return_unit
| None -> Lwt.return_unit
in
deferred_action := None;
let%lwt event = get_next_event state client ide_service in
if not (is_tick event) then
log_debug "next event: %s" (event_to_string event);
ref_event := Some event;
ref_unblocked_time := Unix.gettimeofday ();
(* we keep track of all open files and their contents *)
state := track_open_and_recent_files !state event;
(* we keep track of all files that have unsaved changes in them *)
state := track_edits_if_necessary !state event;
(* this is the main handler for each message*)
let%lwt result_telemetry_opt =
match event with
| Client_message (metadata, message) ->
handle_client_message
~env
~state
~client
~ide_service
~metadata
~message
~ref_unblocked_time
| Daemon_notification notification ->
handle_daemon_notification
~env
~state
~client
~ide_service
~notification
~ref_unblocked_time
| Errors_file result ->
handle_errors_file_item ~state ~ide_service result
| Refs_file result -> Lwt.return (handle_refs_file_items ~state result)
| Shell_out_complete (result, triggering_request, shellable_type) ->
Lwt.return
(handle_shell_out_complete result triggering_request shellable_type)
| Tick -> handle_tick ~state
in
(* for LSP requests and notifications, we keep a log of what+when we responded.
INVARIANT: every LSP request gets either a response logged here,
or an error logged by one of the handlers below. *)
log_response_if_necessary event result_telemetry_opt !ref_unblocked_time;
Lwt.return_unit
with
| Client_fatal_connection_exception { Marshal_tools.stack; message } ->
let e = make_lsp_error ~stack message in
hack_log_error !ref_event e Error_from_client_fatal !ref_unblocked_time;
Lsp_helpers.telemetry_error to_stdout (message ^ ", from_client\n" ^ stack);
let () = exit_fail () in
Lwt.return_unit
| Client_recoverable_connection_exception { Marshal_tools.stack; message }
->
let e = make_lsp_error ~stack message in
hack_log_error
!ref_event
e
Error_from_client_recoverable
!ref_unblocked_time;
Lsp_helpers.telemetry_error to_stdout (message ^ ", from_client\n" ^ stack);
Lwt.return_unit
| (Daemon_nonfatal_exception e | Error.LspException e) as exn ->
let exn = Exception.wrap exn in
let error_source =
match (e.Error.code, Exception.unwrap exn) with
| (Error.RequestCancelled, _) -> Error_from_lsp_cancelled
| (_, Daemon_nonfatal_exception _) -> Error_from_daemon_recoverable
| (_, _) -> Error_from_lsp_misc
in
let e =
make_lsp_error ~data:e.Error.data ~code:e.Error.code e.Error.message
in
respond_to_error !ref_event e;
hack_log_error !ref_event e error_source !ref_unblocked_time;
Lwt.return_unit
| exn ->
let exn = Exception.wrap exn in
let e =
make_lsp_error
~stack:(Exception.get_backtrace_string exn)
~current_stack:false
(Exception.get_ctor_string exn)
in
respond_to_error !ref_event e;
hack_log_error !ref_event e Error_from_lsp_misc !ref_unblocked_time;
Lwt.return_unit
in
let rec main_loop () : unit Lwt.t =
let%lwt () = process_next_event () in
main_loop ()
in
let%lwt () = main_loop () in
Lwt.return Exit_status.No_error |
OCaml Interface | hhvm/hphp/hack/src/client/clientLsp.mli | (*
* 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.
*
*)
(** The command-line arguments for "hh_client lsp" *)
type args = {
from: string;
(** The source where the client was spawned from, i.e. nuclide, vim, emacs, etc. *)
config: (string * string) list; (** --config overrides at the command-line *)
ignore_hh_version: bool;
naming_table: string option;
verbose: bool;
(** Extra logging, including logs per LSP message (voluminous!) *)
root_from_cli: Path.t;
(** clientLsp only ever uses the root path provided to us in the initialize request.
This field here isn't that! it's a record of what root was derived upon launch
(well before the initialize request), either from an argument if supplied, or
otherwise by searching from the CWD. We use this field solely to validate
whether there's a mismatch between the project root implied by how we launched,
and the project root supplied by initialize, in case we want to warn about
any difference. *)
}
(** This is the main loop for processing incoming Lsp client requests,
and incoming server notifications. Never returns. *)
val main : args -> init_id:string -> Exit_status.t Lwt.t |
OCaml | hhvm/hphp/hack/src/client/clientMethodJumps.ml | (*
* Copyright (c) 2015, 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 MethodJumps = ServerCommandTypes.Method_jumps
let pos_to_json pos =
let (line, start, end_) = Pos.info_pos pos in
Hh_json.JSON_Object
[
("file", Hh_json.JSON_String (Pos.filename pos));
(* we can't use Pos.json *)
("line", Hh_json.int_ line);
("char_start", Hh_json.int_ start);
("char_end", Hh_json.int_ end_);
]
let cls_or_mthd_to_json name pos p_name =
Hh_json.JSON_Object
[
("name", Hh_json.JSON_String (Utils.strip_ns name));
("pos", pos_to_json pos);
("parent_name", Hh_json.JSON_String (Utils.strip_ns p_name));
]
let to_json input =
let entries =
List.map input ~f:(fun res ->
Hh_json.JSON_Object
[
( "origin",
cls_or_mthd_to_json
res.MethodJumps.orig_name
res.MethodJumps.orig_pos
res.MethodJumps.orig_p_name );
( "destination",
cls_or_mthd_to_json
res.MethodJumps.dest_name
res.MethodJumps.dest_pos
res.MethodJumps.dest_p_name );
])
in
Hh_json.JSON_Array entries
let print_json res =
print_endline (Hh_json.json_to_string (to_json res));
()
let go res find_children output_json =
if output_json then
print_json res
else
MethodJumps.print_readable res ~find_children |
OCaml | hhvm/hphp/hack/src/client/clientOutline.ml | (*
* Copyright (c) 2015, 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 print_json res =
Nuclide_rpc_message_printer.(outline_response_to_json res |> print_json)
let go res output_json =
if output_json then
print_json res
else
FileOutline.print res
let print_json_definition res =
Nuclide_rpc_message_printer.(symbol_by_id_response_to_json res |> print_json)
let print_readable_definition res =
match res with
| Some res -> FileOutline.print_def "" res
| None -> print_endline "None" |
OCaml | hhvm/hphp/hack/src/client/clientRename.ml | (*
* Copyright (c) 2015, 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 ClientEnv
let get_pos = ServerRenameTypes.get_pos
let compare_result = ServerRenameTypes.compare_result
let apply_patches_to_string old_content patch_list =
let buf = Buffer.create (String.length old_content) in
let patch_list = List.sort ~compare:compare_result patch_list in
ServerRenameTypes.write_patches_to_buffer buf old_content patch_list;
Buffer.contents buf
let apply_patches_to_file fn patch_list =
let old_content = Sys_utils.cat fn in
let new_file_contents = apply_patches_to_string old_content patch_list in
ServerRenameTypes.write_string_to_file fn new_file_contents
let list_to_file_map =
List.fold_left ~f:ServerRenameTypes.map_patches_to_filename ~init:SMap.empty
let plural count one many =
let obj =
if count = 1 then
one
else
many
in
string_of_int count ^ " " ^ obj
let apply_patches patches =
let file_map = list_to_file_map patches in
SMap.iter apply_patches_to_file file_map;
print_endline
("Rewrote " ^ plural (SMap.cardinal file_map) "file" "files" ^ ".")
let patch_to_json res =
let (type_, replacement) =
match res with
| ServerRenameTypes.Insert patch -> ("insert", patch.ServerRenameTypes.text)
| ServerRenameTypes.Replace patch ->
("replace", patch.ServerRenameTypes.text)
| ServerRenameTypes.Remove _ -> ("remove", "")
in
let pos = get_pos res in
let (char_start, char_end) = Pos.info_raw pos in
let (line, start, end_) = Pos.info_pos pos in
Hh_json.JSON_Object
[
("char_start", Hh_json.int_ char_start);
("char_end", Hh_json.int_ char_end);
("line", Hh_json.int_ line);
("col_start", Hh_json.int_ start);
("col_end", Hh_json.int_ end_);
("patch_type", Hh_json.JSON_String type_);
("replacement", Hh_json.JSON_String replacement);
]
let patches_to_json_string patches =
let file_map = list_to_file_map patches in
let entries =
SMap.fold
begin
fun fn patch_list acc ->
Hh_json.JSON_Object
[
("filename", Hh_json.JSON_String fn);
( "patches",
Hh_json.JSON_Array (List.map patch_list ~f:patch_to_json) );
]
:: acc
end
file_map
[]
in
Hh_json.json_to_string (Hh_json.JSON_Array entries)
let print_patches_json patches = print_endline (patches_to_json_string patches)
let go_ide_from_patches patches json =
if json then
print_patches_json patches
else
apply_patches patches
let go
(conn : unit -> ClientConnect.conn Lwt.t)
~(desc : string)
(args : client_check_env)
(mode : rename_mode)
~(before : string)
~(after : string) : unit Lwt.t =
let command =
match mode with
| Class -> ServerRenameTypes.ClassRename (before, after)
| Function ->
ServerRenameTypes.FunctionRename { old_name = before; new_name = after }
| Method ->
let befores = Str.split (Str.regexp "::") before in
if List.length befores <> 2 then
failwith "Before string should be of the format class::method";
let afters = Str.split (Str.regexp "::") after in
if List.length afters <> 2 then
failwith "After string should be of the format class::method";
let before_class = List.hd_exn befores in
let before_method = List.hd_exn (List.tl_exn befores) in
let after_class = List.hd_exn afters in
let after_method = List.hd_exn (List.tl_exn afters) in
if not (String.equal before_class after_class) then (
Printf.printf "%s %s\n" before_class after_class;
failwith "Before and After classname must match"
) else
ServerRenameTypes.MethodRename
{
class_name = before_class;
old_name = before_method;
new_name = after_method;
}
| _ -> failwith "Unexpected Mode"
in
let%lwt patches =
ClientConnect.rpc_with_retry conn ~desc @@ ServerCommandTypes.RENAME command
in
if args.output_json then
print_patches_json patches
else
apply_patches patches;
Lwt.return_unit |
OCaml Interface | hhvm/hphp/hack/src/client/clientRename.mli | (*
* 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.
*
*)
val apply_patches : ServerRenameTypes.patch list -> unit
val patches_to_json_string : ServerRenameTypes.patch list -> string
val print_patches_json : ServerRenameTypes.patch list -> unit
val go :
(unit -> ClientConnect.conn Lwt.t) ->
desc:string ->
ClientEnv.client_check_env ->
ClientEnv.rename_mode ->
before:string ->
after:string ->
unit Lwt.t
val go_ide_from_patches : ServerRenameTypes.patch list -> bool -> unit |
OCaml | hhvm/hphp/hack/src/client/clientRestart.ml | (*
* Copyright (c) 2015, 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 main (env : ClientStart.env) : Exit_status.t Lwt.t =
HackEventLogger.set_from env.ClientStart.from;
HackEventLogger.client_restart
~data:
(Config_file.Utils.parse_hhconfig_and_hh_conf_to_json
~root:env.ClientStart.root
~server_local_config_path:ServerLocalConfig.system_config_path);
if
MonitorConnection.server_exists (ServerFiles.lock_file env.ClientStart.root)
then
ClientStop.kill_server env.ClientStart.root env.ClientStart.from
else
Printf.eprintf
"Warning: no server to restart for %s\n%!"
(Path.to_string env.ClientStart.root);
ClientStart.start_server env;
Lwt.return Exit_status.No_error |
OCaml | hhvm/hphp/hack/src/client/clientResultPrinter.ml | (*
* Copyright (c) 2018, 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 Hh_json
module type Result_printer = sig
type t
val go : (t, string) result -> bool -> unit
end
module type Result_converter = sig
type t
val to_string : t -> string
val to_json : t -> Hh_json.json
end
module Unit_converter = struct
type t = unit
let to_string : t -> string = (fun () -> "")
let to_json : t -> Hh_json.json = (fun () -> JSON_String "ok")
end
module Int_converter = struct
type t = int
let to_string : t -> string = string_of_int
let to_json : t -> Hh_json.json = (fun i -> JSON_Number (string_of_int i))
end
module Make (Converter : Result_converter) :
Result_printer with type t = Converter.t = struct
type t = Converter.t
let to_json result =
let result =
match result with
| Ok result -> ("result", Converter.to_json result)
| Error s -> ("error_message", JSON_String s)
in
JSON_Object [result]
let print_json res = print_endline (Hh_json.json_to_string (to_json res))
let print_readable = function
| Ok result -> Printf.printf "%s" (Converter.to_string result)
| Error s ->
let msg = Printf.sprintf "Error: %s" s in
print_endline msg;
exit 1
let go res output_json =
if output_json then
print_json res
else
print_readable res
end
module Unit_printer = Make (Unit_converter)
module Int_printer = Make (Int_converter) |
OCaml | hhvm/hphp/hack/src/client/clientSavedStateProjectMetadata.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.
*
*)
exception GetProjectMetadataError of string
let main (env : ClientEnv.client_check_env) (config : ServerLocalConfig.t) :
Exit_status.t Lwt.t =
let {
ClientEnv.root;
ignore_hh_version;
saved_state_ignore_hhconfig = _;
config = _;
autostart = _;
custom_hhi_path = _;
custom_telemetry_data = _;
error_format = _;
force_dormant_start = _;
from = _;
show_spinner = _;
gen_saved_ignore_type_errors = _;
paths = _;
log_inference_constraints = _;
max_errors = _;
mode = _;
no_load = _;
save_64bit = _;
save_human_readable_64bit_dep_map = _;
output_json = _;
prechecked = _;
mini_state = _;
remote = _;
sort_results = _;
stdin_name = _;
deadline = _;
watchman_debug_logging = _;
allow_non_opt_build = _;
desc = _;
} =
env
in
let%lwt result =
State_loader_lwt.get_project_metadata
~progress_callback:(fun _ -> ())
~saved_state_type:Saved_state_loader.Naming_and_dep_table_distc
~repo:root
~ignore_hh_version
~opts:config.ServerLocalConfig.saved_state
in
match result with
| Error (error, _telemetry) ->
raise
(GetProjectMetadataError
(Saved_state_loader.LoadError.debug_details_of_error error))
| Ok (project_metadata, _telemetry) ->
Printf.printf "%s\n%!" project_metadata;
Lwt.return Exit_status.No_error |
OCaml | hhvm/hphp/hack/src/client/clientSearch.ml | (*
* Copyright (c) 2015, 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 SUtils = SearchUtils
let print_results (results : SearchUtils.result) : unit =
List.iter results ~f:(fun res ->
let pos_string = Pos.string res.SUtils.pos in
let desc_string = SearchUtils.kind_to_string res.SUtils.result_type in
print_endline
(pos_string ^ " " ^ Utils.strip_ns res.SUtils.name ^ ", " ^ desc_string))
let print_results_json (results : SearchUtils.result) : unit =
let results =
Hh_json.JSON_Array (List.map results ~f:ServerSearch.result_to_json)
in
print_endline (Hh_json.json_to_string results)
let go (results : SearchUtils.result) (output_json : bool) : unit =
if output_json then
print_results_json results
else
print_results results |
OCaml | hhvm/hphp/hack/src/client/clientSpinner.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
let ascii_chars = [| "-"; "\\"; "|"; "/" |]
(** Some terminals display the emoji using only one column, even though they
may take up two columns, and put the cursor immediately after it in an
illegible manner. We append an extra space to separate the cursor from the emoji. *)
let emoji_chars =
[|
"\xF0\x9F\x98\xA1 ";
(* Angry Face *)
"\xF0\x9F\x98\x82 ";
(* Face With Tears of Joy *)
"\xF0\x9F\xA4\x94 ";
(* Thinking Face *)
"\xF0\x9F\x92\xAF ";
(* Hundred Points *)
|]
type message =
| Init
(** There has not yet been a call to [report (Some s)], so there's nothing to show *)
| Message of {
text: string;
(** This reflects the most recent call to [report (Some text)].
It is displayed as "hh_server is busy: [<s>] <spinner>". *)
is_hidden: bool;
(** This is true when [report None] has been called more recently than [report Some].
It means that the text won't be displayed on stderr.
(However, the text is still used for heartbeat and logging). *)
start_time: float;
(** the time of the oldest [report (Some text)] with no other [report (Some other_text)] since then. *)
}
type state = {
message: message;
to_stderr: bool; (** should this be displayed on stderr? *)
angery_reaccs_only: bool; (* do we use emoji_chars or ascii_chars? *)
index: int; (** which of the four chars is used as spinner *)
}
(** The current state of the spinner. Invariant: whatever this current state implies
is reflected in stderr -- either some message, or nothing. *)
let state : state ref =
ref
{ message = Init; to_stderr = false; angery_reaccs_only = false; index = 0 }
let get_latest_report () : (string * float) option =
let now = Unix.gettimeofday () in
match !state.message with
| Message { text; is_hidden = false; start_time } ->
Some (text, now -. start_time)
| Message { text; is_hidden = true; start_time } ->
Some ("[hidden] " ^ text, now -. start_time)
| Init -> None
(** Used so that when we Hh_logger.log a spinner change, we can show wall-time. *)
let start_time : float = Unix.gettimeofday ()
let start_heartbeat_telemetry () : unit =
let rec loop n : 'a =
let%lwt _ = Lwt_unix.sleep 1.0 in
HackEventLogger.spinner_heartbeat n ~spinner:(get_latest_report ());
loop (n + 1)
in
let _future = loop 1 in
()
(** This updates stderr to reflect new_state. This might involve clearing
the old stderr (if there was anything on it), and displaying a new thing
on stderr (if needed). *)
let update_stderr (old_state : state) ~(new_state : state) : unit =
let was_present =
match old_state.message with
| Message { is_hidden = false; _ } when old_state.to_stderr -> true
| _ -> false
in
if was_present then Tty.print_clear_line stderr;
match new_state.message with
| Message { is_hidden = false; text; _ } when new_state.to_stderr ->
let chars =
if new_state.angery_reaccs_only then
emoji_chars
else
ascii_chars
in
let spinner = Array.get chars new_state.index in
Tty.eprintf "hh_server is busy: [%s] %s%!" text spinner
| _ -> ()
(** Never-ending background process to update the spinner on stderr once a second.
This is kicked off by the first time someone calls [report]. *)
let rec animate () : unit Lwt.t =
let%lwt () = Lwt_unix.sleep 1.0 in
let new_state = { !state with index = (!state.index + 1) % 4 } in
update_stderr !state ~new_state;
state := new_state;
animate ()
(** Mutable field so that [report] knows whether it needs to kick off [animate] in the background. *)
let animator : unit Lwt.t option ref = ref None
let report ~(to_stderr : bool) ~(angery_reaccs_only : bool) :
string option -> unit =
fun next ->
if Option.is_none !animator then animator := Some (animate ());
let message =
match (!state.message, next) with
| (Message { text = prev; start_time; _ }, Some next)
when String.equal prev next ->
(* text is unchanged. But if it was hidden before, now let it be shown *)
Message { text = next; is_hidden = false; start_time }
| (_, Some next) ->
(* text has changed *)
Hh_logger.log
"spinner %0.1fs: [%s]"
(Unix.gettimeofday () -. start_time)
next;
HackEventLogger.spinner_change ~spinner:(get_latest_report ()) ~next;
Message
{ text = next; is_hidden = false; start_time = Unix.gettimeofday () }
| (Message { text; start_time; _ }, None) ->
(* pre-existing text gets hidden *)
Message { text; start_time; is_hidden = true }
| (Init, None) ->
(* no-op, because we're hiding when no text has yet been reported *)
Init
in
let new_state = { !state with message; to_stderr; angery_reaccs_only } in
update_stderr !state ~new_state;
state := new_state;
() |
OCaml Interface | hhvm/hphp/hack/src/client/clientSpinner.mli | (*
* 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.
*
*)
(** The caller should invoke [start_heartbeat_telemetry ()] once, as close as possible
to process start. From this point until process termination, it will log once
a second to HackEventLogger what the latest non-None report is.
(It's not called automatically because sometimes the startup path might determine
that it doesn't want heartbeats. *)
val start_heartbeat_telemetry : unit -> unit
(** [report ~to_stderr ~angery_reaccs_only message_opt] is used to report progress:
* Heartbeat: if [message_opt] is [Some] then all subsequent heartbeats will report
this [message_opt] to telemetry, at least until the next time [report] is invoked
* Hh_logger: if [message_opt] is [Some], and differs from what was previously reported,
then it will be written to Hh_logger i.e. to `$(hh --client-logname)`.
* Stderr: if [to_stderr] is true and [message_opt] is [Some] then it will be displayed
on stderr with an animated spinner (which continues to animate automatically, even if
you don't call [report] again).
* Use [message_opt=None] to erase the spinner from stderr. This won't be written to the log.
It won't affect future heartbeats, nor [get_latest_report]. The assumption is that
if someone erases the spinner, they do so only temporarily. *)
val report : to_stderr:bool -> angery_reaccs_only:bool -> string option -> unit
(** For telemetry purposes, this is the most recent non-None report,
and how long since it was first reported. *)
val get_latest_report : unit -> (string * float) option |
OCaml | hhvm/hphp/hack/src/client/clientStart.ml | (*
* Copyright (c) 2015, 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
(** What is the path to the hh_server binary?
1. If HH_SERVER_PATH environment variable is defined, use this (even if it doesn't exist on disk!)
2. Otherwise, if "dirname(realpath(executable_name))/hh_server[.exe]" exists then use this
3. Otherwise, use unqualified "hh_server[.exe]" (hence search on PATH).
The third case is currently what happens for "hh switch buck2" *)
let get_hhserver_path () =
match Sys.getenv_opt "HH_SERVER_PATH" with
| Some p ->
Hh_logger.log "For hh_server path, using HH_SERVER_PATH=%s" p;
p
| None ->
let exe_name =
if Sys.win32 then
"hh_server.exe"
else
"hh_server"
in
(* Path.executable_name is an alias for Sys.executable_name. Its documentation is quite vague:
"This name may be absolute or relative to the current directory, depending on the platform
and whether the program was compiled to bytecode or a native executable." In my testing
on native ocaml binaries on CentOS, it produces the fully-qualified realpath of the executable,
i.e. it digs through symlinks. *)
let server_next_to_client =
Path.concat (Path.dirname Path.executable_name) exe_name |> Path.to_string
in
if Sys.file_exists server_next_to_client then begin
Hh_logger.log
"For hh_server path, found it adjacent to %s"
(Path.executable_name |> Path.to_string);
server_next_to_client
end else begin
Hh_logger.log
"For hh_server path, will do unqualified search for %s"
exe_name;
exe_name
end
type env = {
root: Path.t;
from: string;
no_load: bool;
watchman_debug_logging: bool;
log_inference_constraints: bool;
silent: bool;
exit_on_failure: bool;
ignore_hh_version: bool;
save_64bit: string option;
save_human_readable_64bit_dep_map: string option;
saved_state_ignore_hhconfig: bool;
prechecked: bool option;
mini_state: string option;
config: (string * string) list;
custom_hhi_path: string option;
custom_telemetry_data: (string * string) list;
allow_non_opt_build: bool;
}
(* Sometimes systemd-run is available but we can't use it. For example, the
* systemd might not have a proper working user session, so we might not be
* able to run commands via systemd-run as a user process *)
let can_run_systemd () =
if not Sys.unix then
false
else
(* if we're on Unix, verify systemd-run is in the path *)
let systemd_binary =
try
Unix.open_process_in "which systemd-run 2> /dev/null"
|> In_channel.input_line
with
| _ -> None
in
if is_none systemd_binary then
false
else
(* Use `timeout` in case it hangs mysteriously.
* `--quiet` only suppresses stdout. *)
let ic =
Unix.open_process_in
"timeout 1 systemd-run --scope --quiet --user -- true 2> /dev/null"
in
(* If all goes right, `systemd-run` will return immediately with exit code 0
* and run `true` asynchronously as a service. If it goes wrong, it will exit
* with a non-zero exit code *)
match Unix.close_process_in ic with
| Unix.WEXITED 0 -> true
| _ -> false
let start_server (env : env) =
let {
root;
from;
no_load;
watchman_debug_logging;
log_inference_constraints;
silent;
exit_on_failure;
ignore_hh_version;
save_64bit;
save_human_readable_64bit_dep_map;
saved_state_ignore_hhconfig;
prechecked;
mini_state;
config;
custom_hhi_path;
custom_telemetry_data;
allow_non_opt_build;
} =
env
in
(* Create a pipe for synchronization with the server: we will wait
until the server finishes its initialisation phase. *)
let (in_fd, out_fd) = Unix.pipe () in
Unix.set_close_on_exec in_fd;
let ic = Unix.in_channel_of_descr in_fd in
let serialize_key_value_options
(option : string) (keyvalues : (string * string) list) =
keyvalues
|> List.map ~f:(fun (key, value) ->
[| option; Printf.sprintf "%s=%s" key value |])
|> Array.concat
in
let hh_server = get_hhserver_path () in
let hh_server_args =
Array.concat
[
[| hh_server; "-d"; Path.to_string root |];
(if String.equal from "" then
[||]
else
[| "--from"; from |]);
(match mini_state with
| None -> [||]
| Some state -> [| "--with-mini-state"; state |]);
(if no_load then
[| "--no-load" |]
else
[||]);
(if watchman_debug_logging then
[| "--watchman-debug-logging" |]
else
[||]);
(if log_inference_constraints then
[| "--log-inference-constraints" |]
else
[||]);
(* If the client starts up a server monitor process, the output of that
* bootup is passed to this FD - so this FD needs to be threaded
* through the server monitor process then to the typechecker process.
*
* Note: Yes, the FD is available in the monitor process as well, but
* it doesn't, and shouldn't, use it. *)
[| "--waiting-client"; string_of_int (Handle.get_handle out_fd) |];
(if ignore_hh_version then
[| "--ignore-hh-version" |]
else
[||]);
(if saved_state_ignore_hhconfig then
[| "--saved-state-ignore-hhconfig" |]
else
[||]);
(match save_64bit with
| None -> [||]
| Some dest -> [| "--save-64bit"; dest |]);
(match save_human_readable_64bit_dep_map with
| None -> [||]
| Some dest -> [| "--save-human-readable-64bit-dep-map"; dest |]);
[||];
(match prechecked with
| Some true -> [| "--prechecked" |]
| _ -> [||]);
(match prechecked with
| Some false -> [| "--no-prechecked" |]
| _ -> [||]);
serialize_key_value_options "--config" config;
(match custom_hhi_path with
| None -> [||]
| Some dest -> [| "--custom-hhi-path"; dest |]);
serialize_key_value_options
"--custom-telemetry-data"
custom_telemetry_data;
(if allow_non_opt_build then
[| "--allow-non-opt-build" |]
else
[||]);
]
in
let (stdin, stdout, stderr) =
if silent then
let nfd = Unix.openfile Sys_utils.null_path [Unix.O_RDWR] 0 in
(nfd, nfd, nfd)
else
Unix.(stdin, stdout, stderr)
in
try
let (exe, args) =
if can_run_systemd () then
(* launch command
* systemd-run (creates a transient cgroup)
* --scope (allows synchronous execution of hh_server)
* --user (specifies this to be a user instance)
* --quiet (suppresses output to stdout)
* --slice=hack.slice (puts created units under hack.slice)
* hh_server <hh_server args>
*)
let systemd_exe = "systemd-run" in
let systemd_args =
[|
systemd_exe; "--scope"; "--user"; "--quiet"; "--slice=hack.slice";
|]
in
(systemd_exe, Array.concat [systemd_args; hh_server_args])
else
(hh_server, hh_server_args)
in
if not silent then
Printf.eprintf
"Server launched with the following command:\n\t%s\n%!"
(String.concat
~sep:" "
(Array.to_list (Array.map ~f:Filename.quote args)));
let server_pid = Unix.create_process exe args stdin stdout stderr in
Unix.close out_fd;
match Sys_utils.waitpid_non_intr [] server_pid with
| (_, Unix.WEXITED 0) ->
assert (String.equal (Stdlib.input_line ic) MonitorUtils.ready);
Stdlib.close_in ic
| (_, Unix.WEXITED i) ->
if not silent then
Printf.eprintf
"Starting hh_server failed. Exited with status code: %d!\n"
i;
if exit_on_failure then Exit.exit Exit_status.Server_already_exists
| _ ->
if not silent then Printf.eprintf "Could not start hh_server!\n";
if exit_on_failure then Exit.exit Exit_status.Server_already_exists
with
| _ ->
if not silent then Printf.eprintf "Could not start hh_server!\n";
if exit_on_failure then Exit.exit Exit_status.Server_already_exists
let should_start env =
let root_s = Path.to_string env.root in
let handoff_options =
MonitorRpc.
{
force_dormant_start = false;
pipe_name = ServerController.(pipe_type_to_string Default);
}
in
let tracker = Connection_tracker.create () in
Hh_logger.log
"[%s] ClientStart.should_start"
(Connection_tracker.log_id tracker);
match
MonitorConnection.connect_once
~tracker
~timeout:3
~terminate_monitor_on_version_mismatch:true
env.root
handoff_options
with
| Ok _conn -> false
| Error MonitorUtils.(Connect_to_monitor_failure { server_exists = false; _ })
| Error (MonitorUtils.Build_id_mismatched_monitor_will_terminate _)
| Error MonitorUtils.Server_died ->
true
| Error (MonitorUtils.Build_id_mismatched_client_must_terminate _) ->
HackEventLogger.invariant_violation_bug
"we requested terminate_monitor_on_version_mismatch";
Printf.eprintf "Internal error. Please try `hh stop`\n";
false
| Error MonitorUtils.Server_dormant
| Error MonitorUtils.Server_dormant_out_of_retries ->
Printf.eprintf "Server already exists but is dormant";
false
| Error MonitorUtils.(Connect_to_monitor_failure { server_exists = true; _ })
->
Printf.eprintf "Replacing unresponsive server for %s\n%!" root_s;
ClientStop.kill_server env.root env.from;
true
let main (env : env) : Exit_status.t Lwt.t =
HackEventLogger.set_from env.from;
HackEventLogger.client_start ();
(* TODO(ljw): There are some race conditions here. First scenario: two *)
(* processes simultaneously do 'hh start' while the server isn't running. *)
(* Both their calls to should_start will see the lockfile absent and *)
(* immediately get back 'Server_missing'. So both of them launch hh_server. *)
(* One hh_server process will be slightly faster and will create a lockfile *)
(* and shortly start listening on the socket. The other will see that the *)
(* lockfile already exists and so terminate with error code 0 immediately *)
(* without sending the "ready" message. And the second start_server call *)
(* will fail its assert that a "ready" message should come. *)
(* *)
(* Second scenario: one process does 'hh start', and creates the lockfile, *)
(* and after a short delay will start listening on its socket. Another *)
(* process does 'hh start', sees the lockfile is present, tries to connect, *)
(* but we're still in above short delay and so it gets ECONNREFUSED *)
(* immediately, which (given the presence of a lockfile) is returned as *)
(* Monitor_not_ready. The should_start routine deems this an unresponsive *)
(* server and so kills it and launches a new server again. The first *)
(* process might or might not report failure, depending on how far it got *)
(* with its 'hh start' -- i.e. whether or not it yet observed the "ready". *)
(* *)
(* Third and most typical scenario: an LSP client like Nuclide is running, *)
(* and the user does 'hh restart' which kills the server and then calls *)
(* start_server. As soon as LSP sees the server killed, it too immediately *)
(* calls ClientStart.main. Maybe it will see the lockfile absent, and so *)
(* proceed according to the first race scenario above. Maybe it will see *)
(* the lockfile present and proceed according to the second race scenario *)
(* above. In both cases the LSP client will see problem reports. *)
(* *)
(* The root problem is that should_start assumes an invariant that "if *)
(* hh_server monitor is busy then it has failed and should be shut down." *)
(* This invariant isn't true. Note that the reason we call should_start, *)
(* rather than just using the default ClientConnect.autorestart which calls *)
(* into ClientStart.start_server, is because we do like its ability to kill *)
(* an unresponsive server. So the should_start function should simply give *)
(* a grace period in case of a temporarily busy server. *)
(* *)
(* I believe there's a second similar problem inside ClientConnect.connect *)
(* when its env.autorestart is true. During the short delay window it might *)
(* immediately get Server_missing similar to the first scenario, and so *)
(* ClientStart.start_server, which will fail in the same way. Or it might *)
(* immediately get ECONNREFUSED during the delay window, so it will retry *)
(* connection attempt immediately, and it might burn through all of its *)
(* available retries instantly. That's because ECONNREFUSED is immediate. *)
if should_start env then (
start_server env;
Lwt.return Exit_status.No_error
) else (
if not env.silent then
Printf.eprintf
"Error: Server already exists for %s\nUse hh_client restart if you want to kill it and start a new one\n%!"
(Path.to_string env.root);
Lwt.return Exit_status.Server_already_exists
) |
OCaml Interface | hhvm/hphp/hack/src/client/clientStart.mli | (*
* Copyright (c) 2015, 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 env = {
root: Path.t;
from: string;
no_load: bool;
watchman_debug_logging: bool;
log_inference_constraints: bool;
silent: bool;
exit_on_failure: bool;
ignore_hh_version: bool;
save_64bit: string option;
save_human_readable_64bit_dep_map: string option;
saved_state_ignore_hhconfig: bool;
prechecked: bool option;
mini_state: string option;
config: (string * string) list;
custom_hhi_path: string option;
custom_telemetry_data: (string * string) list;
allow_non_opt_build: bool;
}
val main : env -> Exit_status.t Lwt.t
val start_server : env -> unit |
OCaml | hhvm/hphp/hack/src/client/clientStop.ml | (*
* Copyright (c) 2015, 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 MC = MonitorConnection
exception FailedToKill
type env = {
root: Path.t;
from: string;
}
let wait_for_death root secs =
let i = ref 0 in
try
while MC.server_exists (ServerFiles.lock_file root) do
incr i;
if !i < secs then
ignore @@ Unix.sleep 1
else
raise Exit
done;
true
with
| Exit -> false
let nice_kill env =
let root_s = Path.to_string env.root in
Printf.eprintf "Attempting to nicely kill server for %s\n%!" root_s;
let tracker = Connection_tracker.create () in
Hh_logger.log "[%s] ClientStop.nice_kill" (Connection_tracker.log_id tracker);
try
match MonitorConnection.connect_and_shut_down ~tracker env.root with
| Ok shutdown_result -> begin
match shutdown_result with
| MonitorUtils.SHUTDOWN_VERIFIED ->
Printf.eprintf "Successfully killed server for %s\n%!" root_s
| MonitorUtils.SHUTDOWN_UNVERIFIED ->
Printf.eprintf
"Failed to kill server nicely for %s (Shutdown not verified)\n%!"
root_s;
raise FailedToKill
end
| Error (MonitorUtils.Build_id_mismatched_monitor_will_terminate _) ->
Printf.eprintf "Successfully killed server for %s\n%!" root_s
| Error
MonitorUtils.(Connect_to_monitor_failure { server_exists = false; _ })
->
Printf.eprintf "No server to kill for %s\n%!" root_s
| Error _ ->
Printf.eprintf "Failed to kill server nicely for %s\n%!" root_s;
raise FailedToKill
with
| _ ->
Printf.eprintf "Failed to kill server nicely for %s\n%!" root_s;
raise FailedToKill
let mean_kill env =
let root_s = Path.to_string env.root in
Printf.eprintf "Attempting to meanly kill server for %s\n%!" root_s;
let pids =
try PidLog.get_pids (ServerFiles.pids_file env.root) with
| PidLog.FailedToGetPids ->
Printf.eprintf
"Unable to figure out pids of running Hack server. Try manually killing it with `pkill hh_server`\n%!";
raise FailedToKill
in
let success =
try
List.iter pids ~f:(fun (pid, _reason) ->
try Sys_utils.terminate_process pid with
| Unix.Unix_error (Unix.ESRCH, "kill", _) ->
(* no such process *)
());
wait_for_death env.root 3
with
| e ->
print_endline (Exn.to_string e);
false
in
if not success then (
Printf.eprintf
"Failed to kill server meanly for %s. Try manually killing it with `pkill hh_server`\n%!"
root_s;
raise FailedToKill
) else
Printf.eprintf "Successfully killed server for %s\n%!" root_s
let do_kill env =
try nice_kill env with
| FailedToKill ->
(try mean_kill env with
| FailedToKill -> raise Exit_status.(Exit_with Kill_error))
let main (env : env) : Exit_status.t Lwt.t =
HackEventLogger.set_from env.from;
HackEventLogger.client_stop ();
do_kill env;
Lwt.return Exit_status.No_error
let kill_server root from = do_kill { root; from } |
OCaml Interface | hhvm/hphp/hack/src/client/clientStop.mli | (*
* Copyright (c) 2015, 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 env = {
root: Path.t;
from: string;
}
val kill_server : Path.t -> string -> unit
val main : env -> Exit_status.t Lwt.t |
OCaml | hhvm/hphp/hack/src/client/clientSymbolInfo.ml | (*
* Copyright (c) 2015, 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 go
(conn : ClientConnect.conn)
~(desc : string)
(files : string)
(expand_path : string -> string) : unit Lwt.t =
let file_list =
match files with
| "-" ->
let content = Sys_utils.read_stdin_to_string () in
Str.split (Str.regexp "\n") content
| _ -> Str.split (Str.regexp ";") files
in
let expand_path_list file_list =
List.rev_map file_list ~f:(fun file_path -> expand_path file_path)
in
let command =
ServerCommandTypes.DUMP_SYMBOL_INFO (expand_path_list file_list)
in
let%lwt (result, _telemetry) = ClientConnect.rpc conn ~desc command in
let result_json = ServerCommandTypes.Symbol_info_service.to_json result in
print_endline (Hh_json.json_to_string result_json);
Lwt.return_unit |
OCaml | hhvm/hphp/hack/src/client/clientTastHoles.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.
*
*)
open Hh_prelude
(* Convert result type to tuple since it's not available to
Nuclide_rpc_message_printer *)
let tast_holes_result_to_tuple
TastHolesService.
{
pos;
actual_ty_string;
expected_ty_string;
actual_ty_json;
expected_ty_json;
} =
(actual_ty_string, actual_ty_json, expected_ty_string, expected_ty_json, pos)
let print_json ~print_file result =
Nuclide_rpc_message_printer.(
print_json
@@ tast_holes_response_to_json ~print_file
@@ List.map ~f:tast_holes_result_to_tuple result)
let print_string ~print_file result =
let printer pos =
if print_file then
Pos.to_absolute pos |> Pos.string
else
Pos.string_no_file pos
in
let print_elem
TastHolesService.{ pos; actual_ty_string; expected_ty_string; _ } =
print_endline
@@ Format.sprintf
{|%s actual type: %s, expected type: %s|}
(printer pos)
actual_ty_string
expected_ty_string
in
match result with
| [] -> print_endline "No TAST Holes"
| _ -> List.iter ~f:print_elem result
let go result ~print_file output_json =
if output_json then
print_json ~print_file result
else
print_string ~print_file result |
OCaml Interface | hhvm/hphp/hack/src/client/clientTastHoles.mli | (*
* 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.
*
*)
val go : TastHolesService.result -> print_file:bool -> bool -> unit |
OCaml | hhvm/hphp/hack/src/client/clientTraceAi.ml | (*
* Copyright (c) 2015, 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 Hh_json
let print_json res = print_endline (Hh_json.json_to_string (JSON_String res))
let go res output_json =
if output_json then
print_json res
else
print_endline res |
OCaml | hhvm/hphp/hack/src/client/clientTypeAtPos.ml | (*
* Copyright (c) 2015, 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 go result output_json =
if output_json then
let response =
match result with
| None -> (None, None)
| Some (str, json) -> (Some str, Some json)
in
Nuclide_rpc_message_printer.(
infer_type_response_to_json response |> print_json)
else
match result with
| Some (str, _) -> print_endline str
| None -> print_endline "(unknown)" |
OCaml | hhvm/hphp/hack/src/client/clientTypeErrorAtPos.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.
*
*)
open Hh_prelude
let print_json result =
Nuclide_rpc_message_printer.(
print_json
@@ infer_type_error_response_to_json
@@ Option.value_map
result
~default:(None, None, None, None)
~f:(fun
InferErrorAtPosService.
{
actual_ty_string;
expected_ty_string;
actual_ty_json;
expected_ty_json;
}
->
( Some actual_ty_string,
Some actual_ty_json,
Some expected_ty_string,
Some expected_ty_json )))
let print_string result =
print_endline
@@ Option.value_map
result
~default:"(unknown)"
~f:(fun
InferErrorAtPosService.{ actual_ty_string; expected_ty_string; _ }
->
Format.sprintf
{|actual: %s, expected: %s|}
actual_ty_string
expected_ty_string)
let go result output_json =
if output_json then
print_json result
else
print_string result |
OCaml Interface | hhvm/hphp/hack/src/client/clientTypeErrorAtPos.mli | (*
* 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.
*
*)
val go : InferErrorAtPosService.t option -> bool -> unit |
hhvm/hphp/hack/src/client/dune | (library
(name client)
(wrapped false)
(modules
(:standard
\
clientLogCommand
clientGetDefinition
clientHighlightRefs))
(libraries
connection_tracker
client_get_definition
client_highlight_refs
client_ide_service
clowder_paste
flytrap
formatting_stubs
hh_server_monitor
logging
lwt
lwt.unix
lwt_utils
messages
nuclide_rpc_message_printer
pos
rage
server
server_command_types
server_monitor
server_progress
server_progress_lwt
server_utils
state_loader
sys_utils
utils_config_file_lwt
yojson
version)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_variants_conv)))
(library
(name client_log_command)
(modules clientLogCommand)
(libraries sys_utils)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name client_get_definition)
(wrapped false)
(modules clientGetDefinition)
(libraries nuclide_rpc_message_printer server_file_outline sys_utils)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name client_highlight_refs)
(wrapped false)
(modules clientHighlightRefs)
(libraries pos nuclide_rpc_message_printer server sys_utils)
(preprocess
(pps lwt_ppx ppx_deriving.std))) |
|
OCaml | hhvm/hphp/hack/src/client/ide_service/clientIdeDaemon.ml | (*
* Copyright (c) 2019, 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
(** These are messages on ClientIdeDaemon's internal message-queue *)
type message =
| ClientRequest : 'a ClientIdeMessage.tracked_t -> message
(** ClientRequest came from ClientIdeService over stdin;
it expects a response. *)
| GotNamingTable :
(ClientIdeInit.init_result, ClientIdeMessage.rich_error) result
-> message
(** GotNamingTable is posted from within ClientIdeDaemon itself once
our attempt at loading saved-state has finished; it's picked
up by handle_messages. *)
type message_queue = message Lwt_message_queue.t
exception Outfd_write_error of string * string
let is_outfd_write_error (exn : Exception.t) : bool =
match Exception.unwrap exn with
| Outfd_write_error _ -> true
| _ -> false
type common_state = {
hhi_root: Path.t;
(** hhi_root files are written during initialize, deleted at shutdown, and
refreshed periodically in case the tmp-cleaner has deleted them. *)
config: ServerConfig.t; [@opaque]
local_config: ServerLocalConfig.t; [@opaque]
local_memory: Provider_backend.local_memory; [@opaque]
(** Local_memory backend; includes decl caches *)
}
[@@deriving show]
type open_files_state = {
open_files:
(Provider_context.entry * Errors.t option ref) Relative_path.Map.t;
(** The [entry] caches the TAST+errors; the [Errors.t option] stores what was
the most recent version of the errors to have been returned to clientLsp
by didOpen/didChange/didClose/codeAction. *)
changed_files_to_process: Relative_path.Set.t;
(** changed_files_to_process is grown during File_changed events, and steadily
whittled down one by one in `serve` as we get around to processing them
via `process_changed_files`. *)
changed_files_denominator: int;
(** the user likes to see '5/10' for how many changed files has been processed
in the current batch of changes. The denominator counts up for every new file
that has to be processed, until the batch ends - i.e. changed_files_to_process
becomes empty - and we reset the denominator. *)
}
(** istate, "initialized state", is the state the daemon after it has
finished initialization (i.e. finished loading saved state),
concerning these data-structures:
1. forward-naming-table-delta stored in naming_table
2. reverse-naming-table-delta-and-cache stored in local_memory
3. entries with source text, stored in open_files
3. cached ASTs and TASTs, stored in open_files
4. shallow-decl-cache, folded-decl-cache stored in local-memory
There are two concepts to understand.
1. "Singleton context" (ctx). When processing IDE requests for a file, we create
a context object in which that entry's source text and AST and TAST
are present in the context, and no others are.
2. "Quarantine with respect to an entry". We enter a quarantine while
computing the TAST for a singleton context entry. The invariants within
the quarantine are different from those without.
The key algorithms which read from these data-structures are:
1. Ast_provider.get_ast will fetch the cached AST for an entry in ctx, or if
the entry is present but as yet lacks an AST then it will parse and cache,
or if it's lookinng for the AST of a file not in ctx then it will parse
off disk but decline to cache.
2. Naming_provider.get_* will get_ast for ctx entry to see if symbol is there.
If not it will look in reverse-delta-and-cache or read from sqlite
and store the answer back in reverse-delta-and-cache. But if the answer
to that fallback was a file in ctx, then it will say that the symbol's
not defined.
3. Shallow_classes_provider.get_* will look it up in shallow-decl-cache, and otherwise
will ask Naming_provider and Ast_provider for the AST, will compute shallow decl,
and will store it in shallow-decl-cache
4. Decl_provider.get_* will look it up in folded-decl-cache, computing it if
not there using shallow provider, and store it back in folded-decl-cache
5. Tast_provider.compute* is only ever called on entries. It returns the cached
TAST if present; otherwise, it runs normal type-checking-and-inference, relies
upon all the other providers, and writes the answer back in the entry's TAST cache.
The invariants for forward and reverse naming tables:
1. These tables only ever reflect truth about disk files; they are unaffected
by open_file entries.
2. They are updated asynchronously by update_naming_tables_for_changed_file_lwt
in response to DidChangeWatchedFile events. Thus, we might be asked to fetch
a shallow decl even before the naming-tables have been fully updated.
We might for instance read the naming-table and try to fetch a shallow
decl from a file that doesn't even exist on disk any more.
The invariants for AST, TAST, shallow, and folded-decl caches:
1. AST, if present, reflects the AST of its entry's source text,
and is a "full" AST (not decl-only), and has errors.
2. TAST, if present, reflects the TAST of its entry's source text computed
against the on-disk state of all other files
3. Outside a quarantine, all entries in shallow cache are correct as of disk
(at least as far as asynchronous file updates have been processed).
4. Likewise, all entries in folded caches are correct as of disk.
5. We only ever enter quarantine with respect to one single entry.
For the duration of the quarantine, an AST for that entry,
if present, is correct as of the entry's source text.
6. Likewise any shallow decls for an entry are correct as of its source text.
Moreover, if shallow decls for an entry are present, then the entry's AST
is present and contains those symbols.
7. Any shallow decls not for the entry are correct as of disk.
8. During quarantine, the shallow-decl of all other files is correct as of disk.
9. The entry's TAST, along with every single decl,
are correct as of this entry's source text plus every other file off disk.
Here are the algorithms we use that satisfy those invariants.
1. Upon a disk-file-change, we invalidate all TASTs (satisfying invariant 2).
We use the forward-naming-table to find all "old" symbols that were
defined in the file prior to the disk change, and invalidate those
shallow decls (satisfying invariant 3). We invalidate all
folded caches (satisfying invariant 4). Invariant 1 is N/A.
2. Upon an editor change to a file, we invalidate the entry's AST and TAST
(satisfying invariant 1).
3. Upon request for a TAST of a file, we create a singleton context for
that entry, and enter quarantine as follows. We parse the file and
cache its AST and invalidate shallow decls for all symbols inside
this new AST (satisfying invariant 6). We invalidate all decls
(satisfying invariant 9). Subsequent fetches,
thanks to the "key algorithms for reading these datastructures" (above)
will only cache things in accordance with invariants 6,7,8,9.
4. We leave quarantine as follows. We invalidate shallow decls for
all symbols in the entry's AST; thanks to invariant 5, this will
fulfill invariant 3. We invalidate all decls (satisfying invariant 4).
*)
type istate = {
icommon: common_state;
ifiles: open_files_state; [@opaque]
naming_table: Naming_table.t; [@opaque]
(** the forward-naming-table is constructed during initialize and updated
during process_changed_files. It stores an in-memory map of FileInfos that
have changed since sqlite. When a file is changed on disk, we need this to
know which shallow decls to invalidate. Note: while the forward-naming-table
is stored here, the reverse-naming-table is instead stored in ctx. *)
sienv: SearchUtils.si_env; [@opaque]
(** sienv provides autocomplete and find-symbols. It is constructed during
initialize and updated during process_changed_files. It stores a few
in-memory structures such as namespace-list, plus in-memory deltas. *)
}
(** dstate, "during_init state", is the state the daemon after it has received an
init message (and has parsed config files to get popt/tcopt, has initialized
glean, as written out hhi files) but before it has loaded saved-state or processed
file updates. *)
type dstate = {
start_time: float;
(** When did we kick off the attempt to load saved-state? *)
dcommon: common_state;
dfiles: open_files_state; [@opaque]
}
[@@deriving show]
type state =
| Pending_init (** We haven't yet received init request *)
| During_init of dstate
(** We're working on the init request. We're still in
the process of loading the saved state. *)
| Initialized of istate (** Finished work on init request. *)
| Failed_init of ClientIdeMessage.rich_error
(** Failed request, with root cause *)
type t = {
message_queue: message_queue;
state: state;
}
let state_to_log_string (state : state) : string =
let files_to_log_string (files : open_files_state) : string =
Printf.sprintf
"%d open_files; %d changed_files_to_process"
(Relative_path.Map.cardinal files.open_files)
(Relative_path.Set.cardinal files.changed_files_to_process)
in
match state with
| Pending_init -> "Pending_init"
| During_init { dfiles; _ } ->
Printf.sprintf "During_init(%s)" (files_to_log_string dfiles)
| Initialized { ifiles; _ } ->
Printf.sprintf "Initialized(%s)" (files_to_log_string ifiles)
| Failed_init reason ->
Printf.sprintf "Failed_init(%s)" reason.ClientIdeMessage.category
let log s = Hh_logger.log ("[ide-daemon] " ^^ s)
let log_debug s = Hh_logger.debug ("[ide-daemon] " ^^ s)
let set_up_hh_logger_for_client_ide_service (root : Path.t) : unit =
(* Log to a file on disk. Note that calls to `Hh_logger` will always write to
`stderr`; this is in addition to that. *)
let client_ide_log_fn = ServerFiles.client_ide_log root in
begin
try Sys.rename client_ide_log_fn (client_ide_log_fn ^ ".old") with
| _e -> ()
end;
Hh_logger.set_log client_ide_log_fn;
log "Starting client IDE service at %s" client_ide_log_fn
let write_message
~(out_fd : Lwt_unix.file_descr)
~(message : ClientIdeMessage.message_from_daemon) : unit Lwt.t =
try%lwt
let%lwt (_ : int) = Marshal_tools_lwt.to_fd_with_preamble out_fd message in
Lwt.return_unit
with
| Unix.Unix_error (Unix.EPIPE, fn, param) ->
raise @@ Outfd_write_error (fn, param)
let log_startup_time
?(count : int option) (component : string) (start_time : float) : float =
let now = Unix.gettimeofday () in
HackEventLogger.serverless_ide_startup ?count ~start_time component;
now
let restore_hhi_root_if_necessary (istate : istate) : istate =
if Sys.file_exists (Path.to_string istate.icommon.hhi_root) then
istate
else
(* Some processes may clean up the temporary HHI directory we're using.
Assume that such a process has deleted the directory, and re-write the HHI
files to disk. *)
let hhi_root = Hhi.get_hhi_root ~force_write:true () in
log
"Old hhi root %s no longer exists. Creating a new hhi root at %s"
(Path.to_string istate.icommon.hhi_root)
(Path.to_string hhi_root);
Relative_path.set_path_prefix Relative_path.Hhi hhi_root;
{ istate with icommon = { istate.icommon with hhi_root } }
(** Deletes the hhi files we've created. *)
let remove_hhi (state : state) : unit =
match state with
| Pending_init
| Failed_init _ ->
()
| During_init { dcommon = { hhi_root; _ }; _ }
| Initialized { icommon = { hhi_root; _ }; _ } ->
let hhi_root = Path.to_string hhi_root in
log "Removing hhi directory %s..." hhi_root;
(try Sys_utils.rm_dir_tree hhi_root with
| exn ->
let e = Exception.wrap exn in
ClientIdeUtils.log_bug "remove_hhi" ~e ~telemetry:true)
(** Helper called to process a batch of file changes. Updates the naming table, and invalidates the decl and tast caches for the changes. *)
let batch_update_naming_table_and_invalidate_caches
~(ctx : Provider_context.t)
~(naming_table : Naming_table.t)
~(sienv : SearchUtils.si_env)
~(local_memory : Provider_backend.local_memory)
~(open_files :
(Provider_context.entry * Errors.t option ref) Relative_path.Map.t)
(changes : Relative_path.Set.t) : ClientIdeIncremental.Batch.update_result =
let ({ ClientIdeIncremental.Batch.changes = changes_results; _ } as
update_naming_table_result) =
ClientIdeIncremental.Batch.update_naming_tables_and_si
~ctx
~naming_table
~sienv
~changes
in
List.iter
changes_results
~f:(fun { ClientIdeIncremental.Batch.old_file_info; _ } ->
Option.iter
old_file_info
~f:(Provider_utils.invalidate_local_decl_caches_for_file local_memory));
Relative_path.Map.iter open_files ~f:(fun _path (entry, _) ->
Provider_utils.invalidate_tast_cache_of_entry entry);
update_naming_table_result
(** An empty ctx with no entries *)
let make_empty_ctx (common : common_state) : Provider_context.t =
Provider_context.empty_for_tool
~popt:(ServerConfig.parser_options common.config)
~tcopt:(ServerConfig.typechecker_options common.config)
~backend:(Provider_backend.Local_memory common.local_memory)
~deps_mode:(Typing_deps_mode.InMemoryMode None)
(** Constructs a temporary ctx with just one entry. *)
let make_singleton_ctx (common : common_state) (entry : Provider_context.entry)
: Provider_context.t =
let ctx = make_empty_ctx common in
let ctx = Provider_context.add_or_overwrite_entry ~ctx entry in
ctx
(** initialize1 is called by handle_request upon receipt of an "init"
message from the client. It is synchronous. It sets up global variables and
glean. The remainder of init work will happen after we return... our caller
handle_request will kick off async work to load saved-state, and once done
it will stick a GotNamingTable message into the queue, and handle_one_message
will subsequently pick up that message and call [initialize2]. *)
let initialize1 (param : ClientIdeMessage.Initialize_from_saved_state.t) :
dstate =
log_debug "initialize1";
let open ClientIdeMessage.Initialize_from_saved_state in
let start_time = Unix.gettimeofday () in
HackEventLogger.serverless_ide_set_root param.root;
set_up_hh_logger_for_client_ide_service param.root;
Relative_path.set_path_prefix Relative_path.Root param.root;
let hhi_root = Hhi.get_hhi_root () in
log "Extracted hhi files to directory %s" (Path.to_string hhi_root);
Relative_path.set_path_prefix Relative_path.Hhi hhi_root;
Relative_path.set_path_prefix Relative_path.Tmp (Path.make "/tmp");
let server_args =
ServerArgs.default_options_with_check_mode ~root:(Path.to_string param.root)
in
let server_args = ServerArgs.set_config server_args param.config in
let (config, local_config) = ServerConfig.load ~silent:true server_args in
(* Ignore package loading errors for now TODO(jjwu) *)
let open GlobalOptions in
log "Loading package configuration";
let (_, package_info) = PackageConfig.load_and_parse () in
let tco = ServerConfig.typechecker_options config in
let config =
ServerConfig.set_tc_options
config
{ tco with tco_package_info = package_info }
in
HackEventLogger.set_hhconfig_version
(ServerConfig.version config |> Config_file.version_to_string_opt);
HackEventLogger.set_rollout_flags
(ServerLocalConfig.to_rollout_flags local_config);
HackEventLogger.set_rollout_group local_config.ServerLocalConfig.rollout_group;
Provider_backend.set_local_memory_backend
~max_num_decls:local_config.ServerLocalConfig.ide_max_num_decls
~max_num_shallow_decls:
local_config.ServerLocalConfig.ide_max_num_shallow_decls;
let local_memory =
match Provider_backend.get () with
| Provider_backend.Local_memory local_memory -> local_memory
| _ -> failwith "expected local memory backend"
in
(* We only ever serve requests on files that are open. That's why our caller
passes an initial list of open files, the ones already open in the editor
at the time we were launched. We don't actually care about their contents
at this stage, since updated contents will be delivered upon each request.
(and indeed it's pointless to waste time reading existing contents off disk).
All we care is that every open file is listed in 'open_files'. *)
let open_files =
param.open_files
|> List.map ~f:(fun path ->
path |> Path.to_string |> Relative_path.create_detect_prefix)
|> List.map ~f:(fun path ->
( path,
( Provider_context.make_entry
~path
~contents:Provider_context.Raise_exn_on_attempt_to_read,
ref None ) ))
|> Relative_path.Map.of_list
in
let start_time =
log_startup_time
"initialize1"
~count:(List.length param.open_files)
start_time
in
log_debug "initialize1.done";
{
start_time;
dcommon = { hhi_root; config; local_config; local_memory };
dfiles =
{
open_files;
changed_files_to_process = Relative_path.Set.empty;
changed_files_denominator = 0;
};
}
(** initialize2 is called by handle_one_message upon receipt of a
[GotNamingTable] message. It sends the appropriate message on to the
client, and transitions into either [Initialized] or [Failed_init]
state. *)
let initialize2
(out_fd : Lwt_unix.file_descr)
(dstate : dstate)
(init_result :
(ClientIdeInit.init_result, ClientIdeMessage.rich_error) result) :
state Lwt.t =
let start_time = log_startup_time "load_naming_table" dstate.start_time in
log_debug "initialize2";
match init_result with
| Ok { ClientIdeInit.naming_table; sienv; changed_files } ->
let changed_files_to_process =
Relative_path.Set.union
dstate.dfiles.changed_files_to_process
(Relative_path.Set.of_list changed_files)
|> Relative_path.Set.filter ~f:FindUtils.path_filter
in
let changed_files_denominator =
Relative_path.Set.cardinal changed_files_to_process
in
let istate =
if dstate.dcommon.local_config.ServerLocalConfig.ide_batch_process_changes
then
let ClientIdeIncremental.Batch.
{ naming_table; sienv; changes = _changes } =
batch_update_naming_table_and_invalidate_caches
~ctx:(make_empty_ctx dstate.dcommon)
~naming_table
~sienv
~local_memory:dstate.dcommon.local_memory
~open_files:dstate.dfiles.open_files
changed_files_to_process
in
{
naming_table;
sienv;
icommon = dstate.dcommon;
ifiles =
{
open_files = dstate.dfiles.open_files;
changed_files_to_process = Relative_path.Set.empty;
changed_files_denominator = 0;
};
}
else
{
naming_table;
sienv;
icommon = dstate.dcommon;
ifiles =
{
open_files = dstate.dfiles.open_files;
changed_files_to_process;
changed_files_denominator;
};
}
in
(* Note: Done_init is needed to (1) transition clientIdeService state, (2) cause
clientLsp to know to ask for squiggles to be refreshed on open files. *)
(* TODO: Done_init always shows "Done_init(0/0)". We should remove the progress here. *)
let p = { ClientIdeMessage.Processing_files.total = 0; processed = 0 } in
let%lwt () =
write_message
~out_fd
~message:
(ClientIdeMessage.Notification (ClientIdeMessage.Done_init (Ok p)))
in
let count =
Option.some_if
dstate.dcommon.local_config.ServerLocalConfig.ide_batch_process_changes
changed_files_denominator
in
let (_ : float) = log_startup_time "initialize2" start_time ?count in
log_debug "initialize2.done";
Lwt.return (Initialized istate)
| Error reason ->
log_debug "initialize2.error";
let%lwt () =
write_message
~out_fd
~message:
(ClientIdeMessage.Notification
(ClientIdeMessage.Done_init (Error reason)))
in
remove_hhi (During_init dstate);
Lwt.return (Failed_init reason)
(** This funtion is about papering over a bug. Sometimes, rarely, we're
failing to receive DidOpen messages from clientLsp. Our model is to
only ever answer IDE requests on open files, so we know we'll eventually
reveive a DidClose even for them and be able to clear their TAST cache
at that time. But for now, to paper over the bug, we'll call this
function to log the event and we'll assume that we just missed a DidOpen. *)
let log_missing_open_file_BUG (reason : string) (path : Relative_path.t) : unit
=
let path = Relative_path.to_absolute path in
let message =
Printf.sprintf "Error: action on non-open file [%s] %s" reason path
in
ClientIdeUtils.log_bug message ~telemetry:true
(** Registers the file in response to DidOpen or DidChange,
during the During_init state, by putting in a new
entry in open_files, with empty AST and TAST. If the LSP client
happened to send us two DidOpens for a file, or DidChange before DidOpen,
well, we won't complain. *)
let open_or_change_file_during_init
(dstate : dstate) (path : Relative_path.t) (contents : string) : dstate =
let entry =
Provider_context.make_entry
~path
~contents:(Provider_context.Provided_contents contents)
in
let open_files =
Relative_path.Map.add
dstate.dfiles.open_files
~key:path
~data:(entry, ref None)
in
{ dstate with dfiles = { dstate.dfiles with open_files } }
(** Closes a file, in response to DidClose event, by removing the
entry in open_files. If the LSP client sents us multile DidCloses,
or DidClose for an unopen file, we won't complain. *)
let close_file (files : open_files_state) (path : Relative_path.t) :
open_files_state =
if not (Relative_path.Map.mem files.open_files path) then
log_missing_open_file_BUG "close-without-open" path;
let open_files = Relative_path.Map.remove files.open_files path in
{ files with open_files }
(** Updates an existing opened file, with new contents; if the
contents haven't changed then the existing open file's AST and TAST
will be left intact. *)
let update_file
(files : open_files_state) (document : ClientIdeMessage.document) :
open_files_state * Provider_context.entry * Errors.t option ref =
let path =
document.ClientIdeMessage.file_path
|> Path.to_string
|> Relative_path.create_detect_prefix
in
let contents = document.ClientIdeMessage.file_contents in
let (entry, published_errors) =
match Relative_path.Map.find_opt files.open_files path with
| None ->
(* This is a common scenario although I'm not quite sure why *)
( Provider_context.make_entry
~path
~contents:(Provider_context.Provided_contents contents),
ref None )
| Some (entry, published_errors)
when Option.equal
String.equal
(Some contents)
(Provider_context.get_file_contents_if_present entry) ->
(* we can just re-use the existing entry; contents haven't changed *)
(entry, published_errors)
| Some _ ->
(* We'll create a new entry; existing entry caches, if present, will be dropped
But first, need to clear the Fixme cache. This is a global cache
which is updated as a side-effect of the Ast_provider. *)
Fixme_provider.remove_batch (Relative_path.Set.singleton path);
( Provider_context.make_entry
~path
~contents:(Provider_context.Provided_contents contents),
ref None )
in
let open_files =
Relative_path.Map.add
files.open_files
~key:path
~data:(entry, published_errors)
in
({ files with open_files }, entry, published_errors)
(** like [update_file], but for convenience also produces a ctx for
use in typechecking. Also ensures that hhi files haven't been deleted
by tmp_cleaner, so that type-checking will succeed. *)
let update_file_ctx (istate : istate) (document : ClientIdeMessage.document) :
istate * Provider_context.t * Provider_context.entry * Errors.t option ref =
let istate = restore_hhi_root_if_necessary istate in
let (ifiles, entry, published_errors) = update_file istate.ifiles document in
let ctx = make_singleton_ctx istate.icommon entry in
({ istate with ifiles }, ctx, entry, published_errors)
(** Simple helper. It updates the [ifiles] or [dfiles] member of Initialized
or During_init states, respectively. Will throw if you call it on any other
state. *)
let update_state_files (state : state) (files : open_files_state) : state =
match state with
| During_init dstate -> During_init { dstate with dfiles = files }
| Initialized istate -> Initialized { istate with ifiles = files }
| _ -> failwith ("Update_state_files: unexpected " ^ state_to_log_string state)
(** We avoid showing typing errors if there are parsing errors. *)
let get_user_facing_errors
~(ctx : Provider_context.t) ~(entry : Provider_context.entry) : Errors.t =
let (_, ast_errors) =
Ast_provider.compute_parser_return_and_ast_errors
~popt:(Provider_context.get_popt ctx)
~entry
in
if Errors.is_empty ast_errors then
let { Tast_provider.Compute_tast_and_errors.errors = all_errors; _ } =
Tast_provider.compute_tast_and_errors_quarantined ~ctx ~entry
in
all_errors
else
ast_errors
(** Computes the Errors.t for what's on disk at a given path.
We provide [istate] just in case we can benefit from a cached answer. *)
let get_errors_for_path (istate : istate) (path : Relative_path.t) : Errors.t =
let disk_content_opt =
Sys_utils.cat_or_failed (Relative_path.to_absolute path)
in
let cached_entry_opt =
Relative_path.Map.find_opt istate.ifiles.open_files path
in
let entry_opt =
match (disk_content_opt, cached_entry_opt) with
| (None, _) ->
(* if the disk file is absent (e.g. it was deleted prior to the user closing it),
then we naturally can't compute errors for it. *)
None
| ( Some disk_content,
Some
( ({
Provider_context.contents =
Provider_context.(
Contents_from_disk str | Provided_contents str);
_;
} as entry),
_ ) )
when String.equal disk_content str ->
(* file on disk was the same as what we currently have in the entry, and
the entry very likely already has errors computed for it, so as an optimization
we'll re-use errors from that entry. *)
Some entry
| (Some disk_content, _) ->
(* file on disk is different from what we have in the entry, e.g. because the
user closed a modified file, so compute errors from the disk content. *)
Some
(Provider_context.make_entry
~path
~contents:(Provider_context.Provided_contents disk_content))
in
match entry_opt with
| None ->
(* file couldn't be read off disk (maybe absent); therefore, by definition, no errors *)
Errors.empty
| Some entry ->
(* Here we'll get either cached errors from the cached entry, or will recompute errors
from the partially cached entry, or will compute errors from the file on disk. *)
let ctx = make_singleton_ctx istate.icommon entry in
get_user_facing_errors ~ctx ~entry
(** handle_request invariants: Messages are only ever handled serially; we never
handle one message while another is being handled. It is a bug if the client sends
anything other than [Initialize_from_saved_state] as its first message. Upon
receipt+processing of this we transition from [Pre_init] to [During_init]
and kick off some async work to prepare the naming table. During this async work, i.e.
during [During_init], we are able to handle a few requests but will reject
others. Important: files may change during [During_init], and it's important that we keep track of and eventually index these changed files.
Our caller [handle_one_message] is actually the one that transitions
us from [During_init] to either [Failed_init] or [Initialized]. Once in one
of those states, we never thereafter transition state. *)
let handle_request
(type a)
(message_queue : message_queue)
(state : state)
(_tracking_id : string)
(message : a ClientIdeMessage.t) : (state * (a, Lsp.Error.t) result) Lwt.t =
let open ClientIdeMessage in
match (state, message) with
(***********************************************************)
(************************* HANDLED IN ANY STATE ************)
(***********************************************************)
| (_, Verbose_to_file verbose) ->
if verbose then
Hh_logger.Level.set_min_level_file Hh_logger.Level.Debug
else
Hh_logger.Level.set_min_level_file Hh_logger.Level.Info;
Lwt.return (state, Ok ())
| (_, Shutdown ()) ->
remove_hhi state;
Lwt.return (state, Ok ())
(***********************************************************)
(************************* INITIALIZATION ******************)
(***********************************************************)
| (Pending_init, Initialize_from_saved_state param) -> begin
(* Invariant: no message will be sent to us prior to this request,
and we must send no message until we've sent this response. *)
try
let dstate = initialize1 param in
(* We're going to kick off the asynchronous part of initializing now.
Once it's done, it will appear as a GotNamingTable message on the queue. *)
Lwt.async (fun () ->
let%lwt naming_table_result =
ClientIdeInit.init
~config:dstate.dcommon.config
~local_config:dstate.dcommon.local_config
~param
~hhi_root:dstate.dcommon.hhi_root
~local_memory:dstate.dcommon.local_memory
in
(* if the following push fails, that must be because the queues
have been shut down, in which case there's nothing to do. *)
let (_succeeded : bool) =
Lwt_message_queue.push
message_queue
(GotNamingTable naming_table_result)
in
Lwt.return_unit);
log "Finished saved state initialization. State: %s" (show_dstate dstate);
Lwt.return (During_init dstate, Ok ())
with
| exn ->
let e = Exception.wrap exn in
let reason = ClientIdeUtils.make_rich_error "initialize1" ~e in
(* Our caller has an exception handler. But we must handle this ourselves
to change state to Failed_init; our caller's handler doesn't change state. *)
(* TODO: remove_hhi *)
Lwt.return (Failed_init reason, Error (ClientIdeUtils.to_lsp_error reason))
end
| (_, Initialize_from_saved_state _) ->
failwith ("Unexpected init in " ^ state_to_log_string state)
(***********************************************************)
(************************* CAN HANDLE DURING INIT **********)
(***********************************************************)
| (During_init { dfiles; _ }, Did_change_watched_files changes) ->
(* While init is happening, we accumulate changes in [changed_files_to_process].
Once naming-table has been loaded, then [initialize2] will process+discharge all these
accumulated changes. *)
let dfiles =
{
dfiles with
changed_files_to_process =
Relative_path.Set.union dfiles.changed_files_to_process changes;
changed_files_denominator =
dfiles.changed_files_denominator + Relative_path.Set.cardinal changes;
}
in
Lwt.return (update_state_files state dfiles, Ok ())
| (Initialized istate, Did_change_watched_files changes)
when istate.icommon.local_config.ServerLocalConfig.ide_batch_process_changes
->
let ClientIdeIncremental.Batch.{ naming_table; sienv; changes = _changes } =
batch_update_naming_table_and_invalidate_caches
~ctx:(make_empty_ctx istate.icommon)
~naming_table:istate.naming_table
~sienv:istate.sienv
~local_memory:istate.icommon.local_memory
~open_files:istate.ifiles.open_files
changes
in
let istate = { istate with naming_table; sienv } in
Lwt.return (Initialized istate, Ok ())
| (Initialized { ifiles; _ }, Did_change_watched_files changes) ->
(* Legacy, will be deleted once we rollout ide_batch_process_changes *)
let ifiles =
{
ifiles with
changed_files_to_process =
Relative_path.Set.union ifiles.changed_files_to_process changes;
changed_files_denominator =
ifiles.changed_files_denominator + Relative_path.Set.cardinal changes;
}
in
Lwt.return (update_state_files state ifiles, Ok ())
(* didClose *)
| (During_init { dfiles = files; _ }, Did_close file_path) ->
let path =
file_path |> Path.to_string |> Relative_path.create_detect_prefix
in
let files = close_file files path in
Lwt.return (update_state_files state files, Ok [])
| (Initialized istate, Did_close file_path) ->
let path =
file_path |> Path.to_string |> Relative_path.create_detect_prefix
in
let errors = get_errors_for_path istate path |> Errors.sort_and_finalize in
let files = close_file istate.ifiles path in
Lwt.return (update_state_files state files, Ok errors)
(* didOpen or didChange *)
| ( During_init dstate,
Did_open_or_change ({ file_path; file_contents }, _should_calculate_errors)
) ->
let path =
file_path |> Path.to_string |> Relative_path.create_detect_prefix
in
let dstate = open_or_change_file_during_init dstate path file_contents in
Lwt.return (During_init dstate, Ok None)
| ( Initialized istate,
Did_open_or_change (document, { should_calculate_errors }) ) ->
let (istate, ctx, entry, published_errors_ref) =
update_file_ctx istate document
in
let errors =
if should_calculate_errors then begin
let errors = get_user_facing_errors ~ctx ~entry in
published_errors_ref := Some errors;
Some (Errors.sort_and_finalize errors)
end else
None
in
Lwt.return (Initialized istate, Ok errors)
(* Document Symbol *)
| ( ( During_init { dfiles = files; dcommon = common; _ }
| Initialized { ifiles = files; icommon = common; _ } ),
Document_symbol document ) ->
let (files, entry, _) = update_file files document in
let result =
FileOutline.outline_entry_no_comments
~popt:(ServerConfig.parser_options common.config)
~entry
in
Lwt.return (update_state_files state files, Ok result)
(***********************************************************)
(************************* UNABLE TO HANDLE ****************)
(***********************************************************)
| (During_init dstate, _) ->
let e =
{
Lsp.Error.code = Lsp.Error.RequestCancelled;
message = "IDE service has not yet completed init";
data = None;
}
in
Lwt.return (During_init dstate, Error e)
| (Failed_init reason, _) ->
Lwt.return (Failed_init reason, Error (ClientIdeUtils.to_lsp_error reason))
| (Pending_init, _) ->
failwith
(Printf.sprintf
"unexpected message '%s' in state '%s'"
(ClientIdeMessage.t_to_string message)
(state_to_log_string state))
(***********************************************************)
(************************* NORMAL HANDLING AFTER INIT ******)
(***********************************************************)
| (Initialized istate, Hover (document, { line; column })) ->
let (istate, ctx, entry, _) = update_file_ctx istate document in
let result =
Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () ->
ServerHover.go_quarantined ~ctx ~entry ~line ~column)
in
Lwt.return (Initialized istate, Ok result)
| ( Initialized istate,
Go_to_implementation (document, { line; column }, document_list) ) ->
let (istate, ctx, entry, _) = update_file_ctx istate document in
let (istate, result) =
Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () ->
match ServerFindRefs.go_from_file_ctx ~ctx ~entry ~line ~column with
| Some (_name, action)
when not @@ ServerGoToImpl.is_searchable ~action ->
(istate, ClientIdeMessage.Invalid_symbol_impl)
| Some (name, action) ->
(*
1) For all open files that we know about in ClientIDEDaemon, uesd the
cached TASTs to return positions of implementations
2) Return this list, alongside the name and action
3) ClientLSP, upon receiving, will shellout to hh_server
and reject all server-provided positions for files that ClientIDEDaemon
knew about, under the assumption that our cached TAST provides edited
file info, if applicable.
*)
let (istate, single_file_positions) =
List.fold
~f:(fun (istate, accum) document ->
let (istate, ctx, _entry, _errors) =
update_file_ctx istate document
in
let stringified_path =
Path.to_string document.ClientIdeMessage.file_path
in
let filename =
Relative_path.create_detect_prefix stringified_path
in
let single_file_pos =
ServerGoToImpl.go_for_single_file
~ctx
~action
~naming_table:istate.naming_table
~filename
|> ServerFindRefs.to_absolute
|> List.map ~f:snd
in
let urikey =
Lsp_helpers.path_to_lsp_uri
stringified_path
~default_path:stringified_path
in
let updated_map =
Lsp.UriMap.add urikey single_file_pos accum
in
(istate, updated_map))
document_list
~init:(istate, Lsp.UriMap.empty)
in
( istate,
ClientIdeMessage.Go_to_impl_success
(name, action, single_file_positions) )
| None -> (istate, ClientIdeMessage.Invalid_symbol_impl))
in
Lwt.return (Initialized istate, Ok result)
(* textDocument/rename *)
| ( Initialized istate,
Rename (document, { line; column }, new_name, document_list) ) ->
let (istate, ctx, entry, _errors) = update_file_ctx istate document in
let (istate, result) =
Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () ->
match
ServerFindRefs.go_from_file_ctx_with_symbol_definition
~ctx
~entry
~line
~column
with
| None -> (istate, ClientIdeMessage.Not_renameable_position)
| Some (_definition, action) when ServerFindRefs.is_local action ->
let res =
match ServerRename.go_for_localvar ctx action new_name with
| Ok (Some patch_list) ->
ClientIdeMessage.Rename_success
{ shellout = None; local = patch_list }
| Ok None ->
ClientIdeMessage.Rename_success { shellout = None; local = [] }
| Error action ->
let str =
Printf.sprintf
"ClientIDEDaemon failed to rename for localvar %s"
(ServerCommandTypes.Find_refs.show_action action)
in
log "%s" str;
failwith "ClientIDEDaemon failed to rename for a localvar"
in
(istate, res)
| Some (symbol_definition, action) ->
let (istate, single_file_patches) =
List.fold
~f:(fun (istate, accum) document ->
let (istate, ctx, _entry, _errors) =
update_file_ctx istate document
in
let filename =
Path.to_string document.ClientIdeMessage.file_path
|> Relative_path.create_detect_prefix
in
let single_file_patches =
ServerRename.go_for_single_file
ctx
~find_refs_action:action
~filename
~symbol_definition
~new_name
~naming_table:istate.naming_table
in
let patches =
match single_file_patches with
| Ok patches -> patches
| Error _ -> []
in
let patch_list = List.rev_append patches accum in
(istate, patch_list))
~init:(istate, [])
document_list
in
( istate,
ClientIdeMessage.Rename_success
{
shellout = Some (symbol_definition, action);
local = single_file_patches;
} )
(* not a localvar, must defer to hh_server *))
in
Lwt.return (Initialized istate, Ok result)
(* textDocument/references - localvar only *)
| ( Initialized istate,
Find_references (document, { line; column }, document_list) ) ->
let open Result.Monad_infix in
(* Update the state of the world with the document as it exists in the IDE *)
let (istate, ctx, entry, _) = update_file_ctx istate document in
let (istate, result) =
Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () ->
match ServerFindRefs.go_from_file_ctx ~ctx ~entry ~line ~column with
| Some (name, action) when ServerFindRefs.is_local action ->
let result =
ServerFindRefs.go_for_localvar ctx action
>>| ServerFindRefs.to_absolute
in
let result =
match result with
| Ok ide_result ->
let lsp_uri_map =
begin
match ide_result with
| [] ->
(* If we find-refs on a localvar via right-click, is it possible that it doesn't return references?
It's possible some nondeterminism changed the cached TAST,
but assert that it's a failure for now
*)
let err =
Printf.sprintf
"FindRefs returned an empty list of positions for localvar %s"
name
in
log "%s" err;
HackEventLogger.invariant_violation_bug err;
failwith err
| positions ->
let filename =
List.hd_exn positions |> snd |> Pos.filename
in
let uri =
Lsp_helpers.path_to_lsp_uri
~default_path:filename
filename
in
Lsp.UriMap.add uri positions Lsp.UriMap.empty
end
in
let () =
if lsp_uri_map |> Lsp.UriMap.values |> List.length = 1 then
()
else
(* Can a localvar cross file boundaries? I sure hope not. *)
let err =
Printf.sprintf
"Found more than one file when executing find refs for localvar %s"
name
in
log "%s" err;
HackEventLogger.invariant_violation_bug err;
failwith err
in
ClientIdeMessage.Find_refs_success
{
full_name = name;
action = None;
hint_suffixes = [];
open_file_results = lsp_uri_map;
}
| Error _action ->
let err =
Printf.sprintf "Failed to find refs for localvar %s" name
in
log "%s" err;
HackEventLogger.invariant_violation_bug err;
failwith err
in
(istate, result)
(* clientLsp should raise if we return a LocalVar action *)
| None ->
(* Clicking a line+col that isn't a symbol *)
(istate, ClientIdeMessage.Invalid_symbol)
| Some (name, action) ->
(* Not a localvar, so we do the following:
1) For all open files that we know about in ClientIDEDaemon, uesd the
cached TASTs to return positions of references
2) Return this list, alongside the name and action
3) ClientLSP, upon receiving, will shellout to hh_server
and reject all server-provided positions for files that ClientIDEDaemon
knew about, under the assumption that our cached TAST provides edited
file info, if applicable.
*)
let (istate, single_file_refs) =
List.fold
~f:(fun (istate, accum) document ->
let (istate, ctx, _entry, _errors) =
update_file_ctx istate document
in
let stringified_path =
Path.to_string document.ClientIdeMessage.file_path
in
let filename =
Relative_path.create_detect_prefix stringified_path
in
let single_file_ref =
ServerFindRefs.go_for_single_file
~ctx
~action
~filename
~name
~naming_table:istate.naming_table
|> ServerFindRefs.to_absolute
in
let urikey =
Lsp_helpers.path_to_lsp_uri
stringified_path
~default_path:stringified_path
in
let updated_map =
Lsp.UriMap.add urikey single_file_ref accum
in
(istate, updated_map))
document_list
~init:(istate, Lsp.UriMap.empty)
in
let sienv_ref = ref istate.sienv in
let hints =
SymbolIndex.find_refs ~sienv_ref ~action ~max_results:100
in
let hint_suffixes =
Option.value_map hints ~default:[] ~f:(fun hints ->
List.filter_map hints ~f:(fun path ->
if Relative_path.is_root (Relative_path.prefix path) then
Some (Relative_path.suffix path)
else
None))
in
( { istate with sienv = !sienv_ref },
ClientIdeMessage.Find_refs_success
{
full_name = name;
action = Some action;
hint_suffixes;
open_file_results = single_file_refs;
} ))
in
Lwt.return (Initialized istate, Ok result)
(* Autocomplete *)
| ( Initialized istate,
Completion
(document, { line; column }, { ClientIdeMessage.is_manually_invoked })
) ->
(* Update the state of the world with the document as it exists in the IDE *)
let (istate, ctx, entry, _) = update_file_ctx istate document in
let sienv_ref = ref istate.sienv in
let result =
ServerAutoComplete.go_ctx
~ctx
~entry
~sienv_ref
~is_manually_invoked
~line
~column
~naming_table:istate.naming_table
in
let istate = { istate with sienv = !sienv_ref } in
Lwt.return (Initialized istate, Ok result)
(* Autocomplete docblock resolve *)
| (Initialized istate, Completion_resolve (symbol, kind)) ->
let ctx = make_empty_ctx istate.icommon in
let result = ServerDocblockAt.go_docblock_for_symbol ~ctx ~symbol ~kind in
Lwt.return (Initialized istate, Ok result)
(* Autocomplete docblock resolve *)
| ( Initialized istate,
Completion_resolve_location (file_path, { line; column }, kind) ) ->
(* We're given a location but it often won't be an opened file.
We will only serve autocomplete docblocks as of truth on disk.
Hence, we construct temporary entry to reflect the file which
contained the target of the resolve. *)
let path =
file_path |> Path.to_string |> Relative_path.create_detect_prefix
in
let ctx = make_empty_ctx istate.icommon in
let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path in
let result =
Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () ->
ServerDocblockAt.go_docblock_ctx ~ctx ~entry ~line ~column ~kind)
in
Lwt.return (Initialized istate, Ok result)
(* Document highlighting *)
| (Initialized istate, Document_highlight (document, { line; column })) ->
let (istate, ctx, entry, _) = update_file_ctx istate document in
let results =
Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () ->
ServerHighlightRefs.go_quarantined ~ctx ~entry ~line ~column)
in
Lwt.return (Initialized istate, Ok results)
(* Signature help *)
| (Initialized istate, Signature_help (document, { line; column })) ->
let (istate, ctx, entry, _) = update_file_ctx istate document in
let results =
Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () ->
ServerSignatureHelp.go_quarantined ~ctx ~entry ~line ~column)
in
Lwt.return (Initialized istate, Ok results)
(* Type Hierarchy *)
| (Initialized istate, Type_Hierarchy (document, { line; column })) ->
let (istate, ctx, entry, _) = update_file_ctx istate document in
let results =
Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () ->
ServerTypeHierarchy.go_quarantined ~ctx ~entry ~line ~column)
in
Lwt.return (Initialized istate, Ok results)
(* Code actions (refactorings, quickfixes) *)
| (Initialized istate, Code_action (document, range)) ->
let (istate, ctx, entry, published_errors_ref) =
update_file_ctx istate document
in
let results =
Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () ->
Server_code_actions_services.go ~ctx ~entry ~range)
in
(* We'll take this opportunity to make sure we've returned the latest errors.
Why only return errors from didOpen,didChange,didClose,codeAction, and not also all
the other methods like "hover" which might have recomputed TAST+errors? -- simplicity,
mainly -- it's simpler to perform+handle this logic in just a few places rather than
everywhere, and also because codeAction is called so frequently (e.g. upon changing
tabs) that it's the best opportunity we have. *)
let errors = get_user_facing_errors ~ctx ~entry in
let errors_opt =
match !published_errors_ref with
| Some published_errors when phys_equal published_errors errors ->
(* If the previous errors we returned are physically equal, that's an indication
that the entry's TAST+errors hasn't been recomputed since last we returned errors
back to clientLsp, so no need to do anything.
And we actively WANT to do nothing in this case, since codeAction is called so frequently --
e.g. every time the caret moves -- and we wouldn't want errors to be republished that
frequently. *)
None
| Some _
| None ->
(* [Some _] -> This case indicates either that we'd previously returned errors back to clientLsp
but the TAST+errors has changed since then, e.g. maybe the TAST+errors were invalidated
due to a decl change, and some other action like hover recomputed the TAST+errors but
didn't return them to clientLsp (because hover doesn't return errors), and so it's
fallen to us to send them back. Note: only didOpen,didChange,didClose,codeAction
ever return errors back to clientLsp. *)
(* [None] -> This case indicates that we don't have a record of previous errors returned back to clientLsp.
Might happen because a decl change invalidated TAST+errors and we are the first action since
the decl change. Or because for some reason didOpen didn't arrive prior to codeAction. *)
published_errors_ref := Some errors;
Some (Errors.sort_and_finalize errors)
in
Lwt.return (Initialized istate, Ok (results, errors_opt))
(* Code action resolve (refactorings, quickfixes) *)
| ( Initialized istate,
Code_action_resolve { document; range; resolve_title; use_snippet_edits }
) ->
let (istate, ctx, entry, _) = update_file_ctx istate document in
let result =
Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () ->
Server_code_actions_services.resolve
~ctx
~entry
~range
~resolve_title
~use_snippet_edits)
in
Lwt.return (Initialized istate, Ok result)
(* Go to definition *)
| (Initialized istate, Definition (document, { line; column })) ->
let (istate, ctx, entry, _) = update_file_ctx istate document in
let result =
Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () ->
ServerGoToDefinition.go_quarantined ~ctx ~entry ~line ~column)
in
Lwt.return (Initialized istate, Ok result)
(* Type Definition *)
| (Initialized istate, Type_definition (document, { line; column })) ->
let (istate, ctx, entry, _) = update_file_ctx istate document in
let result =
Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () ->
ServerTypeDefinition.go_quarantined ~ctx ~entry ~line ~column)
in
Lwt.return (Initialized istate, Ok result)
(* Workspace Symbol *)
| (Initialized istate, Workspace_symbol query) ->
(* Note: needs reverse-naming-table, hence only works in initialized
state: for top-level queries it needs reverse-naming-table to look
up positions; for member queries "Foo::bar" it needs it to fetch the
decl for Foo. *)
(* Note: we intentionally don't give results from unsaved files *)
let ctx = make_empty_ctx istate.icommon in
let sienv_ref = ref istate.sienv in
let result = ServerSearch.go ctx query ~kind_filter:"" sienv_ref in
let istate = { istate with sienv = !sienv_ref } in
Lwt.return (Initialized istate, Ok result)
let write_status ~(out_fd : Lwt_unix.file_descr) (state : state) : unit Lwt.t =
match state with
| Pending_init
| During_init _
| Failed_init _ ->
Lwt.return_unit
| Initialized { ifiles; _ } ->
if Relative_path.Set.is_empty ifiles.changed_files_to_process then
let%lwt () =
write_message
~out_fd
~message:
(ClientIdeMessage.Notification ClientIdeMessage.Done_processing)
in
Lwt.return_unit
else
let total = ifiles.changed_files_denominator in
let processed =
total - Relative_path.Set.cardinal ifiles.changed_files_to_process
in
let%lwt () =
write_message
~out_fd
~message:
(ClientIdeMessage.Notification
(ClientIdeMessage.Processing_files
{ ClientIdeMessage.Processing_files.processed; total }))
in
Lwt.return_unit
(** Allow to process the next file change only if we have no new events to
handle. To ensure correctness, we would have to actually process all file
change events *before* we processed any other IDE queries. However, we're
trying to maximize availability, even if occasionally we give stale
results. We can revisit this trade-off later if we decide that the stale
results are baffling users. *)
let should_process_file_change
(in_fd : Lwt_unix.file_descr)
(message_queue : message_queue)
(istate : istate) : bool =
Lwt_message_queue.is_empty message_queue
&& (not (Lwt_unix.readable in_fd))
&& not (Relative_path.Set.is_empty istate.ifiles.changed_files_to_process)
let process_one_file_change (out_fd : Lwt_unix.file_descr) (istate : istate) :
istate Lwt.t =
let next_file =
Relative_path.Set.choose istate.ifiles.changed_files_to_process
in
let changed_files_to_process =
Relative_path.Set.remove istate.ifiles.changed_files_to_process next_file
in
let ClientIdeIncremental.{ naming_table; sienv; old_file_info; _ } =
ClientIdeIncremental.update_naming_tables_for_changed_file
~ctx:(make_empty_ctx istate.icommon)
~naming_table:istate.naming_table
~sienv:istate.sienv
~path:next_file
in
Option.iter
old_file_info
~f:
(Provider_utils.invalidate_local_decl_caches_for_file
istate.icommon.local_memory);
Relative_path.Map.iter istate.ifiles.open_files ~f:(fun _path (entry, _) ->
Provider_utils.invalidate_tast_cache_of_entry entry);
let changed_files_denominator =
if Relative_path.Set.is_empty changed_files_to_process then
0
else
istate.ifiles.changed_files_denominator
in
let istate =
{
naming_table;
sienv;
icommon = istate.icommon;
ifiles =
{
istate.ifiles with
changed_files_to_process;
changed_files_denominator;
};
}
in
let%lwt () = write_status ~out_fd (Initialized istate) in
Lwt.return istate
(** This function will either process one change that's pending,
or will await as necessary to handle one message. *)
let handle_one_message_exn
~(in_fd : Lwt_unix.file_descr)
~(out_fd : Lwt_unix.file_descr)
~(message_queue : message_queue)
~(state : state) : state option Lwt.t =
(* The precise order of operations is to help us be responsive
to requests, to never to await if there are pending changes to process,
but also to await for the next thing to do:
(1) If there's a message in [message_queue] then handle it;
(2) Otherwise if there's a message in [in_fd] then await until it
gets pumped into [message_queue] and then handle it;
(3) Otherwise if there are pending file-changes then process them;
(4) otherwise await until the next client request arrives in [in_fd]
and gets pumped into [message_queue] and then handle it. *)
match state with
| Initialized istate
when should_process_file_change in_fd message_queue istate ->
let%lwt istate = process_one_file_change out_fd istate in
Lwt.return_some (Initialized istate)
| _ ->
let%lwt message = Lwt_message_queue.pop message_queue in
(match (state, message) with
| (_, None) ->
Lwt.return_none (* exit loop if message_queue has been closed *)
| (During_init dstate, Some (GotNamingTable naming_table_result)) ->
let%lwt state = initialize2 out_fd dstate naming_table_result in
Lwt.return_some state
| (_, Some (GotNamingTable _)) ->
failwith ("Unexpected GotNamingTable in " ^ state_to_log_string state)
| (_, Some (ClientRequest { ClientIdeMessage.tracking_id; message })) ->
let unblocked_time = Unix.gettimeofday () in
let%lwt (state, response) =
try%lwt
let%lwt (s, r) =
handle_request message_queue state tracking_id message
in
Lwt.return (s, r)
with
| exn ->
(* Our caller has an exception handler which logs the exception.
But we instead must fulfil our contract of responding to the client,
even if we have an exception. Hence we need our own handler here. *)
let e = Exception.wrap exn in
let reason = ClientIdeUtils.make_rich_error "handle_request" ~e in
Lwt.return (state, Error (ClientIdeUtils.to_lsp_error reason))
in
let%lwt () =
write_message
~out_fd
~message:
ClientIdeMessage.(
Response { response; tracking_id; unblocked_time })
in
Lwt.return_some state)
let serve ~(in_fd : Lwt_unix.file_descr) ~(out_fd : Lwt_unix.file_descr) :
unit Lwt.t =
let rec flush_event_logger () : unit Lwt.t =
let%lwt () = Lwt_unix.sleep 0.5 in
HackEventLogger.Memory.profile_if_needed ();
Lwt.async EventLoggerLwt.flush;
EventLogger.recheck_disk_files ();
flush_event_logger ()
in
let rec pump_stdin (message_queue : message_queue) : unit Lwt.t =
let%lwt (message, is_queue_open) =
try%lwt
let%lwt { ClientIdeMessage.tracking_id; message } =
Marshal_tools_lwt.from_fd_with_preamble in_fd
in
let is_queue_open =
Lwt_message_queue.push
message_queue
(ClientRequest { ClientIdeMessage.tracking_id; message })
in
Lwt.return (message, is_queue_open)
with
| End_of_file ->
(* There are two proper ways to close clientIdeDaemon: (1) by sending it a Shutdown message
over the FD which is handled above, or (2) by closing the FD which is handled here. Neither
path is considered anomalous and neither will raise an exception.
Note that closing the message-queue is how we tell handle_messages loop to terminate. *)
Lwt_message_queue.close message_queue;
Lwt.return (ClientIdeMessage.Shutdown (), false)
| exn ->
let e = Exception.wrap exn in
Lwt_message_queue.close message_queue;
Exception.reraise e
in
match message with
| ClientIdeMessage.Shutdown () -> Lwt.return_unit
| _ when not is_queue_open -> Lwt.return_unit
| _ ->
(* Care! The following call should be tail recursive otherwise we'll get huge callstacks.
The [@tailcall] attribute would normally enforce this, but doesn't help the presence of lwt. *)
(pump_stdin [@tailcall]) message_queue
in
let rec handle_messages ({ message_queue; state } : t) : unit Lwt.t =
let%lwt next_state_opt =
try%lwt
let%lwt state =
handle_one_message_exn ~in_fd ~out_fd ~message_queue ~state
in
Lwt.return state
with
| exn ->
let e = Exception.wrap exn in
ClientIdeUtils.log_bug "handle_one_message" ~e ~telemetry:true;
if is_outfd_write_error e then exit 1;
(* if out_fd is down then there's no use continuing. *)
Lwt.return_some state
in
match next_state_opt with
| None -> Lwt.return_unit (* exit loop *)
| Some state ->
(* Care! The following call should be tail recursive otherwise we'll get huge callstacks.
The [@tailcall] attribute would normally enforce this, but doesn't help the presence of lwt. *)
(handle_messages [@tailcall]) { message_queue; state }
in
try%lwt
let message_queue = Lwt_message_queue.create () in
let flusher_promise = flush_event_logger () in
let%lwt () = handle_messages { message_queue; state = Pending_init }
and () = pump_stdin message_queue in
Lwt.cancel flusher_promise;
Lwt.return_unit
with
| exn ->
let e = Exception.wrap exn in
ClientIdeUtils.log_bug "fatal clientIdeDaemon" ~e ~telemetry:true;
Lwt.return_unit
let daemon_main
(args : ClientIdeMessage.daemon_args)
(channels : ('a, 'b) Daemon.channel_pair) : unit =
Folly.ensure_folly_init ();
Printexc.record_backtrace true;
let (ic, oc) = channels in
let in_fd = Lwt_unix.of_unix_file_descr (Daemon.descr_of_in_channel ic) in
let out_fd = Lwt_unix.of_unix_file_descr (Daemon.descr_of_out_channel oc) in
let daemon_init_id =
Printf.sprintf
"%s.%s"
args.ClientIdeMessage.init_id
(Random_id.short_string ())
in
HackEventLogger.serverless_ide_init ~init_id:daemon_init_id;
if args.ClientIdeMessage.verbose_to_stderr then
Hh_logger.Level.set_min_level_stderr Hh_logger.Level.Debug
else
Hh_logger.Level.set_min_level_stderr Hh_logger.Level.Error;
if args.ClientIdeMessage.verbose_to_file then
Hh_logger.Level.set_min_level_file Hh_logger.Level.Debug
else
Hh_logger.Level.set_min_level_file Hh_logger.Level.Info;
Lwt_utils.run_main (fun () -> serve ~in_fd ~out_fd)
let daemon_entry_point : (ClientIdeMessage.daemon_args, unit, unit) Daemon.entry
=
Daemon.register_entry_point "ClientIdeService" daemon_main |
OCaml Interface | hhvm/hphp/hack/src/client/ide_service/clientIdeDaemon.mli | (*
* Copyright (c) 2019, 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.
*
*)
val daemon_entry_point : (ClientIdeMessage.daemon_args, unit, unit) Daemon.entry |
OCaml | hhvm/hphp/hack/src/client/ide_service/clientIdeIncremental.ml | (*
* Copyright (c) 2019, 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 log s = Hh_logger.log ("[ide-incremental] " ^^ s)
let log_debug s = Hh_logger.debug ("[ide-incremental] " ^^ s)
(** Print file change *)
let log_file_info_change
~(old_file_info : FileInfo.t option)
~(new_file_info : FileInfo.t option)
~(path : Relative_path.t) : unit =
let verb =
match (old_file_info, new_file_info) with
| (Some _, Some _) -> "updated"
| (Some _, None) -> "deleted"
| (None, Some _) -> "added"
| (None, None) ->
(* May or may not indicate a bug in either the language client or the
language server.
- Could happen if the language client sends spurious notifications.
- Could happen if the editor writes files in a certain way, such as if
they delete the file before moving a new one into place.
- Could happen if the language server was not able to read the file,
despite it existing on disk (e.g. due to permissions). In this case,
we would fail to generate its [FileInfo.t] and assume that it was
deleted. This is correct from a certain point of view.
- Could happen due to a benign race condition where we process
file-change notifications more slowly than they happen. If a file is
quickly created, then deleted before we process the create event,
we'll think it was deleted twice. This is the correct way to handle
the race condition.
*)
"spuriously updated"
in
log_debug "File changed: %s %s" (Relative_path.to_absolute path) verb
(* TODO(T150077239): deprecate. *)
(** This fetches the new names out of the modified file. *)
let compute_fileinfo_for_path
(popt : ParserOptions.t) (contents : string option) (path : Relative_path.t)
: FileInfo.t option =
match contents with
| None -> None
(* The file couldn't be read from disk. Assume it's been deleted or is
otherwise inaccessible. Our caller will delete the entries from the
naming and reverse naming table; there's nothing for us to do here. *)
| Some contents ->
Some
(Direct_decl_parser.parse_and_hash_decls
(DeclParserOptions.from_parser_options popt)
(ParserOptions.deregister_php_stdlib popt)
path
contents
|> Direct_decl_parser.decls_to_fileinfo path)
type changed_file_results = {
naming_table: Naming_table.t;
sienv: SearchUtils.si_env;
old_file_info: FileInfo.t option;
new_file_info: FileInfo.t option;
}
let should_update_changed_file (path : Relative_path.t) : bool =
Relative_path.is_root (Relative_path.prefix path)
&& FindUtils.path_filter path
let update_naming_tables_for_changed_file
~(ctx : Provider_context.t)
~(naming_table : Naming_table.t)
~(sienv : SearchUtils.si_env)
~(path : Relative_path.t) : changed_file_results =
if should_update_changed_file path then begin
(* note: clientIdeDaemon uses local-memory-backed file provider. This operation converts [path] to an absolute path, then tries to cat it.*)
let contents = File_provider.get_contents path in
let new_file_info =
compute_fileinfo_for_path (Provider_context.get_popt ctx) contents path
in
let old_file_info = Naming_table.get_file_info naming_table path in
log_file_info_change ~old_file_info ~new_file_info ~path;
(* update the reverse-naming-table, which is mutable storage owned by backend *)
Naming_provider.update
~backend:(Provider_context.get_backend ctx)
~path
~old_file_info
~new_file_info;
(* remove old FileInfo from forward-naming-table, then add new FileInfo *)
let naming_table =
match old_file_info with
| None -> naming_table
| Some _ -> Naming_table.remove naming_table path
in
let naming_table =
match new_file_info with
| None -> naming_table
| Some new_file_info ->
Naming_table.update naming_table path new_file_info
in
(* update search index *)
let sienv =
match new_file_info with
| None ->
SymbolIndexCore.remove_files
~sienv
~paths:(Relative_path.Set.singleton path)
| Some info ->
SymbolIndexCore.update_files
~ctx
~sienv
~paths:[(path, info, SearchUtils.TypeChecker)]
in
{ naming_table; sienv; old_file_info; new_file_info }
end else begin
log "Ignored change to file %s" (Relative_path.to_absolute path);
{ naming_table; sienv; old_file_info = None; new_file_info = None }
end
module Batch = struct
external batch_index_root_relative_paths_only :
DeclParserOptions.t ->
bool ->
Path.t ->
Relative_path.t list ->
(Relative_path.t * (FileInfo.t * SearchTypes.si_addendum list) option) list
= "batch_index_hackrs_ffi_root_relative_paths_only"
type changed_file_info = {
path: Relative_path.t;
old_file_info: FileInfo.t option;
new_file_info: FileInfo.t option;
}
type update_result = {
naming_table: Naming_table.t;
sienv: SearchUtils.si_env;
changes: changed_file_info list;
}
(** For each path, direct decl parse to compute the names and positions in the file. If the file at the path doesn't exist, return [None]. *)
let compute_file_info_batch_root_relative_paths_only
(popt : ParserOptions.t) (paths : Relative_path.t list) :
(Relative_path.t * (FileInfo.t * SearchTypes.si_addendum list) option)
list =
batch_index_root_relative_paths_only
(DeclParserOptions.from_parser_options popt)
(ParserOptions.deregister_php_stdlib popt)
(Relative_path.path_of_prefix Relative_path.Root |> Path.make)
paths
let update_naming_tables_and_si
~(ctx : Provider_context.t)
~(naming_table : Naming_table.t)
~(sienv : SearchUtils.si_env)
~(changes : Relative_path.Set.t) : update_result =
log
"Batch change %d files, e.g. %s"
(Relative_path.Set.cardinal changes)
(Relative_path.Set.choose_opt changes
|> Option.value_map ~default:"[none]" ~f:Relative_path.suffix);
Relative_path.Set.filter changes ~f:(fun path ->
not @@ should_update_changed_file path)
|> Relative_path.Set.iter ~f:(fun ignored_path ->
log
"Ignored change to file %s"
(Relative_path.to_absolute ignored_path));
(* NOTE: our batch index/file info computation expects only files relative to root. *)
let batch_index_benchmark_start = Unix.gettimeofday () in
let index_result =
let changes_to_update =
Relative_path.Set.filter changes ~f:should_update_changed_file
in
compute_file_info_batch_root_relative_paths_only
(Provider_context.get_popt ctx)
(Relative_path.Set.elements changes_to_update)
in
log
"Batch index completed in %f seconds"
(Unix.gettimeofday () -. batch_index_benchmark_start);
let changed_file_infos =
List.map index_result ~f:(fun (path, new_file_info_with_addendum) ->
let old_file_info = Naming_table.get_file_info naming_table path in
{
path;
new_file_info = Option.map new_file_info_with_addendum ~f:fst;
old_file_info;
})
in
(* update the reverse-naming-table, which is mutable storage owned by backend *)
let update_reverse_naming_table_benchmark_start = Unix.gettimeofday () in
List.iter
changed_file_infos
~f:(fun { path; new_file_info; old_file_info } ->
Naming_provider.update
~backend:(Provider_context.get_backend ctx)
~path
~old_file_info
~new_file_info);
log
"Updated reverse naming table in %f seconds"
(Unix.gettimeofday () -. update_reverse_naming_table_benchmark_start);
(* update the forward-naming-table (file -> symbols) *)
(* remove old, then add new *)
let update_forward_naming_table_benchmark_start = Unix.gettimeofday () in
let naming_table =
List.fold_left
changed_file_infos
~init:naming_table
~f:(fun naming_table { path; old_file_info; _ } ->
match old_file_info with
| None -> naming_table
| Some _ -> Naming_table.remove naming_table path)
in
(* update new *)
let naming_table =
let paths_with_new_file_info =
List.filter_map changed_file_infos ~f:(fun { path; new_file_info; _ } ->
Option.map new_file_info ~f:(fun new_file_info ->
(path, new_file_info)))
in
Naming_table.update_many
naming_table
(paths_with_new_file_info |> Relative_path.Map.of_list)
in
log
"Updated forward naming table in %f seconds"
(Unix.gettimeofday () -. update_forward_naming_table_benchmark_start);
(* update search index *)
(* remove paths without new file info *)
let removing_search_index_files_benchmark_start = Unix.gettimeofday () in
let sienv =
let paths_without_new_file_info =
List.filter changed_file_infos ~f:(fun { new_file_info; _ } ->
Option.is_none new_file_info)
|> List.map ~f:(fun { path; _ } -> path)
|> Relative_path.Set.of_list
in
SymbolIndexCore.remove_files ~sienv ~paths:paths_without_new_file_info
in
log
"Removed files from search index in %f seconds"
(Unix.gettimeofday () -. removing_search_index_files_benchmark_start);
(* now update paths with new file info *)
let updating_search_index_new_files_benchmark_start =
Unix.gettimeofday ()
in
let sienv =
let get_addenda_opt (path, new_file_info_with_addenda_opt) =
Option.map
new_file_info_with_addenda_opt
~f:(fun (_new_file_info, addenda) ->
(path, addenda, SearchUtils.TypeChecker))
in
let paths_with_addenda =
List.filter_map index_result ~f:get_addenda_opt
in
SymbolIndexCore.update_from_addenda ~sienv ~paths_with_addenda
in
log
"Update search index with new files in %f seconds"
(Unix.gettimeofday () -. updating_search_index_new_files_benchmark_start);
{ naming_table; sienv; changes = changed_file_infos }
end |
OCaml Interface | hhvm/hphp/hack/src/client/ide_service/clientIdeIncremental.mli | (*
* Copyright (c) 2019, 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 changed_file_results = {
naming_table: Naming_table.t;
sienv: SearchUtils.si_env;
old_file_info: FileInfo.t option;
new_file_info: FileInfo.t option;
}
(** Updates the reverse-naming-table (which is inside ctx for the local
memory backend, and is a sharedmem heap for the sharedmem backend).
Returns an updated forward-naming-table in 'naming_table', and updated
symbol-search index in 'sienv'. It does this by by parsing the file at
the given path and reading their declarations. If the file could not be read,
it's assumed to be deleted, and so the old forward-naming-table indicates
which caches will have to be deleted by the caller.
Note: this function ignores non-root files,
and those that fail FindUtils.path_filter.
IO: this function uses File_provider to read the file. *)
val update_naming_tables_for_changed_file :
ctx:Provider_context.t ->
naming_table:Naming_table.t ->
sienv:SearchUtils.si_env ->
path:Relative_path.t ->
changed_file_results
module Batch : sig
type changed_file_info = {
path: Relative_path.t;
old_file_info: FileInfo.t option;
new_file_info: FileInfo.t option;
}
type update_result = {
naming_table: Naming_table.t;
sienv: SearchUtils.si_env;
changes: changed_file_info list;
}
(** Like [update_naming_tables_for_changed_file], but uses a Rust multi-threaded
indexer to parse files. TODO: will replace
[update_naming_tables_for_changed_file] when fully tested. *)
val update_naming_tables_and_si :
ctx:Provider_context.t ->
naming_table:Naming_table.t ->
sienv:SearchUtils.si_env ->
changes:Relative_path.Set.t ->
update_result
end |
OCaml | hhvm/hphp/hack/src/client/ide_service/clientIdeInit.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
type init_result = {
naming_table: Naming_table.t;
sienv: SearchUtils.si_env;
changed_files: Saved_state_loader.changed_files;
}
type 'a outcome =
| Success of 'a
| Failure of ClientIdeMessage.rich_error
| Skip of string
let error_from_load_error (load_error : Saved_state_loader.LoadError.t) :
ClientIdeMessage.rich_error =
let data =
Some
(Hh_json.JSON_Object
[
( "debug_details",
Hh_json.string_
(Saved_state_loader.LoadError.debug_details_of_error load_error)
);
])
in
let reason =
ClientIdeUtils.make_rich_error
(Saved_state_loader.LoadError.category_of_error load_error)
~data
in
(* [make_rich_error] returns a vague "IDE isn't working" message.
If load_error was actionable, then we can get more specific information
out of the load_error, although it's no longer IDE-specific. Instead
it says things like "zstd fault stopped Hack from working". We'll
get the best of both worlds with a vague IDE-specific message if
it's not actionable, or a precise non-IDE-specific message if it is. *)
if Saved_state_loader.LoadError.is_error_actionable load_error then
{
reason with
ClientIdeMessage.is_actionable = true;
short_user_message =
Saved_state_loader.LoadError.short_user_message_of_error load_error;
medium_user_message =
Saved_state_loader.LoadError.medium_user_message_of_error load_error;
long_user_message =
Saved_state_loader.LoadError.long_user_message_of_error load_error;
}
else
reason
(** LSP initialize method might directly contain the path of a saved-state to use.
Note: this path doesn't yet support changed_files. *)
let init_via_lsp
~(naming_table_load_info :
ClientIdeMessage.Initialize_from_saved_state.naming_table_load_info
option) : Path.t outcome Lwt.t =
match naming_table_load_info with
| None -> Lwt.return (Skip "no naming_table_load_info")
| Some naming_table_load_info ->
let open ClientIdeMessage.Initialize_from_saved_state in
(* tests may wish to pretend there's a delay *)
let%lwt () = Lwt_unix.sleep naming_table_load_info.test_delay in
Lwt.return (Success naming_table_load_info.path)
(** We might find a saved-state available for download, and download it. *)
let init_via_fetch
(ctx : Provider_context.t) ~(root : Path.t) ~(ignore_hh_version : bool) :
(Path.t * Saved_state_loader.changed_files) outcome Lwt.t =
let ssopt = TypecheckerOptions.saved_state (Provider_context.get_tcopt ctx) in
let%lwt load_result =
State_loader_lwt.load
~ssopt
~progress_callback:(fun _ -> ())
~watchman_opts:
Saved_state_loader.Watchman_options.{ root; sockname = None }
~ignore_hh_version
~saved_state_type:Saved_state_loader.Naming_and_dep_table_distc
in
match load_result with
| Ok { Saved_state_loader.main_artifacts; changed_files; _ } ->
let path =
main_artifacts
.Saved_state_loader.Naming_and_dep_table_info.naming_sqlite_table_path
in
Lwt.return (Success (path, changed_files))
| Error load_error -> Lwt.return (Failure (error_from_load_error load_error))
(** Performs a full index of [root], building a naming table on disk,
and then loading it. Also returns [si_addenda] from what we gathered
during the full index. *)
let init_via_build
~(config : ServerConfig.t) ~(root : Path.t) ~(hhi_root : Path.t) :
(Path.t * SymbolIndexCore.paths_with_addenda) outcome Lwt.t =
let path = Path.make (ServerFiles.client_ide_naming_table root) in
let rec poll_build_until_complete_exn progress =
match Naming_table_builder_ffi_externs.poll_exn progress with
| Some build_result -> Lwt.return build_result
| None ->
let%lwt () = Lwt_unix.sleep 0.1 in
poll_build_until_complete_exn progress
in
if not (ServerConfig.ide_fall_back_to_full_index config) then begin
Lwt.return (Skip "ide_fallback_to_full_index=false")
end else begin
let progress =
Naming_table_builder_ffi_externs.build
~www:root
~custom_hhi_path:hhi_root
~output:path
in
let%lwt build_result = poll_build_until_complete_exn progress in
match build_result with
| {
Naming_table_builder_ffi_externs.exit_status = 0;
time_taken_secs = _;
si_addenda;
} ->
let paths_with_addenda =
List.map si_addenda ~f:(fun (path, addenda) ->
(path, addenda, SearchUtils.TypeChecker))
in
Lwt.return (Success (path, paths_with_addenda))
| { Naming_table_builder_ffi_externs.exit_status; time_taken_secs = _; _ }
->
let data =
Some
(Hh_json.JSON_Object
[("naming_table_builder_exit_status", Hh_json.int_ exit_status)])
in
Lwt.return
(Failure (ClientIdeUtils.make_rich_error "full_index_error" ~data))
end
let init_via_find
(ctx : Provider_context.t)
~(local_config : ServerLocalConfig.t)
~(root : Path.t)
~(ignore_hh_version : bool) :
(Path.t * Saved_state_loader.changed_files) outcome Lwt.t =
if not local_config.ServerLocalConfig.ide_load_naming_table_on_disk then begin
Lwt.return (Skip "ide_load_naming_table_on_disk=false")
end else begin
let%lwt get_metadata_result =
State_loader_lwt.get_project_metadata
~opts:(Provider_context.get_tcopt ctx |> TypecheckerOptions.saved_state)
~progress_callback:(fun _ -> ())
~repo:root
~ignore_hh_version
~saved_state_type:Saved_state_loader.Naming_and_dep_table_distc
in
match get_metadata_result with
| Error (load_error, _telemetry) ->
Lwt.return (Failure (error_from_load_error load_error))
| Ok (project_metadata, _telemetry) -> begin
let%lwt load_off_disk_result =
State_loader_lwt.load_arbitrary_naming_table_from_disk
~saved_state_type:Saved_state_loader.Naming_and_dep_table_distc
~project_metadata
~threshold:
local_config.ServerLocalConfig.ide_naming_table_update_threshold
~root
in
match load_off_disk_result with
| Ok (path, changed_files) -> Lwt.return (Success (path, changed_files))
| Error err ->
let data = Some (Hh_json.JSON_Object [("err", Hh_json.string_ err)]) in
Lwt.return
(Failure (ClientIdeUtils.make_rich_error "find_failed" ~data))
end
end
(** This is a helper function used to add logging+telemetry to each
attempt at initializing the symbol table. Used like this:
[let%lwt result = attempt ... |> map_attempt key ~telemetry ~prev ~f]
Here [attempt ...] returns an Lwt.t representing the attempt that has been
kicked off. The return of [map_attempt] is a wrapper promise around that
underlying promise, one which adds logging and telemetry, including
any unhandled exceptions. *)
let map_attempt
(type a)
(key : string)
(ctx : Provider_context.t)
~(prev : Telemetry.t * ClientIdeMessage.rich_error)
~(f : a -> Path.t * Saved_state_loader.changed_files * SearchUtils.si_env)
(promise : a outcome Lwt.t) :
( Telemetry.t
* Naming_table.t
* Saved_state_loader.changed_files
* SearchUtils.si_env,
Telemetry.t * ClientIdeMessage.rich_error )
result
Lwt.t =
let start_time = Unix.gettimeofday () in
let (telemetry, prev_error) = prev in
Hh_logger.log "Init: %s?" key;
try%lwt
let%lwt result = promise in
match result with
| Success a ->
let (path, changed_files, sienv) = f a in
Hh_logger.log
"Init: %s ok, at %s, %d changed_files"
key
(Path.to_string path)
(List.length changed_files);
let naming_table =
Naming_table.load_from_sqlite ctx (Path.to_string path)
in
let telemetry =
telemetry
|> Telemetry.string_ ~key ~value:"winner"
|> Telemetry.duration ~start_time
in
Lwt.return_ok (telemetry, naming_table, changed_files, sienv)
| Skip reason ->
Hh_logger.log "Init: %s skipped - %s" key reason;
let telemetry = telemetry |> Telemetry.string_ ~key ~value:reason in
Lwt.return_error (telemetry, prev_error)
| Failure reason ->
let { ClientIdeMessage.category; data; _ } = reason in
let data = Option.value data ~default:Hh_json.JSON_Null in
Hh_logger.log
"Init: %s error - %s - %s"
key
category
(Hh_json.json_to_string data);
let telemetry =
telemetry
|> Telemetry.object_
~key
~value:
(Telemetry.create ()
|> Telemetry.duration ~start_time
|> Telemetry.string_ ~key:"error" ~value:category
|> Telemetry.json_ ~key:"data" ~value:data)
in
Lwt.return_error (telemetry, reason)
with
| exn ->
let e = Exception.wrap exn in
(* unhandled exception from the attempt itself, or from loading the found sqlite *)
let reason = ClientIdeUtils.make_rich_error ~e (key ^ " exn") in
Hh_logger.log "Init: %s exn - %s" key (Exception.to_string e);
let telemetry =
telemetry
|> Telemetry.object_
~key
~value:
(Telemetry.create ()
|> Telemetry.duration ~start_time
|> Telemetry.exception_ ~e)
in
Lwt.return_error (telemetry, reason)
let init
~(config : ServerConfig.t)
~(local_config : ServerLocalConfig.t)
~(param : ClientIdeMessage.Initialize_from_saved_state.t)
~(hhi_root : Path.t)
~(local_memory : Provider_backend.local_memory) :
(init_result, ClientIdeMessage.rich_error) result Lwt.t =
let start_time = Unix.gettimeofday () in
let open ClientIdeMessage.Initialize_from_saved_state in
let root = param.root in
let ignore_hh_version = param.ignore_hh_version in
let naming_table_load_info = param.naming_table_load_info in
let popt = ServerConfig.parser_options config in
let tcopt = ServerConfig.typechecker_options config in
let ctx =
Provider_context.empty_for_tool
~popt
~tcopt
~backend:(Provider_backend.Local_memory local_memory)
~deps_mode:(Typing_deps_mode.InMemoryMode None)
in
let sienv =
SymbolIndex.initialize
~gleanopt:(ServerConfig.glean_options config)
~namespace_map:(ParserOptions.auto_namespace_map tcopt)
~provider_name:
local_config.ServerLocalConfig.ide_symbolindex_search_provider
~quiet:local_config.ServerLocalConfig.symbolindex_quiet
~savedstate_file_opt:local_config.ServerLocalConfig.symbolindex_file
~workers:None
in
(* We will make several attempts using different techniques, in order, to try
to find a saved-state, and use the first attempt to succeed.
The goal of this code is (1) rich telemetry about why each attempt failed,
(2) in case none of them succeed, then return a user-facing
[ClientIdeMessage.rich_error] that has the most pertinent information for the user.
An attempt might either skip (e.g. if config flags disable it), or it might fail.
The way I've solved goal (2) is that we'll display a user-facing message
about the final failed attempt.
There are some subtle interactions here worth drawing attention to, based on how
various libraries were written that we call into:
1. [init_via_find] returns Skip if ide_load_naming_table_on_disk=false, but it
returns Failure if there were no saved-states on disk, or none were recent enough,
or if it found a candidate but experienced a runtime failure trying to use it.
2. [init_via_fetch] doesn't ever return Skip; it only uses Failure. This makes
sense in cases like manifold crash or zstd crash, but it's a bit odd in cases
like the user modified .hhconfig so no saved-state is possible, or the user
is in a repository that doesn't even have saved-states.
How does all this fit together to satisfy goal (2)? If we're in a repository that
allows building (i.e. its .hhconfig lacks "ide_fallback_to_full_index=false") then
the user-facing message upon overall failure will only ever be about the failure to build.
If we're in a repository that doesn't allow building, then the user-facing message
message upon overall failure will only ever be about the failure to load saved-state.
How does it satisfy goal (1)? Inside [map_attempt], if there was a "skip" then we
only store brief telemetry about it. But if there was a "failure" then we store
very detailed telemetry. Once ide_load_naming_table_on_disk is fully rolled out,
we'll end up storing detailed telemetry about every single "failed to find on disk".
That's good! I fully hope and expect that 99% of users will find something on disk
and be good. But if that fails, we'll always store rich information about every
"failed to fetch". That's also what we want. *)
(* As mentioned, Skip will result in the previous error message falling through.
So we have to seed with an initial [prev] -- even though some of the attempts never
return Skip and so this [prev] never makes its way through to the end! *)
let prev =
(Telemetry.create (), ClientIdeUtils.make_rich_error "trying...")
in
(* Specified in the LSP initialize message? *)
let%lwt result =
init_via_lsp ~naming_table_load_info
|> map_attempt "lsp" ctx ~prev ~f:(fun path -> (path, [], sienv))
in
(* Find on disk? *)
let%lwt result =
match result with
| Ok _ -> Lwt.return result
| Error prev ->
init_via_find ctx ~local_config ~root ~ignore_hh_version
|> map_attempt "find" ctx ~prev ~f:(fun (path, changed_files) ->
(path, changed_files, sienv))
in
(* Fetch? *)
let%lwt result =
match result with
| Ok _ -> Lwt.return result
| Error prev ->
init_via_fetch ctx ~root ~ignore_hh_version
|> map_attempt "fetch" ctx ~prev ~f:(fun (path, changed_files) ->
(path, changed_files, sienv))
in
(* Build? *)
let%lwt result =
match result with
| Ok _ -> Lwt.return result
| Error prev ->
init_via_build ~config ~root ~hhi_root
|> map_attempt "build" ctx ~prev ~f:(fun (path, paths_with_addenda) ->
let sienv =
SymbolIndexCore.update_from_addenda ~sienv ~paths_with_addenda
in
(path, [], sienv))
in
match result with
| Ok (telemetry, naming_table, changed_files, sienv) ->
HackEventLogger.serverless_ide_load_naming_table
~start_time
~local_file_count:(Some (List.length changed_files))
telemetry;
Lwt.return_ok { naming_table; sienv; changed_files }
| Error (telemetry, e) ->
HackEventLogger.serverless_ide_load_naming_table
~start_time
~local_file_count:None
telemetry;
Lwt.return_error e |
OCaml Interface | hhvm/hphp/hack/src/client/ide_service/clientIdeInit.mli | (*
* 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.
*
*)
(** Success case for [init]. *)
type init_result = {
naming_table: Naming_table.t;
(** An open connection to sqlite naming-table file. (Naming_table.t is able to store an in-memory
delta, but in our case the result of [init] always has an empty delta.) *)
sienv: SearchUtils.si_env;
(** search+autocomplete index, either full (in case we built) or delta
plus a connection to whatever symbolindex is specified in hh.conf and .hhconfig
(in other cases) *)
changed_files: Saved_state_loader.changed_files;
(** files changed between saved-state and "now", for some arbitrary value of "now"
during the execution of [init]. For race-freedom, the caller will need to set up
some subscription for change-notifications prior to calling [init]. *)
}
(** "Initialization" for clinetIdeDaemon means setting up naming-table and search-index
and figuring out what files have changed and need to be indexed.
We uses a strategy of "lsp/find/fetch/build":
1. [LSP] If the LSP initialize request contains the path of a naming-table
then use it, trust that there are no files-changed since that saved-state, and initialize sienv empty
2. [FIND] Otherwise, (if ide_load_naming_table_on_disk) look for any saved-state already on disk
in the canonical location /tmp/hh_server that's within an age threshold,
and if found then use it, ask mercurial for files changed since that saved-state,
and initialize sienv empty
3. [FETCH] Otherwise, try [State_loader_lwt.load] which uses manifold to look for
the best saved-state. If one is found then download it, ask mercurial for
files changed since that saved-state, and initialize sienv empty
4. [BUILD] Otherwise, if .hhconfig allows fall_back_to_full_index (default true) then do a fast
multi-core build of the naming-table-sqlite, initialize the naming-table with that,
deem that there are no files changed since the build, and initialize sienv with all the symbols that
we parsed while building the full naming table
5. Otherwise, error.
If a step determines that it's got an sqlite file path, but we subsequently error
while trying to open the sqlite file (e.g. it has zero size) then that counts as
failure and we continue on to the next attempt. Weird but true. *)
val init :
config:ServerConfig.t ->
local_config:ServerLocalConfig.t ->
param:ClientIdeMessage.Initialize_from_saved_state.t ->
hhi_root:Path.t ->
local_memory:Provider_backend.local_memory ->
(init_result, ClientIdeMessage.rich_error) result Lwt.t |
OCaml | hhvm/hphp/hack/src/client/ide_service/clientIdeMessage.ml | (*
* Copyright (c) 2019, 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 Initialize_from_saved_state = struct
type t = {
root: Path.t;
naming_table_load_info: naming_table_load_info option;
config: (string * string) list;
ignore_hh_version: bool;
open_files: Path.t list;
}
and naming_table_load_info = {
path: Path.t;
test_delay: float; (** artificial delay in seconds, for test purposes *)
}
end
type document = {
file_path: Path.t;
file_contents: string;
}
type location = {
line: int;
column: int;
}
type find_refs_result =
| Invalid_symbol
| Find_refs_success of {
full_name: string; (** from [SymbolDefinition.full_name] *)
action: ServerCommandTypes.Find_refs.action option;
(** if true, then clientLsp should shell out to hh_server to collect more positions;
this action will specifiy what hh_server shoud look for. *)
hint_suffixes: string list;
(** in case of a shell-out, we will suggest hh_server to look in these root-relative paths first. *)
open_file_results: (string * Pos.absolute) list Lsp.UriMap.t;
(** All references that were found in all open files in clientIdeDaemon. *)
}
type rename_result =
| Not_renameable_position
| Rename_success of {
shellout:
(Relative_path.t SymbolDefinition.t
* ServerCommandTypes.Find_refs.action)
option;
local: ServerRenameTypes.patch list;
}
type go_to_impl_result =
| Invalid_symbol_impl
| Go_to_impl_success of
(string
* ServerCommandTypes.Find_refs.action
* Pos.absolute list Lsp.UriMap.t)
type completion_request = { is_manually_invoked: bool }
type should_calculate_errors = { should_calculate_errors: bool }
(* GADT for request/response types. See [ServerCommandTypes] for a discussion on
using GADTs in this way. *)
type _ t =
| Initialize_from_saved_state : Initialize_from_saved_state.t -> unit t
(** Invariant: the client sends no messages to the daemon before
Initialize_from_state. And the daemon sends no messages before
it has responded. *)
| Shutdown : unit -> unit t
| Did_change_watched_files : Relative_path.Set.t -> unit t
(** This might include deleted files. The caller is responsible for filtering,
and resolving symlinks (even resolving root symlink for a deleted file...) *)
| Did_open_or_change :
document * should_calculate_errors
-> Errors.finalized_error list option t
(** if the bool is true, it will send back an error-list;
if false, it will return None. *)
| Did_close : Path.t -> Errors.finalized_error list t
(** This returns diagnostics for the file as it is on disk.
This is to serve the following scenario: (1) file was open with
modified contents and squiggles appropriate to the modified contents,
(2) user closes file without saving. In this scenario we must
restore squiggles to what would be appropriate for the file on disk.
It'd be possible to return an [Errors.t option], and only return [Some]
if the file had been closed while modified, if perf here is ever a concern. *)
| Verbose_to_file : bool -> unit t
| Hover : document * location -> HoverService.result t
| Definition :
document * location
-> ServerCommandTypes.Go_to_definition.result t
| Completion :
document * location * completion_request
-> AutocompleteTypes.ide_result t
(** Handles "textDocument/completion" LSP messages *)
| Completion_resolve_location :
Path.t * location * SearchTypes.si_kind
-> DocblockService.result t
(** "completionItem/resolve" LSP messages - if we have file/line/column.
The scenario is that VSCode requests textDocument/completion in A.PHP line 5 col 6,
and we responded with a completion item that points to a class defined in B.PHP line 10 col 5,
and now VSCode requests completionItem/resolve [(B.PHP, {line=10; column=5;}, class)],
and this method will look up B.PHP to find the docblock for that class and return it.
Typically B.PHP won't even be open. That's why we only provide it as Path.t *)
| Completion_resolve :
string * SearchTypes.si_kind
-> DocblockService.result t
(** "completionItem/resolve" LSP messages - if we have symbol name, and [Completion_resolve_location] failed *)
| Document_highlight : document * location -> Ide_api_types.range list t
(** Handles "textDocument/documentHighlight" LSP messages *)
| Document_symbol : document -> FileOutline.outline t
(** Handles "textDocument/documentSymbol" LSP messages *)
| Workspace_symbol : string -> SearchUtils.result t
| Go_to_implementation :
document * location * document list
-> go_to_impl_result t
| Find_references : document * location * document list -> find_refs_result t
| Rename : document * location * string * document list -> rename_result t
(** The result of Rename is one of:
- Not_renameable_position, indicating an attempt to rename something that isn't a valid symbol
- Rename_success, where we return a record containing two fields:
- [shellout], an optional tuple of (SymbolDefinition.full_name * Find_refs.action)
to indicate that ClientIdeDaemon could not satisfy all of the rename (the non-localvar case)
- [local], a [ServerRenameTypes.patch list], a list of rename patches for each open file supplied
in the input document list
*)
| Type_definition :
document * location
-> ServerCommandTypes.Go_to_type_definition.result t
(** Handles "textDocument/typeDefinition" LSP messages *)
| Signature_help : document * location -> Lsp.SignatureHelp.result t
(** Handles "textDocument/signatureHelp" LSP messages *)
| Code_action :
document * Ide_api_types.range
-> (Lsp.CodeAction.command_or_action list
* Errors.finalized_error list option)
t
(** Handles "textDocument/codeActions" LSP messages.
Also, we take this as a handy opportunity to send updated [Errors.t]
to clientLsp so it can publish them. We return [None] if the TAST+errors
haven't changed since they were last sent to clientLsp (through didOpen,
didChange, didClose or an earlier codeAction), and [Some] if they have
been changed.
Why send errors in code-action? It's for the scenario where file A.PHP
is open, file B.PHP changes on disk (e.g. due to user saving it), which
invalidates the TAST+errors of A.PHP, and we might therefore need to send
updated errors. For efficiency we chose to do this lazily when the user
interacts with A.PHP or switches tab to it, rather than doing every single
open file up-front. We could have sent updated errors on every single action,
e.g. hover and go-to-def. But settled for now on only doing it for codeAction
because this is called so frequently by VSCode (when you switch tab, and every
time the caret moves) in the hope that this will be a good balance of simple
code and decent experience. *)
| Code_action_resolve : {
document: document;
range: Ide_api_types.range;
resolve_title: string;
use_snippet_edits: bool;
}
-> Lsp.CodeActionResolve.result t
| Type_Hierarchy : document * location -> ServerTypeHierarchyTypes.result t
(** Handles "textDocument/typeHierarchy" LSP messages *)
let t_to_string : type a. a t -> string = function
| Initialize_from_saved_state _ -> "Initialize_from_saved_state"
| Shutdown () -> "Shutdown"
| Did_change_watched_files paths ->
let paths =
paths |> Relative_path.Set.elements |> List.map ~f:Relative_path.suffix
in
let (files, remainder) = List.split_n paths 10 in
let remainder =
if List.is_empty remainder then
""
else
",..."
in
Printf.sprintf
"Did_change_watched_files(%s%s)"
(String.concat files)
remainder
| Did_open_or_change ({ file_path; _ }, { should_calculate_errors }) ->
Printf.sprintf
"Did_open_or_change(%s,%b)"
(Path.to_string file_path)
should_calculate_errors
| Did_close file_path ->
Printf.sprintf "Ide_file_closed(%s)" (Path.to_string file_path)
| Verbose_to_file verbose -> Printf.sprintf "Verbose_to_file(%b)" verbose
| Hover ({ file_path; _ }, _) ->
Printf.sprintf "Hover(%s)" (Path.to_string file_path)
| Definition ({ file_path; _ }, _) ->
Printf.sprintf "Definition(%s)" (Path.to_string file_path)
| Completion ({ file_path; _ }, _, _) ->
Printf.sprintf "Completion(%s)" (Path.to_string file_path)
| Completion_resolve (symbol, _) ->
Printf.sprintf "Completion_resolve(%s)" symbol
| Completion_resolve_location (file_path, _, _) ->
Printf.sprintf "Completion_resolve_location(%s)" (Path.to_string file_path)
| Document_highlight ({ file_path; _ }, _) ->
Printf.sprintf "Document_highlight(%s)" (Path.to_string file_path)
| Document_symbol { file_path; _ } ->
Printf.sprintf "Document_symbol(%s)" (Path.to_string file_path)
| Workspace_symbol query -> Printf.sprintf "Workspace_symbol(%s)" query
| Type_definition ({ file_path; _ }, _) ->
Printf.sprintf "Type_definition(%s)" (Path.to_string file_path)
| Signature_help ({ file_path; _ }, _) ->
Printf.sprintf "Signature_help(%s)" (Path.to_string file_path)
| Code_action ({ file_path; _ }, _) ->
Printf.sprintf "Code_action(%s)" (Path.to_string file_path)
| Code_action_resolve { document = { file_path; _ }; resolve_title; _ } ->
Printf.sprintf
"Code_action_resolve(%s, %s)"
(Path.to_string file_path)
resolve_title
| Go_to_implementation ({ file_path; _ }, _, _) ->
Printf.sprintf "Go_to_implementation(%s)" (Path.to_string file_path)
| Find_references ({ file_path; _ }, _, _) ->
Printf.sprintf "Find_references(%s)" (Path.to_string file_path)
| Rename ({ file_path; _ }, _, _, _) ->
Printf.sprintf "Rename(%s)" (Path.to_string file_path)
| Type_Hierarchy ({ file_path; _ }, _) ->
Printf.sprintf "Type_Hierarchy(%s)" (Path.to_string file_path)
type 'a tracked_t = {
tracking_id: string;
message: 'a t;
}
let tracked_t_to_string : type a. a tracked_t -> string =
fun { tracking_id; message } ->
Printf.sprintf "#%s: %s" tracking_id (t_to_string message)
module Processing_files = struct
type t = {
processed: int;
total: int;
}
let to_string (t : t) : string = Printf.sprintf "%d/%d" t.processed t.total
end
(** This can be used for user-facing messages as well as LSP error responses. *)
type rich_error = {
short_user_message: string;
(** max 20 chars, for status bar. Will be prepended by "Hack:" *)
medium_user_message: string;
(** max 10 words, for tooltip and alert. Will be postpended by " See <log>" *)
is_actionable: bool;
(** used to decide if we hould show window/showMessage, i.e. an alert *)
long_user_message: string;
(** max 5 lines, for window/logMessage, i.e. Output>Hack window. Will be postpended by "\nDetails: <url>" *)
category: string; (** used in LSP Error message and telemetry *)
data: Hh_json.json option; (** used in LSP Error message and telemetry *)
}
type notification =
| Done_init of (Processing_files.t, rich_error) result
| Processing_files of Processing_files.t
| Done_processing
let notification_to_string (n : notification) : string =
match n with
| Done_init (Ok p) ->
Printf.sprintf "Done_init(%s)" (Processing_files.to_string p)
| Done_init (Error edata) ->
Printf.sprintf "Done_init(%s)" edata.medium_user_message
| Processing_files p ->
Printf.sprintf "Processing_file(%s)" (Processing_files.to_string p)
| Done_processing -> "Done_processing"
type 'a timed_response = {
unblocked_time: float;
tracking_id: string;
response: ('a, Lsp.Error.t) result;
}
type message_from_daemon =
| Notification of notification
| Response : 'a timed_response -> message_from_daemon
let message_from_daemon_to_string (m : message_from_daemon) : string =
match m with
| Notification n -> notification_to_string n
| Response { response = Error { Lsp.Error.message; _ }; tracking_id; _ } ->
Printf.sprintf "#%s: Response_error(%s)" tracking_id message
| Response { response = Ok _; tracking_id; _ } ->
Printf.sprintf "#%s: Response_ok" tracking_id
type daemon_args = {
init_id: string;
verbose_to_stderr: bool;
verbose_to_file: bool;
} |
OCaml | hhvm/hphp/hack/src/client/ide_service/clientIdeService.ml | (*
* Copyright (c) 2019, 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 Status = struct
type t =
| Initializing
| Processing_files of ClientIdeMessage.Processing_files.t
| Rpc of Telemetry.t list
| Ready
| Stopped of ClientIdeMessage.rich_error
let is_ready (t : t) : bool =
match t with
| Ready -> true
| _ -> false
let to_log_string (t : t) : string =
match t with
| Initializing -> "Initializing"
| Processing_files p ->
Printf.sprintf
"Processing_files(%s)"
(ClientIdeMessage.Processing_files.to_string p)
| Rpc requests ->
Printf.sprintf
"Rpc [%s]"
(requests |> List.map ~f:Telemetry.to_string |> String.concat ~sep:",")
| Ready -> "Ready"
| Stopped { ClientIdeMessage.short_user_message; _ } ->
Printf.sprintf "Stopped(%s)" short_user_message
end
module Stop_reason = struct
type t =
| Crashed
| Closed
| Editor_exited
| Restarting
| Testing
let to_log_string (t : t) : string =
match t with
| Crashed -> "crashed"
| Closed -> "closed"
| Editor_exited -> "editor exited"
| Restarting -> "restarting"
| Testing -> "testing-only, you should not see this"
end
type state =
| Uninitialized
(** The ide_service is created. We may or may not have yet sent an
initialize message to the daemon. *)
| Failed_to_initialize of ClientIdeMessage.rich_error
(** The response to our initialize message was a failure. This is
a terminal state. *)
| Initialized of { status: Status.t }
(** We have received an initialize response from the daemon and all
is well. The only thing that can take us out of this state is if
someone invokes [stop], or if the daemon connection gets EOF. *)
| Stopped of ClientIdeMessage.rich_error
(** Someone called [stop] or the daemon connection got EOF.
This is a terminal state. This is the only state that arose
from actions on our side; all the other states arose from
responses from clientIdeDaemon. *)
let state_to_log_string (state : state) : string =
match state with
| Uninitialized -> Printf.sprintf "Uninitialized"
| Failed_to_initialize { ClientIdeMessage.category; _ } ->
Printf.sprintf "Failed_to_initialize(%s)" category
| Initialized env ->
Printf.sprintf "Initialized(%s)" (Status.to_log_string env.status)
| Stopped { ClientIdeMessage.category; _ } ->
Printf.sprintf "Stopped(%s)" category
type message_wrapper =
| Message_wrapper : 'a ClientIdeMessage.tracked_t -> message_wrapper
(** Existential type wrapper for `ClientIdeMessage.t`s, so that we can put
them in a queue without the typechecker trying to infer a concrete type for
`'a` based on its first use. *)
type message_queue = message_wrapper Lwt_message_queue.t
type response_wrapper =
| Response_wrapper : 'a ClientIdeMessage.timed_response -> response_wrapper
(** Similar to [Message_wrapper] above. *)
type response_emitter = response_wrapper Lwt_message_queue.t
type notification_emitter = ClientIdeMessage.notification Lwt_message_queue.t
module Active_rpc_requests = struct
type t = {
requests: Telemetry.t IMap.t;
(** These are requests which have been sent to the daemon but we haven't yet had
a response, e.g. if we sent requests #3 and #4 and #5 and a response #5 has come
back, then active would be #3 and #4. *)
counter: int;
(** Monotonically increasing counter, used as indices in [requests]. E.g. we might
at one moment have requests #3 and #4 active, while the counter is at #6. *)
}
let new_ () : t = { requests = IMap.empty; counter = 0 }
let add (telemetry : Telemetry.t) (t : t) : t * int =
let id = t.counter in
({ requests = IMap.add id telemetry t.requests; counter = id + 1 }, id)
let remove (id : int) (t : t) : t =
{ t with requests = IMap.remove id t.requests }
let is_empty (t : t) : bool = IMap.is_empty t.requests
let values (t : t) : Telemetry.t list = IMap.values t.requests
end
type t = {
mutable state: state;
mutable active_rpc_requests: Active_rpc_requests.t;
state_changed_cv: unit Lwt_condition.t;
(** Used to notify tasks when the state changes, so that they can wait for the
IDE service to be initialized. *)
daemon_handle: (unit, unit) Daemon.handle;
(** The handle to the daemon process backing the IDE service.
Note that `(unit, unit)` here refers to the input and output types of the
IDE service. However, we don't use the Daemon API's method of
producing/consuming these messages and instead do it with Lwt, so these
type parameters are not used. *)
in_fd: Lwt_unix.file_descr;
out_fd: Lwt_unix.file_descr;
messages_to_send: message_queue;
(** The queue of messages that we have yet to send to the daemon. *)
response_emitter: response_emitter;
(** The queue of responses that we received from RPC calls to the daemon. We
assume that we receive the responses in the same order that we sent their
requests. *)
notification_emitter: notification_emitter;
(** The queue of notifications that the daemon emitted. Notifications can be
emitted at any time, not just in response to an RPC call. *)
}
let log s = Hh_logger.log ("[ide-service] " ^^ s)
let log_debug s = Hh_logger.debug ("[ide-service] " ^^ s)
let set_state (t : t) (new_state : state) : unit =
log
"ClientIdeService.set_state %s -> %s"
(state_to_log_string t.state)
(state_to_log_string new_state);
t.state <- new_state;
Lwt_condition.broadcast t.state_changed_cv ()
let make (args : ClientIdeMessage.daemon_args) : t =
let daemon_handle =
Daemon.spawn
~channel_mode:`pipe
(Unix.stdin, Unix.stdout, Unix.stderr)
ClientIdeDaemon.daemon_entry_point
args
in
let (ic, oc) = daemon_handle.Daemon.channels in
let in_fd = Lwt_unix.of_unix_file_descr (Daemon.descr_of_in_channel ic) in
let out_fd = Lwt_unix.of_unix_file_descr (Daemon.descr_of_out_channel oc) in
{
state = Uninitialized;
active_rpc_requests = Active_rpc_requests.new_ ();
state_changed_cv = Lwt_condition.create ();
daemon_handle;
in_fd;
out_fd;
messages_to_send = Lwt_message_queue.create ();
response_emitter = Lwt_message_queue.create ();
notification_emitter = Lwt_message_queue.create ();
}
(** This function does an rpc to the daemon: it pushes a message
onto the daemon's stdin queue, then awaits until [serve] has stuck
the stdout response from the daemon response onto our [response_emitter].
The daemon updates [ref_unblocked_time], the time at which the
daemon starting handling the rpc.
The progress callback will be invoked during this call to rpc, at times
when the result of [get_status t] might have changed. It's designed
so the caller of rpc can, in their callback, invoke get_status and display
some kind of progress message.
Note: it is safe to call this method even while an existing rpc
is outstanding - we guarantee that results will be delivered in order.
Note: it is not safe to cancel this method, since we might end up
with no one reading the response to the message we just pushed, leading
to desync.
Note: If we're in Stopped state (due to someone calling [stop]) then
we'll refrain from sending the rpc. Stopped is the only state we enter
due to our own volition; all other states are just a reflection
of what state the daemon is in, and so it's fine for the daemon
to respond as it see fits while in the other states. *)
let rpc
(t : t)
~(tracking_id : string)
~(ref_unblocked_time : float ref)
~(progress : unit -> unit)
(message : 'a ClientIdeMessage.t) : ('a, Lsp.Error.t) Lwt_result.t =
let tracked_message = { ClientIdeMessage.tracking_id; message } in
try%lwt
match t.state with
| Stopped reason -> Lwt.return_error (ClientIdeUtils.to_lsp_error reason)
| Uninitialized
| Initialized _
| Failed_to_initialize _ ->
let success =
Lwt_message_queue.push
t.messages_to_send
(Message_wrapper tracked_message)
in
if not success then
(* queue closure is normal part of shutdown *)
failwith "Could not send message (queue was closed)";
(* If any rpc takes too long, we'll ask clientLsp to refresh status
a short time in, and then again when it's done. *)
let telemetry =
Telemetry.create ()
|> Telemetry.string_ ~key:"tracking_id" ~value:tracking_id
|> Telemetry.string_
~key:"message"
~value:(ClientIdeMessage.t_to_string message)
in
let (active, id) =
Active_rpc_requests.add telemetry t.active_rpc_requests
in
t.active_rpc_requests <- active;
let pingPromise = Lwt_unix.sleep 0.2 |> Lwt.map progress in
let%lwt (response : response_wrapper option) =
Lwt_message_queue.pop t.response_emitter
in
t.active_rpc_requests <-
Active_rpc_requests.remove id t.active_rpc_requests;
Lwt.cancel pingPromise;
progress ();
(* when might t.active_rpc_count <> 0? well, if the caller did
Lwt.pick [rpc t message1, rpc t message2], then active_rpc_count will
reach a peak of 2, then when the first rpc has finished it will go dowwn
to 1, then when the second rpc has finished it will go down to 0. *)
(* Discussion about why the following is safe, even if multiple people call rpc:
Imagine `let%lwt x = rpc(X) and y = rpc(Y)`.
We will therefore push X onto the [messages_to_send] queue, then
await [Lwt_message_queue.pop] on [response_emitter] for a response to X,
then we'll push Y onto the queue, then await pop for a response to Y.
The [messages_to_send] queue will necessarily send them in order X,Y.
The daemon will receive X,Y in order.
The daemon will handle X first (the daemon only handles a single message
at a time) and send it response, then handle Y next and send its response.
Our [serve] will read the responses to X,Y in order and put them onto
[response_emitter].
Why will "pop x" wake up and pick an element before "pop y" even though
they're both waiting? The crucial fact is that "pop x" was called
before "pop y". And [Lwt_message_queue.pop] is built upon
[Lwt_condition.wait], which in turn is built upon [Lwt_sequence.t]:
It maintains an ordered queue of callers who are awaiting on pop,
and when a new item arrives then it wakes up the first one. *)
(match response with
| Some (Response_wrapper timed_response)
when String.equal
tracked_message.ClientIdeMessage.tracking_id
timed_response.ClientIdeMessage.tracking_id ->
ref_unblocked_time := timed_response.ClientIdeMessage.unblocked_time;
let (response : ('a, Lsp.Error.t) result) =
Result.map ~f:Obj.magic timed_response.ClientIdeMessage.response
in
(* Obj.magic cast is safe because if we pushed an 'a request
then the daemon guarantees to return an 'a. *)
Lwt.return response
| Some _ ->
(* as discussed above, this case will never be hit. *)
failwith "ClientIdeService desync"
| None ->
(* queue closure is part of normal shutdown *)
failwith "Could not read response: queue was closed")
with
| exn ->
let e = Exception.wrap exn in
Lwt.return_error
(ClientIdeUtils.make_rich_error "rpc" ~e |> ClientIdeUtils.to_lsp_error)
let initialize_from_saved_state
(t : t)
~(root : Path.t)
~(naming_table_load_info :
ClientIdeMessage.Initialize_from_saved_state.naming_table_load_info
option)
~(config : (string * string) list)
~(ignore_hh_version : bool)
~(open_files : Path.t list) :
(unit, ClientIdeMessage.rich_error) Lwt_result.t =
let open ClientIdeMessage in
set_state t Uninitialized;
try%lwt
let message =
{
tracking_id = "init";
message =
Initialize_from_saved_state
{
Initialize_from_saved_state.root;
naming_table_load_info;
config;
ignore_hh_version;
open_files;
};
}
in
(* Can't use [rpc] here, since that depends on the [serve] event loop,
which is called only after we return. We rely on the invariant
that daemon will send us no messages until after it has responded
to this first message. *)
log_debug "-> %s [init]" (tracked_t_to_string message);
let%lwt (_ : int) =
Marshal_tools_lwt.to_fd_with_preamble t.out_fd message
in
let%lwt (response : message_from_daemon) =
Marshal_tools_lwt.from_fd_with_preamble t.in_fd
in
log_debug "<- %s [init]" (message_from_daemon_to_string response);
match response with
| Response { response = Ok _; tracking_id = "init"; _ } -> Lwt.return_ok ()
| Response { response = Error e; tracking_id = "init"; _ } ->
(* that error has structure, which we wish to preserve in our error_data. *)
Lwt.return_error
(ClientIdeUtils.make_rich_error
e.Lsp.Error.message
~data:e.Lsp.Error.data)
| _ ->
(* What we got back wasn't the 'init' response we expected:
the clientIdeDaemon has violated its contract. *)
failwith ("desync: " ^ message_from_daemon_to_string response)
with
| exn ->
let e = Exception.wrap exn in
let reason = ClientIdeUtils.make_rich_error "init_failed" ~e in
set_state t (Failed_to_initialize reason);
Lwt.return_error reason
let process_status_notification
(t : t) (notification : ClientIdeMessage.notification) : unit =
let open ClientIdeMessage in
let open ClientIdeMessage.Processing_files in
match (t.state, notification) with
| (Failed_to_initialize _, _)
| (Stopped _, _) ->
(* terminal states, which don't change with notifications *)
()
| (Uninitialized, Done_init (Ok { total = 0; _ })) ->
set_state t (Initialized { status = Status.Ready })
| (Uninitialized, Done_init (Ok p)) ->
set_state t (Initialized { status = Status.Processing_files p })
| (Uninitialized, Done_init (Error edata)) ->
set_state t (Failed_to_initialize edata)
| (Initialized _, Processing_files p) ->
set_state t (Initialized { status = Status.Processing_files p })
| (Initialized _, Done_processing) ->
set_state t (Initialized { status = Status.Ready })
| (_, _) ->
let message =
Printf.sprintf
"Unexpected notification '%s' in state '%s'"
(ClientIdeMessage.notification_to_string notification)
(state_to_log_string t.state)
in
ClientIdeUtils.log_bug message ~telemetry:true;
()
let destroy (t : t) ~(tracking_id : string) : unit Lwt.t =
let%lwt () =
match t.state with
| Uninitialized
| Failed_to_initialize _
| Stopped _ ->
Lwt.return_unit
| Initialized _ ->
let open Lsp.Error in
let start_time = Unix.gettimeofday () in
let ref_unblocked_time = ref 0. in
let%lwt result =
try%lwt
Lwt.pick
[
rpc
t
~tracking_id
~ref_unblocked_time
~progress:(fun () -> ())
(ClientIdeMessage.Shutdown ());
(let%lwt () = Lwt_unix.sleep 5.0 in
Lwt.return_error
{ code = InternalError; message = "timeout"; data = None });
]
with
| exn ->
let e = Exception.wrap exn in
Lwt.return_error
(ClientIdeUtils.make_rich_error "destroy" ~e
|> ClientIdeUtils.to_lsp_error)
in
let () =
match result with
| Ok () -> HackEventLogger.serverless_ide_destroy_ok start_time
| Error { message; data; _ } ->
HackEventLogger.serverless_ide_destroy_error start_time message data;
log "ClientIdeService.destroy %s" message
in
Daemon.force_quit t.daemon_handle;
Lwt.return_unit
in
Lwt_message_queue.close t.messages_to_send;
Lwt_message_queue.close t.notification_emitter;
Lwt_message_queue.close t.response_emitter;
Lwt.return_unit
let stop
(t : t)
~(tracking_id : string)
~(stop_reason : Stop_reason.t)
~(e : Exception.t option) : unit Lwt.t =
(* we store both a user-facing reason here, and a programmatic error
for use in subsequent telemetry *)
let reason = ClientIdeUtils.make_rich_error "stop" ?e in
(* We'll stick the stop_reason into that programmatic error, so that subsequent
telemetry can pick it up. (It never affects the user-facing message.) *)
let items =
match reason.ClientIdeMessage.data with
| None -> []
| Some (Hh_json.JSON_Object items) -> items
| Some json -> [("data", json)]
in
let items =
("stop_reason", stop_reason |> Stop_reason.to_log_string |> Hh_json.string_)
:: items
in
let reason =
{ reason with ClientIdeMessage.data = Some (Hh_json.JSON_Object items) }
in
let%lwt () = destroy t ~tracking_id in
(* Correctness here is very subtle... During the course of that call to
'destroy', we do let%lwt on an rpc call to shutdown the daemon.
Either that will return in 5s, or it won't; either way, we will
synchronously force quit the daemon handle and close the message queue.
The interleaving we have to worry about is: what will other code
do while the state is still "Initialized", after we've sent the shutdown
message to the daemon, and we're let%lwt awaiting for a responnse?
Will anything go wrong?
Well, the daemon has responded to 'shutdown' by deleting its hhi dir
but leaving itself in its "Initialized" state.
Meantime, some of our code uses the state "Stopped" as a signal to not
do work, and some uses a closed message-queue as a signal to not do work
and neither is met. We might indeed receive further requests from
clientLsp and dutifully pass them on to the daemon and have it fail
weirdly because of the lack of hhi.
Luckily we're saved from that because clientLsp never makes rpc requests
to us after it has called 'stop'. *)
set_state t (Stopped reason);
Lwt.return_unit
let cleanup_upon_shutdown_or_exn (t : t) ~(e : Exception.t option) : unit Lwt.t
=
(* We are invoked with e=None when one of the message-queues has said that
it's closed. This indicates an orderly shutdown has been performed by 'stop'.
We are invoked with e=Some when we had an exception in our main serve loop. *)
let stop_reason =
match e with
| None ->
log "Normal shutdown due to message-queue closure";
Stop_reason.Closed
| Some e ->
ClientIdeUtils.log_bug "shutdown" ~e ~telemetry:true;
Stop_reason.Crashed
in
(* We might as well call 'stop' in both cases; there'll be no harm. *)
match t.state with
| Stopped _ -> Lwt.return_unit
| _ ->
log "Shutting down...";
let%lwt () = stop t ~tracking_id:"cleanup_or_shutdown" ~stop_reason ~e in
Lwt.return_unit
let rec serve (t : t) : unit Lwt.t =
(* Behavior of 'serve' is (1) take items from `messages_to_send` and send
then over the wire to the daemon, (2) take items from the wire from the
daemon and put them onto `notification_emitter` or `response_emitter` queues,
(3) keep doing this until we discover that a queue has been closed, which
is the "cancellation" signal for us to stop our loop.
The code looks a bit funny because the only way to tell if a queue is closed
is when we attemept to awaitingly-read or synchronously-write to it. *)
try%lwt
(* We mutate the data in `t` which is why we don't return a new `t` here. *)
let%lwt next_action =
(* Care! we only put things in a Pick which are safe to cancel. *)
Lwt.pick
[
(let%lwt outgoing_opt = Lwt_message_queue.pop t.messages_to_send in
match outgoing_opt with
| None -> Lwt.return `Close
| Some outgoing -> Lwt.return (`Outgoing outgoing));
(let%lwt () = Lwt_unix.wait_read t.in_fd in
Lwt.return `Incoming);
]
in
match next_action with
| `Close ->
let%lwt () = cleanup_upon_shutdown_or_exn t ~e:None in
Lwt.return_unit
| `Outgoing (Message_wrapper next_message) ->
log_debug "-> %s" (ClientIdeMessage.tracked_t_to_string next_message);
let%lwt (_ : int) =
Marshal_tools_lwt.to_fd_with_preamble t.out_fd next_message
in
serve t
| `Incoming ->
let%lwt (message : ClientIdeMessage.message_from_daemon) =
Marshal_tools_lwt.from_fd_with_preamble t.in_fd
in
log_debug "<- %s" (ClientIdeMessage.message_from_daemon_to_string message);
let queue_is_open =
match message with
| ClientIdeMessage.Notification notification ->
process_status_notification t notification;
Lwt_message_queue.push t.notification_emitter notification
| ClientIdeMessage.Response response ->
Lwt_message_queue.push t.response_emitter (Response_wrapper response)
in
if queue_is_open then
serve t
else
let%lwt () = cleanup_upon_shutdown_or_exn t ~e:None in
Lwt.return_unit
with
| exn ->
let e = Exception.wrap exn in
(* cleanup function below will log the exception *)
let%lwt () = cleanup_upon_shutdown_or_exn t ~e:(Some e) in
Lwt.return_unit
let get_notifications (t : t) : notification_emitter = t.notification_emitter
let get_status (t : t) : Status.t =
match t.state with
| Uninitialized -> Status.Initializing
| Failed_to_initialize error_data -> Status.Stopped error_data
| Stopped reason -> Status.Stopped reason
| Initialized { status } ->
if
Status.is_ready status
&& not (Active_rpc_requests.is_empty t.active_rpc_requests)
then
Status.Rpc (Active_rpc_requests.values t.active_rpc_requests)
else
status |
OCaml Interface | hhvm/hphp/hack/src/client/ide_service/clientIdeService.mli | (*
* Copyright (c) 2019, 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.
*
*)
(** Provides IDE services in the client, without an instance of hh_server
running.
Basic approach: we load the naming table to give us just enough symbol
information to provide IDE services for just the files you're looking at. When
we need to look up declarations to service an IDE query, we parse and typecheck
the files containing those declarations on-demand, then answer your IDE query.
*)
type t
module Status : sig
type t =
| Initializing
(** The IDE services are still initializing (e.g. loading saved-state or
building indexes.) *)
| Processing_files of ClientIdeMessage.Processing_files.t
(** The IDE services are available, but are also in the middle of
processing files. *)
| Rpc of Telemetry.t list
(** The IDE services will be available once they're done handling
one or more existing requests. The telemetry items are information
about each received request currently being performed. *)
| Ready (** The IDE services are available. *)
| Stopped of ClientIdeMessage.rich_error
(** The IDE services are not available. *)
end
module Stop_reason : sig
type t =
| Crashed (** clientIdeService encountered an unexpected bug *)
| Closed
(** clientIdeService shut down normally, although we've failed to record why *)
| Editor_exited (** clientLsp decided to close in response to shutdown*)
| Restarting
(** clientLsp decided to close this clientIdeService and start a new one *)
| Testing
(** test harnesses can tell clientLsp to shut down clientIdeService *)
val to_log_string : t -> string
end
(** Create an uninitialized IDE service. All queries made to this service will
fail immediately, unless otherwise requested in the initialization procedure. *)
val make : ClientIdeMessage.daemon_args -> t
(** Request that the IDE service initialize from the saved state. Queries made
to the service will fail until it is done initializing, unless
[wait_for_initialization] is [true], in which case queries made to the service
will block until the initializing is complete. *)
val initialize_from_saved_state :
t ->
root:Path.t ->
naming_table_load_info:
ClientIdeMessage.Initialize_from_saved_state.naming_table_load_info option ->
config:(string * string) list ->
ignore_hh_version:bool ->
open_files:Path.t list ->
(unit, ClientIdeMessage.rich_error) Lwt_result.t
(** Pump the message loop for the IDE service. Exits once the IDE service has
been [destroy]ed. *)
val serve : t -> unit Lwt.t
(** Clean up any resources held by the IDE service (such as the message loop
and background processes). Mark the service's status as "shut down" for the
given [reason]. *)
val stop :
t ->
tracking_id:string ->
stop_reason:Stop_reason.t ->
e:Exception.t option ->
unit Lwt.t
(** Make an RPC call to the IDE service. *)
val rpc :
t ->
tracking_id:string ->
ref_unblocked_time:float ref ->
progress:(unit -> unit) ->
'response ClientIdeMessage.t ->
('response, Lsp.Error.t) Lwt_result.t
(** Get a handle to the stream of notifications sent by the IDE service. These
notifications may be sent even during RPC requests, and so should be processed
asynchronously. *)
val get_notifications : t -> ClientIdeMessage.notification Lwt_message_queue.t
(** Get the status of the IDE services, based on the internal state and any
notifications that the IDE service process has sent to us. *)
val get_status : t -> Status.t |
OCaml | hhvm/hphp/hack/src/client/ide_service/clientIdeUtils.ml | (*
* Copyright (c) 2019, 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
type error = {
category: string;
data: Hh_json.json;
}
let make_error_internal
~(category : string) ~(data : Hh_json.json option) ~(e : Exception.t option)
: error =
let open Hh_json in
let (category, stack, desc) =
match e with
| None -> (category, Exception.get_current_callstack_string 99, "")
| Some e -> begin
let backtrace = Exception.get_backtrace_string e in
match Exception.to_exn e with
| Decl_class.Decl_heap_elems_bug details ->
(category ^ ": Decl_heap_elems_bug", backtrace, details)
| Decl_defs.Decl_not_found details ->
(category ^ ": Decl_not_found", backtrace, details)
| _ -> (category ^ ": " ^ Exception.get_ctor_string e, backtrace, "")
end
in
let stack = ("stack", stack |> Exception.clean_stack |> string_) in
let desc = ("desc", string_ desc) in
let elems =
match data with
| None -> [stack]
| Some (JSON_Object elems) ->
if List.Assoc.mem ~equal:String.equal elems "stack" then
elems
else
stack :: elems
| Some data -> [("data", data); stack; desc]
in
let data = Hh_json.JSON_Object elems in
{ category; data }
let log_bug
?(data : Hh_json.json option = None)
?(e : Exception.t option)
~(telemetry : bool)
(category : string) : unit =
let { category; data } = make_error_internal ~category ~e ~data in
Hh_logger.error "%s\n%s" category (Hh_json.json_to_string data);
if telemetry then HackEventLogger.serverless_ide_bug ~message:category ~data;
()
let make_rich_error
?(data : Hh_json.json option = None)
?(e : Exception.t option)
(category : string) : ClientIdeMessage.rich_error =
let { category; data } = make_error_internal ~category ~e ~data in
{
ClientIdeMessage.short_user_message = "failed";
medium_user_message = "Hack IDE support has failed.";
long_user_message =
"Hack IDE support has failed.\nThis is unexpected.\nPlease file a bug within your IDE, and try restarting it.";
is_actionable = false;
category;
data = Some data;
}
let to_lsp_error (reason : ClientIdeMessage.rich_error) : Lsp.Error.t =
{
Lsp.Error.code = Lsp.Error.UnknownErrorCode;
message = reason.ClientIdeMessage.category;
data = reason.ClientIdeMessage.data;
} |
OCaml Interface | hhvm/hphp/hack/src/client/ide_service/clientIdeUtils.mli | (*
* Copyright (c) 2019, 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.
*
*)
(** for when we encountered an internal bugs and we want to write to
the logfile, and optionally also record telemetry. *)
val log_bug :
?data:Hh_json.json option ->
?e:Exception.t ->
telemetry:bool ->
string ->
unit
(** for when we encountered an internal bug and want a user-facing problem report. *)
val make_rich_error :
?data:Hh_json.json option ->
?e:Exception.t ->
string ->
ClientIdeMessage.rich_error
val to_lsp_error : ClientIdeMessage.rich_error -> Lsp.Error.t |
hhvm/hphp/hack/src/client/ide_service/dune | (library
(name client_ide_service)
(wrapped false)
(modules clientIdeDaemon clientIdeIncremental clientIdeInit clientIdeService)
(libraries
client_ide_message
client_ide_utils
folly_stubs
lwt
lsp
package_config
package_info
rust_batch_index_ffi
server
server_autocomplete_services
server_env
server_env_build
server_go_to
server_highlight_refs
server_type_hierarchy
server_search
state_loader
naming_table_builder_ffi_externs
sys_utils)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name client_ide_message)
(wrapped false)
(modules clientIdeMessage)
(libraries lwt_utils server_command_types server_services sys_utils)
(preprocess
(pps lwt_ppx)))
(library
(name client_ide_utils)
(wrapped false)
(modules clientIdeUtils)
(libraries client_ide_message)
(preprocess
(pps lwt_ppx)))
(rule
(targets librust_batch_index_ffi.a)
(deps
(source_tree %{workspace_root}/hack/src))
(locks /cargo)
(action
(run
%{workspace_root}/hack/scripts/invoke_cargo.sh
rust_batch_index_ffi
rust_batch_index_ffi)))
(library
(name rust_batch_index_ffi)
(wrapped false)
(modules)
(foreign_archives rust_batch_index_ffi)) |
|
Rust | hhvm/hphp/hack/src/client/ide_service/rust_batch_index_ffi.rs | // 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.
use std::io;
use std::path::Path;
use std::path::PathBuf;
use anyhow::Result;
use bumpalo::Bump;
use ocamlrep_ocamlpool::ocaml_ffi;
use oxidized::decl_parser_options::DeclParserOptions;
use oxidized::file_info::FileInfo;
use oxidized::search_types::SiAddendum;
use oxidized_by_ref::direct_decl_parser::ParsedFileWithHashes;
use rayon::prelude::*;
use relative_path::RelativePath;
use unwrap_ocaml::UnwrapOcaml;
ocaml_ffi! {
fn batch_index_hackrs_ffi_root_relative_paths_only(
parser_options: DeclParserOptions,
deregister_php_stdlib_if_hhi: bool,
root: PathBuf,
filenames: Vec<RelativePath>,
) -> Vec<(RelativePath, Option<(FileInfo, Vec<SiAddendum>)>)> {
let filenames_and_contents = par_read_file_root_only(&root, filenames).unwrap_ocaml();
let filenames_and_contents: Vec<_> = filenames_and_contents
.into_par_iter()
.map(|(relpath, contents)| {
let contents = match contents {
Some(contents) => contents,
None => return (relpath, None)
};
let arena = Bump::new();
let parsed_file = direct_decl_parser::parse_decls_for_typechecking(
&parser_options,
relpath.clone(),
&contents,
&arena,
);
let with_hashes = ParsedFileWithHashes::new(
parsed_file,
deregister_php_stdlib_if_hhi,
relpath.prefix(),
&arena,
);
let addenda = si_addendum::get_si_addenda(&with_hashes);
let file_info: hackrs_provider_backend::FileInfo = with_hashes.into();
(relpath, Some((file_info, addenda)))
})
.collect();
filenames_and_contents.into_iter().map(|(relpath, contents)| {
(relpath, contents.map(|(with_hashes, addenda)| {
(with_hashes.into(), addenda)}))
}).collect()
}
}
// For each file in filenames, return a tuple of its path followed by `Some` of
// its contents if the file is found, otherwise `None`.
fn par_read_file_root_only(
root: &Path,
filenames: Vec<RelativePath>,
) -> Result<Vec<(RelativePath, Option<Vec<u8>>)>> {
filenames
.into_par_iter()
.map(|relpath| {
let prefix = relpath.prefix();
let abspath = match prefix {
relative_path::Prefix::Root => root.join(relpath.path()),
_ => panic!("should only be reading files relative to root"),
};
match std::fs::read(abspath) {
Ok(text) => Ok((relpath, Some(text))),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok((relpath, None)),
Err(e) => Err(e.into()),
}
})
.collect()
} |
TOML | hhvm/hphp/hack/src/client/ide_service/cargo/rust_batch_index_ffi/Cargo.toml | # @generated by autocargo
[package]
name = "rust_batch_index_ffi"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../rust_batch_index_ffi.rs"
test = false
doctest = false
crate-type = ["lib", "staticlib"]
[dependencies]
anyhow = "1.0.71"
bumpalo = { version = "3.11.1", features = ["collections"] }
direct_decl_parser = { version = "0.0.0", path = "../../../../parser/api/cargo/direct_decl_parser" }
hackrs_provider_backend = { version = "0.0.0", path = "../../../../providers/hackrs_provider_backend" }
ocamlrep_ocamlpool = { version = "0.1.0", git = "https://github.com/facebook/ocamlrep/", branch = "main" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" }
oxidized_by_ref = { version = "0.0.0", path = "../../../../oxidized_by_ref" }
rayon = "1.2"
relative_path = { version = "0.0.0", path = "../../../../utils/rust/relative_path" }
si_addendum = { version = "0.0.0", path = "../../../../utils/cargo/si_addendum" }
unwrap_ocaml = { version = "0.0.0", path = "../../../../utils/unwrap_ocaml" } |
hhvm/hphp/hack/src/client/rage/dune | (* -*- tuareg -*- *)
let library_entry name suffix =
Printf.sprintf
"(library
(name %s)
(wrapped false)
(modules)
(libraries %s_%s))" name name suffix
let fb_entry name =
library_entry name "fb"
let stubs_entry name =
library_entry name "stubs"
let entry is_fb name =
if is_fb then
fb_entry name
else
stubs_entry name
let () =
(* test presence of fb subfolder *)
let current_dir = Sys.getcwd () in
(* we are in src/client/rage, locate src/facebook *)
let src_dir = Filename.dirname @@ Filename.dirname current_dir in
let fb_dir = Filename.concat src_dir "facebook" in
(* locate src/facebook/dune *)
let fb_dune = Filename.concat fb_dir "dune" in
let is_fb = Sys.file_exists fb_dune in
let rage = entry is_fb "rage" in
Jbuild_plugin.V1.send rage |
|
OCaml | hhvm/hphp/hack/src/common/common.ml | module List = struct
include Core.List
let unzip4 xyzws =
let rec aux ((xs, ys, zs, ws) as acc) = function
| (x, y, z, w) :: rest -> aux (x :: xs, y :: ys, z :: zs, w :: ws) rest
| _ -> acc
in
aux ([], [], [], []) (List.rev xyzws)
let rec fold_left_env env l ~init ~f =
match l with
| [] -> (env, init)
| x :: xs ->
let (env, init) = f env init x in
fold_left_env env xs ~init ~f
let rec fold_left_env_res env l ~init ~err ~f =
match l with
| [] -> (env, init, err)
| x :: xs ->
let (env, init, err) = f env init err x in
fold_left_env_res env xs ~init ~err ~f
let rev_map_env env xs ~f =
let f2 env init x =
let (env, x) = f env x in
(env, x :: init)
in
fold_left_env env xs ~init:[] ~f:f2
let rev_map_env_ty_err_opt ?(err = []) env xs ~f =
let f2 env init errs x =
match f env x with
| ((env, Some err), x) -> (env, x :: init, err :: errs)
| ((env, _), x) -> (env, x :: init, errs)
in
let (env, xs, errs) = fold_left_env_res env xs ~init:[] ~err ~f:f2 in
((env, errs), xs)
let rev_map_env_res env xs ~f =
let f2 env init errs x =
let (env, x, err) = f env x in
(env, x :: init, err :: errs)
in
fold_left_env_res env xs ~init:[] ~err:[] ~f:f2
let map_env env xs ~f =
let rec aux env xs counter =
match xs with
| [] -> (env, [])
| [y1] ->
let (env, z1) = f env y1 in
(env, [z1])
| [y1; y2] ->
let (env, z1) = f env y1 in
let (env, z2) = f env y2 in
(env, [z1; z2])
| [y1; y2; y3] ->
let (env, z1) = f env y1 in
let (env, z2) = f env y2 in
let (env, z3) = f env y3 in
(env, [z1; z2; z3])
| [y1; y2; y3; y4] ->
let (env, z1) = f env y1 in
let (env, z2) = f env y2 in
let (env, z3) = f env y3 in
let (env, z4) = f env y4 in
(env, [z1; z2; z3; z4])
| [y1; y2; y3; y4; y5] ->
let (env, z1) = f env y1 in
let (env, z2) = f env y2 in
let (env, z3) = f env y3 in
let (env, z4) = f env y4 in
let (env, z5) = f env y5 in
(env, [z1; z2; z3; z4; z5])
| y1 :: y2 :: y3 :: y4 :: y5 :: ys ->
let (env, z1) = f env y1 in
let (env, z2) = f env y2 in
let (env, z3) = f env y3 in
let (env, z4) = f env y4 in
let (env, z5) = f env y5 in
let (env, zs) =
if counter > 1000 then
let (env, zs) = rev_map_env env ys ~f in
(env, rev zs)
else
aux env ys (counter + 1)
in
(env, z1 :: z2 :: z3 :: z4 :: z5 :: zs)
in
aux env xs 0
let map_env_ty_err_opt
env xs ~(f : 'a -> 'b -> ('a * 'e option) * 'c) ~combine_ty_errs =
let rec aux env xs counter =
match xs with
| [] -> ((env, []), [])
| [y1] ->
let ((env, ty_err_opt), z1) = f env y1 in
((env, Option.to_list ty_err_opt), [z1])
| [y1; y2] ->
let ((env, ty_err_opt1), z1) = f env y1 in
let ((env, ty_err_opt2), z2) = f env y2 in
let ty_errs = List.filter_map (fun x -> x) [ty_err_opt1; ty_err_opt2] in
((env, ty_errs), [z1; z2])
| [y1; y2; y3] ->
let ((env, ty_err_opt1), z1) = f env y1 in
let ((env, ty_err_opt2), z2) = f env y2 in
let ((env, ty_err_opt3), z3) = f env y3 in
let ty_errs =
List.filter_map (fun x -> x) [ty_err_opt1; ty_err_opt2; ty_err_opt3]
in
((env, ty_errs), [z1; z2; z3])
| [y1; y2; y3; y4] ->
let ((env, ty_err_opt1), z1) = f env y1 in
let ((env, ty_err_opt2), z2) = f env y2 in
let ((env, ty_err_opt3), z3) = f env y3 in
let ((env, ty_err_opt4), z4) = f env y4 in
let ty_errs =
List.filter_map
(fun x -> x)
[ty_err_opt1; ty_err_opt2; ty_err_opt3; ty_err_opt4]
in
((env, ty_errs), [z1; z2; z3; z4])
| [y1; y2; y3; y4; y5] ->
let ((env, ty_err_opt1), z1) = f env y1 in
let ((env, ty_err_opt2), z2) = f env y2 in
let ((env, ty_err_opt3), z3) = f env y3 in
let ((env, ty_err_opt4), z4) = f env y4 in
let ((env, ty_err_opt5), z5) = f env y5 in
let ty_errs =
List.filter_map
(fun x -> x)
[ty_err_opt1; ty_err_opt2; ty_err_opt3; ty_err_opt4; ty_err_opt5]
in
((env, ty_errs), [z1; z2; z3; z4; z5])
| y1 :: y2 :: y3 :: y4 :: y5 :: ys ->
let ((env, ty_err_opt1), z1) = f env y1 in
let ((env, ty_err_opt2), z2) = f env y2 in
let ((env, ty_err_opt3), z3) = f env y3 in
let ((env, ty_err_opt4), z4) = f env y4 in
let ((env, ty_err_opt5), z5) = f env y5 in
let err =
List.filter_map
(fun x -> x)
[ty_err_opt1; ty_err_opt2; ty_err_opt3; ty_err_opt4; ty_err_opt5]
in
let (env, zs) =
if counter > 1000 then
let (env, zs) = rev_map_env_ty_err_opt env ys ~f ~err in
(env, rev zs)
else
aux env ys (counter + 1)
in
(env, z1 :: z2 :: z3 :: z4 :: z5 :: zs)
in
let ((env, ty_errs), xs) = aux env xs 0 in
((env, combine_ty_errs ty_errs), xs)
let map_env_err_res env xs ~f =
let rec aux env xs counter =
match xs with
| [] -> (env, [], [])
| [y1] ->
let (env, z1, res) = f env y1 in
(env, [z1], [res])
| [y1; y2] ->
let (env, z1, res1) = f env y1 in
let (env, z2, res2) = f env y2 in
(env, [z1; z2], [res1; res2])
| [y1; y2; y3] ->
let (env, z1, res1) = f env y1 in
let (env, z2, res2) = f env y2 in
let (env, z3, res3) = f env y3 in
(env, [z1; z2; z3], [res1; res2; res3])
| [y1; y2; y3; y4] ->
let (env, z1, res1) = f env y1 in
let (env, z2, res2) = f env y2 in
let (env, z3, res3) = f env y3 in
let (env, z4, res4) = f env y4 in
(env, [z1; z2; z3; z4], [res1; res2; res3; res4])
| [y1; y2; y3; y4; y5] ->
let (env, z1, res1) = f env y1 in
let (env, z2, res2) = f env y2 in
let (env, z3, res3) = f env y3 in
let (env, z4, res4) = f env y4 in
let (env, z5, res5) = f env y5 in
(env, [z1; z2; z3; z4; z5], [res1; res2; res3; res4; res5])
| y1 :: y2 :: y3 :: y4 :: y5 :: ys ->
let (env, z1, res1) = f env y1 in
let (env, z2, res2) = f env y2 in
let (env, z3, res3) = f env y3 in
let (env, z4, res4) = f env y4 in
let (env, z5, res5) = f env y5 in
let (env, zs, res6) =
if counter > 1000 then
let (env, zs, errs) = rev_map_env_res env ys ~f in
(env, rev zs, rev errs)
else
aux env ys (counter + 1)
in
( env,
z1 :: z2 :: z3 :: z4 :: z5 :: zs,
res1 :: res2 :: res3 :: res4 :: res5 :: res6 )
in
aux env xs 0
let rec map2_env env l1 l2 ~f =
match (l1, l2) with
| ([], []) -> (env, [])
| ([], _)
| (_, []) ->
raise @@ Invalid_argument "map2_env"
| (x1 :: rl1, x2 :: rl2) ->
let (env, x) = f env x1 x2 in
let (env, rl) = map2_env env rl1 rl2 ~f in
(env, x :: rl)
let map2_env_ty_err_opt env l1 l2 ~f ~combine_ty_errs =
let rec aux env l1 l2 =
match (l1, l2) with
| ([], []) -> (env, [], [])
| ([], _)
| (_, []) ->
raise @@ Invalid_argument "map2_env_ty_err_opt"
| (x1 :: rl1, x2 :: rl2) ->
let ((env, e), x) = f env x1 x2 in
let (env, es, rl) = aux env rl1 rl2 in
(env, e :: es, x :: rl)
in
let (env, errs, xs) = aux env l1 l2 in
((env, combine_ty_errs errs), xs)
let rec map3_env env l1 l2 l3 ~f =
if length l1 <> length l2 || length l2 <> length l3 then
raise @@ Invalid_argument "map3_env"
else
match (l1, l2, l3) with
| ([], [], []) -> (env, [])
| ([], _, _)
| (_, [], _)
| (_, _, []) ->
raise @@ Invalid_argument "map3_env"
| (x1 :: rl1, x2 :: rl2, x3 :: rl3) ->
let (env, x) = f env x1 x2 x3 in
let (env, rl) = map3_env env rl1 rl2 rl3 ~f in
(env, x :: rl)
let filter_map_env env xs ~f =
let (env, l) = rev_map_env env xs ~f in
(env, rev_filter_map l ~f:(fun x -> x))
let rec exists_env env xs ~f =
match xs with
| [] -> (env, false)
| x :: xs ->
(match f env x with
| (env, true) -> (env, true)
| (env, false) -> exists_env env xs ~f)
let rec for_all_env env xs ~f =
match xs with
| [] -> (env, true)
| x :: xs ->
(match f env x with
| (env, false) -> (env, false)
| (env, true) -> for_all_env env xs ~f)
let rec replicate ~num x =
match num with
| 0 -> []
| n when n < 0 ->
raise
@@ Invalid_argument
(Printf.sprintf "List.replicate was called with %d argument" n)
| _ -> x :: replicate ~num:(num - 1) x
end
module Result = struct
include Core.Result
let fold t ~ok ~error =
match t with
| Ok x -> ok x
| Error err -> error err
end |
OCaml | hhvm/hphp/hack/src/count_imprecise_types/count_imprecise_types.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
module JSON = Hh_json
type result = {
mixed_count: int;
nonnull_count: int;
dynamic_count: int;
}
let json_of_results results =
let json_of_result (id, result) =
JSON.JSON_Object
[
("id", JSON.string_ id);
("mixed_count", JSON.int_ result.mixed_count);
("dynamic_count", JSON.int_ result.dynamic_count);
("nonnull_count", JSON.int_ result.nonnull_count);
]
in
SMap.bindings results |> JSON.array_ json_of_result
let bad_type_visitor_per_def =
object (self)
inherit [_] Tast_visitor.reduce
method zero = { mixed_count = 0; nonnull_count = 0; dynamic_count = 0 }
method plus r1 r2 =
{
mixed_count = r1.mixed_count + r2.mixed_count;
nonnull_count = r1.nonnull_count + r2.nonnull_count;
dynamic_count = r1.dynamic_count + r2.dynamic_count;
}
method! on_'ex _ ty =
match Typing_defs.get_node ty with
| Typing_defs.Tintersection [] -> { (self#zero) with mixed_count = 1 }
| Typing_defs.Toption ty
when Typing_defs.equal_locl_ty_
(Typing_defs.get_node ty)
Typing_defs.Tnonnull ->
{ (self#zero) with mixed_count = 1 }
| Typing_defs.Tdynamic -> { (self#zero) with dynamic_count = 1 }
| Typing_defs.Tnonnull -> { (self#zero) with nonnull_count = 1 }
| _ -> self#zero
end
let bad_type_visitor =
object
inherit [_] Tast_visitor.reduce
method zero = SMap.empty
method plus =
SMap.union ~combine:(fun id _ _ -> failwith ("Clash at %s" ^ id))
method! on_fun_def env ({ Aast.fd_name = (_, id); _ } as fun_def) =
let result = bad_type_visitor_per_def#on_fun_def env fun_def in
SMap.singleton id result
method! on_method_ env (Aast_defs.{ m_name = (_, mid); _ } as method_def) =
let result = bad_type_visitor_per_def#on_method_ env method_def in
let cid = Tast_env.get_self_id env |> Option.value_exn in
let id = cid ^ "::" ^ mid in
SMap.singleton id result
end
let count ctx tast = bad_type_visitor#go ctx tast |
OCaml Interface | hhvm/hphp/hack/src/count_imprecise_types/count_imprecise_types.mli | (*
* 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.
*
*)
type result
(** Counts the number of mixed, dynamic, and types occurring in functions and
methods. *)
val count : Provider_context.t -> Tast.program -> result SMap.t
val json_of_results : result SMap.t -> Hh_json.json |
hhvm/hphp/hack/src/count_imprecise_types/dune | (library
(name count_imprecise_types)
(wrapped false)
(modules count_imprecise_types)
(libraries tast_env typing_defs utils_core)) |
|
OCaml | hhvm/hphp/hack/src/custom_error/custom_error.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.
*
*)
type versioned_patt_error = Error_v1 of Patt_error.t [@@deriving eq, show]
type versioned_error_message = Message_v1 of Error_message.t
[@@deriving eq, show]
type t = {
name: string;
patt: versioned_patt_error;
error_message: versioned_error_message;
}
[@@deriving eq, show] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.