language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
OCaml Interface | hhvm/hphp/hack/src/server/findRefsWireFormat.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 half_open_one_based = {
filename: string; (** absolute *)
line: int; (** 1-based *)
char_start: int; (** 1-based *)
char_end: int; (** 1-based *)
}
(** Produced by "hh --ide-find-refs-by-symbol" and parsed by clientLsp *)
module IdeShellout : sig
val to_string : (string * Pos.absolute) list -> string
val from_string_exn : string -> half_open_one_based list
end
(** Used by hh_server's findRefsService to write to a streaming file, read by clientLsp *)
module Ide_stream : sig
(** Locks the file and appends refs to it *)
val append : Unix.file_descr -> (string * Pos.absolute) list -> unit
(** Locks the file and reads the refs in the file that came after [pos], if any;
returns a new [pos] after the last ref that was read.*)
val read : Unix.file_descr -> pos:int -> half_open_one_based list * int
end
(** Used "hh --find-refs --json" and read by HackAst and other tools *)
module HackAst : sig
val to_string : (string * Pos.absolute) list -> string
end
(** Used by "hh --find-refs" *)
module CliHumanReadable : sig
val print_results : (string * Pos.absolute) list -> unit
end
(** CliArgs is produced by clientLsp when it invokes "hh --ide-find-refs-by-symbol <args>"
and consumed by clientArgs when it parses that argument. *)
module CliArgs : sig
type t = {
symbol_name: string;
action: SearchTypes.Find_refs.action;
stream_file: Path.t option;
hint_suffixes: string list;
}
val to_string : t -> string
val from_string_exn : string -> t
val to_string_triple : t -> string * string * string
val from_string_triple_exn : string * string * string -> t
end |
OCaml | hhvm/hphp/hack/src/server/fullFidelityParseService.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.
*
*)
module SyntaxTree =
Full_fidelity_syntax_tree.WithSyntax (Full_fidelity_positioned_syntax)
(* Entry Point *)
let go filename =
let file = Relative_path.create Relative_path.Dummy filename 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
Hh_json.json_to_string json |
OCaml | hhvm/hphp/hack/src/server/hh_saved_state_verifier.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 naming_table_filename = "hh_mini_saved_state_naming.sql"
type args = {
control: string;
test: string;
}
let die str =
prerr_endline str;
exit 2
let parse_options () =
let control_path = ref None in
let test_path = ref None in
let set_control_path path = control_path := Some path in
let set_test_path path = test_path := Some path in
let options =
[
( "--control",
Arg.String set_control_path,
"Set path for control saved state" );
("--test", Arg.String set_test_path, "Set path for test saved state");
]
in
let usage =
Printf.sprintf
"Usage: %s --control <control_saved_state> --test <test_saved_state>"
Sys.argv.(0)
in
Arg.parse options (fun _ -> die usage) usage;
match (!control_path, !test_path) with
| (Some control_path, Some test_path) ->
{ control = control_path; test = test_path }
| _ -> die usage
let get_test_control_pair args path =
let control = Filename.concat args.control path in
let test = Filename.concat args.test path in
(control, test)
let diff_naming_table args =
let (control_naming_table, test_naming_table) =
get_test_control_pair args naming_table_filename
in
(* - By default the tool is run on saved-state of the form
"hack_saved_state/tree/hack/64_distc/<hash>" which saves the
naming table in sqlite format
- The saved state "hack_saved_state/tree/hack/naming/<hash>"
would also have a naming table in the sqlite format.
*)
DiffNamingTable.diff control_naming_table test_naming_table
let () =
let args = parse_options () in
let naming_tables_and_errors_diff = diff_naming_table args in
if naming_tables_and_errors_diff then
die
(Printf.sprintf
"Saved states %s and %s are different"
args.control
args.test) |
OCaml | hhvm/hphp/hack/src/server/hoverService.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 hover_info = {
(* For fields and locals, this is the type. For method and function calls, it
is the signature, including any inferred types for generics.
This is also the only part of the hover info to get displayed as code
rather than Markdown. *)
snippet: string;
(* Additional information, such as doc string and declaration file. Displayed
as Markdown. *)
addendum: string list;
(* Position of this result. *)
pos: Pos.t option;
}
[@@deriving eq]
type result = hover_info list
let string_of_result { snippet; addendum; pos } =
Printf.sprintf
"{ snippet = %S; addendum = [%s]; pos = %s }"
snippet
(String.concat "; " (List.map (fun s -> Printf.sprintf "%S" s) addendum))
(match pos with
| None -> "None"
| Some p -> Printf.sprintf "Some %S" (Pos.multiline_string_no_file p)) |
OCaml | hhvm/hphp/hack/src/server/identifySymbolService.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 SymbolOccurrence
open Typing_defs
module SN = Naming_special_names
module FFP = Full_fidelity_positioned_syntax
module Result_set = Caml.Set.Make (struct
type t = Relative_path.t SymbolOccurrence.t
let compare : t -> t -> int = SymbolOccurrence.compare Relative_path.compare
end)
let is_target target_line target_char { pos; _ } =
let (l, start, end_) = Pos.info_pos pos in
l = target_line && start <= target_char && target_char - 1 <= end_
let process_class_id
?(is_declaration = false) ?(class_id_type = ClassId) (pos, cid) =
Result_set.singleton
{ name = cid; type_ = Class class_id_type; is_declaration; pos }
let process_attribute (pos, name) class_name method_ =
let type_ =
match (name, class_name, method_) with
| (name, Some (_, class_name), Some ((_, method_name), is_static))
when String.equal name Naming_special_names.UserAttributes.uaOverride ->
Attribute (Some { class_name; method_name; is_static })
| _ -> Attribute None
in
Result_set.singleton { name; type_; is_declaration = false; pos }
let process_xml_attrs class_name attrs =
List.fold attrs ~init:Result_set.empty ~f:(fun acc attr ->
match attr with
| Aast.Xhp_simple { Aast.xs_name = (pos, name); _ } ->
Result_set.add
{
name;
type_ = XhpLiteralAttr (class_name, Utils.add_xhp_ns name);
is_declaration = false;
pos;
}
acc
| _ -> acc)
let clean_member_name name = String_utils.lstrip name "$"
let process_member ?(is_declaration = false) recv_class id ~is_method ~is_const
=
let member_name = snd id in
let type_ =
if is_const then
ClassConst (recv_class, member_name)
else if is_method then
Method (recv_class, member_name)
else
(*
Per comment in symbolOcurrence.mli, XhpLiteralAttr
is only used for attributes in XHP literals. Since
process_member is not being used to handle XML attributes
it is fine to define every symbol as Property.
*)
Property (recv_class, member_name)
in
let c_name =
match recv_class with
| ClassName name -> name
| UnknownClass -> "_"
in
Result_set.singleton
{
name = c_name ^ "::" ^ clean_member_name member_name;
type_;
is_declaration;
pos = fst id;
}
(* If there's an exact class name can find for this type, return its name. *)
let concrete_cls_name_from_ty enclosing_class_name ty : string option =
let ty =
match Typing_defs_core.get_node ty with
| Tnewtype (n, _, ty) when String.equal n SN.Classes.cSupportDyn -> ty
| _ -> ty
in
match Typing_defs_core.get_node ty with
| Tclass ((_, cls_name), _, _) -> Some cls_name
| Tgeneric ("this", _) -> enclosing_class_name
| _ -> None
let get_callee enclosing_class_name (recv : Tast.expr) : receiver option =
let (_, _, recv_expr_) = recv in
match recv_expr_ with
| Aast.Id (_, id) -> Some (FunctionReceiver id)
| Aast.Class_const ((ty, _, _), (_, meth_name)) ->
(match concrete_cls_name_from_ty enclosing_class_name ty with
| Some cls_name ->
Some (MethodReceiver { cls_name; meth_name; is_static = true })
| None -> None)
| Aast.Obj_get ((ty, _, _), (_, _, Aast.Id (_, meth_name)), _, _) ->
(match concrete_cls_name_from_ty enclosing_class_name ty with
| Some cls_name ->
Some (MethodReceiver { cls_name; meth_name; is_static = false })
| None -> None)
| _ -> None
let process_arg_names recv (args : Tast.expr list) : Result_set.t =
match recv with
| Some recv_name ->
List.mapi args ~f:(fun i (_, pos, _) ->
{
name = "(unused)";
type_ = BestEffortArgument (recv_name, i);
is_declaration = false;
pos;
})
|> Result_set.of_list
| None -> Result_set.empty
(* Add parameter names for all arguments at a call site. This enables
us to show hover information on arguments.
greet_user("John Doe");
//^ Hover shows: Parameter: $name
*)
let process_callee_arg_names
enclosing_class
(recv : Tast.expr)
(args : (Ast_defs.param_kind * Tast.expr) list) : Result_set.t =
let enclosing_class_name = Option.map ~f:snd enclosing_class in
let recv = get_callee enclosing_class_name recv in
process_arg_names recv (List.map ~f:snd args)
(* Add parameter names for all arguments at an instantiation
site. This enables us to show hover information on arguments.
new User("John Doe");
//^ Hover shows: Parameter: $name
*)
let process_constructor_arg_names
enclosing_class
(parent_class_hint : Aast.hint option)
((_, _, cid) : Tast.class_id)
(args : Tast.expr list) : Result_set.t =
let enclosing_class_name = Option.map ~f:snd enclosing_class in
let cls_name =
match cid with
| Aast.CIparent ->
(match parent_class_hint with
| Some (_, Aast.Happly ((_, cls_name), _)) -> Some cls_name
| _ -> None)
| Aast.CIself -> enclosing_class_name
| Aast.CIstatic -> enclosing_class_name
| Aast.CIexpr (ty, _, _) ->
concrete_cls_name_from_ty enclosing_class_name ty
| Aast.CI (_, id) -> Some id
in
let recv =
match cls_name with
| Some cls_name ->
Some
(MethodReceiver
{ cls_name; meth_name = SN.Members.__construct; is_static = false })
| None -> None
in
process_arg_names recv args
let process_fun_id ?(is_declaration = false) id =
Result_set.singleton
{ name = snd id; type_ = Function; is_declaration; pos = fst id }
let process_global_const ?(is_declaration = false) id =
Result_set.singleton
{ name = snd id; type_ = GConst; is_declaration; pos = fst id }
let process_lvar_id ?(is_declaration = false) id =
Result_set.singleton
{ name = snd id; type_ = LocalVar; is_declaration; pos = fst id }
let process_typeconst ?(is_declaration = false) (class_name, tconst_name, pos) =
Result_set.singleton
{
name = class_name ^ "::" ^ tconst_name;
type_ = Typeconst (class_name, tconst_name);
is_declaration;
pos;
}
let process_class class_ =
let acc = process_class_id ~is_declaration:true class_.Aast.c_name in
let c_name = snd class_.Aast.c_name in
let (constructor, static_methods, methods) =
Aast.split_methods class_.Aast.c_methods
in
let all_methods = static_methods @ methods in
let acc =
List.fold all_methods ~init:acc ~f:(fun acc method_ ->
Result_set.union acc
@@ process_member
(ClassName c_name)
method_.Aast.m_name
~is_declaration:true
~is_method:true
~is_const:false)
in
let all_props = class_.Aast.c_vars in
let acc =
List.fold all_props ~init:acc ~f:(fun acc prop ->
Result_set.union acc
@@ process_member
(ClassName c_name)
prop.Aast.cv_id
~is_declaration:true
~is_method:false
~is_const:false)
in
let acc =
List.fold class_.Aast.c_consts ~init:acc ~f:(fun acc const ->
Result_set.union acc
@@ process_member
(ClassName c_name)
const.Aast.cc_id
~is_declaration:true
~is_method:false
~is_const:true)
in
let acc =
List.fold class_.Aast.c_typeconsts ~init:acc ~f:(fun acc typeconst ->
let (pos, tconst_name) = typeconst.Aast.c_tconst_name in
Result_set.union acc
@@ process_typeconst ~is_declaration:true (c_name, tconst_name, pos))
in
(* We don't check anything about xhp attributes, so the hooks won't fire when
typechecking the class. Need to look at them individually. *)
let acc =
List.fold class_.Aast.c_xhp_attr_uses ~init:acc ~f:(fun acc attr ->
match attr with
| (_, Aast.Happly (cid, _)) ->
Result_set.union acc @@ process_class_id cid
| _ -> acc)
in
match constructor with
| Some method_ ->
let id = (fst method_.Aast.m_name, SN.Members.__construct) in
Result_set.union acc
@@ process_member
(ClassName c_name)
id
~is_declaration:true
~is_method:true
~is_const:false
| None -> acc
let typed_member_id env receiver_ty mid ~is_method ~is_const =
Tast_env.get_receiver_ids env receiver_ty
|> List.map ~f:(function
| Tast_env.RIclass cid -> ClassName cid
| Tast_env.RIdynamic
| Tast_env.RIerr
| Tast_env.RIany ->
UnknownClass)
|> List.map ~f:(fun rid -> process_member rid mid ~is_method ~is_const)
|> List.fold ~init:Result_set.empty ~f:Result_set.union
let typed_method = typed_member_id ~is_method:true ~is_const:false
let typed_const = typed_member_id ~is_method:false ~is_const:true
let typed_property = typed_member_id ~is_method:false ~is_const:false
let typed_constructor env ty pos =
typed_method env ty (pos, SN.Members.__construct)
let typed_class_id ?(class_id_type = ClassId) env ty pos =
Tast_env.get_class_ids env ty
|> List.map ~f:(fun cid -> process_class_id ~class_id_type (pos, cid))
|> List.fold ~init:Result_set.empty ~f:Result_set.union
(* When we detect a function reference encapsulated in a string,
* we want to update the function reference without removing the apostrophes.
*
* Example: class_meth(myclass::class, 'myfunc');
*
* In this case, we only want to replace the text 'myfunc' - so we need
* to shrink our positional data by the apostrophes. *)
let remove_apostrophes_from_function_eval (mid : Ast_defs.pstring) :
Ast_defs.pstring =
let (pos, member_name) = mid in
let new_pos = Pos.shrink_by_one_char_both_sides pos in
(new_pos, member_name)
let visitor =
let class_name = ref None in
let parent_class_hint = ref None in
let method_name = ref None in
object (self)
inherit [_] Tast_visitor.reduce as super
method zero = Result_set.empty
method plus = Result_set.union
method! on_expr env expr =
let (_, pos, expr_) = expr in
let ( + ) = self#plus in
let acc =
match expr_ with
| Aast.Hole (_e, _ty, _ty2, Aast.UnsafeCast _) ->
process_fun_id (pos, SN.PseudoFunctions.unsafe_cast)
| Aast.Hole (_e, _ty, _ty2, Aast.UnsafeNonnullCast) ->
process_fun_id (pos, SN.PseudoFunctions.unsafe_nonnull_cast)
| Aast.New ((ty, p, _), _, _, _, _) -> typed_constructor env ty p
| Aast.Obj_get ((ty, _, _), (_, _, Aast.Id mid), _, _) ->
typed_property env ty mid
| Aast.Class_const ((ty, _, _), mid) -> typed_const env ty mid
| Aast.Class_get ((ty, _, _), Aast.CGstring mid, _) ->
typed_property env ty mid
| Aast.Xml (cid, attrs, _) ->
let class_id = process_class_id cid in
let xhp_attributes = process_xml_attrs (snd cid) attrs in
self#plus class_id xhp_attributes
| Aast.FunctionPointer (Aast.FP_id id, _targs) -> process_fun_id id
| Aast.FunctionPointer (Aast.FP_class_const ((ty, _, _cid), mid), _targs)
->
typed_method env ty mid
| Aast.Method_caller (((_, cid) as pcid), mid) ->
process_fun_id (pos, SN.AutoimportedFunctions.meth_caller)
+ process_class_id pcid
+ process_member
(ClassName cid)
(remove_apostrophes_from_function_eval mid)
~is_method:true
~is_const:false
| Aast.ValCollection ((_, kind), _, _) ->
let type_name =
match kind with
| Aast_defs.Vector -> "Vector"
| Aast_defs.ImmVector -> "ImmVector"
| Aast_defs.Set -> "Set"
| Aast_defs.ImmSet -> "ImmSet"
| Aast_defs.Keyset -> "keyset"
| Aast_defs.Vec -> "vec"
in
process_class_id (pos, "\\HH\\" ^ type_name)
| Aast.KeyValCollection ((_, kind), _, _) ->
let type_name =
match kind with
| Aast_defs.Map -> "Map"
| Aast_defs.ImmMap -> "ImmMap"
| Aast_defs.Dict -> "dict"
in
process_class_id (pos, "\\HH\\" ^ type_name)
| Aast.EnumClassLabel (enum_name, label_name) -> begin
match enum_name with
| None ->
let (ety, _, _) = expr in
let ty = Typing_defs_core.get_node ety in
(match ty with
| Tnewtype (_, [ty_enum_class; _], _) ->
(match get_node ty_enum_class with
| Tclass ((_, enum_class_name), _, _)
| Tgeneric (enum_class_name, _) ->
Result_set.singleton
{
name = Utils.strip_ns enum_class_name ^ "#" ^ label_name;
type_ = EnumClassLabel (enum_class_name, label_name);
is_declaration = false;
pos;
}
| _ -> self#zero)
| _ -> self#zero)
| Some ((_, enum_name) as enum_id) ->
process_class_id enum_id
+ Result_set.singleton
{
name = Utils.strip_ns enum_name ^ "#" ^ label_name;
type_ = EnumClassLabel (enum_name, label_name);
is_declaration = false;
pos;
}
end
| _ -> self#zero
in
acc + super#on_expr env expr
method! on_expression_tree
env
Aast.
{
et_hint;
et_virtualized_expr;
et_splices;
et_function_pointers;
et_runtime_expr = _;
et_dollardollar_pos = _;
} =
(* We only want to consider completion from the hint and the
virtualized expression, not the visitor expression. The
visitor expression is unityped, so we can't do much.*)
let acc = self#on_hint env et_hint in
let acc = self#plus acc (self#on_Block env et_splices) in
(* We're overriding super#on_expression_tree, so we need to
update the environment. *)
let env = Tast_env.inside_expr_tree env et_hint in
let acc = self#plus acc (self#on_Block env et_function_pointers) in
let (_, _, virtualized_expr_) = et_virtualized_expr in
let e =
match virtualized_expr_ with
| Aast.(
Call
{
func =
( _,
_,
Efun
{
ef_fun =
{ f_body = { fb_ast = [(_, Return (Some e))]; _ }; _ };
_;
} );
_;
}) ->
(* The virtualized expression is wrapped in an invoked
lambda to help check unbound variables, which leads to
unwanted closure info in hovers. Use the inner
expression directly. *)
e
| _ -> et_virtualized_expr
in
self#plus acc (self#on_expr env e)
method! on_class_id env (ty, p, cid) =
match cid with
| Aast.CIexpr expr ->
(* We want to special case this because we want to get the type of the
inner expression, which will have a type like `classname<Foo>`, rather
than the resolved type of the class ID, which will have a type like
`Foo`. Since the class ID and the inner expression have the same span,
it is not easy to distinguish them later. *)
self#on_expr env expr
| Aast.CIparent
| Aast.CIself
| Aast.CIstatic ->
(* We want to special case these because we want to keep track of the
original class id type. This information is useful in some cases, for
instance when refactoring class names, because we want to avoid
refactoring `self`, `static`, and `parent` class ids. *)
typed_class_id ~class_id_type:Other env ty p
| Aast.CI _ -> typed_class_id env ty p
method! on_If env cond then_block else_block : Result_set.t =
match ServerUtils.resugar_invariant_call env cond then_block with
| Some e -> self#on_expr env e
| None -> super#on_If env cond then_block else_block
method! on_Call
env
Aast.{ func = (_, _, expr_) as e; targs = tal; args = el; unpacked_arg }
=
(* For Id, Obj_get (with an Id member), and Class_const, we don't want to
* use the result of `self#on_expr env e`, since it would record a
* property, class const, or global const access instead of a method call.
* So instead of invoking super#on_Call, we reimplement it here, omitting
* `self#on_expr env e` when necessary. *)
let ( + ) = self#plus in
let ea =
if Tast_env.is_in_expr_tree env then
(* In an expression tree, we desugar function calls and
method calls to calls to ::symbolType(). Any other
function call is just calling typing helpers, and isn't
useful in hover or go-to-definition.
This ensures that when a user hovers over a literal "abc" we only
show the inferred type, and don't show
MyVisitor::stringType() information. *)
match expr_ with
| Aast.(
Call
{
func = (_, _, Class_const (_, (_, methName)));
args = [(_, arg)];
_;
})
when String.equal methName SN.ExpressionTrees.symbolType ->
(* Treat MyVisitor::symbolType(foo<>) as just foo(). *)
self#on_expr env arg
| _ -> self#zero
else
let expr_ =
match expr_ with
| Aast.ReadonlyExpr (_, _, e) -> e
| _ -> expr_
in
match expr_ with
| Aast.Id id ->
(* E.g. foo() *)
process_fun_id id
| Aast.Obj_get
(((ty, _, _) as obj), (_, _, Aast.Id mid), _, Aast.Is_method) ->
(* E.g. $bar->foo() *)
self#on_expr env obj + typed_method env ty mid
| Aast.Obj_get
(((ty, _, _) as obj), (_, _, Aast.Id mid), _, Aast.Is_prop) ->
(* E.g. ($bar->foo)() *)
self#on_expr env obj + typed_property env ty mid
| Aast.Class_const (((ty, _, _) as cid), mid) ->
(* E.g. Bar::foo() *)
self#on_class_id env cid + typed_method env ty mid
| _ -> self#on_expr env e
in
let tala = self#on_list self#on_targ env tal in
let ela = self#on_list self#on_expr env (List.map ~f:snd el) in
let arg_names = process_callee_arg_names !class_name e el in
let uea =
Option.value_map
~default:Result_set.empty
~f:(self#on_expr env)
unpacked_arg
in
ea + tala + ela + arg_names + uea
method! on_New env cid targs args var_arg constr_ty =
let named_params =
process_constructor_arg_names !class_name !parent_class_hint cid args
in
self#plus named_params (super#on_New env cid targs args var_arg constr_ty)
method! on_Haccess env root ids =
let acc =
Tast_env.referenced_typeconsts env root ids
|> List.map ~f:process_typeconst
|> List.fold ~init:self#zero ~f:self#plus
in
self#plus acc (super#on_Haccess env root ids)
method! on_Hrefinement env root refs =
let process_refinement acc r =
let id =
match r with
| Aast.Rctx (id, _)
| Aast.Rtype (id, _) ->
id
in
Tast_env.referenced_typeconsts env root [id]
|> List.map ~f:process_typeconst
|> List.fold ~init:acc ~f:self#plus
in
let acc = List.fold ~init:self#zero ~f:process_refinement refs in
self#plus acc (super#on_Hrefinement env root refs)
method! on_tparam env tp =
let (pos, name) = tp.Aast.tp_name in
let acc =
Result_set.singleton
{ name; type_ = TypeVar; is_declaration = true; pos }
in
self#plus acc (super#on_tparam env tp)
method! on_Lvar env (pos, id) =
let acc =
if Local_id.is_user_denotable id then
process_lvar_id (pos, Local_id.get_name id)
else
Result_set.empty
in
self#plus acc (super#on_Lvar env (pos, id))
method! on_capture_lid _env (_, (pos, id)) =
process_lvar_id (pos, Local_id.get_name id)
method! on_hint env h =
let acc =
match h with
| (pos, Aast.Habstr (name, _)) ->
Result_set.singleton
{ name; type_ = TypeVar; is_declaration = false; pos }
| (pos, Aast.Hprim prim) ->
let name = Aast_defs.string_of_tprim prim in
Result_set.singleton
{
name;
type_ = BuiltInType (BIprimitive prim);
is_declaration = false;
pos;
}
| (pos, Aast.Hnothing) ->
Result_set.singleton
{
name = "nothing";
type_ = BuiltInType BInothing;
is_declaration = false;
pos;
}
| (pos, Aast.Hmixed) ->
Result_set.singleton
{
name = "mixed";
type_ = BuiltInType BImixed;
is_declaration = false;
pos;
}
| (pos, Aast.Hnonnull) ->
Result_set.singleton
{
name = "nonnull";
type_ = BuiltInType BInonnull;
is_declaration = false;
pos;
}
| (pos, Aast.Hdynamic) ->
Result_set.singleton
{
name = "dynamic";
type_ = BuiltInType BIdynamic;
is_declaration = false;
pos;
}
| (pos, Aast.Hshape _) ->
Result_set.singleton
{
name = "shape";
type_ = BuiltInType BIshape;
is_declaration = false;
pos;
}
| (pos, Aast.Hthis) ->
Result_set.singleton
{
name = "this";
type_ = BuiltInType BIthis;
is_declaration = false;
pos;
}
| (pos, Aast.Hoption _) ->
(* Narrow the position to just the '?', not the whole ?Foo<Complicated<Bar>>. *)
let (_start_line, start_column) = Pos.line_column pos in
let qmark_pos = Pos.set_col_end (start_column + 1) pos in
Result_set.singleton
{
name = "?";
type_ = BuiltInType BIoption;
is_declaration = false;
pos = qmark_pos;
}
| _ -> Result_set.empty
in
self#plus acc (super#on_hint env h)
method! on_fun_param env param =
let acc = process_lvar_id (param.Aast.param_pos, param.Aast.param_name) in
self#plus acc (super#on_fun_param env param)
method! on_Happly env sid hl =
match hl with
| [h] when String.equal (snd sid) SN.Classes.cSupportDyn ->
self#on_hint env h
| _ ->
let acc = process_class_id sid in
self#plus acc (super#on_Happly env sid hl)
method! on_catch env (sid, lid, block) =
let acc = process_class_id sid in
self#plus acc (super#on_catch env (sid, lid, block))
method! on_class_ env class_ =
class_name := Some class_.Aast.c_name;
parent_class_hint := List.hd class_.Aast.c_extends;
let acc = process_class class_ in
(*
Enums implicitly extend BuiltinEnum. However, BuiltinEnums also extend
the same Enum as a type parameter.
Ex: enum Size extends BuiltinEnum<Size> { ... }
This will return the definition of the enum twice when finding references
on it. As a result, we set the extends property of an enum's tast to an empty list.
The same situation applies to Enum classes that extends
BuiltinEnumClass. However in this case we just want to filter out
this one extends, and keep the other unchanged.
*)
let class_ =
let open Aast in
let c_name = snd class_.c_name in
(* Checks if the hint is matching the pattern
* `HH\BuiltinEnumClass<HH\MemberOf<c_name, _>>`
*)
let is_generated_builtin_enum_class = function
| ( _,
Happly
( (_, builtin_enum_class),
[
( _,
Happly
( (_, memberof),
[(_, Happly ((_, name), [])); _interface] ) );
] ) ) ->
String.equal builtin_enum_class SN.Classes.cHH_BuiltinEnumClass
&& String.equal memberof SN.Classes.cMemberOf
&& String.equal name c_name
| (_, Happly ((_, builtin_abstract_enum_class), [])) ->
String.equal
builtin_abstract_enum_class
SN.Classes.cHH_BuiltinAbstractEnumClass
| _ -> false
in
(* Checks if the hint is matching the pattern
* `HH\BuiltinEnum<c_name>`
*)
let is_generated_builtin_enum = function
| (_, Happly ((_, builtin_enum), [(_, Happly ((_, name), []))])) ->
String.equal builtin_enum SN.Classes.cHH_BuiltinEnum
&& String.equal name c_name
| _ -> false
in
(* If the class is an enum or enum class, remove the generated
* occurrences.
*)
if Ast_defs.is_c_enum_class class_.c_kind then
(* Enum classes might extend other classes, so we filter
* the list and we don't depend on their order.
*)
let c_extends =
List.filter_map
~f:(fun h ->
if is_generated_builtin_enum_class h then
(* don't take this occurrence into account *)
None
else
Some h)
class_.c_extends
in
(* We also have to take care of the type of constants that
* are rewritten from Foo to MemberOf<EnumName, Foo>
*)
let c_consts =
List.map
~f:(fun cc ->
let cc_type =
Option.map
~f:(fun h ->
match snd h with
| Happly ((_, name), [_; h])
when String.equal name SN.Classes.cMemberOf ->
h
| _ -> h)
cc.cc_type
in
{ cc with cc_type })
class_.c_consts
in
{ class_ with c_extends; c_consts }
else if Ast_defs.is_c_enum class_.c_kind then
(* For enums, we could remove everything as they don't extends
* other classes, but let's filter anyway, just to be resilient
* to future evolutions
*)
let c_extends =
List.filter_map
~f:(fun h ->
if is_generated_builtin_enum h then
(* don't take this occurrence into account *)
None
else
Some h)
class_.c_extends
in
{ class_ with c_extends }
else
class_
in
let acc = self#plus acc (super#on_class_ env class_) in
class_name := None;
parent_class_hint := None;
acc
method! on_fun_def env fd =
let acc = process_fun_id ~is_declaration:true fd.Aast.fd_name in
self#plus acc (super#on_fun_def env fd)
method! on_fun_ env fun_ =
super#on_fun_ env { fun_ with Aast.f_unsafe_ctxs = None }
method! on_typedef env typedef =
let acc = process_class_id ~is_declaration:true typedef.Aast.t_name in
self#plus acc (super#on_typedef env typedef)
method! on_gconst env cst =
let acc = process_global_const ~is_declaration:true cst.Aast.cst_name in
self#plus acc (super#on_gconst env cst)
method! on_Id env id =
let acc = process_global_const id in
self#plus acc (super#on_Id env id)
method! on_Obj_get env obj ((_, _, expr_) as member) ognf prop_or_method =
match expr_ with
| Aast.Id _ ->
(* Don't visit this Id, since we would record it as a gconst access. *)
let obja = self#on_expr env obj in
let ognfa = self#on_og_null_flavor env ognf in
self#plus obja ognfa
| _ -> super#on_Obj_get env obj member ognf prop_or_method
method! on_SFclass_const env cid mid =
let ( + ) = Result_set.union in
process_class_id cid
+ process_member (ClassName (snd cid)) mid ~is_method:false ~is_const:true
+ super#on_SFclass_const env cid mid
method! on_method_ env m =
method_name := Some (m.Aast.m_name, m.Aast.m_static);
let acc = super#on_method_ env { m with Aast.m_unsafe_ctxs = None } in
method_name := None;
acc
method! on_user_attribute env ua =
let tcopt = Tast_env.get_tcopt env in
(* Don't show __SupportDynamicType if it's implicit everywhere *)
if
String.equal
(snd ua.Aast.ua_name)
SN.UserAttributes.uaSupportDynamicType
&& TypecheckerOptions.everything_sdt tcopt
&& not (TypecheckerOptions.enable_no_auto_dynamic tcopt)
then
Result_set.empty
else
let acc = process_attribute ua.Aast.ua_name !class_name !method_name in
self#plus acc (super#on_user_attribute env ua)
method! on_SetModule env sm =
let (pos, id) = sm in
let acc =
Result_set.singleton
{ name = id; type_ = Module; is_declaration = false; pos }
in
self#plus acc (super#on_SetModule env sm)
method! on_module_def env md =
let (pos, id) = md.Aast.md_name in
let acc =
Result_set.singleton
{ name = id; type_ = Module; is_declaration = false; pos }
in
self#plus acc (super#on_module_def env md)
end
(* Types of decls used in keyword extraction.*)
type classish_decl_kind =
| DKclass
| DKinterface
| DKenumclass
type module_decl_kind =
| DKModuleDeclaration
| DKModuleMembershipDeclaration
type keyword_context =
| ClassishDecl of classish_decl_kind
| Method
| Parameter
| ReturnType
| TypeConst
| AsyncBlockHeader
| ModuleDecl of module_decl_kind
let trivia_pos (t : Full_fidelity_positioned_trivia.t) : Pos.t =
let open Full_fidelity_positioned_trivia in
let open Full_fidelity_source_text in
relative_pos
t.source_text.file_path
t.source_text
t.offset
(t.offset + t.width)
let fixme_elt (t : Full_fidelity_positioned_trivia.t) : Result_set.elt option =
match t.Full_fidelity_positioned_trivia.kind with
| Full_fidelity_trivia_kind.FixMe ->
let pos = trivia_pos t in
Some { name = "HH_FIXME"; type_ = HhFixme; is_declaration = false; pos }
| _ -> None
let fixmes (tree : Full_fidelity_positioned_syntax.t) : Result_set.elt list =
let open Full_fidelity_positioned_syntax in
let rec aux acc s =
let trivia_list = leading_trivia s in
let fixme_elts = List.map trivia_list ~f:fixme_elt |> List.filter_opt in
List.fold (children s) ~init:(fixme_elts @ acc) ~f:aux
in
aux [] tree
let token_pos (t : FFP.Token.t) : Pos.t =
let offset = t.FFP.Token.offset + t.FFP.Token.leading_width in
Full_fidelity_source_text.relative_pos
t.FFP.Token.source_text.Full_fidelity_source_text.file_path
t.FFP.Token.source_text
offset
(offset + t.FFP.Token.width)
let syntax_pos (s : FFP.t) : Pos.t =
let open Full_fidelity_positioned_syntax in
let offset = start_offset s + leading_width s in
let source = source_text s in
Full_fidelity_source_text.relative_pos
source.Full_fidelity_source_text.file_path
source
offset
(offset + width s)
(** Get keyword positions from the FFP for every keyword that has hover
documentation. **)
let keywords (tree : FFP.t) : Result_set.elt list =
let open Full_fidelity_positioned_syntax in
let elt_of_token (ctx : keyword_context option) (t : FFP.Token.t) :
Result_set.elt option =
match t.Token.kind with
| Token.TokenKind.Class ->
(match ctx with
| Some (ClassishDecl DKenumclass) ->
Some
{
name = "enum class";
type_ = Keyword EnumClass;
is_declaration = false;
pos = token_pos t;
}
| _ ->
Some
{
name = "class";
type_ = Keyword Class;
is_declaration = false;
pos = token_pos t;
})
| Token.TokenKind.Interface ->
Some
{
name = "interface";
type_ = Keyword Interface;
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Trait ->
Some
{
name = "trait";
type_ = Keyword Trait;
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Enum ->
(match ctx with
| Some (ClassishDecl DKenumclass) ->
Some
{
name = "enum class";
type_ = Keyword EnumClass;
is_declaration = false;
pos = token_pos t;
}
| _ ->
Some
{
name = "enum";
type_ = Keyword Enum;
is_declaration = false;
pos = token_pos t;
})
| Token.TokenKind.Type ->
Some
{
name = "type";
type_ =
Keyword
(match ctx with
| Some TypeConst -> ConstType
| _ -> Type);
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Newtype ->
Some
{
name = "newtype";
type_ = Keyword Newtype;
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Attribute ->
Some
{
name = "attribute";
type_ = Keyword XhpAttribute;
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Children ->
Some
{
name = "children";
type_ = Keyword XhpChildren;
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Const ->
Some
{
name = "const";
type_ =
Keyword
(match ctx with
| None -> ConstGlobal
| Some TypeConst -> ConstType
| _ -> ConstOnClass);
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Static ->
Some
{
name = "static";
type_ =
Keyword
(match ctx with
| Some Method -> StaticOnMethod
| _ -> StaticOnProperty);
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Use ->
Some
{
name = "use";
type_ = Keyword Use;
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Function ->
Some
{
name = "function";
type_ =
Keyword
(match ctx with
| Some Method -> FunctionOnMethod
| _ -> FunctionGlobal);
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Extends ->
Some
{
name = "extends";
type_ =
Keyword
(match ctx with
| Some (ClassishDecl DKclass) -> ExtendsOnClass
| Some (ClassishDecl DKinterface) -> ExtendsOnInterface
| _ -> ExtendsOnClass);
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Abstract ->
Some
{
name = "abstract";
type_ =
Keyword
(match ctx with
| Some Method -> AbstractOnMethod
| _ -> AbstractOnClass);
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Final ->
Some
{
name = "final";
type_ =
Keyword
(match ctx with
| Some Method -> FinalOnMethod
| _ -> FinalOnClass);
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Public ->
Some
{
name = "public";
type_ = Keyword Public;
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Protected ->
Some
{
name = "protected";
type_ = Keyword Protected;
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Private ->
Some
{
name = "private";
type_ = Keyword Private;
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Async ->
Some
{
name = "async";
type_ =
Keyword
(match ctx with
| Some AsyncBlockHeader -> AsyncBlock
| _ -> Async);
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Await ->
Some
{
name = "await";
type_ = Keyword Await;
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Concurrent ->
Some
{
name = "concurrent";
type_ = Keyword Concurrent;
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Readonly ->
Some
{
name = "readonly";
type_ =
Keyword
(match ctx with
| Some Method -> ReadonlyOnMethod
| Some Parameter -> ReadonlyOnParameter
| Some ReturnType -> ReadonlyOnReturnType
| _ -> ReadonlyOnExpression);
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Internal ->
Some
{
name = "internal";
type_ = Keyword Internal;
is_declaration = false;
pos = token_pos t;
}
| Token.TokenKind.Module ->
Some
{
name = "module";
type_ =
Keyword
(match ctx with
| Some (ModuleDecl DKModuleDeclaration) ->
ModuleInModuleDeclaration
| Some (ModuleDecl DKModuleMembershipDeclaration) ->
ModuleInModuleMembershipDeclaration
| _ -> ModuleInModuleDeclaration);
is_declaration = false;
pos = token_pos t;
}
| _ -> None
in
(* Walk FFP syntax node [s], tracking the current context [ctx]
(e.g. are we in an interface?) and accumulate hover items. *)
let rec aux
(ctx : keyword_context option) (acc : Result_set.elt list) (s : FFP.t) :
Result_set.elt list =
match s.syntax with
| ClassishDeclaration cd ->
let classish_decl_kind =
match cd.classish_keyword.syntax with
| Token t ->
(match t.Token.kind with
| Token.TokenKind.Class -> DKclass
| Token.TokenKind.Interface -> DKinterface
| _ -> DKclass)
| _ -> DKclass
in
let ctx = Some (ClassishDecl classish_decl_kind) in
List.fold (children s) ~init:acc ~f:(aux ctx)
| EnumClassDeclaration _ ->
List.fold
(children s)
~init:acc
~f:(aux (Some (ClassishDecl DKenumclass)))
| MethodishDeclaration _ ->
List.fold (children s) ~init:acc ~f:(aux (Some Method))
| FunctionDeclarationHeader
{
function_modifiers;
function_keyword;
function_name;
function_type_parameter_list;
function_left_paren;
function_parameter_list;
function_right_paren;
function_contexts;
function_colon;
function_readonly_return;
function_type;
function_where_clause;
} ->
let acc = aux ctx acc function_modifiers in
let acc = aux ctx acc function_keyword in
let acc = aux ctx acc function_name in
let acc = aux ctx acc function_type_parameter_list in
let acc = aux ctx acc function_left_paren in
let acc = aux ctx acc function_parameter_list in
let acc = aux ctx acc function_right_paren in
let acc = aux ctx acc function_contexts in
let acc = aux ctx acc function_colon in
let acc = aux (Some ReturnType) acc function_readonly_return in
let acc = aux ctx acc function_type in
let acc = aux ctx acc function_where_clause in
acc
| ParameterDeclaration _ ->
List.fold (children s) ~init:acc ~f:(aux (Some Parameter))
| AwaitableCreationExpression
{
awaitable_attribute_spec;
awaitable_async;
awaitable_compound_statement;
} ->
let acc = aux ctx acc awaitable_attribute_spec in
let acc = aux (Some AsyncBlockHeader) acc awaitable_async in
aux ctx acc awaitable_compound_statement
| ModuleDeclaration _ ->
List.fold
(children s)
~init:acc
~f:(aux (Some (ModuleDecl DKModuleDeclaration)))
| ModuleMembershipDeclaration _ ->
List.fold
(children s)
~init:acc
~f:(aux (Some (ModuleDecl DKModuleMembershipDeclaration)))
| TypeConstDeclaration _ ->
List.fold (children s) ~init:acc ~f:(aux (Some TypeConst))
| Contexts c ->
let acc = List.fold (children s) ~init:acc ~f:(aux ctx) in
let is_empty =
match c.contexts_types.syntax with
| Missing -> true
| _ -> false
in
if is_empty then
{
name = "pure function";
type_ = PureFunctionContext;
is_declaration = false;
pos = syntax_pos s;
}
:: acc
else
acc
| Token t ->
(match elt_of_token ctx t with
| Some elt -> elt :: acc
| None -> acc)
| _ -> List.fold (children s) ~init:acc ~f:(aux ctx)
in
aux None [] tree
let all_symbols ctx tast : Result_set.elt list =
Errors.ignore_ (fun () -> visitor#go ctx tast |> Result_set.elements)
let all_symbols_ctx
~(ctx : Provider_context.t) ~(entry : Provider_context.entry) :
Result_set.elt list =
match entry.Provider_context.symbols with
| None ->
let cst = Ast_provider.compute_cst ~ctx ~entry in
let tree = Provider_context.PositionedSyntaxTree.root cst in
let fixme_symbols = fixmes tree in
let keyword_symbols = keywords tree in
let { Tast_provider.Compute_tast.tast; _ } =
Tast_provider.compute_tast_quarantined ~ctx ~entry
in
let symbols =
fixme_symbols
@ keyword_symbols
@ all_symbols ctx tast.Tast_with_dynamic.under_normal_assumptions
in
entry.Provider_context.symbols <- Some symbols;
symbols
| Some symbols -> symbols
let go_quarantined
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(line : int)
~(column : int) : Relative_path.t SymbolOccurrence.t list =
all_symbols_ctx ~ctx ~entry |> List.filter ~f:(is_target line column) |
OCaml Interface | hhvm/hphp/hack/src/server/identifySymbolService.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.
*
*)
module Result_set : Set.S with type elt = Relative_path.t SymbolOccurrence.t
val clean_member_name : string -> string
val all_symbols : Provider_context.t -> Tast.program -> Result_set.elt list
val all_symbols_ctx :
ctx:Provider_context.t -> entry:Provider_context.entry -> Result_set.elt list
val go_quarantined :
ctx:Provider_context.t ->
entry:Provider_context.entry ->
line:int ->
column:int ->
Relative_path.t SymbolOccurrence.t list |
OCaml | hhvm/hphp/hack/src/server/ide_info_store.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
open Option.Monad_infix
module ClientId : sig
type t = int
val make : unit -> t
end = struct
type t = int
let next_id : t ref = ref 0
let make () =
let id = !next_id in
next_id := id + 1;
id
end
type client_id = ClientId.t
type t = {
id: ClientId.t;
client: ClientProvider.client;
open_files: Relative_path.Set.t;
}
(* We track the IDE using a global reference instead of using the server env (ServerEnv.env)
because:
- the code that agglomerates job results needs access to the IDE to stream errors
- but that code does not have access to the server environment, as it can be called without a server
- besides, interrupts passed to MultiWorker can edit IDE info. We want the code agglomerating job results
to see those changes. *)
let ide_info : t option ref = ref None
let new_ client =
let client = ClientProvider.make_persistent client in
let id = ClientId.make () in
Hh_logger.info "[Ide_info_store] New tracked IDE with ID %d." id;
ide_info := Some { id; client; open_files = Relative_path.Set.empty };
()
let ide_disconnect () =
Option.iter !ide_info ~f:(fun ide_info ->
Hh_logger.info "[Ide_info_store] IDE with ID %d disconnected" ide_info.id);
ide_info := None
let with_open_file file ide =
{ ide with open_files = Relative_path.Set.add ide.open_files file }
let open_file file = ide_info := !ide_info >>| with_open_file file
let with_close_file file ide =
{ ide with open_files = Relative_path.Set.remove ide.open_files file }
let close_file file = ide_info := !ide_info >>| with_close_file file
let get () = !ide_info
let get_client () = get () >>| fun { client; _ } -> client |
OCaml Interface | hhvm/hphp/hack/src/server/ide_info_store.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.
*
*)
(** Module to track the current connected IDE. *)
type client_id = int
(** The information we track about an IDE. *)
type t = {
id: client_id; (** A unique ID assigned to this IDE when it's created. *)
client: ClientProvider.client;
(** Used to communicated with the IDE client. *)
open_files: Relative_path.Set.t; (** Files which are opened in this IDE. *)
}
(** Make this client persistent and track a new IDE client. *)
val new_ : ClientProvider.client -> unit
(** Notify that the IDE has disconnected and stop tracking it. *)
val ide_disconnect : unit -> unit
(** Notify that a file has been opened in the IDE. *)
val open_file : Relative_path.t -> unit
(** Notify that a file has been closed in the IDE. *)
val close_file : Relative_path.t -> unit
(** Get current IDE tracked information. *)
val get : unit -> t option
val get_client : unit -> ClientProvider.client option |
OCaml | hhvm/hphp/hack/src/server/inferAtPosService.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 first string is the pretty-printed type, the second is the JSON *)
type result = (string * string) option |
OCaml | hhvm/hphp/hack/src/server/inferErrorAtPosService.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 t = {
actual_ty_string: string;
actual_ty_json: string;
expected_ty_string: string;
expected_ty_json: string;
}
type result = t option |
OCaml | hhvm/hphp/hack/src/server/methodJumps.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.Method_jumps
open Typing_defs
module Cls = Decl_provider.Class
let string_filter_to_method_jump_filter = function
| "No_filter" -> Some No_filter
| "Class" -> Some Class
| "Interface" -> Some Interface
| "Trait" -> Some Trait
| _ -> None
(* Used so the given input doesn't need the `\`. *)
let add_ns name =
if Char.equal name.[0] '\\' then
name
else
"\\" ^ name
let get_overridden_methods ctx origin_class get_or_method dest_class acc =
match Decl_provider.get_class ctx dest_class with
| None -> acc
| Some dest_class ->
(* Check if each destination method exists in the origin *)
List.fold
(Cls.methods dest_class)
~init:acc
~f:(fun acc (m_name, de_mthd) ->
(* Filter out inherited methods *)
if not (String.equal de_mthd.ce_origin (Cls.name dest_class)) then
acc
else
let or_mthd = get_or_method m_name in
match or_mthd with
| Some or_mthd when String.equal or_mthd.ce_origin origin_class ->
let get_pos (lazy ty) =
ty
|> Typing_defs.get_pos
|> Naming_provider.resolve_position ctx
|> Pos.to_absolute
in
{
orig_name = m_name;
orig_pos = get_pos or_mthd.ce_type;
dest_name = m_name;
dest_pos = get_pos de_mthd.ce_type;
orig_p_name = origin_class;
dest_p_name = Cls.name dest_class;
}
:: acc
| Some _
| None ->
acc)
let check_if_extends_class_and_find_methods
ctx target_class_name get_method target_class_pos class_name acc =
let class_ = Decl_provider.get_class ctx class_name in
match class_ with
| None -> acc
| Some c when Cls.has_ancestor c target_class_name ->
let acc =
get_overridden_methods ctx target_class_name get_method class_name acc
in
{
orig_name = target_class_name;
orig_pos =
Pos.to_absolute
@@ Naming_provider.resolve_position ctx
@@ target_class_pos;
dest_name = Cls.name c;
dest_pos =
Pos.to_absolute @@ Naming_provider.resolve_position ctx @@ Cls.pos c;
orig_p_name = "";
dest_p_name = "";
}
:: acc
| _ -> acc
let filter_extended_classes
ctx target_class_name get_method target_class_pos acc classes =
List.fold_left classes ~init:acc ~f:(fun acc (_, cid, _) ->
check_if_extends_class_and_find_methods
ctx
target_class_name
get_method
target_class_pos
cid
acc)
let find_extended_classes_in_files
ctx target_class_name get_method target_class_pos acc classes =
List.fold_left classes ~init:acc ~f:(fun acc classes ->
filter_extended_classes
ctx
target_class_name
get_method
target_class_pos
acc
classes)
(* Might raise {!Naming_table.File_info_not_found} *)
let find_extended_classes_in_files_parallel
ctx workers target_class_name get_method target_class_pos naming_table files
=
let classes =
Relative_path.Set.fold files ~init:[] ~f:(fun fn acc ->
let { FileInfo.classes; _ } =
Naming_table.get_file_info_unsafe naming_table fn
in
classes :: acc)
in
if List.length classes > 10 then
MultiWorker.call
workers
~job:
(find_extended_classes_in_files
ctx
target_class_name
get_method
target_class_pos)
~merge:List.rev_append
~neutral:[]
~next:(MultiWorker.next workers classes)
else
find_extended_classes_in_files
ctx
target_class_name
get_method
target_class_pos
[]
classes
(* Find child classes.
Might raise {!Naming_table.File_info_not_found} *)
let get_child_classes_and_methods ctx cls ~filter naming_table workers =
(match filter with
| No_filter -> ()
| _ -> failwith "Method jump filters not implemented for finding children");
let files = FindRefsService.get_child_classes_files ctx (Cls.name cls) in
find_extended_classes_in_files_parallel
ctx
workers
(Cls.name cls)
(Cls.get_method cls)
(Cls.pos cls)
naming_table
files
let class_passes_filter ~filter cls =
match (filter, Cls.kind cls) with
| (No_filter, _) -> true
| (Class, Ast_defs.Cclass _) -> true
| (Interface, Ast_defs.Cinterface) -> true
| (Trait, Ast_defs.Ctrait) -> true
| _ -> false
(* Find ancestor classes *)
let get_ancestor_classes_and_methods ctx cls ~filter acc =
let class_ = Decl_provider.get_class ctx (Cls.name cls) in
match class_ with
| None -> []
| Some cls ->
List.fold (Cls.all_ancestor_names cls) ~init:acc ~f:(fun acc k ->
let class_ = Decl_provider.get_class ctx k in
match class_ with
| Some c when class_passes_filter ~filter c ->
let acc =
get_overridden_methods
ctx
(Cls.name cls)
(Cls.get_method cls)
(Cls.name c)
acc
in
{
orig_name = Utils.strip_ns (Cls.name cls);
orig_pos =
Cls.pos cls
|> Naming_provider.resolve_position ctx
|> Pos.to_absolute;
dest_name = Utils.strip_ns (Cls.name c);
dest_pos =
Cls.pos c
|> Naming_provider.resolve_position ctx
|> Pos.to_absolute;
orig_p_name = "";
dest_p_name = "";
}
:: acc
| _ -> acc)
(* Returns a list of the ancestor or child
* classes and methods for a given class.
* Might raise {!Naming_table.File_info_not_found}
*)
let get_inheritance ctx class_ ~filter ~find_children naming_table workers =
let class_ = add_ns class_ in
let class_ = Decl_provider.get_class ctx class_ in
match class_ with
| None -> []
| Some c ->
if find_children then
get_child_classes_and_methods ctx c ~filter naming_table workers
else
get_ancestor_classes_and_methods ctx c ~filter [] |
OCaml | hhvm/hphp/hack/src/server/monitorRpc.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 handoff_options = {
(* If server is dormant because it is waiting for Informant to start one,
* set this to true to start a server anyway. *)
force_dormant_start: bool;
(* There can be multiple named channels between server and monitor in order
* to prioritize some requests over others. Connecting code needs to specify
* which channel it wants to use. *)
pipe_name: string;
}
type command =
| HANDOFF_TO_SERVER of Connection_tracker.t * handoff_options
(* Shut down all servers and then the monitor. *)
| SHUT_DOWN of Connection_tracker.t
(** Sent by monitor in ServerMonitor, received by server in ServerClientProvider *)
type monitor_to_server_handoff_msg = {
m2s_tracker: Connection_tracker.t;
m2s_sequence_number: int;
(** A unique number incremented for each client socket handoff from monitor to server.
Useful to correlate monitor and server logs. *)
}
let (receipt_serialize, receipt_deserialize) =
let key = "sequence_number_high_water_mark" in
let serialize i = Hh_json.JSON_Object [(key, Hh_json.int_ i)] in
let deserialize json = Hh_json_helpers.Jget.int_exn (Some json) key in
(serialize, deserialize)
(** This writes to the specified file. Invariants maintained by callers:
(1) the file is deleted shortly after the server launches, if it already existed,
(2) after the server has first received a handoff then it writes to the file,
(3) after each successive handoff the server overwrites the file,
(4) each write is protected by a unix writer lock.
In case of failure, we log but don't raise exceptions, in the hope that a
future write will succeed. *)
let write_server_receipt_to_monitor_file
~(server_receipt_to_monitor_file : string)
~(sequence_number_high_water_mark : int) : unit =
let json =
receipt_serialize sequence_number_high_water_mark
|> Hh_json.json_to_multiline
in
try Sys_utils.protected_write_exn server_receipt_to_monitor_file json with
| exn ->
let e = Exception.wrap exn in
Hh_logger.log
"SERVER_RECEIPT_TO_MONITOR(write) %s\n%s"
(Exception.get_ctor_string e)
(Exception.get_backtrace_string e |> Exception.clean_stack);
HackEventLogger.server_receipt_to_monitor_write_exn
~server_receipt_to_monitor_file
e;
()
(** This reads the specified file, under a unix reader lock.
There are legitimate scenarios where the file might not exist,
e.g. if the server has only recently started up and hasn't yet
written any receipts. In this case we return None.
If there are failures e.g. a malformed file content, then we write
a log and return None. *)
let read_server_receipt_to_monitor_file
~(server_receipt_to_monitor_file : string) : int option =
let content = ref "[not yet read content]" in
try
content := Sys_utils.protected_read_exn server_receipt_to_monitor_file;
let sequence_number_high_water_mark =
receipt_deserialize (Hh_json.json_of_string !content)
in
Some sequence_number_high_water_mark
with
| Unix.Unix_error (Unix.ENOENT, _, _) -> None
| exn ->
let e = Exception.wrap exn in
Hh_logger.log
"SERVER_RECEIPT_TO_MONITOR(read) %s\n%s\n%s"
(Exception.get_ctor_string e)
(Exception.get_backtrace_string e |> Exception.clean_stack)
!content;
HackEventLogger.server_receipt_to_monitor_read_exn
~server_receipt_to_monitor_file
e
!content;
None |
OCaml | hhvm/hphp/hack/src/server/saveStateService.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 SaveStateServiceTypes
let get_errors_filename (filename : string) : string = filename ^ ".err"
let get_errors_filename_json (filename : string) : string =
filename ^ ".err.json"
let get_legacy_decls_filename (filename : string) : string = filename ^ ".decls"
let get_shallow_decls_filename (filename : string) : string =
filename ^ ".shallowdecls"
(* Writes some OCaml object to a file with the given filename. *)
let save_contents (output_filename : string) (contents : 'a) : unit =
let chan = Stdlib.open_out_bin output_filename in
Marshal.to_channel chan contents [];
Stdlib.close_out chan
(* If the contents doesn't contain the value of the expected type, the result
is undefined behavior. We may crash, or we may continue with a bogus value. *)
let load_contents_unsafe (input_filename : string) : 'a =
let ic = Stdlib.open_in_bin input_filename in
let contents = Marshal.from_channel ic in
Stdlib.close_in ic;
contents
(* Loads the file info and the errors, if any. *)
let load_saved_state_exn
~(naming_table_fallback_path : string option)
~(errors_path : string)
(ctx : Provider_context.t) : Naming_table.t * saved_state_errors =
let old_naming_table =
match naming_table_fallback_path with
| Some nt_path ->
let naming_table_exists = Sys.file_exists nt_path in
Hh_logger.log
"Checked if the old naming table file exists (%b)"
naming_table_exists;
if not naming_table_exists then
failwith
(Printf.sprintf
"Naming table file does not exist on disk: '%s'"
nt_path);
Naming_table.load_from_sqlite ctx nt_path
| None ->
(*
If we reach here, then there was neither a SQLite naming table
in the saved state directory, nor was a path provided via
genv.local_config.naming_table_path.
ServerCheckUtils.get_naming_table_fallback_path will return None,
in which case we raise a failure, since the OCaml-marshalled
naming table no longer exists.
*)
HackEventLogger.naming_table_sqlite_missing ();
let str =
"No naming table path found, either from saved state directory or local config"
in
Hh_logger.log "%s" str;
failwith str
in
let (old_errors : saved_state_errors) =
if not (Sys.file_exists errors_path) then
Relative_path.Set.empty
else
Marshal.from_channel (In_channel.create ~binary:true errors_path)
in
(old_naming_table, old_errors)
let get_hot_classes (filename : string) : SSet.t =
if not (Disk.file_exists filename) then (
Hh_logger.log "Hot classes file '%s' was not found" filename;
SSet.empty
) else
Disk.cat filename
|> Hh_json.json_of_string
|> Hh_json.get_object_exn
|> List.find_exn ~f:(fun (k, _) -> String.equal k "classes")
|> snd
|> Hh_json.get_array_exn
|> List.map ~f:Hh_json.get_string_exn
|> SSet.of_list
(** Dumps the naming-table (a saveable form of FileInfo), and errors if any,
and hot class decls. *)
let dump_naming_and_errors
(output_filename : string)
(naming_table : Naming_table.t)
(errors : Errors.t) : unit =
let naming_sql_filename = output_filename ^ "_naming.sql" in
let (save_result : Naming_sqlite.save_result) =
Naming_table.save naming_table naming_sql_filename
in
Hh_logger.log
"Inserted symbols into the naming table:\n%s"
(Naming_sqlite.show_save_result save_result);
Hh_logger.log
"Finished saving naming table with %d errors."
(List.length save_result.Naming_sqlite.errors);
if List.length save_result.Naming_sqlite.errors > 0 then
Exit.exit Exit_status.Sql_assertion_failure;
assert (Sys.file_exists naming_sql_filename);
Hh_logger.log "Saved naming table sqlite to '%s'" naming_sql_filename;
(* Let's not write empty error files. *)
(if Errors.is_empty errors then
()
else
let error_files : saved_state_errors = Errors.get_failed_files errors in
save_contents (get_errors_filename output_filename) error_files);
()
(** Sorts and dumps the error relative paths in JSON format.
* An empty JSON list will be dumped if there are no errors.*)
let dump_errors_json (output_filename : string) (errors : Errors.t) : unit =
let error_files = Errors.get_failed_files errors in
let errors_json =
Hh_json.(
JSON_Array
(List.rev
(Relative_path.Set.fold
~init:[]
~f:(fun relative_path acc ->
JSON_String (Relative_path.suffix relative_path) :: acc)
error_files)))
in
let chan = Stdlib.open_out (get_errors_filename_json output_filename) in
Hh_json.json_to_output chan errors_json;
Stdlib.close_out chan
let saved_state_info_file_name ~base_file_name = base_file_name ^ "_info.json"
let saved_state_build_revision_write ~(base_file_name : string) : unit =
let info_file = saved_state_info_file_name ~base_file_name in
let open Hh_json in
Out_channel.with_file info_file ~f:(fun fh ->
json_to_output fh
@@ JSON_Object [("build_revision", string_ Build_id.build_revision)])
let saved_state_build_revision_read ~(base_file_name : string) : string =
let info_file = saved_state_info_file_name ~base_file_name in
let contents = RealDisk.cat info_file in
let json = Some (Hh_json.json_of_string contents) in
let build_revision = Hh_json_helpers.Jget.string_exn json "build_revision" in
build_revision
let dump_dep_graph_64bit ~mode ~db_name ~incremental_info_file =
let t = Unix.gettimeofday () in
let base_dep_graph =
match mode with
| Typing_deps_mode.InMemoryMode base_dep_graph -> base_dep_graph
| Typing_deps_mode.SaveToDiskMode { graph; _ } -> graph
| Typing_deps_mode.HhFanoutRustMode _ ->
failwith "HhFanoutRustMode is not supported in SaveStateService"
in
let () =
let open Hh_json in
Out_channel.with_file incremental_info_file ~f:(fun fh ->
json_to_output fh
@@ JSON_Object [("base_dep_graph", opt_string_to_json base_dep_graph)])
in
let dep_table_edges_added =
Typing_deps.save_discovered_edges
mode
~dest:db_name
~reset_state_after_saving:false
in
let (_ : float) = Hh_logger.log_duration "Writing discovered edges took" t in
{ dep_table_edges_added }
(** Saves the saved state to the given path. Returns number of dependency
* edges dumped into the database. *)
let save_state (env : ServerEnv.env) (output_filename : string) :
save_state_result =
let () = Sys_utils.mkdir_p (Filename.dirname output_filename) in
let db_name =
match env.ServerEnv.deps_mode with
| Typing_deps_mode.InMemoryMode _
| Typing_deps_mode.SaveToDiskMode _ ->
output_filename ^ "_64bit_dep_graph.delta"
| Typing_deps_mode.HhFanoutRustMode _ ->
"HhFanoutRustMode is not supported in SaveStateService"
in
let () =
if Sys.file_exists output_filename then
failwith
(Printf.sprintf "Cowardly refusing to overwrite '%s'." output_filename)
else
()
in
let () =
if Sys.file_exists db_name then
failwith (Printf.sprintf "Cowardly refusing to overwrite '%s'." db_name)
else
()
in
let (_ : float) =
let naming_table = env.ServerEnv.naming_table in
let errors = env.ServerEnv.errorl in
let t = Unix.gettimeofday () in
dump_naming_and_errors output_filename naming_table errors;
Hh_logger.log_duration "Saving saved-state naming+errors took" t
in
match env.ServerEnv.deps_mode with
| Typing_deps_mode.InMemoryMode _ ->
let incremental_info_file = output_filename ^ "_incremental_info.json" in
dump_errors_json output_filename env.ServerEnv.errorl;
saved_state_build_revision_write ~base_file_name:output_filename;
dump_dep_graph_64bit
~mode:env.ServerEnv.deps_mode
~db_name
~incremental_info_file
| Typing_deps_mode.SaveToDiskMode
{ graph = _; new_edges_dir; human_readable_dep_map_dir } ->
dump_errors_json output_filename env.ServerEnv.errorl;
saved_state_build_revision_write ~base_file_name:output_filename;
Hh_logger.warn
"saveStateService: not saving 64-bit dep graph edges to disk, because they are already in %s"
new_edges_dir;
(match human_readable_dep_map_dir with
| None -> ()
| Some dir ->
Hh_logger.warn "saveStateService: human readable dep map dir: %s" dir);
{ dep_table_edges_added = 0 }
| Typing_deps_mode.HhFanoutRustMode _ ->
failwith "HhFanoutRustMode is not supported in SaveStateService"
let go_naming (naming_table : Naming_table.t) (output_filename : string) :
(save_naming_result, string) result =
Utils.try_with_stack (fun () ->
let save_result = Naming_table.save naming_table output_filename in
Hh_logger.log
"Inserted symbols into the naming table:\n%s"
(Naming_sqlite.show_save_result save_result);
if List.length save_result.Naming_sqlite.errors > 0 then begin
Sys_utils.rm_dir_tree output_filename;
failwith "Naming table state had errors - deleting output file!"
end else
{
nt_files_added = save_result.Naming_sqlite.files_added;
nt_symbols_added = save_result.Naming_sqlite.symbols_added;
})
|> Result.map_error ~f:(fun e -> Exception.get_ctor_string e)
(* If successful, returns the # of edges from the dependency table that were written. *)
(* TODO: write some other stats, e.g., the number of names, the number of errors, etc. *)
let go (env : ServerEnv.env) (output_filename : string) :
(save_state_result, string) result =
Utils.try_with_stack (fun () -> save_state env output_filename)
|> Result.map_error ~f:(fun e -> Exception.get_ctor_string e) |
OCaml | hhvm/hphp/hack/src/server/saveStateServiceTypes.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.
*
*)
(** An alias for the errors type that we marshal to and unmarshal from the saved state.
Keep this in sync with saved_states.rs:dump_error_files *)
type saved_state_errors = Relative_path.Set.t
type save_state_result = { dep_table_edges_added: int }
type save_naming_result = {
nt_files_added: int;
nt_symbols_added: int;
} |
OCaml | hhvm/hphp/hack/src/server/searchServiceRunner.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 ServerEnv
module SearchServiceRunner = struct
type t = Relative_path.t * FileInfo.t
(* Chosen so that multiworker takes about ~2.5 seconds *)
let chunk_size genv = genv.local_config.ServerLocalConfig.search_chunk_size
let queue = Queue.create ()
(* Pops the first num_files from the queue *)
let update_search
(ctx : Provider_context.t) (sienv : SearchUtils.si_env) num_files :
SearchUtils.si_env =
let t = Unix.gettimeofday () in
let rec iter acc n =
if n <= 0 || Queue.is_empty queue then
acc
else
let x = Queue.dequeue_exn queue in
iter (x :: acc) (n - 1)
in
let defs_per_file = iter [] num_files in
let len = List.length defs_per_file in
if len = 0 then
sienv
else begin
Hh_logger.log "UPDATE_SEARCH start";
if len > 10 then ServerProgress.write "indexing %d files" len;
let sienv =
SymbolIndexCore.update_files ~ctx ~sienv ~paths:defs_per_file
in
let telemetry =
Telemetry.create ()
|> Telemetry.int_ ~key:"files" ~value:len
|> Telemetry.int_ ~key:"remaining" ~value:(Queue.length queue)
in
Hh_logger.log
"UPDATE_SEARCH_END %fs %s"
(Unix.gettimeofday () -. t)
(Telemetry.to_string telemetry);
HackEventLogger.update_search_end t telemetry;
sienv
end
(* Completely clears the queue *)
let run_completely (ctx : Provider_context.t) (sienv : SearchUtils.si_env) :
SearchUtils.si_env =
update_search ctx sienv (Queue.length queue)
let run genv (ctx : Provider_context.t) (sienv : SearchUtils.si_env) :
SearchUtils.si_env =
if Option.is_none (ServerArgs.ai_mode genv.options) then
let size =
if chunk_size genv = 0 then
Queue.length queue
else
chunk_size genv
in
update_search ctx sienv size
else
sienv
let internal_ssr_update
(fn : Relative_path.t)
(info : FileInfo.t)
~(source : SearchUtils.file_source) =
Queue.enqueue queue (fn, info, source)
(* Return true if it's best to run all queue items in one go,
* false if we should run small chunks every few seconds *)
let should_run_completely
(genv : ServerEnv.genv) (_ : SearchUtils.search_provider) : bool =
chunk_size genv = 0 && Option.is_none (ServerArgs.ai_mode genv.options)
let update_fileinfo_map
(defs_per_file : Naming_table.t) ~(source : SearchUtils.file_source) :
unit =
let i = ref 0 in
Naming_table.iter defs_per_file ~f:(fun fn info ->
internal_ssr_update fn info ~source;
i := !i + 1)
end |
OCaml | hhvm/hphp/hack/src/server/serverArgs.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
include Cli_args
type saved_state_target = Saved_state_target_info of saved_state_target_info
[@@deriving show]
(*****************************************************************************)
(* The options from the command line *)
(*****************************************************************************)
type options = {
ai_mode: Ai_options.t option;
check_mode: bool;
concatenate_prefix: string option;
config: (string * string) list;
custom_hhi_path: string option;
custom_telemetry_data: (string * string) list;
dump_fanout: bool;
from: string;
gen_saved_ignore_type_errors: bool;
ignore_hh_version: bool;
enable_ifc: string list;
enable_global_access_check: bool;
saved_state_ignore_hhconfig: bool;
json_mode: bool;
log_inference_constraints: bool;
max_procs: int option;
no_load: bool;
prechecked: bool option;
remote: bool;
root: Path.t;
save_filename: string option;
save_64bit: string option;
save_human_readable_64bit_dep_map: string option;
save_naming_filename: string option;
should_detach: bool;
(* AKA, daemon mode *)
waiting_client: Unix.file_descr option;
watchman_debug_logging: bool;
with_saved_state: saved_state_target option;
allow_non_opt_build: bool;
write_symbol_info: string option;
}
(*****************************************************************************)
(* Usage code *)
(*****************************************************************************)
let usage = Printf.sprintf "Usage: %s [WWW DIRECTORY]\n" Sys.argv.(0)
(*****************************************************************************)
(* Options *)
(*****************************************************************************)
module Messages = struct
let ai = " run ai with options"
let check = " check and exit"
let concatenate_prefix = " combine multiple hack files"
let config = " override arbitrary value from hh.conf (format: <key>=<value>)"
let custom_hhi_path = " use custom hhi files"
let daemon = " detach process"
let dump_fanout = " dump fanout to stdout as JSON, then exit"
let enable_ifc =
" run IFC analysis on any file whose path is prefixed by the argument (format: comma separated list of path prefixes)"
let enable_global_access_check =
" run global access checker to check global writes and reads"
let from = " so we know who's invoking - e.g. nuclide, vim, emacs, vscode"
let from_vim = " DEPRECATED"
let from_emacs = " DEPRECATED"
let from_hhclient = " DEPRECATED"
let gen_saved_ignore_type_errors =
" generate a saved state even if there are type errors."
let ignore_hh_version = " ignore hh_version check when loading saved states"
let saved_state_ignore_hhconfig =
" ignore hhconfig hash when loading saved states"
let json = " output errors in json format (arc lint mode)"
let log_inference_constraints =
" (for hh debugging purpose only) log type"
^ " inference constraints into external logger (e.g. Scuba)"
let max_procs = " max numbers of workers"
let no_load = " don't load from a saved state"
let prechecked = " override value of \"prechecked_files\" flag from hh.conf"
let profile_log = " enable profile logging"
let remote = " force remote type checking"
let save_state = " save server state to file"
let save_naming = " save naming table to file"
let save_64bit = " save discovered 64-bit to the given directory"
let save_human_readable_64bit_dep_map =
" save human readable map of 64bit hashes to names to files in the given directory"
let waiting_client =
" send message to fd/handle when server has begun"
^ " starting and again when it's done starting"
let watchman_debug_logging =
" Logs full Watchman requests and responses. This is very noisy"
let with_saved_state =
" Init with the given saved state instead of fetching it.\n"
^ "Expects a JSON string specified as: "
^ saved_state_json_descr
let write_symbol_info = " write symbol info to json files"
end
let print_json_version () =
print_endline @@ Hh_json.json_to_string Hh_version.version_json
(*****************************************************************************)
(* The main entry point *)
(*****************************************************************************)
let parse_options () : options =
let ai_mode = ref None in
let check_mode = ref false in
let concatenate_prefix = ref None in
let config = ref [] in
let custom_hhi_path = ref None in
let custom_telemetry_data = ref [] in
let dump_fanout = ref false in
let enable_ifc = ref [] in
let enable_global_access_check = ref false in
let from = ref "" in
let from_emacs = ref false in
let from_hhclient = ref false in
let from_vim = ref false in
let gen_saved_ignore_type_errors = ref false in
let ignore_hh = ref false in
let saved_state_ignore_hhconfig = ref false in
let json_mode = ref false in
let log_inference_constraints = ref false in
let max_procs = ref None in
let no_load = ref false in
let prechecked = ref None in
let remote = ref false in
let root = ref "" in
let save = ref None in
let save_64bit = ref None in
let save_human_readable_64bit_dep_map = ref None in
let save_naming = ref None in
let should_detach = ref false in
let version = ref false in
let waiting_client = ref None in
let watchman_debug_logging = ref false in
let with_saved_state = ref None in
let allow_non_opt_build = ref false in
let write_symbol_info = ref None in
let set_ai s = ai_mode := Some (Ai_options.prepare ~server:true s) in
let set_max_procs n = max_procs := Some n in
let set_save_state s = save := Some s in
let set_save_naming s = save_naming := Some s in
let set_wait fd = waiting_client := Some (Handle.wrap_handle fd) in
let set_with_saved_state s = with_saved_state := Some s in
let set_write_symbol_info s = write_symbol_info := Some s in
let set_enable_ifc s = enable_ifc := String_utils.split ',' s in
let set_from s = from := s in
let options =
[
("--ai", Arg.String set_ai, Messages.ai);
("--allow-non-opt-build", Arg.Set allow_non_opt_build, "");
("--check", Arg.Set check_mode, Messages.check);
( "--concatenate-all",
Arg.String (fun s -> concatenate_prefix := Some s),
Messages.concatenate_prefix );
( "--config",
Arg.String (fun s -> config := String_utils.split2_exn '=' s :: !config),
Messages.config );
( "--custom-hhi-path",
Arg.String (fun s -> custom_hhi_path := Some s),
Messages.custom_hhi_path );
( "--custom-telemetry-data",
Arg.String
(fun s ->
custom_telemetry_data :=
String_utils.split2_exn '=' s :: !custom_telemetry_data),
"Add a custom column to all logged telemetry samples (format: <column>=<value>)"
);
("--daemon", Arg.Set should_detach, Messages.daemon);
("--dump-fanout", Arg.Set dump_fanout, Messages.dump_fanout);
("--enable-ifc", Arg.String set_enable_ifc, Messages.enable_ifc);
( "--enable-global-access-check",
Arg.Set enable_global_access_check,
Messages.enable_global_access_check );
("--from-emacs", Arg.Set from_emacs, Messages.from_emacs);
("--from-hhclient", Arg.Set from_hhclient, Messages.from_hhclient);
("--from-vim", Arg.Set from_vim, Messages.from_vim);
("--from", Arg.String set_from, Messages.from);
( "--gen-saved-ignore-type-errors",
Arg.Set gen_saved_ignore_type_errors,
Messages.gen_saved_ignore_type_errors );
("--ignore-hh-version", Arg.Set ignore_hh, Messages.ignore_hh_version);
("--json", Arg.Set json_mode, Messages.json);
( "--log-inference-constraints",
Arg.Set log_inference_constraints,
Messages.log_inference_constraints );
("--max-procs", Arg.Int set_max_procs, Messages.max_procs);
("--no-load", Arg.Set no_load, Messages.no_load);
( "--no-prechecked",
Arg.Unit (fun () -> prechecked := Some false),
Messages.prechecked );
( "--prechecked",
Arg.Unit (fun () -> prechecked := Some true),
Messages.prechecked );
( "--profile-log",
Arg.Unit (fun () -> config := ("profile_log", "true") :: !config),
Messages.profile_log );
("--remote", Arg.Set remote, Messages.remote);
("--save-mini", Arg.String set_save_state, Messages.save_state);
("--save-naming", Arg.String set_save_naming, Messages.save_naming);
("--save-state", Arg.String set_save_state, Messages.save_state);
( "--save-64bit",
Arg.String (fun s -> save_64bit := Some s),
Messages.save_64bit );
( "--save-human-readable-64bit-dep-map",
Arg.String (fun s -> save_human_readable_64bit_dep_map := Some s),
Messages.save_human_readable_64bit_dep_map );
( "--saved-state-ignore-hhconfig",
Arg.Set saved_state_ignore_hhconfig,
Messages.saved_state_ignore_hhconfig );
("--version", Arg.Set version, "");
("--waiting-client", Arg.Int set_wait, Messages.waiting_client);
( "--watchman-debug-logging",
Arg.Set watchman_debug_logging,
Messages.watchman_debug_logging );
( "--with-mini-state",
Arg.String set_with_saved_state,
Messages.with_saved_state );
( "--write-symbol-info",
Arg.String set_write_symbol_info,
Messages.write_symbol_info );
("-d", Arg.Set should_detach, Messages.daemon);
("-s", Arg.String set_save_state, Messages.save_state);
]
in
let options = Arg.align options in
Arg.parse options (fun s -> root := s) usage;
if !version then (
if !json_mode then
print_json_version ()
else
print_endline Hh_version.version;
exit 0
);
(* --json, --save, --write-symbol-info, --concatenate-all all imply check *)
let check_mode =
Option.is_some !write_symbol_info
|| !check_mode
|| !json_mode
|| Option.is_some !save
|| Option.is_some !concatenate_prefix
in
if check_mode && Option.is_some !waiting_client then (
Printf.eprintf "--check is incompatible with wait modes!\n";
Exit.exit Exit_status.Input_error
);
let with_saved_state =
match get_saved_state_spec !with_saved_state with
| Ok (Some spec) -> Some (Saved_state_target_info spec)
| Ok None -> None
| Error message -> raise (Arg.Bad message)
in
(match !root with
| "" ->
Printf.eprintf "You must specify a root directory!\n";
Exit.exit Exit_status.Input_error
| _ -> ());
let root_path = Path.make !root in
Wwwroot.assert_www_directory root_path;
if !gen_saved_ignore_type_errors && not (Option.is_some !save) then (
Printf.eprintf
"--gen-saved-ignore-type-errors is only valid when combined with --save-state\n%!";
exit 1
);
{
ai_mode = !ai_mode;
check_mode;
concatenate_prefix = !concatenate_prefix;
config = !config;
custom_hhi_path = !custom_hhi_path;
custom_telemetry_data = !custom_telemetry_data;
dump_fanout = !dump_fanout;
enable_ifc = !enable_ifc;
enable_global_access_check = !enable_global_access_check;
from = !from;
gen_saved_ignore_type_errors = !gen_saved_ignore_type_errors;
ignore_hh_version = !ignore_hh;
saved_state_ignore_hhconfig = !saved_state_ignore_hhconfig;
json_mode = !json_mode;
log_inference_constraints = !log_inference_constraints;
max_procs = !max_procs;
no_load = !no_load;
prechecked = !prechecked;
remote = !remote;
root = root_path;
save_filename = !save;
save_64bit = !save_64bit;
save_human_readable_64bit_dep_map = !save_human_readable_64bit_dep_map;
save_naming_filename = !save_naming;
should_detach = !should_detach;
waiting_client = !waiting_client;
watchman_debug_logging = !watchman_debug_logging;
with_saved_state;
allow_non_opt_build = !allow_non_opt_build;
write_symbol_info = !write_symbol_info;
}
(* useful in testing code *)
let default_options ~root =
{
ai_mode = None;
check_mode = false;
concatenate_prefix = None;
config = [];
custom_hhi_path = None;
custom_telemetry_data = [];
dump_fanout = false;
enable_ifc = [];
enable_global_access_check = false;
from = "";
gen_saved_ignore_type_errors = false;
ignore_hh_version = false;
saved_state_ignore_hhconfig = false;
json_mode = false;
log_inference_constraints = false;
max_procs = None;
no_load = true;
prechecked = None;
remote = false;
root = Path.make root;
save_filename = None;
save_64bit = None;
save_human_readable_64bit_dep_map = None;
save_naming_filename = None;
should_detach = false;
waiting_client = None;
watchman_debug_logging = false;
with_saved_state = None;
allow_non_opt_build = false;
write_symbol_info = None;
}
(** Useful for executables which don't want to make a subscription to a
file-watching service. *)
let default_options_with_check_mode ~root =
{ (default_options ~root) with check_mode = true }
(*****************************************************************************)
(* Accessors *)
(*****************************************************************************)
let ai_mode options = options.ai_mode
let check_mode options = options.check_mode
let concatenate_prefix options = options.concatenate_prefix
let config options = options.config
let custom_hhi_path options = options.custom_hhi_path
let custom_telemetry_data options = options.custom_telemetry_data
let dump_fanout options = options.dump_fanout
let enable_ifc options = options.enable_ifc
let enable_global_access_check options = options.enable_global_access_check
let from options = options.from
let gen_saved_ignore_type_errors options = options.gen_saved_ignore_type_errors
let ignore_hh_version options = options.ignore_hh_version
let saved_state_ignore_hhconfig options = options.saved_state_ignore_hhconfig
let json_mode options = options.json_mode
let log_inference_constraints options = options.log_inference_constraints
let max_procs options = options.max_procs
let no_load options = options.no_load
let prechecked options = options.prechecked
let remote options = options.remote
let root options = options.root
let save_filename options = options.save_filename
let save_64bit options = options.save_64bit
let save_human_readable_64bit_dep_map options =
options.save_human_readable_64bit_dep_map
let save_naming_filename options = options.save_naming_filename
let should_detach options = options.should_detach
let waiting_client options = options.waiting_client
let watchman_debug_logging options = options.watchman_debug_logging
let with_saved_state options = options.with_saved_state
let is_using_precomputed_saved_state options =
match with_saved_state options with
| Some (Saved_state_target_info _) -> true
| None -> false
let allow_non_opt_build options = options.allow_non_opt_build
let write_symbol_info options = options.write_symbol_info
(*****************************************************************************)
(* Setters *)
(*****************************************************************************)
let set_ai_mode options ai_mode = { options with ai_mode }
let set_check_mode options check_mode = { options with check_mode }
let set_gen_saved_ignore_type_errors options ignore_type_errors =
{ options with gen_saved_ignore_type_errors = ignore_type_errors }
let set_max_procs options procs = { options with max_procs = Some procs }
let set_no_load options is_no_load = { options with no_load = is_no_load }
let set_config options config = { options with config }
let set_from options from = { options with from }
let set_save_64bit options save_64bit = { options with save_64bit }
let set_save_naming_filename options save_naming_filename =
{ options with save_naming_filename }
let set_save_filename options save_filename = { options with save_filename }
(****************************************************************************)
(* Misc *)
(****************************************************************************)
let to_string
{
ai_mode;
check_mode;
concatenate_prefix;
config;
custom_hhi_path;
custom_telemetry_data;
dump_fanout;
enable_ifc;
enable_global_access_check;
from;
gen_saved_ignore_type_errors;
ignore_hh_version;
saved_state_ignore_hhconfig;
json_mode;
log_inference_constraints;
max_procs;
no_load;
prechecked;
remote;
root;
save_filename;
save_64bit;
save_human_readable_64bit_dep_map;
save_naming_filename;
should_detach;
waiting_client;
watchman_debug_logging;
with_saved_state;
allow_non_opt_build;
write_symbol_info;
} =
let ai_mode_str =
match ai_mode with
| None -> "<>"
| Some _ -> "Some(...)"
in
let saved_state_str =
match with_saved_state with
| None -> "<>"
| Some _ -> "SavedStateTarget(...)"
in
let waiting_client_str =
match waiting_client with
| None -> "<>"
| Some _ -> "WaitingClient(...)"
in
let concatenate_prefix_str =
match concatenate_prefix with
| None -> "<>"
| Some path -> path
in
let custom_hhi_path_str =
match custom_hhi_path with
| None -> "<>"
| Some path -> path
in
let save_filename_str =
match save_filename with
| None -> "<>"
| Some path -> path
in
let save_64bit_str =
match save_64bit with
| None -> "<>"
| Some path -> path
in
let save_human_readable_64bit_dep_map_str =
match save_human_readable_64bit_dep_map with
| None -> "<>"
| Some path -> path
in
let save_naming_filename_str =
match save_naming_filename with
| None -> "<>"
| Some path -> path
in
let prechecked_str =
match prechecked with
| None -> "<>"
| Some b -> string_of_bool b
in
let max_procs_str =
match max_procs with
| None -> "<>"
| Some n -> string_of_int n
in
let write_symbol_info_str =
match write_symbol_info with
| None -> "<>"
| Some s -> s
in
let config_str =
Printf.sprintf
"[%s]"
(String.concat ~sep:", "
@@ List.map
~f:(fun (key, value) -> Printf.sprintf "%s=%s" key value)
config)
in
let enable_ifc_str =
Printf.sprintf "[%s]" (String.concat ~sep:"," enable_ifc)
in
let custom_telemetry_data_str =
custom_telemetry_data
|> List.map ~f:(fun (column, value) -> Printf.sprintf "%s=%s" column value)
|> String.concat ~sep:", "
|> Printf.sprintf "[%s]"
in
[
"ServerArgs.options({";
"ai_mode: ";
ai_mode_str;
", ";
"check_mode: ";
string_of_bool check_mode;
", ";
"concatenate_prefix: ";
concatenate_prefix_str;
", ";
"config: ";
config_str;
"custom_hhi_path: ";
custom_hhi_path_str;
"custom_telemetry_data: ";
custom_telemetry_data_str;
"dump_fanout: ";
string_of_bool dump_fanout;
", ";
"enable_ifc: ";
enable_ifc_str;
", ";
"enable_global_access_check: ";
string_of_bool enable_global_access_check;
", ";
"from: ";
from;
", ";
"gen_saved_ignore_type_errors: ";
string_of_bool gen_saved_ignore_type_errors;
", ";
"ignore_hh_version: ";
string_of_bool ignore_hh_version;
", ";
"saved_state_ignore_hhconfig: ";
string_of_bool saved_state_ignore_hhconfig;
", ";
"json_mode: ";
string_of_bool json_mode;
", ";
"log_inference_constraints: ";
string_of_bool log_inference_constraints;
", ";
"maxprocs: ";
max_procs_str;
", ";
"no_load: ";
string_of_bool no_load;
", ";
"prechecked: ";
prechecked_str;
"remote: ";
string_of_bool remote;
", ";
"root: ";
Path.to_string root;
", ";
"save_filename: ";
save_filename_str;
", ";
"save_64bit: ";
save_64bit_str;
", ";
"save_human_readable_64bit_dep_map: ";
save_human_readable_64bit_dep_map_str;
", ";
"save_naming_filename: ";
save_naming_filename_str;
", ";
"should_detach: ";
string_of_bool should_detach;
", ";
"waiting_client: ";
waiting_client_str;
", ";
"watchman_debug_logging: ";
string_of_bool watchman_debug_logging;
", ";
"with_saved_state: ";
saved_state_str;
", ";
"allow_non_opt_build: ";
string_of_bool allow_non_opt_build;
", ";
"write_symbol_info: ";
write_symbol_info_str;
", ";
"})";
]
|> String.concat ~sep:"" |
OCaml Interface | hhvm/hphp/hack/src/server/serverArgs.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 options
include module type of Cli_args
type saved_state_target = Saved_state_target_info of saved_state_target_info
[@@deriving show]
(****************************************************************************)
(* The main entry point *)
(****************************************************************************)
val default_options : root:string -> options
val default_options_with_check_mode : root:string -> options
val parse_options : unit -> options
(****************************************************************************)
(* Accessors *)
(****************************************************************************)
val ai_mode : options -> Ai_options.t option
val check_mode : options -> bool
val concatenate_prefix : options -> string option
val config : options -> (string * string) list
val custom_hhi_path : options -> string option
val custom_telemetry_data : options -> (string * string) list
val dump_fanout : options -> bool
val enable_ifc : options -> string list
val enable_global_access_check : options -> bool
val from : options -> string
val gen_saved_ignore_type_errors : options -> bool
val ignore_hh_version : options -> bool
val saved_state_ignore_hhconfig : options -> bool
val json_mode : options -> bool
val log_inference_constraints : options -> bool
val max_procs : options -> int option
val no_load : options -> bool
val prechecked : options -> bool option
val remote : options -> bool
val root : options -> Path.t
val save_filename : options -> string option
val save_64bit : options -> string option
val save_human_readable_64bit_dep_map : options -> string option
val save_naming_filename : options -> string option
val should_detach : options -> bool
val waiting_client : options -> Unix.file_descr option
val watchman_debug_logging : options -> bool
val with_saved_state : options -> saved_state_target option
val is_using_precomputed_saved_state : options -> bool
val allow_non_opt_build : options -> bool
val write_symbol_info : options -> string option
(****************************************************************************)
(* Setters *)
(****************************************************************************)
val set_ai_mode : options -> Ai_options.t option -> options
val set_check_mode : options -> bool -> options
val set_gen_saved_ignore_type_errors : options -> bool -> options
val set_max_procs : options -> int -> options
val set_no_load : options -> bool -> options
val set_config : options -> (string * string) list -> options
val set_from : options -> string -> options
val set_save_64bit : options -> string option -> options
val set_save_naming_filename : options -> string option -> options
val set_save_filename : options -> string option -> options
(****************************************************************************)
(* Misc *)
(****************************************************************************)
val print_json_version : unit -> unit
val to_string : options -> string |
OCaml | hhvm/hphp/hack/src/server/serverAutoComplete.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
(*****************************************************************************)
(* Code for auto-completion *)
(*****************************************************************************)
(* For identifying case statements from text context *)
let context_after_single_colon_regex = Str.regexp ".*[a-zA-Z_0-9\"']:$"
(* For identifying user attributes *)
let context_after_double_right_angle_bracket_regex =
Str.regexp ".*[a-zA-z_0-9\"' ,)]>>$"
(* For identifying shape keys *)
let context_after_quote = Str.regexp ".*['\"]$"
(* For identifying instances of { that are not part of an XHP attribute value. *)
let context_after_open_curly_brace_without_equals_regex =
Str.regexp ".*[^=][ ]*{$"
let get_autocomplete_context
~(file_content : string)
~(pos : File_content.position)
~(is_manually_invoked : bool) :
AutocompleteTypes.legacy_autocomplete_context =
(* This function retrieves the current line of text up to the position, *)
(* and determines whether it's something like "<nt:te" or "->:attr". *)
(* This is a dumb implementation. Would be better to replace it with FFP. *)
if pos.File_content.column = 1 then
{
AutocompleteTypes.is_manually_invoked;
is_after_single_colon = false;
is_after_double_right_angle_bracket = false;
is_after_open_square_bracket = false;
is_after_quote = false;
is_before_apostrophe = false;
is_open_curly_without_equals = false;
char_at_pos = ' ';
}
else
let pos_start = { pos with File_content.column = 1 } in
let (offset_start, offset) =
File_content.get_offsets file_content (pos_start, pos)
in
let leading_text =
String.sub file_content ~pos:offset_start ~len:(offset - offset_start)
in
(* text is the text from the start of the line up to the caret position *)
let is_after_single_colon =
Str.string_match context_after_single_colon_regex leading_text 0
in
let is_after_double_right_angle_bracket =
Str.string_match
context_after_double_right_angle_bracket_regex
leading_text
0
in
let is_after_open_square_bracket =
String.length leading_text >= 1
&& String.equal (Str.last_chars leading_text 1) "["
in
let is_after_quote = Str.string_match context_after_quote leading_text 0 in
(* Detect what comes next *)
let char_at_pos =
try
file_content.[offset + AutocompleteTypes.autocomplete_token_length]
with
| _ -> ' '
in
let is_before_apostrophe = Char.equal char_at_pos '\'' in
let is_open_curly_without_equals =
Str.string_match
context_after_open_curly_brace_without_equals_regex
leading_text
0
in
{
AutocompleteTypes.is_manually_invoked;
is_after_single_colon;
is_after_double_right_angle_bracket;
is_after_open_square_bracket;
is_after_quote;
is_before_apostrophe;
is_open_curly_without_equals;
char_at_pos;
}
(** Call this function if you have an edited text file that ALREADY INCLUDES "AUTO332" *)
let go_at_auto332_ctx
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(sienv_ref : SearchUtils.si_env ref)
~(autocomplete_context : AutocompleteTypes.legacy_autocomplete_context)
~(naming_table : Naming_table.t) :
AutocompleteTypes.autocomplete_item list Utils.With_complete_flag.t =
(* Be sure to set this option on all entry points of this file *)
let ctx = Provider_context.set_autocomplete_mode ctx in
AutocompleteService.go_ctx
~ctx
~entry
~sienv_ref
~autocomplete_context
~naming_table
(** Call this function if you have a raw text file that DOES NOT have "AUTO332" in it *)
let go_ctx
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(sienv_ref : SearchUtils.si_env ref)
~(naming_table : Naming_table.t)
~(is_manually_invoked : bool)
~(line : int)
~(column : int) : AutocompleteTypes.ide_result =
(* Be sure to set this option on all entry points of this file *)
let ctx = Provider_context.set_autocomplete_mode ctx in
let open File_content in
(* We have to edit the file content to add the text AUTO332.
TODO: Switch to FFP Autocomplete to avoid doing this file edit *)
let file_content = Provider_context.read_file_contents_exn entry in
let pos = { line; column } in
let edits =
[
{
range = Some { st = pos; ed = pos };
text = AutocompleteTypes.autocomplete_token;
};
]
in
let auto332_content = File_content.edit_file_unsafe file_content edits in
let (modified_auto332_context, modified_auto332_entry) =
Provider_context.add_or_overwrite_entry_contents
~ctx
~path:entry.Provider_context.path
~contents:auto332_content
in
let autocomplete_context =
get_autocomplete_context
~file_content:auto332_content
~pos
~is_manually_invoked
in
let result =
go_at_auto332_ctx
~ctx:modified_auto332_context
~entry:modified_auto332_entry
~sienv_ref
~autocomplete_context
~naming_table
in
{
AutocompleteTypes.completions = result.Utils.With_complete_flag.value;
char_at_pos = autocomplete_context.AutocompleteTypes.char_at_pos;
is_complete = result.Utils.With_complete_flag.is_complete;
} |
OCaml Interface | hhvm/hphp/hack/src/server/serverAutoComplete.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.
*
*)
val go_ctx :
ctx:Provider_context.t ->
entry:Provider_context.entry ->
sienv_ref:SearchUtils.si_env ref ->
naming_table:Naming_table.t ->
is_manually_invoked:bool ->
line:int ->
column:int ->
AutocompleteTypes.ide_result
val go_at_auto332_ctx :
ctx:Provider_context.t ->
entry:Provider_context.entry ->
sienv_ref:SearchUtils.si_env ref ->
autocomplete_context:AutocompleteTypes.legacy_autocomplete_context ->
naming_table:Naming_table.t ->
AutocompleteTypes.autocomplete_item list Utils.With_complete_flag.t
val get_autocomplete_context :
file_content:string ->
pos:File_content.position ->
is_manually_invoked:bool ->
AutocompleteTypes.legacy_autocomplete_context |
OCaml | hhvm/hphp/hack/src/server/serverBusyStatus.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.
*
*)
let send (status : ServerCommandTypes.busy_status) : ServerEnv.seconds option =
match Ide_info_store.get_client () with
| None -> None
| Some client ->
let message = ServerCommandTypes.BUSY_STATUS status in
(try
ClientProvider.send_push_message_to_client client message;
Some (Unix.gettimeofday ())
with
| ClientProvider.Client_went_away -> None
| e ->
Hh_logger.log "Failed to send busy status - %s" (Printexc.to_string e);
None) |
OCaml Interface | hhvm/hphp/hack/src/server/serverBusyStatus.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.
*
*)
(** Send status to persistent client, if any. Log in case of failure.
Returns the timestamp of the send or None if nothing
was sent, e.g. because of there is no persistent client
or sending failed. *)
val send : ServerCommandTypes.busy_status -> ServerEnv.seconds option |
OCaml | hhvm/hphp/hack/src/server/serverCallHierarchyIncomingCalls.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 group_refs_by_file (ref_result : ServerCommandTypes.Find_refs.result) :
(string * ServerCommandTypes.Find_refs.result) list =
let table = ref (3 * List.length ref_result / 4 |> Hashtbl.create) in
let key_list : string list ref = ref [] in
let add_ref_to_tbl ((name, pos) : string * Pos.absolute) : unit =
let file_ = Pos.filename pos in
if not (Hashtbl.mem !table file_) then key_list := file_ :: !key_list;
Hashtbl.add !table file_ (name, pos)
in
List.iter add_ref_to_tbl ref_result;
List.map (fun key -> (key, Hashtbl.find_all !table key)) !key_list
let occ_defs_of_file (ctx : Provider_context.t) (file : string) :
(Relative_path.t SymbolOccurrence.t
* Relative_path.t SymbolDefinition.t option)
list =
let path = Relative_path.create_detect_prefix file in
let (ctx_out, entry) = Provider_context.add_entry_if_missing ~ctx ~path in
let all_symbols = IdentifySymbolService.all_symbols_ctx ~ctx:ctx_out ~entry in
let all_defs =
List.filter (fun s -> s.SymbolOccurrence.is_declaration) all_symbols
in
let (_, get_def) = ServerDepsUtil.get_ast_getdef ctx_out entry in
List.map (fun s -> (s, get_def s)) all_defs
let call_sites
(refs : ServerCommandTypes.Find_refs.result)
((_, d) :
Relative_path.t SymbolOccurrence.t
* Relative_path.t SymbolDefinition.t option) :
ServerCommandTypes.Find_refs.result =
match d with
| None -> []
| Some ds ->
List.filter
(fun (_, p) -> Pos.contains ds.SymbolDefinition.span (Pos.to_relative p))
refs
let def_call_sites_to_incoming_call
((o, d) :
Relative_path.t SymbolOccurrence.t
* Relative_path.t SymbolDefinition.t option)
(refs : ServerCommandTypes.Find_refs.result) :
Lsp.CallHierarchyIncomingCalls.callHierarchyIncomingCall =
let open Lsp.CallHierarchyIncomingCalls in
let from_ = Lsp_helpers.symbol_to_lsp_call_item o d in
let fromRanges_ =
List.map (fun (_, p) -> Lsp_helpers.hack_pos_to_lsp_range_adjusted p) refs
in
{ from = from_; fromRanges = fromRanges_ }
let file_refs_to_incoming_calls
(ctx : Provider_context.t)
((file, refs) : string * ServerCommandTypes.Find_refs.result) :
Lsp.CallHierarchyIncomingCalls.callHierarchyIncomingCall list =
let occ_defs = occ_defs_of_file ctx file in
let present_occ_defs =
List.filter (fun (_, d) -> Option.is_some d) occ_defs
in
let def_call_sites = List.map (call_sites refs) present_occ_defs in
let def_call_sites_zipped = List.combine present_occ_defs def_call_sites in
let def_call_sites_zipped_filtered =
List.filter (fun (_, r) -> List.length r != 0) def_call_sites_zipped
in
let (present_occ_defs_filtered, def_call_sites_filtered) =
List.split def_call_sites_zipped_filtered
in
List.map2
def_call_sites_to_incoming_call
present_occ_defs_filtered
def_call_sites_filtered
let string_pos_to_enclosing_rel_occs
~(ctx : Provider_context.t) (pos : string Pos.pos) :
Relative_path.t SymbolOccurrence.t list =
let file = Pos.filename pos in
let path = Relative_path.create_detect_prefix file in
let (ctx_out, entry) = Provider_context.add_entry_if_missing ~ctx ~path in
let all_symbols = IdentifySymbolService.all_symbols_ctx ~ctx:ctx_out ~entry in
let all_defs =
List.filter (fun s -> s.SymbolOccurrence.is_declaration) all_symbols
in
let pos_rel = Pos.to_relative pos in
List.filter (fun s -> Pos.contains s.SymbolOccurrence.pos pos_rel) all_defs
let ref_result_to_incoming_call_result
(ctx : Provider_context.t)
(ref_result : ServerCommandTypes.Find_refs.result) :
Lsp.CallHierarchyIncomingCalls.callHierarchyIncomingCall list =
let grouped_by_file = group_refs_by_file ref_result in
let incoming_calls =
List.concat_map (file_refs_to_incoming_calls ctx) grouped_by_file
in
incoming_calls
let go
(item : Lsp.CallHierarchyItem.t)
~(ctx : Provider_context.t)
~(genv : ServerEnv.genv)
~(env : ServerEnv.env) :
Lsp.CallHierarchyIncomingCalls.callHierarchyIncomingCall list
ServerCommandTypes.Done_or_retry.t
list =
let file = Lsp_helpers.lsp_uri_to_path item.Lsp.CallHierarchyItem.uri in
let (ctx, entry, _, get_def) = ServerDepsUtil.get_def_setup ctx file in
let declarations =
IdentifySymbolService.all_symbols_ctx ~ctx ~entry
|> List.filter (fun s -> s.SymbolOccurrence.is_declaration)
in
let target_symbols =
ServerCallHierarchyUtils.call_item_to_symbol_occ_list ~ctx ~entry ~item
in
let get_body_references =
ServerDepsInBatch.body_references
~ctx
~entry
~genv
~env
~get_def
~declarations
in
let ref_result_or_retries =
List.concat_map get_body_references target_symbols
in
List.map
(fun s ->
ServerCommandTypes.Done_or_retry.map_env
~f:(ref_result_to_incoming_call_result ctx)
(env, s)
|> snd)
ref_result_or_retries |
OCaml | hhvm/hphp/hack/src/server/serverCallHierarchyOutgoingCalls.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.
*
*)
(*Assusmes no occ_list is empty*)
let def_with_calling_occs_to_outgoing_call_option
((def, occ_list) :
Relative_path.t SymbolDefinition.t
* Relative_path.t SymbolOccurrence.t list) :
Lsp.CallHierarchyOutgoingCalls.callHierarchyOutgoingCall =
let open Lsp.CallHierarchyOutgoingCalls in
match occ_list with
| [] -> raise (Invalid_argument "Empty occ list")
| h :: _ ->
let call_to_ = Lsp_helpers.symbol_to_lsp_call_item h (Some def) in
let fromRanges_ =
List.map
(fun occ ->
Lsp_helpers.hack_pos_to_lsp_range_adjusted occ.SymbolOccurrence.pos)
occ_list
in
{ call_to = call_to_; fromRanges = fromRanges_ }
let group_occs_by_def
(get_def :
Relative_path.t SymbolOccurrence.t ->
Relative_path.t SymbolDefinition.t option)
(sym_occs : Relative_path.t SymbolOccurrence.t list) :
(Relative_path.t SymbolDefinition.t
* Relative_path.t SymbolOccurrence.t list)
list =
let table = ref (3 * List.length sym_occs / 4 |> Hashtbl.create) in
let (key_list : Relative_path.t SymbolDefinition.t list ref) = ref [] in
let add_sym_occ_to_table (sym_occ : Relative_path.t SymbolOccurrence.t) : unit
=
match get_def sym_occ with
| None -> ()
| Some def ->
if not (Hashtbl.mem !table def) then key_list := def :: !key_list;
Hashtbl.add !table def sym_occ
in
List.iter add_sym_occ_to_table sym_occs;
List.map (fun key -> (key, Hashtbl.find_all !table key)) !key_list
let go (item : Lsp.CallHierarchyItem.t) ~(ctx : Provider_context.t) =
let file = Lsp_helpers.lsp_uri_to_path item.Lsp.CallHierarchyItem.uri in
let (ctx, entry, _, get_def) = ServerDepsUtil.get_def_setup ctx file in
let dependable_symbols =
IdentifySymbolService.all_symbols_ctx ~ctx ~entry
|> List.filter ServerDepsUtil.symbol_in_call_hierarchy
in
let target_symbols =
ServerCallHierarchyUtils.call_item_to_symbol_occ_list ~ctx ~entry ~item
in
let target_defs = List.map get_def target_symbols in
let targets_zipped = List.combine target_symbols target_defs in
let targets_zipped_filtered =
List.filter (fun (_, d) -> Option.is_some d) targets_zipped
in
let (target_symbols_filtered, target_defs_filtered) =
List.split targets_zipped_filtered
in
let target_defs_filtered_nopt = List.map Option.get target_defs_filtered in
let body_symbols_lists =
List.map2
(ServerDepsUtil.body_symbols ~ctx ~entry dependable_symbols)
target_symbols_filtered
target_defs_filtered_nopt
in
let grouped_body_symbols_list =
List.concat_map (group_occs_by_def get_def) body_symbols_lists
in
try
let call_out_list =
List.map
def_with_calling_occs_to_outgoing_call_option
grouped_body_symbols_list
in
Some call_out_list
with
| Invalid_argument _ -> None |
OCaml | hhvm/hphp/hack/src/server/serverCallHierarchyUtils.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 Lsp.CallHierarchyItem
let item_matches_symocc
(item : Lsp.CallHierarchyItem.t)
(symbol : Relative_path.t SymbolOccurrence.t) : bool =
let open SymbolOccurrence in
item.name = symbol.name
&& Lsp_helpers.sym_occ_kind_to_lsp_sym_info_kind symbol.type_ = item.kind
&&
let selection = Lsp_helpers.hack_pos_to_lsp_range_adjusted symbol.pos in
let squiggle = item.selectionRange in
Lsp_helpers.get_range_overlap selection squiggle
= Lsp_helpers.Selection_covers_whole_squiggle
let call_item_to_symbol_occ_list
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(item : Lsp.CallHierarchyItem.t) : Relative_path.t SymbolOccurrence.t list
=
let all_symbols = IdentifySymbolService.all_symbols_ctx ~ctx ~entry in
List.filter (item_matches_symocc item) all_symbols |
OCaml | hhvm/hphp/hack/src/server/serverCheckpoint.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 Reordered_argument_collections
let checkpoints = ref SMap.empty
let process_updates updates =
(* Appending changed files to each checkpoint in the map *)
checkpoints :=
SMap.map !checkpoints ~f:(fun cur_set ->
Relative_path.Set.fold
updates
~f:
begin
(fun path acc -> Relative_path.Set.add acc path)
end
~init:cur_set)
let create_checkpoint x =
checkpoints := SMap.add !checkpoints ~key:x ~data:Relative_path.Set.empty
let retrieve_checkpoint x =
match SMap.find_opt !checkpoints x with
| Some files ->
Some
(List.map (Relative_path.Set.elements files) ~f:Relative_path.to_absolute)
| None -> None
let delete_checkpoint x =
match SMap.find_opt !checkpoints x with
| Some _ ->
checkpoints := SMap.remove !checkpoints x;
true
| None -> false |
OCaml | hhvm/hphp/hack/src/server/serverCheckUtils.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
open ServerEnv
open ServerLocalConfig
let get_naming_table_fallback_path genv : string option =
match genv.local_config.naming_sqlite_path with
| Some path as p ->
Hh_logger.log "Loading naming table path from config: %s" path;
p
| None ->
Hh_logger.log "No path set in config, using the loaded naming table";
None
(** [extend_defs_per_file_sequential defs_per_file naming_table additional_files]
extends [defs_per_file] file-to-defs table with definitions in [additional_files]
by querying [naming_table] for their definitions.
Does so sequentially file by file. *)
let extend_defs_per_file_sequential defs_per_file naming_table additional_files
=
Hh_logger.log "Extending file-to-defs table sequentially (in memory)...";
Relative_path.Set.fold
additional_files
~init:defs_per_file
~f:(fun path acc ->
match Relative_path.Map.find_opt defs_per_file path with
| None ->
(try
let info = Naming_table.get_file_info_unsafe naming_table path in
let info_names = FileInfo.simplify info in
Relative_path.Map.add acc ~key:path ~data:info_names
with
| Naming_table.File_info_not_found -> acc)
| Some _ -> acc)
(** [extend_defs_per_file_batch genv defs_per_file naming_table additional_files bucket_size]
extends [defs_per_file] file-to-defs table with definitions in [additional_files]
by querying [naming_table] for their definitions.
Does so in batches of size [bucket_size]. *)
let extend_defs_per_file_batch
genv defs_per_file naming_table additional_files bucket_size =
Hh_logger.log "Extending file-to-defs table in batch mode...";
let additional_files = Relative_path.Set.elements additional_files in
let get_one acc x =
try
let info = Naming_table.get_file_info_unsafe naming_table x in
let info_names = FileInfo.simplify info in
Relative_path.Map.add acc ~key:x ~data:info_names
with
| Naming_table.File_info_not_found -> acc
in
let job (acc : FileInfo.names Relative_path.Map.t) additional_files =
Core.(
let result = List.fold_left additional_files ~f:get_one ~init:acc in
result)
in
let next =
MultiWorker.next ~max_size:bucket_size genv.workers additional_files
in
let neutral = Relative_path.Map.empty in
let merge = Relative_path.Map.union in
let extended_defs_per_file =
MultiWorker.call genv.workers ~job ~neutral ~merge ~next
in
Relative_path.Map.union defs_per_file extended_defs_per_file
(** [extend_defs_per_file genv defs_per_file naming_table additional_files]
extends [defs_per_file] file-to-defs table with definitions in [additional_files]
by querying [naming_table] for their definitions.
Does so either sequentially or in batches depending on how many files to add. *)
let extend_defs_per_file
genv
(defs_per_file : FileInfo.names Relative_path.Map.t)
(naming_table : Naming_table.t)
(additional_files : Relative_path.Set.t) :
FileInfo.names Relative_path.Map.t =
let additional_count = Relative_path.Set.cardinal additional_files in
if additional_count = 0 then
defs_per_file
else (
Hh_logger.log
"Extending the file-to-defs table by %d additional files"
additional_count;
let t = Unix.gettimeofday () in
let bucket_size =
genv.local_config.ServerLocalConfig.extend_defs_per_file_bucket_size
in
let extended_defs_per_file =
match Naming_table.get_forward_naming_fallback_path naming_table with
| Some _sqlite_path when additional_count >= bucket_size ->
extend_defs_per_file_batch
genv
defs_per_file
naming_table
additional_files
bucket_size
| _ ->
extend_defs_per_file_sequential
defs_per_file
naming_table
additional_files
in
let _t = Hh_logger.log_duration "Extended file-to-defs table" t in
extended_defs_per_file
)
let global_typecheck_kind genv env =
if genv.ServerEnv.options |> ServerArgs.remote then
ServerCommandTypes.Remote_blocking "Forced remote type check"
else if env.can_interrupt then
ServerCommandTypes.Interruptible
else
ServerCommandTypes.Blocking
let get_check_info ~check_reason ~log_errors (genv : genv) env :
Typing_service_types.check_info =
{
Typing_service_types.init_id = env.init_env.init_id;
check_reason;
log_errors;
recheck_id = env.init_env.recheck_id;
use_max_typechecker_worker_memory_for_decl_deferral =
genv.local_config
.ServerLocalConfig.use_max_typechecker_worker_memory_for_decl_deferral;
per_file_profiling = genv.local_config.ServerLocalConfig.per_file_profiling;
memtrace_dir = genv.local_config.ServerLocalConfig.memtrace_dir;
}
type user_filter =
| UserFilterInclude of Str.regexp list
| UserFilterExclude of Str.regexp list
| UserFilterFiles of SSet.t
let user_filter_of_json (json : Hh_json.json) : user_filter =
let open Hh_json_helpers in
let json = Some json in
let type_ = Jget.string_exn json "type" in
if String.equal type_ "include" then
let regexes = Jget.string_array_exn json "regexes" in
let regexes =
List.map regexes ~f:(fun re ->
try Str.regexp re with
| Failure explanation ->
raise
@@ Failure
(Printf.sprintf
"Could not parse regex \"%s\": %s"
re
explanation))
in
UserFilterInclude regexes
else if String.equal type_ "exclude" then
let regexes = Jget.string_array_exn json "regexes" in
let regexes =
List.map regexes ~f:(fun re ->
try Str.regexp re with
| Failure explanation ->
raise
@@ Failure
(Printf.sprintf
"Could not parse regex \"%s\": %s"
re
explanation))
in
UserFilterExclude regexes
else if String.equal type_ "specific_files" then
let file_list = Jget.string_array_exn json "files" in
UserFilterFiles (SSet.of_list file_list)
else
raise @@ Failure (Printf.sprintf "Unknown filter type: '%s'" type_)
let user_filter_should_type_check
(user_filter : user_filter) (path : Relative_path.t) : bool =
let suffix = Relative_path.suffix path in
let matches_any regexes =
List.exists regexes ~f:(fun re ->
try Str.search_forward re suffix 0 >= 0 with
| Caml.Not_found -> false)
in
match user_filter with
| UserFilterInclude regexes -> matches_any regexes
| UserFilterExclude regexes -> not (matches_any regexes)
| UserFilterFiles files -> SSet.mem (Relative_path.suffix path) files
let user_filters_should_type_check
(user_filters : user_filter list) (path : Relative_path.t) : bool =
List.for_all user_filters ~f:(fun f -> user_filter_should_type_check f path)
let user_filter_type_check_files ~to_recheck ~reparsed ~is_ide_file =
Hh_logger.log "Filtering files to type check using user-defined predicates";
let config_file_path =
Sys_utils.expanduser "~/.hack_type_check_files_filter"
in
let read_config_file_once () : user_filter list =
let contents = Sys_utils.cat config_file_path in
let json = Hh_json.json_of_string contents in
let filters = Hh_json.get_array_exn json in
List.map filters ~f:user_filter_of_json
in
let rec read_config_file () : user_filter list =
Hh_logger.log "Reading in config file at %s" config_file_path;
try read_config_file_once () with
| e ->
ServerProgress.write
~include_in_logs:false
"error while applying user file filter, see logs to continue";
let e = Exception.wrap e in
Printf.fprintf stderr "%s" (Exception.to_string e);
Hh_logger.log
"An exception occurred while reading %s, retrying in 5s..."
config_file_path;
Sys_utils.sleep ~seconds:5.;
read_config_file ()
in
let filters = read_config_file () in
let to_recheck_original_count = Relative_path.Set.cardinal to_recheck in
let to_recheck =
Relative_path.Set.filter to_recheck ~f:(fun path ->
Relative_path.Set.mem reparsed path
|| is_ide_file path
|| user_filters_should_type_check filters path)
in
let passed_filter_count = Relative_path.Set.cardinal to_recheck in
Hh_logger.log
"Filtered files to recheck from %d to %d"
to_recheck_original_count
passed_filter_count;
to_recheck |
OCaml Interface | hhvm/hphp/hack/src/server/serverCheckUtils.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.
*
*)
val get_check_info :
check_reason:string ->
log_errors:bool ->
ServerEnv.genv ->
ServerEnv.env ->
Typing_service_types.check_info
val global_typecheck_kind :
ServerEnv.genv -> ServerEnv.env -> ServerCommandTypes.global_typecheck_kind
val user_filter_type_check_files :
to_recheck:Relative_path.Set.t ->
reparsed:Relative_path.Set.t ->
is_ide_file:(Relative_path.t -> bool) ->
Relative_path.Set.t
val get_naming_table_fallback_path : ServerEnv.genv -> string option
(** [extend_defs_per_file genv defs_per_file naming_table additional_files]
extends [defs_per_file] file-to-defs table with definitions in [additional_files]
by querying [naming_table] for their definitions. *)
val extend_defs_per_file :
ServerEnv.genv ->
FileInfo.names Relative_path.Map.t ->
Naming_table.t ->
Relative_path.Set.t ->
FileInfo.names Relative_path.Map.t |
OCaml | hhvm/hphp/hack/src/server/serverClientProvider.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open ServerCommandTypes
exception Client_went_away
type t = {
default_in_fd: Unix.file_descr;
(** Default pipe. Used for non time sensitive commands and IDE connections. *)
priority_in_fd: Unix.file_descr;
(** Priority pipe.
There's a handler for events happening on this pipe which will interrupt the typing service.
In practice this is used for commands that can be served immediately. *)
force_dormant_start_only_in_fd: Unix.file_descr;
(** Force formant start only pipe, used to perform the --force-dormant-start command. *)
}
type priority =
| Priority_high
| Priority_default
| Priority_dormant
type persistent_client = {
fd: Unix.file_descr;
mutable tracker: Connection_tracker.t;
}
type client =
| Non_persistent_client of {
ic: Timeout.in_channel;
oc: Out_channel.t;
priority: priority;
mutable tracker: Connection_tracker.t;
}
(** In practice this is hh_client. There can be multiple non-persistent clients. *)
| Persistent_client of persistent_client
(** In practice this is the IDE. There is only one persistent client. *)
type handoff = {
client: client;
m2s_sequence_number: int;
(** A unique number incremented for each client socket handoff from monitor to server.
Useful to correlate monitor and server logs. *)
}
type select_outcome =
| Select_persistent
| Select_new of handoff
| Select_nothing
| Select_exception of Exception.t
| Not_selecting_hg_updating
let provider_from_file_descriptors
(default_in_fd, priority_in_fd, force_dormant_start_only_in_fd) =
{ default_in_fd; priority_in_fd; force_dormant_start_only_in_fd }
let provider_for_test () = failwith "for use in tests only"
(** Retrieve channels to client from monitor process. *)
let accept_client
(priority : priority)
(parent_in_fd : Unix.file_descr)
(t_sleep_and_check : float)
(t_monitor_fd_ready : float) : handoff =
let ({ MonitorRpc.m2s_tracker = tracker; m2s_sequence_number }
: MonitorRpc.monitor_to_server_handoff_msg) =
Marshal_tools.from_fd_with_preamble parent_in_fd
in
let t_got_tracker = Unix.gettimeofday () in
Hh_logger.log
"[%s] got tracker #%d handoff from monitor"
(Connection_tracker.log_id tracker)
m2s_sequence_number;
let socket = Libancillary.ancil_recv_fd parent_in_fd in
let t_got_client_fd = Unix.gettimeofday () in
MonitorRpc.write_server_receipt_to_monitor_file
~server_receipt_to_monitor_file:
(ServerFiles.server_receipt_to_monitor_file (Unix.getpid ()))
~sequence_number_high_water_mark:m2s_sequence_number;
Hh_logger.log
"[%s] got FD#%d handoff from monitor"
(Connection_tracker.log_id tracker)
m2s_sequence_number;
let tracker =
let open Connection_tracker in
tracker
|> track ~key:Server_sleep_and_check ~time:t_sleep_and_check
|> track ~key:Server_monitor_fd_ready ~time:t_monitor_fd_ready
|> track ~key:Server_got_tracker ~time:t_got_tracker
|> track ~key:Server_got_client_fd ~time:t_got_client_fd
in
{
client =
Non_persistent_client
{
ic = Timeout.in_channel_of_descr socket;
oc = Unix.out_channel_of_descr socket;
priority;
tracker;
};
m2s_sequence_number;
}
let select ~idle_gc_slice fd_list timeout =
let deadline = Unix.gettimeofday () +. timeout in
match ServerIdleGc.select ~slice:idle_gc_slice ~timeout fd_list with
| [] ->
let timeout = Float.(max 0.0 (deadline -. Unix.gettimeofday ())) in
let (ready_fds, _, _) = Unix.select fd_list [] [] timeout in
ready_fds
| ready_fds -> ready_fds
(** Waits up to 0.1 seconds and checks for new connection attempts.
Select what client to serve next and call
retrieve channels to client from monitor process. *)
let sleep_and_check
({ default_in_fd; priority_in_fd; force_dormant_start_only_in_fd } : t)
(persistent_client_opt : client option)
~(ide_idle : bool)
~(idle_gc_slice : int)
(kind : [< `Any | `Force_dormant_start_only | `Priority ]) : select_outcome
=
let t_sleep_and_check = Unix.gettimeofday () in
let in_fds =
[default_in_fd; priority_in_fd; force_dormant_start_only_in_fd]
in
let fd_l =
match (kind, persistent_client_opt) with
| (`Force_dormant_start_only, _) -> [force_dormant_start_only_in_fd]
| (`Priority, _) -> [priority_in_fd]
| (`Any, Some (Persistent_client { fd; _ })) ->
(* If we are not sure that there are no more IDE commands, do not even
* look at non-persistent client to avoid race conditions. *)
if not ide_idle then
[fd]
else
fd :: in_fds
| (`Any, Some (Non_persistent_client _)) ->
(* The arguments for "sleep_and_check" are "the source of new clients"
* and the "client we already store in the env". We only store
* persistent clients *)
assert false
| (`Any, None) -> in_fds
in
let ready_fd_l = select ~idle_gc_slice fd_l 0.1 in
let t_monitor_fd_ready = Unix.gettimeofday () in
(* Prioritize existing persistent client requests over command line ones *)
let is_persistent fd =
match persistent_client_opt with
| Some (Persistent_client { fd = x; _ }) -> Poly.equal fd x
| _ -> false
in
try
if List.exists ready_fd_l ~f:is_persistent then
Select_persistent
else if List.mem ~equal:Poly.( = ) ready_fd_l priority_in_fd then
Select_new
(accept_client
Priority_high
priority_in_fd
t_sleep_and_check
t_monitor_fd_ready)
else if List.mem ~equal:Poly.( = ) ready_fd_l default_in_fd then
Select_new
(accept_client
Priority_default
default_in_fd
t_sleep_and_check
t_monitor_fd_ready)
else if List.mem ~equal:Poly.( = ) ready_fd_l force_dormant_start_only_in_fd
then
Select_new
(accept_client
Priority_dormant
force_dormant_start_only_in_fd
t_sleep_and_check
t_monitor_fd_ready)
else if List.is_empty ready_fd_l then
Select_nothing
else
failwith "sleep_and_check got impossible fd"
with
| End_of_file as exn ->
let e = Exception.wrap exn in
HackEventLogger.get_client_channels_exception e;
Hh_logger.log "GET_CLIENT_CHANNELS_EXCEPTION End_of_file. Terminating.";
Exit.exit Exit_status.Server_got_eof_from_monitor
| exn ->
let e = Exception.wrap exn in
HackEventLogger.get_client_channels_exception e;
Hh_logger.log
"GET_CLIENT_CHANNELS_EXCEPTION(%s). Ignoring."
(Exception.get_ctor_string e);
Unix.sleepf 0.5;
Select_exception e
let has_persistent_connection_request = function
| Persistent_client { fd; _ } ->
let (ready, _, _) = Unix.select [fd] [] [] 0.0 in
not (List.is_empty ready)
| _ -> false
let priority_fd { priority_in_fd; _ } = Some priority_in_fd
let get_client_fd = function
| Persistent_client { fd; _ } -> Some fd
| Non_persistent_client _ -> failwith "not implemented"
let track ~key ?time ?log ?msg ?long_delay_okay client =
match client with
| Persistent_client client ->
client.tracker <-
Connection_tracker.track
client.tracker
~key
?time
?log
?msg
?long_delay_okay
| Non_persistent_client client ->
client.tracker <-
Connection_tracker.track
client.tracker
~key
?time
?log
?msg
?long_delay_okay
let say_hello oc =
let fd = Unix.descr_of_out_channel oc in
let (_ : int) =
Marshal_tools.to_fd_with_preamble fd ServerCommandTypes.Hello
in
()
let read_connection_type_from_channel (ic : Timeout.in_channel) :
connection_type =
Timeout.with_timeout
~timeout:1
~on_timeout:(fun _ -> raise Read_command_timeout)
~do_:(fun timeout ->
let connection_type : connection_type = Timeout.input_value ~timeout ic in
connection_type)
(* Warning 52 warns about using Sys_error. Here we have no alternative but to depend on Sys_error strings *)
[@@@warning "-52"]
let read_connection_type (client : client) : connection_type =
match client with
| Non_persistent_client client -> begin
try
say_hello client.oc;
client.tracker <-
Connection_tracker.(track client.tracker ~key:Server_sent_hello);
let connection_type : connection_type =
read_connection_type_from_channel client.ic
in
client.tracker <-
Connection_tracker.(
track client.tracker ~key:Server_got_connection_type);
connection_type
with
| Sys_error "Connection reset by peer"
| Unix.Unix_error (Unix.EPIPE, "write", _) ->
raise Client_went_away
end
| Persistent_client _ ->
(* Every client starts as Non_persistent_client, and after we read its
* desired connection type, can be turned into Persistent_client
* (via make_persistent). *)
assert false
(* CARE! scope of warning suppression should be only read_connection_type *)
[@@@warning "+52"]
let send_response_to_client client response =
let (fd, tracker) =
match client with
| Non_persistent_client { oc; tracker; _ } ->
(Unix.descr_of_out_channel oc, tracker)
| Persistent_client { fd; tracker; _ } -> (fd, tracker)
in
let (_ : int) =
Marshal_tools.to_fd_with_preamble
fd
(ServerCommandTypes.Response (response, tracker))
in
()
let send_push_message_to_client client response =
match client with
| Non_persistent_client _ ->
failwith "non-persistent clients don't expect push messages "
| Persistent_client { fd; _ } ->
(try
let (_ : int) =
Marshal_tools.to_fd_with_preamble fd (ServerCommandTypes.Push response)
in
()
with
| Unix.Unix_error (Unix.EPIPE, "write", "") -> raise Client_went_away)
let read_client_msg ic =
try
Timeout.with_timeout
~timeout:1
~on_timeout:(fun _ -> raise Read_command_timeout)
~do_:(fun timeout -> Timeout.input_value ~timeout ic)
with
| End_of_file -> raise Client_went_away
let client_has_message = function
| Non_persistent_client _ -> true
| Persistent_client { fd; _ } ->
let (ready, _, _) = Unix.select [fd] [] [] 0.0 in
not (List.is_empty ready)
let read_client_msg = function
| Non_persistent_client { ic; _ } -> read_client_msg ic
| Persistent_client { fd; _ } ->
(* TODO: this is probably wrong, since for persistent client we'll
* construct a new input channel for each message, while the old one
* could have already buffered it *)
let ic = Timeout.in_channel_of_descr fd in
read_client_msg ic
let get_channels = function
| Non_persistent_client { ic; oc; _ } -> (ic, oc)
| Persistent_client _ ->
(* This function is used to "break" the module abstraction for some things
* we don't have mocking for yet, like STREAM and DEBUG request types. We
* have mocking for all the features of persistent clients, so this should
* never be hit *)
assert false
let make_persistent client =
match client with
| Non_persistent_client { ic; tracker; _ } ->
Persistent_client { fd = Timeout.descr_of_in_channel ic; tracker }
| Persistent_client _ ->
(* See comment on read_connection_type. Non_persistent_client can be
* turned into Persistent_client, but not the other way *)
assert false
let is_persistent = function
| Non_persistent_client _ -> false
| Persistent_client _ -> true
let priority_to_string (client : client) : string =
match client with
| Persistent_client _ -> "persistent"
| Non_persistent_client { priority = Priority_high; _ } -> "high"
| Non_persistent_client { priority = Priority_default; _ } -> "default"
| Non_persistent_client { priority = Priority_dormant; _ } -> "dormant"
let shutdown_client client =
let (ic, oc) =
match client with
| Non_persistent_client { ic; oc; _ } -> (ic, oc)
| Persistent_client { fd; _ } ->
(Timeout.in_channel_of_descr fd, Unix.out_channel_of_descr fd)
in
ServerUtils.shutdown_client (ic, oc)
let ping = function
| Non_persistent_client { oc; _ } ->
let fd = Unix.descr_of_out_channel oc in
let (_ : int) =
try Marshal_tools.to_fd_with_preamble fd ServerCommandTypes.Ping with
| _ -> raise Client_went_away
in
()
| Persistent_client _ -> () |
OCaml Interface | hhvm/hphp/hack/src/server/serverClientProvider.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.
*
*)
include ClientProvider_sig.S |
OCaml | hhvm/hphp/hack/src/server/serverCollectTastHoles.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 mk_result env pos ty_actual ty_expected =
TastHolesService.(
Set.singleton
{
actual_ty_string = Tast_env.print_ty env ty_actual;
actual_ty_json =
Hh_json.json_to_string @@ Tast_env.ty_to_json env ty_actual;
expected_ty_string = Tast_env.print_ty env ty_expected;
expected_ty_json =
Hh_json.json_to_string @@ Tast_env.ty_to_json env ty_expected;
pos;
})
let filter_source hole_filter src =
match (hole_filter, src) with
| (ServerCommandTypes.Tast_hole.Any, _) -> true
| (ServerCommandTypes.Tast_hole.Typing, Aast.Typing) -> true
| (ServerCommandTypes.Tast_hole.Cast, Aast.(UnsafeCast _ | EnforcedCast _)) ->
true
| _ -> false
let visitor hole_filter =
object (self)
inherit [_] Tast_visitor.reduce as super
method private zero = TastHolesService.Set.empty
method private plus t1 t2 = TastHolesService.Set.union t1 t2
method! on_Hole env ((_, pos, _) as expr) from_ty to_ty src =
let acc = super#on_Hole env expr from_ty to_ty src in
if filter_source hole_filter src then
self#plus acc (mk_result env pos from_ty to_ty)
else
acc
end
let tast_holes ctx tast hole_src_opt =
TastHolesService.Set.elements ((visitor hole_src_opt)#go ctx tast)
let go_ctx
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(hole_filter : ServerCommandTypes.Tast_hole.filter) =
let { Tast_provider.Compute_tast.tast; _ } =
Tast_provider.compute_tast_quarantined ~ctx ~entry
in
tast_holes ctx tast.Tast_with_dynamic.under_normal_assumptions hole_filter |
OCaml Interface | hhvm/hphp/hack/src/server/serverCollectTastHoles.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 tast_holes :
Provider_context.t ->
Tast.program ->
ServerCommandTypes.Tast_hole.filter ->
TastHolesService.result
val go_ctx :
ctx:Provider_context.t ->
entry:Provider_context.entry ->
hole_filter:ServerCommandTypes.Tast_hole.filter ->
TastHolesService.result |
OCaml | hhvm/hphp/hack/src/server/serverCommand.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 Utils
open ServerCommandTypes
exception Nonfatal_rpc_exception of Exception.t * ServerEnv.env
(** Some client commands require full check to be run in order to update global
state that they depend on *)
let rpc_command_needs_full_check : type a. a t -> bool =
fun msg ->
match msg with
(* global error list is not updated during small checks *)
| STATUS _ -> true
| LIST_FILES_WITH_ERRORS
| REMOVE_DEAD_FIXMES _
| REMOVE_DEAD_UNSAFE_CASTS
| CODEMOD_SDT _ ->
true (* need same information as STATUS *)
| REWRITE_LAMBDA_PARAMETERS _ -> true
(* Finding references/implementations uses global dependency table *)
| FIND_REFS _ -> true
| GO_TO_IMPL _ -> true
| IDE_FIND_REFS_BY_SYMBOL _ -> true
| IDE_GO_TO_IMPL_BY_SYMBOL _ -> true
| METHOD_JUMP (_, _, find_children) -> find_children (* uses find refs *)
| SAVE_NAMING _ -> false
| SAVE_STATE _ -> true
(* Codebase-wide rename, uses find references *)
| RENAME _ -> true
| IDE_RENAME_BY_SYMBOL _ -> true
(* Same case as Ai commands *)
| CREATE_CHECKPOINT _ -> true
| RETRIEVE_CHECKPOINT _ -> true
| DELETE_CHECKPOINT _ -> true
| IN_MEMORY_DEP_TABLE_SIZE -> true
| NO_PRECHECKED_FILES -> true
| POPULATE_REMOTE_DECLS _ -> false
| STATS -> false
| DISCONNECT -> false
| STATUS_SINGLE _ -> false
| INFER_TYPE _ -> false
| INFER_TYPE_BATCH _ -> false
| INFER_TYPE_ERROR _ -> false
| IS_SUBTYPE _ -> false
| TAST_HOLES _ -> false
| TAST_HOLES_BATCH _ -> false
| IDE_HOVER _ -> false
| DOCBLOCK_AT _ -> false
| DOCBLOCK_FOR_SYMBOL _ -> false
| IDE_SIGNATURE_HELP _ -> false
| XHP_AUTOCOMPLETE_SNIPPET _ -> true
| IDENTIFY_FUNCTION _ -> false
| IDENTIFY_SYMBOL _ -> false
| METHOD_JUMP_BATCH _ -> false
| DUMP_SYMBOL_INFO _ -> false
| LINT _ -> false
| LINT_STDIN _ -> false
| LINT_ALL _ -> false
| FORMAT _ -> false
| DUMP_FULL_FIDELITY_PARSE _ -> false
| IDE_AUTOCOMPLETE _ -> false
| CODE_ACTION _ -> false
| CODE_ACTION_RESOLVE _ -> false
| OUTLINE _ -> false
| IDE_IDLE -> false
| RAGE -> false
| CST_SEARCH _ -> false
| SEARCH _ -> false
| OPEN_FILE _ -> false
| CLOSE_FILE _ -> false
| EDIT_FILE _ -> false
| FUN_DEPS_BATCH _ -> false
| DEPS_OUT_BATCH _ -> false
| FILE_DEPENDENTS _ -> true
| IDENTIFY_TYPES _ -> false
| EXTRACT_STANDALONE _ -> false
| CONCATENATE_ALL _ -> true
| GO_TO_DEFINITION _ -> false
| PREPARE_CALL_HIERARCHY _ -> false
| CALL_HIERARCHY_INCOMING_CALLS _ -> true
| CALL_HIERARCHY_OUTGOING_CALLS _ -> false
| PAUSE true -> false
(* when you unpause, then it will catch up *)
| PAUSE false -> true
| VERBOSE _ -> false
| DEPS_IN_BATCH _ -> true
let command_needs_full_check = function
| Rpc (_metadata, x) -> rpc_command_needs_full_check x
| Debug_DO_NOT_USE -> failwith "Debug_DO_NOT_USE"
let is_edit : type a. a command -> bool = function
| Rpc (_metadata, EDIT_FILE _) -> true
| _ -> false
let use_priority_pipe (type result) (command : result ServerCommandTypes.t) :
bool =
match command with
| _ when rpc_command_needs_full_check command -> false
| OPEN_FILE (path, _)
| EDIT_FILE (path, _)
| CLOSE_FILE path ->
HackEventLogger.invariant_violation_bug
"Asked whether to use priority-pipe for persistent-connection-only command"
~data:path;
false
| DISCONNECT ->
HackEventLogger.invariant_violation_bug
"Asked whether to use priority-pipe for persistent-connection-only command";
false
| _ -> true
let full_recheck_if_needed' genv env reason profiling =
if
ServerEnv.(is_full_check_done env.full_check_status)
&& Relative_path.Set.is_empty env.ServerEnv.ide_needs_parsing
then
env
else
let () = Hh_logger.log "Starting a blocking type-check due to %s" reason in
let start_time = Unix.gettimeofday () in
let env = { env with ServerEnv.can_interrupt = false } in
let (env, _res, _telemetry) =
ServerTypeCheck.(type_check genv env CheckKind.Full start_time profiling)
in
let env = { env with ServerEnv.can_interrupt = true } in
assert (ServerEnv.(is_full_check_done env.full_check_status));
env
let force_remote = function
| Rpc (_metadata, STATUS status) -> status.remote
| _ -> false
let ignore_ide = function
| Rpc (_metadata, STATUS status) -> status.ignore_ide
| _ -> false
let apply_changes env changes =
Relative_path.Map.fold changes ~init:env ~f:(fun path content env ->
ServerFileSync.open_file
~predeclare:false
env
(Relative_path.to_absolute path)
content)
let get_unsaved_changes env =
let changes = ServerFileSync.get_unsaved_changes env in
Relative_path.Map.(map ~f:fst changes, map ~f:snd changes)
let reason = ServerCommandTypesUtils.debug_describe_cmd
let full_recheck_if_needed genv env msg =
if ignore_ide msg then
let (ide, disk) = get_unsaved_changes env in
let env = apply_changes env disk in
let env =
CgroupProfiler.step_group "Full_check" ~log:true
@@ full_recheck_if_needed'
genv
{ env with ServerEnv.remote = force_remote msg }
(reason msg)
in
apply_changes env ide
else
env
(****************************************************************************)
(* Called by the server *)
(****************************************************************************)
(* Only grant access to dependency table to commands that declared that they
* need full check - without full check, there are no guarantees about
* dependency table being up to date. *)
let with_dependency_table_reads mode full_recheck_needed f =
let deptable_unlocked =
if full_recheck_needed then
Some (Typing_deps.allow_dependency_table_reads mode true)
else
None
in
try_finally ~f ~finally:(fun () ->
Option.iter deptable_unlocked ~f:(fun deptable_unlocked ->
ignore
(Typing_deps.allow_dependency_table_reads mode deptable_unlocked
: bool)))
(* Construct a continuation that will finish handling the command and update
* the environment. Server can execute the continuation immediately, or store it
* to be completed later (when full recheck is completed, when workers are
* available, when current recheck is cancelled... *)
let actually_handle genv client msg full_recheck_needed ~is_stale env =
Hh_logger.debug "SeverCommand.actually_handle preamble";
with_dependency_table_reads env.ServerEnv.deps_mode full_recheck_needed
@@ fun () ->
Errors.ignore_ @@ fun () ->
assert (
(not full_recheck_needed)
|| ServerEnv.(is_full_check_done env.full_check_status));
(* There might be additional rechecking required when there are unsaved IDE
* changes and we asked for an answer that requires ignoring those.
* This is very rare. *)
let env = full_recheck_if_needed genv env msg in
ClientProvider.track
client
~key:Connection_tracker.Server_done_full_recheck
~long_delay_okay:true;
match msg with
| Rpc (_, cmd) ->
ClientProvider.ping client;
let t_start = Unix.gettimeofday () in
ClientProvider.track
client
~key:Connection_tracker.Server_start_handle
~time:t_start;
Sys_utils.start_gc_profiling ();
Full_fidelity_parser_profiling.start_profiling ();
let (new_env, response) =
try ServerRpc.handle ~is_stale genv env cmd with
| exn ->
let e = Exception.wrap exn in
if ServerCommandTypes.is_critical_rpc cmd then
Exception.reraise e
else
raise (Nonfatal_rpc_exception (e, env))
in
let parsed_files = Full_fidelity_parser_profiling.stop_profiling () in
ClientProvider.track
client
~key:Connection_tracker.Server_end_handle
~log:true;
let (major_gc_time, minor_gc_time) = Sys_utils.get_gc_time () in
HackEventLogger.handled_command
(ServerCommandTypesUtils.debug_describe_t cmd)
~start_t:t_start
~major_gc_time
~minor_gc_time
~parsed_files;
ClientProvider.send_response_to_client client response;
if
ServerCommandTypes.is_disconnect_rpc cmd
|| (not @@ ClientProvider.is_persistent client)
then
ClientProvider.shutdown_client client;
new_env
| Debug_DO_NOT_USE -> failwith "Debug_DO_NOT_USE"
let handle
(genv : ServerEnv.genv)
(env : ServerEnv.env)
(client : ClientProvider.client) :
ServerEnv.env ServerUtils.handle_command_result =
(* In the case if LSP, it's normal that this [Server_waiting_for_cmd]
track happens on a per-message basis, much later than the previous
[Server_got_connection_type] track that happened when the persistent
connection was established; the flag [long_delay_okay]
means that the default behavior, of alarming log messages in case of delays,
will be suppressed. *)
ClientProvider.track
client
~key:Connection_tracker.Server_waiting_for_cmd
~long_delay_okay:(ClientProvider.is_persistent client);
let msg = ClientProvider.read_client_msg client in
(* This is a helper to update progress.json to things like "[hh_client:idle done]" or "[HackAst:--type-at-pos check]"
or "[HackAst:--type-at-pos]". We try to balance something useful to the user, with something that helps the hack
team know what's going on and who is to blame.
The form is [FROM:CMD PHASE].
FROM is the --from argument passed at the command-line, or "hh_client" in case of LSP requests.
CMD is the "--type-at-pos" or similar command-line argument that gave rise to serverRpc, or something sensible for LSP.
PHASE is empty at the start, "done" once we've finished handling, "write" if Needs_writes, "check" if Needs_full_recheck. *)
let send_progress phase =
ServerProgress.write
~include_in_logs:false
"%s%s"
(ServerCommandTypesUtils.status_describe_cmd msg)
phase
in
(* Once again, it's expected that [Server_got_cmd] happens a long time
after we started waiting for one! *)
ClientProvider.track
client
~key:Connection_tracker.Server_got_cmd
~log:true
~msg:
(Printf.sprintf
"%s [%s]"
(ServerCommandTypesUtils.debug_describe_cmd msg)
(ClientProvider.priority_to_string client))
~long_delay_okay:(ClientProvider.is_persistent client);
let env = { env with ServerEnv.remote = force_remote msg } in
let full_recheck_needed = command_needs_full_check msg in
let is_stale =
ServerEnv.(env.last_recheck_loop_stats.RecheckLoopStats.updates_stale)
in
let handle_command =
send_progress "";
let r = actually_handle genv client msg full_recheck_needed ~is_stale in
send_progress " done";
r
in
(* The sense of [command_needs_writes] is a little confusing.
Recall that for editor_open_files, hh_server deems that the IDE is the
source of truth for the contents of those files. Thus, the act of
opening/closing/editing an IDE file is equivalent to altering ("writing")
the content of the file.
With these IDE actions, in order to avoid races, we will have the
current typecheck stop [MultiThreadedCall.Cancel] before processing
the open/edit/close command. That way, in case the current typecheck
had previously read one version of the file contents, we'll be sure that
the same typecheck won't read the new version of the file contents.
Note that "cancel" in this context means cancel remaining fanout-typechecking
work in the current round of [ServerTypeCheck.type_check], but don't throw
away results from the files we've already typechecked; as soon as we've
cancelled and handled this command, then continue on to the next round
of [ServerTypeCheck.type_check] i.e. recalculate naming table and fanout
and then typecheck this new fanout.
(It's interesting to compare these to watchman, which does have races...
all that watchman allows us is to get a notification *after the fact* that
the file content has changed. The typecheck still gets cancelled, but it
might have read conflicting file contents prior to cancellation.) *)
let command_needs_writes (type a) (msg : a command) : bool =
match msg with
| Debug_DO_NOT_USE -> failwith "Debug_DO_NOT_USE"
| Rpc (_metadata, OPEN_FILE (path, ide_content)) ->
(* If the [ide_content] we're about to open is the same as what might have
previously been read from disk in the current typecheck (i.e. the typical case),
then this command won't end up altering file content and doesn't need to cancel
the current typecheck. (Why might they ever be different? Well, it's up to
VSCode what content it picks when the user opens a file. It'd be weird but
permissable say for VSCode to replace newlines upon open. *)
let disk_content = ServerFileSync.get_file_content_from_disk path in
let is_content_changed = not (String.equal ide_content disk_content) in
Hh_logger.log "OPEN_FILE is_content_changed? %b" is_content_changed;
is_content_changed
| Rpc (_metadata, EDIT_FILE _) ->
(* If the user is editing a file, it will necessary change file content,
and hence will necessarily cancel the current typecheck. Also we want
it to cancel the current typecheck so we can start a new Lazy_check
and get out squiggles for the just-edited file as soon as possible. *)
true
| Rpc (_metadata, CLOSE_FILE path) ->
(* If the [ide_content] we're closing is the same as what might be read
from disk in the current typecheck, then this command won't end up altering
file content and doesn't need to cancel the current typecheck.
The [ide_content] is necessarily what's in the File_provider for this path.
(Why might they ever be different? Well, if there were unsaved modifications
then the will be different.) *)
let ide_content =
ServerFileSync.get_file_content (ServerCommandTypes.FileName path)
in
let disk_content = ServerFileSync.get_file_content_from_disk path in
let is_content_changed = not (String.equal ide_content disk_content) in
Hh_logger.log "CLOSE_FILE is_content_changed? %b" is_content_changed;
is_content_changed
| Rpc (_metadata, DISCONNECT) ->
(* DISCONNECT involves CLOSE-ing all previously opened files.
We could be fancy and use the same logic as [CLOSE_FILE] above, but it's
not worth it; we're okay with cancelling the current typecheck in this
rare case. *)
true
| Rpc (_metadata, _) -> false
in
if command_needs_writes msg then begin
send_progress " write";
ServerUtils.Needs_writes
{
env;
finish_command_handling = handle_command;
recheck_restart_is_needed = not (is_edit msg);
(* What is [recheck_restart_is_needed] for? ...
IDE edits can come in quick succession and be immediately followed
by time sensitivie queries (like autocomplete). There is a constant cost
to stopping and resuming the global typechecking jobs, which leads to
flaky experience. Here we set the flag [recheck_restart_is_needed] to [false] for
Edit, meaning that after we've finished handling the edit then
[ServerMain.persistent_client_interrupt_handler] will stop the natural
full check from taking place (by setting [env.full_check_status = Full_check_needed]).
The flag only has effect in the "false" direction which stops the full check
from taking place; setting it to "true" won't force an already-stopped full check to resume.
So what does cause a full check to resume? There are two heuristics, both of them crummy,
aimed at making a decentishuser experience where (1) we don't resume so aggressively
that we pay the heavy cost of starting+stopping, (2) the user is rarely too perplexed
at why things don't seem to be proceeding.
* In [ServerMain.watchman_interrupt_handler], if a file on disk is modified, then
the typecheck will resume.
* In [ServerMain.recheck_until_no_changes_left], if it's been 5.0s or more since the last Edit,
then the typecheck will resume. *)
reason = ServerCommandTypesUtils.debug_describe_cmd msg;
}
end else if full_recheck_needed then begin
send_progress " typechecking";
ServerUtils.Needs_full_recheck
{ env; finish_command_handling = handle_command; reason = reason msg }
end else
ServerUtils.Done (handle_command env) |
OCaml Interface | hhvm/hphp/hack/src/server/serverCommand.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.
*
*)
exception Nonfatal_rpc_exception of Exception.t * ServerEnv.env
(** The priority pipe is only for "read-only" commands.
Invariant (checked in [ServerMain.priority_client_interrupt_handler]):
if a command uses the priority pipe, then [handle] will only
ever return [Done]. *)
val use_priority_pipe : 'result ServerCommandTypes.t -> bool
(** Handle a client command. This can either execute the command immediately,
or store it as a continuation to be completed later
(when full recheck is completed, when workers are available,
when current recheck is cancelled...).
Invariant (checked in [ServerMain.priority_client_interrupt_handler]):
if this returns anything other than [Done], then [use_priority_pipe]
must have returned false for the command we fetch from the client to handle. *)
val handle :
ServerEnv.genv ->
ServerEnv.env ->
ClientProvider.client ->
ServerEnv.env ServerUtils.handle_command_result |
OCaml | hhvm/hphp/hack/src/server/serverCommandLwt.ml | open Hh_prelude
open ServerCommandTypes
exception Remote_fatal_exception of Marshal_tools.remote_exception_data
exception Remote_nonfatal_exception of Marshal_tools.remote_exception_data
let rec wait_for_rpc_response stack fd state callback =
try%lwt
let%lwt message = Marshal_tools_lwt.from_fd_with_preamble fd in
match message with
| Response (r, tracker) -> Lwt.return (Ok (state, r, tracker))
| Push (ServerCommandTypes.FATAL_EXCEPTION remote_e_data) ->
Lwt.return (Error (state, stack, Remote_fatal_exception remote_e_data))
| Push (ServerCommandTypes.NONFATAL_EXCEPTION remote_e_data) ->
Lwt.return (Error (state, stack, Remote_nonfatal_exception remote_e_data))
| Push m ->
let state = callback state m in
let%lwt response = wait_for_rpc_response stack fd state callback in
Lwt.return response
| Hello ->
Lwt.return (Error (state, stack, Failure "unexpected second hello"))
| Ping ->
Lwt.return
(Error (state, stack, Failure "unexpected ping on persistent connection"))
| Monitor_failed_to_handoff ->
Lwt.return
(Error
( state,
stack,
Failure
"unexpected monitor_failed_to_handoff on persistent connection"
))
with
| e -> Lwt.return (Error (state, stack, e))
(** Sends a message over the given `out_channel`, then listens for incoming
messages - either an exception which it raises, or a push which it dispatches
via the supplied callback, or a response which it returns.
Note: although this function returns a promise, it is not safe to call this
function multiple times in parallel, since they are writing to the same output
channel, and the server is not equipped to serve parallel requests anyways. *)
let rpc_persistent :
type a s.
Timeout.in_channel * Out_channel.t ->
s ->
(s -> push -> s) ->
desc:string ->
a t ->
(s * a * Connection_tracker.t, s * Utils.callstack * exn) result Lwt.t =
fun (_, oc) state callback ~desc cmd ->
let stack =
Caml.Printexc.get_callstack 100 |> Caml.Printexc.raw_backtrace_to_string
in
let stack = Utils.Callstack stack in
try%lwt
let fd = Unix.descr_of_out_channel oc in
let oc = Lwt_io.of_unix_fd fd ~mode:Lwt_io.Output in
let metadata = { ServerCommandTypes.from = "IDE"; desc } in
let buffer = Marshal.to_string (Rpc (metadata, cmd)) [] in
let%lwt () = Lwt_io.write oc buffer in
let%lwt () = Lwt_io.flush oc in
let%lwt response =
wait_for_rpc_response
stack
(Lwt_unix.of_unix_file_descr fd)
state
callback
in
Lwt.return response
with
| e -> Lwt.return (Error (state, stack, e))
let send_connection_type oc t =
Marshal.to_channel oc t [];
Out_channel.flush oc |
OCaml Interface | hhvm/hphp/hack/src/server/serverCommandLwt.mli | (****************************************************************************)
(* Called by the client *)
(****************************************************************************)
exception Remote_fatal_exception of Marshal_tools.remote_exception_data
exception Remote_nonfatal_exception of Marshal_tools.remote_exception_data
val rpc_persistent :
Timeout.in_channel * Core.Out_channel.t ->
's ->
('s -> ServerCommandTypes.push -> 's) ->
desc:string ->
'a ServerCommandTypes.t ->
('s * 'a * Connection_tracker.t, 's * Utils.callstack * exn) result Lwt.t
val send_connection_type : out_channel -> 'a -> unit |
OCaml | hhvm/hphp/hack/src/server/serverCommandTypes.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
open Ide_api_types
type connection_type =
| Persistent
| Non_persistent
type connection_response = Connected
type status_liveness =
| Stale_status
| Live_status
module Server_status = struct
type t = {
liveness: status_liveness;
has_unsaved_changes: bool;
error_list: Errors.finalized_error list;
dropped_count: int;
last_recheck_stats: Telemetry.t option;
}
end
module Identify_symbol = struct
type single_result =
string SymbolOccurrence.t * string SymbolDefinition.t option
type result = single_result list
end
module Method_jumps = struct
type result = {
orig_name: string;
orig_pos: Pos.absolute;
dest_name: string;
dest_pos: Pos.absolute;
orig_p_name: string;
(* Used for methods to find their parent class *)
dest_p_name: string;
}
type filter =
| No_filter
| Class
| Interface
| Trait
[@@deriving show]
let readable_place name pos p_name =
let readable = Pos.string pos in
if String.length p_name <> 0 then
readable ^ " " ^ Utils.strip_ns p_name ^ "::" ^ Utils.strip_ns name
else
readable ^ " " ^ Utils.strip_ns name
let print_readable res ~find_children =
List.iter res ~f:(fun res ->
let origin_readable =
readable_place res.orig_name res.orig_pos res.orig_p_name
in
let dest_readable =
readable_place res.dest_name res.dest_pos res.dest_p_name
in
let extended =
"inherited "
^
if find_children then
"by"
else
"from"
in
print_endline
(origin_readable ^ "\n " ^ extended ^ " " ^ dest_readable));
()
end
module Done_or_retry = struct
(* This is an ugly hack to support following case:
* - client issues a command that requires full recheck. Server knows not to
* accept it until full check is completed .
* - while processing the command, it turns out that we need to recheck even
* more files for full check to be "good enough" for this command
* This can happen when combining prechecked files and find references.
* We could store the client with its command somwhere, and come back to it
* after this additional rechecking is done, but in practice this is ugly to
* implement in current atchitecture. What is easier to do instead, is to
* return a special "Retry" response to the client, which will cause it to
* re-issue the same request (which will once again not be accepted until full
* check is completed. Since command is the same, its second execution should
* not add even more files to recheck, hence a limit of only two attempts.
*
* In other words: the goal of this is to avoid implementing even more
* server-side client queing mechanisms, but re-use an existing "clients waiting
* for full check" queue. *)
exception Two_retries_in_a_row
type 'a t =
| Done of 'a
| Retry
(* Note: this is designed to work with calls that always will succeed on second try
* (the reason for retrying is a one time event that is resolved during first call).
* If this ends up throwing, it's a bug in hh_server. *)
let rec call ~(f : unit -> 'a t Lwt.t) ~(depth : int) : _ Lwt.t =
Lwt.Infix.(
(if depth = 2 then
Lwt.fail Two_retries_in_a_row
else
Lwt.return_unit)
>>= fun () ->
f () >>= fun result ->
match result with
| Done x -> Lwt.return x
| Retry -> call ~f ~depth:(depth + 1))
(* Call the function returning Done_or_retry.t with at most one retry, expecting
* that this is enough to yield a non-Retry value, which is returned *)
let call ~(f : unit -> 'a t Lwt.t) : _ Lwt.t = call ~f ~depth:0
(* Helper function useful when mapping over results from functions that (in addition
* to Done_or_retry.t result) thread through some kind of environment. *)
let map_env ~(f : 'a -> 'b) ((env, x) : 'env * 'a t) : 'env * 'b t =
match x with
| Done x -> (env, Done (f x))
| Retry -> (env, Retry)
end
module Find_refs = struct
include SearchTypes.Find_refs
type server_result = (string * Pos.t) list
type result = (string * Pos.absolute) list
type server_result_or_retry = server_result Done_or_retry.t
type result_or_retry = result Done_or_retry.t
end
module Rename = struct
type ide_result = (ServerRenameTypes.patch list, string) result
type result = ServerRenameTypes.patch list
type ide_result_or_retry = ide_result Done_or_retry.t
type result_or_retry = result Done_or_retry.t
(** Returns a string in the form of
* NEW_NAME|COMMA_SEPARATED_FIND_REFS_ACTION|OCaml_marshalled_SymbolDefinition.T
*)
let arguments_to_string_exn
(new_name : string)
(action : Find_refs.action)
(symbol_def : Relative_path.t SymbolDefinition.t) : string =
let symbol_and_action =
FindRefsWireFormat.CliArgs.to_string
{
FindRefsWireFormat.CliArgs.symbol_name = new_name;
action;
stream_file = None;
hint_suffixes = [];
}
in
let marshalled_def = Marshal.to_string symbol_def [] in
let encoded = Base64.encode_exn marshalled_def in
Printf.sprintf "%s|%s" symbol_and_action encoded
(** Expects a string in the form of
* NEW_NAME|COMMA_SEPARATED_FIND_REFS_ACTION|OCaml_marshalled_SymbolDefinition.T
* For example, a valid entry is
* HackTypecheckerQueryBase::WWWDir|Member,\HackTypecheckerQueryBase,Method,getWWWDir|<byte_string>
*)
let string_to_args arg :
string * Find_refs.action * Relative_path.t SymbolDefinition.t =
let split_arg = Str.split (Str.regexp "|") arg in
let (symbol_name, action_arg, marshalled_def) =
match split_arg with
| [symbol_name; action_arg; marshalled_def] ->
(symbol_name, action_arg, marshalled_def)
| _ ->
Printf.eprintf "Invalid input\n";
raise Exit_status.(Exit_with Input_error)
in
let str = Printf.sprintf "%s|%s" symbol_name action_arg in
let { FindRefsWireFormat.CliArgs.symbol_name = new_name; action; _ } =
FindRefsWireFormat.CliArgs.from_string_exn str
in
let decoded_str = Base64.decode_exn marshalled_def in
let symbol_definition : Relative_path.t SymbolDefinition.t =
Marshal.from_string decoded_str 0
in
(new_name, action, symbol_definition)
end
module Symbol_type = struct
type t = {
pos: string Pos.pos;
type_: string;
ident_: int;
}
[@@deriving show]
end
module Symbol_info_service = struct
type target_type =
| Function
| Method
| Constructor
[@@deriving ord, show]
type symbol_fun_call = {
name: string;
type_: target_type;
pos: string Pos.pos;
caller: string;
}
[@@deriving show]
type result = {
fun_calls: symbol_fun_call list;
symbol_types: Symbol_type.t list;
}
let fun_call_to_json fun_call_results =
let open Hh_json in
List.map fun_call_results ~f:(fun item ->
let item_type =
match item.type_ with
| Function -> "Function"
| Method -> "Method"
| Constructor -> "Constructor"
in
JSON_Object
[
("name", JSON_String item.name);
("type", JSON_String item_type);
("pos", Pos.json item.pos);
("caller", JSON_String item.caller);
])
let symbol_type_to_json symbol_type_results =
let open Hh_json in
Symbol_type.(
List.rev_map symbol_type_results ~f:(fun item ->
JSON_Object
[
("pos", Pos.json item.pos);
("type", JSON_String item.type_);
("ident", int_ item.ident_);
]))
let to_json result =
let open Hh_json in
let fun_call_json = fun_call_to_json result.fun_calls in
let symbol_type_json = symbol_type_to_json result.symbol_types in
JSON_Object
[
("function_calls", JSON_Array fun_call_json);
("symbol_types", JSON_Array symbol_type_json);
]
end
module Outline = struct
type outline = string SymbolDefinition.t list
end
module Infer_return_type = struct
type t =
| Function of string
| Method of string * string
type result = (string, string) Stdlib.result
end
module Ide_rename_type = struct
type t = {
filename: Relative_path.t;
line: int;
char: int;
new_name: string;
}
[@@deriving show]
end
module Go_to_definition = struct
type result = (string SymbolOccurrence.t * string SymbolDefinition.t) list
end
module Go_to_type_definition = struct
type result = (Pos.absolute * string) list
end
module Extract_standalone = struct
type target =
| Function of string
| Method of string * string
[@@deriving show]
end
module Tast_hole = struct
type filter =
| Typing
| Cast
| Any
[@@deriving show]
end
type file_input =
| FileName of string
| FileContent of string
[@@deriving show]
type labelled_file =
| LabelledFileName of string
| LabelledFileContent of {
filename: string;
content: string;
}
[@@deriving show]
type lint_stdin_input = {
filename: string;
contents: string;
}
[@@deriving show]
type cst_search_input = {
sort_results: bool;
input: Hh_json.json;
files_to_search: string list option; (* if None, search all files *)
}
[@@deriving show]
(* The following datatypes can be interpreted as follows:
* MESSAGE_TAG : Argument type (sent from client to server) -> return type t *)
type _ t =
| STATUS : {
ignore_ide: bool;
remote: bool;
max_errors: int option;
}
-> Server_status.t t
| STATUS_SINGLE : {
file_names: file_input list;
max_errors: int option;
}
-> (Errors.finalized_error list * int) t
| INFER_TYPE : file_input * int * int -> InferAtPosService.result t
| INFER_TYPE_BATCH :
(string * int * int * (int * int) option) list
-> string list t
| INFER_TYPE_ERROR : file_input * int * int -> InferErrorAtPosService.result t
| IS_SUBTYPE : string -> (string, string) result t
| TAST_HOLES : file_input * Tast_hole.filter -> TastHolesService.result t
| TAST_HOLES_BATCH : string list -> TastHolesService.result t
| IDE_HOVER : string * int * int -> HoverService.result t
| DOCBLOCK_AT :
(string * int * int * string option * SearchTypes.si_kind)
-> DocblockService.result t
| DOCBLOCK_FOR_SYMBOL :
(string * SearchTypes.si_kind)
-> DocblockService.result t
| IDE_SIGNATURE_HELP : (string * int * int) -> Lsp.SignatureHelp.result t
| XHP_AUTOCOMPLETE_SNIPPET : string -> string option t
| IDENTIFY_SYMBOL : string -> string SymbolDefinition.t list t
| IDENTIFY_FUNCTION :
string * file_input * int * int
-> Identify_symbol.result t
| METHOD_JUMP :
(string * Method_jumps.filter * bool)
-> Method_jumps.result list t
| METHOD_JUMP_BATCH :
(string list * Method_jumps.filter)
-> Method_jumps.result list t
| FIND_REFS : Find_refs.action -> Find_refs.result_or_retry t
| GO_TO_IMPL : Find_refs.action -> Find_refs.result_or_retry t
| IDE_FIND_REFS_BY_SYMBOL :
FindRefsWireFormat.CliArgs.t
-> Find_refs.result_or_retry t
| IDE_GO_TO_IMPL_BY_SYMBOL :
FindRefsWireFormat.CliArgs.t
-> Find_refs.result_or_retry t
| RENAME : ServerRenameTypes.action -> Rename.result_or_retry t
| IDE_RENAME_BY_SYMBOL :
Find_refs.action * string * Relative_path.t SymbolDefinition.t
-> Rename.ide_result_or_retry t
| CODEMOD_SDT :
string
-> (ServerRenameTypes.patch list
* string list
* [ `ClassLike | `Function ])
t
| DUMP_SYMBOL_INFO : string list -> Symbol_info_service.result t
| REMOVE_DEAD_FIXMES :
int list
-> [ `Ok of ServerRenameTypes.patch list | `Error of string ] t
| REMOVE_DEAD_UNSAFE_CASTS
: [ `Ok of ServerRenameTypes.patch list | `Error of string ] t
| REWRITE_LAMBDA_PARAMETERS : string list -> ServerRenameTypes.patch list t
| IN_MEMORY_DEP_TABLE_SIZE : (int, string) Stdlib.result t
| SAVE_NAMING :
string
-> (SaveStateServiceTypes.save_naming_result, string) Stdlib.result t
| SAVE_STATE :
(string * bool)
-> (SaveStateServiceTypes.save_state_result, string) Stdlib.result t
| SEARCH : string * string -> SearchUtils.result t
| LINT : string list -> ServerLintTypes.result t
| LINT_STDIN : lint_stdin_input -> ServerLintTypes.result t
| LINT_ALL : int -> ServerLintTypes.result t
| CREATE_CHECKPOINT : string -> unit t
| RETRIEVE_CHECKPOINT : string -> string list option t
| DELETE_CHECKPOINT : string -> bool t
| STATS : Stats.t t
| FORMAT : ServerFormatTypes.action -> ServerFormatTypes.result t
| DUMP_FULL_FIDELITY_PARSE : string -> string t
| OPEN_FILE : string * string -> unit t
| CLOSE_FILE : string -> unit t
| EDIT_FILE : string * text_edit list -> unit t
| IDE_AUTOCOMPLETE :
string * position * bool
-> AutocompleteTypes.ide_result t
| CODE_ACTION : {
path: string;
range: range;
}
-> Lsp.CodeAction.command_or_action list t
| CODE_ACTION_RESOLVE : {
path: string;
range: range;
resolve_title: string;
use_snippet_edits: bool;
}
-> Lsp.CodeActionResolve.result t
| DISCONNECT : unit t
| OUTLINE : string -> Outline.outline t
| IDE_IDLE : unit t
| RAGE : ServerRageTypes.result t
| CST_SEARCH : cst_search_input -> (Hh_json.json, string) result t
| NO_PRECHECKED_FILES : unit t
| POPULATE_REMOTE_DECLS : Relative_path.t list option -> unit t
| FUN_DEPS_BATCH : (string * int * int) list -> string list t
| LIST_FILES_WITH_ERRORS : string list t
| FILE_DEPENDENTS : string list -> string list t
| IDENTIFY_TYPES : labelled_file * int * int -> (Pos.absolute * string) list t
| EXTRACT_STANDALONE : Extract_standalone.target -> string t
| CONCATENATE_ALL : string list -> string t
| GO_TO_DEFINITION : labelled_file * int * int -> Go_to_definition.result t
| PREPARE_CALL_HIERARCHY :
labelled_file * int * int
-> Lsp.PrepareCallHierarchy.result t
| CALL_HIERARCHY_INCOMING_CALLS :
Lsp.CallHierarchyItem.t
-> Lsp.CallHierarchyIncomingCalls.callHierarchyIncomingCall list
Done_or_retry.t
list
t
| CALL_HIERARCHY_OUTGOING_CALLS :
Lsp.CallHierarchyItem.t
-> Lsp.CallHierarchyOutgoingCalls.result t
| PAUSE : bool -> unit t
| VERBOSE : bool -> unit t
| DEPS_OUT_BATCH : (string * int * int) list -> string list t
| DEPS_IN_BATCH :
(string * int * int) list
-> Find_refs.result_or_retry list t
type cmd_metadata = {
from: string;
(* a short human-readable string, used in "hh_server is busy [desc]" *)
desc: string;
}
let is_disconnect_rpc : type a. a t -> bool = function
| DISCONNECT -> true
| _ -> false
let is_critical_rpc : type a. a t -> bool = function
(* An exception during any critical rpc should shutdown the persistent connection. *)
(* The critical ones are those that affect the state. *)
| DISCONNECT -> true
| CREATE_CHECKPOINT _ -> true
| DELETE_CHECKPOINT _ -> true
| OPEN_FILE _ -> true
| CLOSE_FILE _ -> true
| EDIT_FILE _ -> true
| _ -> false
let is_idle_rpc : type a. a t -> bool = function
| IDE_IDLE -> true
| _ -> false
type 'a command =
| Rpc of cmd_metadata * 'a t
| Debug_DO_NOT_USE
(** this unused constructor is part of the binary protocol
between client and server; removing it would alter the protocol. *)
and streamed =
| SHOW of string
| LIST_MODES
type errors = Errors.finalized_error list [@@deriving show]
let equal_errors errors1 errors2 =
let errors1 = Errors.FinalizedErrorSet.of_list errors1 in
let errors2 = Errors.FinalizedErrorSet.of_list errors2 in
Errors.FinalizedErrorSet.equal errors1 errors2
type diagnostic_errors = errors SMap.t [@@deriving eq, show]
type push =
| DIAGNOSTIC of {
errors: diagnostic_errors;
is_truncated: int option;
(** Whether the list of errors has been truncated
to preserve IDE perf. *)
}
| BUSY_STATUS of busy_status
| NEW_CLIENT_CONNECTED
| FATAL_EXCEPTION of (Marshal_tools.remote_exception_data[@opaque])
| NONFATAL_EXCEPTION of (Marshal_tools.remote_exception_data[@opaque])
and busy_status =
| Needs_local_typecheck
| Doing_local_typecheck
| Done_local_typecheck
| Doing_global_typecheck of global_typecheck_kind
| Done_global_typecheck
and global_typecheck_kind =
| Blocking
| Interruptible
| Remote_blocking of string
[@@deriving eq, show]
type pushes = push list [@@deriving eq, show]
type 'a message_type =
| Hello
(** Hello is the first message sent to the client by the server, for both persistent and non-persistent *)
| Monitor_failed_to_handoff
(** However, if the handoff failed, this will be sent instead of Hello, and the connection terminated. *)
| Ping
(** Server sometimes sends these, after Hello and before Response, to check if client fd is still open *)
| Response of 'a * Connection_tracker.t
(** Response message is the response to an RPC. For non-persistent, the server will close fd after this. *)
| Push of push
(** This is how errors are sent; only sent to persistent connections. *)
(** Timeout on reading the command from the client - client probably frozen. *)
exception Read_command_timeout
(** Invariant: The server_finale_file is created by Exit.exit and left there. *)
type server_specific_files = {
server_finale_file: string; (** just before exit, server will write here *)
} |
OCaml | hhvm/hphp/hack/src/server/serverCommandTypesUtils.ml | open Hh_prelude
open ServerCommandTypes
let debug_describe_t : type a. a t -> string = function
| STATUS _ -> "STATUS"
| STATUS_SINGLE _ -> "STATUS_SINGLE"
| INFER_TYPE _ -> "INFER_TYPE"
| INFER_TYPE_BATCH _ -> "INFER_TYPE_BATCH"
| INFER_TYPE_ERROR _ -> "INFER_TYPE_ERROR"
| IS_SUBTYPE _ -> "IS_SUBTYPE"
| TAST_HOLES _ -> "TAST_HOLES"
| TAST_HOLES_BATCH _ -> "TAST_HOLES_BATCH"
| IDE_HOVER _ -> "IDE_HOVER"
| DOCBLOCK_AT _ -> "DOCBLOCK_AT"
| DOCBLOCK_FOR_SYMBOL _ -> "DOCBLOCK_FOR_SYMBOL"
| IDE_SIGNATURE_HELP _ -> "SIGNATURE_HELP"
| XHP_AUTOCOMPLETE_SNIPPET _ -> "XHP_AUTOCOMPLETE_SNIPPET"
| IDENTIFY_FUNCTION _ -> "IDENTIFY_FUNCTION"
| IDENTIFY_SYMBOL _ -> "IDENTIFY_SYMBOL"
| METHOD_JUMP _ -> "METHOD_JUMP"
| METHOD_JUMP_BATCH _ -> "METHOD_JUMP_BATCH"
| FIND_REFS _ -> "FIND_REFS"
| GO_TO_IMPL _ -> "GO_TO_IMPL"
| IDE_FIND_REFS_BY_SYMBOL _ -> "IDE_FIND_REFS_BY_SYMBOL"
| IDE_GO_TO_IMPL_BY_SYMBOL _ -> "IDE_GO_TO_IMPL_BY_SYMBOL"
| RENAME _ -> "RENAME"
| IDE_RENAME_BY_SYMBOL _ -> "IDE_RENAME_BY_SYMBOL"
| DUMP_SYMBOL_INFO _ -> "DUMP_SYMBOL_INFO"
| REMOVE_DEAD_FIXMES _ -> "REMOVE_DEAD_FIXMES"
| CODEMOD_SDT _ -> "CODEMOD_SDT"
| REMOVE_DEAD_UNSAFE_CASTS -> "REMOVE_DEAD_UNSAFE_CASTS"
| REWRITE_LAMBDA_PARAMETERS _ -> "REWRITE_LAMBDA_PARAMETERS"
| SEARCH _ -> "SEARCH"
| LINT _ -> "LINT"
| LINT_STDIN _ -> "LINT_STDIN"
| LINT_ALL _ -> "LINT_ALL"
| CREATE_CHECKPOINT _ -> "CREATE_CHECKPOINT"
| RETRIEVE_CHECKPOINT _ -> "RETRIEVE_CHECKPOINT"
| DELETE_CHECKPOINT _ -> "DELETE_CHECKPOINT"
| IN_MEMORY_DEP_TABLE_SIZE -> "IN_MEMORY_DEP_TABLE_SIZE"
| SAVE_NAMING _ -> "SAVE_NAMING"
| SAVE_STATE _ -> "SAVE_STATE"
| STATS -> "STATS"
| FORMAT _ -> "FORMAT"
| DUMP_FULL_FIDELITY_PARSE _ -> "DUMP_FULL_FIDELITY_PARSE"
| OPEN_FILE _ -> "OPEN_FILE"
| CLOSE_FILE _ -> "CLOSE_FILE"
| EDIT_FILE _ -> "EDIT_FILE"
| IDE_AUTOCOMPLETE _ -> "IDE_AUTOCOMPLETE"
| CODE_ACTION _ -> "CODE_ACTIONS"
| CODE_ACTION_RESOLVE _ -> "CODE_ACTION_RESOLVE"
| DISCONNECT -> "DISCONNECT"
| OUTLINE _ -> "OUTLINE"
| IDE_IDLE -> "IDE_IDLE"
| RAGE -> "RAGE"
| CST_SEARCH _ -> "CST_SEARCH"
| NO_PRECHECKED_FILES -> "NO_PRECHECKED_FILES"
| POPULATE_REMOTE_DECLS _ -> "POPULATE_REMOTE_DECLS"
| FUN_DEPS_BATCH _ -> "FUN_DEPS_BATCH"
| LIST_FILES_WITH_ERRORS -> "LIST_FILES_WITH_ERRORS"
| FILE_DEPENDENTS _ -> "FILE_DEPENDENTS"
| IDENTIFY_TYPES _ -> "IDENTIFY_TYPES"
| EXTRACT_STANDALONE _ -> "EXTRACT_STANDALONE"
| CONCATENATE_ALL _ -> "CONCATENATE_ALL"
| GO_TO_DEFINITION _ -> "GO_TO_DEFINITION"
| PREPARE_CALL_HIERARCHY _ -> "PREPARE_CALL_HIERARCHY"
| CALL_HIERARCHY_INCOMING_CALLS _ -> "CALL_HIERARCHY_INCOMING_CALLS"
| CALL_HIERARCHY_OUTGOING_CALLS _ -> "CALL_HIERARCHY_OUTGOING_CALLS"
| PAUSE _ -> "PAUSE"
| VERBOSE _ -> "VERBOSE"
| DEPS_OUT_BATCH _ -> "DEPS_OUT_BATCH"
| DEPS_IN_BATCH _ -> "DEPS_IN_BATCH"
let debug_describe_cmd : type a. a command -> string = function
| Rpc ({ ServerCommandTypes.from; _ }, rpc) ->
debug_describe_t rpc
^
if String.equal from "" then
""
else
" --from " ^ from
| Debug_DO_NOT_USE -> failwith "Debug_DO_NOT_USE"
(** This returns a string that's shown "hh_server is busy [STATUS]".
The intent is that users understand what command hh_server is currently busy with.
For command-line commands, we show the "--" option that the user used, e.g. --type-at-pos.
For IDE commands like hover, we show a description like "hover". *)
let status_describe_cmd : type a. a command -> string =
fun cmd ->
match cmd with
| Rpc ({ ServerCommandTypes.from; desc }, _rpc) ->
(if String.equal from "" then
""
else
from ^ ":")
^ desc
| Debug_DO_NOT_USE -> failwith "Debug_DO_NOT_USE"
let debug_describe_message_type : type a. a message_type -> string = function
| Hello -> "Hello"
| Monitor_failed_to_handoff -> "Monitor_failed_to_handoff"
| Ping -> "Ping"
| Response _ -> "Response"
| Push _ -> "Push"
let extract_labelled_file (labelled_file : ServerCommandTypes.labelled_file) :
Relative_path.t * ServerCommandTypes.file_input =
match labelled_file with
| ServerCommandTypes.LabelledFileName filename ->
let path = Relative_path.create_detect_prefix filename in
(path, ServerCommandTypes.FileName filename)
| ServerCommandTypes.LabelledFileContent { filename; content } ->
let path = Relative_path.create_detect_prefix filename in
(path, ServerCommandTypes.FileContent content) |
OCaml | hhvm/hphp/hack/src/server/serverConcatenateAll.ml | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE fn in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open ServerEnv
module SourceText = Full_fidelity_source_text
module Syntax = Full_fidelity_editable_syntax
module SyntaxTree = Full_fidelity_syntax_tree.WithSyntax (Syntax)
module PositionedSyntaxTree =
Full_fidelity_syntax_tree.WithSyntax (Full_fidelity_positioned_syntax)
module Rewriter = Full_fidelity_rewriter.WithSyntax (Syntax)
module Token = Full_fidelity_editable_token
module TokenKind = Full_fidelity_token_kind
exception CircularDependency of string
(* remove <?hh if present *)
let without_markup_suffix node =
Rewriter.rewrite_pre_and_stop
(fun inner ->
match Syntax.syntax inner with
| Syntax.MarkupSuffix _ ->
Rewriter.Replace (Syntax.make_missing SourceText.empty 0)
| _ -> Rewriter.Keep)
node
(* replace `namespace Foo;` with `namespace Foo { ... }` *)
let normalize_namespace_body node =
match Syntax.syntax node with
| Syntax.Script s -> begin
match Syntax.syntax s.script_declarations with
| Syntax.SyntaxList declarations -> begin
match
List.find_mapi declarations ~f:(fun i f ->
match Syntax.syntax f with
| Syntax.NamespaceDeclaration ns -> begin
match Syntax.syntax ns.namespace_body with
| Syntax.NamespaceEmptyBody _ ->
let inner =
List.drop declarations (i + 1)
|> Syntax.make_list SourceText.empty 0
in
let open_brace =
Token.create TokenKind.LeftBrace "{" [] []
|> Syntax.make_token
in
let close_brace =
Token.create TokenKind.RightBrace "}" [] []
|> Syntax.make_token
in
let body =
Syntax.make_namespace_body open_brace inner close_brace
in
let ns =
Syntax.make_namespace_declaration ns.namespace_header body
in
let pre = List.take declarations i in
Some
(Syntax.make_script
(Syntax.make_list SourceText.empty 0 (pre @ [ns])))
| _ -> Some node
end
| _ -> None)
with
| Some replacement -> replacement
| None ->
(* no namespace statement; add a namespace { ... }: if there are
* any namespace declarations in the concatenated file, all
* statements must be in namespace blocks *)
let open_brace =
Token.create TokenKind.LeftBrace "{" [] [] |> Syntax.make_token
in
let close_brace =
Token.create TokenKind.RightBrace "}" [] [] |> Syntax.make_token
in
let ns =
Syntax.make_namespace_declaration
(Syntax.make_namespace_declaration_header
(Syntax.make_token
(Token.create TokenKind.Namespace "namespace" [] []))
(Syntax.make_missing SourceText.empty 0))
(Syntax.make_namespace_body
open_brace
(Syntax.make_list SourceText.empty 0 declarations)
close_brace)
in
Syntax.make_script (Syntax.make_list SourceText.empty 0 [ns])
end
| _ -> node
end
| _ -> node
(* Apply any necessary AST transformations, then return the source code *)
let get_normalized_content (path : Relative_path.t) =
let source_text = SourceText.from_file path in
let mode = Full_fidelity_parser.parse_mode source_text in
let env = Full_fidelity_parser_env.make ?mode () in
let tree =
PositionedSyntaxTree.make ~env source_text
|> SyntaxTransforms.editable_from_positioned
|> without_markup_suffix
|> normalize_namespace_body
in
"///// " ^ Relative_path.suffix path ^ " /////\n" ^ Syntax.text tree
(* return all files with the specified prefix as a single file. This will:
* - resolve inclusion order for class definitions
* - remove `<?hh` headers
* - rewrite namespace statements so that concatenation is valid
*)
let go (genv : ServerEnv.genv) (env : ServerEnv.env) (prefixes : string list) =
let ctx = Provider_utils.ctx_from_server_env env in
let deps_mode = Provider_context.get_deps_mode ctx in
let file_filter (path : string) =
FindUtils.file_filter path
&& List.exists prefixes ~f:(fun prefix -> String.is_prefix path ~prefix)
in
let path_filter (path : Relative_path.t) =
file_filter (Relative_path.to_absolute path)
in
let paths =
genv.indexer file_filter ()
|> List.map ~f:Relative_path.create_detect_prefix
in
let naming_table = env.ServerEnv.naming_table in
let dependent_files (path : Relative_path.t) =
let fileinfo = Naming_table.get_file_info naming_table path in
match fileinfo with
| Some FileInfo.{ classes; _ } ->
let classes =
let open Typing_deps in
List.fold_left
~init:(DepSet.make ())
~f:(fun acc (_, class_id, _) ->
DepSet.add acc (Dep.make (Dep.Type class_id)))
classes
in
let deps =
Typing_deps.add_extend_deps deps_mode classes
|> Naming_provider.get_files ctx
|> Relative_path.Set.filter ~f:path_filter
in
Relative_path.Set.remove deps path
| _ -> Relative_path.Set.empty
in
let shallow_dependents =
List.fold_left
~init:Relative_path.Map.empty
~f:(fun (acc : Relative_path.Set.t Relative_path.Map.t) path ->
Relative_path.Map.add ~key:path ~data:(dependent_files path) acc)
paths
in
let rec get_recursive_dependents path =
match Relative_path.Map.find_opt shallow_dependents path with
| Some shallow ->
Relative_path.Set.fold
~init:shallow
~f:(fun dep_path acc ->
Relative_path.Set.union acc @@ get_recursive_dependents dep_path)
shallow
| _ -> Relative_path.Set.empty
in
let recursive_dependents =
Relative_path.Map.map
~f:(fun paths ->
Relative_path.Set.fold
~init:paths
~f:(fun path acc ->
Relative_path.Set.union acc @@ get_recursive_dependents path)
paths)
shallow_dependents
in
let recursive_dependencies =
List.map
~f:(fun dependent ->
let dependencies =
List.filter
~f:(fun dependency ->
match
Relative_path.Map.find_opt recursive_dependents dependency
with
| Some dependents -> Relative_path.Set.mem dependents dependent
| _ -> false)
paths
in
(dependent, Relative_path.Set.of_list dependencies))
paths
|> Relative_path.Map.of_list
in
let rec sort (visited : Relative_path.t list) (rest : Relative_path.Set.t) =
let files_without_deps =
Relative_path.Set.filter rest ~f:(fun path ->
match Relative_path.Map.find_opt recursive_dependencies path with
| Some deps ->
(* any dependencies that aren't in `rest` must have already
* been visited *)
let pending_deps = Relative_path.Set.inter deps rest in
Relative_path.Set.is_empty pending_deps
| None -> true)
in
(if Relative_path.Set.is_empty files_without_deps then
(* everything has an unsatisifed dependency, so error out *)
let visited_pretty =
List.map ~f:Relative_path.to_absolute visited |> String.concat ~sep:", "
in
let rest_pretty =
List.map
(Relative_path.Set.elements rest)
~f:(fun (path : Relative_path.t) ->
let deps =
Relative_path.Map.find recursive_dependencies path
|> Relative_path.Set.inter rest
|> Relative_path.Set.elements
|> List.map ~f:Relative_path.to_absolute
|> String.concat ~sep:", "
in
Relative_path.to_absolute path ^ "[" ^ deps ^ "]")
|> String.concat ~sep:", "
in
raise
(CircularDependency
("circular dependency detected:\nvisited: "
^ visited_pretty
^ "\nrest: "
^ rest_pretty)));
let rest = Relative_path.Set.diff rest files_without_deps in
let visited = visited @ Relative_path.Set.elements files_without_deps in
if Relative_path.Set.is_empty rest then
(visited, rest)
else
sort visited rest
in
let (ordered, _) = sort [] (Relative_path.Set.of_list paths) in
List.map ~f:get_normalized_content ordered |> String.concat ~sep:"\n" |
OCaml | hhvm/hphp/hack/src/server/serverConfig.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.
*
*)
(**
* Parses and gathers information from the .hhconfig in the repo.
*)
open Hh_prelude
open Config_file.Getters
open Reordered_argument_collections
open ServerLocalConfig
type t = {
version: Config_file.version; [@printer (fun fmt _ -> fprintf fmt "version")]
load_script_timeout: int;
(* in seconds *)
(* Configures only the workers. Workers can have more relaxed GC configs as
* they are short-lived processes *)
gc_control: Gc.control; [@printer (fun fmt _ -> fprintf fmt "control")]
sharedmem_config: SharedMem.config;
tc_options: TypecheckerOptions.t;
parser_options: ParserOptions.t;
glean_options: GleanOptions.t;
symbol_write_options: SymbolWriteOptions.t;
formatter_override: Path.t option;
config_hash: string option;
(* A list of regexps for paths to ignore *)
ignored_paths: string list;
(* A list of extra paths to search for declarations *)
extra_paths: Path.t list;
warn_on_non_opt_build: bool;
(* clientIdeDaemon will fall back to performing a full index of files to construct a naming table if it fails to load one. *)
ide_fall_back_to_full_index: bool;
}
[@@deriving show]
let repo_config_path =
Relative_path.from_root ~suffix:Config_file.file_path_relative_to_repo_root
let is_compatible c1 c2 =
(* This comparison can eventually be made more complex; we may not always
* need to restart hh_server, e.g. changing the path to the load script
* is immaterial*)
Poly.equal c1 c2
let make_gc_control config =
let { Gc.Control.minor_heap_size; space_overhead; _ } =
GlobalConfig.gc_control
in
let minor_heap_size =
int_ "gc_minor_heap_size" ~default:minor_heap_size config
in
let space_overhead =
int_ "gc_space_overhead" ~default:space_overhead config
in
{ GlobalConfig.gc_control with Gc.Control.minor_heap_size; space_overhead }
let make_sharedmem_config config options local_config =
let { SharedMem.global_size; heap_size; shm_min_avail; _ } =
SharedMem.default_config
in
let shm_dirs = local_config.ServerLocalConfig.shm_dirs in
let global_size = int_ "sharedmem_global_size" ~default:global_size config in
let heap_size = int_ "sharedmem_heap_size" ~default:heap_size config in
let hash_table_pow = int_ "sharedmem_hash_table_pow" ~default:18 config in
let log_level = int_ "sharedmem_log_level" ~default:0 config in
let sample_rate = float_ "sharedmem_sample_rate" ~default:0.0 config in
let compression = int_ "sharedmem_compression" ~default:0 config in
let shm_dirs = string_list "sharedmem_dirs" ~default:shm_dirs config in
let shm_use_sharded_hashtbl =
bool_
"shm_use_sharded_hashtbl"
~default:local_config.ServerLocalConfig.shm_use_sharded_hashtbl
config
in
let shm_cache_size =
int_
"shm_cache_size"
~default:local_config.ServerLocalConfig.shm_cache_size
config
in
let shm_min_avail =
int_ "sharedmem_minimum_available" ~default:shm_min_avail config
in
let config =
{
SharedMem.global_size;
heap_size;
hash_table_pow;
log_level;
sample_rate;
shm_dirs;
shm_use_sharded_hashtbl;
shm_cache_size;
shm_min_avail;
compression;
}
in
match ServerArgs.ai_mode options with
| None -> config
| Some ai_options -> Ai_options.modify_shared_mem ai_options config
let config_list_regexp = Str.regexp "[, \t]+"
let process_experimental sl =
match List.map sl ~f:String.lowercase with
| ["false"] -> SSet.empty
| ["true"] -> TypecheckerOptions.experimental_all
| features -> List.fold_left features ~f:SSet.add ~init:SSet.empty
let config_experimental_tc_features config =
Option.map
(Config_file.Getters.string_opt "enable_experimental_tc_features" config)
~f:(fun list_str ->
let sl = Str.split config_list_regexp list_str in
process_experimental sl)
let process_migration_flags sl =
match sl with
| ["false"] -> SSet.empty
| ["true"] -> TypecheckerOptions.migration_flags_all
| flags ->
List.iter flags ~f:(fun s ->
if not (SSet.mem TypecheckerOptions.migration_flags_all s) then
failwith ("invalid migration flag: " ^ s));
List.fold_left flags ~f:SSet.add ~init:SSet.empty
let config_tc_migration_flags config =
Option.map
(Config_file.Getters.string_opt "enable_tc_migration_flags" config)
~f:(fun list_str ->
Str.split config_list_regexp list_str
|> List.map ~f:String.lowercase
|> process_migration_flags)
let convert_paths str =
let json = Hh_json.json_of_string ~strict:true str in
let l = Hh_json.get_array_exn json in
List.filter_map
~f:(fun s ->
match s with
| Hh_json.JSON_String path -> Some path
| _ -> None)
l
let process_ignored_paths config =
Config_file.Getters.string_opt "ignored_paths" config
|> Option.value_map ~f:convert_paths ~default:[]
let maybe_relative_path fn =
(* Note: this is not the same as calling realpath; the cwd is not
* necessarily the same as hh_server's root!!! *)
Path.make
begin
if Filename.is_relative fn then
Relative_path.(to_absolute (from_root ~suffix:fn))
else
fn
end
let process_extra_paths config =
match Config_file.Getters.string_opt "extra_paths" config with
| Some s -> Str.split config_list_regexp s |> List.map ~f:maybe_relative_path
| _ -> []
let process_untrusted_mode config =
match Config_file.Getters.string_opt "untrusted_mode" config with
| Some s ->
if bool_of_string s then
let blacklist =
[
(* out of tree file access*)
"extra_paths";
(* potential resource abuse *)
"language_feature_logging";
]
in
let prefix_blacklist =
[(* potential resource abuse *) "gc_"; "sharedmem_"]
in
let invalid_keys =
List.filter (Config_file.keys config) ~f:(fun ck ->
let ck = String.lowercase ck in
let exact_match =
List.find ~f:(fun bli -> String.equal bli ck) blacklist
in
let prefix_match =
List.find
~f:(fun blp -> String.is_prefix ck ~prefix:blp)
prefix_blacklist
in
match (exact_match, prefix_match) with
| (None, None) -> false
| _ -> true)
in
if not (List.is_empty invalid_keys) then
failwith
("option not permitted in untrusted_mode: "
^ String.concat ~sep:", " invalid_keys)
else
failwith "untrusted_mode can only be enabled, not disabled"
| _ -> ()
let extract_auto_namespace_element ns_map element =
match element with
| (source, Hh_json.JSON_String target) -> (source, target) :: ns_map
| _ ->
(* This means the JSON we received is incorrect *)
ns_map
let convert_auto_namespace_to_map map =
let json = Hh_json.json_of_string ~strict:true map in
let pairs = Hh_json.get_object_exn json in
(* We do a fold instead of a map to filter
* out the incorrect entrie as we look at each item *)
List.fold_left ~init:[] ~f:extract_auto_namespace_element pairs
let prepare_auto_namespace_map config =
Option.map
(Config_file.Getters.string_opt "auto_namespace_map" config)
~f:convert_auto_namespace_to_map
let extract_log_level = function
| (log_key, Hh_json.JSON_Number log_level) -> begin
match int_of_string_opt log_level with
| Some log_level -> (log_key, log_level)
| None -> failwith "non-integer log level value"
end
| _ -> failwith "non-integer log level value"
let convert_log_levels_to_map map =
let json = Hh_json.json_of_string ~strict:true map in
let pairs = Hh_json.get_object_exn json in
List.map ~f:extract_log_level pairs |> SMap.of_list
let prepare_log_levels config =
Option.map
(Config_file.Getters.string_opt "log_levels" config)
~f:convert_log_levels_to_map
let prepare_iset config config_name =
Option.map
(Config_file.Getters.string_opt config_name config)
~f:(fun list_str ->
Str.split config_list_regexp list_str
|> List.map ~f:int_of_string
|> List.fold_right ~init:ISet.empty ~f:ISet.add)
let prepare_allowed_decl_fixme_codes config =
prepare_iset config "allowed_decl_fixme_codes"
let load_config config options =
GlobalOptions.set
?po_deregister_php_stdlib:(bool_opt "deregister_php_stdlib" config)
?tco_language_feature_logging:(bool_opt "language_feature_logging" config)
?tco_timeout:(int_opt "timeout" config)
?tco_disallow_invalid_arraykey:(bool_opt "disallow_invalid_arraykey" config)
?tco_disallow_byref_dynamic_calls:
(bool_opt "disallow_byref_dynamic_calls" config)
?tco_disallow_byref_calls:(bool_opt "disallow_byref_calls" config)
?po_disable_lval_as_an_expression:
(bool_opt "disable_lval_as_an_expression" config)
?code_agnostic_fixme:(bool_opt "code_agnostic_fixme" config)
?allowed_fixme_codes_strict:
(prepare_iset config "allowed_fixme_codes_strict")
?po_auto_namespace_map:(prepare_auto_namespace_map config)
?tco_experimental_features:(config_experimental_tc_features config)
?tco_migration_flags:(config_tc_migration_flags config)
?tco_like_type_hints:(bool_opt "like_type_hints" config)
?tco_union_intersection_type_hints:
(bool_opt "union_intersection_type_hints" config)
?tco_coeffects:(bool_opt "call_coeffects" config)
?tco_coeffects_local:(bool_opt "local_coeffects" config)
?tco_like_casts:(bool_opt "like_casts" config)
?tco_check_xhp_attribute:(bool_opt "check_xhp_attribute" config)
?tco_check_redundant_generics:(bool_opt "check_redundant_generics" config)
?tco_disallow_unresolved_type_variables:
(bool_opt "disallow_unresolved_type_variables" config)
?tco_locl_cache_capacity:(int_opt "locl_cache_capacity" config)
?tco_locl_cache_node_threshold:(int_opt "locl_cache_node_threshold" config)
?po_enable_class_level_where_clauses:
(bool_opt "class_level_where_clauses" config)
?po_disable_legacy_soft_typehints:
(bool_opt "disable_legacy_soft_typehints" config)
?po_disallow_toplevel_requires:
(bool_opt "disallow_toplevel_requires" config)
?po_allowed_decl_fixme_codes:(prepare_allowed_decl_fixme_codes config)
?po_allow_new_attribute_syntax:
(bool_opt "allow_new_attribute_syntax" config)
?po_disable_legacy_attribute_syntax:
(bool_opt "disable_legacy_attribute_syntax" config)
?tco_const_attribute:(bool_opt "const_attribute" config)
?po_const_default_func_args:(bool_opt "const_default_func_args" config)
?po_const_default_lambda_args:(bool_opt "const_default_lambda_args" config)
?po_disallow_silence:(bool_opt "disallow_silence" config)
?po_keep_user_attributes:(bool_opt "keep_user_attributes" config)
?tco_const_static_props:(bool_opt "const_static_props" config)
?po_abstract_static_props:(bool_opt "abstract_static_props" config)
?tco_check_attribute_locations:(bool_opt "check_attribute_locations" config)
?glean_reponame:(string_opt "glean_reponame" config)
?symbol_write_index_inherited_members:
(bool_opt "symbol_write_index_inherited_members" config)
?symbol_write_ownership:(bool_opt "symbol_write_ownership" config)
?symbol_write_root_path:(string_opt "symbol_write_root_path" config)
?symbol_write_hhi_path:(string_opt "symbol_write_hhi_path" config)
?symbol_write_ignore_paths:
(string_list_opt "symbol_write_ignore_paths" config)
?symbol_write_index_paths:
(string_list_opt "symbol_write_index_paths" config)
?symbol_write_index_paths_file:
(string_opt "symbol_write_index_paths_file" config)
?symbol_write_index_paths_file_output:
(string_opt "symbol_write_index_paths_file_output" config)
?symbol_write_include_hhi:(bool_opt "symbol_write_include_hhi" config)
?symbol_write_sym_hash_in:(string_opt "symbol_write_sym_hash_in" config)
?symbol_write_exclude_out:(string_opt "symbol_write_exclude_out" config)
?symbol_write_referenced_out:
(string_opt "symbol_write_referenced_out" config)
?symbol_write_sym_hash_out:(bool_opt "symbol_write_sym_hash_out" config)
?po_disallow_func_ptrs_in_constants:
(bool_opt "disallow_func_ptrs_in_constants" config)
?tco_error_php_lambdas:(bool_opt "error_php_lambdas" config)
?tco_disallow_discarded_nullable_awaitables:
(bool_opt "disallow_discarded_nullable_awaitables" config)
?po_disable_xhp_element_mangling:
(bool_opt "disable_xhp_element_mangling" config)
?po_disable_xhp_children_declarations:
(bool_opt "disable_xhp_children_declarations" config)
?po_enable_xhp_class_modifier:(bool_opt "enable_xhp_class_modifier" config)
?po_disable_hh_ignore_error:(int_opt "disable_hh_ignore_error" config)
?tco_method_call_inference:(bool_opt "method_call_inference" config)
?tco_report_pos_from_reason:(bool_opt "report_pos_from_reason" config)
?tco_typecheck_sample_rate:(float_opt "typecheck_sample_rate" config)
?tco_enable_sound_dynamic:(bool_opt "enable_sound_dynamic_type" config)
?tco_pessimise_builtins:(bool_opt "pessimise_builtins" config)
?tco_enable_no_auto_dynamic:(bool_opt "enable_no_auto_dynamic" config)
?tco_skip_check_under_dynamic:(bool_opt "skip_check_under_dynamic" config)
?tco_enable_modules:(bool_opt "enable_modules" config)
?po_interpret_soft_types_as_like_types:
(bool_opt "interpret_soft_types_as_like_types" config)
?tco_enable_strict_string_concat_interp:
(bool_opt "enable_strict_string_concat_interp" config)
?tco_ignore_unsafe_cast:(bool_opt "ignore_unsafe_cast" config)
?tco_allowed_expression_tree_visitors:
(Option.map
(string_list_opt "allowed_expression_tree_visitors" config)
~f:(fun l -> List.map l ~f:Utils.add_ns))
?tco_math_new_code:(bool_opt "math_new_code" config)
?tco_typeconst_concrete_concrete_error:
(bool_opt "typeconst_concrete_concrete_error" config)
?tco_enable_strict_const_semantics:
(let key = "enable_strict_const_semantics" in
match int_opt_result key config with
| None -> None
| Some (Ok i) -> Some i
| Some (Error _) ->
(* not an int *)
bool_opt key config |> Option.map ~f:Bool.to_int)
?tco_strict_wellformedness:(int_opt "strict_wellformedness" config)
?tco_meth_caller_only_public_visibility:
(bool_opt "meth_caller_only_public_visibility" config)
?tco_require_extends_implements_ancestors:
(bool_opt "require_extends_implements_ancestors" config)
?tco_strict_value_equality:(bool_opt "strict_value_equality" config)
?tco_enforce_sealed_subclasses:(bool_opt "enforce_sealed_subclasses" config)
?tco_everything_sdt:(bool_opt "everything_sdt" config)
?tco_explicit_consistent_constructors:
(int_opt "explicit_consistent_constructors" config)
?tco_require_types_class_consts:
(int_opt "require_types_tco_require_types_class_consts" config)
?tco_type_printer_fuel:(int_opt "type_printer_fuel" config)
?tco_profile_top_level_definitions:
(bool_opt "profile_top_level_definitions" config)
?tco_is_systemlib:(bool_opt "is_systemlib" config)
?log_levels:(prepare_log_levels config)
?tco_allowed_files_for_module_declarations:
(string_list_opt "allowed_files_for_module_declarations" config)
?tco_allow_all_files_for_module_declarations:
(bool_opt "allow_all_files_for_module_declarations" config)
?tco_expression_tree_virtualize_functions:
(bool_opt "expression_tree_virtualize_functions" config)
?tco_use_type_alias_heap:(bool_opt "use_type_alias_heap" config)
?tco_populate_dead_unsafe_cast_heap:
(bool_opt "populate_dead_unsafe_cast_heap" config)
?po_disallow_static_constants_in_default_func_args:
(bool_opt "disallow_static_constants_in_default_func_args" config)
?tco_log_exhaustivity_check:(bool_opt "log_exhaustivity_check" config)
?dump_tast_hashes:(bool_opt "dump_tast_hashes" config)
options
let load ~silent options : t * ServerLocalConfig.t =
let command_line_overrides =
Config_file.of_list @@ ServerArgs.config options
in
let (config_hash, config) =
Config_file.parse_hhconfig (Relative_path.to_absolute repo_config_path)
in
let config =
Config_file.apply_overrides
~config
~overrides:command_line_overrides
~log_reason:None
in
process_untrusted_mode config;
let version =
Config_file.parse_version (Config_file.Getters.string_opt "version" config)
in
let local_config =
let current_rolled_out_flag_idx =
int_
"current_saved_state_rollout_flag_index"
~default:Int.min_value
config
in
let deactivate_saved_state_rollout =
bool_ "deactivate_saved_state_rollout" ~default:false config
in
ServerLocalConfig.load
~silent
~current_version:version
~current_rolled_out_flag_idx
~deactivate_saved_state_rollout
~from:(ServerArgs.from options)
command_line_overrides
in
let local_config =
if Option.is_some (ServerArgs.ai_mode options) then
let open ServerLocalConfig in
{
local_config with
watchman =
{
local_config.watchman with
Watchman.enabled = false;
subscribe = false;
};
interrupt_on_watchman = false;
interrupt_on_client = false;
trace_parsing = false;
}
else
local_config
in
let ignored_paths = process_ignored_paths config in
let extra_paths = process_extra_paths config in
(* Since we use the unix alarm() for our timeouts, a timeout value of 0 means
* to wait indefinitely *)
let load_script_timeout = int_ "load_script_timeout" ~default:0 config in
let warn_on_non_opt_build =
bool_ "warn_on_non_opt_build" ~default:false config
in
let ide_fall_back_to_full_index =
bool_ "ide_fall_back_to_full_index" ~default:true config
in
let formatter_override =
Option.map
(Config_file.Getters.string_opt "formatter_override" config)
~f:maybe_relative_path
in
let global_opts =
let tco_custom_error_config = CustomErrorConfig.load_and_parse () in
let glean_reponame =
(* TODO(ljw): remove this after rollout complete; T158354704 *)
if local_config.glean_v2 then
Some "www.hack.light"
else
None
in
let local_config_opts =
GlobalOptions.set
?so_naming_sqlite_path:local_config.naming_sqlite_path
?glean_reponame
?tco_log_large_fanouts_threshold:
local_config.log_large_fanouts_threshold
~tco_remote_old_decls_no_limit:
local_config.ServerLocalConfig.remote_old_decls_no_limit
~tco_fetch_remote_old_decls:
local_config.ServerLocalConfig.fetch_remote_old_decls
~tco_populate_member_heaps:
local_config.ServerLocalConfig.populate_member_heaps
~tco_skip_hierarchy_checks:
local_config.ServerLocalConfig.skip_hierarchy_checks
~tco_skip_tast_checks:local_config.ServerLocalConfig.skip_tast_checks
~po_allow_unstable_features:
local_config.ServerLocalConfig.allow_unstable_features
~tco_saved_state:local_config.ServerLocalConfig.saved_state
~tco_rust_elab:local_config.ServerLocalConfig.rust_elab
~tco_log_inference_constraints:
(ServerArgs.log_inference_constraints options)
~po_parser_errors_only:(Option.is_some (ServerArgs.ai_mode options))
~tco_ifc_enabled:(ServerArgs.enable_ifc options)
~tco_global_access_check_enabled:
(ServerArgs.enable_global_access_check options)
~dump_tast_hashes:local_config.dump_tast_hashes
~tco_custom_error_config
GlobalOptions.default
in
load_config config local_config_opts
in
Errors.allowed_fixme_codes_strict :=
GlobalOptions.allowed_fixme_codes_strict global_opts;
Errors.report_pos_from_reason :=
TypecheckerOptions.report_pos_from_reason global_opts;
Errors.code_agnostic_fixme := GlobalOptions.code_agnostic_fixme global_opts;
( {
version;
load_script_timeout;
gc_control = make_gc_control config;
sharedmem_config = make_sharedmem_config config options local_config;
tc_options = global_opts;
parser_options = global_opts;
glean_options = global_opts;
symbol_write_options = global_opts;
formatter_override;
config_hash = Some config_hash;
ignored_paths;
extra_paths;
warn_on_non_opt_build;
ide_fall_back_to_full_index;
},
local_config )
(* useful in testing code *)
let default_config =
{
version = Config_file.Opaque_version None;
load_script_timeout = 0;
gc_control = GlobalConfig.gc_control;
sharedmem_config = SharedMem.default_config;
tc_options = TypecheckerOptions.default;
glean_options = GleanOptions.default;
symbol_write_options = SymbolWriteOptions.default;
parser_options = ParserOptions.default;
formatter_override = None;
config_hash = None;
ignored_paths = [];
extra_paths = [];
warn_on_non_opt_build = false;
ide_fall_back_to_full_index = false;
}
let set_parser_options config popt = { config with parser_options = popt }
let set_tc_options config tcopt = { config with tc_options = tcopt }
let set_glean_options config gleanopt = { config with glean_options = gleanopt }
let set_symbol_write_options config swriteopt =
{ config with symbol_write_options = swriteopt }
let gc_control config = config.gc_control
let sharedmem_config config = config.sharedmem_config
let typechecker_options config = config.tc_options
let parser_options config = config.parser_options
let glean_options config = config.glean_options
let symbol_write_options config = config.symbol_write_options
let formatter_override config = config.formatter_override
let config_hash config = config.config_hash
let ignored_paths config = config.ignored_paths |> List.map ~f:Str.regexp
let extra_paths config = config.extra_paths
let version config = config.version
let warn_on_non_opt_build config = config.warn_on_non_opt_build
let ide_fall_back_to_full_index config = config.ide_fall_back_to_full_index |
OCaml Interface | hhvm/hphp/hack/src/server/serverConfig.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.
*
*)
open Hh_prelude
type t [@@deriving show]
val set_parser_options : t -> ParserOptions.t -> t
val set_tc_options : t -> TypecheckerOptions.t -> t
val set_glean_options : t -> GleanOptions.t -> t
val set_symbol_write_options : t -> SymbolWriteOptions.t -> t
val repo_config_path : Relative_path.t
val load_config : Config_file_common.t -> GlobalOptions.t -> GlobalOptions.t
val load : silent:bool -> ServerArgs.options -> t * ServerLocalConfig.t
val is_compatible : t -> t -> bool
val default_config : t
val ignored_paths : t -> Str.regexp list
val extra_paths : t -> Path.t list
val gc_control : t -> Gc.control
val sharedmem_config : t -> SharedMem.config
val typechecker_options : t -> TypecheckerOptions.t
val parser_options : t -> ParserOptions.t
val glean_options : t -> GleanOptions.t
val symbol_write_options : t -> SymbolWriteOptions.t
val formatter_override : t -> Path.t option
val config_hash : t -> string option
val version : t -> Config_file.version
val warn_on_non_opt_build : t -> bool
val ide_fall_back_to_full_index : t -> bool
val convert_auto_namespace_to_map : string -> (string * string) list
val make_sharedmem_config :
Config_file.t -> ServerArgs.options -> ServerLocalConfig.t -> SharedMem.config |
OCaml | hhvm/hphp/hack/src/server/serverDepsInBatch.ml | open Hh_prelude
open ServerDepsUtil
let references
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(genv : ServerEnv.genv)
~(env : ServerEnv.env)
(occ : Relative_path.t SymbolOccurrence.t) :
ServerCommandTypes.Find_refs.result_or_retry =
let (line, column, _) = Pos.info_pos occ.SymbolOccurrence.pos in
match ServerFindRefs.go_from_file_ctx ~ctx ~entry ~line ~column with
| None -> ServerCommandTypes.Done_or_retry.Done []
| Some (_, action) ->
ServerFindRefs.(go ctx action false ~stream_file:None ~hints:[] genv env)
|> ServerCommandTypes.Done_or_retry.map_env ~f:ServerFindRefs.to_absolute
|> snd
let body_references
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(genv : ServerEnv.genv)
~(env : ServerEnv.env)
~(declarations : Relative_path.t SymbolOccurrence.t list)
~(get_def :
Relative_path.t SymbolOccurrence.t ->
Relative_path.t SymbolDefinition.t option)
(occ : Relative_path.t SymbolOccurrence.t) :
ServerCommandTypes.Find_refs.result_or_retry list =
match get_def occ with
| None -> [ServerCommandTypes.Done_or_retry.Done []]
| Some def ->
let symbols_to_find =
occ :: body_symbols ~ctx ~entry declarations occ def
in
List.map symbols_to_find ~f:(references ~ctx ~entry ~genv ~env)
let go
~(ctx : Provider_context.t)
~(genv : ServerEnv.genv)
~(env : ServerEnv.env)
(pos_list : (string * int * int) list) :
ServerCommandTypes.Find_refs.result_or_retry list =
let deps_in_of_location acc_ctx_in (file, line, column) :
Provider_context.t * ServerCommandTypes.Find_refs.result_or_retry list =
let (acc_ctx_out, entry, _, get_def) = get_def_setup acc_ctx_in file in
(*Other files can only depend on things declared in this one*)
let declarations =
IdentifySymbolService.all_symbols_ctx ~ctx:acc_ctx_out ~entry
|> List.filter ~f:(fun s -> s.SymbolOccurrence.is_declaration)
in
let target_symbols = List.filter declarations ~f:(is_target line column) in
let deps =
List.concat_map
target_symbols
~f:(body_references ~ctx ~entry ~genv ~env ~declarations ~get_def)
in
(acc_ctx_out, deps)
in
List.fold_map pos_list ~init:ctx ~f:deps_in_of_location |> snd |> List.concat |
OCaml | hhvm/hphp/hack/src/server/serverDepsOutBatch.ml | open Hh_prelude
open ServerDepsUtil
let build_json_def def =
let open SymbolDefinition in
let open Hh_json in
Hh_json.JSON_Object
[
("kind", string_ (SymbolDefinition.string_of_kind def.kind));
("name", string_ def.full_name);
("position", Pos.to_absolute def.pos |> Pos.multiline_json);
]
let rec build_json_entry
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(total_occ_list : Relative_path.t SymbolOccurrence.t list)
~(get_def :
Relative_path.t SymbolOccurrence.t ->
Relative_path.t SymbolDefinition.t option)
(occ : Relative_path.t SymbolOccurrence.t) : Hh_json.json =
let open SymbolOccurrence in
let open Hh_json in
let def_opt = get_def occ in
let depends_json =
match def_opt with
| None -> string_ "None"
| Some def ->
if not occ.is_declaration then
build_json_def def
else
let body_list = body_symbols ~ctx ~entry total_occ_list occ def in
Hh_json.array_
(build_json_entry ~ctx ~entry ~total_occ_list ~get_def)
body_list
in
Hh_json.JSON_Object
[
("kind", kind_to_string occ.type_ |> string_);
("name", string_ occ.name);
("declaration", bool_ occ.is_declaration);
("position", Pos.to_absolute occ.pos |> Pos.multiline_json);
("depends_on", depends_json);
]
let interesting_occ (occ : Relative_path.t SymbolOccurrence.t) : bool =
let open SymbolOccurrence in
match occ.type_ with
| Keyword _
| LocalVar
| BuiltInType _
| BestEffortArgument _ ->
false
| _ -> true
let go_json :
Provider_context.t -> (string * int * int) list -> Hh_json.json list =
fun server_ctx pos_list ->
let json_of_symbols acc_ctx_in (file, line, column) =
let (acc_ctx_out, entry, _, get_def) = get_def_setup acc_ctx_in file in
let total_occ_list =
IdentifySymbolService.all_symbols_ctx ~ctx:acc_ctx_out ~entry
|> List.filter ~f:interesting_occ
in
let symbols = List.filter total_occ_list ~f:(is_target line column) in
let json =
Hh_json.JSON_Array
(List.map
symbols
~f:
(build_json_entry ~ctx:acc_ctx_out ~entry ~total_occ_list ~get_def))
in
(acc_ctx_out, json)
in
let (_, json_list) =
List.fold_map pos_list ~init:server_ctx ~f:json_of_symbols
in
json_list
let go (ctx : Provider_context.t) (pos_list : (string * int * int) list) :
string list =
let jsons = go_json ctx pos_list in
List.map jsons ~f:(Hh_json.json_to_string ~pretty:true) |
OCaml Interface | hhvm/hphp/hack/src/server/serverDepsOutBatch.mli | val go_json :
Provider_context.t -> (string * int * int) list -> Hh_json.json list
val go : Provider_context.t -> (string * int * int) list -> string list |
OCaml | hhvm/hphp/hack/src/server/serverDepsUtil.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 symbol_in_call_hierarchy (sym_occ : Relative_path.t SymbolOccurrence.t) :
bool =
let open SymbolOccurrence in
match sym_occ.type_ with
| Class _ -> true
| BuiltInType _ -> false
| Function -> true
| Method _ -> true
| LocalVar -> false
| TypeVar -> false
| Property _ -> true
| XhpLiteralAttr _ -> false
| ClassConst _ -> false
| Typeconst _ -> false
| GConst -> false
| Attribute _ -> true
| EnumClassLabel _ -> true
| Keyword _ -> false
| PureFunctionContext -> false
| BestEffortArgument _ -> false
| HhFixme -> false
| Module -> true
let is_target target_line target_char (occ : Relative_path.t SymbolOccurrence.t)
=
let open SymbolOccurrence in
let pos = occ.pos in
let (l, start, end_) = Pos.info_pos pos in
l = target_line && start <= target_char && target_char - 1 <= end_
let body_symbols
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
(filter_against : Relative_path.t SymbolOccurrence.t list)
(occ : Relative_path.t SymbolOccurrence.t)
(def : Relative_path.t SymbolDefinition.t) :
Relative_path.t SymbolOccurrence.t list =
let open SymbolOccurrence in
let open SymbolDefinition in
let node_opt =
ServerSymbolDefinition.get_definition_cst_node_ctx
~ctx
~entry
~kind:def.kind
~pos:def.pos
in
match node_opt with
| None -> []
| Some node ->
let span_pos_opt =
Full_fidelity_positioned_syntax.position (Pos.filename def.pos) node
in
(match span_pos_opt with
| None -> []
| Some span_pos ->
let pos_filter (o : Relative_path.t SymbolOccurrence.t) =
(not (phys_equal o occ)) && Pos.contains span_pos o.pos
in
List.filter filter_against ~f:pos_filter)
let get_ast_getdef (ctx : Provider_context.t) (entry : Provider_context.entry) =
let ast =
Ast_provider.compute_ast ~popt:(Provider_context.get_popt ctx) ~entry
in
let get_def = ServerSymbolDefinition.go ctx (Some ast) in
(ast, get_def)
let get_def_setup (acc_ctx_in : Provider_context.t) (file : string) =
let path = Relative_path.create_detect_prefix file in
let (acc_ctx_out, entry) =
Provider_context.add_entry_if_missing ~ctx:acc_ctx_in ~path
in
let (ast, get_def) = get_ast_getdef acc_ctx_out entry in
(acc_ctx_out, entry, ast, get_def) |
OCaml | hhvm/hphp/hack/src/server/serverDocblockAt.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 Cls = Decl_provider.Class
let get_all_ancestors ctx class_name =
let rec helper classes_to_check cinfos seen_classes =
match classes_to_check with
| [] -> cinfos
| class_name :: classes when SSet.mem class_name seen_classes ->
helper classes cinfos seen_classes
| class_name :: classes -> begin
match Decl_provider.get_class ctx class_name with
| None -> helper classes cinfos seen_classes
| Some class_info ->
let ancestors =
Cls.all_ancestor_names class_info
|> List.fold ~init:classes ~f:(fun acc cid -> cid :: acc)
in
helper
ancestors
(class_info :: cinfos)
(SSet.add class_name seen_classes)
end
in
helper [class_name] [] SSet.empty
let get_docblock_for_member ctx class_info member_name =
let open Option.Monad_infix in
Cls.get_method class_info member_name >>= fun member ->
match Typing_defs.get_node @@ Lazy.force member.Typing_defs.ce_type with
| Typing_defs.Tfun _ ->
let pos =
Lazy.force member.Typing_defs.ce_pos
|> Naming_provider.resolve_position ctx
in
let path = Pos.filename pos in
let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path in
ServerSymbolDefinition.get_definition_cst_node_ctx
~ctx
~entry
~kind:SymbolDefinition.Method
~pos
>>= Docblock_finder.get_docblock
| _ -> None
let render_ancestor_docblocks docblocks =
let docblocks_to_ancestor =
docblocks
|> List.fold ~init:SMap.empty ~f:(fun acc (class_name, docblock) ->
let existing_ancestors =
match SMap.find_opt docblock acc with
| None -> []
| Some lst -> lst
in
SMap.add docblock (class_name :: existing_ancestors) acc)
in
match SMap.elements docblocks_to_ancestor with
| [] -> None
| [(docblock, _)] -> Some docblock
| docblock_ancestors_pairs ->
docblock_ancestors_pairs
|> List.map ~f:(fun (docblock, ancestors) ->
let ancestors_str =
String.concat ~sep:", " (List.map ~f:Utils.strip_ns ancestors)
in
Printf.sprintf "%s\n(from %s)" docblock ancestors_str)
|> String.concat ~sep:"\n\n---\n\n"
|> fun results -> Some results
let fallback ctx class_name member_name =
let rec all_interfaces_or_first_class_docblock
seen_interfaces ancestors_to_check =
match ancestors_to_check with
| [] -> seen_interfaces
| ancestor :: ancestors -> begin
match get_docblock_for_member ctx ancestor member_name with
| None -> all_interfaces_or_first_class_docblock seen_interfaces ancestors
| Some docblock ->
(match Cls.kind ancestor with
| Ast_defs.Cclass _ -> [(Cls.name ancestor, docblock)]
| Ast_defs.(Ctrait | Cinterface | Cenum | Cenum_class _) ->
all_interfaces_or_first_class_docblock
((Cls.name ancestor, docblock) :: seen_interfaces)
ancestors)
end
in
get_all_ancestors ctx class_name
|> all_interfaces_or_first_class_docblock []
|> render_ancestor_docblocks
let re_generated =
Str.regexp "^This file is generated\\.\\(.*\n\\)*^\u{40}generated.*$"
let re_partially_generated =
Str.regexp
"^This file is partially generated\\.\\(.*\n\\)*^\u{40}partially-generated.*$"
let re_copyright1 = Str.regexp "^(c) Facebook.*$"
let re_copyright2 = Str.regexp "^Copyright [0-9][0-9][0-9][0-9].*$"
let re_copyright3 = Str.regexp "^Copyright (c).*$"
let clean_comments (s : string) : string =
s
|> Str.global_replace re_generated ""
|> Str.global_replace re_partially_generated ""
|> Str.global_replace re_copyright1 ""
|> Str.global_replace re_copyright2 ""
|> Str.global_replace re_copyright3 ""
|> String.strip
let go_comments_from_source_text
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(line : int)
~(column : int)
~(kind : SymbolDefinition.kind) : string option =
let _ = ctx in
let filename = Relative_path.to_absolute entry.Provider_context.path in
let lp =
{
Lexing.pos_fname = filename;
pos_lnum = line;
pos_cnum = column;
pos_bol = 0;
}
in
let pos = Pos.make_from_lexing_pos filename lp lp in
let ffps_opt =
ServerSymbolDefinition.get_definition_cst_node_ctx ~ctx ~entry ~kind ~pos
in
match ffps_opt with
| None -> None
| Some ffps ->
(match Docblock_finder.get_docblock ffps with
| Some db -> Some (clean_comments db)
| None -> None)
(* Fetch a definition *)
let go_comments_for_symbol_ctx
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(def : 'a SymbolDefinition.t)
~(base_class_name : string option) : string option =
match def.SymbolDefinition.docblock with
| Some db -> Some (clean_comments db)
| None ->
(match
ServerSymbolDefinition.get_definition_cst_node_ctx
~ctx
~entry
~kind:def.SymbolDefinition.kind
~pos:def.SymbolDefinition.pos
with
| None -> None
| Some ffps ->
(match Docblock_finder.get_docblock ffps with
| Some db -> Some (clean_comments db)
| None ->
(match (def.SymbolDefinition.kind, base_class_name) with
| (SymbolDefinition.Method, Some base_class_name) ->
fallback ctx base_class_name def.SymbolDefinition.name
| _ -> None)))
(* Locate a symbol and return file, line, column, and base_class *)
let go_locate_symbol
~(ctx : Provider_context.t) ~(symbol : string) ~(kind : SearchTypes.si_kind)
: DocblockService.dbs_symbol_location_result =
(* Look up this class name *)
match SymbolIndexCore.get_position_for_symbol ctx symbol kind with
| None -> None
| Some (path, line, column) ->
let filename = Relative_path.to_absolute path in
(* Determine base class properly *)
let base_class_name =
match kind with
| SearchTypes.SI_Class
| SearchTypes.SI_Enum
| SearchTypes.SI_Function
| SearchTypes.SI_GlobalConstant
| SearchTypes.SI_Interface
| SearchTypes.SI_Trait
| SearchTypes.SI_Typedef ->
Some (Utils.add_ns symbol)
| _ -> None
in
(* Here are the results *)
Some
{
DocblockService.dbs_filename = filename;
dbs_line = line;
dbs_column = column;
dbs_base_class = base_class_name;
}
let symboldefinition_kind_from_si_kind (kind : SearchTypes.si_kind) :
SymbolDefinition.kind =
match kind with
| SearchTypes.SI_Class -> SymbolDefinition.Class
| SearchTypes.SI_Interface -> SymbolDefinition.Interface
| SearchTypes.SI_Enum -> SymbolDefinition.Enum
| SearchTypes.SI_Trait -> SymbolDefinition.Trait
| SearchTypes.SI_Unknown -> SymbolDefinition.Class
| SearchTypes.SI_Mixed -> SymbolDefinition.LocalVar
| SearchTypes.SI_Function -> SymbolDefinition.Function
| SearchTypes.SI_Typedef -> SymbolDefinition.Typedef
| SearchTypes.SI_GlobalConstant -> SymbolDefinition.GlobalConst
| SearchTypes.SI_XHP -> SymbolDefinition.Class
| SearchTypes.SI_ClassMethod -> SymbolDefinition.Method
| SearchTypes.SI_Literal -> SymbolDefinition.LocalVar
| SearchTypes.SI_ClassConstant -> SymbolDefinition.ClassConst
| SearchTypes.SI_Property -> SymbolDefinition.Property
| SearchTypes.SI_LocalVariable -> SymbolDefinition.LocalVar
| SearchTypes.SI_Constructor -> SymbolDefinition.Method
| SearchTypes.SI_Keyword -> failwith "Cannot look up a keyword"
| SearchTypes.SI_Namespace -> failwith "Cannot look up a namespace"
let rec go_docblock_ctx
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(line : int)
~(column : int)
~(kind : SearchTypes.si_kind) : DocblockService.result =
let def_kind = symboldefinition_kind_from_si_kind kind in
match
go_comments_from_source_text ~ctx ~entry ~line ~column ~kind:def_kind
with
| None ->
(* Special case: Classes with an assumed default constructor *)
if SearchTypes.equal_si_kind kind SearchTypes.SI_Constructor then
go_docblock_ctx ~ctx ~entry ~line ~column ~kind:SearchTypes.SI_Class
else
[]
| Some "" -> []
| Some comments -> [DocblockService.Markdown comments]
(* Locate a symbol and return its docblock, no extra steps *)
let go_docblock_for_symbol
~(ctx : Provider_context.t) ~(symbol : string) ~(kind : SearchTypes.si_kind)
: DocblockService.result =
(* Shortcut for namespaces, since they don't have locations *)
if SearchTypes.equal_si_kind kind SearchTypes.SI_Namespace then
let namespace_declaration = Printf.sprintf "namespace %s;" symbol in
[DocblockService.HackSnippet namespace_declaration]
else if SearchTypes.equal_si_kind kind SearchTypes.SI_Keyword then
let txt = Printf.sprintf "Hack language keyword: %s;" symbol in
[DocblockService.HackSnippet txt]
else
match go_locate_symbol ~ctx ~symbol ~kind with
| None ->
let msg =
Printf.sprintf
"Could not find the symbol '%s' (expected to be a %s). This symbol may need namespace information (e.g. HH\\a\\b\\c) to resolve correctly. You can also consider rebasing."
symbol
(SearchTypes.show_si_kind kind)
in
[DocblockService.Markdown msg]
| Some location ->
DocblockService.(
let (ctx, entry) =
Provider_context.add_entry_if_missing
~ctx
~path:(Relative_path.create_detect_prefix location.dbs_filename)
in
go_docblock_ctx
~ctx
~entry
~line:location.dbs_line
~column:location.dbs_column
~kind) |
OCaml Interface | hhvm/hphp/hack/src/server/serverDocblockAt.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.
*
*)
(** Returns the documentation comments for the given symbol or expression. *)
val go_comments_for_symbol_ctx :
ctx:Provider_context.t ->
entry:Provider_context.entry ->
def:'a SymbolDefinition.t ->
base_class_name:string option ->
string option
(** Returns the docblock from these file contents *)
val go_docblock_ctx :
ctx:Provider_context.t ->
entry:Provider_context.entry ->
line:int ->
column:int ->
kind:SearchTypes.si_kind ->
DocblockService.result
(** Simplified one-step symbol/docblock *)
val go_docblock_for_symbol :
ctx:Provider_context.t ->
symbol:string ->
kind:SearchTypes.si_kind ->
DocblockService.result
(** strips boilerplate copyright/codegen comments *)
val clean_comments : string -> string |
OCaml | hhvm/hphp/hack/src/server/serverEagerInit.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.
*
*)
(* Eager Initialization:
hh_server can initialize either by typechecking the entire project (aka
starting from a "fresh state") or by loading from a saved state and
typechecking what has changed. Historically, eager initialization was able to
do both, but we had little need for eager init from saved state, and removed
it.
If we perform an eager init from a fresh state, we run the following phases:
Parsing -> Naming -> Type-decl -> Type-check
If we are initializing lazily from a saved state, we do
Run load script and parsing concurrently -> Naming -> Type-check
Then we typecheck only the files that have changed since the state was saved.
Type-decl is performed lazily as needed.
*)
open Hh_prelude
open SearchServiceRunner
open ServerEnv
open ServerInitTypes
module SLC = ServerLocalConfig
let type_decl
(genv : ServerEnv.genv)
(env : ServerEnv.env)
(defs_per_file : Naming_table.defs_per_file)
(t : float) : ServerEnv.env * float =
ServerProgress.write "evaluating type declarations";
let bucket_size = genv.local_config.SLC.type_decl_bucket_size in
let ctx = Provider_utils.ctx_from_server_env env in
Decl_service.go ~bucket_size ctx genv.workers defs_per_file;
Stats.(stats.init_heap_size <- SharedMem.SMTelemetry.heap_size ());
HackEventLogger.type_decl_end t;
let t = Hh_logger.log_duration "Type-decl" t in
(env, t)
let init
(genv : ServerEnv.genv)
(lazy_level : lazy_level)
(env : ServerEnv.env)
(cgroup_steps : CgroupProfiler.step_group) : ServerEnv.env * float =
let init_telemetry =
ServerEnv.Init_telemetry.make
ServerEnv.Init_telemetry.Init_eager
(Telemetry.create ()
|> Telemetry.float_ ~key:"start_time" ~value:(Unix.gettimeofday ()))
in
(* Load and parse PACKAGES.toml if it exists at the root. *)
let (errors, package_info) = PackageConfig.load_and_parse () in
let tcopt =
{ env.ServerEnv.tcopt with GlobalOptions.tco_package_info = package_info }
in
let env =
ServerEnv.{ env with tcopt; errorl = Errors.merge env.errorl errors }
in
(* We don't support a saved state for eager init. *)
let (get_next, t) =
ServerInitCommon.directory_walk ~telemetry_label:"eager.init.indexing" genv
in
(* Parsing entire repo, too many files to trace *)
let trace = false in
let (env, t) =
ServerInitCommon.parse_files_and_update_forward_naming_table
genv
env
~get_next
t
~trace
~cache_decls:true
~telemetry_label:"eager.init.parsing"
~cgroup_steps
~worker_call:MultiWorker.wrapper
in
if not (ServerArgs.check_mode genv.options) then
SearchServiceRunner.update_fileinfo_map
env.naming_table
~source:SearchUtils.Init;
let (env, t) =
ServerInitCommon
.update_reverse_naming_table_from_env_and_get_duplicate_name_errors
env
t
~telemetry_label:"eager.init.naming"
~cgroup_steps
in
ServerInitCommon.validate_no_errors env.errorl;
let defs_per_file = Naming_table.to_defs_per_file env.naming_table in
let (env, t) =
match lazy_level with
| Off -> type_decl genv env defs_per_file t
| _ -> (env, t)
in
(* Type-checking everything *)
ServerInitCommon.defer_or_do_type_check
genv
env
(Relative_path.Map.keys defs_per_file)
init_telemetry
t
~telemetry_label:"eager.init.type_check"
~cgroup_steps |
OCaml Interface | hhvm/hphp/hack/src/server/serverEagerInit.mli | (*
* 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 ServerInitTypes
val init :
ServerEnv.genv ->
lazy_level ->
ServerEnv.env ->
CgroupProfiler.step_group ->
ServerEnv.env * float |
OCaml | hhvm/hphp/hack/src/server/serverEnv.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 Option.Monad_infix
(*****************************************************************************)
(* Recheck loop types. *)
(*****************************************************************************)
type seconds = float
type seconds_since_epoch = float
module RecheckLoopStats = struct
type t = {
updates_stale: bool;
(** Watchman subscription has gone down, so state of the world after the
recheck loop may not reflect what is actually on disk. *)
per_batch_telemetry: Telemetry.t list;
total_changed_files_count: int;
(** Count of files changed on disk and potentially also in the IDE. *)
total_rechecked_count: int;
last_iteration_start_time: seconds_since_epoch;
duration: seconds;
time_first_result: seconds_since_epoch option;
recheck_id: string;
any_full_checks: bool;
}
let empty ~(recheck_id : string) : t =
{
updates_stale = false;
per_batch_telemetry = [];
total_changed_files_count = 0;
total_rechecked_count = 0;
last_iteration_start_time = 0.;
duration = 0.;
time_first_result = None;
recheck_id;
any_full_checks = false;
}
(** The format of this json is user-facing, returned from 'hh check --json' *)
let to_user_telemetry (stats : t) : Telemetry.t =
let {
updates_stale;
per_batch_telemetry;
total_changed_files_count;
total_rechecked_count;
last_iteration_start_time;
duration;
time_first_result;
recheck_id;
any_full_checks;
} =
stats
in
Telemetry.create ()
|> Telemetry.string_ ~key:"id" ~value:recheck_id
|> Telemetry.float_ ~key:"time" ~value:duration
|> Telemetry.int_ ~key:"count" ~value:total_rechecked_count
|> Telemetry.int_
~key:"total_changed_files_count"
~value:total_changed_files_count
|> Telemetry.object_list
~key:"per_batch"
~value:(List.rev per_batch_telemetry)
|> Telemetry.bool_ ~key:"updates_stale" ~value:updates_stale
|> Telemetry.bool_ ~key:"any_full_checks" ~value:any_full_checks
|> Telemetry.int_opt
~key:"time_to_first_result_ms"
~value:
( time_first_result >>| fun time ->
int_of_float ((time -. last_iteration_start_time) *. 1000.) )
(** Update field [time_first_result] if given timestamp is the
first sent result. *)
let record_result_sent_ts stats new_result_sent_ts =
{
stats with
time_first_result =
Option.first_some stats.time_first_result new_result_sent_ts;
}
end
(*****************************************************************************)
(** The "static" environment, initialized first and then doesn't change *)
type genv = {
options: ServerArgs.options;
config: ServerConfig.t;
local_config: ServerLocalConfig.t;
workers: MultiWorker.worker list option;
notifier: ServerNotifier.t;
indexer: (string -> bool) -> unit -> string list;
(** Returns the list of files under .hhconfig, subject to a filter *)
mutable debug_channels: (Timeout.in_channel * Out_channel.t) option;
}
(*****************************************************************************)
(** The environment constantly maintained by the server *)
(*****************************************************************************)
type full_check_status =
| Full_check_needed
(** Some updates have not been fully processed. We get into this state every
time file contents change (on disk, or through IDE notifications).
Operations that depend on global state (like taking full error list, or
looking up things in dependency table) will have stale results. *)
| Full_check_started
(** Same as above, except server will actively try to process outstanding
changes (by going into ServerTypeCheck from main loop - this might need to
be repeated several times before progressing to Full_check_done, due to
ability to interrupt typecheck jobs).
Server starts in this state, and we also enter it from Full_check_needed
whenever there is a command requiring full check pending, or when user
saves a file. *)
| Full_check_done (** All the changes have been fully processed. *)
[@@deriving show]
let is_full_check_done = function
| Full_check_done -> true
| _ -> false
let is_full_check_needed = function
| Full_check_needed -> true
| _ -> false
let is_full_check_started = function
| Full_check_started -> true
| _ -> false
module Init_telemetry = struct
type reason =
| Init_lazy_dirty
| Init_typecheck_disabled_after_init
| Init_eager
| Init_lazy_full
| Init_prechecked_fanout
[@@deriving show { with_path = false }]
type t = {
reason: reason;
telemetry: Telemetry.t;
}
let make reason telemetry = { reason; telemetry }
let get { reason; telemetry } =
telemetry |> Telemetry.string_ ~key:"reason" ~value:(show_reason reason)
let get_reason { reason; _ } = show_reason reason
end
(** How "old" a given saved state is relative to the working revision.
That is, a saved state has some corresponding revision X, and `hh` is invoked on a commit
of mergebase Y.
Distance tracks the number of revisions between X and Y, using globalrev.
Age tracks the time elapsed between X and Y in seconds, according to hg log data.
*)
type saved_state_delta = {
distance: int;
age: int;
}
[@@deriving show]
(** In addition to this environment, many functions are storing and
updating ASTs, NASTs, and types in a shared space
(see respectively Parser_heap, Naming_table, Typing_env).
The Ast.id are keys to index this shared space. *)
type env = {
naming_table: Naming_table.t;
deps_mode: Typing_deps_mode.t; [@opaque]
tcopt: TypecheckerOptions.t;
popt: ParserOptions.t;
gleanopt: GleanOptions.t;
swriteopt: SymbolWriteOptions.t;
errorl: Errors.t; [@opaque]
(** Errors are indexed by files that were known to GENERATE errors in
corresponding phases. Note that this is different from HAVING errors -
it's possible for checking of A to generate error in B - in this case
Errors.get_failed_files Typing should contain A, not B.
Conversly, if declaring A will require declaring B, we should put
B in failed decl. Same if checking A will cause declaring B (via lazy
decl).
During recheck, we add those files to the set of files to reanalyze
at each stage in order to regenerate their error lists. So those
failed_ sets are the main piece of mutable state that incremental mode
needs to maintain - the errors themselves are more of a cache, and should
always be possible to be regenerated based on those sets. *)
failed_naming: Relative_path.Set.t;
(** failed_naming is used as kind of a dependency tracking mechanism:
if files A.php and B.php both define class C, then those files are
mutually depending on each other (edit to one might resolve naming
ambiguity and change the interpretation of the other). Both of those
files being inside failed_naming is how we track the need to
check for this condition.
See test_naming_errors.ml and test_failed_naming.ml *)
ide_idle: bool; (** Whether last received IDE command was IDE_IDLE *)
last_command_time: float;
(** Timestamp of last IDE file synchronization command *)
last_notifier_check_time: float;
(** Timestamp of last query for disk changes *)
last_idle_job_time: float; (** Timestamp of last ServerIdle.go run *)
editor_open_files: Relative_path.Set.t;
(** The map from full path to synchronized file contents *)
ide_needs_parsing: Relative_path.Set.t;
(** Files which parse trees were invalidated (because they changed on disk
or in editor) and need to be re-parsed *)
disk_needs_parsing: Relative_path.Set.t;
clock: Watchman.clock option;
(** This is the clock as of when disk_needs_parsing was last updated.
None if not using Watchman. *)
needs_phase2_redecl: Relative_path.Set.t;
(** Declarations that became invalidated and moved to "old" part of the heap.
We keep them there to be used in "determining changes" step of recheck.
(when they are compared to "new" versions). Depending on lazy decl to
compute "new" versions in all the other scenarios (like IDE queries) *)
needs_recheck: Relative_path.Set.t;
(** Files that need to be typechecked before commands that depend on global
state (like full list of errors, build, or find all references) can be
executed . After full check this should be empty, unless that check was
cancelled mid-flight, in which case full_check_status will be set to
Full_check_started and entire thing will be retried on next iteration. *)
why_needs_server_type_check: string * string;
init_env: init_env;
full_recheck_on_file_changes: full_recheck_on_file_changes;
(** Set by `hh --pause` or `hh --resume`. Indicates whether full/global recheck
should be triggered on file changes. If paused, it would still be triggered
by commands that require a full recheck, such as STATUS, i.e., `hh`
on the command line. *)
full_check_status: full_check_status;
prechecked_files: prechecked_files_status;
changed_files: Relative_path.Set.t;
can_interrupt: bool;
(** Not every caller of rechecks expects that they can be interrupted,
so making it opt-in by setting this flag at call site *)
interrupt_handlers:
genv ->
env ->
(Unix.file_descr * env MultiThreadedCall.interrupt_handler) list;
remote: bool; (** Whether we should force remote type checking or not *)
pending_command_needs_writes: (env -> env) option;
(** When persistent client sends a command that cannot be handled (due to
thread safety, e.g. opening, closing, editing files)
we put the continuation that finishes handling it here. *)
persistent_client_pending_command_needs_full_check:
((env -> env) * string) option;
(** When the persistent client sends a command that cannot be immediately handled
(due to needing full check) we put the continuation that finishes handling
it here. The string specifies a reason why this command needs full
recheck (for logging/debugging purposes) *)
nonpersistent_client_pending_command_needs_full_check:
((env -> env) * string * ClientProvider.client) option;
[@opaque]
(** When a non-persistent client sends a command that cannot be immediately handled
(due to needing full check) we put the continuation that finishes handling
it here. The string specifies a reason why this command needs full
recheck (for logging/debugging purposes) *)
diagnostic_pusher: Diagnostic_pusher.t;
(** Structure tracking errors to push to LSP client. *)
last_recheck_loop_stats: RecheckLoopStats.t; [@opaque]
last_recheck_loop_stats_for_actual_work: RecheckLoopStats.t option; [@opaque]
local_symbol_table: SearchUtils.si_env; [@opaque]
(** Symbols for locally changed files *)
}
[@@deriving show]
(** Global rechecks in response to file changes can be paused. If the user
changes the state to `Paused` during an ongoing recheck, we should cancel
that recheck.
The effect of the `PAUSE true` RPC during a recheck is that the recheck will
be canceled, while the result of `PAUSE false` is that the client will wait
for the recheck to be finished.
NOTE:
Interrupt handlers are currently set up and used during type checking.
MultiWorker executor (MultiThreadedCall) selects worker file descriptors as
well as some input channels from clients. If a client is sending an RPC over
such a channel, the executor will call that channel's designated handler.
`ServerMain` sets up a few of these handlers, and the one we're interested in
for this change is the __priority__ client interrupt handler. This handler is
only listening to RPCs sent over the priority channel. The client decides
which RPCs are sent over the priority channel vs. the default channel.
In the priority client interrupt handler, we actually handle the RPC that
the client is sending. We then return the updated environment to
the MultiWorker executor, along with the decision on whether it should
continue executing or cancel. We examine the environment after handling
the RPC to check whether the user paused file changes-driven global rechecks
during the *current* recheck. If that is the case, then the current recheck
will be canceled.
The reason we care about whether it's the current recheck that's paused or
some other one is because global rechecks can still happen even if
*file changes-driven* global rechecks are paused. This is because the user
can explicitly request a full recheck by running an `hh_client` command that
*requires* a full recheck. There are a number of such commands, but the most
obvious one is just `hh` (defaults to `hh check`).
It is possible to immediately set the server into paused mode AND cancel
the current recheck. There are two cases the user might wish to do this in:
1) The user notices that some change they made is taking a while to
recheck, so they want to cancel the recheck because they want to make
further changes, or retry the recheck with the `--remote` argument
2) While the server is in the paused state, the user explicitly starts
a full recheck, but then decides that they want to cancel it
In both cases, running `hh --pause` on the command line should stop
the recheck if it's in the middle of the type checking phase.
Note that interrupts are only getting set up for the type checking phase,
so if the server is in the middle of, say, the redecl phase, it's not going
to be interrupted until it gets to the type checking itself. In some cases,
redecling can be very costly. For example, if we redecl using the folded decl
approach, adding `extends ISomeInterface` to `IBaseInterface` that has many
descendants (implementers and their descendants) requires redeclaring all
the descendants of `IBaseInterface`. However, redecling using the shallow
decl approach should be considerably less costly, therefore it may not be
worth it to support interrupting redecling. *)
and full_recheck_on_file_changes =
| Not_paused
| Paused of paused_env
| Resumed
and paused_env = { paused_recheck_id: string option }
and dirty_deps = {
dirty_local_deps: Typing_deps.DepSet.t;
(** We are rechecking dirty files to bootstrap the dependency graph.
After this is done we need to also recheck full fan-out (in this updated
graph) of provided set. *)
dirty_master_deps: Typing_deps.DepSet.t;
(** The fan-outs of those nodes were not expanded yet. *)
rechecked_files: Relative_path.Set.t;
(** Files that have been rechecked since server startup *)
clean_local_deps: Typing_deps.DepSet.t;
(** Those deps have already been checked against their interaction with
dirty_master_deps. Storing them here to avoid checking it over and over *)
}
(** When using prechecked files we split initial typechecking in two phases
(dirty files and a subset of their fan-out). Other init types compute the
full fan-out up-front. *)
and prechecked_files_status =
| Prechecked_files_disabled
| Initial_typechecking of dirty_deps
| Prechecked_files_ready of dirty_deps
and init_env = {
approach_name: string;
ci_info: Ci_util.info option Future.t option; [@opaque]
(** The info describing the CI job the server is a part of, if any *)
init_error: string option;
init_id: string;
init_start_t: float;
init_type: string;
mergebase: string option;
why_needed_full_check: Init_telemetry.t option; [@opaque]
(** This is about the first full check (if any) which was deferred after init.
It gets reset after that first full check is completed.
First parameter is a string label used in telemetry. Second is opaque telemetry. *)
recheck_id: string option;
(* Additional data associated with init that we want to log when a first full
* check completes. *)
saved_state_delta: saved_state_delta option;
naming_table_manifold_path: string option;
(** The manifold path for remote typechecker workers to download the naming table
saved state. This value will be None in the case of full init *)
}
let list_files env =
let acc =
List.fold_right
~f:
begin
fun error (acc : SSet.t) ->
let pos = User_error.get_pos error in
SSet.add (Relative_path.to_absolute (Pos.filename pos)) acc
end
~init:SSet.empty
(Errors.get_error_list env.errorl)
in
SSet.elements acc
let add_changed_files env changed_files =
{
env with
changed_files = Relative_path.Set.union env.changed_files changed_files;
}
let show_clock (clock : Watchman.clock option) : string =
Option.value clock ~default:"[noclock]" |
OCaml Interface | hhvm/hphp/hack/src/server/serverEnv.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
type seconds = float
type seconds_since_epoch = float
(** The "static" environment, initialized first and then doesn't change *)
type genv = {
options: ServerArgs.options;
config: ServerConfig.t;
local_config: ServerLocalConfig.t;
workers: MultiWorker.worker list option;
(** Early-initialized workers to be used in MultiWorker jobs
They are initialized early to keep their heaps as empty as possible. *)
notifier: ServerNotifier.t; (** Common abstraction for watchman/dfind *)
indexer: (string -> bool) -> unit -> string list;
(** Returns the list of files under .hhconfig, subject to a filter.
TODO: this indexer should be moved to a member of ServerNotifier,
but can't because zoncolan needs to tweak it. *)
mutable debug_channels: (Timeout.in_channel * Out_channel.t) option;
}
module Init_telemetry : sig
(** These names appear in telemetry, where it's nice to see the word "Init" in them. *)
type reason =
| Init_lazy_dirty (** normal saved-state init *)
| Init_typecheck_disabled_after_init (** I don't know what this is for *)
| Init_eager (** full init *)
| Init_lazy_full (** failed a saved-state init, and fell back to full *)
| Init_prechecked_fanout (** I don't know what this is for *)
(** This is telemetry, generated by ServerInit, to explain in subsequent
events why ServerMain's first full check had to happen. *)
type t
val make : reason -> Telemetry.t -> t
val get : t -> Telemetry.t
val get_reason : t -> string
end
(** How "old" a given saved state is relative to the working revision.
That is, a saved state has some corresponding revision X, and `hh` is invoked on a commit
of mergebase Y.
Distance tracks the number of revisions between X and Y, using globalrev.
Age tracks the time elapsed between X and Y in seconds, according to hg log data.
*)
type saved_state_delta = {
distance: int;
age: int;
}
[@@deriving show]
type init_env = {
approach_name: string;
ci_info: Ci_util.info option Future.t option; [@opaque]
(** The info describing the CI job the server is a part of, if any *)
init_error: string option;
init_id: string;
init_start_t: float;
init_type: string;
mergebase: string option;
why_needed_full_check: Init_telemetry.t option;
(** This is about the first full check (if any) which was deferred after init.
It gets reset after that first full check is completed.
First parameter is a string label used in telemetry. Second is opaque telemetry. *)
recheck_id: string option;
(* Additional data associated with init that we want to log when a first full
* check completes. *)
saved_state_delta: saved_state_delta option;
naming_table_manifold_path: string option;
(** The manifold path for remote typechecker workers to download the naming table
saved state. This value will be None in the case of full init *)
}
type paused_env = { paused_recheck_id: string option }
(** Global rechecks in response to file changes can be paused. If the user
changes the state to `Paused` during an ongoing recheck, we should cancel
that recheck.
The effect of the `PAUSE true` RPC during a recheck is that the recheck will
be canceled, while the result of `PAUSE false` is that the client will wait
for the recheck to be finished.
NOTE:
Interrupt handlers are currently set up and used during type checking.
MultiWorker executor (MultiThreadedCall) selects worker file descriptors as
well as some input channels from clients. If a client is sending an RPC over
such a channel, the executor will call that channel's designated handler.
`ServerMain` sets up a few of these handlers, and the one we're interested in
for this change is the __priority__ client interrupt handler. This handler is
only listening to RPCs sent over the priority channel. The client decides
which RPCs are sent over the priority channel vs. the default channel.
In the priority client interrupt handler, we actually handle the RPC that
the client is sending. We then return the updated environment to
the MultiWorker executor, along with the decision on whether it should
continue executing or cancel. We examine the environment after handling
the RPC to check whether the user paused file changes-driven global rechecks
during the *current* recheck. If that is the case, then the current recheck
will be canceled.
The reason we care about whether it's the current recheck that's paused or
some other one is because global rechecks can still happen even if
*file changes-driven* global rechecks are paused. This is because the user
can explicitly request a full recheck by running an `hh_client` command that
*requires* a full recheck. There are a number of such commands, but the most
obvious one is just `hh` (defaults to `hh check`).
It is possible to immediately set the server into paused mode AND cancel
the current recheck. There are two cases the user might wish to do this in:
1) The user notices that some change they made is taking a while to
recheck, so they want to cancel the recheck because they want to make
further changes, or retry the recheck with the `--remote` argument
2) While the server is in the paused state, the user explicitly starts
a full recheck, but then decides that they want to cancel it
In both cases, running `hh --pause` on the command line should stop
the recheck if it's in the middle of the type checking phase.
Note that interrupts are only getting set up for the type checking phase,
so if the server is in the middle of, say, the redecl phase, it's not going
to be interrupted until it gets to the type checking itself. In some cases,
redecling can be very costly. For example, if we redecl using the folded decl
approach, adding `extends ISomeInterface` to `IBaseInterface` that has many
descendants (implementers and their descendants) requires redeclaring all
the descendants of `IBaseInterface`. However, redecling using the shallow
decl approach should be considerably less costly, therefore it may not be
worth it to support interrupting redecling. *)
type full_recheck_on_file_changes =
| Not_paused
| Paused of paused_env
| Resumed
type full_check_status =
| Full_check_needed
(** Some updates have not been fully processed. We get into this state every
time file contents change (on disk, or through IDE notifications).
Operations that depend on global state (like taking full error list, or
looking up things in dependency table) will have stale results. *)
| Full_check_started
(** Same as above, except server will actively try to process outstanding
changes (by going into ServerTypeCheck from main loop - this might need to
be repeated several times before progressing to Full_check_done, due to
ability to interrupt typecheck jobs).
Server starts in this state, and we also enter it from Full_check_needed
whenever there is a command requiring full check pending, or when user
saves a file. *)
| Full_check_done (** All the changes have been fully processed. *)
[@@deriving show]
type dirty_deps = {
dirty_local_deps: Typing_deps.DepSet.t;
(** We are rechecking dirty files to bootstrap the dependency graph.
After this is done we need to also recheck full fan-out (in this updated
graph) of provided set. *)
dirty_master_deps: Typing_deps.DepSet.t;
(** The fan-outs of those nodes were not expanded yet. *)
rechecked_files: Relative_path.Set.t;
(** Files that have been rechecked since server startup *)
clean_local_deps: Typing_deps.DepSet.t;
(** Those deps have already been checked against their interaction with
dirty_master_deps. Storing them here to avoid checking it over and over *)
}
(** When using prechecked files we split initial typechecking in two phases
(dirty files and a subset of their fan-out). Other init types compute the
full fan-out up-front. *)
type prechecked_files_status =
| Prechecked_files_disabled
| Initial_typechecking of dirty_deps
| Prechecked_files_ready of dirty_deps
module RecheckLoopStats : sig
type t = {
updates_stale: bool;
(** Watchman subscription has gone down, so state of the world after the
recheck loop may not reflect what is actually on disk. *)
per_batch_telemetry: Telemetry.t list;
total_changed_files_count: int;
(** Count of files changed on disk and potentially also in the IDE. *)
total_rechecked_count: int;
last_iteration_start_time: seconds_since_epoch;
(** Start time of the last loop iteration, after the last user change. *)
duration: seconds;
time_first_result: seconds_since_epoch option;
(** This is either the duration to get the first error if any
or until we get "typecheck done" status message.
This is originally None when no result has been sent yet,
and should be [Some timestamp] at the end of the loop. *)
recheck_id: string;
any_full_checks: bool;
}
val empty : recheck_id:string -> t
(** The format of this json is user-facing, returned from 'hh check --json' *)
val to_user_telemetry : t -> Telemetry.t
(** Update field [time_first_result] if given timestamp is the
first sent result. *)
val record_result_sent_ts : t -> seconds_since_epoch option -> t
end
(** The environment constantly maintained by the server.
In addition to this environment, many functions are storing and
updating ASTs, NASTs, and types in a shared space
(see respectively Parser_heap, Naming_table, Typing_env).
The Ast.id are keys to index this shared space. *)
type env = {
naming_table: Naming_table.t;
deps_mode: Typing_deps_mode.t;
tcopt: TypecheckerOptions.t;
popt: ParserOptions.t;
gleanopt: GleanOptions.t;
swriteopt: SymbolWriteOptions.t;
errorl: Errors.t; [@opaque]
(** Errors are indexed by files that were known to GENERATE errors in
corresponding phases. Note that this is different from HAVING errors -
it's possible for checking of A to generate error in B - in this case
Errors.get_failed_files Typing should contain A, not B.
Conversly, if declaring A will require declaring B, we should put
B in failed decl. Same if checking A will cause declaring B (via lazy
decl).
During recheck, we add those files to the set of files to reanalyze
at each stage in order to regenerate their error lists. So those
failed_ sets are the main piece of mutable state that incremental mode
needs to maintain - the errors themselves are more of a cache, and should
always be possible to be regenerated based on those sets. *)
failed_naming: Relative_path.Set.t;
(** failed_naming is used as kind of a dependency tracking mechanism:
if files A.php and B.php both define class C, then those files are
mutually depending on each other (edit to one might resolve naming
ambiguity and change the interpretation of the other). Both of those
files being inside failed_naming is how we track the need to
check for this condition.
See test_naming_errors.ml and test_failed_naming.ml *)
ide_idle: bool; (** Whether last received IDE command was IDE_IDLE *)
last_command_time: float;
(** Timestamp of last IDE file synchronization command *)
last_notifier_check_time: float;
(** Timestamp of last query for disk changes *)
last_idle_job_time: float; (** Timestamp of last ServerIdle.go run *)
editor_open_files: Relative_path.Set.t;
(** The map from full path to synchronized file contents *)
ide_needs_parsing: Relative_path.Set.t;
(** Files which parse trees were invalidated (because they changed on disk
or in editor) and need to be re-parsed *)
disk_needs_parsing: Relative_path.Set.t;
clock: Watchman.clock option;
(** This is the clock as of when disk_needs_parsing was last updated.
None if not using Watchman. *)
needs_phase2_redecl: Relative_path.Set.t;
(** Declarations that became invalidated and moved to "old" part of the heap.
We keep them there to be used in "determining changes" step of recheck.
(when they are compared to "new" versions). Depending on lazy decl to
compute "new" versions in all the other scenarios (like IDE queries) *)
needs_recheck: Relative_path.Set.t;
(** Files that need to be typechecked before commands that depend on global
state (like full list of errors, build, or find all references) can be
executed . After full check this should be empty, unless that check was
cancelled mid-flight, in which case full_check_status will be set to
Full_check_started and entire thing will be retried on next iteration. *)
why_needs_server_type_check: string * string;
(** Why is a round of ServerTypeCheck needed? For instance, if a typecheck
got interrupted+cancelled leaving files still needing to be checked, the
reason will be stored here. It's written+read by [ServerTypeCheck.type_check].
The first of the two strings is a user-facing message, and the second is additional
information for logs. *)
init_env: init_env;
full_recheck_on_file_changes: full_recheck_on_file_changes;
(** Set by `hh --pause` or `hh --resume`. Indicates whether full/global recheck
should be triggered on file changes. If paused, it would still be triggered
by commands that require a full recheck, such as STATUS, i.e., `hh`
on the command line. *)
full_check_status: full_check_status;
prechecked_files: prechecked_files_status;
changed_files: Relative_path.Set.t;
can_interrupt: bool;
(** Not every caller of rechecks expects that they can be interrupted,
so making it opt-in by setting this flag at call site *)
interrupt_handlers:
genv ->
env ->
(Unix.file_descr * env MultiThreadedCall.interrupt_handler) list;
remote: bool; (** Whether we should force remote type checking or not *)
pending_command_needs_writes: (env -> env) option;
(** When persistent client sends a command that cannot be handled (due to
thread safety) we put the continuation that finishes handling it here. *)
persistent_client_pending_command_needs_full_check:
((env -> env) * string) option;
(** When the persistent client sends a command that cannot be immediately handled
(due to needing full check) we put the continuation that finishes handling
it here. The string specifies a reason why this command needs full
recheck (for logging/debugging purposes) *)
nonpersistent_client_pending_command_needs_full_check:
((env -> env) * string * ClientProvider.client) option;
[@opaque]
(** When a non-persistent client sends a command that cannot be immediately handled
(due to needing full check) we put the continuation that finishes handling
it here. The string specifies a reason why this command needs full
recheck (for logging/debugging purposes) *)
diagnostic_pusher: Diagnostic_pusher.t;
(** Structure tracking errors to push to LSP client. *)
last_recheck_loop_stats: RecheckLoopStats.t;
last_recheck_loop_stats_for_actual_work: RecheckLoopStats.t option;
local_symbol_table: SearchUtils.si_env; [@opaque]
(** Symbols for locally changed files *)
}
[@@deriving show]
val is_full_check_done : full_check_status -> bool
val is_full_check_needed : full_check_status -> bool
val is_full_check_started : full_check_status -> bool
val list_files : env -> string list
val add_changed_files : env -> Relative_path.Set.t -> env
val show_clock : Watchman.clock option -> string |
OCaml | hhvm/hphp/hack/src/server/serverEnvBuild.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.
*
*)
(*****************************************************************************)
(* Building the environment *)
(*****************************************************************************)
open Hh_prelude
open ServerEnv
let make_genv options config local_config workers =
Typing_deps.trace :=
(not (ServerArgs.check_mode options))
|| Option.is_some (ServerArgs.save_filename options);
let (notifier, indexer) =
ServerNotifier.init options local_config ~num_workers:(List.length workers)
in
{
options;
config;
local_config;
workers = Some workers;
notifier;
indexer;
debug_channels = None;
}
(* useful in testing code *)
let default_genv =
{
options = ServerArgs.default_options ~root:"";
config = ServerConfig.default_config;
local_config = ServerLocalConfig.default;
workers = None;
notifier = ServerNotifier.init_null ();
indexer = (fun _ () -> []);
debug_channels = None;
}
let make_env ~init_id ~deps_mode config : ServerEnv.env =
{
tcopt = ServerConfig.typechecker_options config;
popt = ServerConfig.parser_options config;
gleanopt = ServerConfig.glean_options config;
swriteopt = ServerConfig.symbol_write_options config;
naming_table = Naming_table.empty;
deps_mode;
errorl = Errors.empty;
failed_naming = Relative_path.Set.empty;
ide_idle = true;
last_command_time = 0.0;
last_notifier_check_time = 0.0;
last_idle_job_time = 0.0;
editor_open_files = Relative_path.Set.empty;
ide_needs_parsing = Relative_path.Set.empty;
disk_needs_parsing = Relative_path.Set.empty;
clock = None;
needs_phase2_redecl = Relative_path.Set.empty;
needs_recheck = Relative_path.Set.empty;
full_recheck_on_file_changes = Not_paused;
remote = false;
full_check_status = Full_check_done;
changed_files = Relative_path.Set.empty;
prechecked_files = Prechecked_files_disabled;
can_interrupt = true;
interrupt_handlers = (fun _ _ -> []);
pending_command_needs_writes = None;
persistent_client_pending_command_needs_full_check = None;
nonpersistent_client_pending_command_needs_full_check = None;
why_needs_server_type_check = ("init", "");
init_env =
{
approach_name = "";
ci_info = None;
init_error = None;
init_id;
init_start_t = Unix.gettimeofday ();
init_type = "";
mergebase = None;
why_needed_full_check = None;
recheck_id = None;
saved_state_delta = None;
naming_table_manifold_path = None;
};
diagnostic_pusher = Diagnostic_pusher.init;
last_recheck_loop_stats = RecheckLoopStats.empty ~recheck_id:"<none>";
last_recheck_loop_stats_for_actual_work = None;
local_symbol_table = SearchUtils.default_si_env;
} |
OCaml Interface | hhvm/hphp/hack/src/server/serverEnvBuild.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.
*
*)
val make_genv :
ServerArgs.options ->
ServerConfig.t ->
ServerLocalConfig.t ->
MultiWorker.worker list ->
ServerEnv.genv
val default_genv : ServerEnv.genv
val make_env :
init_id:string ->
deps_mode:Typing_deps_mode.t ->
ServerConfig.t ->
ServerEnv.env |
OCaml | hhvm/hphp/hack/src/server/serverError.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.
*
*)
(*****************************************************************************)
(* Error module *)
(*****************************************************************************)
open Hh_prelude
let get_save_state_result_props_json
(save_state_result : SaveStateServiceTypes.save_state_result) :
(string * Hh_json.json) list =
SaveStateServiceTypes.
[
( "dep_table_edges_added",
Hh_json.int_ save_state_result.dep_table_edges_added );
]
let get_save_state_result_json
(save_state_result : SaveStateServiceTypes.save_state_result) :
string * Hh_json.json =
( "save_state_result",
Hh_json.JSON_Object (get_save_state_result_props_json save_state_result) )
let get_error_list_json
(error_list : Errors.finalized_error list)
~(save_state_result : SaveStateServiceTypes.save_state_result option)
~(recheck_stats : Telemetry.t option) =
let (error_list, did_pass) =
match error_list with
| [] -> ([], true)
| error_list -> (List.map ~f:User_error.to_json error_list, false)
in
let (properties : (string * Hh_json.json) list) =
[
("passed", Hh_json.JSON_Bool did_pass);
("errors", Hh_json.JSON_Array error_list);
("version", Hh_version.version_json);
]
in
let properties =
match save_state_result with
| None -> properties
| Some save_state_result ->
let save_state_result_json =
get_save_state_result_json save_state_result
in
save_state_result_json :: properties
in
let properties =
match recheck_stats with
| None -> properties
| Some telemetry ->
("last_recheck", Telemetry.to_json telemetry) :: properties
in
Hh_json.JSON_Object properties
let print_error_list_json
(oc : Out_channel.t)
(error_list : Errors.finalized_error list)
(save_state_result : SaveStateServiceTypes.save_state_result option)
(recheck_stats : Telemetry.t option) =
let res = get_error_list_json error_list ~save_state_result ~recheck_stats in
Hh_json.json_to_output oc res;
Out_channel.flush oc
let print_error_list
(oc : Out_channel.t)
~(stale_msg : string option)
~(output_json : bool)
~(error_list : Errors.finalized_error list)
~(save_state_result : SaveStateServiceTypes.save_state_result option)
~(recheck_stats : Telemetry.t option) =
(if output_json then
print_error_list_json oc error_list save_state_result recheck_stats
else if List.is_empty error_list then
Out_channel.output_string oc "No errors!\n"
else
let sl = List.map ~f:Errors.to_string error_list in
let sl = List.dedup_and_sort ~compare:String.compare sl in
List.iter
~f:
begin
fun s ->
Out_channel.output_string oc s;
Out_channel.output_string oc "\n"
end
sl);
Option.iter stale_msg ~f:(fun msg -> Out_channel.output_string oc msg);
Out_channel.flush oc |
OCaml | hhvm/hphp/hack/src/server/serverExtractStandalone.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
module Fmt = Format_helpers
module Cmd = ServerCommandTypes.Extract_standalone
module SourceText = Full_fidelity_source_text
module Syntax = Full_fidelity_positioned_syntax
module SyntaxTree = Full_fidelity_syntax_tree.WithSyntax (Syntax)
module SyntaxError = Full_fidelity_syntax_error
module SN = Naming_special_names
module Class = Decl_provider.Class
(* -- Exceptions ------------------------------------------------------------ *)
(* Internal error: for example, we are generating code for a dependency on an
enum, but the passed dependency is not an enum *)
exception UnexpectedDependency
exception DependencyNotFound of string
exception Unsupported
let value_exn ex opt =
match opt with
| Some s -> s
| None -> raise ex
let value_or_not_found err_msg opt = value_exn (DependencyNotFound err_msg) opt
(* -- Pretty-printing constants --------------------------------------------- *)
let __CONST_DEFAULT__ = "EXTRACT_STANDALONE_DEFAULT"
let __FILE_PREFIX__ = "////"
let __DUMMY_FILE__ = "__extract_standalone__.php"
let __UNKNOWN_FILE__ = "__unknown__.php"
let __HH_HEADER_PREFIX__ = "<?hh"
(* -- Decl_provider helpers ------------------------------------------------- *)
module Decl : sig
val get_class_exn :
Provider_context.t -> Decl_provider.type_key -> Decl_provider.class_decl
val get_class_pos :
Provider_context.t -> Decl_provider.type_key -> Pos.t option
val get_class_pos_exn : Provider_context.t -> Decl_provider.type_key -> Pos.t
val get_fun_pos : Provider_context.t -> Decl_provider.fun_key -> Pos.t option
val get_fun_pos_exn : Provider_context.t -> Decl_provider.fun_key -> Pos.t
val get_typedef_pos :
Provider_context.t -> Decl_provider.type_key -> Pos.t option
val get_gconst_pos :
Provider_context.t -> Decl_provider.gconst_key -> Pos.t option
val get_class_or_typedef_pos : Provider_context.t -> string -> Pos.t option
val get_module_pos :
Provider_context.t -> Decl_provider.module_key -> Pos.t option
end = struct
let get_class_exn ctx name =
let not_found_msg = Printf.sprintf "Class %s" name in
value_or_not_found not_found_msg @@ Decl_provider.get_class ctx name
let get_fun_pos ctx name =
Decl_provider.get_fun ctx name
|> Option.map
~f:
Typing_defs.(
(fun decl -> decl.fe_pos |> Naming_provider.resolve_position ctx))
let get_fun_pos_exn ctx name = value_or_not_found name (get_fun_pos ctx name)
let get_class_pos ctx name =
Decl_provider.get_class ctx name
|> Option.map ~f:(fun decl ->
Class.pos decl |> Naming_provider.resolve_position ctx)
let get_class_pos_exn ctx name =
value_or_not_found name (get_class_pos ctx name)
let get_typedef_pos ctx name =
Decl_provider.get_typedef ctx name
|> Option.map
~f:
Typing_defs.(
(fun decl -> decl.td_pos |> Naming_provider.resolve_position ctx))
let get_gconst_pos ctx name =
Decl_provider.get_gconst ctx name
|> Option.map ~f:(fun const ->
const.Typing_defs.cd_pos |> Naming_provider.resolve_position ctx)
let get_class_or_typedef_pos ctx name =
Option.first_some (get_class_pos ctx name) (get_typedef_pos ctx name)
let get_module_pos ctx name =
Decl_provider.get_module ctx name
|> Option.map ~f:(fun mdt ->
mdt.Typing_defs.mdt_pos |> Naming_provider.resolve_position ctx)
end
(* -- Nast helpers ---------------------------------------------------------- *)
module Nast_helper : sig
val get_fun : Provider_context.t -> string -> Nast.fun_def option
val get_fun_exn : Provider_context.t -> string -> Nast.fun_def
val get_class : Provider_context.t -> string -> Nast.class_ option
val get_class_exn : Provider_context.t -> string -> Nast.class_
val get_typedef : Provider_context.t -> string -> Nast.typedef option
val get_typedef_exn : Provider_context.t -> string -> Nast.typedef
val get_gconst_exn : Provider_context.t -> string -> Nast.gconst
val get_method : Provider_context.t -> string -> string -> Nast.method_ option
val get_method_exn : Provider_context.t -> string -> string -> Nast.method_
val get_const :
Provider_context.t -> string -> string -> Nast.class_const option
val get_typeconst :
Provider_context.t ->
string ->
string ->
(unit, unit) Aast.class_typeconst_def option
val get_prop : Provider_context.t -> string -> string -> Nast.class_var option
val is_tydef : Provider_context.t -> string -> bool
val is_class : Provider_context.t -> string -> bool
val is_enum_or_enum_class : Provider_context.t -> string -> bool
val is_interface : Provider_context.t -> string -> bool
end = struct
let make_nast_getter ~get_pos ~find_in_file ~naming ctx name =
Option.(
get_pos ctx name >>= fun pos ->
find_in_file ctx (Pos.filename pos) name |> map ~f:(naming ctx))
let get_fun =
make_nast_getter
~get_pos:Decl.get_fun_pos
~find_in_file:(Ast_provider.find_fun_in_file ~full:false)
~naming:Naming.fun_def
let get_fun_exn ctx name = value_or_not_found name (get_fun ctx name)
let get_class =
make_nast_getter
~get_pos:Decl.get_class_pos
~find_in_file:(Ast_provider.find_class_in_file ~full:false)
~naming:Naming.class_
let get_class_exn ctx name = value_or_not_found name (get_class ctx name)
let get_typedef =
make_nast_getter
~get_pos:Decl.get_typedef_pos
~find_in_file:(Ast_provider.find_typedef_in_file ~full:false)
~naming:Naming.typedef
let get_typedef_exn ctx name = value_or_not_found name (get_typedef ctx name)
let get_gconst =
make_nast_getter
~get_pos:Decl.get_gconst_pos
~find_in_file:(Ast_provider.find_gconst_in_file ~full:false)
~naming:Naming.global_const
let get_gconst_exn ctx name = value_or_not_found name (get_gconst ctx name)
let make_class_element_nast_getter ~get_elements ~get_element_name =
let elements_by_class_name = ref SMap.empty in
fun ctx class_name element_name ->
if SMap.mem class_name !elements_by_class_name then
SMap.find_opt
element_name
(SMap.find class_name !elements_by_class_name)
else
let open Option in
get_class ctx class_name >>= fun class_ ->
let elements_by_element_name =
List.fold_left
(get_elements class_)
~f:(fun elements element ->
SMap.add (get_element_name element) element elements)
~init:SMap.empty
in
elements_by_class_name :=
SMap.add class_name elements_by_element_name !elements_by_class_name;
SMap.find_opt element_name elements_by_element_name
let get_method =
Aast.(
make_class_element_nast_getter
~get_elements:(fun class_ -> class_.c_methods)
~get_element_name:(fun method_ -> snd method_.m_name))
let get_method_exn ctx class_name method_name =
value_or_not_found
(class_name ^ "::" ^ method_name)
(get_method ctx class_name method_name)
let get_const =
Aast.(
make_class_element_nast_getter
~get_elements:(fun class_ -> class_.c_consts)
~get_element_name:(fun const -> snd const.cc_id))
let get_typeconst =
Aast.(
make_class_element_nast_getter
~get_elements:(fun class_ -> class_.c_typeconsts)
~get_element_name:(fun typeconst -> snd typeconst.c_tconst_name))
let get_prop =
Aast.(
make_class_element_nast_getter
~get_elements:(fun class_ -> class_.c_vars)
~get_element_name:(fun class_var -> snd class_var.cv_id))
let is_tydef ctx nm = Option.is_some @@ get_typedef ctx nm
let is_class ctx nm = Option.is_some @@ get_class ctx nm
let is_enum_or_enum_class ctx nm =
Option.value_map ~default:false ~f:(fun Aast.{ c_kind; _ } ->
Ast_defs.is_c_enum c_kind || Ast_defs.is_c_enum_class c_kind)
@@ get_class ctx nm
let is_interface ctx nm =
Option.value_map ~default:false ~f:(fun Aast.{ c_kind; _ } ->
Ast_defs.is_c_interface c_kind)
@@ get_class ctx nm
end
(* -- Typing_deps helpers --------------------------------------------------- *)
module Dep : sig
val get_class_name : 'a Typing_deps.Dep.variant -> string option
val get_relative_path :
Provider_context.t ->
Typing_deps.Dep.dependency Typing_deps.Dep.variant ->
Relative_path.t Hh_prelude.Option.t
val get_origin :
Provider_context.t ->
Decl_provider.type_key ->
Typing_deps.Dep.dependency Typing_deps.Dep.variant ->
string
val is_builtin :
Provider_context.t ->
Typing_deps.Dep.dependency Typing_deps.Dep.variant ->
bool
val is_relevant :
Cmd.target -> Typing_deps.Dep.dependent Typing_deps.Dep.variant -> bool
end = struct
let get_class_name : type a. a Typing_deps.Dep.variant -> string option =
(* the OCaml compiler is not smart enough to let us use an or-pattern for all of these
* because of how it's matching on a GADT *)
fun dep ->
Typing_deps.Dep.(
match dep with
| Const (cls, _) -> Some cls
| Method (cls, _) -> Some cls
| SMethod (cls, _) -> Some cls
| Prop (cls, _) -> Some cls
| SProp (cls, _) -> Some cls
| Type cls -> Some cls
| Constructor cls -> Some cls
| AllMembers cls -> Some cls
| Extends cls -> Some cls
| Module md -> Some md
| Fun _
| GConst _
| GConstName _ ->
None)
let get_dep_pos ctx dep =
let open Typing_deps.Dep in
match dep with
| Fun name -> Decl.get_fun_pos ctx name
| Type name
| Const (name, _)
| Method (name, _)
| SMethod (name, _)
| Prop (name, _)
| SProp (name, _)
| Constructor name
| AllMembers name
| Extends name ->
Decl.get_class_or_typedef_pos ctx name
| GConst name
| GConstName name ->
Decl.get_gconst_pos ctx name
| Module name -> Decl.get_module_pos ctx name
let get_relative_path ctx dep =
Option.map ~f:(fun pos -> Pos.filename pos) @@ get_dep_pos ctx dep
let get_origin ctx cls (dep : 'a Typing_deps.Dep.variant) =
let open Typing_deps.Dep in
let description = variant_to_string dep in
let cls =
value_or_not_found description @@ Decl_provider.get_class ctx cls
in
match dep with
| Prop (_, name) ->
let Typing_defs.{ ce_origin; _ } =
value_or_not_found description @@ Class.get_prop cls name
in
ce_origin
| SProp (_, name) ->
let Typing_defs.{ ce_origin; _ } =
value_or_not_found description @@ Class.get_sprop cls name
in
ce_origin
| Method (_, name) ->
let Typing_defs.{ ce_origin; _ } =
value_or_not_found description @@ Class.get_method cls name
in
ce_origin
| SMethod (_, name) ->
let Typing_defs.{ ce_origin; _ } =
value_or_not_found description @@ Class.get_smethod cls name
in
ce_origin
| Const (_, name) ->
let Typing_defs.{ cc_origin; _ } =
value_or_not_found description @@ Class.get_const cls name
in
cc_origin
| Constructor cls -> cls
| _ -> raise UnexpectedDependency
let is_builtin ctx dep =
let msg = Typing_deps.Dep.variant_to_string dep in
let pos = value_or_not_found msg @@ get_dep_pos ctx dep in
Relative_path.(is_hhi @@ prefix @@ Pos.filename pos)
let is_relevant
(target : Cmd.target)
(dep : Typing_deps.Dep.dependent Typing_deps.Dep.variant) =
Cmd.(
match target with
| Function f ->
(match dep with
| Typing_deps.Dep.Fun g -> String.equal f g
| _ -> false)
(* We have to collect dependencies of the entire class because dependency collection is
coarse-grained: if cls's member depends on D, we get a dependency edge cls --> D,
not (cls, member) --> D *)
| Method (cls, _) ->
Option.equal String.equal (get_class_name dep) (Some cls))
end
(* -- Extraction target helpers --------------------------------------------- *)
module Target : sig
val pos : Provider_context.t -> Cmd.target -> Pos.t
val relative_path : Provider_context.t -> Cmd.target -> Relative_path.t
val source_text : Provider_context.t -> Cmd.target -> SourceText.t
end = struct
let pos ctx =
Cmd.(
function
| Function name -> Decl.get_fun_pos_exn ctx name
| Method (name, _) -> Decl.get_class_pos_exn ctx name)
let relative_path ctx target = Pos.filename @@ pos ctx target
let source_text ctx target =
let filename = relative_path ctx target in
let abs_filename = Relative_path.to_absolute filename in
let file_content = In_channel.read_all abs_filename in
let pos =
Cmd.(
match target with
| Function name ->
let fun_ = Nast_helper.get_fun_exn ctx name in
fun_.Aast.fd_fun.Aast.f_span
| Method (class_name, method_name) ->
let method_ = Nast_helper.get_method_exn ctx class_name method_name in
method_.Aast.m_span)
in
SourceText.make filename @@ Pos.get_text_from_pos ~content:file_content pos
end
(* -- Dependency extraction logic ------------------------------------------- *)
module Extract : sig
val collect_dependencies :
Provider_context.t ->
Cmd.target ->
bool * bool * Typing_deps.Dep.dependency Typing_deps.Dep.variant list
end = struct
type extraction_env = {
dependencies: Typing_deps.Dep.dependency Typing_deps.Dep.variant HashSet.t;
depends_on_make_default: bool ref;
depends_on_any: bool ref;
}
let class_names hint =
let rec aux acc = function
| Aast_defs.Happly ((_, nm), hints) -> auxs (nm :: acc) hints
| Aast_defs.(Haccess (hint, _) | Hlike hint | Hsoft hint | Hoption hint)
->
aux acc @@ snd hint
| Aast_defs.Hrefinement (hint, members) ->
let member_hints = function
| Aast_defs.(Rtype (_, TRexact hint) | Rctx (_, CRexact hint)) ->
[hint]
| Aast_defs.(Rtype (_, TRloose { tr_lower; tr_upper })) ->
tr_lower @ tr_upper
| Aast_defs.(Rctx (_, CRloose { cr_lower; cr_upper })) ->
Option.to_list cr_lower @ Option.to_list cr_upper
in
auxs acc (hint :: List.concat_map members ~f:member_hints)
| Aast_defs.Habstr (_, hints)
| Aast_defs.Hunion hints
| Aast_defs.Hintersection hints
| Aast_defs.Htuple hints ->
auxs acc hints
| Aast_defs.(Hvec_or_dict (hint_opt, hint)) ->
let acc = aux acc @@ snd hint in
Option.value_map
~default:acc
~f:(fun hint -> aux acc @@ snd hint)
hint_opt
| Aast_defs.Hfun hint_fun -> aux_fun acc hint_fun
| Aast_defs.Hshape shape_info -> aux_shape acc shape_info
| Aast_defs.(
( Hany | Herr | Hmixed | Hwildcard | Hnonnull | Hprim _ | Hthis
| Hdynamic | Hnothing | Hfun_context _ | Hvar _ )) ->
acc
and auxs acc = function
| [] -> acc
| next :: rest -> auxs (aux acc @@ snd next) rest
and aux_fun acc Aast_defs.{ hf_param_tys; hf_variadic_ty; hf_return_ty; _ }
=
let acc = auxs (aux acc @@ snd hf_return_ty) hf_param_tys in
Option.value_map
~default:acc
~f:(fun hint -> aux acc @@ snd hint)
hf_variadic_ty
and aux_shape acc Aast_defs.{ nsi_field_map; _ } =
auxs acc
@@ List.map nsi_field_map ~f:(fun Aast_defs.{ sfi_hint; _ } -> sfi_hint)
in
aux [] @@ snd hint
let rec do_add_dep ctx env dep =
let is_wildcard =
match dep with
| Typing_deps.Dep.Type h -> String.equal h SN.Typehints.wildcard
| _ -> false
in
if
(not is_wildcard)
&& (not (HashSet.mem env.dependencies dep))
&& not (Dep.is_builtin ctx dep)
then (
HashSet.add env.dependencies dep;
add_signature_dependencies ctx env dep
)
and add_dep ctx env ~this ty : unit =
let visitor =
object
inherit [unit] Type_visitor.decl_type_visitor as super
method! on_tany _ _ = env.depends_on_any := true
method! on_tfun () r ft =
if
List.exists
~f:Typing_defs.get_fp_has_default
ft.Typing_defs.ft_params
then
env.depends_on_make_default := true;
super#on_tfun () r ft
method! on_tapply _ _ (_, name) tyl =
let dep = Typing_deps.Dep.Type name in
do_add_dep ctx env dep;
(* If we have a constant of a generic type, it can only be an
array type, e.g., vec<A>, for which don't need values of A
to generate an initializer. *)
List.iter tyl ~f:(add_dep ctx env ~this)
method! on_tshape _ _ { Typing_defs.s_fields = fdm; _ } =
Typing_defs.TShapeMap.iter
(fun name Typing_defs.{ sft_ty; _ } ->
(match name with
| Typing_defs.TSFlit_int _
| Typing_defs.TSFlit_str _ ->
()
| Typing_defs.TSFclass_const ((_, c), (_, s)) ->
do_add_dep ctx env (Typing_deps.Dep.Type c);
do_add_dep ctx env (Typing_deps.Dep.Const (c, s)));
add_dep ctx env ~this sft_ty)
fdm
(* We un-nest (((this::T1)::T2)::T3) into (this, [T1;T2;T3]) and then re-nest
* because legacy representation of Taccess was using lists. TODO: implement
* this more directly instead.
*)
method! on_taccess () r (root, tconst) =
let rec split_taccess root ids =
Typing_defs.(
match get_node root with
| Taccess (root, id) -> split_taccess root (id :: ids)
| _ -> (root, ids))
in
let rec make_taccess r root ids =
match ids with
| [] -> root
| id :: ids ->
make_taccess
Typing_reason.Rnone
Typing_defs.(mk (r, Taccess (root, id)))
ids
in
let (root, tconsts) = split_taccess root [tconst] in
let expand_type_access class_name tconsts =
match tconsts with
| [] -> raise UnexpectedDependency
(* Expand Class::TConst1::TConst2[::...]: get TConst1 in
Class, get its type or upper bound T, continue adding
dependencies of T::TConst2[::...] *)
| (_, tconst) :: tconsts ->
do_add_dep ctx env (Typing_deps.Dep.Const (class_name, tconst));
let cls = Decl.get_class_exn ctx class_name in
(match Decl_provider.Class.get_typeconst cls tconst with
| Some Typing_defs.{ ttc_kind; _ } ->
let add_cstr_dep tc_type =
(* What does 'this' refer to inside of T? *)
let this =
match Typing_defs.get_node tc_type with
| Typing_defs.Tapply ((_, name), _) -> Some name
| _ -> this
in
let taccess = make_taccess r tc_type tconsts in
add_dep ctx ~this env taccess
in
(* TODO(coeffects) double-check this *)
(* TODO(T88552052) I've kept the existing logic the same in the refactor
* but it exposed clear gaps in which constraints get added. *)
let open Typing_defs in
(match ttc_kind with
| TCConcrete { tc_type } ->
add_dep ctx ~this:(Some class_name) env tc_type;
if not (List.is_empty tconsts) then add_cstr_dep tc_type
| TCAbstract
{
atc_as_constraint;
atc_super_constraint;
atc_default = _ (* TODO *);
} ->
if not (List.is_empty tconsts) then (
Option.iter ~f:add_cstr_dep atc_as_constraint;
Option.iter ~f:add_cstr_dep atc_super_constraint
))
| None -> ())
in
match Typing_defs.get_node root with
| Typing_defs.Taccess (root', tconst) ->
add_dep ctx ~this env (make_taccess r root' (tconst :: tconsts))
| Typing_defs.Tapply ((_, name), _) -> expand_type_access name tconsts
| Typing_defs.Tthis ->
expand_type_access (Option.value_exn this) tconsts
| _ -> raise UnexpectedDependency
end
in
visitor#on_type () ty
and add_signature_dependencies ctx env obj =
let description = Typing_deps.Dep.variant_to_string obj in
match Dep.get_class_name obj with
| Some cls_name ->
do_add_dep ctx env (Typing_deps.Dep.Type cls_name);
Option.iter ~f:(add_class_attr_deps ctx env)
@@ Nast_helper.get_class ctx cls_name;
(match Decl_provider.get_class ctx cls_name with
| None ->
let Typing_defs.{ td_type; td_as_constraint; td_super_constraint; _ } =
value_or_not_found description
@@ Decl_provider.get_typedef ctx cls_name
in
Option.iter ~f:(add_tydef_attr_deps ctx env)
@@ Nast_helper.get_typedef ctx cls_name;
add_dep ctx ~this:None env td_type;
Option.iter td_as_constraint ~f:(add_dep ctx ~this:None env);
Option.iter td_super_constraint ~f:(add_dep ctx ~this:None env)
| Some cls ->
let add_dep = add_dep ctx env ~this:(Some cls_name) in
Typing_deps.Dep.(
(match obj with
| Prop (_, name) ->
let Typing_defs.{ ce_type; _ } =
value_or_not_found description @@ Class.get_prop cls name
in
add_dep @@ Lazy.force ce_type;
Option.iter ~f:(add_classvar_attr_deps ctx env)
@@ Nast_helper.get_prop ctx cls_name name;
(* We need to initialize properties in the constructor, add a dependency on it *)
do_add_dep ctx env (Constructor cls_name)
| SProp (_, name) ->
let Typing_defs.{ ce_type; _ } =
value_or_not_found description @@ Class.get_sprop cls name
in
add_dep @@ Lazy.force ce_type;
Option.iter ~f:(add_classvar_attr_deps ctx env)
@@ Nast_helper.get_prop ctx cls_name name
| Method (_, name) ->
let Typing_defs.{ ce_type; _ } =
value_or_not_found description @@ Class.get_method cls name
in
add_dep @@ Lazy.force ce_type;
Option.iter ~f:(add_method_attr_deps ctx env)
@@ Nast_helper.get_method ctx cls_name name;
Class.all_ancestor_names cls
|> List.iter ~f:(fun ancestor_name ->
match Decl_provider.get_class ctx ancestor_name with
| Some ancestor when Class.has_method ancestor name ->
do_add_dep ctx env (Method (ancestor_name, name))
| _ -> ())
| SMethod (_, name) ->
(match Class.get_smethod cls name with
| Some Typing_defs.{ ce_type; _ } ->
add_dep @@ Lazy.force ce_type;
Option.iter ~f:(add_method_attr_deps ctx env)
@@ Nast_helper.get_method ctx cls_name name;
Class.all_ancestor_names cls
|> List.iter ~f:(fun ancestor_name ->
match Decl_provider.get_class ctx ancestor_name with
| Some ancestor when Class.has_smethod ancestor name ->
do_add_dep ctx env (SMethod (ancestor_name, name))
| _ -> ())
| None ->
(match Class.get_method cls name with
| Some _ ->
HashSet.remove env.dependencies obj;
do_add_dep ctx env (Method (cls_name, name))
| None -> raise (DependencyNotFound description)))
| Const (_, name) ->
(match Class.get_typeconst cls name with
| Some Typing_defs.{ ttc_kind; ttc_origin; _ } ->
if not (String.equal cls_name ttc_origin) then
do_add_dep ctx env (Const (ttc_origin, name));
Option.iter ~f:(add_tyconst_attr_deps ctx env)
@@ Nast_helper.get_typeconst ctx ttc_origin name;
(* TODO(T88552052) Missing lots of deps here *)
let open Typing_defs in
(match ttc_kind with
| TCConcrete { tc_type } -> add_dep tc_type
| TCAbstract
{
atc_default = _;
atc_super_constraint = _;
atc_as_constraint;
} ->
Option.iter atc_as_constraint ~f:add_dep)
| None ->
let Typing_defs.{ cc_type; _ } =
value_or_not_found description @@ Class.get_const cls name
in
add_dep cc_type)
| Constructor _ ->
(match Class.construct cls with
| (Some Typing_defs.{ ce_type; _ }, _) ->
add_dep @@ Lazy.force ce_type;
Option.iter ~f:(add_method_attr_deps ctx env)
@@ Nast_helper.get_method ctx cls_name "__construct"
| _ -> ())
| Type _ ->
List.iter (Class.all_ancestors cls) ~f:(fun (_, ty) -> add_dep ty);
List.iter (Class.all_ancestor_reqs cls) ~f:(fun (_, ty) ->
add_dep ty);
Option.iter
(Class.enum_type cls)
~f:(fun Typing_defs.{ te_base; te_constraint; te_includes; _ } ->
add_dep te_base;
Option.iter te_constraint ~f:add_dep;
List.iter te_includes ~f:add_dep)
| AllMembers _ ->
(* AllMembers is used for dependencies on enums, so we should depend on all constants *)
List.iter
(Class.consts cls)
~f:(fun (name, Typing_defs.{ cc_type; _ }) ->
if not (String.equal name "class") then add_dep cc_type)
(* Ignore, we fetch class hierarchy when we call add_signature_dependencies on a class dep *)
| Extends _ -> ()
| _ -> raise UnexpectedDependency)))
| None ->
Typing_deps.Dep.(
(match obj with
| Fun f ->
let Typing_defs.{ fe_type; _ } =
value_or_not_found description @@ Decl_provider.get_fun ctx f
in
add_dep ctx ~this:None env @@ fe_type;
Option.iter ~f:(add_fun_attr_deps ctx env)
@@ Nast_helper.get_fun ctx f
| GConst c
| GConstName c ->
let const =
value_or_not_found description @@ Decl_provider.get_gconst ctx c
in
add_dep ctx ~this:None env const.Typing_defs.cd_type
| _ -> raise UnexpectedDependency))
and add_user_attr_deps ctx env user_attrs =
List.iter
user_attrs
~f:(fun Aast.{ ua_name = (_, cls); ua_params = exprs } ->
if not @@ String.is_prefix ~prefix:"__" cls then (
do_add_dep ctx env @@ Typing_deps.Dep.Type cls;
do_add_dep ctx env @@ Typing_deps.Dep.Constructor cls
);
List.iter exprs ~f:(function
| (_, _, Aast.(Class_get ((_, _, CI (_, cls)), _, _)))
| (_, _, Aast.(Class_const ((_, _, CI (_, cls)), _))) ->
do_add_dep ctx env @@ Typing_deps.Dep.Type cls
| _ -> ()))
and add_class_attr_deps
ctx env Aast.{ c_user_attributes = attrs; c_tparams = tparams; _ } =
add_user_attr_deps ctx env attrs;
List.iter tparams ~f:(add_tparam_attr_deps ctx env)
and add_classvar_attr_deps ctx env Aast.{ cv_user_attributes = attrs; _ } =
add_user_attr_deps ctx env attrs
and add_tyconst_attr_deps ctx env Aast.{ c_tconst_user_attributes = attrs; _ }
=
add_user_attr_deps ctx env attrs
and add_arg_attr_deps ctx env (attrs, params, tparams) =
add_user_attr_deps ctx env attrs;
List.iter params ~f:(add_fun_param_attr_deps ctx env);
List.iter tparams ~f:(add_tparam_attr_deps ctx env)
and add_fun_attr_deps ctx env fd =
let Aast.{ f_user_attributes = attrs; f_params = params; _ } =
fd.Aast.fd_fun
in
add_arg_attr_deps ctx env (attrs, params, fd.Aast.fd_tparams)
and add_method_attr_deps
ctx
env
Aast.
{ m_user_attributes = attrs; m_tparams = tparams; m_params = params; _ }
=
add_arg_attr_deps ctx env (attrs, params, tparams)
and add_fun_param_attr_deps ctx env Aast.{ param_user_attributes = attrs; _ }
=
add_user_attr_deps ctx env attrs
and add_tydef_attr_deps ctx env Aast.{ t_user_attributes = attrs; _ } =
add_user_attr_deps ctx env attrs
and add_tparam_attr_deps
ctx
env
Aast.
{
tp_user_attributes = attrs;
tp_parameters = tparams;
tp_constraints = cstrs;
_;
} =
add_user_attr_deps ctx env attrs;
List.iter tparams ~f:(add_tparam_attr_deps ctx env);
List.iter
~f:(fun (_, hint) ->
let cs = class_names hint in
List.iter cs ~f:(fun cls_name ->
do_add_dep ctx env (Typing_deps.Dep.Type cls_name)))
cstrs
let add_impls ~ctx ~env ~cls acc ancestor_name =
let open Typing_deps.Dep in
let ancestor = Decl.get_class_exn ctx ancestor_name in
let add_smethod_impl acc smethod_name =
Option.value_map ~default:acc ~f:(fun Typing_defs.{ ce_origin; _ } ->
Typing_deps.Dep.SMethod (ce_origin, smethod_name) :: acc)
@@ Class.get_smethod cls smethod_name
in
let add_method_impl acc method_name =
Option.value_map ~default:acc ~f:(fun Typing_defs.{ ce_origin; _ } ->
Typing_deps.Dep.Method (ce_origin, method_name) :: acc)
@@ Class.get_method cls method_name
in
let add_tyconst_impl acc typeconst_name =
Option.value_map ~default:acc ~f:(fun Typing_defs.{ ttc_origin; _ } ->
Typing_deps.Dep.Const (ttc_origin, typeconst_name) :: acc)
@@ Class.get_typeconst cls typeconst_name
in
let add_const_impl acc const_name =
Option.value_map ~default:acc ~f:(fun Typing_defs.{ cc_origin; _ } ->
Typing_deps.Dep.Const (cc_origin, const_name) :: acc)
@@ Class.get_const cls const_name
in
if Dep.is_builtin ctx (Type ancestor_name) then
let with_smths =
List.fold ~init:acc ~f:(fun acc (nm, _) -> add_smethod_impl acc nm)
@@ Class.smethods ancestor
in
let with_mths =
List.fold ~init:with_smths ~f:(fun acc (nm, _) ->
add_method_impl acc nm)
@@ Class.methods ancestor
in
let with_tyconsts =
List.fold ~init:with_mths ~f:(fun acc (nm, _) ->
add_tyconst_impl acc nm)
@@ Class.typeconsts ancestor
in
List.fold ~init:with_tyconsts ~f:(fun acc (nm, _) ->
add_const_impl acc nm)
@@ Class.consts ancestor
else
let f dep acc =
Typing_deps.Dep.(
match dep with
| SMethod (class_name, method_name)
when String.equal class_name ancestor_name ->
add_smethod_impl acc method_name
| Method (class_name, method_name)
when String.equal class_name ancestor_name ->
add_method_impl acc method_name
| Const (class_name, name)
when String.equal class_name ancestor_name
&& Option.is_some (Class.get_typeconst ancestor name) ->
add_tyconst_impl acc name
| Const (class_name, name)
when String.equal class_name ancestor_name
&& Option.is_some (Class.get_const ancestor name) ->
add_const_impl acc name
| _ -> acc)
in
HashSet.fold ~init:acc ~f env.dependencies
(** Implementation dependencies of all ancestor classes and trait / interface
requirements *)
let get_implementation_dependencies ctx env cls =
let f = add_impls ~ctx ~env ~cls in
let init =
Option.value_map ~default:[] ~f:(fun ss ->
List.map ~f:(fun nm -> Typing_deps.Dep.Type nm) @@ SSet.elements ss)
@@ Class.sealed_whitelist cls
in
let ancs = List.fold ~init ~f @@ Class.all_ancestor_names cls in
List.fold ~f ~init:ancs @@ Class.all_ancestor_req_names cls
(** Add implementation depedencies of all class dependencies until we reach
a fixed point *)
let rec add_implementation_dependencies ctx env =
let size = HashSet.length env.dependencies in
let add_class dep acc =
match dep with
| Typing_deps.Dep.Type cls_name ->
Option.value_map ~default:acc ~f:(fun cls -> cls :: acc)
@@ Decl_provider.get_class ctx cls_name
| _ -> acc
in
env.dependencies
|> HashSet.fold ~init:[] ~f:add_class
|> List.concat_map ~f:(get_implementation_dependencies ctx env)
|> List.iter ~f:(do_add_dep ctx env);
if HashSet.length env.dependencies <> size then
add_implementation_dependencies ctx env
(** Collect dependencies from type decls and transitive closure of resulting
implementation dependencies; determine if any of our dependencies
depend on any or default parameter values *)
let collect_dependencies ctx target =
let filename = Target.relative_path ctx target in
let env =
{
dependencies = HashSet.create ();
depends_on_make_default = ref false;
depends_on_any = ref false;
}
in
let add_dependency
(root : Typing_deps.Dep.dependent Typing_deps.Dep.variant)
(obj : Typing_deps.Dep.dependency Typing_deps.Dep.variant) : unit =
if Dep.is_relevant target root then do_add_dep ctx env obj
in
Typing_deps.add_dependency_callback ~name:"add_dependency" add_dependency;
(* Collect dependencies through side effects of typechecking and remove
* the target function/method from the set of dependencies to avoid
* declaring it twice.
*)
let () =
Typing_deps.Dep.(
match target with
| Cmd.Function func ->
let full_ast =
Ast_provider.find_fun_in_file ctx filename func ~full:true
in
let (_ : Tast.def Tast_with_dynamic.t option) =
Option.bind full_ast ~f:(fun full_ast ->
Typing_check_job.type_fun ctx ~full_ast)
in
add_implementation_dependencies ctx env;
HashSet.remove env.dependencies (Fun func)
| Cmd.Method (cls, m) ->
let full_ast =
Ast_provider.find_class_in_file ctx filename cls ~full:true
in
let (_ : Tast.def Tast_with_dynamic.t option) =
Option.bind full_ast ~f:(fun full_ast ->
Typing_check_job.type_class ctx ~full_ast)
in
HashSet.add env.dependencies (Method (cls, m));
HashSet.add env.dependencies (SMethod (cls, m));
add_implementation_dependencies ctx env;
HashSet.remove env.dependencies (Method (cls, m));
HashSet.remove env.dependencies (SMethod (cls, m)))
in
( !(env.depends_on_make_default),
!(env.depends_on_any),
HashSet.fold env.dependencies ~init:[] ~f:List.cons )
end
(* -- Grouped dependencies ------------------------------------------------- *)
module Grouped : sig
type t
val name : t -> string
val line : t -> int
val compare : t -> t -> int
val pp : Format.formatter -> t -> unit
val of_deps :
Provider_context.t ->
Cmd.target option ->
Typing_deps.Dep.dependency Typing_deps.Dep.variant list ->
t list
end = struct
let strip_ns obj_name =
match String.rsplit2 obj_name ~on:'\\' with
| Some (_, name) -> name
| None -> obj_name
(** Generate an initial value based on type hint *)
let init_value ctx hint =
let unsupported_hint _ =
Hh_logger.log
"%s: get_init_from_hint: unsupported hint: %s"
(Pos.string (Pos.to_absolute (fst hint)))
(Aast_defs.show_hint hint);
raise Unsupported
in
let rec pp tparams ppf hint =
Aast.(
match snd hint with
| Hprim prim -> pp_prim ppf prim
| Hoption _ -> Fmt.string ppf "null"
| Hlike hint -> pp tparams ppf hint
| Hvec_or_dict _ -> Fmt.string ppf "varray[]"
| Htuple hs ->
Fmt.(
prefix (const string "tuple")
@@ parens
@@ list ~sep:comma (pp tparams))
ppf
hs
| Hshape { nsi_field_map; _ } ->
Fmt.(
prefix (const string "shape")
@@ parens
@@ list ~sep:comma (pp_shape_field tparams))
ppf
@@ List.filter nsi_field_map ~f:(fun shape_field_info ->
not shape_field_info.sfi_optional)
| Happly ((_, name), _)
when String.(
name = SN.Collections.cVec
|| name = SN.Collections.cKeyset
|| name = SN.Collections.cDict) ->
Fmt.(suffix (const string "[]") string) ppf @@ strip_ns name
| Happly ((_, name), _)
when String.(
name = SN.Collections.cVector
|| name = SN.Collections.cImmVector
|| name = SN.Collections.cMap
|| name = SN.Collections.cImmMap
|| name = SN.Collections.cSet
|| name = SN.Collections.cImmSet) ->
Fmt.(suffix (const string " {}") string) ppf @@ strip_ns name
| Happly ((_, name), [fst; snd])
when String.(name = SN.Collections.cPair) ->
Fmt.(
prefix (const string "Pair ")
@@ braces
@@ pair ~sep:comma (pp tparams) (pp tparams))
ppf
(fst, snd)
| Happly ((_, name), [(_, Happly ((_, class_name), _))])
when String.(name = SN.Classes.cClassname) ->
Fmt.(suffix (const string "::class") string) ppf class_name
| Happly ((_, name), hints) ->
(match Nast_helper.get_class ctx name with
| Some
{ c_kind; c_consts = Aast.{ cc_id = (_, const_name); _ } :: _; _ }
when Ast_defs.is_c_enum c_kind || Ast_defs.is_c_enum_class c_kind ->
Fmt.(pair ~sep:dbl_colon string string) ppf (name, const_name)
| Some _ -> unsupported_hint ()
| _ ->
let typedef = Nast_helper.get_typedef_exn ctx name in
let ts =
List.fold2_exn
typedef.t_tparams
hints
~init:SMap.empty
~f:(fun tparams tparam hint ->
SMap.add (snd tparam.tp_name) hint tparams)
in
pp (ts :: tparams) ppf typedef.t_kind)
| Habstr (name, []) ->
(* FIXME: support non-empty type arguments of Habstr here? *)
let rec loop tparams_stack =
match tparams_stack with
| tparams :: tparams_stack' ->
(match SMap.find_opt name tparams with
| Some hint -> pp tparams_stack' ppf hint
| None -> loop tparams_stack')
| [] -> unsupported_hint ()
in
loop tparams
| _ -> unsupported_hint ())
and pp_prim ppf =
Aast_defs.(
function
| Tnull -> Fmt.string ppf "null"
| Tint
| Tnum ->
Fmt.string ppf "0"
| Tbool -> Fmt.string ppf "false"
| Tfloat -> Fmt.string ppf "0.0"
| Tstring
| Tarraykey ->
Fmt.string ppf "\"\""
| Tvoid
| Tresource
| Tnoreturn ->
raise Unsupported)
and pp_shape_field tparams ppf Aast.{ sfi_hint; sfi_name; _ } =
Fmt.(pair ~sep:fat_arrow pp_shape_field_name @@ pp tparams)
ppf
(sfi_name, sfi_hint)
and pp_shape_field_name ppf =
Ast_defs.(
function
| SFlit_int (_, s) -> Fmt.string ppf s
| SFlit_str (_, s) -> Fmt.(quote string) ppf s
| SFclass_const ((_, c), (_, s)) ->
Fmt.(pair ~sep:dbl_colon string string) ppf (c, s))
in
Format.asprintf "%a" (pp []) hint
(* -- Shared pretty printers ---------------------------------------------- *)
let pp_visibility ppf = function
| Ast_defs.Private -> Fmt.string ppf "private"
| Ast_defs.Public -> Fmt.string ppf "public"
| Ast_defs.Protected -> Fmt.string ppf "protected"
| Ast_defs.Internal -> Fmt.string ppf "internal"
let pp_paramkind ppf =
Ast_defs.(
function
| Pinout _ -> Fmt.string ppf "inout"
| Pnormal -> ())
let pp_hint = Hint_print.pp_hint
let pp_user_attrs = Hint_print.pp_user_attrs
let pp_contexts ppf (_, ctxts) =
Fmt.(brackets @@ list ~sep:comma @@ pp_hint ~is_ctx:true) ppf ctxts
let pp_constraint_kind ppf =
Ast_defs.(
function
| Constraint_as -> Fmt.string ppf "as"
| Constraint_eq -> Fmt.string ppf "="
| Constraint_super -> Fmt.string ppf "super")
let pp_fun_param_name ppf (param_is_variadic, param_name) =
if param_is_variadic then
Fmt.pf ppf {|...%s|} param_name
else
Fmt.string ppf param_name
let pp_fun_param_default ppf _ = Fmt.pf ppf {| = \%s|} __CONST_DEFAULT__
let update_hfun_context (pos, hints) ~name =
( pos,
List.map hints ~f:(function
| (pos, Aast_defs.Hfun_context nm) when String.(nm = name) ->
(pos, Aast_defs.Hvar "_")
| hint -> hint) )
let update_hint_fun_context hint_fun ~name =
Aast_defs.
{
hint_fun with
hf_ctxs =
Option.map ~f:(update_hfun_context ~name) hint_fun.Aast_defs.hf_ctxs;
}
let update_fun_context (nm, hint_opt) ~name =
let f ((pos, hint_) as hint) =
Aast_defs.(
match hint_ with
| Hfun hint_fun -> (pos, Hfun (update_hint_fun_context hint_fun ~name))
| Hoption (opt_pos, Hfun hint_fun) ->
(pos, Hoption (opt_pos, Hfun (update_hint_fun_context hint_fun ~name)))
(* Non-function option *)
| Hoption _
(* places where we _can't_ use wildcard contexts *)
| Hlike _
| Hsoft _
| Hshape _
| Htuple _
| Hrefinement _
(* places where function types shouldn't appear *)
| Haccess _
| Happly _
(* non-denotable types *)
| Hany
| Herr
| Hmixed
| Hnonnull
| Habstr _
| Hvec_or_dict _
| Hprim _
| Hthis
| Hwildcard
| Hdynamic
| Hnothing
| Hunion _
| Hintersection _
| Hfun_context _
| Hvar _ ->
hint)
in
(nm, Option.map hint_opt ~f)
let pp_tparams = Hint_print.pp_tparams
let pp_type_hint = Hint_print.pp_type_hint
let pp_fun_param
ppf
Aast.
{
param_type_hint;
param_is_variadic;
param_name;
param_expr;
param_callconv;
param_user_attributes;
param_visibility;
_;
} =
Format.(
fprintf
ppf
{|%a %a %a %a%a%a|}
pp_user_attrs
param_user_attributes
Fmt.(option pp_visibility)
param_visibility
pp_paramkind
param_callconv
(pp_type_hint ~is_ret_type:false)
(* Type hint for parameter $f used for contextful function must be a
function type hint whose context is exactly [_] *)
(update_fun_context ~name:param_name param_type_hint)
pp_fun_param_name
(param_is_variadic, param_name)
Fmt.(option pp_fun_param_default)
param_expr)
let pp_fun_params ppf = Fmt.(parens @@ list ~sep:comma pp_fun_param) ppf
(* -- Single element depdencies ------------------------------------------- *)
module Single : sig
type t
val name : t -> string
val line : t -> int
val mk_enum : Provider_context.t -> Nast.class_ -> t
val mk_gconst : Provider_context.t -> Nast.gconst -> t
val mk_gfun : Nast.fun_def -> t
val mk_tydef : Nast.typedef -> t
val mk_target_fun : Provider_context.t -> string * Cmd.target -> t
val pp : Format.formatter -> t -> unit
end = struct
type t =
| SEnum of {
name: string;
line: int;
base: Aast.hint;
constr: Aast.hint option;
consts: (string * string) list;
user_attrs: Nast.user_attribute list;
}
| SGConst of {
name: string;
line: int;
type_: Aast.hint;
init_val: string;
}
| STydef of string * int * int list * Nast.typedef
| SGFun of string * int * Nast.fun_def
| SGTargetFun of string * int * SourceText.t
let mk_target_fun ctx (fun_name, target) =
SGTargetFun
( fun_name,
Pos.line @@ Target.pos ctx target,
Target.source_text ctx target )
let mk_enum
ctx
Aast.{ c_name = (pos, name); c_enum; c_consts; c_user_attributes; _ } =
let Aast.{ e_base; e_constraint; _ } =
value_or_not_found Format.(sprintf "expected an enum class: %s" name)
@@ c_enum
in
let const_val = init_value ctx e_base in
let consts =
List.map c_consts ~f:(fun Aast.{ cc_id = (_, const_name); _ } ->
(const_name, const_val))
in
SEnum
{
name;
line = Pos.line pos;
consts;
base = e_base;
constr = e_constraint;
user_attrs = c_user_attributes;
}
let mk_gconst ctx Aast.{ cst_name = (pos, name); cst_type; _ } =
let type_ = value_or_not_found ("type of " ^ name) cst_type in
let init_val = init_value ctx type_ in
SGConst { name; line = Pos.line pos; type_; init_val }
let mk_gfun ast =
let (pos, name) = ast.Aast.fd_name in
SGFun (name, Pos.line pos, ast)
let mk_tydef (Aast.{ t_name = (pos, name); _ } as ast) =
let fixmes =
ISet.elements @@ Fixme_provider.get_fixme_codes_for_pos pos
in
STydef (name, Pos.line pos, fixmes, ast)
let name = function
| SEnum { name; _ }
| SGConst { name; _ }
| STydef (name, _, _, _)
| SGFun (name, _, _)
| SGTargetFun (name, _, _) ->
name
let line = function
| SEnum { line; _ }
| SGConst { line; _ }
| STydef (_, line, _, _)
| SGFun (_, line, _)
| SGTargetFun (_, line, _) ->
line
(* == Pretty print ====================================================== *)
(* -- Global functions -------------------------------------------------- *)
let pp_fun ppf (name, fd) =
let Aast.{ f_user_attributes; f_params; f_ret; f_ctxs; _ } =
fd.Aast.fd_fun
in
Fmt.(
pf
ppf
"%a function %s%a%a%a%a {throw new \\Exception();}"
pp_user_attrs
f_user_attributes
(strip_ns name)
pp_tparams
fd.Aast.fd_tparams
pp_fun_params
f_params
(option pp_contexts)
f_ctxs
(pp_type_hint ~is_ret_type:true)
f_ret)
(* -- Type definitions -------------------------------------------------- *)
let pp_typedef_visiblity ppf = function
| Aast_defs.Transparent -> Fmt.string ppf "type"
| Aast_defs.CaseType -> Fmt.string ppf "case type"
| Aast_defs.Opaque
| Aast_defs.OpaqueModule ->
Fmt.string ppf "newtype"
let pp_fixme ppf code = Fmt.pf ppf "/* HH_FIXME[%d] */@." code
let pp_tydef
ppf
( nm,
fixmes,
Aast.
{
t_tparams;
t_as_constraint;
t_super_constraint;
t_vis;
t_kind;
t_user_attributes;
_;
} ) =
Fmt.(
pf
ppf
{|%a%a%a %s%a%a%a = %a;|}
(list ~sep:cut pp_fixme)
fixmes
pp_user_attrs
t_user_attributes
pp_typedef_visiblity
t_vis
(strip_ns nm)
pp_tparams
t_tparams
(option @@ prefix (const string " as ") @@ pp_hint ~is_ctx:false)
t_as_constraint
(option @@ prefix (const string " super ") @@ pp_hint ~is_ctx:false)
t_super_constraint
(pp_hint ~is_ctx:false)
t_kind)
(* -- Global constants -------------------------------------------------- *)
let pp_gconst ppf (name, hint, init) =
Fmt.pf
ppf
{|const %a %s = %s;|}
(pp_hint ~is_ctx:false)
hint
(strip_ns name)
init
(* -- Enums ------------------------------------------------------------- *)
let pp_enum ppf (name, base, constr, consts, user_attrs) =
Fmt.(
pf
ppf
{|%a enum %s: %a%a {%a}|}
pp_user_attrs
user_attrs
(strip_ns name)
(pp_hint ~is_ctx:false)
base
(option @@ prefix (const string " as ") @@ pp_hint ~is_ctx:false)
constr
(list ~sep:sp @@ suffix semicolon @@ pair ~sep:equal_to string string)
consts)
let pp ppf = function
| SEnum { name; base; constr; consts; user_attrs; _ } ->
pp_enum ppf (name, base, constr, consts, user_attrs)
| STydef (nm, _, fixmes, ast) -> pp_tydef ppf (nm, fixmes, ast)
| SGConst { name; type_; init_val; _ } ->
pp_gconst ppf (name, type_, init_val)
| SGFun (nm, _, ast) -> pp_fun ppf (nm, ast)
| SGTargetFun (_, _, source) -> Fmt.string ppf @@ SourceText.text source
end
(* -- Dependencies contained within a class dependency -------------------- *)
module Class_elt : sig
type t
val mk_const : Provider_context.t -> Nast.class_const -> t
val mk_tyconst : (unit, unit) Aast.class_typeconst_def -> t
val mk_method : bool -> Nast.method_ -> t
val is_method : t -> method_name:string -> bool
val method_props : t -> SSet.t option
val prop_name : t -> string option
val mk_target_method : Provider_context.t -> Cmd.target -> t
val mk_prop : Provider_context.t -> Nast.class_var -> t
val compare : t -> t -> int
val pp : Format.formatter -> t -> unit
end = struct
type t =
| EltConst of {
name: string;
line: int;
is_abstract: bool;
type_: Aast.hint option;
init_val: string option;
}
| EltMethod of bool * int * Nast.method_
| EltTypeConst of {
name: string;
line: int;
is_abstract: bool;
is_ctx: bool;
type_: Aast.hint option;
constraint_: Aast.hint option;
user_attrs: Nast.user_attribute list;
}
| EltProp of {
name: string;
line: int;
is_static: bool;
visibility: Aast.visibility;
user_attrs: Nast.user_attribute list;
type_: Aast.hint option;
init_val: string option;
}
| EltXHPAttr of {
name: string;
line: int;
user_attrs: Nast.user_attribute list;
type_: Aast.hint option;
init_val: string option;
xhp_attr_info: Aast.xhp_attr_info;
}
| EltTargetMethod of int * SourceText.t
let line = function
| EltConst { line; _ }
| EltMethod (_, line, _)
| EltTypeConst { line; _ }
| EltProp { line; _ }
| EltXHPAttr { line; _ }
| EltTargetMethod (line, _) ->
line
let method_props = function
| EltMethod (_, _, Aast.{ m_params; _ }) ->
Some
(SSet.of_list
@@ List.filter_map
m_params
~f:(fun Aast.{ param_name; param_visibility; _ } ->
Option.map ~f:(fun _ -> param_name) param_visibility))
| _ -> None
let prop_name = function
| EltProp { name; _ } -> Some name
| _ -> None
let compare elt1 elt2 = Int.compare (line elt2) (line elt1)
let mk_target_method ctx tgt =
let pos = Target.pos ctx tgt in
EltTargetMethod (Pos.line pos, Target.source_text ctx tgt)
let mk_const ctx Aast.{ cc_id = (pos, name); cc_kind; cc_type; _ } =
let open Aast in
let is_abstract =
match cc_kind with
| CCAbstract _ -> true
| CCConcrete _ -> false
in
let (type_, init_val) =
match (cc_type, cc_kind) with
| (Some hint, _) -> (Some hint, Some (init_value ctx hint))
| (_, CCAbstract (Some (_, e_pos, e_)))
| (_, CCConcrete (_, e_pos, e_)) ->
(match Decl_utils.infer_const e_ with
| Some tprim ->
let hint = (e_pos, Aast.Hprim tprim) in
(None, Some (init_value ctx hint))
| None -> raise Unsupported)
| (None, CCAbstract None) -> (None, None)
in
let line = Pos.line pos in
EltConst { name; line; is_abstract; type_; init_val }
let mk_tyconst
Aast.
{
c_tconst_kind;
c_tconst_name = (pos, name);
c_tconst_is_ctx;
c_tconst_user_attributes;
_;
} =
let (is_abstract, type_, constraint_) =
Aast.(
match c_tconst_kind with
| TCAbstract { c_atc_as_constraint = c; _ } -> (true, None, c)
| TCConcrete { c_tc_type = t } -> (false, Some t, None))
in
EltTypeConst
{
name;
line = Pos.line pos;
is_abstract;
type_;
constraint_;
is_ctx = c_tconst_is_ctx;
user_attrs = c_tconst_user_attributes;
}
let mk_method from_interface (Aast.{ m_name = (pos, _); _ } as method_) =
EltMethod (from_interface, Pos.line pos, method_)
let is_method t ~method_name =
match t with
| EltMethod (_, _, Aast.{ m_name = (_, nm); _ }) ->
String.(nm = method_name)
| _ -> false
let mk_prop
ctx
Aast.
{
cv_id = (pos, name);
cv_user_attributes;
cv_type;
cv_expr;
cv_xhp_attr;
cv_visibility;
cv_is_static;
_;
} =
let (type_, init_val) =
match (Aast.hint_of_type_hint cv_type, cv_expr) with
| (Some hint, Some _) -> (Some hint, Some (init_value ctx hint))
| (Some hint, None) -> (Some hint, None)
| (None, None) -> (None, None)
(* Untyped prop, not supported for now *)
| (None, Some _) -> raise Unsupported
in
match cv_xhp_attr with
| Some xhp_attr_info ->
EltXHPAttr
{
name;
line = Pos.line pos;
user_attrs = cv_user_attributes;
type_;
init_val;
xhp_attr_info;
}
| _ ->
EltProp
{
name;
line = Pos.line pos;
is_static = cv_is_static;
visibility = cv_visibility;
user_attrs = cv_user_attributes;
type_;
init_val;
}
(* == Pretty printers =================================================== *)
(* -- Methods ----------------------------------------------------------- *)
let pp_where_constraint ppf (h1, cstr_kind, h2) =
Fmt.(
pair ~sep:sp (pp_hint ~is_ctx:false)
@@ pair ~sep:sp pp_constraint_kind (pp_hint ~is_ctx:false))
ppf
(h1, (cstr_kind, h2))
let pp_where_constraints ppf = function
| [] -> ()
| cstrs ->
Fmt.(prefix (const string "where ") @@ list ~sep:sp pp_where_constraint)
ppf
cstrs
let pp_method
ppf
( from_interface,
Aast.
{
m_name = (_, name);
m_tparams;
m_params;
m_ctxs;
m_ret;
m_static;
m_abstract;
m_final;
m_visibility;
m_user_attributes;
m_where_constraints;
_;
} ) =
Fmt.(
pf
ppf
"%a %a %a %a %a function %s%a%a%a%a%a%a"
pp_user_attrs
m_user_attributes
(cond ~pp_t:(const string "abstract") ~pp_f:nop)
(m_abstract && not from_interface)
(cond ~pp_t:(const string "final") ~pp_f:nop)
m_final
pp_visibility
m_visibility
(cond ~pp_t:(const string "static") ~pp_f:nop)
m_static
name
pp_tparams
m_tparams
pp_fun_params
m_params
(option pp_contexts)
m_ctxs
(pp_type_hint ~is_ret_type:true)
m_ret
pp_where_constraints
m_where_constraints
(cond
~pp_t:(const string ";")
~pp_f:(const string "{throw new \\Exception();}"))
(m_abstract || from_interface))
(* -- Properties -------------------------------------------------------- *)
let pp_xhp_attr_tag ppf = function
| Aast.Required -> Fmt.string ppf "@required"
| Aast.LateInit -> Fmt.string ppf "@lateinit"
let pp_xhp_attr_info ppf Aast.{ xai_tag; _ } =
Fmt.(option pp_xhp_attr_tag) ppf xai_tag
let pp_xhp_attr ppf (name, user_attrs, type_, init_val, xhp_attr_info) =
Fmt.(
pf
ppf
{|%a attribute %a %s %a %a;|}
pp_user_attrs
user_attrs
(option @@ pp_hint ~is_ctx:false)
type_
(String.lstrip ~drop:(fun c -> Char.equal c ':') name)
(option @@ prefix equal_to string)
init_val
pp_xhp_attr_info
xhp_attr_info)
let pp_prop ppf (name, is_static, visibility, user_attrs, type_, init_val) =
Fmt.(
pf
ppf
{|%a %a %a %a $%s%a;|}
pp_user_attrs
user_attrs
pp_visibility
visibility
(cond ~pp_t:(const string "static") ~pp_f:nop)
is_static
(option @@ pp_hint ~is_ctx:false)
type_
name
(option @@ prefix equal_to string)
init_val)
(* -- Type constants ---------------------------------------------------- *)
let pp_tyconst
ppf (name, is_abstract, is_ctx, type_, constraint_, user_attrs) =
Fmt.(
pf
ppf
{|%a %a const %a %s%a%a;|}
pp_user_attrs
user_attrs
(cond ~pp_t:(const string "abstract") ~pp_f:nop)
is_abstract
(cond ~pp_t:(const string "ctx") ~pp_f:(const string "type"))
is_ctx
name
(option @@ prefix (const string " as ") @@ pp_hint ~is_ctx:false)
constraint_
(option @@ prefix equal_to @@ pp_hint ~is_ctx)
type_)
(* -- Constants --------------------------------------------------------- *)
let pp_const ppf (name, is_abstract, type_, init_val) =
Fmt.(
pf
ppf
{|%a const %a %s %a;|}
(cond ~pp_t:(const string "abstract") ~pp_f:nop)
is_abstract
(option @@ pp_hint ~is_ctx:false)
type_
name
(option @@ prefix equal_to string)
init_val)
(* -- Top level --------------------------------------------------------- *)
let pp ppf = function
| EltMethod (from_interface, _, method_) ->
pp_method ppf (from_interface, method_)
| EltTargetMethod (_, src) -> Fmt.string ppf @@ SourceText.text src
| EltTypeConst
{ name; is_abstract; is_ctx; type_; constraint_; user_attrs; _ } ->
pp_tyconst
ppf
(name, is_abstract, is_ctx, type_, constraint_, user_attrs)
| EltConst { name; is_abstract; type_; init_val; _ } ->
pp_const ppf (name, is_abstract, type_, init_val)
| EltXHPAttr { name; user_attrs; type_; init_val; xhp_attr_info; _ } ->
pp_xhp_attr ppf (name, user_attrs, type_, init_val, xhp_attr_info)
| EltProp { name; is_static; visibility; user_attrs; type_; init_val; _ }
->
pp_prop ppf (name, is_static, visibility, user_attrs, type_, init_val)
end
module Class_decl : sig
type t
val name : t -> string
val line : t -> int
val of_class : Nast.class_ -> t
val pp : Format.formatter -> t -> unit
end = struct
type t = {
name: string;
line: int;
user_attrs: Nast.user_attribute list;
is_final: bool;
kind: Ast_defs.classish_kind;
tparams: Nast.tparam list;
extends: Aast.class_hint list;
implements: Aast.class_hint list;
}
let name { name; _ } = name
let line { line; _ } = line
let of_class
Aast.
{
c_name = (pos, name);
c_user_attributes;
c_final;
c_kind;
c_tparams;
c_extends;
c_implements;
_;
} =
{
name;
line = Pos.line pos;
user_attrs = c_user_attributes;
is_final = c_final;
kind = c_kind;
tparams = c_tparams;
extends = c_extends;
implements = c_implements;
}
let pp_classish_kind ppf =
Ast_defs.(
function
| Cclass k ->
(match k with
| Abstract -> Fmt.string ppf "abstract class"
| Concrete -> Fmt.string ppf "class")
| Cinterface -> Fmt.string ppf "interface"
| Ctrait -> Fmt.string ppf "trait"
| Cenum -> Fmt.string ppf "enum"
| Cenum_class k ->
(match k with
| Abstract -> Fmt.string ppf "abstract enum class"
| Concrete -> Fmt.string ppf "enum class"))
let pp_class_ancestors class_or_intf ppf = function
| [] ->
(* because we are prefixing the list with a constant string, we
match on the empty list here and noop to avoid priting "extends "
("implements ") with no class (interface) *)
()
| hints ->
let pfx =
match class_or_intf with
| `Class -> Fmt.(const string "extends ")
| `Interface -> Fmt.(const string "implements ")
in
Fmt.(prefix pfx @@ list ~sep:comma @@ pp_hint ~is_ctx:false) ppf hints
let pp
ppf
{ name; user_attrs; is_final; kind; tparams; extends; implements; _ } =
Fmt.(
pf
ppf
{|%a %a %a %s%a %a %a|}
pp_user_attrs
user_attrs
(cond ~pp_t:(const string "final") ~pp_f:nop)
is_final
pp_classish_kind
kind
(strip_ns name)
pp_tparams
tparams
(pp_class_ancestors `Class)
extends
(pp_class_ancestors `Interface)
implements)
end
module Class_body : sig
type t
val of_class : Nast.class_ -> Class_elt.t list -> t
val pp : Format.formatter -> t -> unit
end = struct
type t = {
uses: Aast.trait_hint list;
req_extends: Aast.class_hint list;
req_implements: Aast.class_hint list;
req_class: Aast.class_hint list;
elements: Class_elt.t list;
}
let filter_constructor_props elts =
let ctr_props =
Option.value ~default:SSet.empty
@@ Option.bind ~f:Class_elt.method_props
@@ List.find elts ~f:(fun elt ->
Class_elt.is_method elt ~method_name:"__construct")
in
List.filter elts ~f:(fun elt ->
Option.value_map ~default:true ~f:(fun prop_name ->
not @@ SSet.mem prop_name ctr_props)
@@ Class_elt.prop_name elt)
let of_class Aast.{ c_uses; c_reqs; _ } class_elts =
let (req_extends, req_implements, req_class) =
Aast.partition_map_require_kind ~f:fst c_reqs
in
let elements =
filter_constructor_props
@@ List.sort ~compare:Class_elt.compare class_elts
in
{ uses = c_uses; req_extends; req_implements; req_class; elements }
let pp_use_extend ppf = function
| ([], [], [], []) ->
(* In the presence of any traits or trait/interface requirements
we add a cut after them to match the Hack style given in the docs
(line breaks are not added by HackFmt). We need to check that
we have no traits or requirements here else we end up with
an unnecessary line break in this case *)
()
| (uses, req_extends, req_implements, req_class) ->
let pp_elem pfx ppf hint =
Fmt.(prefix pfx @@ suffix semicolon @@ pp_hint ~is_ctx:false) ppf hint
in
Fmt.(
suffix cut
@@ pair ~sep:nop (list @@ pp_elem @@ const string "use ")
@@ triple
~sep:nop
(list @@ pp_elem @@ const string "require extends ")
(list @@ pp_elem @@ const string "require implements ")
(list @@ pp_elem @@ const string "require is"))
ppf
(uses, (req_extends, req_implements, req_class))
let pp_elts ppf = function
| [] -> ()
| elts -> Fmt.(list ~sep:cut @@ prefix cut Class_elt.pp) ppf elts
let pp ppf { uses; req_extends; req_implements; req_class; elements } =
Fmt.(pair ~sep:nop pp_use_extend pp_elts)
ppf
((uses, req_extends, req_implements, req_class), elements)
end
type t =
| ClsGroup of {
decl: Class_decl.t;
body: Class_body.t;
}
| Single of Single.t
let name = function
| ClsGroup { decl; _ } -> Class_decl.name decl
| Single single -> Single.name single
let line = function
| ClsGroup { decl; _ } -> Class_decl.line decl
| Single single -> Single.line single
let compare g1 g2 = Int.compare (line g1) (line g2)
let of_class (ast, class_elts) =
ClsGroup
{
decl = Class_decl.of_class ast;
body = Class_body.of_class ast class_elts;
}
let pp ppf = function
| ClsGroup { decl; body; _ } ->
Fmt.(pair Class_decl.pp @@ braces @@ vbox Class_body.pp) ppf (decl, body)
| Single single -> Single.pp ppf single
(* -- Classify and group extracted dependencies --------------------------- *)
type dep_part =
| PartClsElt of string * Class_elt.t
| PartSingle of Single.t
| PartCls of string
| PartIgnore
let of_method ctx cls_name method_name =
let is_interface = Nast_helper.is_interface ctx cls_name in
Option.value_map ~default:PartIgnore ~f:(fun ast ->
PartClsElt (cls_name, Class_elt.(mk_method is_interface ast)))
@@ Nast_helper.get_method ctx cls_name method_name
let of_dep ctx dep =
Typing_deps.Dep.(
match dep with
(* -- Class elements -- *)
| Const (cls_nm, nm)
when String.(cls_nm = Dep.get_origin ctx cls_nm dep && nm <> "class")
&& (not @@ Nast_helper.is_enum_or_enum_class ctx cls_nm) ->
PartClsElt
( cls_nm,
value_or_not_found (cls_nm ^ "::" ^ nm)
@@ Option.(
first_some
(map ~f:Class_elt.mk_tyconst
@@ Nast_helper.get_typeconst ctx cls_nm nm)
(map ~f:Class_elt.(mk_const ctx)
@@ Nast_helper.get_const ctx cls_nm nm)) )
| Method (cls_nm, nm) when String.(cls_nm = Dep.get_origin ctx cls_nm dep)
->
of_method ctx cls_nm nm
| SMethod (cls_nm, nm)
when String.(cls_nm = Dep.get_origin ctx cls_nm dep) ->
of_method ctx cls_nm nm
| Constructor cls_nm when String.(cls_nm = Dep.get_origin ctx cls_nm dep)
->
let nm = "__construct" in
of_method ctx cls_nm nm
| Prop (cls_nm, nm) when String.(cls_nm = Dep.get_origin ctx cls_nm dep)
->
PartClsElt
( cls_nm,
value_or_not_found (cls_nm ^ "::" ^ nm)
@@ Option.map ~f:Class_elt.(mk_prop ctx)
@@ Nast_helper.get_prop ctx cls_nm nm )
| SProp (cls_nm, snm) when String.(cls_nm = Dep.get_origin ctx cls_nm dep)
->
let nm = String.lstrip ~drop:(fun c -> Char.equal c '$') snm in
PartClsElt
( cls_nm,
value_or_not_found (cls_nm ^ "::" ^ nm)
@@ Option.map ~f:Class_elt.(mk_prop ctx)
@@ Nast_helper.get_prop ctx cls_nm nm )
(* -- Globals -- *)
| Fun nm -> PartSingle (Single.mk_gfun @@ Nast_helper.get_fun_exn ctx nm)
| GConst nm
| GConstName nm ->
PartSingle (Single.mk_gconst ctx @@ Nast_helper.get_gconst_exn ctx nm)
(* -- Type defs, Enums, Classes -- *)
| Type nm when Nast_helper.is_tydef ctx nm ->
PartSingle (Single.mk_tydef @@ Nast_helper.get_typedef_exn ctx nm)
| Type nm when Nast_helper.is_enum_or_enum_class ctx nm ->
PartSingle (Single.mk_enum ctx @@ Nast_helper.get_class_exn ctx nm)
| Type nm when Nast_helper.is_class ctx nm -> PartCls nm
| Type _ -> raise Unsupported
(* -- Ignore -- *)
| Const _
| Method _
| SMethod _
| Constructor _
| Prop _
| SProp _
| AllMembers _
| Extends _
(* TODO(T108206307) *)
| Module _ ->
PartIgnore)
let of_deps ctx target_opt deps =
let insert_elt (sgls, grps) (cls_nm, cls_elt) =
( sgls,
SMap.update
cls_nm
(function
| Some (cls_ast, cls_elts) -> Some (cls_ast, cls_elt :: cls_elts)
| _ ->
let cls_ast = Nast_helper.get_class_exn ctx cls_nm in
Some (cls_ast, [cls_elt]))
grps )
and insert_cls (sgls, grps) cls_nm =
( sgls,
SMap.update
cls_nm
(function
| Some _ as data -> data
| _ ->
let cls_ast = Nast_helper.get_class_exn ctx cls_nm in
Some (cls_ast, []))
grps )
and insert_single (sgls, grps) single = (Single single :: sgls, grps)
and insert_target (sgls, grps) =
match target_opt with
| Some (Cmd.Function fun_name as tgt) ->
let sgl = Single.mk_target_fun ctx (fun_name, tgt) in
(Single sgl :: sgls, grps)
| Some (Cmd.Method (cls_name, method_name) as tgt) ->
( sgls,
SMap.update
cls_name
(function
| Some (cls_ast, elts) ->
let elt = Class_elt.mk_target_method ctx tgt
and elts' =
List.filter
~f:(fun elt -> not @@ Class_elt.is_method ~method_name elt)
elts
in
Some (cls_ast, elt :: elts')
| _ ->
let cls_ast = Nast_helper.get_class_exn ctx cls_name
and elt = Class_elt.mk_target_method ctx tgt in
Some (cls_ast, [elt]))
grps )
| None -> (sgls, grps)
in
let (sgls, clss) =
insert_target
@@ List.fold_left deps ~init:([], SMap.empty) ~f:(fun acc dep ->
match of_dep ctx dep with
| PartCls cls_nm -> insert_cls acc cls_nm
| PartClsElt (cls_nm, elt) -> insert_elt acc (cls_nm, elt)
| PartSingle single -> insert_single acc single
| _ -> acc)
in
List.append sgls @@ List.map ~f:of_class @@ SMap.values clss
end
(* -- Dependencies nested into namespaces ----------------------------------- *)
module Namespaced : sig
type t
val unfold : Grouped.t list -> t
val pp : Format.formatter -> t -> unit
end = struct
type t = {
line: int option;
deps: Grouped.t list;
children: (string * t) list;
}
let rec pp_ ppf { deps; children; _ } =
(* We guard against empty list of depedencies or nested namespaces here
since we should add a cut between them only when both are non-empty
*)
match (deps, children) with
| (_, []) -> Fmt.(list ~sep:cut @@ suffix cut Grouped.pp) ppf deps
| ([], _) -> Fmt.(list ~sep:cut pp_children) ppf children
| _ ->
Fmt.(
pair
~sep:cut
(list ~sep:cut @@ suffix cut Grouped.pp)
(list ~sep:cut pp_children))
ppf
(deps, children)
and pp_children ppf (nm, t) =
Fmt.(pair (prefix (const string "namespace ") string) (braces pp_))
ppf
(nm, t)
let pp ppf t = Fmt.(vbox @@ prefix cut pp_) ppf t
let namespace_of dep =
Grouped.name dep
|> String.rsplit2_exn ~on:'\\'
|> fst
|> String.strip ~drop:(Char.equal '\\')
|> String.split ~on:'\\'
|> List.filter ~f:String.((fun s -> not @@ is_empty s))
let group_by_prefix deps =
Tuple2.map_snd ~f:SMap.elements
@@ List.fold
~init:([], SMap.empty)
~f:
(fun (toplvl, nested) -> function
| ([], dep) -> (dep :: toplvl, nested)
| (ns :: nss, dep) ->
( toplvl,
SMap.update
ns
(function
| Some deps -> Some ((nss, dep) :: deps)
| _ -> Some [(nss, dep)])
nested ))
deps
let unfold deps =
let compare_line (_, { line = ln1; _ }) (_, { line = ln2; _ }) =
Option.compare Int.compare ln1 ln2
in
let rec aux ~k b =
let (unsorted, dss) = group_by_prefix b in
let deps = List.sort ~compare:Grouped.compare unsorted in
let line = Option.map ~f:Grouped.line @@ List.hd deps in
auxs dss ~k:(fun unsorted_cs ->
let children = List.sort ~compare:compare_line unsorted_cs in
k { deps; line; children })
and auxs ~k = function
| [] -> k []
| (ns, next) :: rest ->
auxs rest ~k:(fun rest' ->
aux next ~k:(fun next' -> k @@ ((ns, next') :: rest')))
in
aux ~k:Fn.id @@ List.map ~f:(fun dep -> (namespace_of dep, dep)) deps
end
(* -- Hack format wrapper --------------------------------------------------- *)
module Hackfmt : sig
val format : string -> string
end = struct
let print_error source_text error =
let text =
SyntaxError.to_positioned_string
error
(SourceText.offset_to_position source_text)
in
Hh_logger.log "%s\n" text
let tree_from_string s =
let source_text = SourceText.make Relative_path.default s in
let mode = Full_fidelity_parser.parse_mode source_text in
let env = Full_fidelity_parser_env.make ?mode () in
let tree = SyntaxTree.make ~env source_text in
if List.is_empty (SyntaxTree.all_errors tree) then
tree
else (
List.iter (SyntaxTree.all_errors tree) ~f:(print_error source_text);
raise Hackfmt_error.InvalidSyntax
)
let tidy_xhp =
let re = Str.regexp "\\\\:" in
Str.global_replace re ":"
let format text =
try Libhackfmt.format_tree @@ tree_from_string @@ tidy_xhp text with
| Hackfmt_error.InvalidSyntax -> text
end
(* -- Per-file grouped dependencies ----------------------------------------- *)
module File : sig
type t
val compare : t -> t -> int
val of_deps :
Provider_context.t ->
Relative_path.t * Cmd.target ->
Relative_path.t option
* Typing_deps.Dep.dependency Typing_deps.Dep.variant list ->
t
val pp : is_multifile:bool -> Format.formatter -> t -> unit
end = struct
type t = {
is_target: bool;
name: string;
content: Namespaced.t;
}
let compare
{ is_target = tgt1; name = nm1; _ } { is_target = tgt2; name = nm2; _ } =
if tgt1 && tgt2 then
0
else if tgt1 then
-1
else if tgt2 then
1
else
String.compare nm2 nm1
let of_deps ctx (target_path, target) (path, deps) =
let is_target =
Option.value_map ~default:false ~f:(Relative_path.equal target_path) path
in
{
is_target;
name =
Option.value_map ~default:__UNKNOWN_FILE__ ~f:Relative_path.suffix path;
content =
Namespaced.unfold
@@ Grouped.of_deps
ctx
(if is_target then
Some target
else
None)
deps;
}
let pp_header ppf name =
Fmt.(hbox @@ pair ~sep:sp string string) ppf (__FILE_PREFIX__, name)
let to_string ~is_multifile { content; name; _ } =
let body = Hackfmt.format @@ Fmt.to_to_string Namespaced.pp content in
if is_multifile then
let header = Fmt.to_to_string pp_header name in
Format.sprintf "%s\n%s\n%s" header __HH_HEADER_PREFIX__ body
else
Format.sprintf "%s\n%s" __HH_HEADER_PREFIX__ body
let pp ~is_multifile = Fmt.of_to_string (to_string ~is_multifile)
end
(* -- All releveant dependencies organized by file -------------------------- *)
module Standalone : sig
type t
val generate :
Provider_context.t ->
Cmd.target ->
bool * bool * Typing_deps.Dep.dependency Typing_deps.Dep.variant list ->
t
val to_string : t -> string
end = struct
type t = {
dep_default: bool;
dep_any: bool;
files: File.t list;
}
let generate ctx target (dep_default, dep_any, deps) =
let target_path = Target.relative_path ctx target in
let files =
List.sort ~compare:File.compare
@@ List.map ~f:File.(of_deps ctx (target_path, target))
@@ SMap.values
@@ SMap.update (Relative_path.to_absolute target_path) (function
| Some _ as data -> data
| _ -> Some (Some target_path, []))
@@ List.fold_left deps ~init:SMap.empty ~f:(fun acc dep ->
let rel_path = Dep.get_relative_path ctx dep in
let key =
Option.value_map
~default:"unknown"
~f:Relative_path.to_absolute
rel_path
in
SMap.update
key
(function
| Some (path, deps) -> Some (path, dep :: deps)
| _ -> Some (rel_path, [dep]))
acc)
in
{ dep_default; dep_any; files }
let __DEPS_ON_DEFAULT__ =
Format.sprintf
{|@.const nothing %s = HH\FIXME\UNSAFE_CAST<mixed, nothing>("");@.|}
__CONST_DEFAULT__
let __DEPS_ON_ANY__ =
Format.sprintf
{|/* HH_FIXME[4101] */@.type %s = \%s_;@.type %s_<T> = T;|}
Hint_print.any_type_name
Hint_print.any_type_name
Hint_print.any_type_name
let pp_helpers ppf (deps_on_default, deps_on_any) =
if deps_on_default && deps_on_any then
Fmt.pf
ppf
{|%s %s@.%s@.%s@.%s@.|}
__FILE_PREFIX__
__DUMMY_FILE__
__HH_HEADER_PREFIX__
__DEPS_ON_DEFAULT__
__DEPS_ON_ANY__
else if deps_on_default then
Fmt.pf
ppf
{|%s %s@.%s@.%s@.|}
__FILE_PREFIX__
__DUMMY_FILE__
__HH_HEADER_PREFIX__
__DEPS_ON_DEFAULT__
else if deps_on_any then
Fmt.pf
ppf
{|%s %s@.%s@.%s@.|}
__FILE_PREFIX__
__DUMMY_FILE__
__HH_HEADER_PREFIX__
__DEPS_ON_ANY__
else
()
let pp ppf { dep_default; dep_any; files } =
if dep_default || dep_any then
Fmt.(pair ~sep:cut (list @@ File.pp ~is_multifile:true) pp_helpers)
ppf
(files, (dep_default, dep_any))
else
let is_multifile =
match files with
| _ :: _ :: _ -> true
| _ -> false
in
Fmt.(list @@ File.pp ~is_multifile) ppf files
let to_string = Fmt.to_to_string pp
end
let go ctx target =
try
Standalone.to_string
@@ Standalone.generate ctx target
@@ Extract.collect_dependencies ctx target
with
| DependencyNotFound d -> Printf.sprintf "Dependency not found: %s" d
| (Unsupported | UnexpectedDependency) as exn ->
let e = Exception.wrap exn in
Exception.to_string e |
OCaml Interface | hhvm/hphp/hack/src/server/serverExtractStandalone.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 :
Provider_context.t -> ServerCommandTypes.Extract_standalone.target -> string |
OCaml | hhvm/hphp/hack/src/server/serverFileDependents.ml | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE fn in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module DepSet = Typing_deps.DepSet
module Dep = Typing_deps.Dep
(* Given the naming table, a list of relative paths,
* find the list of relative paths of all dependencies *)
let deps_of_paths ctx workers naming_table relative_paths =
let deps_mode = Provider_context.get_deps_mode ctx in
let find_dependencies acc paths =
let fileinfos =
List.filter_map ~f:(Naming_table.get_file_info naming_table) paths
in
let initial_deps =
List.fold_left fileinfos ~init:(DepSet.make ()) ~f:(fun acc fileinfo ->
let deps =
Typing_deps.deps_of_file_info fileinfo |> Typing_deps.DepSet.of_list
in
DepSet.union acc deps)
in
DepSet.union acc (Typing_deps.add_all_deps deps_mode initial_deps)
in
let all_deps =
MultiWorker.call
workers
~job:find_dependencies
~neutral:(DepSet.make ())
~merge:DepSet.union
~next:(MultiWorker.next workers relative_paths)
in
all_deps |> Naming_provider.get_files ctx |> Relative_path.Set.elements
let go (genv : ServerEnv.genv) (env : ServerEnv.env) (filenames : string list) =
let ctx = Provider_utils.ctx_from_server_env env in
let workers = genv.ServerEnv.workers in
let naming_table = env.ServerEnv.naming_table in
let paths = List.map ~f:Relative_path.create_detect_prefix filenames in
let all_deps = deps_of_paths ctx workers naming_table paths in
List.map ~f:Relative_path.to_absolute all_deps |
OCaml | hhvm/hphp/hack/src/server/serverFiles.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 Utils
let tmp : Path.t option ref = ref None
(** Normally, the ServerFiles.* functions use GlobalConfig.tmp_dir
which is initialized at startup to be either HH_TMPDIR if defined
or /tmp/hh_server otherwise.
But some tests like to use these ServerFiles.* functions with a
different tmpdir chosen at runtime. These tests can call
ServerFiles.set_tmp_FOR_TESTING_ONLY, and all subsequent ServerFiles.*
will refer to that new tmp directory.
CARE! This is only to be used in limited circumstances. All the
rest of the codebase will continue to use HH_TMPDIR-or-/tmp/hh_server.
This only affects the ServerFiles.* functions; nothing else.
You have been warned. *)
let set_tmp_FOR_TESTING_ONLY (t : Path.t) : unit = tmp := Some t
let get_tmp () : string =
Option.value_map !tmp ~f:Path.to_string ~default:GlobalConfig.tmp_dir
(** Slash-escaped path in the system temp directory corresponding
with this root directory for this extension. *)
let path_of_root root extension =
(* TODO: move this to places that write this file *)
Sys_utils.mkdir_no_fail (get_tmp ());
let root_part = Path.slash_escaped_string_of_path root in
Filename.concat (get_tmp ()) (spf "%s.%s" root_part extension)
let is_of_root root fn =
let root_part = Path.slash_escaped_string_of_path root in
String.is_prefix fn ~prefix:(Filename.concat (get_tmp ()) root_part)
(**
* Lock on this file will be held after the server has finished initializing.
* *)
let lock_file root = path_of_root root "lock"
let log_link root = path_of_root root "log"
let pids_file root = path_of_root root "pids"
let socket_file root = path_of_root root "sock"
let dfind_log root = path_of_root root "dfind"
let client_log root = path_of_root root "client_log"
let client_lsp_log root = path_of_root root "client_lsp_log"
let client_ide_log root = path_of_root root "client_ide_log"
let client_ide_naming_table root = path_of_root root "client_ide_naming_table"
let monitor_log_link root = path_of_root root "monitor_log"
let errors_file_path (root : Path.t) : string = path_of_root root "errors.bin"
let server_finale_file (pid : int) : string =
Filename.concat (get_tmp ()) (spf "%d.fin" pid)
let server_progress_file (root : Path.t) : string =
path_of_root root "progress.json"
let server_receipt_to_monitor_file (pid : int) : string =
Filename.concat (get_tmp ()) (spf "server_receipt_to_monitor.%d.json" pid) |
OCaml | hhvm/hphp/hack/src/server/serverFileSync.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Option.Monad_infix
open ServerEnv
let try_relativize_path x =
Option.try_with (fun () -> Relative_path.(create Root x))
let get_file_content_from_disk_rel (path : Relative_path.t) : string option =
let f () = Sys_utils.cat (Relative_path.to_absolute path) in
Option.try_with f
let get_file_content_from_disk (path : string) : string =
match try_relativize_path path with
| None -> ""
| Some path -> get_file_content_from_disk_rel path |> Option.value ~default:""
let get_file_content = function
| ServerCommandTypes.FileContent s -> s
| ServerCommandTypes.FileName path ->
try_relativize_path path
>>= (fun path ->
match File_provider.get path with
| Some (File_provider.Ide f) -> Some f
| Some (File_provider.Disk c) -> Some c
| None -> get_file_content_from_disk_rel path)
(* In case of errors, proceed with empty file contents *)
|> Option.value ~default:""
let open_file
~(predeclare : bool)
(env : ServerEnv.env)
(path : string)
(content : string) : ServerEnv.env =
let prev_content = get_file_content (ServerCommandTypes.FileName path) in
match try_relativize_path path with
| None -> env
| Some path ->
(* Before making any changes, pre-load (into Decl_heap) currently existing
* declarations so there is always a previous version to compare against,
* which makes incremental mode perform better. *)
(if predeclare && not (Relative_path.Set.mem env.editor_open_files path)
then
let ctx = Provider_utils.ctx_from_server_env env in
Decl.make_env ~sh:SharedMem.Uses ctx path);
let editor_open_files = Relative_path.Set.add env.editor_open_files path in
File_provider.remove_batch (Relative_path.Set.singleton path);
File_provider.provide_file_for_ide path content;
let ide_needs_parsing =
if
String.equal content prev_content
&& is_full_check_done env.full_check_status
then
(* Try to avoid telling the user that a check is needed when the file
* was unchanged. But even in this case, we might need to push
* errors that were previously throttled. They are available only
* when full recheck was completed and there were no further changes. In
* all other cases, we will need to (lazily) recheck the file. *)
env.ide_needs_parsing
else
Relative_path.Set.add env.ide_needs_parsing path
in
Ide_info_store.open_file path;
(* Need to re-parse this file during next full check to update
* global error list positions that refer to it *)
let disk_needs_parsing =
Relative_path.Set.add env.disk_needs_parsing path
in
let last_command_time = Unix.gettimeofday () in
{
env with
editor_open_files;
ide_needs_parsing;
last_command_time;
disk_needs_parsing;
}
let close_relative_path (env : ServerEnv.env) (path : Relative_path.t) :
ServerEnv.env =
let editor_open_files = Relative_path.Set.remove env.editor_open_files path in
let contents =
match File_provider.get_unsafe path with
| File_provider.Ide f -> f
| _ -> assert false
in
File_provider.remove_batch (Relative_path.Set.singleton path);
let new_contents = File_provider.get_contents path in
let ide_needs_parsing =
match new_contents with
| Some c when String.equal c contents -> env.ide_needs_parsing
| _ -> Relative_path.Set.add env.ide_needs_parsing path
in
Ide_info_store.close_file path;
let disk_needs_parsing = Relative_path.Set.add env.disk_needs_parsing path in
let last_command_time = Unix.gettimeofday () in
{
env with
editor_open_files;
ide_needs_parsing;
last_command_time;
disk_needs_parsing;
}
let close_file (env : ServerEnv.env) (path : string) : ServerEnv.env =
let new_env = try_relativize_path path >>| close_relative_path env in
Option.value new_env ~default:env
let edit_file ~predeclare env path (edits : File_content.text_edit list) =
let new_env =
try_relativize_path path >>= fun path ->
(* See similar predeclare in open_file function *)
(if predeclare && not (Relative_path.Set.mem env.editor_open_files path)
then
let ctx = Provider_utils.ctx_from_server_env env in
Decl.make_env ~sh:SharedMem.Uses ctx path);
let (_ : ServerEnv.seconds option) =
ServerBusyStatus.send ServerCommandTypes.Needs_local_typecheck
in
let file_content =
match File_provider.get path with
| Some (File_provider.Ide content)
| Some (File_provider.Disk content) ->
content
| None ->
(try Sys_utils.cat (Relative_path.to_absolute path) with
| _ -> "")
in
let edited_file_content =
match File_content.edit_file file_content edits with
| Ok new_content -> new_content
| Error (reason, e) ->
Hh_logger.log "SERVER_FILE_EDITED_ERROR - %s" reason;
HackEventLogger.server_file_edited_error e ~reason;
Exception.reraise e
in
let editor_open_files = Relative_path.Set.add env.editor_open_files path in
File_provider.remove_batch (Relative_path.Set.singleton path);
File_provider.provide_file_for_ide path edited_file_content;
let ide_needs_parsing = Relative_path.Set.add env.ide_needs_parsing path in
let disk_needs_parsing =
Relative_path.Set.add env.disk_needs_parsing path
in
let last_command_time = Unix.gettimeofday () in
Some
{
env with
editor_open_files;
ide_needs_parsing;
last_command_time;
disk_needs_parsing;
}
in
Option.value new_env ~default:env
let clear_sync_data env =
let env =
Relative_path.Set.fold env.editor_open_files ~init:env ~f:(fun x env ->
close_relative_path env x)
in
Ide_info_store.ide_disconnect ();
env
(** Determine which files are different in the IDE and on disk.
This is achieved using File_provider for the IDE content and reading file from disk.
Returns a map from filename to a tuple of ide contents and disk contents. *)
let get_unsaved_changes env =
Relative_path.Set.fold
env.editor_open_files
~init:Relative_path.Map.empty
~f:(fun path acc ->
match File_provider.get path with
| Some (File_provider.Ide ide_contents) -> begin
match get_file_content_from_disk_rel path with
| Some disk_contents when not (String.equal ide_contents disk_contents)
->
Relative_path.Map.add acc ~key:path ~data:(ide_contents, disk_contents)
| Some _ -> acc
| None ->
(* If one creates a new file, then there will not be corresponding
* disk contents, and we should consider there to be unsaved changes in
* the editor. *)
Relative_path.Map.add acc ~key:path ~data:(ide_contents, "")
end
| _ -> acc)
let has_unsaved_changes env =
not @@ Relative_path.Map.is_empty (get_unsaved_changes env) |
OCaml Interface | hhvm/hphp/hack/src/server/serverFileSync.mli | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(** We maintains state about editor open files and their contents
- some in ServerEnv.env e.g. editor_open_files, some in global sharedmem like FileProvider.
Functions in this module update those states;
they get invoked when an open/edit/close event happens in the editor.
These file events are made known to the server via RPC commands. *)
(** Notify hh of a file opening. *)
val open_file :
predeclare:bool -> ServerEnv.env -> string -> string -> ServerEnv.env
(** Notify hh when first editing a file. *)
val edit_file :
predeclare:bool ->
ServerEnv.env ->
string ->
File_content.text_edit list ->
ServerEnv.env
(** Notify hh of closing a file. *)
val close_file : ServerEnv.env -> string -> ServerEnv.env
(** Call this when losing connection with IDE to clear data
that we have about this IDE. *)
val clear_sync_data : ServerEnv.env -> ServerEnv.env
(** Get file content from File_provider if present, otherwise from disk.
If the argument is [ServerCommandTypes.FileName path] for a path that's not
under Root, or if we get an exception trying to read the file (e.g. because
it has been deleted), then return the empty string. See also
[get_file_content_from_disk] which skips File_provider. *)
val get_file_content : ServerCommandTypes.file_input -> string
(** Get file content from disk. If the path isn't under Root, or we get
an exception trying to read the file (e.g. because it has been deleted) then
return the empty string. See also [get_file_content] which looks up
File_provider first. *)
val get_file_content_from_disk : string -> string
val has_unsaved_changes : ServerEnv.env -> bool
(** Determine which files are different in the IDE and on disk.
Returns a map from filename to a tuple of ide contents and disk contents. *)
val get_unsaved_changes : ServerEnv.env -> (string * string) Relative_path.Map.t |
OCaml | hhvm/hphp/hack/src/server/serverFindLocals.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
module PosSet = Caml.Set.Make (Pos)
module LocalPositions = struct
(**
* Local positions is a map from an identifier -- a unique integer that
* identifies a local "symbol" -- to a set of all known positions where
* that local is used.
*
* Identifiers that identify no known local produce an empty set of
* positions.
*)
type t = PosSet.t IMap.t
let empty = IMap.empty
let get ident locals =
let current = IMap.find_opt ident locals in
Option.value ~default:PosSet.empty current
let add ident pos locals =
let positions = get ident locals in
IMap.add ident (PosSet.add pos positions) locals
end
(* End of module LocalPositions *)
module ScopeChain = struct
(**
* A scope maps from a string (the text of the use of a local) to an
* ident (a unique integer associated with this local symbol).
*
* A scope chain is a stack of scopes. If there is a match at the head
* of the stack, that match shadows any matches in the tail. Otherwise,
* the tail is checked.
*)
type scope = Ident.t SMap.t
type t = scope list
(*
* In correct code locals are always found inside a function, method or
* lambda, and so there is always a scope already pushed on the scope chain
* when the local is added. However, suppose we are in erroneous code, such
* that the parser has parsed a local expression that is not inside a
* function. In that case we might attempt to add a local to the current
* scope with an empty scope chain.
*
* Therefore we head every scope chain with a "dummy" scope that can be
* used for these error cases.
*)
let empty = [SMap.empty]
let push scopechain = SMap.empty :: scopechain
let pop scopechain =
match scopechain with
| _ :: t -> t
| _ -> failwith "popping empty scope chain"
let add name ident scopechain =
match scopechain with
| h :: t -> SMap.add name ident h :: t
| _ -> failwith "adding name to empty scope chain"
let rec get name scopechain =
match scopechain with
| [] -> None
| h :: t ->
let result = SMap.find_opt name h in
if Option.is_none result then
get name t
else
result
end
(* End of module ScopeChain *)
module ScopeChains = struct
(**
* A "scope chain" is a stack of maps from names to idents. You might
* think that would be sufficient, but unfortunately it is not.
*
* When we have a nested function (not a lambda), then the scope chain
* from outside the nested function is not accessible inside the nested
* function. Rather, a new scope chain is created which has on it the
* formal parameters and the variables inherited from the outer scope chain
* by the "use" clause. We therefore have a stack of scope chains.
*)
type t = ScopeChain.t list
let head scopechains =
match scopechains with
| h :: _ -> h
| _ -> failwith "Scope chain stack is empty"
let previous scopechains =
match scopechains with
| _ :: p :: _ -> p
| _ -> failwith "Scope chain stack is too small"
let pop scopechains =
match scopechains with
| _ :: t -> t
| _ -> failwith "Scope chain stack is empty"
let replace_head scopechain scopechains = scopechain :: pop scopechains
let push scopechain scopechains = scopechain :: scopechains
end
(* End of module ScopeChains *)
module LocalMap = struct
(**
* A "local map" is a scope chain stack and a local positions map.
* When a usage of a local is encountered, there are several possibilities
* for what has to happen next.
*
* (1) The most common scenario is: we've seen this local before. We look
* it up in the current scope chain, get a hit, and move on.
*
* (2) If this is the first time we've seen this perfectly ordinary local
* then we make a new identifer and add it to the scope chain.
*
* (3) There are some situations where we know we must introduce a new ident
* even if the name is in scope. Those situations include: a local is
* introduced by a formal parameter, a local is introduced by a catch
* clause, a function static shadows an existing local.
*
* (4) Finally, we need to do a lot of work to correctly handle a nested
* anonymous function with a "use" clause. See below for the details.
*
* Regardless, we add the position to the local positions map.
*
* We have a particular target local in mind but we only know its position.
* When we encounter a local at that position, we'll make a note of the
* ident so that we can look up the associated positions later.
*)
type t = {
scopechains: ScopeChains.t;
locals: LocalPositions.t;
target_line: int;
target_char: int;
target_ident: Ident.t option;
}
let make target_line target_char =
{
scopechains = [ScopeChain.empty];
locals = LocalPositions.empty;
target_line;
target_char;
target_ident = None;
}
let current_scopechain localmap = ScopeChains.head localmap.scopechains
let previous_scopechain localmap = ScopeChains.previous localmap.scopechains
let replace_head scopechain localmap =
let scopechains =
ScopeChains.replace_head scopechain localmap.scopechains
in
{ localmap with scopechains }
let push localmap =
let scopechain = ScopeChain.push (current_scopechain localmap) in
replace_head scopechain localmap
let pop localmap =
let scopechain = ScopeChain.pop (current_scopechain localmap) in
replace_head scopechain localmap
let push_scopechain localmap =
let scopechains = ScopeChains.push ScopeChain.empty localmap.scopechains in
{ localmap with scopechains }
let pop_scopechain localmap =
let scopechains = ScopeChains.pop localmap.scopechains in
{ localmap with scopechains }
let overlaps pos localmap =
let (pos_line, pos_start, pos_end) = Pos.info_pos pos in
(* Pos.t uses zero-indexed offsets, whereas the IDE target char is one-indexed. *)
let target_end_offset = localmap.target_char - 1 in
pos_line = localmap.target_line
&& pos_start <= localmap.target_char
&& target_end_offset <= pos_end
let get_target_ident ident pos localmap =
if Option.is_none localmap.target_ident && overlaps pos localmap then
Some ident
else
localmap.target_ident
(**
* This version of add always overwrites the existing scope entry, even
* if there's a local of this name already in scope. We need this for:
*
* function ($x) {
* $y = $x;
* static $x = 123;
* $z = $x;
* }
*
* We have two variables both named $x, one formal and one static. The
* later comes into scope at the point of its declaration, and is in
* scope for the rest of the body. The easiest way to model this is to
* simply replace the existing scope entry, if there is one.
*)
let force_add name pos localmap =
let ident = Ident.make name in
let current = current_scopechain localmap in
let scopechain = ScopeChain.add name ident current in
let scopechains =
ScopeChains.replace_head scopechain localmap.scopechains
in
let locals = LocalPositions.add ident pos localmap.locals in
let target_ident = get_target_ident ident pos localmap in
{ localmap with scopechains; locals; target_ident }
(**
* When we encounter a |> operator, we need to push a scope on the right
* side and add a brand-new $$ to that scope, but we do not yet have a
* position for it!
*)
let add_dollardollar localmap =
let name = "$$" in
let ident = Ident.make name in
let current = current_scopechain localmap in
let scopechain = ScopeChain.add name ident current in
let scopechains =
ScopeChains.replace_head scopechain localmap.scopechains
in
{ localmap with scopechains }
(* Returns an (ident, bool) where the bool is true if the ident was found. *)
let find_or_create_ident name localmap =
let current = current_scopechain localmap in
let result = ScopeChain.get name current in
match result with
| None -> (Ident.make name, false)
| Some ident -> (ident, true)
(**
* This version of add only adds an entry to the current scope if we haven't
* got a binding for this name.
*)
let add name pos localmap =
let (ident, found) = find_or_create_ident name localmap in
let scopechains =
if found then
localmap.scopechains
else
let current = current_scopechain localmap in
let scopechain = ScopeChain.add name ident current in
ScopeChains.replace_head scopechain localmap.scopechains
in
let locals = LocalPositions.add ident pos localmap.locals in
let target_ident = get_target_ident ident pos localmap in
{ localmap with scopechains; locals; target_ident }
let add_from_use name pos localmap =
(*
* When adding an item from a use clause we've got to do a couple
* things. First, the variables mentioned in the use clause are
* mentions of those variables, so they need to go in the list of
* positions. Second, the binding from the name to its id from the
* _previous_ scopechain needs to be copied into the _current_
* scopechain. *)
let current = current_scopechain localmap in
let previous = previous_scopechain localmap in
let canonical = ScopeChain.get name previous in
(* The user may have given a variable in the use clause which does not
exist. In that case, just make up a new ident. *)
let ident =
match canonical with
| None -> Ident.make name
| Some ident -> ident
in
(* Regardless, this is a mention of that local. *)
let locals = LocalPositions.add ident pos localmap.locals in
let scopechain = ScopeChain.add name ident current in
let scopechains =
ScopeChains.replace_head scopechain localmap.scopechains
in
let target_ident = get_target_ident ident pos localmap in
{ localmap with scopechains; locals; target_ident }
let results localmap =
let results_set =
match localmap.target_ident with
| Some ident -> LocalPositions.get ident localmap.locals
| _ -> PosSet.empty
in
PosSet.elements results_set
end
(* End of module LocalMap *)
(*
* Here begins the code which walks the AST and accumulates the positions
* of every local in this file.
*)
class local_finding_visitor =
object (this)
inherit [LocalMap.t] Nast.Visitor_DEPRECATED.visitor as _super
method! on_lvar localmap (pos, name) =
if Local_id.is_user_denotable name then
LocalMap.add (Local_id.get_name name) pos localmap
else
localmap
method! on_pipe localmap _id left right =
(*
A pipe expression has a left side and a right side. It introduces a
new scope on the right side only which defines a new magic local
called $$, which is equal to the value of the left side.
Consider for example:
( a |> b($$) ) |> ( c((d($$) |> e($$)), $$) )
1 1 2 2 3 3 2
Here I have numbered all the pipe operators and $$s, indicating which
$$ is in scope at each usage.
TODO: ericlippert
TODO: What is the interaction between the pipe operator and nested
TODO: anonymous functions? Does the $$ automatically end up in scope
TODO: inside the body, or does it have to go in a use($$) clause?
TODO: If the former, then we'll need to explicitly copy the active $$
TODO: binding into the scope chain introduced; if the latter then
TODO: the existing mechanisms should be sufficient. Either way,
TODO: this should be tested.
*)
let localmap = this#on_expr localmap left in
let localmap = LocalMap.push localmap in
let localmap = LocalMap.add_dollardollar localmap in
let localmap = this#on_expr localmap right in
LocalMap.pop localmap
method! on_method_ localmap m =
let localmap = LocalMap.push localmap in
let localmap =
List.fold_left m.m_params ~init:localmap ~f:this#on_fun_param
in
let localmap = this#on_block localmap m.m_body.fb_ast in
LocalMap.pop localmap
(*
* This is called for both top-level functions and lambdas, but not
* anonymous functions.
*)
method! on_fun_ localmap f =
let localmap = LocalMap.push localmap in
let localmap =
List.fold_left f.f_params ~init:localmap ~f:this#on_fun_param
in
let localmap = this#on_block localmap f.f_body.fb_ast in
LocalMap.pop localmap
method! on_lfun localmap f _idl = this#on_fun_ localmap f
method on_fun_param localmap p =
(*
* A formal parameter always introduces a new local into the current
* scope; we never want to unify a formal with a local seen previously.
*)
LocalMap.force_add p.param_name p.param_pos localmap
method! on_efun localmap efun =
(*
* This is a traditional PHP nested function, and this is a bit tricky.
* Consider first a normal case:
function test1($x, $y) {
$f = function ($z) use($x) {
$y = 100;
return $x + $y + $z;
};
return $f(10);
}
* We must detect every use of $x as a use of the formal parameter,
* including the usage inside the "use". We must *not* detect use of
* $y as a use of the formal parameter $y, since it was not mentioned
* in the use clause.
*
* Now consider a corner case:
function test2() {
$x = 20;
$f = function ($x) use ($x) {
return $x;
};
return $f(10);
}
* Which $x is returned by the nested function? We have both a formal
* and a closed-over local to choose from. In this case the
* formal wins.
*
* So, what's the deal here? How do we want to structure this?
*
* Consider test1. The local map at the point where we are
* about to evaluate the nested function is:
*
* scopechains:
[
[
[ $x -> 1; $y -> $2; $f -> 3 ]
]
]
*
* We will push a new scopechain so that $y comes out of scope, then
* push *two* scopes, one for the using, and one for the formals:
*
* scopechains:
[
[
[ $z -> 4 ]; [ $x -> 1 ]
];
[
[ $x -> 1; $y -> $2; $f -> 3 ]
]
]
*
* Now a lookup of $z will go to the head of the current scope chain
* stack. A lookup of $x will go the tail. And a lookup of $y will
* fail, because the tail of the scope chain stack is not searched.
* When $y is encountered it will produce:
* scopechains:
[
[
[ $y -> 5; $z -> 4 ]; [ $x -> 1 ]
];
[
[ $x -> 1; $y -> $2; $f -> 3 ]
]
]
*
* What about test2? We will have
* scopechains:
[
[
[ $x -> 2 ]; [ $x -> 1 ]
];
[
[ $x -> 1 ]
]
]
*
* So a lookup of $x in the body will produce the formal.
*
* All right, let's proceed.
*)
let localmap = LocalMap.push_scopechain localmap in
let localmap = LocalMap.push localmap in
(* No need to pop; we're going to pop the whole scopechain. *)
let localmap =
List.fold_left efun.ef_use ~init:localmap ~f:(fun l (_, (p, n)) ->
LocalMap.add_from_use (Local_id.get_name n) p l)
in
let localmap = this#on_fun_ localmap efun.ef_fun in
LocalMap.pop_scopechain localmap
method! on_catch localmap (_, (pos, name), body) =
(*
* A catch block creates a local which is only in scope for the
* body of the catch.
*
* The type name should never reasonably contain a local; we'll ignore it.
*)
let localmap = LocalMap.push localmap in
let localmap = LocalMap.force_add (Local_id.get_name name) pos localmap in
let localmap = this#on_block localmap body in
LocalMap.pop localmap
end
let go_from_ast ~ast ~line ~char =
let empty = LocalMap.make line char in
let visitor = new local_finding_visitor in
let localmap = visitor#on_program empty ast in
LocalMap.results localmap
(**
* This is the entrypoint to this module. The relative path of a file,
* the contents of a file, and a position within it, identifying a local, are given.
* The result is a list of the positions of other uses of that local in the file.
*)
let go ~ctx ~entry ~line ~char =
try
let ast =
Ast_provider.compute_ast ~popt:(Provider_context.get_popt ctx) ~entry
in
let results_list = go_from_ast ~ast ~line ~char in
List.map results_list ~f:(fun pos ->
Pos.set_file entry.Provider_context.path pos)
with
| Failure error ->
let contents = Provider_context.read_file_contents_exn entry in
failwith
(Printf.sprintf "Find locals service failed with error %s:\n" error
^ Printf.sprintf "line %d char %d\ncontent: \n%s\n" line char contents) |
OCaml Interface | hhvm/hphp/hack/src/server/serverFindLocals.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.
*
*)
(** Find references in the current file to the local variable at the given
position. *)
val go :
ctx:Provider_context.t ->
entry:Provider_context.entry ->
line:int ->
char:int ->
Pos.t list
(** Same as [go], but with an AST provided explicitly. Prefer [go] when
possible to make use of caching. *)
val go_from_ast : ast:Nast.program -> line:int -> char:int -> Pos.t list |
OCaml | hhvm/hphp/hack/src/server/serverFindRefs.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 Option.Monad_infix
open ServerEnv
open Reordered_argument_collections
open ServerCommandTypes.Find_refs
open ServerCommandTypes.Done_or_retry
let add_ns name =
if Char.equal name.[0] '\\' then
name
else
"\\" ^ name
let strip_ns results = List.map results ~f:(fun (s, p) -> (Utils.strip_ns s, p))
let search ctx target include_defs ~hints ~files ~stream_file genv =
let hints_set = Relative_path.Set.of_list hints in
let files =
List.filter files ~f:(fun file ->
not (Relative_path.Set.mem hints_set file))
in
let files = hints @ files in
if Hh_logger.Level.passes_min_level Hh_logger.Level.Debug then
List.iter files ~f:(fun file ->
Hh_logger.debug
"ServerFindRefs.search file %s"
(Relative_path.to_absolute file));
(* Get all the references to the provided target in the files *)
let res =
FindRefsService.find_references
ctx
genv.workers
target
include_defs
files
~stream_file
in
strip_ns res
let search_single_file ctx target file =
if Hh_logger.Level.passes_min_level Hh_logger.Level.Debug then
Hh_logger.debug
"ServerFindRefs.search file %s"
(Relative_path.to_absolute file);
(* Get all the references to the provided target in the file *)
let res = FindRefsService.find_references_single_file ctx target file in
strip_ns res
let handle_prechecked_files genv env dep f =
(* We need to handle prechecked files here to get accurate results. *)
let dep = Typing_deps.DepSet.singleton dep in
(* All the callers of this should be listed in ServerCommand.rpc_command_needs_full_check,
* and server should never call this before completing full check *)
assert (is_full_check_done env.full_check_status);
let start_time = Unix.gettimeofday () in
let (env, _telemetry) =
ServerPrecheckedFiles.update_after_local_changes genv env dep ~start_time
in
(* If we added more things to recheck, we can't handle this command now, and
* tell the client to retry instead. *)
if is_full_check_done env.full_check_status then
let () = Hh_logger.debug "ServerFindRefs.handle_prechecked_files: Done" in
let callback_result = f () in
(env, Done callback_result)
else
let () = Hh_logger.debug "ServerFindRefs.handle_prechecked_files: Retry" in
(env, Retry)
let search_function ctx function_name include_defs ~stream_file ~hints genv env
=
let function_name = add_ns function_name in
Hh_logger.debug "ServerFindRefs.search_function: %s" function_name;
handle_prechecked_files genv env Typing_deps.(Dep.(make (Fun function_name)))
@@ fun () ->
let files =
FindRefsService.get_dependent_files_function
ctx
genv.ServerEnv.workers
function_name
|> Relative_path.Set.elements
in
search
ctx
(FindRefsService.IFunction function_name)
include_defs
~hints
~files
~stream_file
genv
let search_single_file_for_function ctx function_name filename =
let function_name = add_ns function_name in
Hh_logger.debug "ServerFindRefs.search_function: %s" function_name;
search_single_file ctx (FindRefsService.IFunction function_name) filename
let search_member
ctx
(class_name : string)
(member : member)
~(include_defs : bool)
~(stream_file : Path.t option)
~(hints : Relative_path.t list)
(genv : genv)
(env : env) : env * (string * Pos.t) list t =
let dep_member_of member =
let open Typing_deps.Dep.Member in
match member with
| Method n -> [method_ n; smethod n]
| Property n -> [prop n; sprop n]
| Class_const n -> [const n]
| Typeconst n -> [const n]
in
let class_name = add_ns class_name in
let origin_class_name =
FindRefsService.get_origin_class_name ctx class_name member
in
handle_prechecked_files
genv
env
Typing_deps.(Dep.(make (Type origin_class_name)))
@@ fun () ->
let (descendant_class_files, member_use_files) =
FindRefsService
.get_files_for_descendants_and_dependents_of_members_in_descendants
ctx
~class_name
(dep_member_of member)
in
let descendant_classes =
FindRefsService.find_child_classes
ctx
origin_class_name
env.naming_table
descendant_class_files
in
let class_and_descendants = SSet.add descendant_classes origin_class_name in
let files =
Relative_path.Set.union descendant_class_files member_use_files
|> Relative_path.Set.elements
in
let target =
FindRefsService.IMember
(FindRefsService.Class_set class_and_descendants, member)
in
search ctx target include_defs ~hints ~files ~stream_file genv
let search_single_file_for_member
ctx
(class_name : string)
(member : member)
~(naming_table : Naming_table.t)
(filename : Relative_path.t) : (string * Pos.t) list =
let class_name = add_ns class_name in
let origin_class_name =
FindRefsService.get_origin_class_name ctx class_name member
in
let descendant_class_files =
Relative_path.Set.add Relative_path.Set.empty filename
in
let descendant_classes =
FindRefsService.find_child_classes
ctx
origin_class_name
naming_table
descendant_class_files
in
let class_and_descendants = SSet.add descendant_classes origin_class_name in
let target =
FindRefsService.IMember
(FindRefsService.Class_set class_and_descendants, member)
in
search_single_file ctx target filename
let search_gconst ctx cst_name include_defs ~stream_file ~hints genv env =
let cst_name = add_ns cst_name in
handle_prechecked_files genv env Typing_deps.(Dep.(make (GConst cst_name)))
@@ fun () ->
let files =
FindRefsService.get_dependent_files_gconst
ctx
genv.ServerEnv.workers
cst_name
|> Relative_path.Set.elements
in
search
ctx
(FindRefsService.IGConst cst_name)
include_defs
~hints
~files
~stream_file
genv
let search_single_file_for_gconst ctx cst_name filename =
let cst_name = add_ns cst_name in
search_single_file ctx (FindRefsService.IGConst cst_name) filename
let search_class
ctx
class_name
include_defs
include_all_ci_types
~stream_file
~hints
genv
env =
let class_name = add_ns class_name in
let target =
if include_all_ci_types then
FindRefsService.IClass class_name
else
FindRefsService.IExplicitClass class_name
in
handle_prechecked_files genv env Typing_deps.(Dep.(make (Type class_name)))
@@ fun () ->
let files =
FindRefsService.get_dependent_files
ctx
genv.ServerEnv.workers
(SSet.singleton class_name)
|> Relative_path.Set.elements
in
search ctx target include_defs ~hints ~files ~stream_file genv
let search_single_file_for_class ctx class_name filename include_all_ci_types =
let class_name = add_ns class_name in
let target =
if include_all_ci_types then
FindRefsService.IClass class_name
else
FindRefsService.IExplicitClass class_name
in
search_single_file ctx target filename
let search_localvar ~ctx ~entry ~line ~char =
let results = ServerFindLocals.go ~ctx ~entry ~line ~char in
match results with
| first_pos :: _ ->
let content = Provider_context.read_file_contents_exn entry in
let var_text = Pos.get_text_from_pos ~content first_pos in
List.map results ~f:(fun x -> (var_text, x))
| [] -> []
let is_local = function
| LocalVar _ -> true
| _ -> false
let go ctx action include_defs ~stream_file ~hints genv env =
match action with
| Member (class_name, member) ->
search_member
ctx
class_name
member
~include_defs
~stream_file
~hints
genv
env
| Function function_name ->
search_function ctx function_name include_defs ~stream_file ~hints genv env
| Class class_name ->
let include_all_ci_types = true in
search_class
ctx
class_name
include_defs
include_all_ci_types
~stream_file
~hints
genv
env
| ExplicitClass class_name ->
let include_all_ci_types = false in
search_class
ctx
class_name
include_defs
include_all_ci_types
~stream_file
~hints
genv
env
| GConst cst_name ->
search_gconst ctx cst_name include_defs ~stream_file ~hints genv env
| LocalVar { filename; file_content; line; char } ->
let (ctx, entry) =
Provider_context.add_or_overwrite_entry_contents
~ctx
~path:filename
~contents:file_content
in
(env, Done (search_localvar ~ctx ~entry ~line ~char))
let go_for_single_file
~(ctx : Provider_context.t)
~(action : ServerCommandTypes.Find_refs.action)
~(filename : Relative_path.t)
~(name : string)
~(naming_table : Naming_table.t) =
let _ = name in
match action with
| Member (class_name, member) ->
search_single_file_for_member ctx class_name member filename ~naming_table
| Function function_name ->
search_single_file_for_function ctx function_name filename
| Class class_name ->
let include_all_ci_types = true in
search_single_file_for_class ctx class_name filename include_all_ci_types
| ExplicitClass class_name ->
let include_all_ci_types = false in
search_single_file_for_class ctx class_name filename include_all_ci_types
| GConst cst_name -> search_single_file_for_gconst ctx cst_name filename
| LocalVar { filename; file_content; line; char } ->
let (ctx, entry) =
Provider_context.add_or_overwrite_entry_contents
~ctx
~path:filename
~contents:file_content
in
search_localvar ~ctx ~entry ~line ~char
let go_for_localvar ctx action =
match action with
| LocalVar { filename; file_content; line; char } ->
let (ctx, entry) =
Provider_context.add_or_overwrite_entry_contents
~ctx
~path:filename
~contents:file_content
in
Ok (search_localvar ~ctx ~entry ~line ~char)
| _ -> Error action
let to_absolute res = List.map res ~f:(fun (r, pos) -> (r, Pos.to_absolute pos))
let get_action symbol (filename, file_content, line, char) =
let module SO = SymbolOccurrence in
let name = symbol.SymbolOccurrence.name in
match symbol.SymbolOccurrence.type_ with
| SO.Class _ -> Some (Class name)
| SO.Function -> Some (Function name)
| SO.Method (SO.ClassName class_name, method_name) ->
Some (Member (class_name, Method method_name))
| SO.Property (SO.ClassName class_name, prop_name)
| SO.XhpLiteralAttr (class_name, prop_name) ->
Some (Member (class_name, Property prop_name))
| SO.ClassConst (SO.ClassName class_name, const_name) ->
Some (Member (class_name, Class_const const_name))
| SO.Typeconst (class_name, tconst_name) ->
Some (Member (class_name, Typeconst tconst_name))
| SO.GConst -> Some (GConst name)
| SO.LocalVar -> Some (LocalVar { filename; file_content; line; char })
| SO.TypeVar -> None
| SO.Attribute _ -> Some (Class name)
| SO.Keyword _
| SO.PureFunctionContext
| SO.BuiltInType _
| SO.BestEffortArgument _
| SO.HhFixme
| SO.Method (SO.UnknownClass, _)
| SO.Property (SO.UnknownClass, _)
| SO.ClassConst (SO.UnknownClass, _)
| SO.Module ->
None
(* TODO(toyang): find references doesn't work for enum labels yet *)
| SO.EnumClassLabel _ -> None
let go_from_file_ctx_with_symbol_definition
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(line : int)
~(column : int) :
(Relative_path.t SymbolDefinition.t * ServerCommandTypes.Find_refs.action)
option =
(* Find the symbol at given position *)
ServerIdentifyFunction.go_quarantined ~ctx ~entry ~line ~column
|> (* If there are few, arbitrarily pick the first *)
List.hd
>>= fun (occurrence, definition) ->
(* Ignore symbols that lack definitions *)
definition >>= fun definition ->
let source_text = Ast_provider.compute_source_text ~entry in
get_action
occurrence
( entry.Provider_context.path,
source_text.Full_fidelity_source_text.text,
line,
column )
>>= fun action -> Some (definition, action)
let go_from_file_ctx
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(line : int)
~(column : int) : (string * ServerCommandTypes.Find_refs.action) option =
go_from_file_ctx_with_symbol_definition ~ctx ~entry ~line ~column
|> Option.map ~f:(fun (def, action) ->
(def.SymbolDefinition.full_name, action)) |
OCaml Interface | hhvm/hphp/hack/src/server/serverFindRefs.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.
*
*)
open Hh_prelude
open ServerCommandTypes.Find_refs
val add_ns : String.t -> String.t
val handle_prechecked_files :
ServerEnv.genv ->
ServerEnv.env ->
Typing_deps.DepSet.elt ->
(unit -> 'a) ->
ServerEnv.env * 'a ServerCommandTypes.Done_or_retry.t
val is_local : action -> bool
(**
* Given a Find_refs action, returns an updated env
* and optional list of all positions where this action exists.
* Wrapped in a Done_or_retry for clientLsp.
*)
val go :
Provider_context.t ->
action ->
bool ->
stream_file:Path.t option ->
hints:Relative_path.t list ->
ServerEnv.genv ->
ServerEnv.env ->
ServerEnv.env * server_result_or_retry
(**
Like `go`, but only looks for references in the cached TAST from the supplied filename.
`go` uses ideps to look for references for ALL files.
*)
val go_for_single_file :
ctx:Provider_context.t ->
action:ServerCommandTypes.Find_refs.action ->
filename:Relative_path.t ->
name:string ->
naming_table:Naming_table.t ->
server_result
(**
* Given a position in a file, returns the [SymbolDefinition.t]
* and data ("action") that represents if it's a class, method, etc.
* This is the same as `go_from_file_ctx` but sends the entire SymbolDefinition back.
*)
val go_from_file_ctx_with_symbol_definition :
ctx:Provider_context.t ->
entry:Provider_context.entry ->
line:int ->
column:int ->
(Relative_path.t SymbolDefinition.t * action) option
(**
* Given a position in a file, returns the name of the symbol
* and data ("action") that represents if it's a class, method, etc.
*)
val go_from_file_ctx :
ctx:Provider_context.t ->
entry:Provider_context.entry ->
line:int ->
column:int ->
(string * action) option
(**
* Like go, but only supports LocalVar actions. If supplied a localvar,
* returns an optional list of all positions of that localvar. If action is not a localvar,
* returns the same action back wrapped in an error.
*)
val go_for_localvar :
Provider_context.t ->
action ->
((string * Pos.t) list, action) Hh_prelude.result
val to_absolute : server_result -> result |
OCaml | hhvm/hphp/hack/src/server/serverFindTypeVar.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
open Aast
(** Is this [def] a class or function that contains this position? *)
let cls_or_fun_at_pos (pos : Pos.t) (def : ('a, 'b) Aast.def) : bool =
match def with
| Fun fd -> Pos.contains fd.fd_fun.f_span pos
| Class c -> Pos.contains c.c_span pos
| _ -> false
(** Find the method that contains [pos], if any. *)
let method_at_pos (methods : ('a, 'b) Aast.method_ list) (pos : Pos.t) :
('a, 'b) Aast.method_ option =
List.find methods ~f:(fun m -> Pos.contains m.m_span pos)
(** Find the type parameter named [name]. *)
let tparam_with_name (params : ('a, 'b) Aast.tparam list) (name : string) :
('a, 'b) Aast.tparam option =
List.find params ~f:(fun tp -> String.equal (snd tp.tp_name) name)
let sym_def_of_tparam (tp : ('a, 'b) Aast.tparam) :
Relative_path.t SymbolDefinition.t =
let (pos, name) = tp.tp_name in
let name_with_constraints =
String.strip (Format.asprintf "%a" Hint_print.pp_tparam tp)
in
let docblock =
if String.equal name name_with_constraints then
None
else
Some name_with_constraints
in
SymbolDefinition.
{
kind = SymbolDefinition.TypeVar;
name;
full_name = name;
class_name = None;
id = Some name;
pos;
span = pos;
modifiers = [];
children = None;
params = None;
docblock;
}
(** Find the type param definition corresponding to the type variable
[name] at [pos]. *)
let find_tparam_def
(program : ('a, 'b) Aast.def list) (pos : Pos.t) (name : string) :
('a, 'b) Aast.tparam option =
let def_at_pos = List.find program ~f:(cls_or_fun_at_pos pos) in
match def_at_pos with
| Some (Fun fd) -> tparam_with_name fd.fd_tparams name
| Some (Class c) ->
let class_tparam = tparam_with_name c.c_tparams name in
(match class_tparam with
| Some tp -> Some tp
| None ->
(* This type parameter didn't occur on the class, try the
method. Type parameters on methods cannot shadow type
parameters on classes, so we don't need to worry about
clashes. *)
(match method_at_pos c.c_methods pos with
| Some m -> tparam_with_name m.m_tparams name
| None -> None))
| _ -> None
let go (program : ('a, 'b) Aast.def list) (pos : Pos.t) (name : string) :
Relative_path.t SymbolDefinition.t option =
Option.map (find_tparam_def program pos name) ~f:sym_def_of_tparam |
OCaml Interface | hhvm/hphp/hack/src/server/serverFindTypeVar.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 :
('a, 'b) Aast.program ->
Pos.t ->
string ->
Relative_path.t SymbolDefinition.t option |
OCaml | hhvm/hphp/hack/src/server/serverFormat.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 Result.Monad_infix
(* TODO t14922604: Further improve error handling *)
let call_external_formatter
(cmd : Exec_command.t) (content : string) (args : string list) :
(string list, string) result =
let args = Array.of_list (Exec_command.to_string cmd :: args) in
let reader timeout ic oc =
Out_channel.output_string oc content;
Out_channel.close oc;
let lines = ref [] in
begin
try
while true do
lines := Timeout.input_line ~timeout ic :: !lines
done
with
| End_of_file -> ()
end;
match Timeout.close_process_in ic with
| Unix.WEXITED 0 -> Ok (List.rev !lines)
| Unix.WEXITED v -> Error (Hackfmt_error.get_error_string_from_exit_value v)
| _ -> Error "Call to hackfmt was killed"
in
Timeout.read_process
~timeout:2
~on_timeout:(fun _ ->
Hh_logger.log "Formatter timeout";
Error "Call to hackfmt timed out")
~reader
cmd
args
let formatting_options_to_args
(options : Lsp.DocumentFormatting.formattingOptions) =
Lsp.DocumentFormatting.(
let args = ["--indent-width"; string_of_int options.tabSize] in
if not options.insertSpaces then
args @ ["--tabs"]
else
args)
let range_offsets_to_args from to_ =
["--range"; string_of_int from; string_of_int to_]
let go_hackfmt ?filename_for_logging ~content args =
let args =
match filename_for_logging with
| Some filename -> args @ ["--filename-for-logging"; filename]
| None -> args
in
Hh_logger.log "%s" (String.concat ~sep:" " args);
let paths = [Path.to_string (Path.make BuildOptions.default_hackfmt_path)] in
let paths =
match Sys.getenv_opt "HACKFMT_TEST_PATH" with
| Some p -> [p] @ paths
| None -> paths
in
let path = List.find ~f:Sys.file_exists paths in
match path with
| Some path ->
call_external_formatter (Exec_command.Hackfmt path) content args
| _ ->
Hh_logger.log "Formatter not found";
Error
("Could not locate formatter - looked in: " ^ String.concat ~sep:" " paths)
(* This function takes 1-based offsets, and 'to_' is exclusive. *)
let go ?filename_for_logging ~content from to_ options =
let format_args = formatting_options_to_args options in
let range_args = range_offsets_to_args from to_ in
let args = format_args @ range_args in
go_hackfmt ?filename_for_logging ~content args >>| fun lines ->
String.concat ~sep:"\n" lines ^ "\n"
(* Our formatting engine can only handle ranges that span entire rows. *)
(* This is signified by a range that starts at column 1 on one row, *)
(* and ends at column 1 on another (because it's half-open). *)
(* Nuclide always provides correct ranges, but other editors might not. *)
let expand_range_to_whole_rows content (range : File_content.range) :
File_content.range * int * int =
File_content.(
(* It's easy to expand the start of the range if necessary, but to expand *)
(* the end of the range requires more work... *)
let range = { range with st = { range.st with column = 1 } } in
let (from0, to0) = get_offsets content (range.st, range.ed) in
if range.ed.column = 1 || to0 = String.length content then
(range, from0, to0)
(* common case is performant. *)
else
(* First guess: we'll extend range.ed to the end of the line. *)
let ed = { line = range.ed.line + 1; column = 1 } in
(* But if this is longer than the length of the file, pull back. *)
let ed_file = offset_to_position content (String.length content) in
let ed =
if
ed.line < ed_file.line
|| (ed.line = ed_file.line && ed.column <= ed_file.column)
then
ed
else
ed_file
in
let range = { range with ed } in
let (from0, to0) = get_offsets content (range.st, range.ed) in
(range, from0, to0))
(* Two integers separated by a space. *)
let range_regexp = Str.regexp "^\\([0-9]+\\) \\([0-9]+\\)$"
let zip_with_index (xs : 'a list) (ys : 'b list) : (int * 'a * 'b option) list =
let rec aux acc i xs ys =
match (xs, ys) with
| (x :: xs, y :: ys) -> aux ((i, x, Some y) :: acc) (i + 1) xs ys
| (x :: xs, []) -> aux ((i, x, None) :: acc) (i + 1) xs ys
| ([], _) -> acc
in
List.rev (aux [] 0 xs ys)
let opt_string_eq (x : string) (y : string option) : bool =
match y with
| Some y -> String.equal x y
| None -> false
let first_changed_line_idx (old_lines : string list) (new_lines : string list) :
int option =
let numbered_lines = zip_with_index old_lines new_lines in
let first_novel_line =
List.find numbered_lines ~f:(fun (_, x, y) -> not (opt_string_eq x y))
in
match first_novel_line with
| Some (i, _, _) -> Some i
| None -> None
let last_changed_line_idx (old_lines : string list) (new_lines : string list) :
int option =
match first_changed_line_idx (List.rev old_lines) (List.rev new_lines) with
| Some rev_idx -> Some (List.length old_lines - rev_idx)
| None -> None
(* Drop the last [n] items in [xs]. *)
let drop_tail (xs : 'a list) (n : int) : 'a list =
List.rev (List.drop (List.rev xs) n)
(* An empty edit that has no effect. *)
let noop_edit =
let range =
{
File_content.st = { File_content.line = 1; column = 1 };
ed = { File_content.line = 1; column = 1 };
}
in
{
ServerFormatTypes.new_text = "";
range = Ide_api_types.ide_range_from_fc range;
}
(* Return an IDE text edit that doesn't include unchanged leading or trailing lines. *)
let minimal_edit (old_src : string) (new_src : string) :
ServerFormatTypes.ide_response =
let old_src_lines = String.split_lines old_src in
let new_src_lines = String.split_lines new_src in
let range_start_line = first_changed_line_idx old_src_lines new_src_lines in
let range_end_line = last_changed_line_idx old_src_lines new_src_lines in
match (range_start_line, range_end_line) with
| (Some range_start_line, Some range_end_line) ->
let new_src_novel_lines =
drop_tail
(List.drop new_src_lines range_start_line)
(List.length old_src_lines - range_end_line)
in
let range =
{
File_content.st =
{ File_content.line = range_start_line + 1; column = 1 };
ed = { File_content.line = range_end_line + 1; column = 1 };
}
in
{
ServerFormatTypes.new_text =
String.concat ~sep:"\n" new_src_novel_lines ^ "\n";
range = Ide_api_types.ide_range_from_fc range;
}
| _ -> noop_edit
let go_ide
~(filename_for_logging : string)
~(content : string)
~(action : ServerFormatTypes.ide_action)
~(options : Lsp.DocumentFormatting.formattingOptions) :
ServerFormatTypes.ide_result =
let open File_content in
let open ServerFormatTypes in
let convert_to_ide_result
(old_format_result : ServerFormatTypes.result)
~(range : File_content.range) : ServerFormatTypes.ide_result =
let range = Ide_api_types.ide_range_from_fc range in
old_format_result |> Result.map ~f:(fun new_text -> { new_text; range })
in
match action with
| Document ->
(* `from0` and `to0` are zero-indexed, hence the name. *)
let from0 = 0 in
let to0 = String.length content in
(* hackfmt currently takes one-indexed integers for range formatting. *)
go ~filename_for_logging ~content (from0 + 1) (to0 + 1) options
|> Result.map ~f:(fun new_text -> minimal_edit content new_text)
| Range range ->
let fc_range = Ide_api_types.ide_range_to_fc range in
let (range, from0, to0) = expand_range_to_whole_rows content fc_range in
go ~filename_for_logging ~content (from0 + 1) (to0 + 1) options
|> convert_to_ide_result ~range
| Position position ->
(* `get_offset` returns a zero-based index, and `--at-char` takes a
zero-based index. *)
let fc_position = Ide_api_types.ide_pos_to_fc position in
let offset = get_offset content fc_position in
let args = ["--at-char"; string_of_int offset] in
let args = args @ formatting_options_to_args options in
go_hackfmt ~filename_for_logging ~content args >>= fun lines ->
(* `hackfmt --at-char` returns the range that was formatted, as well as the
contents of that range. For example, it might return
10 12
}
signifying that we should replace the character under the cursor with the
following content, starting at index 10. We need to extract the range
from the first line and forward it to the client so that it knows where
to apply the edit. *)
begin
match lines with
| range_line :: lines -> Ok (range_line, lines)
| _ -> Error "Got no lines in at-position formatting"
end
>>= fun (range_line, lines) ->
(* Extract the offsets in the first line that form the range.
NOTE: `Str.string_match` sets global state to be consumed immediately
afterwards by `Str.matched_group`. *)
let does_range_match = Str.string_match range_regexp range_line 0 in
if not does_range_match then
Error "Range not found on first line of --at-char output"
else
let from0 = int_of_string (Str.matched_group 1 range_line) in
let to0 = int_of_string (Str.matched_group 2 range_line) in
let range =
{
st = offset_to_position content from0;
ed = offset_to_position content to0;
}
|> Ide_api_types.ide_range_from_fc
in
let new_text = String.concat ~sep:"\n" lines in
Ok { new_text; range } |
OCaml Interface | hhvm/hphp/hack/src/server/serverFormat.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.
*
*)
val go_ide :
filename_for_logging:string ->
content:string ->
action:ServerFormatTypes.ide_action ->
options:Lsp.DocumentFormatting.formattingOptions ->
ServerFormatTypes.ide_result
val go :
?filename_for_logging:string ->
content:string ->
int ->
int ->
Lsp.DocumentFormatting.formattingOptions ->
(string, string) result |
OCaml | hhvm/hphp/hack/src/server/serverFormatTypes.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type action = string * int * int (* file contents, offset start, offset end *)
[@@deriving show]
type result = (string, string) Stdlib.result
type ide_action =
| Document
| Range of Ide_api_types.range
| Position of Ide_api_types.position
(** TODO(T155870670): remove [Position] *)
type ide_response = {
new_text: string;
range: Ide_api_types.range; (* what range was actually replaced? *)
}
type ide_result = (ide_response, string) Stdlib.result |
OCaml | hhvm/hphp/hack/src/server/serverFunDepsBatch.ml | (*
* Copyright (c) 2017, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE fn in the "hack" directory of this source tree.
*
*)
open Hh_prelude
(* In order to run recheck_typing, workers need access to the FileInfo for each
* file to be typechecked, so a FileInfo is paired with each query.
*
* Note that this means that many queries on the same file result in needlessly
* marshalling and unmarshalling the same FileInfo many times over. There are
* probably ways we could avoid this, but it doesn't seem to be a major problem.
*)
module T = Aast
module S = ServerRxApiShared
module SN = Naming_special_names
open SymbolOccurrence
module Results = Caml.Set.Make (struct
type t = Relative_path.t SymbolOccurrence.t
let compare = SymbolOccurrence.compare Relative_path.compare
end)
let process_method_cid n cid =
Results.singleton
{
name = cid ^ "::" ^ snd n;
type_ = Method (ClassName cid, snd n);
is_declaration = false;
pos = fst n;
}
let process_method env ty n =
Tast_env.get_class_ids env ty
|> List.map ~f:(process_method_cid n)
|> List.fold ~init:Results.empty ~f:Results.union
let process_function id =
Results.singleton
{ name = snd id; type_ = Function; is_declaration = false; pos = fst id }
let process_local id =
Results.singleton
{ name = snd id; type_ = LocalVar; is_declaration = false; pos = fst id }
let collect_in_decl =
object (self)
inherit [_] Tast_visitor.reduce as super
method zero = Results.empty
method plus a b = Results.union a b
method! on_Call env call =
let ( + ) = self#plus in
let T.{ func = (_, _, expr_); _ } = call in
let acc =
match expr_ with
| T.Obj_get ((ty, _, _), (_, _, T.Id mid), _, _) ->
process_method env ty mid
| T.Id id -> process_function id
| T.Class_const ((ty, _, _), mid) -> process_method env ty mid
| T.Lvar (pos, id) -> process_local (pos, Local_id.get_name id)
| _ -> self#zero
in
acc + super#on_Call env call
method! on_New env ((ty, p, _) as c) targs el unpacked_element ctor_annot =
let ( + ) = self#plus in
let acc = process_method env ty (p, SN.Members.__construct) in
acc + super#on_New env c targs el unpacked_element ctor_annot
method! on_expr env ((_, _, expr_) as expr) =
let ( + ) = self#plus in
let acc =
match expr_ with
| T.Method_caller ((p, cid), mid) ->
process_function (p, SN.AutoimportedFunctions.meth_caller)
+ process_method_cid mid cid
| T.FunctionPointer (T.FP_id id, _targs) -> process_function id
| T.FunctionPointer (T.FP_class_const ((ty, _, _cid), mid), _targs) ->
process_method env ty mid
| _ -> self#zero
in
acc + super#on_expr env expr
end
let result_to_string result (fn, line, char) =
Hh_json.(
let obj =
JSON_Object
[
("position", S.pos_to_json fn line char);
(match result with
| Ok (Some refs) ->
( "deps",
let l =
List.map refs ~f:(fun def_opt ->
match def_opt with
| None -> JSON_Null
| Some def ->
let module SD = SymbolDefinition in
let props =
[
("name", JSON_String def.SD.full_name);
("kind", JSON_String (SD.string_of_kind def.SD.kind));
("position", Pos.json (Pos.to_absolute def.SD.pos));
]
in
JSON_Object props)
in
JSON_Array l )
| Ok None -> ("error", JSON_String "Function/method not found")
| Error e -> ("error", JSON_String e));
]
in
json_to_string obj)
let remove_duplicates_except_none ~compare l =
let rec loop l accum =
match l with
| [] -> accum
| [x] -> x :: accum
| x1 :: x2 :: tl ->
if Option.is_some x1 && compare x1 x2 = 0 then
loop (x2 :: tl) accum
else
loop (x2 :: tl) (x1 :: accum)
in
List.rev (loop l [])
let handlers =
let compare =
Option.compare (SymbolDefinition.compare Relative_path.compare)
in
{
S.result_to_string;
S.walker =
{
S.plus = collect_in_decl#plus;
S.on_method = collect_in_decl#on_method_;
S.on_fun_def = collect_in_decl#on_fun_def;
};
S.get_state =
begin
(fun ctx fn -> Ast_provider.get_ast ~full:true ctx fn)
end;
S.map_result =
begin
fun ctx ast refs ->
let ast = Some ast in
Results.elements refs
|> List.map ~f:(ServerSymbolDefinition.go ctx ast)
|> List.sort ~compare
|> remove_duplicates_except_none ~compare
end;
}
(* Entry Point *)
let go :
MultiWorker.worker list option ->
(string * int * int) list ->
ServerEnv.env ->
_ =
(fun workers pos_list env -> ServerRxApiShared.go workers pos_list env handlers) |
OCaml | hhvm/hphp/hack/src/server/serverGlobalInferenceTypes.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 mode =
| MMerge
| MSolve
| MExport
| MRewrite
[@@deriving show]
type result =
| RMerge of unit
| RSolve of unit
| RExport of unit
| RRewrite of ServerRenameTypes.patch list
| RError of string |
OCaml | hhvm/hphp/hack/src/server/serverGlobalState.ml | (*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type t = {
saved_root: Path.t;
saved_hhi: Path.t;
saved_tmp: Path.t;
trace: bool;
allowed_fixme_codes_strict: ISet.t;
code_agnostic_fixme: bool;
paths_to_ignore: Str.regexp list;
no_load: bool;
logging_init: unit -> unit;
cgroup_initial_reading: CgroupProfiler.initial_reading;
}
let save ~logging_init =
{
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 = !Typing_deps.trace;
allowed_fixme_codes_strict = !Errors.allowed_fixme_codes_strict;
code_agnostic_fixme = !Errors.code_agnostic_fixme;
paths_to_ignore = FilesToIgnore.get_paths_to_ignore ();
no_load = ServerLoadFlag.get_no_load ();
logging_init;
cgroup_initial_reading = CgroupProfiler.get_initial_reading ();
}
let worker_id_str ~(worker_id : int) =
if worker_id = 0 then
"master"
else
Printf.sprintf "worker-%d" worker_id
let restore
{
saved_root;
saved_hhi;
saved_tmp;
trace;
allowed_fixme_codes_strict;
code_agnostic_fixme;
paths_to_ignore;
no_load;
logging_init;
cgroup_initial_reading;
}
~(worker_id : int) =
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;
Typing_deps.worker_id := Some worker_id;
Errors.allowed_fixme_codes_strict := allowed_fixme_codes_strict;
Errors.code_agnostic_fixme := code_agnostic_fixme;
FilesToIgnore.set_paths_to_ignore paths_to_ignore;
ServerLoadFlag.set_no_load no_load;
Errors.set_allow_errors_in_default_path false;
CgroupProfiler.use_initial_reading cgroup_initial_reading;
logging_init ()
let to_string
{
saved_root;
saved_hhi;
saved_tmp;
trace;
allowed_fixme_codes_strict = _;
code_agnostic_fixme = _;
paths_to_ignore = _;
no_load = _;
logging_init = _;
cgroup_initial_reading = _;
} =
let saved_root = Path.to_string saved_root in
let saved_hhi = Path.to_string saved_hhi in
let saved_tmp = Path.to_string saved_tmp in
let trace =
if trace then
"true"
else
"false"
in
(* OCaml regexps cannot be re-serialized to strings *)
let paths_to_ignore = "(...)" in
[
("saved_root", saved_root);
("saved_hhi", saved_hhi);
("saved_tmp", saved_tmp);
("trace", trace);
("paths_to_ignore", paths_to_ignore);
]
|> List.map (fun (x, y) -> Printf.sprintf "%s : %s" x y)
|> String.concat ", "
|> Printf.sprintf "{%s}" |
OCaml Interface | hhvm/hphp/hack/src/server/serverGlobalState.mli | (*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type t
val save : logging_init:(unit -> unit) -> t
val worker_id_str : worker_id:int -> string
val restore : t -> worker_id:int -> unit
val to_string : t -> string |
OCaml | hhvm/hphp/hack/src/server/serverGoToDefinition.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 go_quarantined
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(line : int)
~(column : int) : ServerCommandTypes.Go_to_definition.result =
let results =
ServerIdentifyFunction.go_quarantined ~ctx ~entry ~line ~column
in
let results = List.filter_map results ~f:Utils.unwrap_snd in
(* What's it like when we return multiple definitions? For instance, if you ask
* for the definition of "new C()" then we've now got the definition of the
* class "\C" and also of the constructor "\\C::__construct". I think that
* users would be happier to only have the definition of the constructor, so
* as to jump straight to it without the fuss of clicking to select which one.
* That indeed is what Typescript does -- it only gives the constructor.
* (VSCode displays multiple definitions with a peek view of them all;
* Atom displays them with a small popup showing just title+file+line of each).
* There's one subtlety. If you declare a base class "B" with a constructor,
* and a derived class "C" without a constructor, and click on "new C()", then
* Typescript and VS Code will pop up a little window with both options. This
* seems like a reasonable compromise, so Hack should do the same. *)
let cls =
List.fold results ~init:`None ~f:(fun class_opt (occ, _) ->
match (class_opt, SymbolOccurrence.enclosing_class occ) with
| (`None, Some c) -> `Single c
| (`Single c, Some c2) when String.equal c c2 -> `Single c
| (`Single _, Some _) ->
(* Symbol occurrences for methods/properties that only exist in a base
class still have the derived class as their enclosing class, even
though it doesn't explicitly override that member. Because of that, if
we hit this case then we know that we're dealing with a union type. In
that case, it's not really possible to do the rest of this filtration,
since it would have to be decided on a per-class basis. *)
`Multiple
| (class_opt, _) -> class_opt)
in
let results =
match cls with
| `None
| `Multiple ->
results
| `Single _ ->
SymbolOccurrence.(
let explicitly_defined =
List.fold results ~init:[] ~f:(fun acc (occ, def) ->
let cls = get_class_name occ in
match cls with
| None -> acc
| Some cls ->
if
String.is_prefix
def.SymbolDefinition.full_name
~prefix:(Utils.strip_ns cls)
then
(occ, def) :: acc
else
acc)
|> List.rev
in
let is_result_constructor (occ, _) = is_constructor occ in
let has_explicit_constructor =
List.exists explicitly_defined ~f:is_result_constructor
in
let has_constructor = List.exists results ~f:is_result_constructor in
let has_class = List.exists results ~f:(fun (occ, _) -> is_class occ) in
(* If we have a constructor but it's derived, then we'd like to show both
the class and the constructor. If the constructor is explicitly
defined, though, we'd like to filter the class out and only show the
constructor. *)
if has_constructor && has_class && has_explicit_constructor then
List.filter results ~f:is_result_constructor
else
results)
in
List.map results ~f:(fun (occurrence, definition) ->
let occurrence = SymbolOccurrence.to_absolute occurrence in
let definition = SymbolDefinition.to_absolute definition in
(occurrence, definition)) |
OCaml Interface | hhvm/hphp/hack/src/server/serverGoToDefinition.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.
*
*)
(** Returns the definition of the symbol at the given position in the document.
This function is for interactive use only, as it may return multiple definitions
for the user's convenience. For example, when hovering over a constructor call,
it may return both the definition for the class being constructed, and the
`__construct` method of the class. Tooling should use
[ServerCommandTypes.IDENTIFY_FUNCTION] instead. *)
val go_quarantined :
ctx:Provider_context.t ->
entry:Provider_context.entry ->
line:int ->
column:int ->
ServerCommandTypes.Go_to_definition.result |
OCaml | hhvm/hphp/hack/src/server/serverGoToImpl.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
open ServerEnv
open Reordered_argument_collections
open ServerCommandTypes.Find_refs
open ServerCommandTypes.Done_or_retry
open Typing_defs
let parallel_limit = 10
let find_positions_of_classes
(ctx : Provider_context.t)
(acc : (string * Pos.t) list)
(child_classes : string list) : (string * Pos.t) list =
acc
@ List.map child_classes ~f:(fun child_class ->
match Naming_provider.get_type_pos ctx child_class with
| None ->
failwith ("Could not find definition of child class: " ^ child_class)
| Some (FileInfo.Full pos) -> (child_class, pos)
| Some (FileInfo.File (FileInfo.Class, path)) ->
(match
Ast_provider.find_class_in_file ctx path child_class ~full:false
with
| None ->
failwith
(Printf.sprintf
"Could not find class %s in %s"
child_class
(Relative_path.to_absolute path))
| Some { Aast.c_name = (name_pos, _); _ } -> (child_class, name_pos))
| Some FileInfo.(File ((Fun | Typedef | Const | Module), _path)) ->
failwith
(Printf.sprintf
"Information for class %s was returned as not a class"
child_class))
let parallel_find_positions_of_classes
(ctx : Provider_context.t)
(child_classes : string list)
(workers : MultiWorker.worker list option) : (string * Pos.t) list =
MultiWorker.call
workers
~job:(find_positions_of_classes ctx)
~neutral:[]
~merge:List.append
~next:(MultiWorker.next workers child_classes)
let add_if_valid_origin ctx class_elt child_class method_name result =
if String.equal class_elt.ce_origin child_class then
( method_name,
Lazy.force class_elt.ce_pos |> Naming_provider.resolve_position ctx )
:: result
else
let origin_decl = Decl_provider.get_class ctx class_elt.ce_origin in
match origin_decl with
| Some origin_decl ->
let origin_kind = Decl_provider.Class.kind origin_decl in
if Ast_defs.is_c_trait origin_kind then
( method_name,
Lazy.force class_elt.ce_pos |> Naming_provider.resolve_position ctx )
:: result
else
result
| None -> failwith "TODO"
let find_positions_of_methods
(ctx : Provider_context.t)
(method_name : string)
(acc : (string * Pos.t) list)
(child_classes : string list) : (string * Pos.t) list =
List.fold child_classes ~init:acc ~f:(fun result child_class ->
let class_decl = Decl_provider.get_class ctx child_class in
match class_decl with
| Some decl ->
let method_info = Decl_provider.Class.get_method decl method_name in
(match method_info with
| Some class_elt ->
add_if_valid_origin ctx class_elt child_class method_name result
| None ->
let smethod_info = Decl_provider.Class.get_smethod decl method_name in
(match smethod_info with
| Some class_elt ->
add_if_valid_origin ctx class_elt child_class method_name result
| None -> result))
| None ->
failwith ("Could not find definition of child class: " ^ child_class))
let parallel_find_positions_of_methods
(ctx : Provider_context.t)
(child_classes : string list)
(method_name : string)
(workers : MultiWorker.worker list option) : (string * Pos.t) list =
MultiWorker.call
workers
~job:(find_positions_of_methods ctx method_name)
~neutral:[]
~merge:List.append
~next:(MultiWorker.next workers child_classes)
let find_child_classes
(ctx : Provider_context.t)
(class_name : string)
(genv : ServerEnv.genv)
(env : ServerEnv.env) : string list =
let files =
FindRefsService.get_dependent_files
ctx
genv.ServerEnv.workers
(SSet.singleton class_name)
in
let ctx = Provider_utils.ctx_from_server_env env in
FindRefsService.find_child_classes ctx class_name env.naming_table files
|> SSet.elements
let find_child_classes_in_file
(ctx : Provider_context.t)
(class_name : string)
(naming_table : Naming_table.t)
(filename : Relative_path.t) : string list =
let fileset = Relative_path.Set.(add empty filename) in
FindRefsService.find_child_classes ctx class_name naming_table fileset
|> SSet.elements
let search_class
(ctx : Provider_context.t)
(class_name : string)
(genv : ServerEnv.genv)
(env : ServerEnv.env) : ServerEnv.env * server_result_or_retry =
let class_name = ServerFindRefs.add_ns class_name in
ServerFindRefs.handle_prechecked_files
genv
env
Typing_deps.(Dep.(make (Type class_name)))
@@ fun () ->
let child_classes = find_child_classes ctx class_name genv env in
if List.length child_classes < parallel_limit then
find_positions_of_classes ctx [] child_classes
else
parallel_find_positions_of_classes ctx child_classes genv.workers
let search_single_file_for_class
(ctx : Provider_context.t)
(class_name : string)
(naming_table : Naming_table.t)
(filename : Relative_path.t) : server_result =
let class_name = ServerFindRefs.add_ns class_name in
let child_classes =
find_child_classes_in_file ctx class_name naming_table filename
in
find_positions_of_classes ctx [] child_classes
let search_member
(ctx : Provider_context.t)
(class_name : string)
(member : member)
(genv : ServerEnv.genv)
(env : ServerEnv.env) : ServerEnv.env * server_result_or_retry =
match member with
| Method method_name ->
let class_name = ServerFindRefs.add_ns class_name in
let class_name =
FindRefsService.get_origin_class_name ctx class_name member
in
ServerFindRefs.handle_prechecked_files
genv
env
Typing_deps.(Dep.(make (Type class_name)))
@@ fun () ->
(* Find all the classes that extend this one *)
let child_classes = find_child_classes ctx class_name genv env in
let results =
if List.length child_classes < parallel_limit then
find_positions_of_methods ctx method_name [] child_classes
else
parallel_find_positions_of_methods
ctx
child_classes
method_name
genv.workers
in
List.dedup_and_sort results ~compare:(fun (_, pos1) (_, pos2) ->
Pos.compare pos1 pos2)
| Property _
| Class_const _
| Typeconst _ ->
(env, Done [])
let search_single_file_for_member
(ctx : Provider_context.t)
(class_name : string)
(member : member)
(naming_table : Naming_table.t)
(filename : Relative_path.t) : server_result =
match member with
| Method method_name ->
let class_name = ServerFindRefs.add_ns class_name in
let class_name =
FindRefsService.get_origin_class_name ctx class_name member
in
(* Find all the classes that extend this one *)
let child_classes =
find_child_classes_in_file ctx class_name naming_table filename
in
let results = find_positions_of_methods ctx method_name [] child_classes in
List.dedup_and_sort results ~compare:(fun (_, pos1) (_, pos2) ->
Pos.compare pos1 pos2)
| Property _
| Class_const _
| Typeconst _ ->
[]
let is_searchable ~action =
match action with
| Class _
| ExplicitClass _
| Member (_, _) ->
true
| Function _
| GConst _
| LocalVar _ ->
false
let go_for_single_file
~(ctx : Provider_context.t)
~(action : action)
~(naming_table : Naming_table.t)
~(filename : Relative_path.t) : server_result =
match action with
| Class class_name
| ExplicitClass class_name ->
search_single_file_for_class ctx class_name naming_table filename
| Member (class_name, member) ->
search_single_file_for_member ctx class_name member naming_table filename
| Function _
| GConst _
| LocalVar _ ->
[]
let go ~(action : action) ~(genv : ServerEnv.genv) ~(env : ServerEnv.env) :
ServerEnv.env * server_result_or_retry =
let ctx = Provider_utils.ctx_from_server_env env in
match action with
| Class class_name
| ExplicitClass class_name ->
search_class ctx class_name genv env
| Member (class_name, member) -> search_member ctx class_name member genv env
| Function _
| GConst _
| LocalVar _ ->
(env, Done []) |
OCaml Interface | hhvm/hphp/hack/src/server/serverGoToImpl.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 ServerCommandTypes.Find_refs
val go :
action:action ->
genv:ServerEnv.genv ->
env:ServerEnv.env ->
ServerEnv.env * server_result_or_retry
val go_for_single_file :
ctx:Provider_context.t ->
action:action ->
naming_table:Naming_table.t ->
filename:Relative_path.t ->
server_result
val is_searchable : action:action -> bool |
OCaml | hhvm/hphp/hack/src/server/serverHighlightRefs.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 get_target symbol =
SymbolOccurrence.(
let module Types = ServerCommandTypes.Find_refs in
let module SO = SymbolOccurrence in
FindRefsService.(
match symbol.type_ with
| SO.Class _ -> Some (IClass symbol.name)
| SO.Function -> Some (IFunction symbol.name)
| SO.Method (SO.ClassName class_name, member_name) ->
Some (IMember (Subclasses_of class_name, Types.Method member_name))
| SO.Property (SO.ClassName class_name, member_name)
| SO.XhpLiteralAttr (class_name, member_name) ->
Some (IMember (Subclasses_of class_name, Types.Property member_name))
| SO.ClassConst (SO.ClassName class_name, member_name) ->
Some (IMember (Subclasses_of class_name, Types.Class_const member_name))
| SO.Typeconst (class_name, member_name) ->
Some (IMember (Subclasses_of class_name, Types.Typeconst member_name))
| SO.GConst -> Some (IGConst symbol.name)
| _ -> None))
let highlight_symbol ctx entry line char symbol =
let res =
match get_target symbol with
| Some target ->
let results = FindRefsService.find_refs_ctx ~ctx ~entry ~target in
List.rev (List.map results ~f:snd)
| None
when SymbolOccurrence.equal_kind
symbol.SymbolOccurrence.type_
SymbolOccurrence.LocalVar ->
ServerFindLocals.go ~ctx ~entry ~line ~char
| None -> []
in
List.map res ~f:Ide_api_types.pos_to_range
let compare r1 r2 =
Ide_api_types.(
let (s1, s2) = (r1.st, r2.st) in
if s1.line < s2.line then
-1
else if s1.line > s2.line then
1
else if s1.column < s2.column then
-1
else if s1.column > s2.column then
1
else
0)
let go_quarantined
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(line : int)
~(column : int) : ServerHighlightRefsTypes.result =
let symbol_to_highlight =
IdentifySymbolService.go_quarantined ~ctx ~entry ~line ~column
in
let results =
List.fold symbol_to_highlight ~init:[] ~f:(fun acc s ->
let stuff = highlight_symbol ctx entry line column s in
List.append stuff acc)
in
let results = List.dedup_and_sort ~compare results in
results |
OCaml Interface | hhvm/hphp/hack/src/server/serverHighlightRefs.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.
*
*)
(* For serverless IDE *)
val go_quarantined :
ctx:Provider_context.t ->
entry:Provider_context.entry ->
line:int ->
column:int ->
ServerHighlightRefsTypes.result |
OCaml | hhvm/hphp/hack/src/server/serverHighlightRefsTypes.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type result = Ide_api_types.range list |
OCaml | hhvm/hphp/hack/src/server/serverHotClassesDescription.stubs.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE fn in the "hack" directory of this source tree.
*
*)
let comment = ["generated by hh_client --gen-hot-classes-file"]
let postprocess x = x |
OCaml | hhvm/hphp/hack/src/server/serverHover.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 HoverService
module SN = Naming_special_names
(** When we get a Class occurrence and a Method occurrence, that means that the
user is hovering over an invocation of the constructor, and would therefore only
want to see information about the constructor, rather than getting both the
class and constructor back in the hover. *)
let filter_class_and_constructor results =
let result_is_constructor result =
SymbolOccurrence.is_constructor (fst result)
in
let result_is_class result = SymbolOccurrence.is_class (fst result) in
let has_class = List.exists results ~f:result_is_class in
let has_constructor = List.exists results ~f:result_is_constructor in
if has_class && has_constructor then
List.filter results ~f:result_is_constructor |> List.map ~f:snd
else
results |> List.map ~f:snd
let docs_url_markdown name url : string =
Printf.sprintf
"See the [documentation for %s](%s)."
(Markdown_lite.md_codify (Utils.strip_ns name))
url
let typedef_docs_url ctx name : string option =
let qualified_name = "\\" ^ name in
Option.(
Decl_provider.get_typedef ctx qualified_name >>= fun decl ->
decl.Typing_defs.td_docs_url >>| fun url -> docs_url_markdown name url)
(* If [classish_name] (or any of its parents) has a documentation URL,
return the docs of the closest type. *)
let classish_docs_url ctx classish_name : string option =
let docs_url name =
match Decl_provider.get_class ctx name with
| Some decl -> Decl_provider.Class.get_docs_url decl
| None -> None
in
let qualified_name = "\\" ^ classish_name in
let ancestors =
match Decl_provider.get_class ctx qualified_name with
| Some decl -> Decl_provider.Class.all_ancestor_names decl
| None -> []
in
List.find_map (qualified_name :: ancestors) ~f:(fun ancestor ->
match docs_url ancestor with
| Some url -> Some (docs_url_markdown ancestor url)
| None -> None)
let docs_url ctx def : string option =
let open SymbolDefinition in
match def.kind with
| Class
| Enum
| Interface
| Trait ->
classish_docs_url ctx def.name
| Typedef -> typedef_docs_url ctx def.name
| Function
| Method
| Property
| ClassConst
| GlobalConst
| LocalVar
| TypeVar
| Param
| Typeconst
| Module ->
None
let make_hover_doc_block ctx entry occurrence def_opt =
match def_opt with
| Some def when not occurrence.SymbolOccurrence.is_declaration ->
(* The docblock is useful at the call site, but it's redundant at
the definition site. *)
let base_class_name = SymbolOccurrence.enclosing_class occurrence in
let doc_block_hover =
ServerDocblockAt.go_comments_for_symbol_ctx
~ctx
~entry
~def
~base_class_name
|> Option.to_list
in
(match docs_url ctx def with
| Some info -> info :: doc_block_hover
| None -> doc_block_hover)
| None
| Some _ ->
[]
(* Given a function/method call receiver, find the position of the
definition site. *)
let callee_def_pos ctx recv : Pos_or_decl.t option =
SymbolOccurrence.(
match recv with
| FunctionReceiver fun_name ->
let f = Decl_provider.get_fun ctx fun_name in
Option.map f ~f:(fun fe -> fe.Typing_defs.fe_pos)
| MethodReceiver { cls_name; _ } ->
let c = Decl_provider.get_class ctx cls_name in
Option.map c ~f:Decl_provider.Class.pos)
(* Return the name of the [n]th parameter in [params], handling
variadics correctly. *)
let nth_param_name (params : ('a, 'b) Aast.fun_param list) (n : int) :
string option =
let param =
if n >= List.length params then
match List.last params with
| Some param when param.Aast.param_is_variadic -> Some param
| _ -> None
else
List.nth params n
in
Option.map param ~f:(fun param ->
if param.Aast.param_is_variadic then
"..." ^ param.Aast.param_name
else
param.Aast.param_name)
(* Return the name of the [n]th parameter of function [fun_name]. *)
let nth_fun_param tast fun_name n : string option =
List.find_map tast ~f:(fun def ->
match def with
| Aast.Fun { Aast.fd_fun; fd_name; _ } ->
if String.equal fun_name (snd fd_name) then
nth_param_name fd_fun.Aast.f_params n
else
None
| _ -> None)
(* Return the name of the [n]th parameter of this method. *)
let nth_meth_param tast ~cls_name ~meth_name ~is_static ~arg_n =
let class_methods =
List.find_map tast ~f:(fun def ->
match def with
| Aast.Class c ->
if String.equal cls_name (snd c.Aast.c_name) then
Some c.Aast.c_methods
else
None
| _ -> None)
|> Option.value ~default:[]
in
let class_method =
List.find_map class_methods ~f:(fun m ->
if
String.equal meth_name (snd m.Aast.m_name)
&& Bool.equal is_static m.Aast.m_static
then
Some m
else
None)
in
match class_method with
| Some m -> nth_param_name m.Aast.m_params arg_n
| None -> None
let nth_param ctx recv i : string option =
match callee_def_pos ctx recv with
| Some pos ->
let path = Pos_or_decl.filename pos in
let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path in
let { Tast_provider.Compute_tast.tast; _ } =
Tast_provider.compute_tast_quarantined ~ctx ~entry
in
let tast = tast.Tast_with_dynamic.under_normal_assumptions in
SymbolOccurrence.(
(match recv with
| FunctionReceiver fun_name -> nth_fun_param tast fun_name i
| MethodReceiver { cls_name; meth_name; is_static } ->
nth_meth_param tast ~cls_name ~meth_name ~is_static ~arg_n:i))
| None -> None
let make_hover_const_definition entry def_opt =
Option.map def_opt ~f:(fun def ->
Pos.get_text_from_pos
~content:(Provider_context.read_file_contents_exn entry)
def.SymbolDefinition.span)
(* Return a markdown description of built-in Hack attributes. *)
let make_hover_attr_docs name =
Option.first_some
(SMap.find_opt name SN.UserAttributes.as_map)
(SMap.find_opt name SN.UserAttributes.systemlib_map)
|> Option.map ~f:(fun attr_info -> attr_info.SN.UserAttributes.doc)
|> Option.to_list
let pure_context_info =
"This function has an empty context list, so it has no capabilities."
^ "\nIt may only read properties, access constants, or call other pure functions."
let hh_fixme_info =
"`HH_FIXME[N]` disables type checker error N on the next line. It does
not change runtime behavior.
**`HH_FIXME` is almost always a bad idea**. You might get an
exception, or you might get an unexpected value. Even scarier, you
might cause an exception in a totally different part of the codebase.
```
/* HH_FIXME[4110] My reason here */
takes_num(\"x\") + takes_num(\"y\");
```
In this example, the type checker will accept the code, but the code
will still crash when you run it (`TypeHintViolationException` when
calling `takes_num`).
Note that `HH_FIXME` applies to all occurrences of the error on the
next line.
## You can fix it!
It is always possible to write code without `HH_FIXME`. This usually
requires changing type signatures and some refactoring. Your code will
be more reliable, the type checker can help you, and future changes
will be less scary.
See also `HH\\FIXME\\UNSAFE_CAST()`, which is still bad, but much more
precise."
let keyword_info (khi : SymbolOccurrence.keyword_with_hover_docs) : string =
let await_explanation =
"\n\nThis does not give you threads. Only one function is running at any point in time."
^ " Instead, the runtime may switch to another function at an `await` expression, and come back to this function later."
^ "\n\nThis allows data fetching (e.g. database requests) to happen in parallel."
in
match khi with
| SymbolOccurrence.Class ->
"A `class` contains methods, properties and constants that together solve a problem."
| SymbolOccurrence.Interface ->
"An `interface` defines signatures for methods that classes must implement."
| SymbolOccurrence.Trait ->
"A `trait` provides methods and properties that can be `use`d in classes."
^ "\n\nTraits are often used to provide default implementations for methods declared in an `interface`."
^ "\n\nWhen in doubt, use a class rather than a trait. You only need a trait when you want the same method in multiple classes that don't inherit from each other."
| SymbolOccurrence.Enum ->
"An `enum` is a fixed set of string or integer values."
^ "\n\nYou can use `switch` with an `enum` and the type checker will ensure you handle every possible value."
| SymbolOccurrence.EnumClass ->
"An `enum class` is a fixed set of values that can be used as typed constants."
^ "\n\nEnum classes enable you to write generic getter and setter methods."
^ "\n\n```
enum class PersonFields: BaseField {
Field<string> name = Field::string();
Field<string> email = Field::string();
Field<int> age = Field::int();
}
```"
^ "\n\nYou can refer to items within an enum class by name (using the `#` syntax), and Hack knows the exact type."
^ "\n\n```
function person_get(
Person $p,
HH\\EnumClass\\Label<PersonFields, Field<T>> $field_name
): T {
// ... implementation here ...
}
person_get($a_person, #email); // string
```"
^ "\n\nSee also `HH\\EnumClass\\Label` and `HH\\MemberOf`."
| SymbolOccurrence.Type ->
"A `type` is an alias for another type."
^ "\n\n`type` aliases are transparent, so you can use the original type and its alias interchangeably."
^ "\n\nSee also `newtype` for opaque type aliases."
| SymbolOccurrence.Newtype ->
"A `newtype` is a type alias that is opaque."
^ "\n\nInside the current file, code can see the underlying type. In all other files, code cannot see the underlying type."
^ " This enables you to hide implementation details."
^ "\n\nSee also `type` for transparent type aliases."
| SymbolOccurrence.FinalOnClass ->
"A `final` class cannot be extended by other classes.\n\nTo restrict which classes can extend this, use `<<__Sealed()>>`."
| SymbolOccurrence.FinalOnMethod ->
"A `final` method cannot be overridden in child classes."
| SymbolOccurrence.AbstractOnClass ->
"An `abstract` class can only contain `static` methods and `abstract` instance methods.\n\n"
^ "`abstract` classes cannot be instantiated directly. You can only use `new` on child classes that aren't `abstract`."
| SymbolOccurrence.AbstractOnMethod ->
"An `abstract` method has a signature but no body. Child classes must provide an implementation."
| SymbolOccurrence.ExtendsOnClass ->
"Extending a class allows your class to inherit methods from another class."
^ "\n\nInheritance allows your class to:"
^ "\n * Reuse methods from the parent class"
^ "\n * Call `protected` methods on the parent class"
^ "\n * Be passed as a parameter whenever an instance of the parent class is expected"
^ "\n\nHack does not support multiple inheritance on classes. If you need to share functionality between"
^ " unrelated classes, use traits."
| SymbolOccurrence.ExtendsOnInterface ->
"Extending an interface allows your interface to include methods from other interfaces."
^ "\n\nAn interface can extend multiple interfaces."
| SymbolOccurrence.ReadonlyOnMethod ->
"A `readonly` method treats `$this` as `readonly`."
| SymbolOccurrence.ReadonlyOnExpression
| SymbolOccurrence.ReadonlyOnParameter ->
"A `readonly` value is a reference that cannot modify the underlying value."
| SymbolOccurrence.ReadonlyOnReturnType ->
"This function/method may return a `readonly` value."
| SymbolOccurrence.XhpAttribute ->
"`attribute` declares which attributes are permitted on the current XHP class."
^ "\n\nAttributes are optional unless marked with `@required`."
| SymbolOccurrence.XhpChildren ->
"`children` declares which XHP types may be used as children when creating instances of this class."
^ "\n\nFor example, `children (:p)+` means that users may write `<my-class><p>hello</p><p>world</p></my_class>`."
^ "\n\n**`children` is not enforced by the type checker**, but an XHP framework can choose to validate it at runtime."
| SymbolOccurrence.ConstGlobal -> "A `const` is a global constant."
| SymbolOccurrence.ConstOnClass ->
"A class constant."
^ "\n\nClass constants have public visibility, so you can access `MyClass::MY_CONST` anywhere."
| SymbolOccurrence.ConstType ->
"A `const type` declares a type constant inside a class. You can refer to type constants in signatures with `this::TMyConstType`."
^ "\n\nType constants are also a form of generics."
^ "\n\n```"
^ "\nabstract class Pet {"
^ "\n abstract const type TFood;"
^ "\n}"
^ "\n"
^ "\nclass Cat extends Pet {"
^ "\n const type TFood = Fish;"
^ "\n}"
^ "\n```"
^ "\n\nType constants are static, not per-instance. All instances of `Cat` have the same value for `TFood`, whereas `MyObject<T>` generics can differ between instances."
^ "\n\nThis enables type constants to be used outside the class, e.g. `Cat::TFood`."
| SymbolOccurrence.StaticOnMethod ->
"A static method can be called without an instance, e.g. `MyClass::my_method()`."
| SymbolOccurrence.StaticOnProperty ->
"A static property is shared between all instances of a class. It can be accessed with `MyClass::$myProperty`."
| SymbolOccurrence.Use ->
"Include all the items (methods, properties etc) from a trait in this class/trait."
^ "\n\nIf this class/trait already has an item of the same name, the trait item is not copied."
| SymbolOccurrence.FunctionOnMethod ->
"A `function` inside a class declares a method."
| SymbolOccurrence.FunctionGlobal -> "A standalone global function."
| SymbolOccurrence.Async ->
"An `async` function can use `await` to get results from other `async` functions. You may still return plain values, e.g. `return 1;` is permitted in an `Awaitable<int>` function."
^ await_explanation
| SymbolOccurrence.AsyncBlock ->
"An `async` block is syntactic sugar for an `async` lambda that is immediately called."
^ "\n\n```"
^ "\n$f = async { return 1; };"
^ "\n// Equivalent to:"
^ "\n$f = (async () ==> { return 1; })();"
^ "\n```"
^ "\n\nThis is useful when building more complex async expressions."
^ "\n\n```"
^ "\nconcurrent {"
^ "\n $group_name = await async {"
^ "\n return $group is null ? '' : await $group->genName();"
^ "\n };"
^ "\n await async {"
^ "\n try {"
^ "\n await gen_log_request();"
^ "\n } catch (LogRequestFailed $_) {}"
^ "\n }"
^ "\n}"
^ "\n```"
| SymbolOccurrence.Await ->
"`await` waits for the result of an `Awaitable<_>` value."
^ await_explanation
| SymbolOccurrence.Concurrent ->
"`concurrent` allows you to `await` multiple values at once. This is similar to `Vec\\map_async`, but `concurrent` allows awaiting unrelated values of different types."
| SymbolOccurrence.Public ->
"A `public` method or property has no restrictions on access. It can be accessed from any part of the codebase."
^ "\n\nSee also `protected` and `private`."
| SymbolOccurrence.Protected ->
"A `protected` method or property can only be accessed from methods defined on the current class, or methods on subclasses."
^ "\n\nIf the current class `use`s a trait, the trait methods can also access `protected` methods and properties."
^ "\n\nSee also `public` and `private`."
| SymbolOccurrence.Private ->
"A `private` method or property can only be accessed from methods defined on the current class."
^ "\n\nPrivate items can be accessed on any instance of the current class. "
^ "For example, if you have a private property `name`, you can access both `$this->name` and `$other_instance->name`."
^ "\n\nIf the current class `use`s a trait, the trait methods can also access `private` methods and properties."
^ "\n\nSee also `public` and `protected`."
| SymbolOccurrence.Internal ->
"An `internal` symbol can only be accessed from files that belong to the current `module`."
| SymbolOccurrence.ModuleInModuleDeclaration ->
"`new module Foo {}` defines a new module but does not associate any code with it."
^ "\n\nYou must use `module Foo;` to mark all the definitions in a given file as associated with the `Foo` module and enable them to use `internal`."
| SymbolOccurrence.ModuleInModuleMembershipDeclaration ->
"`module Foo;` marks all the definitions in the current file as associated with the `Foo` module, and enables them to use `internal`."
^ "\n\nYou must also define this module with `new module Foo {}` inside or outside this file."
let split_class_name (full_name : string) : string =
match String.lsplit2 full_name ~on:':' with
| Some (class_name, _member) -> class_name
| None -> full_name
let fun_defined_in def_opt : string =
match def_opt with
| Some { SymbolDefinition.full_name; _ } ->
let abs_name = "\\" ^ full_name in
if SN.PseudoFunctions.is_pseudo_function abs_name then
""
else (
match String.rsplit2 (Utils.strip_hh_lib_ns abs_name) ~on:'\\' with
| Some (namespace, _) when not (String.equal namespace "") ->
Printf.sprintf "// Defined in namespace %s\n" namespace
| _ -> ""
)
| _ -> ""
let make_hover_info under_dynamic_result ctx env_and_ty entry occurrence def_opt
=
SymbolOccurrence.(
Typing_defs.(
let defined_in =
match def_opt with
| Some def ->
Printf.sprintf
"// Defined in %s\n"
(split_class_name def.SymbolDefinition.full_name)
| None -> ""
in
let snippet =
match (occurrence, env_and_ty) with
| ({ name; _ }, None) -> Utils.strip_hh_lib_ns name
| ({ type_ = Method (ClassName classname, name); _ }, Some (env, ty))
when String.equal name Naming_special_names.Members.__construct ->
let snippet_opt =
Option.Monad_infix.(
Decl_provider.get_class ctx classname >>= fun c ->
fst (Decl_provider.Class.construct c) >>| fun elt ->
let ty = Lazy.force_val elt.ce_type in
Tast_env.print_ty_with_identity env (DeclTy ty) occurrence def_opt)
in
defined_in
^
(match snippet_opt with
| Some s -> s
| None ->
Tast_env.print_ty_with_identity env (LoclTy ty) occurrence def_opt)
| ({ type_ = BestEffortArgument (recv, i); _ }, _) ->
let param_name = nth_param ctx recv i in
Printf.sprintf "Parameter: %s" (Option.value ~default:"$_" param_name)
| ({ type_ = Method _; _ }, Some (env, ty))
| ({ type_ = ClassConst _; _ }, Some (env, ty))
| ({ type_ = Property _; _ }, Some (env, ty)) ->
let ty = Tast_env.strip_dynamic env ty in
defined_in
^ Tast_env.print_ty_with_identity env (LoclTy ty) occurrence def_opt
| ({ type_ = GConst; _ }, Some (env, ty)) ->
(match make_hover_const_definition entry def_opt with
| Some def_txt -> def_txt
| None ->
Tast_env.print_ty_with_identity env (LoclTy ty) occurrence def_opt)
| ({ type_ = Function; _ }, Some (env, ty)) ->
fun_defined_in def_opt
^ Tast_env.print_ty_with_identity env (LoclTy ty) occurrence def_opt
| (occurrence, Some (env, ty)) ->
Tast_env.print_ty_with_identity env (LoclTy ty) occurrence def_opt
^ under_dynamic_result
in
let addendum =
match occurrence with
| { name; type_ = Attribute _; _ } ->
List.concat
[
make_hover_attr_docs name;
make_hover_doc_block ctx entry occurrence def_opt;
]
| { type_ = Keyword info; _ } -> [keyword_info info]
| { type_ = HhFixme; _ } -> [hh_fixme_info]
| { type_ = PureFunctionContext; _ } -> [pure_context_info]
| { type_ = BuiltInType bt; _ } ->
[SymbolOccurrence.built_in_type_hover bt]
| _ -> make_hover_doc_block ctx entry occurrence def_opt
in
HoverService.
{ snippet; addendum; pos = Some occurrence.SymbolOccurrence.pos }))
let make_hover_info_with_fallback under_dynamic_result results =
let class_fallback =
List.hd
(List.filter results ~f:(fun (_, _, _, occurrence, _) ->
SymbolOccurrence.is_class occurrence))
in
List.map
~f:(fun (ctx, env_and_ty, entry, occurrence, def_opt) ->
if
SymbolOccurrence.is_constructor occurrence
&& List.is_empty (make_hover_doc_block ctx entry occurrence def_opt)
then
(* Case where constructor docblock is empty. *)
let hover_info =
make_hover_info
under_dynamic_result
ctx
env_and_ty
entry
occurrence
def_opt
in
match class_fallback with
| Some (ctx, _, entry, class_occurrence, def_opt) ->
let fallback_doc_block =
make_hover_doc_block ctx entry class_occurrence def_opt
in
( occurrence,
HoverService.
{
snippet = hover_info.snippet;
addendum = List.concat [fallback_doc_block; hover_info.addendum];
pos = hover_info.pos;
} )
| None -> (occurrence, hover_info)
else
( occurrence,
make_hover_info
under_dynamic_result
ctx
env_and_ty
entry
occurrence
def_opt ))
results
let go_quarantined
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(line : int)
~(column : int) : HoverService.result =
let identities =
ServerIdentifyFunction.go_quarantined ~ctx ~entry ~line ~column
in
let { Tast_provider.Compute_tast.tast; _ } =
Tast_provider.compute_tast_quarantined ~ctx ~entry
in
let env_and_ty =
ServerInferType.human_friendly_type_at_pos
~under_dynamic:false
ctx
tast
line
column
in
let env_and_ty_dynamic =
ServerInferType.human_friendly_type_at_pos
~under_dynamic:true
ctx
tast
line
column
in
let under_dynamic_result =
match env_and_ty_dynamic with
| Some (env, ty') ->
(match env_and_ty with
| None -> ""
| Some (_, ty) ->
if Typing_defs.ty_equal ty ty' then
""
else
Printf.sprintf
" (%s when called dynamically)"
(Tast_env.print_ty env ty'))
| None -> ""
in
let result =
match (identities, env_and_ty) with
| ([], Some (env, ty)) ->
(* There are no identities (named entities) at the cursor, but we
know the type of the expression. Just show the type.
This can occur if the user hovers over a literal such as `123`. *)
[
{
snippet = Tast_env.print_ty env ty ^ under_dynamic_result;
addendum = [];
pos = None;
};
]
| ( [
( {
SymbolOccurrence.type_ =
SymbolOccurrence.BestEffortArgument (recv, i);
_;
},
_ );
],
_ ) ->
(* There are no identities (named entities) at the cursor, but we
know the type of the expression and the name of the parameter
from the definition site.
This can occur if the user hovers over a literal in a call,
e.g. `foo(123)`. *)
let ty_result =
match env_and_ty with
| Some (env, ty) ->
[
{
snippet = Tast_env.print_ty env ty ^ under_dynamic_result;
addendum = [];
pos = None;
};
]
| None -> []
in
let param_result =
match nth_param ctx recv i with
| Some param_name ->
[
{
snippet = Printf.sprintf "Parameter: %s" param_name;
addendum = [];
pos = None;
};
]
| None -> []
in
ty_result @ param_result
| (identities, _) ->
(* We have a list of named things at the cursor. Show the
docblock and type of each thing. *)
identities
|> List.map ~f:(fun (occurrence, def_opt) ->
(* If we're hovering over a type hint, we're not interested
in the type of the enclosing expression. *)
let env_and_ty =
match occurrence.SymbolOccurrence.type_ with
| SymbolOccurrence.TypeVar -> None
| SymbolOccurrence.BuiltInType _ -> None
| _ -> env_and_ty
in
let path =
def_opt
|> Option.map ~f:(fun def -> def.SymbolDefinition.pos)
|> Option.map ~f:Pos.filename
|> Option.value ~default:entry.Provider_context.path
in
let (ctx, entry) =
Provider_context.add_entry_if_missing ~ctx ~path
in
(ctx, env_and_ty, entry, occurrence, def_opt))
|> make_hover_info_with_fallback under_dynamic_result
|> filter_class_and_constructor
|> List.remove_consecutive_duplicates ~equal:equal_hover_info
in
result |
OCaml Interface | hhvm/hphp/hack/src/server/serverHover.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.
*
*)
(** Returns detailed information about the symbol or expression at the given
location. *)
val go_quarantined :
ctx:Provider_context.t ->
entry:Provider_context.entry ->
line:int ->
column:int ->
HoverService.result |
OCaml | hhvm/hphp/hack/src/server/serverIdentifyFunction.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
(* Order symbols from innermost to outermost *)
let by_nesting x y =
if Pos.contains x.SymbolOccurrence.pos y.SymbolOccurrence.pos then
if Pos.contains y.SymbolOccurrence.pos x.SymbolOccurrence.pos then
0
else
1
else
-1
let rec take_best_suggestions l =
match l with
| first :: rest ->
(* Check if we should stop finding suggestions. For example, in
"foo($bar)" it's not useful to look outside the local variable "$bar". *)
let stop =
match first.SymbolOccurrence.type_ with
| SymbolOccurrence.LocalVar -> true
| SymbolOccurrence.Method _ -> true
| SymbolOccurrence.Class _ -> true
| _ -> false
in
if stop then
(* We're stopping here, but also include the other suggestions for
this span. *)
first :: List.take_while rest ~f:(fun x -> by_nesting first x = 0)
else
first :: take_best_suggestions rest
| [] -> []
let go_quarantined
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(line : int)
~(column : int) =
let symbols =
IdentifySymbolService.go_quarantined ~ctx ~entry ~line ~column
in
let symbols = take_best_suggestions (List.sort ~compare:by_nesting symbols) in
(* TODO(ljw): shouldn't the following be quarantined also? *)
List.map symbols ~f:(fun symbol ->
let ast =
Ast_provider.compute_ast ~popt:(Provider_context.get_popt ctx) ~entry
in
let symbol_definition = ServerSymbolDefinition.go ctx (Some ast) symbol in
(symbol, symbol_definition))
let go_quarantined_absolute
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(line : int)
~(column : int) :
(string SymbolOccurrence.t * string SymbolDefinition.t option) list =
go_quarantined ~ctx ~entry ~line ~column
|> List.map ~f:(fun (occurrence, definition) ->
let occurrence = SymbolOccurrence.to_absolute occurrence in
let definition =
Option.map ~f:SymbolDefinition.to_absolute definition
in
(occurrence, definition)) |
OCaml | hhvm/hphp/hack/src/server/serverIdle.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 SearchServiceRunner
(*****************************************************************************)
(* Periodically called by the daemon *)
(*****************************************************************************)
type callback =
| Periodic of (float ref * float * (env:ServerEnv.env -> ServerEnv.env))
| Once of (float ref * (env:ServerEnv.env -> ServerEnv.env))
module Periodical : sig
val always : float
val one_second : float
val one_minute : float
val one_hour : float
val one_day : float
val one_week : float
(** Check if any callback is due and run those. *)
val check : ServerEnv.env -> ServerEnv.env
(* register_callback X Y
* Registers a new callback Y called every X seconds.
* The time is an approximation, don't expect it to be supper accurate.
* More or less 1 sec is a more or less what you can expect.
* More or less 30 secs if the server is busy.
*)
val register_callback : callback -> unit
end = struct
let always = 0.0
let one_second = 1.0
let one_minute = 60.0
let one_hour = 3600.0
let one_day = 86400.0
let one_week = 604800.0
let callback_list = ref []
let last_call = ref (Unix.time ())
let check (env : ServerEnv.env) : ServerEnv.env =
let current = Unix.time () in
let delta = current -. !last_call in
let env = ref env in
last_call := current;
callback_list :=
List.filter !callback_list ~f:(fun callback ->
(match callback with
| Periodic (seconds_left, _, job)
| Once (seconds_left, job) ->
seconds_left := !seconds_left -. delta;
if Float.(!seconds_left < 0.0) then env := job ~env:!env);
match callback with
| Periodic (seconds_left, period, _) ->
if Float.(!seconds_left < 0.0) then seconds_left := period;
true
| Once _ -> false);
!env
let register_callback cb = callback_list := cb :: !callback_list
end
let go = Periodical.check
let async f = Periodical.register_callback (Once (ref 0.0, f))
(*****************************************************************************)
(*
* kill the server every 24h. We do this to save resources and
* make sure everyone is +/- running the same version.
*
* TODO: improve this check so the server only restarts
* if there hasn't been any activity for x hours/days.
*)
(*****************************************************************************)
(* We want to keep track of when the server was last used. Every few hours, we'll
* check this variable. If the server hasn't been used for a few days, we exit.
*)
let last_client_connect : float ref = ref (Unix.time ())
let stamp_connection () =
last_client_connect := Unix.time ();
()
let exit_if_unused () =
let delta : float = Unix.time () -. !last_client_connect in
if Float.(delta > Periodical.one_week) then (
Printf.eprintf "Exiting server. Last used >7 days ago\n";
Exit.exit Exit_status.Unused_server
)
(*****************************************************************************)
(* The registered jobs *)
(*****************************************************************************)
let init (genv : ServerEnv.genv) (root : Path.t) : unit =
let jobs =
[
(* I'm not sure explicitly invoking the Gc here is necessary, but
* major_slice takes something like ~0.0001s to run, so why not *)
( Periodical.always,
fun ~env ->
let _result : int = Gc.major_slice 0 in
env );
( Periodical.one_second,
fun ~env ->
EventLogger.recheck_disk_files ();
env );
( Periodical.one_minute *. 5.,
fun ~env ->
begin
try
(* We'll cycle the client-log if it gets bigger than 1Mb.
We do this cycling here in the server (rather than in the client)
to avoid races when multiple concurrent clients try to cycle it. *)
let client_log_fn = ServerFiles.client_log root in
let stat = Unix.stat client_log_fn in
if stat.Unix.st_size > 1024 * 1024 then
Sys.rename client_log_fn (client_log_fn ^ ".old")
with
| _ -> ()
end;
env );
( Periodical.one_hour *. 3.,
fun ~env ->
EventLogger.log_gc_stats ();
env );
( Periodical.always,
fun ~env ->
SharedMem.GC.collect `aggressive;
env );
( Periodical.always,
fun ~env ->
EventLogger.flush ();
env );
( Periodical.always,
fun ~env ->
let ctx = Provider_utils.ctx_from_server_env env in
let local_symbol_table =
SearchServiceRunner.run genv ctx env.ServerEnv.local_symbol_table
in
{ env with ServerEnv.local_symbol_table } );
( Periodical.one_day,
fun ~env ->
exit_if_unused ();
env );
( Periodical.one_day,
fun ~env ->
Hhi.touch ();
env );
(* Touch_existing{false} wraps Unix.lutimes, which doesn't open/close any fds, so we
* won't lose our lock by doing this. We are only touching the top level
* of files, however -- we don't want to do it recursively so that old
* files under e.g. /tmp/hh_server/logs still get cleaned up. *)
( Periodical.one_day,
fun ~env ->
Array.iter
~f:
begin
fun fn ->
let fn = Filename.concat GlobalConfig.tmp_dir fn in
if
(try Sys.is_directory fn with
| _ -> false)
(* We don't want to touch things like .watchman_failed *)
|| String.is_prefix fn ~prefix:"."
|| not (ServerFiles.is_of_root root fn)
then
()
else
Sys_utils.try_touch
(Sys_utils.Touch_existing { follow_symlinks = false })
fn
end
(Sys.readdir GlobalConfig.tmp_dir);
env );
]
in
List.iter jobs ~f:(fun (period, cb) ->
Periodical.register_callback (Periodic (ref period, period, cb))) |
OCaml Interface | hhvm/hphp/hack/src/server/serverIdle.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.
*
*)
(** This module contains the code to be run whenever the server is idle, e.g.
garbage collection. It manages a set of callbacks to be run periodically
whenever the server is idle. *)
(** Initialize with a set of default periodic callbacks, for example
garbage collection, log flushing, etc. *)
val init : ServerEnv.genv -> Path.t -> unit
(** Register the provided function as a callback to be run next time the server
is idle. *)
val async : (env:ServerEnv.env -> ServerEnv.env) -> unit
(** Called whenever the server is idle. Will run any due callbacks. *)
val go : ServerEnv.env -> ServerEnv.env
(** Record timestamp of client connections *)
val stamp_connection : unit -> unit |
OCaml | hhvm/hphp/hack/src/server/serverIdleGc.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.
*
*)
(* We need some estimate when to stop running major_slice to avoid just marking and sweeping
* in a busy loop forever. There might be some more accurate counters hidden somewhere, but for
* now I will just very conservatively assume that EVERY word allocated in major heap is potentially
* garbage and will keep running major_slice as long as the sum of its arguments is less than total
* major heap words allocated since program start. This is obviously way too much:
* - some of the words are not garbage
* - some (probably many) of the words will be already collected by automatic slices
* - there is some chance that major_slice argument doesn't mean what I think it means
*
* It seems to be working in practice - it stops marking and sweeping reasonably fast
* (below 200ms) after allocations stop, and it does smooth out some test cases I tried *)
let gc_slice_sum_ref = ref 0.0
let gc slice =
let { Gc.major_words; _ } = Gc.quick_stat () in
let next_sum = !gc_slice_sum_ref +. float_of_int slice in
if major_words < next_sum then
true
else
let (_ : int) = Gc.major_slice slice in
gc_slice_sum_ref := next_sum;
false
let rec select ~slice ~deadline fd_list =
let (ready_fds, _, _) = Unix.select fd_list [] [] 0.0 in
let t = Unix.gettimeofday () in
match ready_fds with
| [] when slice = 0 -> []
| [] when t < deadline ->
let is_finished = gc slice in
if is_finished then
ready_fds
else
select ~slice ~deadline fd_list
| _ -> ready_fds
let select ~slice ~timeout fd_list =
let deadline = Unix.gettimeofday () +. timeout in
select ~slice ~deadline fd_list |
OCaml Interface | hhvm/hphp/hack/src/server/serverIdleGc.mli | (*
* 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.
*
*)
val select :
slice:int -> timeout:float -> Unix.file_descr list -> Unix.file_descr list |
OCaml | hhvm/hphp/hack/src/server/serverInferType.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 Option.Monad_infix
(* Is this expression indexing into a value of type shape?
* E.g. $some_shope['foo'].
*
* If so, return the receiver.
*)
let shape_indexing_receiver env (_, _, expr_) : Tast.expr option =
match expr_ with
| Aast.Array_get (((recv_ty, _, _) as recv), _) ->
let ty = Tast_env.fully_expand env recv_ty in
let (_, ty_) = Typing_defs_core.deref ty in
(match ty_ with
| Typing_defs_core.Tshape _ -> Some recv
| _ -> None)
| _ -> None
let class_const_ty env (cc : Tast.class_const) : Tast.ty option =
let open Aast in
match cc.cc_type with
| Some hint ->
let decl_ty = Tast_env.hint_to_ty env hint in
let (_, ty) = Tast_env.localize_no_subst env ~ignore_errors:true decl_ty in
Some ty
| None ->
let init_expr =
match cc.cc_kind with
| CCConcrete e -> Some e
| CCAbstract e_opt -> e_opt
in
init_expr >>| fun (ty, _, _) -> ty
let class_id_ty env (id : Ast_defs.id) : Tast.ty =
let (p, _) = id in
let hint = (p, Aast.Happly (id, [])) in
let decl_ty = Tast_env.hint_to_ty env hint in
let (_, ty) = Tast_env.localize_no_subst env ~ignore_errors:true decl_ty in
ty
(** Return the type of the smallest expression node whose associated span
* (the Pos.t in its Tast.ExprAnnotation.t) contains the given position.
* "Smallest" here refers to the size of the node's associated span, in terms of
* its byte length in the original source file.
*
* If there is no single smallest node (i.e., multiple expression nodes have
* spans of the same length containing the given position, where that length is
* less than the length of all other spans containing the given position),
* return the type of the first of these nodes visited in a preorder traversal
* of the Tast.
*
* This choice is somewhat arbitrary, and would seem to be unnecessary at first
* blush (and indeed would be in a concrete syntax tree). In most situations,
* each expression should have a distinct span, but consider a sugar
* pseudofunction `log_arraykey` which is desugared as follows:
*
* log_arraykey($ak);
* // desugars to:
* if (is_int($ak)) { log_int($ak); }
* if (is_string($ak)) { log_string($ak); }
*
* In this situation, four expressions in the TAST have an equivalent span
* referring to the span of `$ak` in the original source. We return the type of
* the first visited in a preorder traversal, the argument to `is_int`. This
* expression will have the expected type (i.e., the type of `$ak` before it is
* refined by `is_int` or `is_string` in desugared code).
*
* Multiple expressions could also be associated with the same span if we
* introduced a purely-logical expression to the TAST, which had no syntactical
* representation (i.e., it contained a single child: another expression with
* the same associated span).
*
* The choice of returning the "smallest" expression is as a proxy for concrete
* syntax specificity, where a child node (in the concrete syntax tree) is
* considered more specific than its parent. We would like to return the type of
* the most specific expression node containing the given position, but we
* cannot assume that the structure of the CST is reflected in the TAST.
*)
let base_visitor ~human_friendly ~under_dynamic line char =
object (self)
inherit [_] Tast_visitor.reduce as super
inherit [Pos.t * _ * _] Visitors_runtime.option_monoid
method private correct_assumptions env =
let is_under_dynamic_assumptions =
(Tast_env.tast_env_as_typing_env env).Typing_env_types.checked
|> Tast.is_under_dynamic_assumptions
in
Bool.equal is_under_dynamic_assumptions under_dynamic
method private merge lhs rhs =
(* A node with position P is not always a parent of every other node with
* a position contained by P. Some desugaring can cause nodes to be
* rearranged so that this is no longer the case (e.g., `invariant`).
*
* To deal with this, we simply take the smaller node. *)
let (lpos, _, _) = lhs in
let (rpos, _, _) = rhs in
if Pos.length lpos <= Pos.length rpos then
lhs
else
rhs
method private merge_opt lhs rhs =
match (lhs, rhs) with
| (Some lhs, Some rhs) -> Some (self#merge lhs rhs)
| (Some lhs, None) -> Some lhs
| (None, Some rhs) -> Some rhs
| (None, None) -> None
method! on_expr env ((ty, pos, _) as expr) =
if Pos.inside pos line char && self#correct_assumptions env then begin
match shape_indexing_receiver env expr with
| Some recv when human_friendly ->
(* If we're looking at a shape indexing expression, we don't
want to recurse on the string literal.
For example, if we have the code $user['age'] and hover
over 'age', we want the hover type to be int, not string. *)
self#merge_opt (Some (pos, env, ty)) (self#on_expr env recv)
| _ -> self#merge_opt (Some (pos, env, ty)) (super#on_expr env expr)
end else
super#on_expr env expr
method! on_fun_param env fp =
if Pos.inside fp.Aast.param_pos line char && self#correct_assumptions env
then
self#merge_opt
(Some (fp.Aast.param_pos, env, fp.Aast.param_annotation))
(super#on_fun_param env fp)
else
super#on_fun_param env fp
method! on_capture_lid env ((ty, (pos, _)) as cl) =
if Pos.inside pos line char && self#correct_assumptions env then
Some (pos, env, ty)
else
super#on_capture_lid env cl
method! on_xhp_simple env attribute =
let (pos, _) = attribute.Aast.xs_name in
if Pos.inside pos line char && self#correct_assumptions env then
Some (pos, env, attribute.Aast.xs_type)
else
super#on_xhp_simple env attribute
method! on_class_id env ((ty, pos, _) as cid) =
match cid with
(* Don't use the resolved class type (the expr_annotation on the class_id
type) when hovering over a CIexpr--we will want to show the type the
expression is annotated with (e.g., classname<C>) and it will not have a
smaller position. *)
| (_, _, Aast.CIexpr e) -> self#on_expr env e
| _ ->
if Pos.inside pos line char && self#correct_assumptions env then
self#merge_opt (Some (pos, env, ty)) (super#on_class_id env cid)
else
super#on_class_id env cid
method! on_class_const env cc =
let acc = super#on_class_const env cc in
let (pos, _) = cc.Aast.cc_id in
if Pos.inside pos line char && self#correct_assumptions env then
match class_const_ty env cc with
| Some ty -> self#merge_opt (Some (pos, env, ty)) acc
| None -> acc
else
acc
method! on_EnumClassLabel env id label_name =
let acc = super#on_EnumClassLabel env id label_name in
match id with
| Some ((pos, _) as id)
when Pos.inside pos line char && self#correct_assumptions env ->
let ty = class_id_ty env id in
Some (pos, env, ty)
| _ -> acc
method! on_If env cond then_block else_block =
match ServerUtils.resugar_invariant_call env cond then_block with
| Some e -> self#on_expr env e
| None -> super#on_If env cond then_block else_block
end
(** Return the type of the node associated with exactly the given range.
When more than one node has the given range, return the type of the first
node visited in a preorder traversal.
*)
let range_visitor startl startc endl endc =
object
inherit [_] Tast_visitor.reduce as super
inherit [_] Visitors_runtime.option_monoid
method merge x _ = x
method! on_expr env ((ty, pos, _) as expr) =
if
Pos.exactly_matches_range
pos
~start_line:startl
~start_col:startc
~end_line:endl
~end_col:endc
then
Some (env, ty)
else
super#on_expr env expr
method! on_fun_param env fp =
if
Pos.exactly_matches_range
fp.Aast.param_pos
~start_line:startl
~start_col:startc
~end_line:endl
~end_col:endc
then
Some (env, fp.Aast.param_annotation)
else
super#on_fun_param env fp
method! on_class_id env ((ty, pos, _) as cid) =
if
Pos.exactly_matches_range
pos
~start_line:startl
~start_col:startc
~end_line:endl
~end_col:endc
then
Some (env, ty)
else
super#on_class_id env cid
end
let type_at_pos
(ctx : Provider_context.t)
(tast : Tast.program Tast_with_dynamic.t)
(line : int)
(char : int) : (Tast_env.env * Tast.ty) option =
(base_visitor ~human_friendly:false ~under_dynamic:false line char)#go
ctx
tast.Tast_with_dynamic.under_normal_assumptions
>>| fun (_, env, ty) -> (env, ty)
(* Return the expanded type of smallest expression at this
position. Skips string literals in shape indexing expressions so
hover results are more relevant.
If [under_dynamic] is true, look for type produced
when env.checked = CUnderDynamicAssumptions
Otherwise, look for type produced in normal checking
when env.checked = COnce or env.checked = CUnderNormalAssumptions.
*)
let human_friendly_type_at_pos
~under_dynamic
(ctx : Provider_context.t)
(tast : Tast.program Tast_with_dynamic.t)
(line : int)
(char : int) : (Tast_env.env * Tast.ty) option =
let tast =
if under_dynamic then
Option.value ~default:[] tast.Tast_with_dynamic.under_dynamic_assumptions
else
tast.Tast_with_dynamic.under_normal_assumptions
in
(base_visitor ~human_friendly:true ~under_dynamic line char)#go ctx tast
|> Option.map ~f:(fun (_, env, ty) -> (env, Tast_expand.expand_ty env ty))
let type_at_range
(ctx : Provider_context.t)
(tast : Tast.program Tast_with_dynamic.t)
(start_line : int)
(start_char : int)
(end_line : int)
(end_char : int) : (Tast_env.env * Tast.ty) option =
(range_visitor start_line start_char end_line end_char)#go
ctx
tast.Tast_with_dynamic.under_normal_assumptions
let go_ctx
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(line : int)
~(column : int) : (string * string) option =
let { Tast_provider.Compute_tast.tast; _ } =
Tast_provider.compute_tast_quarantined ~ctx ~entry
in
type_at_pos ctx tast line column >>| fun (env, ty) ->
( Tast_env.print_ty env ty,
Tast_env.ty_to_json env ty |> Hh_json.json_to_string ) |
OCaml Interface | hhvm/hphp/hack/src/server/serverInferType.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 type_at_pos :
Provider_context.t ->
Tast.program Tast_with_dynamic.t ->
int ->
int ->
(Tast_env.env * Tast.ty) option
val human_friendly_type_at_pos :
under_dynamic:bool ->
Provider_context.t ->
Tast.program Tast_with_dynamic.t ->
int ->
int ->
(Tast_env.env * Tast.ty) option
val type_at_range :
Provider_context.t ->
Tast.program Tast_with_dynamic.t ->
int ->
int ->
int ->
int ->
(Tast_env.env * Tast.ty) option
val go_ctx :
ctx:Provider_context.t ->
entry:Provider_context.entry ->
line:int ->
column:int ->
(string * string) option |
OCaml | hhvm/hphp/hack/src/server/serverInferTypeBatch.ml | (*
* Copyright (c) 2017, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE fn in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type pos = Relative_path.t * int * int * (int * int) option
type spos = string * int * int * (int * int) option [@@deriving eq, ord]
let recheck_typing ctx (path_list : Relative_path.t list) =
let files_to_check =
List.sort path_list ~compare:Relative_path.compare
|> List.remove_consecutive_duplicates ~equal:Relative_path.equal
in
let (ctx, paths_and_tasts) =
List.fold
files_to_check
~init:(ctx, [])
~f:(fun (ctx, paths_and_tasts) path ->
let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path in
let { Tast_provider.Compute_tast.tast; _ } =
Tast_provider.compute_tast_unquarantined ~ctx ~entry
in
(ctx, (path, tast) :: paths_and_tasts))
in
(ctx, paths_and_tasts)
let get_tast_map ctx path_list =
let (ctx, paths_and_tasts) = recheck_typing ctx path_list in
let tasts =
List.fold
paths_and_tasts
~init:Relative_path.Map.empty
~f:(fun map (key, data) -> Relative_path.Map.add map ~key ~data)
in
(ctx, tasts)
let result_to_string result (fn, line, char, range_end) =
Hh_json.(
let obj =
JSON_Object
[
( "position",
JSON_Object
([("file", JSON_String (Relative_path.to_absolute fn))]
@
match range_end with
| None -> [("line", int_ line); ("character", int_ char)]
| Some (end_line, end_char) ->
let pos l c =
JSON_Object [("line", int_ l); ("character", int_ c)]
in
[("start", pos line char); ("end", pos end_line end_char)]) );
(match result with
| Ok ty -> ("type", Option.value ty ~default:JSON_Null)
| Error e -> ("error", JSON_String e));
]
in
json_to_string obj)
let helper ctx acc pos_list =
let path_list = List.map pos_list ~f:(fun (path, _, _, _) -> path) in
let (ctx, tasts) = get_tast_map ctx path_list in
List.fold pos_list ~init:acc ~f:(fun acc pos ->
let (fn, line, char, range_end) = pos in
let result =
Relative_path.Map.find_opt tasts fn
|> Result.of_option ~error:"No such file or directory"
|> Result.map ~f:(fun tast ->
let env_and_ty =
match range_end with
| None -> ServerInferType.type_at_pos ctx tast line char
| Some (end_line, end_char) ->
ServerInferType.type_at_range
ctx
tast
line
char
end_line
end_char
in
Option.map env_and_ty ~f:(fun (env, ty) ->
Tast_env.ty_to_json env ty))
in
result_to_string result pos :: acc)
(** This divides files amongst all the workers.
No file is handled by more than one worker. *)
let parallel_helper
(workers : MultiWorker.worker list option)
(ctx : Provider_context.t)
(pos_list : pos list) : string list =
let add_pos_to_map map pos =
let (path, _, _, _) = pos in
Relative_path.Map.update
path
(function
| None -> Some [pos]
| Some others -> Some (pos :: others))
map
in
let pos_by_file =
List.fold ~init:Relative_path.Map.empty ~f:add_pos_to_map pos_list
|> Relative_path.Map.values
in
(* pos_by_file is a list-of-lists [[posA1;posA2;...];[posB1;...];...]
where each inner list [posA1;posA2;...] is all for the same file.
This is so that a given file is only ever processed by a single worker. *)
MultiWorker.call
workers
~job:(fun acc pos_by_file -> helper ctx acc (List.concat pos_by_file))
~neutral:[]
~merge:List.rev_append
~next:(MultiWorker.next workers pos_by_file)
(* Entry Point *)
let go :
MultiWorker.worker list option ->
(string * int * int * (int * int) option) list ->
ServerEnv.env ->
string list =
fun workers pos_list env ->
let pos_list =
pos_list
(* Sort, so that many queries on the same file will (generally) be
* dispatched to the same worker. *)
|> List.sort ~compare:compare_spos
(* Dedup identical queries *)
|> List.remove_consecutive_duplicates ~equal:equal_spos
|> List.map ~f:(fun (fn, line, char, range_end) ->
let fn = Relative_path.create_detect_prefix fn in
(fn, line, char, range_end))
in
let num_files =
pos_list
|> List.map ~f:(fun (path, _, _, _) -> path)
|> Relative_path.Set.of_list
|> Relative_path.Set.cardinal
in
let num_positions = List.length pos_list in
let ctx = Provider_utils.ctx_from_server_env env in
let start_time = Unix.gettimeofday () in
(* Just for now, as a rollout telemetry defense against crashes, we'll log at the start *)
HackEventLogger.type_at_pos_batch
~start_time
~num_files
~num_positions
~results:None;
let results =
if num_positions < 10 then
helper ctx [] pos_list
else
parallel_helper workers ctx pos_list
in
HackEventLogger.type_at_pos_batch
~start_time
~num_files
~num_positions
~results:(Some (List.length results));
results |
OCaml Interface | hhvm/hphp/hack/src/server/serverInferTypeBatch.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 pos = Relative_path.t * int * int * (int * int) option
val get_tast_map :
Provider_context.t ->
Relative_path.t list ->
Provider_context.t * Tast.program Tast_with_dynamic.t Relative_path.Map.t
val go :
MultiWorker.worker list option ->
(string * int * int * (int * int) option) list ->
ServerEnv.env ->
string list |
OCaml | hhvm/hphp/hack/src/server/serverInferTypeError.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 starts_at pos line char_start =
let (l, c, _) = Pos.info_pos pos in
line = l && char_start = c
let visitor line char =
object
inherit [_] Tast_visitor.reduce as super
method private zero = None
(* A node with position P is not always a parent of every other node with
* a position contained by P. Some desugaring can cause nodes to be
* rearranged so that this is no longer the case (e.g., `invariant`).
*
* Since we are finding `Hole`s based on their exact starting position,
* we _shouldn't_ encounter the case of two simultaneous `Hole`s with
* different parents but the logic to handle this is retained - we simply
* take the smaller node. *)
method private plus lhs rhs =
Option.merge
lhs
rhs
~f:(fun ((lpos, _, _, _) as lhs) ((rpos, _, _, _) as rhs) ->
if Pos.length lpos <= Pos.length rpos then
lhs
else
rhs)
(* Find the the `Hole` which exactly starts at the provided position;
if the current hole does not, call method on supertype to continue
recursion *)
method! on_Hole env expr from_ty to_ty hole_source =
match (expr, hole_source) with
| ((_, pos, _), Aast.Typing) when starts_at pos line char ->
Some (pos, env, from_ty, to_ty)
| _ -> super#on_Hole env expr from_ty to_ty hole_source
end
let type_error_at_pos
(ctx : Provider_context.t) (tast : Tast.program) (line : int) (char : int) :
(Tast_env.env * Tast.ty * Tast.ty) option =
Option.(
(visitor line char)#go ctx tast >>| fun (_, env, actual_ty, expected_ty) ->
(env, actual_ty, expected_ty))
let go_ctx
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(line : int)
~(column : int) : InferErrorAtPosService.result =
let { Tast_provider.Compute_tast.tast; _ } =
Tast_provider.compute_tast_quarantined ~ctx ~entry
in
Option.(
type_error_at_pos
ctx
tast.Tast_with_dynamic.under_normal_assumptions
line
column
>>| fun (env, from_ty, to_ty) ->
Tast_env.(
InferErrorAtPosService.
{
actual_ty_string = print_ty env from_ty;
actual_ty_json = Hh_json.json_to_string @@ ty_to_json env from_ty;
expected_ty_string = print_ty env to_ty;
expected_ty_json = Hh_json.json_to_string @@ ty_to_json env to_ty;
})) |
OCaml | hhvm/hphp/hack/src/server/serverInit.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 Result.Export
open SearchServiceRunner
open ServerEnv
module SLC = ServerLocalConfig
include ServerInitTypes
let run_search (genv : ServerEnv.genv) (env : ServerEnv.env) :
SearchUtils.si_env =
let ctx = Provider_utils.ctx_from_server_env env in
let sienv = env.local_symbol_table in
if
SearchServiceRunner.should_run_completely
genv
sienv.SearchUtils.sie_provider
then
SearchServiceRunner.run_completely ctx sienv
else
sienv
let save_state
(genv : ServerEnv.genv) (env : ServerEnv.env) (output_filename : string) :
SaveStateServiceTypes.save_state_result option =
let ignore_errors =
ServerArgs.gen_saved_ignore_type_errors genv.ServerEnv.options
in
let has_errors = not (Errors.is_empty env.errorl) in
let do_save_state =
if ignore_errors then (
if has_errors then
Printf.eprintf
"WARNING: BROKEN SAVED STATE! Generating saved state. Ignoring type errors.\n%!"
else
Printf.eprintf
"Generating saved state and ignoring type errors, but there were none.\n%!";
true
) else if has_errors then (
Printf.eprintf
"Refusing to generate saved state. There are type errors\n%!";
Printf.eprintf "and --gen-saved-ignore-type-errors was not provided.\n%!";
false
) else
true
in
if not do_save_state then
None
else
let result = SaveStateService.save_state env output_filename in
Some result
let post_init genv (env, _t) =
(* Configure symbol index settings *)
ServerProgress.write "updating search index...";
let namespace_map = ParserOptions.auto_namespace_map env.tcopt in
let env =
{
env with
local_symbol_table =
SymbolIndex.initialize
~gleanopt:env.gleanopt
~namespace_map
~provider_name:
genv.local_config.ServerLocalConfig.symbolindex_search_provider
~quiet:genv.local_config.ServerLocalConfig.symbolindex_quiet
~savedstate_file_opt:
genv.local_config.ServerLocalConfig.symbolindex_file
~workers:genv.workers;
}
in
let env = { env with local_symbol_table = run_search genv env } in
SharedMem.SMTelemetry.init_done ();
env
let get_lazy_level (genv : ServerEnv.genv) : lazy_level =
let lazy_decl = Option.is_none (ServerArgs.ai_mode genv.options) in
let lazy_parse = genv.local_config.SLC.lazy_parse in
let lazy_initialize = genv.local_config.SLC.lazy_init in
match (lazy_decl, lazy_parse, lazy_initialize) with
| (true, false, false) -> Decl
| (true, true, false) -> Parse
| (true, true, true) -> Init
| _ -> Off
let lazy_full_init genv env profiling =
( ServerLazyInit.full_init genv env profiling |> post_init genv,
Load_state_declined "No saved-state requested (for lazy init)" )
let lazy_parse_only_init genv env profiling =
( ServerLazyInit.parse_only_init genv env profiling |> fst,
Load_state_declined "No saved-state requested (for lazy parse-only init)" )
let lazy_saved_state_init
~do_indexing genv env root load_state_approach profiling =
let result =
ServerLazyInit.saved_state_init
~do_indexing
~load_state_approach
genv
env
root
profiling
in
(* Saved-state init is the only kind of init that might error... *)
match result with
| Ok ((env, t), ({ saved_state_delta; _ }, _)) ->
let env = post_init genv (env, t) in
(env, Load_state_succeeded saved_state_delta)
| Error err ->
let ServerInitTypes.{ message; auto_retry; telemetry } =
load_state_error_to_verbose_string err
in
let (next_step_descr, next_step, user_instructions) =
if do_indexing then
(* ServerInit.Write_symbol_info_with_state will never fallback upon saved-state problems *)
("fatal", Exit_status.Failed_to_load_should_abort, None)
else if not genv.local_config.SLC.require_saved_state then
(* without "--config require_saved_state=true", we're happy to fallback to full init *)
("fallback", Exit_status.No_error, None)
else if auto_retry then
(* The auto-retry means we'll exit in such a way that find_hh.sh will rerun us *)
("retry", Exit_status.Failed_to_load_should_retry, None)
else
(* No fallbacks, no retries, no recourse! Let's explain this clearly to the user. *)
( "fatal",
Exit_status.Failed_to_load_should_abort,
Some ServerInitMessages.messageSavedStateFailedFullInitDisabled )
in
let user_message = Printf.sprintf "%s [%s]" message next_step_descr in
let user_message =
match user_instructions with
| None -> user_message
| Some user_instructions ->
Printf.sprintf "%s\n\n%s" user_message user_instructions
in
HackEventLogger.load_state_exn telemetry;
Hh_logger.log "LOAD_STATE_EXN %s" (Telemetry.to_string telemetry);
(match next_step with
| Exit_status.No_error ->
let fall_back_to_full_init profiling =
ServerLazyInit.full_init genv env profiling |> post_init genv
in
( CgroupProfiler.step_group "lazy_full_init" ~log:true
@@ fall_back_to_full_init,
Load_state_failed (user_message, telemetry) )
| _ -> Exit.exit ~msg:user_message ~telemetry next_step)
let eager_init genv env _lazy_lev profiling =
let init_result =
Hh_logger.log "Saved-state requested, but overridden by eager init";
Load_state_declined "Saved-state requested, but overridden by eager init"
in
let env =
ServerEagerInit.init genv _lazy_lev env profiling |> post_init genv
in
(env, init_result)
let eager_full_init genv env _lazy_lev profiling =
let env =
ServerEagerInit.init genv _lazy_lev env profiling |> post_init genv
in
let init_result = Load_state_declined "No saved-state requested" in
(env, init_result)
let lazy_write_symbol_info_init genv env root (load_state : 'a option) profiling
=
match load_state with
| None ->
( ServerLazyInit.write_symbol_info_full_init genv env profiling
|> post_init genv,
Load_state_declined "Write Symobl info state" )
| Some load_state_approach ->
lazy_saved_state_init
~do_indexing:true
genv
env
root
load_state_approach
profiling
(* entry point *)
let init
~(init_approach : init_approach)
(genv : ServerEnv.genv)
(env : ServerEnv.env) : ServerEnv.env * init_result =
if genv.local_config.ServerLocalConfig.rust_provider_backend then (
Hh_logger.log "ServerInit: using rust backend";
Provider_backend.set_rust_backend env.popt
);
let lazy_lev = get_lazy_level genv in
let root = ServerArgs.root genv.options in
let (init_method, init_method_name) =
Hh_logger.log "ServerInit: lazy_lev=%s" (show_lazy_level lazy_lev);
Hh_logger.log
"ServerInit: init_approach=%s"
(show_init_approach init_approach);
match (lazy_lev, init_approach) with
| (Init, Full_init) -> (lazy_full_init genv env, "lazy_full_init")
| (Init, Parse_only_init) ->
(lazy_parse_only_init genv env, "lazy_parse_only_init")
| (Init, Saved_state_init load_state_approach) ->
( lazy_saved_state_init
~do_indexing:false
genv
env
root
load_state_approach,
"lazy_saved_state_init" )
| (Off, Full_init)
| (Decl, Full_init)
| (Parse, Full_init) ->
(eager_full_init genv env lazy_lev, "eager full init")
| (Off, _)
| (Decl, _)
| (Parse, _) ->
(eager_init genv env lazy_lev, "eager_init")
| (_, Write_symbol_info) ->
( lazy_write_symbol_info_init genv env root None,
"lazy_write_symbol_info_init" )
| (_, Write_symbol_info_with_state load_state_approach) ->
( lazy_write_symbol_info_init genv env root (Some load_state_approach),
"lazy_write_symbol_info_init with state" )
in
CgroupProfiler.step_group init_method_name ~log:true init_method |
OCaml Interface | hhvm/hphp/hack/src/server/serverInit.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 load_state_approach =
| Precomputed of ServerArgs.saved_state_target_info
(* Load a saved state using Ocaml implementation of saved state loader. *)
| Load_state_natively
type init_approach =
| Full_init
| Parse_only_init
| Saved_state_init of load_state_approach
| Write_symbol_info
| Write_symbol_info_with_state of load_state_approach
(* Saves the state that is used by init below and returns the number of
edges added to the saved state dependency table. *)
val save_state :
ServerEnv.genv ->
ServerEnv.env ->
string ->
SaveStateServiceTypes.save_state_result option
type init_result =
(* Loaded a saved saved state of this distance. Note: for older load scripts
* distance is unknown, thus None. *)
| Load_state_succeeded of ServerEnv.saved_state_delta option
(* Loading error *)
| Load_state_failed of string * Telemetry.t
(* This option means we didn't even try to load a saved state *)
| Load_state_declined of string
(** Parse, name, typecheck the next set of files,
refresh the environment and update the many shared heaps *)
val init :
init_approach:init_approach ->
ServerEnv.genv ->
ServerEnv.env ->
ServerEnv.env * (* If the script failed, the error message *) init_result |
OCaml | hhvm/hphp/hack/src/server/serverInitCommon.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module Hack_bucket = Bucket
open Hh_prelude
module Bucket = Hack_bucket
open ServerEnv
let directory_walk
?hhi_filter ~(telemetry_label : string) (genv : ServerEnv.genv) :
Relative_path.t list Bucket.next * float =
ServerProgress.write "indexing";
let t = Unix.gettimeofday () in
let get_next =
ServerUtils.make_next
?hhi_filter
~indexer:(genv.indexer FindUtils.file_filter)
~extra_roots:(ServerConfig.extra_paths genv.config)
in
HackEventLogger.indexing_end ~desc:telemetry_label t;
let t = Hh_logger.log_duration ("indexing " ^ telemetry_label) t in
(get_next, t)
let parse_files_and_update_forward_naming_table
(genv : ServerEnv.genv)
(env : ServerEnv.env)
~(get_next : Relative_path.t list Bucket.next)
?(count : int option)
(t : float)
~(trace : bool)
~(cache_decls : bool)
~(telemetry_label : string)
~(cgroup_steps : CgroupProfiler.step_group)
~(worker_call : MultiWorker.call_wrapper) : ServerEnv.env * float =
CgroupProfiler.step_start_end cgroup_steps telemetry_label
@@ fun _cgroup_step ->
begin
match count with
| None -> ServerProgress.write "parsing"
| Some c -> ServerProgress.write "parsing %d files" c
end;
let ctx = Provider_utils.ctx_from_server_env env in
let defs_per_file =
Direct_decl_service.go
ctx
~worker_call
genv.workers
~ide_files:Relative_path.Set.empty
~get_next
~trace
~cache_decls
in
let naming_table = Naming_table.update_many env.naming_table defs_per_file in
let hs = SharedMem.SMTelemetry.heap_size () in
Stats.(stats.init_parsing_heap_size <- hs);
(* The true count of how many files we parsed is wrapped up in the get_next closure.
But our caller provides us 'count' option in cases where it knows the number in
advance, e.g. during init. We'll log that for now. In future it'd be nice to
log the actual number parsed. *)
HackEventLogger.parsing_end_for_init
t
hs
~parsed_count:count
~desc:telemetry_label;
let env = { env with naming_table } in
(env, Hh_logger.log_duration ("Parsing " ^ telemetry_label) t)
let update_reverse_naming_table_from_env_and_get_duplicate_name_errors
(env : ServerEnv.env)
(t : float)
~(telemetry_label : string)
~(cgroup_steps : CgroupProfiler.step_group) : ServerEnv.env * float =
CgroupProfiler.step_start_end cgroup_steps telemetry_label
@@ fun _cgroup_step ->
ServerProgress.write "resolving symbol references";
let ctx = Provider_utils.ctx_from_server_env env in
let count = ref 0 in
let env =
Naming_table.fold
env.naming_table
~f:(fun k v env ->
count := !count + 1;
let failed_naming =
Naming_global.ndecl_file_and_get_conflict_files ctx k v
in
{
env with
failed_naming =
Relative_path.Set.union env.failed_naming failed_naming;
})
~init:env
in
HackEventLogger.global_naming_end
~count:!count
~desc:telemetry_label
~heap_size:(SharedMem.SMTelemetry.heap_size ())
~start_t:t;
(env, Hh_logger.log_duration ("Naming " ^ telemetry_label) t)
let validate_no_errors (errors : Errors.t) : unit =
let witness_opt =
Errors.fold_errors errors ~init:None ~f:(fun path error _acc ->
Some (path, error))
in
match witness_opt with
| None -> ()
| Some (path, error) ->
let error = User_error.to_absolute error |> Errors.to_string in
Hh_logger.log "Unexpected error during init: %s" error;
HackEventLogger.invariant_violation_bug
"unexpected error during init"
~path
~data:error;
()
let log_type_check_end
env
genv
~start_t
~total_rechecked_count
~desc
~init_telemetry
~typecheck_telemetry : unit =
let hash_telemetry = ServerUtils.log_and_get_sharedmem_load_telemetry () in
let telemetry =
Telemetry.create ()
|> Telemetry.object_
~key:"init"
~value:(ServerEnv.Init_telemetry.get init_telemetry)
|> Telemetry.object_ ~key:"typecheck" ~value:typecheck_telemetry
|> Telemetry.object_ ~key:"hash" ~value:hash_telemetry
|> Telemetry.object_ ~key:"errors" ~value:(Errors.as_telemetry env.errorl)
|> Telemetry.object_
~key:"repo_states"
~value:(Watchman.RepoStates.get_as_telemetry ())
in
HackEventLogger.type_check_end
(Some telemetry)
~heap_size:(SharedMem.SMTelemetry.heap_size ())
~started_count:total_rechecked_count
~total_rechecked_count
~desc
~experiments:genv.local_config.ServerLocalConfig.experiments
~start_t
let defer_or_do_type_check
(genv : ServerEnv.genv)
(env : ServerEnv.env)
(files_to_check : Relative_path.t list)
(init_telemetry : Init_telemetry.t)
(t : float)
~(telemetry_label : string)
~(cgroup_steps : CgroupProfiler.step_group) : ServerEnv.env * float =
(* No type checking in AI mode *)
if Option.is_some (ServerArgs.ai_mode genv.options) then
(env, t)
else if
ServerArgs.check_mode genv.options
|| Option.is_some (ServerArgs.save_filename genv.options)
then (
(* Prechecked files are not supported in check/saving-state modes, we
* should always recheck everything necessary up-front. *)
assert (
match env.prechecked_files with
| Prechecked_files_disabled -> true
| _ -> false);
(* Streaming errors aren't supported for these niche cases: for simplicity, the only
code that sets up and tears down streaming errors is in [ServerTypeCheck.type_check].
Our current code calls into typing_check_service.ml without having done that set up,
and so we will override whatever was set before and disable it now. *)
Hh_logger.log "Streaming errors disabled for eager init";
ServerProgress.enable_error_production false;
let count = List.length files_to_check in
let logstring =
Printf.sprintf "Filter %d files [%s]" count telemetry_label
in
Hh_logger.log "Begin %s" logstring;
let files_to_check =
if
not
genv.ServerEnv.local_config
.ServerLocalConfig.enable_type_check_filter_files
then
files_to_check
else
let files_to_check_set = Relative_path.Set.of_list files_to_check in
let filtered_check =
ServerCheckUtils.user_filter_type_check_files
~to_recheck:files_to_check_set
~reparsed:Relative_path.Set.empty
~is_ide_file:(fun _ -> false)
in
Relative_path.Set.elements filtered_check
in
let (_new_t : float) = Hh_logger.log_duration logstring t in
let total_rechecked_count = List.length files_to_check in
let logstring =
Printf.sprintf "type-check %d files" total_rechecked_count
in
Hh_logger.log "Begin %s" logstring;
let {
Typing_check_service.errors = errorl;
telemetry = typecheck_telemetry;
_;
} =
let memory_cap =
genv.local_config.ServerLocalConfig.max_typechecker_worker_memory_mb
in
let longlived_workers =
genv.local_config.ServerLocalConfig.longlived_workers
in
let use_hh_distc_instead_of_hulk =
genv.local_config.ServerLocalConfig.use_hh_distc_instead_of_hulk
in
let hh_distc_fanout_threshold =
Some genv.local_config.ServerLocalConfig.hh_distc_fanout_threshold
in
let root = Some (ServerArgs.root genv.ServerEnv.options) in
let ctx = Provider_utils.ctx_from_server_env env in
CgroupProfiler.step_start_end cgroup_steps telemetry_label @@ fun () ->
Typing_check_service.go
ctx
genv.workers
(Telemetry.create ())
files_to_check
~root
~memory_cap
~longlived_workers
~use_hh_distc_instead_of_hulk
~hh_distc_fanout_threshold
~check_info:
(ServerCheckUtils.get_check_info
~check_reason:(ServerEnv.Init_telemetry.get_reason init_telemetry)
~log_errors:true
genv
env)
in
let env = { env with errorl = Errors.merge errorl env.errorl } in
log_type_check_end
env
genv
~start_t:t
~total_rechecked_count
~desc:telemetry_label
~init_telemetry
~typecheck_telemetry;
(env, Hh_logger.log_duration logstring t)
) else
let needs_recheck =
List.fold files_to_check ~init:Relative_path.Set.empty ~f:(fun acc fn ->
Relative_path.Set.add acc fn)
in
let env =
{
env with
needs_recheck = Relative_path.Set.union env.needs_recheck needs_recheck;
(* eagerly start rechecking after init *)
full_check_status = Full_check_started;
init_env =
{ env.init_env with why_needed_full_check = Some init_telemetry };
}
in
(env, t) |
OCaml Interface | hhvm/hphp/hack/src/server/serverInitCommon.mli | (*
* 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.
*
*)
(** Walks the directory tree to find all .php files that match [Find_utils.file_filter].
It actually returns a [Bucket.next], i.e. a lazy list, rather than doing it eagerly. *)
val directory_walk :
?hhi_filter:(string -> bool) ->
telemetry_label:string ->
ServerEnv.genv ->
Relative_path.t list Bucket.next * float
(** This parses all the lazy list of files provided by [get_next] to get [FileInfo.t]
information for all of them, then updates the forward naming table [env.naming_table]. *)
val parse_files_and_update_forward_naming_table :
ServerEnv.genv ->
ServerEnv.env ->
get_next:Relative_path.t list Bucket.next ->
?count:int ->
float ->
trace:bool ->
cache_decls:bool ->
telemetry_label:string ->
cgroup_steps:CgroupProfiler.step_group ->
worker_call:MultiWorker.call_wrapper ->
ServerEnv.env * float
(** This walks [env.naming_table], the forward-naming-table, and uses it to
update the (global mutable) reverse naming table. It also adds
duplicate-name-errors into [env.errors], and also puts them also
into [env.failed_naming] since that's how we currently accomplish
incremental updates that fix duplicate names. *)
val update_reverse_naming_table_from_env_and_get_duplicate_name_errors :
ServerEnv.env ->
float ->
telemetry_label:string ->
cgroup_steps:CgroupProfiler.step_group ->
ServerEnv.env * float
(** Just a quick validation that there are no errors *)
val validate_no_errors : Errors.t -> unit
(** This function has two different behaviors:
- For the normal case, it adds the provided list of files into [env.needs_recheck].
It also sets [env.full_check_status=Full_check_started] which is important for
correctness of streaming errors (it guarantees that ServerTypeCheck will do
an iteration, even if [env.needs_recheck] is empty).
It also sets [env.init_env] which is important for telemetry, so the first
ServerTypeCheck loop will record information about the Init_telemetry (i.e.
saved-state-loading) which determined the typecheck.
- For Zoncolan, and "hh_server check" (i.e. full init that doesn't support incremental updates),
and "hh_server --save-state" (i.e. full-init which saves a state and then quits),
it typechecks all the files provided in the list. *)
val defer_or_do_type_check :
ServerEnv.genv ->
ServerEnv.env ->
Relative_path.t list ->
ServerEnv.Init_telemetry.t ->
float ->
telemetry_label:string ->
cgroup_steps:CgroupProfiler.step_group ->
ServerEnv.env * float |
OCaml Interface | hhvm/hphp/hack/src/server/serverInitMessages.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.
*
*)
(** Message that accompanies a saved-state load failure, when full init
fallback is disabled *)
val messageSavedStateFailedFullInitDisabled : string |
OCaml | hhvm/hphp/hack/src/server/serverInitMessages.stubs.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
let messageSavedStateFailedFullInitDisabled =
"Please retry. If the problem persists, check your saved state set up "
^ "or open an issue on GitHub." |
OCaml | hhvm/hphp/hack/src/server/serverInitTypes.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.
*
*)
type load_state_error =
(* an error reported when downloading saved-state through [Saved_state_loader] *)
| Load_state_saved_state_loader_failure of Saved_state_loader.LoadError.t
(* an error fetching list of dirty files from hg *)
| Load_state_dirty_files_failure of Future.error
(* any other unhandled exception from lazy_init *)
| Load_state_unhandled_exception of Exception.t
type load_state_verbose_error = {
message: string;
auto_retry: bool;
telemetry: Telemetry.t;
}
type load_state_approach =
| Precomputed of ServerArgs.saved_state_target_info
| Load_state_natively
[@@deriving show]
type init_approach =
| Full_init
| Parse_only_init
| Saved_state_init of load_state_approach
| Write_symbol_info
| Write_symbol_info_with_state of load_state_approach
[@@deriving show]
(** Docs are in .mli *)
type init_result =
| Load_state_succeeded of ServerEnv.saved_state_delta option
| Load_state_failed of string * Telemetry.t
| Load_state_declined of string
(** returns human-readable string, an indication of whether auto-retry is sensible, and stack *)
let load_state_error_to_verbose_string (err : load_state_error) :
load_state_verbose_error =
match err with
| Load_state_saved_state_loader_failure err ->
{
message =
Printf.sprintf
("Could not load saved-state from DevX infrastructure. "
^^ "The underlying error message was: %s\n\n"
^^ "The accompanying debug details are: %s")
(Saved_state_loader.LoadError.long_user_message_of_error err)
(Saved_state_loader.LoadError.debug_details_of_error err);
auto_retry = false;
telemetry =
Telemetry.create ()
|> Telemetry.string_
~key:"kind"
~value:"Load_state_saved_state_loader_failure"
|> Telemetry.string_
~key:"category"
~value:(Saved_state_loader.LoadError.category_of_error err)
|> Telemetry.string_
~key:"debug_details"
~value:(Saved_state_loader.LoadError.debug_details_of_error err)
|> Telemetry.string_opt
~key:"saved_state_manifold_api_key"
~value:
(Saved_state_loader.LoadError
.saved_state_manifold_api_key_of_error
err);
}
| Load_state_dirty_files_failure error ->
let Future.{ message; stack = Utils.Callstack stack; environment } =
Future.error_to_string_verbose error
in
{
message = Printf.sprintf "Problem getting dirty files from hg: %s" message;
auto_retry = false;
telemetry =
Telemetry.create ()
|> Telemetry.string_ ~key:"kind" ~value:"Load_state_dirty_files_failure"
|> Telemetry.string_ ~key:"message" ~value:message
|> Telemetry.string_ ~key:"stack" ~value:stack
|> Telemetry.string_opt ~key:"environment" ~value:environment;
}
| Load_state_unhandled_exception e ->
{
message =
Printf.sprintf
"Unexpected bug loading saved state - %s"
(Exception.get_ctor_string e);
auto_retry = false;
telemetry =
Telemetry.create ()
|> Telemetry.string_ ~key:"kind" ~value:"Load_state_unhandled_exception"
|> Telemetry.exception_ ~e;
}
type files_changed_while_parsing = Relative_path.Set.t
type loaded_info = {
naming_table_fn: string;
deptable_fn: string;
naming_table_fallback_fn: string option;
corresponding_rev: Hg.rev;
mergebase_rev: Hg.global_rev option;
mergebase: Hg.hg_rev option;
(* Files changed between the loaded naming table saved state and current revision. *)
dirty_naming_files: Relative_path.Set.t; [@printer Relative_path.Set.pp_large]
(* Files changed between saved state revision and current public merge base *)
dirty_master_files: Relative_path.Set.t; [@printer Relative_path.Set.pp_large]
(* Files changed between public merge base and current revision *)
dirty_local_files: Relative_path.Set.t; [@printer Relative_path.Set.pp_large]
old_naming_table: Naming_table.t; [@opaque]
old_errors: SaveStateServiceTypes.saved_state_errors; [@opaque]
saved_state_delta: ServerEnv.saved_state_delta option;
(* The manifold path for naming table saved state, to be used by remote type checker
for downloading the naming table in the case of a saved-state init *)
naming_table_manifold_path: string option;
}
[@@deriving show]
(* Laziness *)
type lazy_level =
| Off
| Decl
| Parse
| Init
[@@deriving show] |
OCaml | hhvm/hphp/hack/src/server/serverInvalidateUnits.stubs.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
let go _ _ _ _ _ = () |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.