language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
OCaml | hhvm/hphp/hack/src/typing/tast_check/tany_logger/tany_logger_types.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.
*
*)
(** A masking scheme indicating logging mode.
For example, both the log levels 1 (0x1) and 3 (0x11) enable logging to a
file. *)
type log_mask =
| File [@value 1]
| Scuba [@value 2]
[@@deriving enum]
type expression_info = {
declaration_usage: bool;
(** Notes that a bad type appears in the expression type as a direct
consequence of a declaration having a bad type in it.
This is less important than other bad types because the real culprit
is the signature with the bad type in it. *)
producer: string option;
(** Marks a point where a bad type is introduced, e.g., as a result of a
function call. When statically available, it indicates what produced
the bad type, e.g., a function name. *)
}
type parameter_info = {
is_inout: bool;
is_variadic: bool;
}
type position =
| Return
| Parameter of parameter_info
type declaration_info = {
position: position; (** Where in a declaration a bad type appears? *)
}
(** A context is either a function name or a method name qualified by the
enclosing class. *)
type context_id =
| Function of string
| Method of string * string
type common_info = {
is_generated: bool; (** Is it in a generated file (based on path)? *)
is_test: bool; (** Is it in a test file (based on path)? *)
pos: Relative_path.t Pos.pos; (** Position of a bad type *)
context_id: context_id;
(** Identifier for where bad types appear either of the form
`function_name` or `class_name::method_name` *)
}
type context =
| Expression of expression_info
| Declaration of declaration_info
type info = {
context: context;
(** Information that is depended on being a decl or an expression *)
common_info: common_info;
(** Information common to different contexts bad types appear in. *)
} |
hhvm/hphp/hack/src/typing/write_symbol_info/dune | (library
(name write_symbol_info)
(wrapped false)
(modules
symbol_sym_def
symbol_gencode
symbol_indexable
symbol_file_info
symbol_add_fact
symbol_build_json
symbol_fact_id
symbol_xrefs
symbol_json_util
symbol_sym_hash
symbol_index_batch
symbol_index_decls
symbol_index_xrefs
symbol_entrypoint
symbol_predicate)
(libraries
ast_provider
naming_table
tast_provider
typing
typing_ast
parser
procs_procs
server_services
utils_core
base64
uutf)
(preprocess
(pps ppx_deriving.std))) |
|
OCaml | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_add_fact.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 Aast
open Hh_prelude
open Hh_json
module Util = Symbol_json_util
module Build_json = Symbol_build_json
module Predicate = Symbol_predicate
module Fact_id = Symbol_fact_id
module Fact_acc = Symbol_predicate.Fact_acc
module XRefs = Symbol_xrefs
let namespace_decl name progress =
let json_fields =
[("name", Build_json.build_namespaceqname_json_nested name)]
in
Fact_acc.add_fact
Predicate.(Hack NamespaceDeclaration)
(JSON_Object json_fields)
progress
(* create a namespace fact from a namespace attribute in node. Name can be empty
in that case we simply ignore it *)
let namespace_decl_opt name progress =
match name.Namespace_env.ns_name with
| None -> progress (* global name space *)
| Some "" -> progress
| Some name -> namespace_decl name progress |> snd
let container_decl decl_pred name progress =
let json = JSON_Object [("name", Build_json.build_qname_json_nested name)] in
Fact_acc.add_fact decl_pred json progress
(* Helper function for adding facts for container parents, given
a context, a list of declarations, a predicate type, and progress state *)
let parent_decls ctx decls pred prog =
List.fold decls ~init:([], prog) ~f:(fun (decl_refs, prog) decl ->
let name = Util.strip_tparams (Util.get_type_from_hint ctx decl) in
let (decl_id, prog) = container_decl pred name prog in
let ref = Build_json.build_id_json decl_id in
(ref :: decl_refs, prog))
let module_decl name progress =
let json = JSON_Object [("name", Build_json.build_name_json_nested name)] in
Fact_acc.add_fact Predicate.(Hack ModuleDeclaration) json progress
let module_field module_ internal progress =
match module_ with
| None -> ([], progress)
| Some (_pos, module_name) ->
let (decl_id, progress) = module_decl module_name progress in
( [("module_", Build_json.build_module_membership_nested decl_id ~internal)],
progress )
let member_cluster ~members prog =
let json = JSON_Object [("members", JSON_Array members)] in
Fact_acc.add_fact Predicate.(Hack MemberCluster) json prog
let inherited_members ~container_type ~container_id ~member_clusters prog =
let json =
JSON_Object
[
( "container",
Build_json.build_container_json_ref container_type container_id );
( "inheritedMembers",
JSON_Array (List.map ~f:Build_json.build_id_json member_clusters) );
]
in
Fact_acc.add_fact Predicate.(Hack InheritedMembers) json prog
let container_defn ctx source_text clss decl_id member_decls prog =
let prog = namespace_decl_opt clss.c_namespace prog in
let tparams =
List.map
clss.c_tparams
~f:(Build_json.build_type_param_json ctx source_text)
in
let (mf, prog) = module_field clss.c_module clss.c_internal prog in
let common_fields =
mf
@ [
("declaration", Build_json.build_id_json decl_id);
("members", JSON_Array member_decls);
( "attributes",
Build_json.build_attributes_json_nested
source_text
clss.c_user_attributes );
("typeParams", JSON_Array tparams);
]
in
let (req_extends_hints, req_implements_hints, req_class_hints) =
Aast.partition_map_require_kind ~f:(fun x -> x) clss.c_reqs
in
let (req_extends, prog) =
parent_decls
ctx
(List.map req_extends_hints ~f:fst)
Predicate.(Hack ClassDeclaration)
prog
in
let (req_implements, prog) =
parent_decls
ctx
(List.map req_implements_hints ~f:fst)
Predicate.(Hack InterfaceDeclaration)
prog
in
let (req_class, prog) =
parent_decls
ctx
(List.map req_class_hints ~f:fst)
Predicate.(Hack ClassDeclaration)
prog
in
let (defn_pred, json_fields, prog) =
match Predicate.get_parent_kind clss.c_kind with
| Predicate.InterfaceContainer ->
let (extends, prog) =
parent_decls
ctx
clss.c_extends
Predicate.(Hack InterfaceDeclaration)
prog
in
let req_fields =
common_fields
@ [
("extends_", JSON_Array extends);
("requireExtends", JSON_Array req_extends);
]
in
(Predicate.(Hack InterfaceDefinition), req_fields, prog)
| Predicate.TraitContainer ->
let (impls, prog) =
parent_decls
ctx
clss.c_implements
Predicate.(Hack InterfaceDeclaration)
prog
in
let (uses, prog) =
parent_decls ctx clss.c_uses Predicate.(Hack TraitDeclaration) prog
in
let req_fields =
common_fields
@ [
("implements_", JSON_Array impls);
("uses", JSON_Array uses);
("requireExtends", JSON_Array req_extends);
("requireImplements", JSON_Array req_implements);
("requireClass", JSON_Array req_class);
]
in
(Predicate.(Hack TraitDefinition), req_fields, prog)
| Predicate.ClassContainer ->
let is_abstract = Ast_defs.is_classish_abstract clss.c_kind in
let (class_fields, prog) =
let (impls, prog) =
parent_decls
ctx
clss.c_implements
Predicate.(Hack InterfaceDeclaration)
prog
in
let (uses, prog) =
parent_decls ctx clss.c_uses Predicate.(Hack TraitDeclaration) prog
in
let req_class_fields =
common_fields
@ Hh_json.
[
("isAbstract", JSON_Bool is_abstract);
("isFinal", JSON_Bool clss.c_final);
("implements_", JSON_Array impls);
("uses", JSON_Array uses);
]
in
match clss.c_extends with
| [] -> (req_class_fields, prog)
| [parent] ->
let (decl_id, prog) =
let parent_clss =
Util.strip_tparams (Util.get_type_from_hint ctx parent)
in
container_decl Predicate.(Hack ClassDeclaration) parent_clss prog
in
( ("extends_", Build_json.build_id_json decl_id) :: req_class_fields,
prog )
| _ ->
Hh_logger.log
"WARNING: skipping extends field for class with multiple parents %s"
(snd clss.c_name);
(req_class_fields, prog)
in
(Predicate.(Hack ClassDefinition), class_fields, prog)
in
Fact_acc.add_fact defn_pred (JSON_Object json_fields) prog
let property_decl con_type decl_id name progress =
let json =
JSON_Object
[
("name", Build_json.build_name_json_nested name);
("container", Build_json.build_container_json_ref con_type decl_id);
]
in
Fact_acc.add_fact Predicate.(Hack PropertyDeclaration) json progress
let class_const_decl con_type decl_id name progress =
let json =
JSON_Object
[
("name", Build_json.build_name_json_nested name);
("container", Build_json.build_container_json_ref con_type decl_id);
]
in
Fact_acc.add_fact Predicate.(Hack ClassConstDeclaration) json progress
let type_const_decl con_type decl_id name progress =
let json =
JSON_Object
[
("name", Build_json.build_name_json_nested name);
("container", Build_json.build_container_json_ref con_type decl_id);
]
in
Fact_acc.add_fact Predicate.(Hack TypeConstDeclaration) json progress
let method_decl con_type decl_id name progress =
let json =
JSON_Object
[
("name", Build_json.build_name_json_nested name);
("container", Build_json.build_container_json_ref con_type decl_id);
]
in
Fact_acc.add_fact Predicate.(Hack MethodDeclaration) json progress
let type_info ~ty sym_pos progress =
let json =
JSON_Object
[
("displayType", Build_json.build_type_json_nested ty);
("xrefs", Build_json.build_hint_xrefs_json sym_pos);
]
in
Fact_acc.add_fact Predicate.(Hack TypeInfo) json progress
let aggregate_pos (json_pos_list : (json * Util.pos) list) :
(json * Util.pos list) list =
let jmap =
List.fold json_pos_list ~init:JMap.empty ~f:(fun acc (json, pos) ->
let f = function
| None -> Some [pos]
| Some prev -> Some (pos :: prev)
in
JMap.update json f acc)
in
JMap.to_seq jmap |> Caml.List.of_seq
let build_signature ctx pos_map_opt source_text params ctxs ret progress =
let pos_map =
match pos_map_opt with
| Some pos_map -> pos_map
| None -> failwith "Internal error: pos_map should be set in previous phase"
in
let hint_to_str_opt h progress =
match hint_of_type_hint h with
| None -> (None, None, progress)
| Some hint ->
let legacy_ty = Util.get_type_from_hint ctx hint in
let (ty, sym_pos) = Util.hint_to_string_and_symbols ctx hint in
let decl_json_pos =
List.filter_map sym_pos ~f:(fun (source_pos, pos) ->
match XRefs.PosMap.find_opt source_pos pos_map with
| Some (XRefs.{ target; _ } :: _) -> Some (target, pos)
| _ -> None)
in
let decl_json_aggr_pos = aggregate_pos decl_json_pos in
let (fact_id, progress) = type_info ~ty decl_json_aggr_pos progress in
(Some legacy_ty, Some fact_id, progress)
in
let (params, progress) =
List.fold params ~init:([], progress) ~f:(fun (t_params, progress) p ->
let (p_ty, fact_id, progress) =
hint_to_str_opt p.param_type_hint progress
in
((p, fact_id, p_ty) :: t_params, progress))
in
let params = List.rev params in
let (ret_ty, return_info, progress) = hint_to_str_opt ret progress in
let signature =
Build_json.build_signature_json
ctx
source_text
params
ctxs
~ret_ty
~return_info
in
(signature, progress)
let readonly_assoc key = function
| None -> []
| Some elem -> [(key, Build_json.build_readonly_kind_json elem)]
let method_defn ctx source_text meth decl_id progress =
let m_tparams = Util.remove_generated_tparams meth.m_tparams in
let tparams =
List.map m_tparams ~f:(Build_json.build_type_param_json ctx source_text)
in
let (signature, progress) =
build_signature
ctx
(Fact_acc.get_pos_map progress)
source_text
meth.m_params
meth.m_ctxs
meth.m_ret
progress
in
let readonly_ret = readonly_assoc "readonlyRet" meth.m_readonly_ret in
let is_readonly_this =
if meth.m_readonly_this then
[("isReadonlyThis", JSON_Bool meth.m_readonly_this)]
else
[]
in
let json =
JSON_Object
(List.concat
[
[
("declaration", Build_json.build_id_json decl_id);
("signature", signature);
("visibility", Build_json.build_visibility_json meth.m_visibility);
("isAbstract", JSON_Bool meth.m_abstract);
("isAsync", Build_json.build_is_async_json meth.m_fun_kind);
("isFinal", JSON_Bool meth.m_final);
("isStatic", JSON_Bool meth.m_static);
( "attributes",
Build_json.build_attributes_json_nested
source_text
meth.m_user_attributes );
("typeParams", JSON_Array tparams);
];
readonly_ret;
is_readonly_this;
])
in
Fact_acc.add_fact Predicate.(Hack MethodDefinition) json progress
let method_overrides
meth_name base_cont_name base_cont_type der_cont_name der_cont_type prog =
let json =
JSON_Object
[
( "derived",
Build_json.build_method_decl_nested
meth_name
der_cont_name
der_cont_type );
( "base",
Build_json.build_method_decl_nested
meth_name
base_cont_name
base_cont_type );
]
in
Fact_acc.add_fact Predicate.(Hack MethodOverrides) json prog
let property_defn ctx source_text prop decl_id progress =
let base_fields =
[
("declaration", Build_json.build_id_json decl_id);
("visibility", Build_json.build_visibility_json prop.cv_visibility);
("isFinal", JSON_Bool prop.cv_final);
("isAbstract", JSON_Bool prop.cv_abstract);
("isStatic", JSON_Bool prop.cv_is_static);
( "attributes",
Build_json.build_attributes_json_nested
source_text
prop.cv_user_attributes );
]
in
let json_fields =
match hint_of_type_hint prop.cv_type with
| None -> base_fields
| Some h ->
let ty = Util.get_type_from_hint ctx h in
("type", Build_json.build_type_json_nested ty) :: base_fields
in
Fact_acc.add_fact
Predicate.(Hack PropertyDefinition)
(JSON_Object json_fields)
progress
let class_const_defn ctx source_text const decl_id progress =
let base_fields = [("declaration", Build_json.build_id_json decl_id)] in
let json_fields =
match const.cc_kind with
| CCAbstract None -> base_fields
| CCAbstract (Some expr)
| CCConcrete expr ->
let value = Util.ast_expr_to_json source_text expr in
("value", value) :: base_fields
in
let json_fields =
match const.cc_type with
| None -> json_fields
| Some h ->
let ty = Util.get_type_from_hint ctx h in
("type", Build_json.build_type_json_nested ty) :: json_fields
in
Fact_acc.add_fact
Predicate.(Hack ClassConstDefinition)
(JSON_Object json_fields)
progress
let type_const_defn ctx source_text tc decl_id progress =
let base_fields =
[
("declaration", Build_json.build_id_json decl_id);
("kind", Build_json.build_type_const_kind_json tc.c_tconst_kind);
( "attributes",
Build_json.build_attributes_json_nested
source_text
tc.c_tconst_user_attributes );
]
in
let json_fields =
(* TODO(T88552052) should the default of an abstract type constant be used
* as a value here *)
match tc.c_tconst_kind with
| TCConcrete { c_tc_type = h }
| TCAbstract { c_atc_default = Some h; _ } ->
let ty = Util.get_type_from_hint ctx h in
("type", Build_json.build_type_json_nested ty) :: base_fields
| TCAbstract { c_atc_default = None; _ } -> base_fields
in
Fact_acc.add_fact
Predicate.(Hack TypeConstDefinition)
(JSON_Object json_fields)
progress
let enum_decl name progress =
let json = JSON_Object [("name", Build_json.build_qname_json_nested name)] in
Fact_acc.add_fact Predicate.(Hack EnumDeclaration) json progress
let enum_defn ctx source_text enm enum_id enum_data enumerators progress =
let prog = namespace_decl_opt enm.c_namespace progress in
let (includes, prog) =
parent_decls ctx enum_data.e_includes Predicate.(Hack EnumDeclaration) prog
in
let is_enum_class = Aast.is_enum_class enm in
let (mf, prog) = module_field enm.c_module enm.c_internal prog in
let json_fields =
mf
@ [
("declaration", Build_json.build_id_json enum_id);
( "enumBase",
Build_json.build_type_json_nested
(Util.get_type_from_hint ctx enum_data.e_base) );
("enumerators", JSON_Array enumerators);
( "attributes",
Build_json.build_attributes_json_nested
source_text
enm.c_user_attributes );
("includes", JSON_Array includes);
("isEnumClass", JSON_Bool is_enum_class);
]
in
let json_fields =
match enum_data.e_constraint with
| None -> json_fields
| Some c ->
( "enumConstraint",
Build_json.build_type_json_nested (Util.get_type_from_hint ctx c) )
:: json_fields
in
Fact_acc.add_fact
Predicate.(Hack EnumDefinition)
(JSON_Object json_fields)
prog
let enumerator decl_id const_name progress =
let json =
JSON_Object
[
("name", Build_json.build_name_json_nested const_name);
("enumeration", Build_json.build_id_json decl_id);
]
in
Fact_acc.add_fact Predicate.(Hack Enumerator) json progress
let func_decl name progress =
let json = JSON_Object [("name", Build_json.build_qname_json_nested name)] in
Fact_acc.add_fact Predicate.(Hack FunctionDeclaration) json progress
let func_defn ctx source_text fd decl_id progress =
let elem = fd.fd_fun in
let prog = namespace_decl_opt fd.fd_namespace progress in
let fd_tparams = Util.remove_generated_tparams fd.fd_tparams in
let tparams =
List.map fd_tparams ~f:(Build_json.build_type_param_json ctx source_text)
in
let (mf, prog) = module_field fd.fd_module fd.fd_internal prog in
let (signature, prog) =
build_signature
ctx
(Fact_acc.get_pos_map progress)
source_text
elem.f_params
elem.f_ctxs
elem.f_ret
prog
in
let readonly_ret = readonly_assoc "readonlyRet" elem.f_readonly_ret in
let json_fields =
List.concat
[
mf;
[
("declaration", Build_json.build_id_json decl_id);
("signature", signature);
("isAsync", Build_json.build_is_async_json elem.f_fun_kind);
( "attributes",
Build_json.build_attributes_json_nested
source_text
elem.f_user_attributes );
("typeParams", JSON_Array tparams);
];
readonly_ret;
]
in
Fact_acc.add_fact
Predicate.(Hack FunctionDefinition)
(JSON_Object json_fields)
prog
let module_defn _ctx source_text elem decl_id progress =
let json_fields =
[
("declaration", Build_json.build_id_json decl_id);
( "attributes",
Build_json.build_attributes_json_nested
source_text
elem.md_user_attributes );
]
in
Fact_acc.add_fact
Predicate.(Hack ModuleDefinition)
(JSON_Object json_fields)
progress
let typedef_decl name progress =
let json = JSON_Object [("name", Build_json.build_qname_json_nested name)] in
Fact_acc.add_fact Predicate.(Hack TypedefDeclaration) json progress
let typedef_defn ctx source_text elem decl_id progress =
let prog = namespace_decl_opt elem.t_namespace progress in
let is_transparent =
match elem.t_vis with
| Transparent -> true
| CaseType
| Opaque
| OpaqueModule ->
false
in
let tparams =
List.map
elem.t_tparams
~f:(Build_json.build_type_param_json ctx source_text)
in
let (mf, prog) = module_field elem.t_module elem.t_internal prog in
let json_fields =
mf
@ [
("declaration", Build_json.build_id_json decl_id);
("isTransparent", JSON_Bool is_transparent);
( "attributes",
Build_json.build_attributes_json_nested
source_text
elem.t_user_attributes );
("typeParams", JSON_Array tparams);
]
in
Fact_acc.add_fact
Predicate.(Hack TypedefDefinition)
(JSON_Object json_fields)
prog
let gconst_decl name progress =
let json = JSON_Object [("name", Build_json.build_qname_json_nested name)] in
Fact_acc.add_fact Predicate.(Hack GlobalConstDeclaration) json progress
let gconst_defn ctx source_text elem decl_id progress =
let prog = namespace_decl_opt elem.cst_namespace progress in
let value = Util.ast_expr_to_json source_text elem.cst_value in
let req_fields =
[("declaration", Build_json.build_id_json decl_id); ("value", value)]
in
let json_fields =
match elem.cst_type with
| None -> req_fields
| Some h ->
let ty = Util.get_type_from_hint ctx h in
("type", Build_json.build_type_json_nested ty) :: req_fields
in
let json = JSON_Object json_fields in
Fact_acc.add_fact Predicate.(Hack GlobalConstDefinition) json prog
let decl_loc ~path pos decl_json progress =
let json =
JSON_Object
[
("declaration", decl_json);
("file", Build_json.build_file_json_nested path);
("span", Build_json.build_bytespan_json pos);
]
in
Fact_acc.add_fact Predicate.(Hack DeclarationLocation) json progress
let decl_comment ~path pos decl_json progress =
let json =
JSON_Object
[
("declaration", decl_json);
("file", Build_json.build_file_json_nested path);
("span", Build_json.build_bytespan_json pos);
]
in
Fact_acc.add_fact Predicate.(Hack DeclarationComment) json progress
let decl_span ~path pos decl_json progress =
let json =
JSON_Object
[
("declaration", decl_json);
("file", Build_json.build_file_json_nested path);
("span", Build_json.build_bytespan_json pos);
]
in
Fact_acc.add_fact Predicate.(Hack DeclarationSpan) json progress
let file_lines ~path sourceText progress =
let lineLengths =
Line_break_map.offsets_to_line_lengths
sourceText.Full_fidelity_source_text.offset_map
in
let endsInNewline = Util.ends_in_newline sourceText in
let hasUnicodeOrTabs = Util.has_tabs_or_multibyte_codepoints sourceText in
let json =
Build_json.build_file_lines_json
path
lineLengths
endsInNewline
hasUnicodeOrTabs
in
Fact_acc.add_fact Predicate.(Src FileLines) json progress
let gen_code ~path ~fully_generated ~signature ~source ~command ~class_ progress
=
let json =
Build_json.build_gen_code_json
~path
~fully_generated
~signature
~source
~command
~class_
in
Fact_acc.add_fact Predicate.(Gencode GenCode) json progress
let file_xrefs ~path fact_map progress =
let json =
JSON_Object
[
("file", Build_json.build_file_json_nested path);
("xrefs", Build_json.build_xrefs_json fact_map);
]
in
Fact_acc.add_fact Predicate.(Hack FileXRefs) json progress
let file_decls ~path decls progress =
let json =
JSON_Object
[
("file", Build_json.build_file_json_nested path);
("declarations", JSON_Array decls);
]
in
Fact_acc.add_fact Predicate.(Hack FileDeclarations) json progress
let method_occ receiver_class name progress =
let module SO = SymbolOccurrence in
let json =
List.concat
@@ [
[("name", Build_json.build_name_json_nested name)];
(match receiver_class with
| SO.ClassName className ->
[("className", Build_json.build_name_json_nested className)]
| SO.UnknownClass -> []);
]
in
Fact_acc.add_fact
Predicate.(Hack MethodOccurrence)
(JSON_Object json)
progress
let file_call ~path pos ~callee_infos ~call_args ~dispatch_arg progress =
let callee_xrefs = List.map callee_infos ~f:(fun ti -> ti.XRefs.target) in
let receiver_type =
match List.find_map callee_infos ~f:(fun ti -> ti.XRefs.receiver_type) with
| None -> []
| Some receiver_type -> [("receiver_type", receiver_type)]
in
let dispatch_arg =
match dispatch_arg with
| None -> receiver_type
| Some dispatch_arg -> ("dispatch_arg", dispatch_arg) :: receiver_type
in
(* pick an abitrary target, but resolved if possible. "declaration"
before "occurrence" *)
let callee_xref =
match List.sort ~compare:Hh_json.JsonKey.compare callee_xrefs with
| [] -> []
| hd :: _ -> [("callee_xref", hd)]
in
let json =
JSON_Object
(callee_xref
@ dispatch_arg
@ [
("file", Build_json.build_file_json_nested path);
("callee_span", Build_json.build_bytespan_json pos);
("call_args", JSON_Array call_args);
("callee_xrefs", JSON_Array callee_xrefs);
])
in
Fact_acc.add_fact Predicate.(Hack FileCall) json progress
let global_namespace_alias ~from ~to_ progress =
let json =
JSON_Object
[
("from", Build_json.build_name_json_nested from);
("to", Build_json.build_namespaceqname_json_nested to_);
]
in
Fact_acc.add_fact Predicate.(Hack GlobalNamespaceAlias) json progress
let indexerInputsHash key hashes progress =
let value =
JSON_String
(List.map hashes ~f:(fun x -> Md5.to_binary x |> Base64.encode_string)
|> String.concat)
in
let key = JSON_String key in
Fact_acc.add_fact Predicate.(Hack IndexerInputsHash) key ~value progress |
OCaml Interface | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_add_fact.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.
*
*)
(*
* These functions build up the JSON necessary and then add facts
* to the running result.
*)
open Hh_prelude
module Fact_id = Symbol_fact_id
module Predicate = Symbol_predicate
module Fact_acc = Symbol_predicate.Fact_acc
module XRefs = Symbol_xrefs
module Util = Symbol_json_util
val namespace_decl : string -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val container_decl :
Symbol_predicate.t -> string -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val parent_decls :
Provider_context.t ->
Aast.hint list ->
Symbol_predicate.t ->
Fact_acc.t ->
Hh_json.json list * Fact_acc.t
val member_cluster :
members:Hh_json.json list -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val inherited_members :
container_type:string ->
container_id:Fact_id.t ->
member_clusters:Fact_id.t list ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t
val container_defn :
Provider_context.t ->
Full_fidelity_source_text.t ->
('a, 'b) Aast.class_ ->
Fact_id.t ->
Hh_json.json list ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t
val property_decl :
string -> Fact_id.t -> string -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val class_const_decl :
string -> Fact_id.t -> string -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val type_const_decl :
string -> Fact_id.t -> string -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val method_decl :
string -> Fact_id.t -> string -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val method_defn :
Provider_context.t ->
Full_fidelity_source_text.t ->
('a, 'b) Aast.method_ ->
Fact_id.t ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t
val method_overrides :
string ->
string ->
string ->
string ->
string ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t
val property_defn :
Provider_context.t ->
Full_fidelity_source_text.t ->
('a, 'b) Aast.class_var ->
Fact_id.t ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t
val class_const_defn :
Provider_context.t ->
Full_fidelity_source_text.t ->
('a, 'b) Aast.class_const ->
Fact_id.t ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t
val type_const_defn :
Provider_context.t ->
Full_fidelity_source_text.t ->
('a, 'b) Aast.class_typeconst_def ->
Fact_id.t ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t
val enum_decl : string -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val enum_defn :
Provider_context.t ->
Full_fidelity_source_text.t ->
('a, 'b) Aast.class_ ->
Fact_id.t ->
Aast.enum_ ->
Hh_json.json list ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t
val enumerator : Fact_id.t -> string -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val func_decl : string -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val func_defn :
Provider_context.t ->
Full_fidelity_source_text.t ->
('a, 'b) Aast.fun_def ->
Fact_id.t ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t
val typedef_decl : string -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val typedef_defn :
Provider_context.t ->
Full_fidelity_source_text.t ->
('a, 'b) Aast.typedef ->
Fact_id.t ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t
val module_decl : string -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val module_defn :
Provider_context.t ->
Full_fidelity_source_text.t ->
('a, 'b) Aast.module_def ->
Fact_id.t ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t
val gconst_decl : string -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val gconst_defn :
Provider_context.t ->
Full_fidelity_source_text.t ->
('a, 'b) Aast.gconst ->
Fact_id.t ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t
val decl_loc :
path:string -> Pos.t -> Hh_json.json -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val decl_comment :
path:string -> Pos.t -> Hh_json.json -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val decl_span :
path:string -> Pos.t -> Hh_json.json -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val file_lines :
path:string ->
Full_fidelity_source_text.t ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t
val gen_code :
path:string ->
fully_generated:bool ->
signature:string option ->
source:string option ->
command:string option ->
class_:string option ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t
val file_xrefs :
path:string -> XRefs.fact_map -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val file_decls :
path:string -> Hh_json.json list -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val file_call :
path:string ->
Pos.t ->
callee_infos:XRefs.target_info list ->
call_args:Hh_json.json list ->
dispatch_arg:Hh_json.json option ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t
val global_namespace_alias :
from:string -> to_:string -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val method_occ :
SymbolOccurrence.receiver_class ->
string ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t
val indexerInputsHash :
string -> Md5.t list -> Fact_acc.t -> Fact_id.t * Fact_acc.t
val type_info :
ty:string ->
(Hh_json.json * Util.pos list) list ->
Fact_acc.t ->
Fact_id.t * Fact_acc.t |
OCaml | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_build_json.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 Aast
open Ast_defs
open Hh_json
open Hh_prelude
module Util = Symbol_json_util
module Fact_id = Symbol_fact_id
module XRefs = Symbol_xrefs
let build_id_json fact_id = JSON_Object [("id", Fact_id.to_json_number fact_id)]
let build_argument_lit_json lit =
Hh_json.JSON_Object [("lit", Hh_json.JSON_Object [("key", JSON_String lit)])]
let build_argument_xref_json xref = Hh_json.JSON_Object [("xref", xref)]
let build_file_json_nested filepath =
JSON_Object [("key", JSON_String filepath)]
let build_name_json_nested name =
(* Remove leading slash, if present, so names such as
Exception and \Exception are captured by the same fact *)
let basename = Utils.strip_ns name in
JSON_Object [("key", JSON_String basename)]
let rec build_namespaceqname_json_nested ns =
let fields =
match Util.split_name ns with
| None -> [("name", build_name_json_nested ns)]
| Some (parent_ns, namespace) ->
[
("name", build_name_json_nested namespace);
("parent", build_namespaceqname_json_nested parent_ns);
]
in
JSON_Object [("key", JSON_Object fields)]
let build_qname_json_nested qname =
let fields =
match Util.split_name qname with
(* Global namespace *)
| None -> [("name", build_name_json_nested qname)]
| Some (ns, name) ->
[
("name", build_name_json_nested name);
("namespace_", build_namespaceqname_json_nested ns);
]
in
JSON_Object [("key", JSON_Object fields)]
let build_method_decl_nested meth_name con_name con_type =
let cont_decl = JSON_Object [("name", build_qname_json_nested con_name)] in
let nested_cont_decl =
JSON_Object [(con_type, JSON_Object [("key", cont_decl)])]
in
let meth_decl =
JSON_Object
[
("name", build_name_json_nested meth_name);
("container", nested_cont_decl);
]
in
JSON_Object [("key", meth_decl)]
let build_type_json_nested type_name =
(* Remove namespace slash from type, if present *)
let ty = Utils.strip_ns type_name in
JSON_Object [("key", JSON_String ty)]
let build_signature_json_nested parameters ctxs return_type_name return_info =
let fields =
let params = [("parameters", JSON_Array parameters)] in
let params_return_type =
match return_type_name with
| None -> params
| Some ty -> ("returns", build_type_json_nested ty) :: params
in
let params_return_info =
match return_info with
| None -> params_return_type
| Some fact_id ->
("returnsTypeInfo", build_id_json fact_id) :: params_return_type
in
match ctxs with
| None -> params_return_info
| Some ctxs_name -> ("contexts", JSON_Array ctxs_name) :: params_return_info
in
JSON_Object [("key", JSON_Object fields)]
let build_module_membership_nested decl_id ~internal =
let fields =
[("declaration", build_id_json decl_id); ("internal", JSON_Bool internal)]
in
JSON_Object fields
let build_attributes_json_nested source_text attrs =
let attributes =
List.map attrs ~f:(fun attr ->
let (_, name) = attr.ua_name in
let params =
List.fold_right attr.ua_params ~init:[] ~f:(fun expr acc ->
Util.ast_expr_to_json source_text expr :: acc)
in
let fields =
[
("name", build_name_json_nested name);
("parameters", JSON_Array params);
]
in
JSON_Object [("key", JSON_Object fields)])
in
JSON_Array attributes
let build_bytespan_json pos =
let start = fst (Pos.info_raw pos) in
let length = Pos.length pos in
JSON_Object
[
("start", JSON_Number (string_of_int start));
("length", JSON_Number (string_of_int length));
]
let build_rel_bytespan_json offset len =
JSON_Object
[
("offset", JSON_Number (string_of_int offset));
("length", JSON_Number (string_of_int len));
]
let build_call_arguments_json arguments =
let argument_json span arg_opt =
JSON_Object
(("span", span)
::
(match arg_opt with
| Some json_obj -> [("argument", json_obj)]
| None -> []))
in
let f (json_fields, last_start) (arg_opt, pos) =
let (start, _) = Pos.info_raw pos in
let length = Pos.length pos in
let rel_span = build_rel_bytespan_json (start - last_start) length in
(argument_json rel_span arg_opt :: json_fields, start)
in
List.fold arguments ~init:([], 0) ~f |> fst |> List.rev
let build_constraint_kind_json kind =
let num =
match kind with
| Constraint_as -> 0
| Constraint_eq -> 1
| Constraint_super -> 2
in
JSON_Number (string_of_int num)
let build_constraint_json ctx (kind, hint) =
let type_string = Util.get_type_from_hint ctx hint in
JSON_Object
[
("constraintKind", build_constraint_kind_json kind);
("type", build_type_json_nested type_string);
]
let build_decl_target_json json = JSON_Object [("declaration", json)]
let build_occ_target_json json = JSON_Object [("occurrence", json)]
let build_file_lines_json filepath lineLengths endsInNewline hasUnicodeOrTabs =
let lengths =
List.map lineLengths ~f:(fun len -> JSON_Number (string_of_int len))
in
JSON_Object
[
("file", build_file_json_nested filepath);
("lengths", JSON_Array lengths);
("endsInNewline", JSON_Bool endsInNewline);
("hasUnicodeOrTabs", JSON_Bool hasUnicodeOrTabs);
]
let build_string_json_nested str = JSON_Object [("key", JSON_String str)]
let build_gen_code_json
~path ~fully_generated ~signature ~source ~command ~class_ =
let fields =
[
("file", build_file_json_nested path);
( "variant",
JSON_Number
(if fully_generated then
"0"
else
"1") );
]
in
let l =
[
("signature", signature);
("source", source);
("command", command);
("class_", class_);
]
in
let f (key, value_opt) =
match value_opt with
| None -> None
| Some value -> Some (key, build_string_json_nested value)
in
JSON_Object (fields @ List.filter_map ~f l)
let build_is_async_json fun_kind =
let is_async =
match fun_kind with
| FAsync -> true
| FAsyncGenerator -> true
| _ -> false
in
JSON_Bool is_async
let build_readonly_kind_json _ = JSON_Number "0"
let build_parameter_json
source_text
param_name
param_type_name
def_val
is_inout
is_variadic
readonly_kind_opt
attrs
type_info =
let fields =
[
("name", build_name_json_nested param_name);
("isInout", JSON_Bool is_inout);
("isVariadic", JSON_Bool is_variadic);
("attributes", build_attributes_json_nested source_text attrs);
]
in
let fields =
match param_type_name with
| None -> fields
| Some ty -> ("type", build_type_json_nested ty) :: fields
in
let fields =
match def_val with
| None -> fields
| Some expr ->
("defaultValue", JSON_String (Util.strip_nested_quotes expr)) :: fields
in
let fields =
match type_info with
| None -> fields
| Some fact_id -> ("typeInfo", build_id_json fact_id) :: fields
in
let fields =
match readonly_kind_opt with
| None -> fields
| Some readonly_kind ->
("readonly", build_readonly_kind_json readonly_kind) :: fields
in
JSON_Object fields
let build_signature_json
ctx
source_text
params
(ctxs_hints : Aast.contexts option)
~ret_ty
~return_info =
let ctx_hint_to_json ctx_hint =
JSON_Object [("key", JSON_String (Util.get_context_from_hint ctx ctx_hint))]
in
let f (_pos, ctx_hint) = List.map ~f:ctx_hint_to_json ctx_hint in
let ctxs_hints = Option.map ctxs_hints ~f in
let build_param (p, type_xref, ty) =
let is_inout =
match p.param_callconv with
| Pinout _ -> true
| Pnormal -> false
in
let def_value =
Option.map p.param_expr ~f:(fun expr ->
Util.ast_expr_to_string source_text expr)
in
build_parameter_json
source_text
p.param_name
ty
def_value
is_inout
p.param_is_variadic
p.param_readonly
p.param_user_attributes
type_xref
in
let parameters = List.map params ~f:build_param in
build_signature_json_nested parameters ctxs_hints ret_ty return_info
let build_reify_kind_json kind =
let num =
match kind with
| Erased -> 0
| Reified -> 1
| SoftReified -> 2
in
JSON_Number (string_of_int num)
let build_type_const_kind_json kind =
let num =
match kind with
| TCAbstract _ -> 0
| TCConcrete _ -> 1
in
JSON_Number (string_of_int num)
let build_variance_json variance =
let num =
match variance with
| Contravariant -> 0
| Covariant -> 1
| Invariant -> 2
in
JSON_Number (string_of_int num)
let build_type_param_json ctx source_text tp =
let (_, name) = tp.tp_name in
let constraints = List.map tp.tp_constraints ~f:(build_constraint_json ctx) in
JSON_Object
[
("name", build_name_json_nested name);
("variance", build_variance_json tp.tp_variance);
("reifyKind", build_reify_kind_json tp.tp_reified);
("constraints", JSON_Array constraints);
( "attributes",
build_attributes_json_nested source_text tp.tp_user_attributes );
]
let build_visibility_json (visibility : Aast.visibility) =
let num =
match visibility with
| Private -> 0
| Protected -> 1
| Public -> 2
| Internal -> 3
in
JSON_Number (string_of_int num)
let build_generic_xrefs_json (sym_pos : (Hh_json.json * Util.pos list) Seq.t) =
let xrefs =
Caml.Seq.fold_left
(fun acc (target_json, pos_list) ->
let sorted_pos = Caml.List.sort_uniq Util.compare_pos pos_list in
let (rev_byte_spans, _) =
List.fold
sorted_pos
~init:([], 0)
~f:(fun (spans, last_start) Util.{ start; length } ->
let span = build_rel_bytespan_json (start - last_start) length in
(span :: spans, start))
in
let byte_spans = List.rev rev_byte_spans in
let xref =
JSON_Object
[("ranges", JSON_Array byte_spans); ("target", target_json)]
in
xref :: acc)
[]
sym_pos
in
(* there's no specified order for xref arrays, but it helps to avoid non-determinism
when diffing dbs *)
let sorted_xrefs = List.sort ~compare:Hh_json.JsonKey.compare xrefs in
JSON_Array sorted_xrefs
let build_xrefs_json (fact_map : XRefs.fact_map) =
let f (_fact_id, (json, pos_list)) =
let util_pos_list =
List.map pos_list ~f:(fun pos ->
let start = fst (Pos.info_raw pos) in
let length = Pos.length pos in
Util.{ start; length })
in
(json, util_pos_list)
in
let sym_pos = Fact_id.Map.to_seq fact_map |> Caml.Seq.map f in
build_generic_xrefs_json sym_pos
let build_hint_xrefs_json sym_pos =
Caml.List.to_seq sym_pos |> build_generic_xrefs_json
(* These are functions for building JSON to reference some
existing fact. *)
let build_class_const_decl_json_ref fact_id =
JSON_Object [("classConst", build_id_json fact_id)]
let build_container_json_ref container_type fact_id =
JSON_Object [(container_type, build_id_json fact_id)]
let build_container_decl_json_ref container_type fact_id =
let container_json = build_container_json_ref container_type fact_id in
JSON_Object [("container", container_json)]
let build_enum_decl_json_ref fact_id =
build_container_decl_json_ref "enum_" fact_id
let build_namespace_decl_json_ref fact_id =
JSON_Object [("namespace_", build_id_json fact_id)]
let build_enumerator_decl_json_ref fact_id =
JSON_Object [("enumerator", build_id_json fact_id)]
let build_func_decl_json_ref fact_id =
JSON_Object [("function_", build_id_json fact_id)]
let build_gconst_decl_json_ref fact_id =
JSON_Object [("globalConst", build_id_json fact_id)]
let build_method_decl_json_ref fact_id =
JSON_Object [("method", build_id_json fact_id)]
let build_property_decl_json_ref fact_id =
JSON_Object [("property_", build_id_json fact_id)]
let build_type_const_decl_json_ref fact_id =
JSON_Object [("typeConst", build_id_json fact_id)]
let build_typedef_decl_json_ref fact_id =
JSON_Object [("typedef_", build_id_json fact_id)]
let build_module_decl_json_ref fact_id =
JSON_Object [("module", build_id_json fact_id)]
let build_method_occ_json_ref fact_id =
JSON_Object [("method", build_id_json fact_id)]
let build_class_decl_json_nested receiver =
JSON_Object
[
( "container",
JSON_Object
[
( "class_",
JSON_Object
[
( "key",
JSON_Object [("name", build_qname_json_nested receiver)] );
] );
] );
] |
OCaml Interface | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_build_json.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.
*
*)
(*
* JSON builder functions. These all return JSON objects, which
* may be used to build up larger objects. The functions with suffix
* _nested include the key field because they are used for writing
* nested facts.
*)
module Fact_id = Symbol_fact_id
module Util = Symbol_json_util
val build_id_json : Fact_id.t -> Hh_json.json
val build_file_json_nested : string -> Hh_json.json
val build_name_json_nested : string -> Hh_json.json
val build_namespaceqname_json_nested : string -> Hh_json.json
val build_qname_json_nested : string -> Hh_json.json
val build_method_decl_nested : string -> string -> string -> Hh_json.json
val build_type_json_nested : string -> Hh_json.json
val build_module_membership_nested : Fact_id.t -> internal:bool -> Hh_json.json
val build_attributes_json_nested :
Full_fidelity_source_text.t ->
('a, 'b) Aast.user_attribute list ->
Hh_json.json
val build_bytespan_json : Pos.t -> Hh_json.json
val build_decl_target_json : Hh_json.json -> Hh_json.json
val build_occ_target_json : Hh_json.json -> Hh_json.json
val build_file_lines_json : string -> int list -> bool -> bool -> Hh_json.json
val build_gen_code_json :
path:string ->
fully_generated:bool ->
signature:string option ->
source:string option ->
command:string option ->
class_:string option ->
Hh_json.json
val build_call_arguments_json :
(Hh_json.json option * Pos.t) list -> Hh_json.json list
(* expects a utf-8 string *)
val build_argument_lit_json : string -> Hh_json.json
val build_argument_xref_json : Hh_json.json -> Hh_json.json
val build_is_async_json : Ast_defs.fun_kind -> Hh_json.json
(* params come with the string representation for their type
and an option type_xref fact *)
val build_signature_json :
Provider_context.t ->
Full_fidelity_source_text.t ->
(('a, 'b) Aast.fun_param * Fact_id.t option * string option) list ->
Aast.contexts option ->
ret_ty:string option ->
return_info:Fact_id.t option ->
Hh_json.json
val build_type_const_kind_json : Aast.class_typeconst -> Hh_json.json
val build_type_param_json :
Provider_context.t ->
Full_fidelity_source_text.t ->
('a, 'b) Aast.tparam ->
Hh_json.json
val build_visibility_json : Aast.visibility -> Hh_json.json
val build_readonly_kind_json : Ast_defs.readonly_kind -> Hh_json.json
val build_xrefs_json : (Hh_json.json * Pos.t list) Fact_id.Map.t -> Hh_json.json
val build_hint_xrefs_json : (Hh_json.json * Util.pos list) list -> Hh_json.json
val build_class_const_decl_json_ref : Fact_id.t -> Hh_json.json
val build_container_json_ref : string -> Fact_id.t -> Hh_json.json
val build_container_decl_json_ref : string -> Fact_id.t -> Hh_json.json
val build_enum_decl_json_ref : Fact_id.t -> Hh_json.json
val build_namespace_decl_json_ref : Fact_id.t -> Hh_json.json
val build_enumerator_decl_json_ref : Fact_id.t -> Hh_json.json
val build_func_decl_json_ref : Fact_id.t -> Hh_json.json
val build_gconst_decl_json_ref : Fact_id.t -> Hh_json.json
val build_method_decl_json_ref : Fact_id.t -> Hh_json.json
val build_property_decl_json_ref : Fact_id.t -> Hh_json.json
val build_type_const_decl_json_ref : Fact_id.t -> Hh_json.json
val build_typedef_decl_json_ref : Fact_id.t -> Hh_json.json
val build_module_decl_json_ref : Fact_id.t -> Hh_json.json
val build_method_occ_json_ref : Fact_id.t -> Hh_json.json
val build_class_decl_json_nested : string -> Hh_json.json |
OCaml | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_entrypoint.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 Hh_json
module File_info = Symbol_file_info
module Add_fact = Symbol_add_fact
module Fact_acc = Symbol_predicate.Fact_acc
module Indexable = Symbol_indexable
module Sym_hash = Symbol_sym_hash
module JobReturn = struct
type t = {
elapsed: float;
hashes: Md5.Set.t;
reindexed: SSet.t;
referenced: SSet.t; (* set of files referenced by the indexed files *)
}
let neutral =
{
elapsed = 0.0;
hashes = Md5.Set.empty;
reindexed = SSet.empty;
referenced = SSet.empty;
}
let merge t1 t2 =
{
elapsed = t1.elapsed +. t2.elapsed;
hashes = Md5.Set.union t1.hashes t2.hashes;
reindexed = SSet.union t1.reindexed t2.reindexed;
referenced = SSet.union t1.referenced t2.referenced;
}
end
let log_elapsed s elapsed =
let { Unix.tm_min; tm_sec; _ } = Unix.gmtime elapsed in
Hh_logger.log "%s %dm%ds" s tm_min tm_sec
let write_referenced referenced output_file =
let open Out_channel in
let oc = create output_file in
SSet.iter
(fun str ->
output_string oc str;
newline oc)
referenced;
close oc
let write_file out_dir num_tasts json_chunks =
let (_out_file, channel) =
Caml.Filename.open_temp_file
~temp_dir:out_dir
"glean_symbol_info_chunk_"
".json"
in
let json_string = json_to_string (JSON_Array json_chunks) in
let json_length = String.length json_string in
Out_channel.output_string channel json_string;
Out_channel.close channel;
Hh_logger.log
"Wrote %s of JSON facts on %i files"
(Byte_units.to_string_hum (Byte_units.of_bytes_int json_length))
num_tasts
(* these facts aren't generated by the workers, but once for the whole
indexing run. There are
- symbol hash facts for incrementality (empty if gen_sym_hash isn't set)
- the namespace aliases defined in .hhconfig *)
let gen_global_facts ns ~ownership ~shard_name all_hashes =
let progress = Fact_acc.init ~ownership in
let list_hashes = Md5.Set.to_list all_hashes in
if ownership then Fact_acc.set_ownership_unit progress (Some ".hhconfig");
List.fold ns ~init:progress ~f:(fun progress (from, to_) ->
Add_fact.global_namespace_alias progress ~from ~to_ |> snd)
|> Add_fact.indexerInputsHash shard_name list_hashes
|> snd
|> Fact_acc.to_json
let write_json
(ctx : Provider_context.t)
(ownership : bool)
(out_dir : string)
(files_info : File_info.t list)
(start_time : float) : JobReturn.t =
(* Large file may lead to large json files which timeout when sent
to the server. Not an issue currently, but if it is, we can index
xrefs/decls separately, or split in batches according to files size *)
(List.iter files_info ~f:(fun File_info.{ tast; path; _ } ->
if List.length tast > 2000 then Hh_logger.log "Large file: %s" path);
try
let json_chunks =
Symbol_index_batch.build_json ctx files_info ~ownership
in
write_file out_dir (List.length files_info) json_chunks
with
| WorkerCancel.Worker_should_exit as exn ->
(* Cancellation requests must be re-raised *)
let e = Exception.wrap exn in
Exception.reraise e
| e ->
Printf.eprintf "WARNING: symbol write failure: \n%s\n" (Exn.to_string e));
let elapsed = Unix.gettimeofday () -. start_time in
log_elapsed "Processed batch in" elapsed;
let hashes =
List.filter_map files_info ~f:(fun file_info ->
file_info.File_info.sym_hash)
|> Md5.Set.of_list
in
JobReturn.{ elapsed; hashes; reindexed = SSet.empty; referenced = SSet.empty }
let references_from_files_info files_info =
List.map files_info ~f:File_info.referenced
|> List.reduce ~f:SSet.union
|> Option.value ~default:SSet.empty
let recheck_job
(ctx : Provider_context.t)
(out_dir : string)
(root_path : string)
(hhi_path : string)
~(gen_sym_hash : bool)
~(incremental : Sym_hash.t option)
(ownership : bool)
~(gen_references : bool)
(_ : JobReturn.t)
(progress : Indexable.t list) : JobReturn.t =
let start_time = Unix.gettimeofday () in
let gen_sym_hash = gen_sym_hash || Option.is_some incremental in
let files_info =
List.map
progress
~f:
(File_info.create
ctx
~root_path
~hhi_path
~gen_sym_hash
~sym_path:gen_references)
in
let reindex f =
match (f.File_info.fanout, incremental, f.File_info.sym_hash) with
| (true, Some table, Some hash) when Sym_hash.mem table hash -> false
| _ -> true
in
let to_reindex = List.filter ~f:reindex files_info in
let res = write_json ctx ownership out_dir to_reindex start_time in
let fanout_reindexed =
let f File_info.{ path; fanout; _ } =
if fanout then
Some path
else
None
in
List.filter_map to_reindex ~f |> SSet.of_list
in
let referenced =
if gen_references then
references_from_files_info files_info
else
SSet.empty
in
JobReturn.{ res with reindexed = fanout_reindexed; referenced }
let sym_hashes ctx ~files =
let f file =
let fi =
File_info.create
ctx
~root_path:"www"
~hhi_path:"hhi"
~gen_sym_hash:true
~sym_path:false
(Indexable.from_file file)
in
let sym_hash =
match fi.File_info.sym_hash with
| None ->
failwith "Internal error" (* can't happen since gen_sym_hash = true *)
| Some sh -> sh
in
(Relative_path.to_absolute file, sym_hash)
in
List.map files ~f
let index_files ctx ~out_dir ~files =
let idx = List.map files ~f:Indexable.from_file in
recheck_job
ctx
out_dir
"www"
"hhi"
~gen_sym_hash:false
~incremental:None
~gen_references:false
false
JobReturn.neutral
idx
|> ignore
(* TODO create a type for all these options *)
let go
(workers : MultiWorker.worker list option)
(ctx : Provider_context.t)
~(referenced_file : string option)
~(namespace_map : (string * string) list)
~(gen_sym_hash : bool)
~(ownership : bool)
~(out_dir : string)
~(root_path : string)
~(hhi_path : string)
~(incremental : Sym_hash.t option)
~(files : Indexable.t list) : unit =
let num_workers =
match workers with
| Some w -> List.length w
| None -> 1
in
let start_time = Unix.gettimeofday () in
let gen_references = Option.is_some referenced_file in
let jobs =
MultiWorker.call
workers
~job:
(recheck_job
ctx
out_dir
root_path
hhi_path
~gen_sym_hash
~incremental
~gen_references
ownership)
~merge:JobReturn.merge
~next:(Bucket.make ~num_workers ~max_size:115 files)
~neutral:JobReturn.neutral
in
(* just a uid *)
let shard_name =
Md5.digest_string (Float.to_string start_time) |> Md5.to_hex
in
let global_facts =
gen_global_facts namespace_map ~ownership ~shard_name jobs.JobReturn.hashes
in
write_file out_dir 1 global_facts;
SSet.iter (Hh_logger.log "Reindexed: %s") jobs.JobReturn.reindexed;
Option.iter referenced_file ~f:(write_referenced jobs.JobReturn.referenced);
let cumulated_elapsed = jobs.JobReturn.elapsed in
log_elapsed "Processed all batches (cumulated time) in " cumulated_elapsed;
let elapsed = Unix.gettimeofday () -. start_time in
log_elapsed "Processed all batches in " elapsed |
OCaml Interface | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_entrypoint.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.
*
*)
(* entry point to the hack indexer *)
open Hh_prelude
module Indexable = Symbol_indexable
module Sym_hash = Symbol_sym_hash
val index_files :
Provider_context.t -> out_dir:string -> files:Relative_path.t list -> unit
val sym_hashes :
Provider_context.t -> files:Relative_path.t list -> (string * Md5.t) list
val go :
MultiWorker.worker list option ->
Provider_context.t ->
referenced_file:string option ->
namespace_map:(string * string) list ->
gen_sym_hash:bool ->
ownership:bool ->
out_dir:string ->
root_path:string ->
hhi_path:string ->
incremental:Sym_hash.t option ->
files:Indexable.t list ->
unit |
OCaml | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_fact_id.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type t = int
let next =
let x = ref 1 in
fun () ->
let r = !x in
x := !x + 1;
r
let to_json_number i = Hh_json.JSON_Number (string_of_int i)
module Map = Map.Make (struct
type t = int
let compare = Int.compare
end) |
OCaml Interface | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_fact_id.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 t = private int
(* return consecutive fact ids, starting from 1 *)
val next : unit -> t
val to_json_number : t -> Hh_json.json
module Map : Map.S with type key = t |
OCaml | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_file_info.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 Indexable = Symbol_indexable
module Sym_def = Symbol_sym_def
module Class = Typing_classes_heap.Api
type symbol = {
occ: Relative_path.t SymbolOccurrence.t;
def: Sym_def.t option;
}
type container = {
name: string;
kind: Ast_defs.classish_kind;
}
type member = { name: string }
type member_cluster = {
container: container;
methods: member list;
properties: member list;
class_constants: member list;
type_constants: member list;
}
type t = {
path: string;
cst: Full_fidelity_positioned_syntax.t;
tast: (Tast.def * member_cluster list) list;
source_text: Full_fidelity_source_text.t;
symbols: symbol list;
sym_hash: Md5.t option;
fanout: bool;
}
let concat_hash str hash = Md5.digest_string (Md5.to_binary hash ^ str)
(* TODO we hash the string representation of the symbol types. We
should move a more robust scheme and make sure this is enough to
identify files which need reindexing *)
let compute_sym_hash symbols init =
let f cur { occ; def } =
let full_name =
match def with
| None -> ""
| Some def ->
Sym_def.(def.full_name ^ SymbolDefinition.string_of_kind def.kind)
in
let str = SymbolOccurrence.(occ.name ^ show_kind occ.type_ ^ full_name) in
concat_hash str cur
in
List.fold ~init ~f symbols
let compute_member_clusters_hash hash member_clusters =
let hash_container hash (c : container) =
concat_hash c.name @@ concat_hash (Ast_defs.show_classish_kind c.kind) hash
in
let hash_member_cluster hash (mc : member_cluster) =
let members =
mc.methods @ mc.properties @ mc.class_constants @ mc.type_constants
in
let init = hash_container hash mc.container in
List.fold members ~init ~f:(fun hash m -> concat_hash m.name hash)
in
List.fold member_clusters ~init:hash ~f:hash_member_cluster
(* We fetch the class for things that are already found in the decl store. So
it should never be the case that the decl doesn't exist. *)
let get_class_exn ctx class_name =
Decl_provider.get_class ctx class_name
|> Option.value_or_thunk ~default:(fun () ->
failwith
@@ "Impossible happened. "
^ class_name
^ " does not have a decl")
(* Use the folded decl of a container definition (class/interface/trait) to
collect inherited members of that definition. Particularly, we collect
methods, properties, class constants, and type constants. *)
let collect_inherited_members ctx def =
let empty_member_cluster container =
{
container;
methods = [];
properties = [];
type_constants = [];
class_constants = [];
}
in
let update_member_cluster add ~name ~origin (mcs : member_cluster SMap.t) =
let origin_decl = get_class_exn ctx origin in
let kind = Class.kind origin_decl in
let container = { name = origin; kind } in
SMap.update
container.name
(function
| None -> Some (add { name } (empty_member_cluster container))
| Some mc -> Some (add { name } mc))
mcs
in
(* All enums/enum classes inherit the same members which CodeHub currently
doesn't index (and is not particularly interesting), so we're only
interested in container definitions: classes, interfaces, and traits. *)
let has_proper_inherited_members c =
let open Ast_defs in
match c.Aast_defs.c_kind with
| Cclass _
| Cinterface
| Ctrait ->
true
| Cenum
| Cenum_class _ ->
false
in
let inherited_member_clusters = function
| Aast_defs.Class class_ when has_proper_inherited_members class_ ->
let class_name = snd class_.Aast_defs.c_name in
let class_decl = get_class_exn ctx class_name in
(* Collect members indexed by their origin *)
let mcs = SMap.empty in
let mcs =
let add_method m mc = { mc with methods = m :: mc.methods } in
let update = update_member_cluster add_method in
Class.methods class_decl @ Class.smethods class_decl
|> List.fold ~init:mcs ~f:(fun mcs (name, elt) ->
let origin = elt.Typing_defs.ce_origin in
(* Skip if not inherited *)
if String.equal origin class_name then
mcs
else
update ~name ~origin mcs)
in
let mcs =
let add_property p mc = { mc with properties = p :: mc.properties } in
let update = update_member_cluster add_property in
Class.props class_decl @ Class.sprops class_decl
|> List.fold ~init:mcs ~f:(fun mcs (name, elt) ->
let origin = elt.Typing_defs.ce_origin in
(* Skip if not inherited *)
if String.equal origin class_name then
mcs
else
update ~name ~origin mcs)
in
let (mcs, type_constants) =
let add_type_constant tc mc =
{ mc with type_constants = tc :: mc.type_constants }
in
let update = update_member_cluster add_type_constant in
Class.typeconsts class_decl
|> List.fold ~init:(mcs, SSet.empty) ~f:(fun (mcs, tcs) (name, elt) ->
let origin = elt.Typing_defs.ttc_origin in
(* Skip if not inherited *)
if String.equal origin class_name then
(mcs, tcs)
else
let mcs = update ~name ~origin mcs in
let tcs = SSet.add name tcs in
(mcs, tcs))
in
let mcs =
let add_class_constant cc mc =
{ mc with class_constants = cc :: mc.class_constants }
in
let update = update_member_cluster add_class_constant in
Class.consts class_decl
|> List.fold ~init:mcs ~f:(fun mcs (name, elt) ->
let origin = elt.Typing_defs.cc_origin in
(* Skip if
- not inherited
- `::class` which is a "synthesised" member that exists in
every class
- is a type constant (we already collected those separately
*)
if
String.equal origin class_name
|| String.equal name Naming_special_names.Members.mClass
|| SSet.mem name type_constants
then
mcs
else
update ~name ~origin mcs)
in
SMap.values mcs
| _ -> []
in
let index_inherited_members =
(Provider_context.get_tcopt ctx)
.GlobalOptions.symbol_write_index_inherited_members
in
let inherited_member_clusters =
if index_inherited_members then
inherited_member_clusters def
else
[]
in
(def, inherited_member_clusters)
let create
ctx Indexable.{ path; fanout } ~gen_sym_hash ~sym_path ~root_path ~hhi_path
=
let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path in
let path_str =
Relative_path.to_absolute_with_prefix
~www:(Path.make root_path)
~hhi:(Path.make hhi_path)
path
in
let source_text = Ast_provider.compute_source_text ~entry in
let { Tast_provider.Compute_tast.tast; _ } =
Tast_provider.compute_tast_unquarantined ~ctx ~entry
in
let tast = tast.Tast_with_dynamic.under_normal_assumptions in
let cst =
Provider_context.PositionedSyntaxTree.root
(Ast_provider.compute_cst ~ctx ~entry)
in
let symbol_occs = IdentifySymbolService.all_symbols ctx tast in
let symbols =
List.map symbol_occs ~f:(fun occ ->
{ occ; def = Sym_def.resolve ctx occ ~sym_path })
in
let tast = List.map tast ~f:(collect_inherited_members ctx) in
let sym_hash =
if gen_sym_hash then
let member_clusterss = List.map ~f:snd tast in
Some
( Md5.digest_string path_str |> compute_sym_hash symbols |> fun init ->
List.fold ~init ~f:compute_member_clusters_hash member_clusterss )
else
None
in
{ path = path_str; tast; source_text; cst; symbols; sym_hash; fanout }
let referenced t =
let path sym =
match sym.def with
| Some Sym_def.{ path = Some path; _ }
when Relative_path.(is_root (prefix path)) ->
Some (Relative_path.to_absolute path)
| _ -> None
in
List.filter_map t.symbols ~f:path |> SSet.of_list |
OCaml Interface | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_file_info.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
module Indexable = Symbol_indexable
module Sym_def = Symbol_sym_def
type symbol = private {
occ: Relative_path.t SymbolOccurrence.t;
def: Sym_def.t option;
}
type container = {
name: string;
kind: Ast_defs.classish_kind;
}
type member = { name: string }
type member_cluster = {
container: container;
methods: member list;
properties: member list;
class_constants: member list;
type_constants: member list;
}
(** [fanout] flag is used in incremental mode. It identifies files which are
unchanged compared to the base db. Such files don't need to be re-indexed
if an identical [sym_hash] exists on the base db. [sym_hash] captures the
file path and the part of the tast which determines xrefs *)
type t = private {
(* path to be used in the glean index *)
path: string;
cst: Full_fidelity_positioned_syntax.t;
tast: (Tast.def * member_cluster list) list;
source_text: Full_fidelity_source_text.t;
symbols: symbol list;
sym_hash: Md5.t option;
fanout: bool;
}
(** all the root (i.e. non-hhi) files referenced by t through xrefs. t
must have been created using [sym_path] set to [true], otherwise
the result set is empty *)
val referenced : t -> SSet.t
val create :
Provider_context.t ->
Indexable.t ->
gen_sym_hash:bool ->
sym_path:bool ->
root_path:string ->
hhi_path:string ->
t |
OCaml | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_gencode.ml | (*
* Copyright (c) Meta, 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 t = {
mutable is_generated: bool;
mutable fully_generated: bool;
mutable source: string option;
mutable command: string option;
mutable class_: string option;
mutable signature: string option;
}
let regex_sig =
{|\(^.*@\(partially-\)?generated\( SignedSource<<\([0-9a-f]+\)>>\)?.*$\)|}
let regex_codegen = {|\(^.*@codegen-\(command\|class\|source\).*: *\(.*\)$\)|}
let regex = Str.regexp (regex_sig ^ {|\||} ^ regex_codegen)
let has_group text i =
Option.(try_with (fun () -> Str.matched_group i text) |> is_some)
let extract_group text i = Option.try_with (fun () -> Str.matched_group i text)
let update_fields t text =
t.is_generated <- true;
if has_group text 1 then (
t.fully_generated <- not (has_group text 2);
t.signature <- extract_group text 4
) else
match extract_group text 6 with
| Some "command" -> t.command <- extract_group text 7
| Some "source" -> t.source <- extract_group text 7
| Some "class" -> t.class_ <- extract_group text 7
| _ -> Hh_logger.log "WARNING: this shouldn't happen."
let search_and_update t text pos =
try
let found_pos = Str.search_forward regex text pos in
update_fields t text;
(true, found_pos)
with
| Caml.Not_found -> (false, 0)
let get_gencode_status text =
let t =
{
is_generated = false;
fully_generated = true;
source = None;
command = None;
class_ = None;
signature = None;
}
in
let cur_pos = ref 0 in
let matched = ref true in
while !matched do
let (m, cp) = search_and_update t text !cur_pos in
cur_pos := cp + 1;
matched := m
done;
t |
OCaml Interface | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_gencode.mli | (*
* Copyright (c) Meta, 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 = private {
mutable is_generated: bool;
mutable fully_generated: bool;
mutable source: string option;
mutable command: string option;
mutable class_: string option;
mutable signature: string option;
}
(* one linear pass of the string to extract the gencode info *)
val get_gencode_status : string -> t |
OCaml | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_indexable.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Hh_json
type t = {
path: Relative_path.t;
fanout: bool;
}
let from_file path = { path; fanout = true }
let parse_line s =
if String.is_prefix s ~prefix:"{" then
match json_of_string s with
| JSON_Object [("path", JSON_String p); ("fanout", JSON_Bool f)] ->
{ path = Relative_path.storage_of_string p; fanout = f }
| _ -> failwith "Can't parse paths file"
else
(* for backward compatibility *)
{ path = Relative_path.storage_of_string s; fanout = false }
let from_options ~paths ~paths_file ~include_hhi =
let hhi_root = Path.make (Relative_path.path_of_prefix Relative_path.Hhi) in
let hhi_files =
match include_hhi with
| false -> []
| true ->
Hhi.get_raw_hhi_contents ()
|> Array.to_list
|> List.filter ~f:(fun (fn, _) ->
not (String.is_prefix fn ~prefix:"hsl_generated"))
|> List.map ~f:(fun (fn, _) ->
from_file
(Relative_path.create
Relative_path.Hhi
Path.(to_string (concat hhi_root fn))))
in
let relative_path_exists r = Sys.file_exists (Relative_path.to_absolute r) in
List.concat
[
Option.value_map paths_file ~default:[] ~f:In_channel.read_lines
|> List.map ~f:parse_line;
hhi_files;
paths
|> List.map ~f:(fun path -> Relative_path.from_root ~suffix:path)
|> List.filter ~f:relative_path_exists
|> List.map ~f:from_file;
]
let from_naming_table naming_table ~include_hhi ~ignore_paths =
let defs_per_file = Naming_table.to_defs_per_file naming_table in
Relative_path.Map.fold defs_per_file ~init:[] ~f:(fun path _ acc ->
match Naming_table.get_file_info naming_table path with
| None -> acc
| Some _ ->
let path_str = Relative_path.S.to_string path in
if
Relative_path.is_hhi (Relative_path.prefix path)
&& ((not include_hhi)
|| String.is_prefix path_str ~prefix:"hhi|hsl_generated")
|| List.exists ignore_paths ~f:(fun ignore ->
String.equal path_str ignore)
then
acc
else
from_file path :: acc) |
OCaml Interface | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_indexable.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 t = private {
path: Relative_path.t;
fanout: bool;
}
val from_file : Relative_path.t -> t
(** Compute files to index based on list of files provided on the CLI, and
from a paths file. Two forms are accepted for lines in [paths_file].
Legacy format: "prefix|rel_path", e.g.
hhi|builtins_fb.hhi
root|scripts/whatsapp/erl/regd/cfg/list_fb_car
JSON: { path = "prefix|rel_path", fanout = bool }
If [with_hhi] is provided, results include the built-in hhi files.
See also [symbol_file_info.mli] for role of [fanout] flag *)
val from_options :
paths:string list -> paths_file:string option -> include_hhi:bool -> t list
(** Get the list of files from the naming table, with possible exclusions.
hh should be run in full-init mode if we want the list of all files to index *)
val from_naming_table :
Naming_table.t -> include_hhi:bool -> ignore_paths:string list -> t list |
OCaml | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_index_batch.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.
*
*)
(** Indexing a Hack file consists in three distinct passes
1. Indexing source text (regex matching for extracting gencode info from comments)
2. Indexing declarations, done in [Symbol_index_decls]
3. Indexing xrefs and filecalls, done in [Symbol_index_refs] *)
open Hh_prelude
module File_info = Symbol_file_info
module Gencode = Symbol_gencode
module Add_fact = Symbol_add_fact
module Fact_acc = Symbol_predicate.Fact_acc
module XRefs = Symbol_xrefs
module Fact_id = Symbol_fact_id
let process_source_text _ctx prog File_info.{ path; source_text; _ } =
let text = Full_fidelity_source_text.text source_text in
match Gencode.get_gencode_status text with
| Gencode.
{
is_generated = true;
fully_generated;
source;
command;
class_;
signature;
} ->
Add_fact.gen_code
~path
~fully_generated
~signature
~source
~command
~class_
prog
|> snd
| _ -> prog
let build_json ctx files_info ~ownership =
let index_file progress file_info =
let path = file_info.File_info.path in
Fact_acc.set_ownership_unit progress (Some path);
let progress = process_source_text ctx progress file_info in
let (progress, xrefs) =
Symbol_index_xrefs.process_xrefs_and_calls ctx progress file_info
in
Fact_acc.set_pos_map progress xrefs.XRefs.pos_map;
let (mod_xrefs, progress) =
Symbol_index_decls.process_decls ctx progress file_info
in
let fact_map_xrefs = xrefs.XRefs.fact_map in
let fact_map_module_xrefs = mod_xrefs.XRefs.fact_map in
let merge _ x _ = Some x in
let all_xrefs =
Fact_id.Map.union merge fact_map_module_xrefs fact_map_xrefs
in
if Fact_id.Map.is_empty all_xrefs then
progress
else
Add_fact.file_xrefs ~path all_xrefs progress |> snd
in
let progress = Fact_acc.init ~ownership in
List.fold files_info ~init:progress ~f:index_file |> Fact_acc.to_json |
OCaml Interface | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_index_batch.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 build_json :
Provider_context.t ->
Symbol_file_info.t list ->
ownership:bool ->
Hh_json.json list |
OCaml | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_index_decls.ml | (*
* Copyright (c) Meta, 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 Aast
open Hh_prelude
module Add_fact = Symbol_add_fact
module Fact_acc = Symbol_predicate.Fact_acc
module Fact_id = Symbol_fact_id
module Util = Symbol_json_util
module Build = Symbol_build_json
module Predicate = Symbol_predicate
module File_info = Symbol_file_info
module XRefs = Symbol_xrefs
let process_doc_comment
(comment : Aast.doc_comment option)
(path : string)
(decl_ref_json : Hh_json.json)
(prog : Fact_acc.t) : Fact_acc.t =
match comment with
| None -> prog
| Some (pos, _doc) -> snd (Add_fact.decl_comment ~path pos decl_ref_json prog)
let process_loc_span
path
(pos : Pos.t)
(span : Pos.t)
(ref_json : Hh_json.json)
(prog : Fact_acc.t) : Fact_acc.t =
let (_, prog) = Add_fact.decl_loc ~path pos ref_json prog in
let (_, prog) = Add_fact.decl_span ~path span ref_json prog in
prog
let process_decl_loc
(decl_fun : string -> Fact_acc.t -> Fact_id.t * Fact_acc.t)
(defn_fun : 'elem -> Fact_id.t -> Fact_acc.t -> Fact_id.t * Fact_acc.t)
(decl_ref_fun : Fact_id.t -> Hh_json.json)
~(path : string)
(pos : Pos.t)
(span : Pos.t)
(id : Ast_defs.id_)
(elem : 'elem)
(doc : Aast.doc_comment option)
(progress : Fact_acc.t) : Fact_id.t * Fact_acc.t =
let (decl_id, prog) = decl_fun id progress in
let (_, prog) = defn_fun elem decl_id prog in
let ref_json = decl_ref_fun decl_id in
let prog = process_doc_comment doc path ref_json prog in
let prog = process_loc_span path pos span ref_json prog in
(decl_id, prog)
let process_member
add_member_decl
build_decl_ref
~container_type
~container_id
(member_ids, prog)
File_info.{ name } =
let (member_id, prog) =
add_member_decl container_type container_id name prog
in
(build_decl_ref member_id :: member_ids, prog)
let process_member_cluster mc prog =
let (container_type, container_id, prog) =
let (con_type, decl_pred) =
Predicate.get_parent_kind mc.File_info.container.File_info.kind
|> Predicate.parent_decl_predicate
in
let (con_decl_id, prog) =
Add_fact.container_decl
decl_pred
mc.File_info.container.File_info.name
prog
in
(con_type, con_decl_id, prog)
in
let process add_member_decl build_decl_ref members acc =
List.fold
members
~init:acc
~f:
(process_member
add_member_decl
build_decl_ref
~container_type
~container_id)
in
([], prog)
|> process
Add_fact.method_decl
Build.build_method_decl_json_ref
mc.File_info.methods
|> process
Add_fact.property_decl
Build.build_property_decl_json_ref
mc.File_info.properties
|> process
Add_fact.type_const_decl
Build.build_type_const_decl_json_ref
mc.File_info.type_constants
|> process
Add_fact.class_const_decl
Build.build_class_const_decl_json_ref
mc.File_info.class_constants
let process_container_decl
ctx path source_text con member_clusters (xrefs, all_decls, progress) =
let (con_pos, con_name) = con.c_name in
let (con_type, decl_pred) =
Predicate.parent_decl_predicate (Predicate.get_parent_kind con.c_kind)
in
let (con_decl_id, prog) =
Add_fact.container_decl decl_pred con_name progress
in
let (prop_decls, prog) =
List.fold_right con.c_vars ~init:([], prog) ~f:(fun prop (decls, prog) ->
let (pos, id) = prop.cv_id in
let (decl_id, prog) =
process_decl_loc
(Add_fact.property_decl con_type con_decl_id)
(Add_fact.property_defn ctx source_text)
Build.build_property_decl_json_ref
~path
pos
prop.cv_span
id
prop
prop.cv_doc_comment
prog
in
(Build.build_property_decl_json_ref decl_id :: decls, prog))
in
let (class_const_decls, prog) =
List.fold_right con.c_consts ~init:([], prog) ~f:(fun const (decls, prog) ->
let (pos, id) = const.cc_id in
let (decl_id, prog) =
process_decl_loc
(Add_fact.class_const_decl con_type con_decl_id)
(Add_fact.class_const_defn ctx source_text)
Build.build_class_const_decl_json_ref
~path
pos
const.cc_span
id
const
const.cc_doc_comment
prog
in
(Build.build_class_const_decl_json_ref decl_id :: decls, prog))
in
let (type_const_decls, prog) =
List.fold_right
con.c_typeconsts
~init:([], prog)
~f:(fun tc (decls, prog) ->
let (pos, id) = tc.c_tconst_name in
let (decl_id, prog) =
process_decl_loc
(Add_fact.type_const_decl con_type con_decl_id)
(Add_fact.type_const_defn ctx source_text)
Build.build_type_const_decl_json_ref
~path
pos
tc.c_tconst_span
id
tc
tc.c_tconst_doc_comment
prog
in
(Build.build_type_const_decl_json_ref decl_id :: decls, prog))
in
let (method_decls, prog) =
List.fold_right con.c_methods ~init:([], prog) ~f:(fun meth (decls, prog) ->
let (pos, id) = meth.m_name in
let (decl_id, prog) =
process_decl_loc
(Add_fact.method_decl con_type con_decl_id)
(Add_fact.method_defn ctx source_text)
Build.build_method_decl_json_ref
~path
pos
meth.m_span
id
meth
meth.m_doc_comment
prog
in
(Build.build_method_decl_json_ref decl_id :: decls, prog))
in
let members =
type_const_decls @ class_const_decls @ prop_decls @ method_decls
in
let (prog, inherited_member_clusters) =
List.fold_map member_clusters ~init:prog ~f:(fun prog mc ->
let (members, prog) = process_member_cluster mc prog in
let (mc, prog) = Add_fact.member_cluster ~members prog in
(prog, mc))
in
let prog =
if not @@ List.is_empty inherited_member_clusters then
let (_id, prog) =
Add_fact.inherited_members
~container_type:con_type
~container_id:con_decl_id
~member_clusters:inherited_member_clusters
prog
in
prog
else
prog
in
let (_, prog) =
Add_fact.container_defn ctx source_text con con_decl_id members prog
in
let ref_json = Build.build_container_decl_json_ref con_type con_decl_id in
let prog = process_loc_span path con_pos con.c_span ref_json prog in
let all_decls = all_decls @ [ref_json] @ members in
let prog = process_doc_comment con.c_doc_comment path ref_json prog in
(xrefs, all_decls, prog)
let process_enum_decl ctx path source_text enm (xrefs, all_decls, progress) =
let (pos, id) = enm.c_name in
match enm.c_enum with
| None ->
Hh_logger.log "WARNING: skipping enum with missing data - %s" id;
(xrefs, all_decls, progress)
| Some enum_data ->
let (enum_id, prog) = Add_fact.enum_decl id progress in
let enum_decl_ref = Build.build_enum_decl_json_ref enum_id in
let prog = process_loc_span path pos enm.c_span enum_decl_ref prog in
let (enumerators, decl_refs, prog) =
List.fold_right
enm.c_consts
~init:([], [], prog)
~f:(fun enumerator (decls, refs, prog) ->
let (pos, id) = enumerator.cc_id in
let (decl_id, prog) = Add_fact.enumerator enum_id id prog in
let _span = enumerator.cc_span in
let ref_json = Build.build_enumerator_decl_json_ref decl_id in
(* TODO we're using pos instead of _span. _span refer to the whole enum container,
rather than the enumerator *)
let prog = process_loc_span path pos pos ref_json prog in
let prog =
process_doc_comment enumerator.cc_doc_comment path ref_json prog
in
(Build.build_id_json decl_id :: decls, ref_json :: refs, prog))
in
let (_, prog) =
Add_fact.enum_defn ctx source_text enm enum_id enum_data enumerators prog
in
let prog = process_doc_comment enm.c_doc_comment path enum_decl_ref prog in
(xrefs, all_decls @ (enum_decl_ref :: decl_refs), prog)
let process_func_decl ctx path source_text fd (xrefs, all_decls, progress) =
let elem = fd.fd_fun in
let (pos, id) = fd.fd_name in
let (decl_id, prog) =
process_decl_loc
Add_fact.func_decl
(Add_fact.func_defn ctx source_text)
Build.build_func_decl_json_ref
~path
pos
elem.f_span
id
fd
elem.f_doc_comment
progress
in
(xrefs, all_decls @ [Build.build_func_decl_json_ref decl_id], prog)
let process_gconst_decl ctx path source_text elem (xrefs, all_decls, progress) =
let (pos, id) = elem.cst_name in
let (decl_id, prog) =
process_decl_loc
Add_fact.gconst_decl
(Add_fact.gconst_defn ctx source_text)
Build.build_gconst_decl_json_ref
~path
pos
elem.cst_span
id
elem
None
progress
in
(xrefs, all_decls @ [Build.build_gconst_decl_json_ref decl_id], prog)
let process_typedef_decl ctx path source_text elem (xrefs, all_decls, progress)
=
let (pos, id) = elem.t_name in
let (decl_id, prog) =
process_decl_loc
Add_fact.typedef_decl
(Add_fact.typedef_defn ctx source_text)
Build.build_typedef_decl_json_ref
~path
pos
elem.t_span
id
elem
elem.t_doc_comment
progress
in
(xrefs, all_decls @ [Build.build_typedef_decl_json_ref decl_id], prog)
let process_module_decl ctx path source_text elem (xrefs, all_decls, progress) =
let (pos, id) = elem.md_name in
let (decl_id, prog) =
process_decl_loc
Add_fact.module_decl
(Add_fact.module_defn ctx source_text)
Build.build_module_decl_json_ref
~path
pos
elem.md_span
id
elem
None
progress
in
(xrefs, all_decls @ [Build.build_module_decl_json_ref decl_id], prog)
let process_namespace_decl ~path (pos, id) (all_decls, progress) =
let (decl_id, prog) =
process_decl_loc
Add_fact.namespace_decl
(fun () fid acc -> (fid, acc))
Build.build_namespace_decl_json_ref
~path
pos
pos (* no span for a namespace decl, we re-use the location *)
id
()
None
progress
in
(all_decls @ [Build.build_namespace_decl_json_ref decl_id], prog)
let process_cst_decls st path root (decls, prog) =
let open Full_fidelity_positioned_syntax in
match root.syntax with
| Script { script_declarations = { syntax = SyntaxList cst_decls; _ } } ->
List.fold cst_decls ~init:(decls, prog) ~f:(fun acc cst_decl ->
match cst_decl.syntax with
| NamespaceDeclaration
{
namespace_header =
{
syntax =
NamespaceDeclarationHeader
{ namespace_name = { syntax = ns_ast; _ }; _ };
_;
};
_;
} ->
(try
let (pos, id) = Util.namespace_ast_to_pos_id ns_ast st in
process_namespace_decl ~path (pos, id) acc
with
| Util.Empty_namespace -> acc
| Util.Ast_error ->
Hh_logger.log "Couldn't extract namespace from declaration";
acc)
| _ -> acc)
| _ ->
Hh_logger.log "Couldn't extract namespaces declarations";
(decls, prog)
let process_mod_xref prog xrefs (pos, id) =
let (target_id, prog) = Add_fact.module_decl id prog in
let xref_json = Build.build_module_decl_json_ref target_id in
let target = Build.build_decl_target_json xref_json in
(XRefs.add xrefs target_id pos XRefs.{ target; receiver_type = None }, prog)
let process_tast_decls ctx ~path tast source_text (decls, prog) =
List.fold tast ~init:(XRefs.empty, decls, prog) ~f:(fun acc (def, im) ->
match def with
| Class en when Util.is_enum_or_enum_class en.c_kind ->
process_enum_decl ctx path source_text en acc
| Class cd -> process_container_decl ctx path source_text cd im acc
| Constant gd -> process_gconst_decl ctx path source_text gd acc
| Fun fd -> process_func_decl ctx path source_text fd acc
| Typedef td -> process_typedef_decl ctx path source_text td acc
| Module md -> process_module_decl ctx path source_text md acc
| SetModule sm ->
let (xrefs, _, prog) = acc in
let (xrefs, prog) = process_mod_xref prog xrefs sm in
(xrefs, decls, prog)
| _ -> acc)
let process_decls ctx prog File_info.{ path; tast; source_text; cst; _ } =
Fact_acc.set_ownership_unit prog (Some path);
let (_, prog) = Add_fact.file_lines ~path source_text prog in
let (mod_xrefs, decls, prog) =
process_tast_decls ctx ~path tast source_text ([], prog)
in
let (decls, prog) = process_cst_decls source_text path cst (decls, prog) in
(mod_xrefs, Add_fact.file_decls ~path decls prog |> snd) |
OCaml Interface | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_index_decls.mli | (*
* Copyright (c) Meta, 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.
*
*)
(** Generate facts for all declarations in AST, and
a XRefs map for the module references *)
val process_decls :
Provider_context.t ->
Symbol_predicate.Fact_acc.t ->
Symbol_file_info.t ->
Symbol_xrefs.t * Symbol_predicate.Fact_acc.t |
OCaml | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_index_xrefs.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 Add_fact = Symbol_add_fact
module Fact_acc = Symbol_predicate.Fact_acc
module Build = Symbol_build_json
module Predicate = Symbol_predicate
module File_info = Symbol_file_info
module XRefs = Symbol_xrefs
module Sym_def = Symbol_sym_def
let call_handler ~path progress_ref (pos_map : XRefs.pos_map) =
object (_self)
inherit Tast_visitor.handler_base
method! at_Call _env call =
let Aast.{ func = (_, callee_pos, callee_exp); args; _ } = call in
let f (_, (_, arg_pos, exp)) =
let exp_json =
match exp with
| Aast.String s
when String.for_all ~f:(fun c -> Caml.Char.code c < 127) s ->
(* TODO make this more general *)
Some (Symbol_build_json.build_argument_lit_json s)
| Aast.Id (id_pos, _)
| Aast.Class_const (_, (id_pos, _)) ->
(match XRefs.PosMap.find_opt id_pos pos_map with
| Some (XRefs.{ target; _ } :: _) ->
(* there shouldn't be more than one target for a symbol in that
position *)
Some (Symbol_build_json.build_argument_xref_json target)
| _ -> None)
| _ -> None
in
(exp_json, arg_pos)
in
let call_args =
Symbol_build_json.build_call_arguments_json (List.map args ~f)
in
let (id_pos, receiver_span) =
match callee_exp with
| Aast.Id (id_pos, _) -> (Some id_pos, None)
| Aast.Class_const (_, (id_pos, _)) -> (Some id_pos, None)
| Aast.(Obj_get ((_, receiver_span, _), (_, _, Id (id_pos, _)), _, _))
->
(Some id_pos, Some receiver_span)
| _ -> (None, None)
in
let dispatch_arg =
Option.(
receiver_span >>= fun pos ->
match Symbol_build_json.build_call_arguments_json [(None, pos)] with
| [arg] -> Some arg
| _ -> None)
in
let callee_infos =
match id_pos with
| None -> []
| Some pos ->
(match XRefs.PosMap.find_opt pos pos_map with
| Some l -> l
| None -> [])
in
progress_ref :=
Add_fact.file_call
~path
callee_pos
~callee_infos
~call_args
~dispatch_arg
!progress_ref
|> snd
end
let process_calls ctx path tast map_pos_decl progress =
let progress_ref = ref progress in
let visitor =
Tast_visitor.iter_with [call_handler ~path progress_ref map_pos_decl]
in
let tast = List.map ~f:fst tast in
visitor#go ctx tast;
!progress_ref
let process_xref
decl_fun decl_ref_fun symbol_name pos ?receiver_type (xrefs, prog) =
let (target_id, prog) = decl_fun symbol_name prog in
let xref_json = decl_ref_fun target_id in
let target = Build.build_decl_target_json xref_json in
let xrefs = XRefs.add xrefs target_id pos XRefs.{ target; receiver_type } in
(xrefs, prog)
let process_enum_xref symbol_name pos (xrefs, prog) =
process_xref
Add_fact.enum_decl
Build.build_enum_decl_json_ref
symbol_name
pos
(xrefs, prog)
let process_typedef_xref symbol_name pos (xrefs, prog) =
process_xref
Add_fact.typedef_decl
Build.build_typedef_decl_json_ref
symbol_name
pos
(xrefs, prog)
let process_function_xref symbol_name pos (xrefs, prog) =
process_xref
Add_fact.func_decl
Build.build_func_decl_json_ref
symbol_name
pos
(xrefs, prog)
let process_gconst_xref symbol_def pos (xrefs, prog) =
process_xref
Add_fact.gconst_decl
Build.build_gconst_decl_json_ref
symbol_def
pos
(xrefs, prog)
let process_member_xref
ctx member pos mem_decl_fun ref_fun ?receiver_type (xrefs, prog) =
let Sym_def.{ name; full_name; kind; _ } = member in
match Str.split (Str.regexp "::") full_name with
| [] -> (xrefs, prog)
| con_name :: _mem_name ->
let con_name_with_ns = Utils.add_ns con_name in
(match Sym_def.get_class_by_name ctx con_name_with_ns with
| `None ->
Hh_logger.log
"WARNING: could not find parent container %s processing reference to %s"
con_name_with_ns
full_name;
(xrefs, prog)
| `Enum ->
(match kind with
| SymbolDefinition.ClassConst ->
let (enum_id, prog) = Add_fact.enum_decl con_name prog in
process_xref
(Add_fact.enumerator enum_id)
Build.build_enumerator_decl_json_ref
name
pos
(xrefs, prog)
(* This includes references to built-in enum methods *)
| _ -> (xrefs, prog))
| `Class cls ->
let con_kind = Predicate.get_parent_kind cls.Aast.c_kind in
let (con_type, decl_pred) = Predicate.parent_decl_predicate con_kind in
let (con_decl_id, prog) =
Add_fact.container_decl decl_pred con_name prog
in
process_xref
(mem_decl_fun con_type con_decl_id)
ref_fun
name
pos
?receiver_type
(xrefs, prog))
let process_container_xref (con_type, decl_pred) symbol_name pos (xrefs, prog) =
process_xref
(Add_fact.container_decl decl_pred)
(Build.build_container_decl_json_ref con_type)
symbol_name
pos
(xrefs, prog)
let process_attribute_xref ctx File_info.{ occ; def } opt_info (xrefs, prog) =
let get_con_preds_from_name con_name =
let con_name_with_ns = Utils.add_ns con_name in
match Sym_def.get_class_by_name ctx con_name_with_ns with
| `None ->
Hh_logger.log
"WARNING: could not find declaration container %s for attribute reference to %s"
con_name_with_ns
con_name;
None
| `Enum ->
Hh_logger.log
"WARNING: unexpected enum %s processing attribute reference %s"
con_name_with_ns
con_name;
None
| `Class cls ->
Some Predicate.(parent_decl_predicate (get_parent_kind cls.Aast.c_kind))
in
(* Process <<__Override>>, for which we write a MethodOverrides fact
instead of a cross-reference *)
let SymbolOccurrence.{ name; pos; _ } = occ in
if String.equal name "__Override" then
match opt_info with
| None ->
Hh_logger.log "WARNING: no override info for <<__Override>> instance";
(xrefs, prog)
| Some SymbolOccurrence.{ class_name; method_name; _ } ->
(match get_con_preds_from_name class_name with
| None -> (xrefs, prog)
| Some override_con_pred_types ->
(match def with
| None -> (xrefs, prog)
| Some Sym_def.{ full_name; _ } ->
(match Str.split (Str.regexp "::") full_name with
| [] -> (xrefs, prog)
| base_con_name :: _mem_name ->
(match get_con_preds_from_name base_con_name with
| None ->
Hh_logger.log
"WARNING: could not compute parent container type for override %s::%s"
class_name
method_name;
(xrefs, prog)
| Some base_con_pred_types ->
let (_fid, prog) =
Add_fact.method_overrides
method_name
base_con_name
(fst base_con_pred_types)
class_name
(fst override_con_pred_types)
prog
in
(* Cross-references for overrides could be added to xefs by calling
'process_member_xref' here with 'sym_def' and 'occ.pos' *)
(xrefs, prog)))))
(* Ignore other built-in attributes *)
else if String.is_prefix name ~prefix:"__" then
(xrefs, prog)
(* Process user-defined attributes *)
else
try
(* Look for a container declaration with the same name as the attribute,
which will be where it is defined *)
match get_con_preds_from_name name with
| None -> (xrefs, prog)
| Some con_pred_types ->
process_container_xref con_pred_types name pos (xrefs, prog)
with
| e ->
Hh_logger.log
"WARNING: error processing reference to attribute %s\n: %s\n"
name
(Exn.to_string e);
(xrefs, prog)
let receiver_type occ =
let open SymbolOccurrence in
match occ.type_ with
| Method (ClassName receiver, _) ->
Some (Build.build_class_decl_json_nested receiver)
| _ -> None
(* given symbols occurring in a file, compute the maps of xrefs *)
let process_xrefs ctx symbols prog : XRefs.t * Fact_acc.t =
let open SymbolOccurrence in
List.fold
symbols
~init:(XRefs.empty, prog)
~f:(fun (xrefs, prog) (File_info.{ occ; def } as sym) ->
if occ.is_declaration then
(xrefs, prog)
else
let pos = occ.pos in
match occ.type_ with
| Attribute info -> process_attribute_xref ctx sym info (xrefs, prog)
| _ ->
(match def with
| None ->
(* no symbol info - likely dynamic *)
(match occ.type_ with
| Method (receiver_class, name) ->
let (target_id, prog) =
Add_fact.method_occ receiver_class name prog
in
let xref_json = Build.build_method_occ_json_ref target_id in
let target = Build.build_occ_target_json xref_json in
let receiver_type = receiver_type occ in
let xrefs =
XRefs.add xrefs target_id pos XRefs.{ target; receiver_type }
in
(xrefs, prog)
| _ -> (xrefs, prog))
| Some (Sym_def.{ name; kind; _ } as sym_def) ->
let open SymbolDefinition in
let proc_mem = process_member_xref ctx sym_def pos in
(match kind with
| Class ->
let con_kind =
Predicate.parent_decl_predicate Predicate.ClassContainer
in
process_container_xref con_kind name pos (xrefs, prog)
| ClassConst ->
let ref_fun = Build.build_class_const_decl_json_ref in
proc_mem Add_fact.class_const_decl ref_fun (xrefs, prog)
| GlobalConst -> process_gconst_xref name pos (xrefs, prog)
| Enum -> process_enum_xref name pos (xrefs, prog)
| Function -> process_function_xref name pos (xrefs, prog)
| Interface ->
let con_kind =
Predicate.parent_decl_predicate Predicate.InterfaceContainer
in
process_container_xref con_kind name pos (xrefs, prog)
| Method ->
let ref_fun = Build.build_method_decl_json_ref in
process_member_xref
ctx
sym_def
pos
Add_fact.method_decl
ref_fun (* TODO just pass the occurrence here *)
?receiver_type:(receiver_type occ)
(xrefs, prog)
| Property ->
let ref_fun = Build.build_property_decl_json_ref in
proc_mem Add_fact.property_decl ref_fun (xrefs, prog)
| Typeconst ->
let ref_fun = Build.build_type_const_decl_json_ref in
proc_mem Add_fact.type_const_decl ref_fun (xrefs, prog)
| Typedef -> process_typedef_xref name pos (xrefs, prog)
| Trait ->
let con_kind =
Predicate.parent_decl_predicate Predicate.TraitContainer
in
process_container_xref con_kind name pos (xrefs, prog)
| _ -> (xrefs, prog))))
let process_xrefs_and_calls ctx prog File_info.{ path; tast; symbols; _ } =
Fact_acc.set_ownership_unit prog (Some path);
let ((XRefs.{ pos_map; _ } as xrefs), prog) =
process_xrefs ctx symbols prog
in
let prog = process_calls ctx path tast pos_map prog in
(prog, xrefs) |
OCaml Interface | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_index_xrefs.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 process_xrefs_and_calls :
Provider_context.t ->
Symbol_predicate.Fact_acc.t ->
Symbol_file_info.t ->
Symbol_predicate.Fact_acc.t * Symbol_xrefs.t |
OCaml | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_json_util.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 is_enum_or_enum_class = function
| Ast_defs.Cenum
| Ast_defs.Cenum_class _ ->
true
| Ast_defs.(Cinterface | Cclass _ | Ctrait) -> false
let get_context_from_hint ctx h =
let mode = FileInfo.Mhhi in
let decl_env = Decl_env.{ mode; droot = None; droot_member = None; ctx } in
let tcopt = Provider_context.get_tcopt ctx in
Typing_print.full_decl ~msg:false tcopt (Decl_hint.context_hint decl_env h)
let get_type_from_hint ctx h =
let mode = FileInfo.Mhhi in
let decl_env = Decl_env.{ mode; droot = None; droot_member = None; ctx } in
let tcopt = Provider_context.get_tcopt ctx in
Typing_print.full_decl ~msg:false tcopt (Decl_hint.hint decl_env h)
let get_type_from_hint_strip_ns ctx h =
let mode = FileInfo.Mhhi in
let decl_env = Decl_env.{ mode; droot = None; droot_member = None; ctx } in
let env = Typing_env_types.empty ctx Relative_path.default ~droot:None in
Typing_print.full_strip_ns_decl ~msg:false env (Decl_hint.hint decl_env h)
(* Replace any codepoints that are not valid UTF-8 with
the unrepresentable character. *)
let check_utf8 str =
let b = Buffer.create (String.length str) in
let replace_malformed () _index = function
| `Uchar u -> Uutf.Buffer.add_utf_8 b u
| `Malformed _ -> Uutf.Buffer.add_utf_8 b Uutf.u_rep
in
Uutf.String.fold_utf_8 replace_malformed () str;
Buffer.contents b
let source_at_span source_text pos =
let st = Pos.start_offset pos in
let fi = Pos.end_offset pos in
let source_text = Full_fidelity_source_text.sub source_text st (fi - st) in
check_utf8 source_text
let strip_nested_quotes str =
let len = String.length str in
let firstc = str.[0] in
let lastc = str.[len - 1] in
if
len >= 2
&& ((Char.equal '"' firstc && Char.equal '"' lastc)
|| (Char.equal '\'' firstc && Char.equal '\'' lastc))
then
String.sub str ~pos:1 ~len:(len - 2)
else
str
let strip_tparams name =
match String.index name '<' with
| None -> name
| Some i -> String.sub name ~pos:0 ~len:i
let ends_in_newline source_text =
let last_char =
Full_fidelity_source_text.(get source_text (source_text.length - 1))
in
Char.equal '\n' last_char || Char.equal '\r' last_char
let has_tabs_or_multibyte_codepoints source_text =
let open Full_fidelity_source_text in
let check_codepoint (num, found) _index = function
| `Uchar u -> (num + 1, found || Uchar.equal u (Uchar.of_char '\t'))
| `Malformed _ -> (num + 1, true)
in
let (num_chars, found_tab_or_malformed) =
Uutf.String.fold_utf_8 check_codepoint (0, false) source_text.text
in
found_tab_or_malformed || num_chars < source_text.length
let split_name (s : string) : (string * string) option =
match String.rindex s '\\' with
| None -> None
| Some pos ->
let name_start = pos + 1 in
let name =
String.sub s ~pos:name_start ~len:(String.length s - name_start)
in
let parent_namespace = String.sub s ~pos:0 ~len:(name_start - 1) in
if String.is_empty parent_namespace || String.is_empty name then
None
else
Some (parent_namespace, name)
let ast_expr_to_json source_text (_, pos, _) =
Hh_json.JSON_String (strip_nested_quotes (source_at_span source_text pos))
let ast_expr_to_string source_text (_, pos, _) = source_at_span source_text pos
module Token = Full_fidelity_positioned_syntax.Token
let tokens_to_pos_id st ~hd ~tl =
let path = st.Full_fidelity_source_text.file_path in
let start_offset = Token.leading_start_offset hd in
let name = String.concat ~sep:"\\" (List.map (hd :: tl) ~f:Token.text) in
let end_offset = start_offset + String.length name in
let pos =
Full_fidelity_source_text.relative_pos path st start_offset end_offset
in
(pos, name)
exception Ast_error
exception Empty_namespace
let namespace_ast_to_pos_id ns_ast st =
let open Full_fidelity_positioned_syntax in
let f item =
match item.syntax with
| ListItem { list_item = { syntax = Token t; _ }; _ } -> t
| _ -> raise Ast_error
in
let (hd, tl) =
match ns_ast with
| Token t -> (t, [])
| QualifiedName
{ qualified_name_parts = { syntax = SyntaxList (hd :: tl); _ } } ->
(f hd, List.map ~f tl)
| Missing -> raise Empty_namespace
| _ -> raise Ast_error
in
tokens_to_pos_id st ~hd ~tl
type pos = {
start: int;
length: int;
}
[@@deriving ord]
(* Pretty-printer for hints. Also generate
xrefs. TODO: This covers most of the types but needs
to be extended OR move the xrefs generartion logic
to Typing_print.full_strip_ns_decl *)
let string_of_type ctx (t : Aast.hint) =
let queue = Queue.create () in
let cur = ref 0 in
let xrefs = ref [] in
let enqueue ?annot str =
let length = String.length str in
let pos = { start = !cur; length } in
Queue.enqueue queue str;
cur := !cur + length;
Option.iter annot ~f:(fun file_pos -> xrefs := (file_pos, pos) :: !xrefs)
in
let rec parse t =
let open Aast in
match snd t with
| Hoption t ->
enqueue "?";
parse t
| Hlike t ->
enqueue "~";
parse t
| Hsoft t ->
enqueue "@";
parse t
| Happly ((file_pos, cn), hs) ->
enqueue ~annot:file_pos (Typing_print.strip_ns cn);
parse_list ("<", ">") hs
| Htuple hs -> parse_list ("(", ")") hs
| Hprim p -> enqueue (Aast_defs.string_of_tprim p)
| Haccess (h, sids) ->
parse h;
List.iter sids ~f:(fun (file_pos, sid) ->
enqueue "::";
enqueue ~annot:file_pos sid)
| _ ->
(* fall back on old pretty printer - without xrefs - for things
not implemented yet *)
enqueue (get_type_from_hint_strip_ns ctx t)
and parse_list (op, cl) = function
| [] -> ()
| [h] ->
enqueue op;
parse h;
enqueue cl
| h :: hs ->
enqueue op;
parse h;
List.iter hs ~f:(fun h ->
enqueue ", ";
parse h);
enqueue cl
in
parse t;
let toks = Queue.to_list queue in
(String.concat toks, !xrefs)
let hint_to_string_and_symbols ctx h =
let ty_pp_ref = get_type_from_hint_strip_ns ctx h in
let (ty_pp, xrefs) = string_of_type ctx h in
match String.equal ty_pp ty_pp_ref with
| true -> (ty_pp, xrefs)
| false ->
(* This is triggered only for very large (truncated) types.
We use ty_pp_ref in that case since it guarantees an
upper bound on the size of types. *)
Hh_logger.log "pretty-printers mismatch: %s %s" ty_pp ty_pp_ref;
(ty_pp_ref, [])
let remove_generated_tparams tparams =
let param_name Aast_defs.{ tp_name = (_, name); _ } = name in
Typing_print.split_desugared_ctx_tparams_gen ~tparams ~param_name |> snd |
OCaml Interface | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_json_util.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 is_enum_or_enum_class : Ast_defs.classish_kind -> bool
(* True if source text ends in a newline *)
val ends_in_newline : Full_fidelity_source_text.t -> bool
val has_tabs_or_multibyte_codepoints : Full_fidelity_source_text.t -> bool
val get_type_from_hint : Provider_context.t -> Aast.hint -> string
type pos = {
start: int;
length: int;
}
[@@deriving ord]
(* A pretty printer which returns a user friendly
type representation, and the list of class names with
their position within the string.
Symbols are identified by their position `Pos.t` within the file *)
val hint_to_string_and_symbols :
Provider_context.t -> Aast.hint -> string * (Pos.t * pos) list
val get_context_from_hint : Provider_context.t -> Aast.hint -> string
(* Values pulled from source code may have quotation marks;
strip these when present, eg: "\"FOO\"" => "FOO" *)
val strip_nested_quotes : string -> string
(* Convert ContainerName<TParam> to ContainerName *)
val strip_tparams : string -> string
(* Split name or subnamespace from its parent namespace, and return
either Some (parent, name), or None if the name has no parent namespace.
The trailing slash is removed from the parent. *)
val split_name : string -> (string * string) option
(* hack to pretty-print an expression. Get the representation from
the source file, in lack of a better solution. This assumes that the
expr comes from the the source text parameter. Should be replaced
by proper pretty-printing functions. *)
val ast_expr_to_json :
Full_fidelity_source_text.t -> ('a, 'b) Aast.expr -> Hh_json.json
val ast_expr_to_string :
Full_fidelity_source_text.t -> ('a, 'b) Aast.expr -> string
exception Ast_error
exception Empty_namespace
(* Retrieve a namespace identifier and its position from an AST namespace node.
Raise Ast_error if the ast doesn't have the expected structure, and Empty_namespace
if the namespace is empty. ) *)
val namespace_ast_to_pos_id :
Full_fidelity_positioned_syntax.syntax ->
Full_fidelity_source_text.t ->
Pos.t * string
(* remove generated parameters of the form T/[ctx $f]*)
val remove_generated_tparams :
('a, 'b) Aast_defs.tparam list -> ('a, 'b) Aast_defs.tparam list |
OCaml | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_predicate.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 Fact_id = Symbol_fact_id
open Hh_prelude
open Hh_json
(* Predicate types for the JSON facts emitted *)
type hack =
| ClassConstDeclaration
| ClassConstDefinition
| ClassDeclaration
| ClassDefinition
| DeclarationComment
| DeclarationLocation
| DeclarationSpan
| EnumDeclaration
| EnumDefinition
| Enumerator
| FileDeclarations
| FileXRefs
| FunctionDeclaration
| FunctionDefinition
| GlobalConstDeclaration
| GlobalConstDefinition
| InheritedMembers
| InterfaceDeclaration
| InterfaceDefinition
| MemberCluster
| MethodDeclaration
| MethodDefinition
| MethodOccurrence
| MethodOverrides
| NamespaceDeclaration
| PropertyDeclaration
| PropertyDefinition
| TraitDeclaration
| TraitDefinition
| TypeConstDeclaration
| TypeConstDefinition
| TypedefDeclaration
| TypedefDefinition
| ModuleDeclaration
| ModuleDefinition
| FileCall
| GlobalNamespaceAlias
| IndexerInputsHash
| TypeInfo
[@@deriving ord]
type src = FileLines [@@deriving ord]
type gencode = GenCode [@@deriving ord]
type t =
| Hack of hack
| Src of src
| Gencode of gencode
[@@deriving ord]
type predicate = t
let compare_predicate = compare
let gencode_to_string = function
| GenCode -> "GenCode"
let hack_to_string = function
| ClassConstDeclaration -> "ClassConstDeclaration"
| ClassConstDefinition -> "ClassConstDefinition"
| ClassDeclaration -> "ClassDeclaration"
| ClassDefinition -> "ClassDefinition"
| DeclarationComment -> "DeclarationComment"
| DeclarationLocation -> "DeclarationLocation"
| DeclarationSpan -> "DeclarationSpan"
| EnumDeclaration -> "EnumDeclaration"
| EnumDefinition -> "EnumDefinition"
| Enumerator -> "Enumerator"
| FileDeclarations -> "FileDeclarations"
| FileXRefs -> "FileXRefs"
| FunctionDeclaration -> "FunctionDeclaration"
| FunctionDefinition -> "FunctionDefinition"
| GlobalConstDeclaration -> "GlobalConstDeclaration"
| GlobalConstDefinition -> "GlobalConstDefinition"
| InheritedMembers -> "InheritedMembers"
| InterfaceDeclaration -> "InterfaceDeclaration"
| InterfaceDefinition -> "InterfaceDefinition"
| MemberCluster -> "MemberCluster"
| MethodDeclaration -> "MethodDeclaration"
| MethodDefinition -> "MethodDefinition"
| MethodOccurrence -> "MethodOccurrence"
| MethodOverrides -> "MethodOverrides"
| NamespaceDeclaration -> "NamespaceDeclaration"
| PropertyDeclaration -> "PropertyDeclaration"
| PropertyDefinition -> "PropertyDefinition"
| TraitDeclaration -> "TraitDeclaration"
| TraitDefinition -> "TraitDefinition"
| TypeConstDeclaration -> "TypeConstDeclaration"
| TypeConstDefinition -> "TypeConstDefinition"
| TypedefDeclaration -> "TypedefDeclaration"
| TypedefDefinition -> "TypedefDefinition"
| ModuleDeclaration -> "ModuleDeclaration"
| ModuleDefinition -> "ModuleDefinition"
| FileCall -> "FileCall"
| GlobalNamespaceAlias -> "GlobalNamespaceAlias"
| IndexerInputsHash -> "IndexerInputsHash"
| TypeInfo -> "TypeInfo"
(* List of all predicates, in the order in which they should appear in the JSON.
This guarantee that facts are introduced before they are referenced. *)
let ordered_all =
[
Gencode GenCode;
Hack MethodOccurrence;
Hack NamespaceDeclaration;
Hack GlobalConstDeclaration;
Hack TypedefDeclaration;
Hack ModuleDeclaration;
Hack InterfaceDeclaration;
Hack TraitDeclaration;
Hack ClassDeclaration;
Hack EnumDeclaration;
Hack Enumerator;
Hack FunctionDeclaration;
Hack TypeConstDeclaration;
Hack TypeInfo;
Hack PropertyDeclaration;
Hack ClassConstDeclaration;
Hack MethodDeclaration;
Hack DeclarationSpan;
Hack DeclarationLocation;
Hack DeclarationComment;
Hack MemberCluster;
Hack InheritedMembers;
Hack GlobalConstDefinition;
Hack TypedefDefinition;
Hack ModuleDefinition;
Hack InterfaceDefinition;
Hack TraitDefinition;
Hack ClassDefinition;
Hack TypeConstDefinition;
Hack PropertyDefinition;
Hack ClassConstDefinition;
Hack EnumDefinition;
Hack FunctionDefinition;
Hack MethodDefinition;
Hack MethodOverrides;
Hack FileXRefs;
Hack FileDeclarations;
Hack FileCall;
Hack GlobalNamespaceAlias;
Hack IndexerInputsHash;
Src FileLines;
]
let src_to_string = function
| FileLines -> "FileLines"
let to_string = function
| Hack x -> "hack." ^ hack_to_string x ^ ".6"
| Src x -> "src." ^ src_to_string x ^ ".1"
| Gencode x -> "gencode." ^ gencode_to_string x ^ ".1"
(* Containers in inheritance relationships which share the four member
types (excludes enum) *)
type parent_container_type =
| ClassContainer
| InterfaceContainer
| TraitContainer
(* Get the container name and predicate type for a given parent
container kind. *)
let parent_decl_predicate parent_container_type =
match parent_container_type with
| ClassContainer -> ("class_", Hack ClassDeclaration)
| InterfaceContainer -> ("interface_", Hack InterfaceDeclaration)
| TraitContainer -> ("trait", Hack TraitDeclaration)
let get_parent_kind = function
| Ast_defs.Cenum_class _ ->
raise (Failure "Unexpected enum class as parent container kind")
| Ast_defs.Cenum -> raise (Failure "Unexpected enum as parent container kind")
| Ast_defs.Cinterface -> InterfaceContainer
| Ast_defs.Ctrait -> TraitContainer
| Ast_defs.Cclass _ -> ClassContainer
let should_cache = function
| Hack ClassConstDeclaration
| Hack ClassDeclaration
| Hack EnumDeclaration
| Hack Enumerator
| Hack FunctionDeclaration
| Hack GlobalConstDeclaration
| Hack InterfaceDeclaration
| Hack MethodDeclaration
| Hack PropertyDeclaration
| Hack TraitDeclaration
| Hack TypeConstDeclaration
| Hack TypedefDeclaration
| Hack ModuleDeclaration ->
true
| _ -> false
module Map = WrappedMap.Make (struct
type t = predicate
let compare = compare_predicate
end)
module Fact_acc = struct
type ownership_unit = string option [@@deriving eq, ord]
type owned_facts = (ownership_unit * json list) list
module JsonPredicateMap = WrappedMap.Make (struct
let compare_json = JsonKey.compare
let compare_predicate = compare
type t = ownership_unit * json * predicate [@@deriving ord]
end)
type t = {
resultJson: owned_facts Map.t;
factIds: Fact_id.t JsonPredicateMap.t;
mutable ownership_unit: ownership_unit;
mutable xrefs: Symbol_xrefs.pos_map option;
ownership: bool;
}
(* if ownership is set, we distinguish facts with different owners,
otherwise we "collapse" the ownership_unit to None. *)
let cache_key ownership ownership_unit json_key predicate =
if ownership then
(ownership_unit, json_key, predicate)
else
(None, json_key, predicate)
let add_to_owned_facts ownership_unit json = function
| (ou, jsons) :: l when equal_ownership_unit ou ownership_unit ->
(ownership_unit, json :: jsons) :: l
| l -> (ownership_unit, [json]) :: l
let update_glean_json
predicate json factkey_opt ({ ownership; ownership_unit; _ } as progress)
=
let update (opt_key : owned_facts option) : owned_facts option =
match opt_key with
| Some facts -> Some (add_to_owned_facts ownership_unit json facts)
| None -> failwith "All predicate keys should be in the map"
in
let resultJson = Map.update predicate update progress.resultJson in
let factIds =
match factkey_opt with
| None -> progress.factIds
| Some (fact_id, json_key) ->
JsonPredicateMap.add
(cache_key ownership ownership_unit json_key predicate)
fact_id
progress.factIds
in
{ progress with resultJson; factIds }
let add_fact
predicate json_key ?value ({ ownership_unit; ownership; _ } as progress) =
let value =
match value with
| None -> []
| Some v -> [("value", v)]
in
let fact_id = Fact_id.next () in
let fields =
[("id", Fact_id.to_json_number fact_id); ("key", json_key)] @ value
in
let json_fact = JSON_Object fields in
match
( should_cache predicate,
JsonPredicateMap.find_opt
(cache_key ownership ownership_unit json_key predicate)
progress.factIds )
with
| (false, _) ->
(fact_id, update_glean_json predicate json_fact None progress)
| (true, None) ->
( fact_id,
update_glean_json
predicate
json_fact
(Some (fact_id, json_key))
progress )
| (true, Some fid) -> (fid, progress)
let init ~ownership =
let resultJson =
List.fold ordered_all ~init:Map.empty ~f:(fun acc k -> Map.add k [] acc)
in
{
resultJson;
factIds = JsonPredicateMap.empty;
ownership_unit = None;
ownership;
xrefs = None;
}
let set_ownership_unit t ou = t.ownership_unit <- ou
let owned_facts_to_json ~ownership (predicate, owned_facts) =
let fact_object ~ou facts =
let obj =
[("predicate", JSON_String predicate); ("facts", JSON_Array facts)]
in
JSON_Object
(match ou with
| Some ou -> ("unit", JSON_String ou) :: obj
| None -> obj)
in
match ownership with
| true -> List.map owned_facts ~f:(fun (ou, facts) -> fact_object ~ou facts)
| false -> [fact_object ~ou:None (List.concat_map owned_facts ~f:snd)]
let to_json ({ ownership; _ } as progress) =
let preds =
List.map
~f:(fun pred -> (to_string pred, Map.find pred progress.resultJson))
ordered_all
in
List.concat_map preds ~f:(owned_facts_to_json ~ownership)
let set_pos_map t xrefs = t.xrefs <- Some xrefs
let get_pos_map t = t.xrefs
end |
OCaml Interface | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_predicate.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.
*
*)
(* Predicate types for the JSON facts emitted *)
type hack =
| ClassConstDeclaration
| ClassConstDefinition
| ClassDeclaration
| ClassDefinition
| DeclarationComment
| DeclarationLocation
| DeclarationSpan
| EnumDeclaration
| EnumDefinition
| Enumerator
| FileDeclarations
| FileXRefs
| FunctionDeclaration
| FunctionDefinition
| GlobalConstDeclaration
| GlobalConstDefinition
| InheritedMembers
| InterfaceDeclaration
| InterfaceDefinition
| MemberCluster
| MethodDeclaration
| MethodDefinition
| MethodOccurrence
| MethodOverrides
| NamespaceDeclaration
| PropertyDeclaration
| PropertyDefinition
| TraitDeclaration
| TraitDefinition
| TypeConstDeclaration
| TypeConstDefinition
| TypedefDeclaration
| TypedefDefinition
| ModuleDeclaration
| ModuleDefinition
| FileCall
| GlobalNamespaceAlias
| IndexerInputsHash
| TypeInfo
type src = FileLines
type gencode = GenCode
type t =
| Hack of hack
| Src of src
| Gencode of gencode
type predicate = t
(* Containers in inheritance relationships which share the four member
types (excludes enum) *)
type parent_container_type =
| ClassContainer
| InterfaceContainer
| TraitContainer
val parent_decl_predicate : parent_container_type -> string * t
val get_parent_kind : Ast_defs.classish_kind -> parent_container_type
module Fact_acc : sig
(* fact accumulator. This is used to maintain state through indexing
a batch. State is mostly generated facts *)
type t
val init : ownership:bool -> t
(** Returns a list of json objects. If [ownership] is false, objects
are of the form {'predicate': PREDICATE, 'facts': FACTS'} and all
predicates are different. If [ownership] is set, objects are of the form
{'unit: UNIT, 'predicate': PREDICATE, 'facts': FACTS}. *)
val to_json : t -> Hh_json.json list
(** set the current ownership unit. All facts added after the unit is set
will be marked with this owner. Initially, ownership_unit is set to None
which corresponds to fact with no owners. If [ownership] is false,
the ownership_unit is ignored. *)
val set_ownership_unit : t -> string option -> unit
val set_pos_map : t -> Symbol_xrefs.pos_map -> unit
val get_pos_map : t -> Symbol_xrefs.pos_map option
(** [add_fact pred fact t] returns an [id] and a new accumulator [t'].
If a fact already exists in [t] for this [pred], returns [t] unchanged
together with its id. Otherwise, [id] is a new fact id, and a fact
of the form { 'id': id, 'key': fact } is added to the accumulator.
If [ownership] is set, we distinguish between identical facts with different
owners *)
val add_fact :
predicate ->
Hh_json.json ->
?value:Hh_json.json ->
t ->
Symbol_fact_id.t * t
end |
OCaml | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_sym_def.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module Util = Symbol_json_util
type t = {
kind: SymbolDefinition.kind;
name: string;
full_name: string;
path: Relative_path.t option;
}
let resolve ctx occ ~sym_path =
Option.map
(ServerSymbolDefinition.go ctx None occ)
~f:(fun SymbolDefinition.{ name; full_name; kind; pos; _ } ->
let path =
if sym_path then
Some (Pos.filename pos)
else
None
in
{ kind; name; full_name; path })
let get_class_by_name ctx class_ =
match ServerSymbolDefinition.get_class_by_name ctx class_ with
| None -> `None
| Some cls when Util.is_enum_or_enum_class cls.Aast.c_kind -> `Enum
| Some cls -> `Class cls
let get_kind ctx class_ =
match ServerSymbolDefinition.get_class_by_name ctx class_ with
| None -> None
| Some cls -> Some cls.Aast.c_kind |
OCaml Interface | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_sym_def.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* This is mostly a wrapper around ServerSymbolDefinition, specialized to
what the indexer needs. Currently, resolve, based on ServerSymbolDefinition.go,
is very slow, and should be implemented more efficiently.
TODO document this interface *)
type t = {
kind: SymbolDefinition.kind;
name: string;
full_name: string;
path: Relative_path.t option;
}
val resolve :
Provider_context.t ->
Relative_path.t SymbolOccurrence.t ->
sym_path:bool ->
t option
val get_class_by_name :
Provider_context.t -> string -> [ `None | `Enum | `Class of Nast.class_ ]
val get_kind : Provider_context.t -> string -> Ast_defs.classish_kind option |
OCaml | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_sym_hash.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
(** Concatenation of hashes, sorted in lexicographic order. *)
type t = string
let mem t h =
let md5_bin = Md5.to_binary h in
let rec binary_search i j =
(* assume inclusive bound *)
assert (i <= j);
let m = (i + j) / 2 in
let m_h = String.sub t ~pos:(m * 16) ~len:16 in
if i = j then
String.equal m_h md5_bin
else if String.(m_h < md5_bin) then
binary_search (m + 1) j
else
binary_search i m
in
binary_search 0 ((String.length t / 16) - 1)
let read ~path : t =
Hh_logger.log "Reading hash table %s" path;
let channel = Sys_utils.open_in_no_fail path in
let next_md5 () =
try
Some
(Stdlib.really_input_string channel 24
|> Base64.decode_exn
|> String.sub ~pos:0 ~len:16)
with
| Caml.End_of_file -> None
in
let rec loop set =
match next_md5 () with
| None -> set
| Some md5 -> loop (String.Set.add set md5)
in
let set = loop String.Set.empty in
In_channel.close channel;
let res = String.concat (String.Set.to_list set) in
Hh_logger.log "Sym table has %d element" (String.Set.length set / 16);
if String.length res = 0 then failwith "Hash table is empty";
if not (String.length res mod 16 = 0) then
failwith "Hash table has incorrect format";
res |
OCaml Interface | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_sym_hash.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.
*
*)
open Hh_prelude
(** Set of Md5.t hashes *)
type t
val mem : t -> Md5.t -> bool
(** Construct a [t] from file [path]. File is a string of concatenated
base64-encoded md5 hash. Fails if file doesn't exist or unable to
deserialize *)
val read : path:string -> t |
OCaml | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_xrefs.ml | (*
* Copyright (c) Meta, 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 Fact_id = Symbol_fact_id
module PosMap = WrappedMap.Make (struct
let compare = Pos.compare
type t = Pos.t
end)
type fact_map = (Hh_json.json * Pos.t list) Fact_id.Map.t
type target_info = {
target: Hh_json.json;
receiver_type: Hh_json.json option;
}
type pos_map = target_info list PosMap.t
type t = {
fact_map: fact_map;
pos_map: pos_map;
}
let add { fact_map; pos_map } target_id pos target_info =
let fact_map =
Fact_id.Map.update
target_id
(function
| None -> Some (target_info.target, [pos])
| Some (json, refs) -> Some (json, pos :: refs))
fact_map
in
let pos_map =
PosMap.update
pos
(function
| None -> Some [target_info]
| Some tis -> Some (target_info :: tis))
pos_map
in
{ fact_map; pos_map }
let empty = { fact_map = Fact_id.Map.empty; pos_map = PosMap.empty } |
OCaml Interface | hhvm/hphp/hack/src/typing/write_symbol_info/symbol_xrefs.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 Fact_id = Symbol_fact_id
module PosMap : WrappedMap_sig.S with type key = Pos.t
(** maps a target fact id to the json representation of the corresponding fact,
and the positions of symbol that reference it *)
type fact_map = (Hh_json.json * Pos.t list) Fact_id.Map.t
type target_info = {
target: Hh_json.json;
receiver_type: Hh_json.json option;
}
(** maps a position to various info about the target *)
type pos_map = target_info list PosMap.t
(* Maps of XRefs, constructed for a given file *)
type t = private {
fact_map: fact_map;
pos_map: pos_map;
}
(* Updates both maps. It is expected that for a given fact_id, all json are equal. *)
val add : t -> Fact_id.t -> Pos.t -> target_info -> t
val empty : t |
OCaml | hhvm/hphp/hack/src/utils/aast_names_utils.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module A = Aast
let stmt_name = function
| A.Fallthrough -> "Fallthrough"
| A.Expr _ -> "Expr"
| A.Break -> "Break"
| A.Continue -> "Continue"
| A.Throw _ -> "Throw"
| A.Return _ -> "Return"
| A.Yield_break -> "Yield_break"
| A.Awaitall _ -> "Awaitall"
| A.If _ -> "If"
| A.Do _ -> "Do"
| A.While _ -> "While"
| A.Using _ -> "Using"
| A.For _ -> "For"
| A.Switch _ -> "Switch"
| A.Match _ -> "Match"
| A.Foreach _ -> "Foreach"
| A.Try _ -> "Try"
| A.Noop -> "Noop"
| A.Declare_local _ -> "Declare_local"
| A.Block _ -> "Block"
| A.Markup _ -> "Markup"
| A.AssertEnv _ -> "AssertEnv"
let expr_name = function
| A.Darray _ -> "Darray"
| A.Varray _ -> "Varray"
| A.Shape _ -> "Shape"
| A.ValCollection _ -> "ValCollection"
| A.KeyValCollection _ -> "KeyValCollection"
| A.Null -> "Null"
| A.This -> "This"
| A.True -> "True"
| A.False -> "False"
| A.Omitted -> "Omitted"
| A.Id _ -> "Id"
| A.Lvar _ -> "Lvar"
| A.Dollardollar _ -> "Dollardollar"
| A.Clone _ -> "Clone"
| A.Obj_get _ -> "Obj_get"
| A.Array_get _ -> "Array_get"
| A.Class_get _ -> "Class_get"
| A.Class_const _ -> "Class_const"
| A.Call _ -> "Call"
| A.FunctionPointer _ -> "FunctionPointer"
| A.Int _ -> "Int"
| A.Float _ -> "Float"
| A.String _ -> "String"
| A.String2 _ -> "String2"
| A.PrefixedString _ -> "PrefixedString"
| A.Yield _ -> "Yield"
| A.Await _ -> "Await"
| A.Tuple _ -> "Tuple"
| A.List _ -> "List"
| A.Cast _ -> "Cast"
| A.Unop _ -> "Unop"
| A.Binop _ -> "Binop"
| A.Pipe _ -> "Pipe"
| A.Eif _ -> "Eif"
| A.Is _ -> "Is"
| A.As _ -> "As"
| A.Upcast _ -> "Upcast"
| A.New _ -> "New"
| A.Efun _ -> "Efun"
| A.Lfun _ -> "Lfun"
| A.Xml _ -> "Xml"
| A.Import _ -> "Import"
| A.Collection _ -> "Collection"
| A.ExpressionTree _ -> "ExpressionTree"
| A.Lplaceholder _ -> "Lplaceholder"
| A.Method_caller _ -> "Method_caller"
| A.Pair _ -> "Pair"
| A.ET_Splice _ -> "ET_splice"
| A.EnumClassLabel _ -> "EnumClassLabel"
| A.ReadonlyExpr _ -> "Readonly"
| A.Hole _ -> "Hole"
| A.Invalid _ -> "Invalid"
| A.Package _ -> "Package" |
OCaml Interface | hhvm/hphp/hack/src/utils/aast_names_utils.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module A = Aast
val stmt_name : ('a, 'b) A.stmt_ -> string
val expr_name : ('a, 'b) A.expr_ -> string |
OCaml | hhvm/hphp/hack/src/utils/bigList.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type 'a t = int * 'a list
let empty = (0, [])
let cons hd (length, tl) = (length + 1, hd :: tl)
let create list = (List.length list, list)
let as_list (_length, list) = list
let is_empty (length, _list) = length = 0
let length (length, _list) = length
let decons (length, list) =
match list with
| [] -> None
| hd :: tl -> Some (hd, (length - 1, tl))
let map (length, list) ~f = (length, List.map list ~f)
let append x (length, list) =
(* List.append has several constant-factor performance tricks up its sleeve,
which I don't want to replicate here. That's why I'm calling both List.length
and List.append here, rather than doing only a single traversal of x.
In any case, by assumption, x isn't a big list so it doesn't matter. *)
(length + List.length x, List.append x list)
let rev_append x (length, list) =
(* See implementtion notes in [append] about efficiency. *)
(length + List.length x, List.rev_append x list)
let rev (length, list) = (length, List.rev list)
let rev_filter (_length, list) ~f =
let rec find ~f (length, acc) list =
match list with
| [] -> (length, acc)
| hd :: tl ->
if f hd then
find ~f (length + 1, hd :: acc) tl
else
find ~f (length, acc) tl
in
find ~f empty list
let filter t ~f = rev (rev_filter t ~f)
let split_n (length, list) n =
(* Could be more efficient if we copy the implementation of List.split_n, to avoid
iterating over [split] twice, but by assumption n is small so it doesn't matter. *)
let (split, rest) = List.split_n list n in
(split, (length - List.length split, rest))
let pp _elem_pp fmt t = Format.pp_print_int fmt (length t) |
OCaml Interface | hhvm/hphp/hack/src/utils/bigList.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.
*
*)
(** A BigList is like a list but with potentially huge contents.
It keeps a "length" integer, so that BigList.length can be O(1) rather than O(t). *)
type 'a t
val empty : 'a t
val cons : 'a -> 'a t -> 'a t
(* This is O(t) as it traverses input list to calculate length. *)
val create : 'a list -> 'a t
(* This is O(1). It simply discards its memory of the length. *)
val as_list : 'a t -> 'a list
val is_empty : 'a t -> bool
(* This is O(1). *)
val length : 'a t -> int
(* This is O(1). If the list is empty, returns None; otherwise returns Some(hd,tl). *)
val decons : 'a t -> ('a * 'a t) option
(** This is O(t).
[filter l ~f] returns all the elements of the list [l] that satisfy the predicate [p].
The order of the elements in the input list is preserved. *)
val filter : 'a t -> f:('a -> bool) -> 'a t
(** This is O(t).
[map f [a1; ...; an]] applies function [f] to [a1], [a2], ..., [an], in order,
and builds the list [[f a1; ...; f an]] with the results returned by [f]. *)
val map : 'a t -> f:('a -> 'b) -> 'b t
(** [append small big] appends a small list in front of a BigList, without traversing the BigList. *)
val append : 'a list -> 'a t -> 'a t
(** [rev_appends small big] a small list in front of a BigList, without traversing the BigList.
It is like BigList.append (List.rev small) big, but more efficient on the small list. *)
val rev_append : 'a list -> 'a t -> 'a t
(** List reversal. This is O(t). *)
val rev : 'a t -> 'a t
(** [split t n] splits of the first n elements of t, without traversing
the remainder of t. It is O(n). *)
val split_n : 'a t -> int -> 'a list * 'a t
val pp : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit |
OCaml | hhvm/hphp/hack/src/utils/cli_args.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 Core
include Cli_args_sig.Types
let files_to_check_range_to_json (range : files_to_check_range) : Hh_json.json =
let range_properties =
match range.to_prefix_excl with
| Some to_prefix_excl ->
[
( "to_prefix_excl",
Hh_json.JSON_String (Relative_path.suffix to_prefix_excl) );
]
| None -> []
in
let range_properties =
match range.from_prefix_incl with
| Some from_prefix_incl ->
let from_prefix_incl =
( "from_prefix_incl",
Hh_json.JSON_String (Relative_path.suffix from_prefix_incl) )
in
from_prefix_incl :: range_properties
| None -> range_properties
in
Hh_json.JSON_Object range_properties
let files_to_check_spec_to_json (files_to_check_spec : files_to_check_spec) :
Hh_json.json =
match files_to_check_spec with
| Range (range : files_to_check_range) -> files_to_check_range_to_json range
| Prefix (prefix : Relative_path.t) ->
Hh_json.JSON_String (Relative_path.suffix prefix)
let get_save_state_spec_json (spec : save_state_spec_info) : string =
let files_to_check_spec_list =
List.map ~f:files_to_check_spec_to_json spec.files_to_check
in
let (properties : (string * Hh_json.json) list) =
[
("gen_with_errors", Hh_json.JSON_Bool spec.gen_with_errors);
("files_to_check", Hh_json.JSON_Array files_to_check_spec_list);
("filename", Hh_json.JSON_String spec.filename);
]
in
Hh_json.json_to_string ~pretty:true (Hh_json.JSON_Object properties)
let save_state_spec_json_example =
{
files_to_check =
[
Prefix (Relative_path.from_root ~suffix:"/some/path/prefix1");
Range
{
from_prefix_incl =
Some (Relative_path.from_root ~suffix:"/from/path/prefix1");
to_prefix_excl =
Some (Relative_path.from_root ~suffix:"/to/path/prefix1");
};
Range
{
from_prefix_incl =
Some (Relative_path.from_root ~suffix:"/from/path/prefix2");
to_prefix_excl =
Some (Relative_path.from_root ~suffix:"/to/path/prefix2");
};
Range
{
from_prefix_incl =
Some (Relative_path.from_root ~suffix:"/from/path/only");
to_prefix_excl = None;
};
Range
{
from_prefix_incl = None;
to_prefix_excl =
Some (Relative_path.from_root ~suffix:"/to/path/only");
};
];
filename = "/some/dir/some_filename";
gen_with_errors = true;
}
let save_state_spec_json_descr =
Printf.sprintf
{|A JSON specification of how and what to save, e.g.:
%s
|}
(get_save_state_spec_json save_state_spec_json_example)
(* TODO: gen examples *)
let saved_state_json_descr =
{|A JSON specification for how to initialize with a saved state.
Saved state JSON looks like this:
{
"state": <saved state filename>,
"corresponding_base_revision" : <Mercurial commit hash>,
"deptable": <dependency table filename>,
"changes": [array of files changed since that saved state]
}
For example:
{
"deptable": "/home/unixname/saved-states/ss1.sql",
"state": "/home/unixname/saved-states/ss1",
"changes": [],
"prechecked_changes": [],
"corresponding_base_revision": "bab0de0041defb4d7a5d520d224aa4922ed04d37"
}
You can put this saved state JSON into a file and pass this JSON as the argument:
{
"from_file": "/home/unixname/saved-states/ss1.json"
}
Alternatively, you can pass this JSON as the argument, with the saved state JSON embedded:
{
"data_dump":
{
"deptable": "/home/unixname/saved-states/ss1.sql",
"state": "/home/unixname/saved-states/ss1",
"changes": [],
"prechecked_changes": [],
"corresponding_base_revision": "bab0de0041defb4d7a5d520d224aa4922ed04d37"
}
}
|}
let get_path (key : string) json_obj : Relative_path.t option =
let value = Hh_json.Access.get_string key json_obj in
match value with
| Ok ((value : string), _keytrace) ->
Some (Relative_path.from_root ~suffix:value)
| Error _ -> None
let get_spec (spec_json : Hh_json.json) : files_to_check_spec =
try
Prefix (Relative_path.from_root ~suffix:(Hh_json.get_string_exn spec_json))
with
| _ ->
let from_prefix_incl = get_path "from_prefix_incl" (spec_json, []) in
let to_prefix_excl = get_path "to_prefix_excl" (spec_json, []) in
Range { from_prefix_incl; to_prefix_excl }
let parse_save_state_json ((json : Hh_json.json), _keytrace) =
Hh_json.Access.(
let files_to_check =
Option.value
~default:[]
(Hh_json.(get_field_opt (get_array "files_to_check")) json)
in
let files_to_check = List.map files_to_check ~f:get_spec in
let json = return json in
json >>= get_string "filename" >>= fun (filename, _filename_keytrace) ->
json >>= get_bool "gen_with_errors"
>>= fun (gen_with_errors, _gen_with_errors_keytrace) ->
return { files_to_check; filename; gen_with_errors })
let get_save_state_spec (v : string option) :
(save_state_spec_info option, string) result =
match v with
| None -> Ok None
| Some blob ->
Hh_json.Access.(
let json = Hh_json.json_of_string blob in
let json = return json in
let parsed_spec_result = json >>= parse_save_state_json in
(match parsed_spec_result with
| Ok ((parsed_spec : save_state_spec_info), _keytrace) ->
Hh_logger.log "Parsed save state spec, everything's good";
Ok (Some parsed_spec)
| Error spec_failure ->
let message =
Printf.sprintf
"Parsing failed:\n%s\nSee input: %s\n"
(access_failure_to_string spec_failure)
blob
in
Error message))
let parse_saved_state_json (json, _keytrace) =
let array_to_path_list =
List.map ~f:(fun file ->
Relative_path.from_root ~suffix:(Hh_json.get_string_exn file))
in
let prechecked_changes =
Hh_json.(get_field_opt (Access.get_array "prechecked_changes")) json
in
let prechecked_changes = Option.value ~default:[] prechecked_changes in
let json = Hh_json.Access.return json in
Hh_json.Access.(
json >>= get_string "state" >>= fun (state, _state_keytrace) ->
json >>= get_string "corresponding_base_revision"
>>= fun (for_base_rev, _for_base_rev_keytrace) ->
json >>= get_string "deptable" >>= fun (deptable, _deptable_keytrace) ->
let compressed_deptable =
match json >>= get_val "compressed_deptable" |> to_option with
| Some (Hh_json.JSON_String path) -> Some path
| _ -> None
in
json >>= get_array "changes" >>= fun (changes, _) ->
let naming_changes =
match json >>= get_val "naming_changes" with
| Ok (Hh_json.JSON_Array files, _) -> array_to_path_list files
| _ -> []
in
let prechecked_changes = array_to_path_list prechecked_changes in
let changes = array_to_path_list changes in
return
{
naming_table_path = state;
corresponding_base_revision = for_base_rev;
deptable_fn = deptable;
compressed_deptable_fn = compressed_deptable;
prechecked_changes;
changes;
naming_changes;
})
let get_saved_state_spec (v : string option) :
(saved_state_target_info option, string) result =
match v with
| None -> Ok None
| Some blob ->
let json = Hh_json.json_of_string blob in
let json = Hh_json.Access.return json in
Hh_json.Access.(
let data_dump_parse_result =
json >>= get_obj "data_dump" >>= parse_saved_state_json
in
let from_file_parse_result =
json >>= get_string "from_file"
>>= fun (filename, _filename_keytrace) ->
let contents = Sys_utils.cat filename in
let json = Hh_json.json_of_string contents in
Hh_json.Access.return json >>= parse_saved_state_json
in
(match (data_dump_parse_result, from_file_parse_result) with
| (Ok (parsed_data_dump, _), Ok (_parsed_from_file, _)) ->
Hh_logger.log
"Warning - %s"
("Parsed saved state target from both JSON blob data dump"
^ " and from contents of file.");
Hh_logger.log "Preferring data dump result";
Ok (Some parsed_data_dump)
| (Ok (parsed_data_dump, _), Error _) -> Ok (Some parsed_data_dump)
| (Error _, Ok (parsed_from_file, _)) -> Ok (Some parsed_from_file)
| (Error data_dump_failure, Error from_file_failure) ->
let message =
Printf.sprintf
"Parsing failed:\n data dump failure: %s\n from_file failure: %s\nSee input: %s\n"
(access_failure_to_string data_dump_failure)
(access_failure_to_string from_file_failure)
blob
in
Error message))
let legacy_hot_decls_path_for_target_info { naming_table_path; _ } =
naming_table_path ^ ".decls"
let shallow_hot_decls_path_for_target_info { naming_table_path; _ } =
naming_table_path ^ ".shallowdecls"
let naming_sqlite_path_for_target_info { naming_table_path; _ } =
naming_table_path ^ "_naming.sql"
let errors_path_for_target_info { naming_table_path; _ } =
naming_table_path ^ ".err" |
OCaml Interface | hhvm/hphp/hack/src/utils/cli_args.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 Cli_args_sig.S |
OCaml | hhvm/hphp/hack/src/utils/cli_args_sig.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 Types = struct
type saved_state_target_info = {
changes: Relative_path.t list;
[@printer Utils.pp_large_list Relative_path.pp]
naming_changes: Relative_path.t list;
[@printer Utils.pp_large_list Relative_path.pp]
corresponding_base_revision: string;
deptable_fn: string;
compressed_deptable_fn: string option;
prechecked_changes: Relative_path.t list;
[@printer Utils.pp_large_list Relative_path.pp]
naming_table_path: string;
}
[@@deriving show]
(* The idea of a file range necessarily means that the hypothetical list
of them is sorted in some way. It is valid to have None as either endpoint
because that simply makes it open-ended. For example, a range of files
{ None - "/some/path" } includes all files with path less than /some/path *)
type files_to_check_range = {
from_prefix_incl: Relative_path.t option;
to_prefix_excl: Relative_path.t option;
}
type files_to_check_spec =
| Range of files_to_check_range
| Prefix of Relative_path.t
type save_state_spec_info = {
files_to_check: files_to_check_spec list;
(* The base name of the file into which we should save the naming table. *)
filename: string;
(* Indicates whether we should generate a state in the presence of errors. *)
gen_with_errors: bool;
}
end
module type S = sig
include module type of Types
val save_state_spec_json_descr : string
val get_save_state_spec :
string option -> (save_state_spec_info option, string) result
val get_save_state_spec_json : save_state_spec_info -> string
val saved_state_json_descr : string
val get_saved_state_spec :
string option -> (saved_state_target_info option, string) result
val legacy_hot_decls_path_for_target_info : saved_state_target_info -> string
val shallow_hot_decls_path_for_target_info : saved_state_target_info -> string
val naming_sqlite_path_for_target_info : saved_state_target_info -> string
val errors_path_for_target_info : saved_state_target_info -> string
end |
OCaml | hhvm/hphp/hack/src/utils/connection_tracker.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
(** The deal with logging is that we normally don't want it verbose, but if something went
wrong then we wish it already had been verbose for a while! As a compromise here's what we'll do...
If any connection-tracker encounters an unfortunately slow track, then we'll turn on verbose
logging for EVERY SINGLE track for the next 30 seconds.
There's one subtlety. A tracker object is moved client -> monitor -> server -> client.
It is therefore easy to detect whether a cross-process delay took anomalously long,
e.g. the delay between client sending to monitor and monitor receiving it.
But it's not easy to turn on verbose logging across ALL processes in responses to that.
As a workaround, each tracker object itself will contain its own snapshot of its own
process's value of [verbose_until], and as trackers move from one process to another
then they'll share this as a high-water-mark. *)
let ref_verbose_until = ref 0.
type key =
| Client_start_connect
| Client_opened_socket
| Client_sent_version
| Client_got_cstate
| Client_ready_to_send_handoff
| Monitor_received_handoff
| Monitor_ready
| Monitor_sent_ack_to_client
| Client_connected_to_monitor
| Server_sleep_and_check
| Server_monitor_fd_ready
| Server_got_tracker
| Server_got_client_fd
| Server_start_recheck
| Server_done_recheck
| Server_sent_diagnostics
| Server_start_handle_connection
| Server_sent_hello
| Client_received_hello
| Client_sent_connection_type
| Server_got_connection_type
| Server_waiting_for_cmd
| Client_ready_to_send_cmd
| Client_sent_cmd
| Server_got_cmd
| Server_done_full_recheck
| Server_start_handle
| Server_end_handle
| Client_received_response
[@@deriving eq, show]
type t = {
id: string;
rev_tracks: (key * float) list;
(** All the (trackname, timestamp) that have been tracked, in reverse order *)
verbose_until: float;
(** each [t] will carry around a snapshot of its process's ref_verbose_until,
so all the separate processes can learn about it. *)
}
let create () : t =
{
id = Random_id.short_string ();
rev_tracks = [];
verbose_until = !ref_verbose_until;
}
let get_telemetry (t : t) : Telemetry.t =
List.fold
t.rev_tracks
~init:(Telemetry.create ())
~f:(fun telemetry (key, value) ->
Telemetry.float_ telemetry ~key:(show_key key) ~value)
let log_id (t : t) : string = "t#" ^ t.id
let get_server_unblocked_time (t : t) : float option =
List.find_map t.rev_tracks ~f:(fun (key, time) ->
Option.some_if (equal_key key Server_start_handle) time)
let track
~(key : key)
?(time : float option)
?(log : bool = false)
?(msg : string option)
?(long_delay_okay = false)
(t : t) : t =
let tnow = Unix.gettimeofday () in
let time = Option.value time ~default:tnow in
ref_verbose_until := Float.max t.verbose_until !ref_verbose_until;
(* If it's been more than 3s since the last track, let's turn on verbose logging for 30s *)
begin
match t.rev_tracks with
| (_prev_key, prev_time) :: _
when Float.(time -. prev_time > 3.) && not long_delay_okay ->
ref_verbose_until := tnow +. 30.;
Hh_logger.log
"[%s] Connection_tracker unfortunately slow: %0.1fs. Verbose until %s\n%s"
(log_id t)
(time -. prev_time)
(Utils.timestring !ref_verbose_until)
(t.rev_tracks
|> List.rev
|> List.map ~f:(fun (key, time) ->
Printf.sprintf " >%s %s" (Utils.timestring time) (show_key key))
|> String.concat ~sep:"\n")
| _ -> ()
end;
let t =
{
t with
rev_tracks = (key, time) :: t.rev_tracks;
verbose_until = !ref_verbose_until;
}
in
if log || Float.(tnow < !ref_verbose_until) then
Hh_logger.log
"[%s] %s %s%s"
(log_id t)
(show_key key)
(Option.value msg ~default:"")
(if String.equal (Utils.timestring tnow) (Utils.timestring time) then
""
else
", was at " ^ Utils.timestring time);
t |
OCaml Interface | hhvm/hphp/hack/src/utils/connection_tracker.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.
*
*)
(** Allow to record the timestamps on multiple connection events. *)
type t
(** The connection events whose timestamps we want to track. *)
type key =
| Client_start_connect (** Client starts connection to monitor *)
| Client_opened_socket (** Has opened socket to monitor *)
| Client_sent_version (** Has sent version to the monitor *)
| Client_got_cstate (** Has received cstate from monitor *)
| Client_ready_to_send_handoff (** Will now send the tracker to monitor *)
| Monitor_received_handoff (** The monitor received handoff from client *)
| Monitor_ready (** Monitor is now ready to do its work *)
| Monitor_sent_ack_to_client (** Monitor has sent ack back to client *)
| Client_connected_to_monitor (** Received ack from monitor *)
| Server_sleep_and_check (** Server loops doing slices of major GC... *)
| Server_monitor_fd_ready (** ...until it detects data on monitor's FD *)
| Server_got_tracker (** Synchronously reads tracker from monitor *)
| Server_got_client_fd (** Synchronously reads the client FD from monitor *)
| Server_start_recheck (** serve_one_iteration is ready *)
| Server_done_recheck (** Finished processing all outstanding changes 1st *)
| Server_sent_diagnostics (** Sent diagnostics to persistent connection *)
| Server_start_handle_connection (** Now turns its attention to the client *)
| Server_sent_hello (** Has sent a hello message to the client *)
| Client_received_hello (** Received "hello" from server *)
| Client_sent_connection_type (** Sent connection_type to server *)
| Server_got_connection_type (** Received connection_type from client *)
| Server_waiting_for_cmd (** Ready to receive cmd from the client *)
| Client_ready_to_send_cmd (** Someone invoked ClientConnect.rpc *)
| Client_sent_cmd (** Client has sent the rpc command to server *)
| Server_got_cmd (** Received cmd from the client *)
| Server_done_full_recheck (** Does another recheck if needed *)
| Server_start_handle (** Sent a ping; next up ServerRpc.handle *)
| Server_end_handle (** Has finished ServerRpc.handle *)
| Client_received_response (** Received rpc response from server *)
(** Create a connection tracker, which allows to record the timestamps
on multiple connection events. *)
val create : unit -> t
(** Get the unique ID of the tracker. *)
val log_id : t -> string
(** Add a timestamp to the tracker for event specified by [key].
If [log] then we'll also print this to Hh_logger.
If [msg] then the message will be provided to Hh_logger to.
Normally if this track comes a long time after the previous track then
we'll consider it anomalous and turn on verbose logging.
But in some tracks (involving the persistent connection) we'll use
[long_delay_okay] to indicate that a long delay is normal and shouldn't
activate logging. *)
val track :
key:key ->
?time:float ->
?log:bool ->
?msg:string ->
?long_delay_okay:bool ->
t ->
t
(** Get the timestamp corresponding to last [Server_start_handle] event. *)
val get_server_unblocked_time : t -> float option
(** Retrieve all the timestamps recorded so far. *)
val get_telemetry : t -> Telemetry.t |
OCaml | hhvm/hphp/hack/src/utils/counters.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
exception WrongEnum
module Category = struct
[@@@warning "-32"]
type t =
| Decling
| Disk_cat
| Get_ast
| Get_decl
| Typecheck
[@@deriving ord, enum]
[@@@warning "+32"]
let to_string (category : t) : string =
match category with
| Decling -> "decling"
| Disk_cat -> "disk_cat"
| Get_ast -> "get_ast"
| Get_decl -> "get_decl"
| Typecheck -> "typecheck"
let count = (* max here is generated by ppx enum *) max + 1
let of_enum_exn (i : int) : t =
match of_enum i with
| Some cat -> cat
| None -> raise WrongEnum
end
module CategorySet = Caml.Set.Make (Category)
type time_in_sec = float
type counter = {
count: int; (** how many times did 'count' get called? *)
time: time_in_sec; (** cumulative duration of all calls to 'count' *)
}
let empty = { count = 0; time = 0. }
(** here we store each individual counter. *)
type t =
(* Making this a map causes 1% typing time regression. *)
counter Array.t
let counters : t ref = ref (Array.create ~len:Category.count empty)
let restore_state (new_state : t) : unit = counters := new_state
let reset () : t =
let old_counters = !counters in
counters := Array.create ~len:Category.count empty;
old_counters
let get_counter (category : Category.t) : counter =
!counters.(Category.to_enum category)
let set_counter (category : Category.t) (counts : counter) : unit =
!counters.(Category.to_enum category) <- counts
let get_time (category : Category.t) : unit -> time_in_sec =
match category with
| Category.Disk_cat ->
(* Wall-clock time, implemented in C:
let t = gettimeofday() in t.tv_sec + t.tv_usec / 1e6 *)
Unix.gettimeofday
| Category.Typecheck
| Category.Decling
| Category.Get_ast
| Category.Get_decl ->
(* CPU time, excluding I/O, implemented in C in one of three ways depending on ocaml compilation flags:
1. let r = getrusage(RUSAGE_SELF) in r.ru_utime.tv_sec + r.ru_utime.tv_usec / 1e6
2. let t = times() in t.tms_utime + t.tms_stime
3. clock() / CLOCKS_PER_SPEC *)
Stdlib.Sys.time
let get_time_label (category : Category.t) : string =
match category with
| Category.Disk_cat -> "walltime"
| Category.Typecheck
| Category.Decling
| Category.Get_ast
| Category.Get_decl ->
"cputime"
let count (category : Category.t) (f : unit -> 'a) : 'a =
let get_time = get_time category in
let tally = get_counter category in
let start_time = get_time () in
Utils.try_finally ~f ~finally:(fun () ->
set_counter
category
{
count = tally.count + 1;
time = tally.time +. get_time () -. start_time;
})
let read_time (category : Category.t) : time_in_sec =
(get_counter category).time
let get_counters () : Telemetry.t =
let telemetry_of_counter category counter =
Telemetry.create ()
|> Telemetry.int_ ~key:"count" ~value:counter.count
|> Telemetry.float_ ~key:(get_time_label category) ~value:counter.time
in
let telemetry =
Array.foldi
~f:(fun i telemetry counter ->
let category = Category.of_enum_exn i in
let telemetry =
Telemetry.object_
telemetry
~key:(Category.to_string category)
~value:(telemetry_of_counter category counter)
in
telemetry)
!counters
~init:(Telemetry.create ())
in
telemetry |
OCaml Interface | hhvm/hphp/hack/src/utils/counters.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 Category : sig
(** Care: each of these entries adds up to telemetry in [HackEventLogger.ProfileTypeCheck.get_stats],
and we should keep the number small... 5 to 10 items here are fine, but more will be a problem. *)
type t =
| Decling
(** Decling is used when --config profile_decling=TopCounts; it's counted by all [Typing_classes_heap] decl accessors.
It measures cpu-time. *)
| Disk_cat
(** Disk_cat is counted every use of [Disk.cat] and measures wall-time. *)
| Get_ast
(** Get_ast is counted for [Ast_provider.get_ast_with_error], fetching the full ASTs of the files we're typechecking.
It is notionally inclusive of Disk_cat time, but it measures cpu-time and so
doesn't count the time spent waiting for IO. *)
| Get_decl
(** Get_decl is counted for [Direct_decl_utils.direct_decl_parse], fetching decls off disk of the types we depend upon.
It is notionally inclusive of Disk_cat time, but it measures cpu-time and so
doesn't count the time spent waiting for IO. *)
| Typecheck
(** Typecheck is counted for [Typing_top_level], typechecking top-level entity. It is inclusive of Get_ast and Get_decl time.
It measures cpu-time. *)
end
module CategorySet : Set.S with type elt = Category.t
type time_in_sec = float
(** state is a global mutable variable, accumulating all counts *)
type t
(** reset will zero all counters, adjust the global mutable state,
and return the previous state. You should 'restore_state' when done,
in case your caller had been doing their own count.
Categories from [enabled_categories] will be enabled
and all others will be disabled. *)
val reset : unit -> t
(** restores global mutable state to what it was before you called 'reset' *)
val restore_state : t -> unit
val count : Category.t -> (unit -> 'a) -> 'a
val get_counters : unit -> Telemetry.t
val read_time : Category.t -> time_in_sec |
OCaml | hhvm/hphp/hack/src/utils/cpu_cycles.ml | (* This API deliberately does not expose a way to reset the counter, so
* as not to disturb programs that expect to be able to use it themselves.
*
* There are a bunch of caveats about what happens if your
* process is interrupted or if you get scheduled onto a different
* processor.
* *)
external cpu_cycles : unit -> int
= "ocaml_cpu_cycles" "ocaml_cpu_cycles" "noalloc" |
OCaml Interface | hhvm/hphp/hack/src/utils/cpu_cycles.mli | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* This `.mli` file was generated automatically. It may include extra
definitions that should not actually be exposed to the caller. If you notice
that this interface file is a poor interface, please take a few minutes to
clean it up manually, and then delete this comment once the interface is in
shape. *)
external cpu_cycles : unit -> int = "ocaml_cpu_cycles" "ocaml_cpu_cycles" |
OCaml | hhvm/hphp/hack/src/utils/decl_reference.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 =
| GlobalConstant of string
| Function of string
| Type of string
| Module of string
[@@deriving eq, show, ord] |
OCaml Interface | hhvm/hphp/hack/src/utils/decl_reference.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 t =
| GlobalConstant of string
| Function of string
| Type of string (** type, interface, trait, typedef, recorddef *)
| Module of string
[@@deriving eq, show, ord] |
hhvm/hphp/hack/src/utils/dune | ; splitted utils:utils
(library
(name trie)
(wrapped false)
(modules trie)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(libraries utils_core))
(library
(name utils_find)
(wrapped false)
(modules findUtils)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(libraries ignore relative_path))
(library
(name utils_multifile)
(wrapped false)
(modules multifile)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(libraries relative_path sys_utils))
(library
(name utils_php_escape)
(wrapped false)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(modules php_escaping)
(libraries collections sys_utils))
(library
(name utils_www_root)
(wrapped false)
(modules wwwroot)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(libraries sys_utils))
(library
(name utils_exit)
(wrapped false)
(modules exit)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(libraries global_config utils_core))
(library
(name temp_file)
(wrapped false)
(modules tempfile)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(libraries sys_utils))
(library
(name temp_file_lwt)
(wrapped false)
(modules tempfile_lwt)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(libraries lwt_utils sys_utils))
; end of splitted utils:utils
(library
(name mutable_accumulator)
(wrapped false)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(modules mutable_accumulator))
(library
(name counters)
(wrapped false)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(modules counters)
(libraries collections utils_core))
(library
(name relative_path)
(wrapped false)
(modules relative_path)
(libraries collections sys_utils)
(preprocess
(pps
ppx_hash
ppx_sexp_conv
ppx_yojson_conv
lwt_ppx
ppx_deriving.std
ppx_deriving.enum)))
(library
(name cli_args)
(wrapped false)
(modules cli_args cli_args_sig)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(libraries collections hh_json relative_path sys_utils utils_core))
(library
(name decl_reference)
(wrapped false)
(modules decl_reference)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum)))
(library
(name pos)
(wrapped false)
(modules
file_pos_large
file_pos_small
line_break_map
pos
pos_source
pos_span_tiny)
(preprocess
(pps ppx_hash ppx_sexp_conv lwt_ppx ppx_deriving.std ppx_deriving.enum))
(libraries relative_path))
(library
(name stack_utils)
(wrapped false)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(modules stack_utils))
(library
(name utils_ocaml_overrides)
(wrapped false)
(modules ocaml_overrides)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(libraries disk))
(library
(name symbol)
(wrapped false)
(modules symbolDefinition symbolOccurrence)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(libraries annotated_ast naming_special_names pos))
(library
(name server_load_flag)
(wrapped false)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(modules serverLoadFlag))
(library
(name promise)
(wrapped false)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(modules promise))
(library
(name signed_source)
(wrapped false)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(libraries utils_core)
(modules signed_source))
(library
(name lwt_utils)
(wrapped false)
(modules lwt_message_queue lwt_utils)
(libraries core_kernel exec_command lwt lwt.unix process promise utils_core)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum)))
(library
(name connection_tracker)
(wrapped false)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(libraries utils_core)
(modules connection_tracker))
(library
(name aast_names_utils)
(wrapped false)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(libraries annotated_ast utils_core)
(modules aast_names_utils))
(library
(name biglist)
(wrapped false)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(libraries utils_core)
(modules bigList))
(library
(name memory_stats)
(wrapped false)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.enum))
(libraries utils_core sys_utils)
(modules memory_stats))
(library
(name gc_utils)
(modules gc_utils)
(libraries utils_core))
(library
(name visitors_runtime)
(wrapped false)
(modules visitors_runtime)
(libraries core_kernel visitors.runtime)) |
|
Rust | hhvm/hphp/hack/src/utils/escaper.rs | // Copyright (c) 2019, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
//
// Implementation of string escaping logic.
// See http://php.net/manual/en/language.types.string.php
use std::borrow::Cow;
use std::error::Error;
use std::fmt;
use std::io::Write;
use bstr::BStr;
use bstr::BString;
use bumpalo::Bump;
#[derive(Debug)]
pub struct InvalidString {
pub msg: String,
}
impl fmt::Display for InvalidString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.msg)
}
}
impl Error for InvalidString {
fn description(&self) -> &str {
&self.msg
}
}
impl<'a> From<&'a str> for InvalidString {
fn from(x: &'a str) -> Self {
Self {
msg: String::from(x),
}
}
}
trait GrowableBytes {
fn push(&mut self, byte: u8);
fn extend_from_slice(&mut self, slice: &[u8]);
}
impl GrowableBytes for Vec<u8> {
fn push(&mut self, byte: u8) {
self.push(byte)
}
fn extend_from_slice(&mut self, slice: &[u8]) {
self.extend_from_slice(slice)
}
}
impl GrowableBytes for bumpalo::collections::Vec<'_, u8> {
fn push(&mut self, byte: u8) {
self.push(byte)
}
fn extend_from_slice(&mut self, slice: &[u8]) {
self.extend_from_slice(slice)
}
}
fn is_printable(c: u8) -> bool {
(b' '..=b'~').contains(&c)
}
pub fn is_lit_printable(c: u8) -> bool {
is_printable(c) && c != b'\\' && c != b'\"'
}
fn is_hex(c: u8) -> bool {
(b'0'..=b'9').contains(&c) || (b'a'..=b'f').contains(&c) || (b'A'..=b'F').contains(&c)
}
fn is_oct(c: u8) -> bool {
(b'0'..=b'7').contains(&c)
}
/// This escapes a string using the format understood by the assembler
/// and php serialization. The assembler and php serialization probably
/// don't actually have the same rules but this should safely fit in both.
/// It will escape $ in octal so that it can also be used as a PHP double
/// string.
pub fn escape_char(c: u8) -> Option<Cow<'static, [u8]>> {
match c {
b'\n' => Some((&b"\\n"[..]).into()),
b'\r' => Some((&b"\\r"[..]).into()),
b'\t' => Some((&b"\\t"[..]).into()),
b'\\' => Some((&b"\\\\"[..]).into()),
b'"' => Some((&b"\\\""[..]).into()),
b'$' => None,
c if is_lit_printable(c) => None,
c => {
let mut r = vec![];
write!(r, "\\{:03o}", c).unwrap();
Some(r.into())
}
}
}
/// `impl Into<..>` allows escape to take a String, consider the following,
/// let a = {
/// let b = String::from("b");
/// escape(b)
/// };
///
/// Replacing `escape(b)` by `escape(&b)` leaks a reference of b to outer scope hence
/// compilation error.
pub fn escape<'a>(s: impl Into<Cow<'a, str>>) -> Cow<'a, str> {
escape_by(s.into(), escape_char)
}
pub fn escape_bstr<'a>(s: impl Into<Cow<'a, BStr>>) -> Cow<'a, BStr> {
escape_bstr_by(s.into(), escape_char)
}
fn cow_str_to_bytes(s: Cow<'_, str>) -> Cow<'_, [u8]> {
match s {
Cow::Borrowed(s) => s.as_bytes().into(),
Cow::Owned(s) => s.into_bytes().into(),
}
}
fn cow_bstr_to_bytes(s: Cow<'_, BStr>) -> Cow<'_, [u8]> {
match s {
Cow::Borrowed(s) => <&[u8]>::from(s).into(),
Cow::Owned(s) => <Vec<u8>>::from(s).into(),
}
}
pub fn escape_by<F>(s: Cow<'_, str>, f: F) -> Cow<'_, str>
where
F: Fn(u8) -> Option<Cow<'static, [u8]>>,
{
let r = escape_byte_by(cow_str_to_bytes(s), f);
// Safety: Since the input is &str these conversions should be safe.
match r {
Cow::Borrowed(s) => unsafe { std::str::from_utf8_unchecked(s) }.into(),
Cow::Owned(s) => unsafe { String::from_utf8_unchecked(s) }.into(),
}
}
pub fn escape_bstr_by<'a, F>(s: Cow<'a, BStr>, f: F) -> Cow<'a, BStr>
where
F: Fn(u8) -> Option<Cow<'static, [u8]>>,
{
let r = escape_byte_by(cow_bstr_to_bytes(s), f);
match r {
Cow::Borrowed(s) => <&BStr>::from(s).into(),
Cow::Owned(s) => BString::from(s).into(),
}
}
fn escape_byte_by<F: Fn(u8) -> Option<Cow<'static, [u8]>>>(
cow: Cow<'_, [u8]>,
f: F,
) -> Cow<'_, [u8]> {
let mut c = vec![];
let mut copied = false;
let s = cow.as_ref();
for i in 0..s.len() {
match f(s[i]) {
None if copied => c.push(s[i]),
Some(cc) => {
if copied {
c.extend_from_slice(cc.as_ref());
} else {
c.extend_from_slice(&s[..i]);
c.extend_from_slice(cc.as_ref());
copied = true;
}
}
_ => {}
}
}
if copied { c.into() } else { cow }
}
fn codepoint_to_utf8(n: u32, output: &mut impl GrowableBytes) -> Result<(), InvalidString> {
if n <= 0x7f {
output.push(n as u8);
} else if n <= 0x7ff {
output.push(0xc0 | (n >> 6) as u8);
output.push(0x80 | (n & 0b111111) as u8);
} else if n <= 0x00ffff {
output.push(0xe0 | (n >> 12) as u8);
output.push(0x80 | ((n >> 6) & 0b111111) as u8);
output.push(0x80 | (n & 0x3f) as u8);
} else if n <= 0x10ffff {
output.push(0xf0 | (n >> 18) as u8);
output.push(0x80 | ((n >> 12) & 0b111111) as u8);
output.push(0x80 | ((n >> 6) & 0b111111) as u8);
output.push(0x80 | (n & 0x3f) as u8);
} else {
return Err("UTF-8 codepoint too large".into());
}
Ok(())
}
fn parse_int(s: &[u8], base: u32) -> Result<u32, InvalidString> {
// input `s` can be assumed only contains ascii digits and 'aA' - 'fF',
// it is safe to call from_utf8 here.
let s = match std::str::from_utf8(s) {
Ok(s) => s,
_ => {
return Err("invalid numeric escape".into());
}
};
let s = u32::from_str_radix(s, base);
match s {
Ok(v) => Ok(v),
_ => Err("invalid numeric escape".into()),
}
}
fn parse_numeric_escape(trim_to_byte: bool, s: &[u8], base: u32) -> Result<u8, InvalidString> {
match parse_int(s, base) {
Ok(v) => {
if !trim_to_byte && (v > 255) {
Err("Invalid UTF-8 code point.".into())
} else {
Ok(v as u8)
}
}
Err(_) => Err("Invalid UTF-8 code point.".into()),
}
}
#[derive(PartialEq)]
pub enum LiteralKind {
LiteralHeredoc,
LiteralDoubleQuote,
LiteralLongString,
}
/// Copies `s` into `output`, replacing escape sequences with the characters
/// they represent.
///
/// The output is NOT guaranteed to be valid UTF-8. While this function will
/// return `Err` in some cases where the input contains an escape sequence
/// specifying an invalid codepoint, it will return invalid UTF-8 in some
/// circumstances (e.g., for invalid UTF-8 encoded as hex or octal byte escapes,
/// or UTF-16 encoded as \u escapes).
fn unescape_literal(
literal_kind: LiteralKind,
s: &str,
output: &mut impl GrowableBytes,
) -> Result<(), InvalidString> {
unescape_literal_bytes(literal_kind, s.as_bytes(), output)
}
/// Helper method for `unescape_literal`
fn unescape_literal_bytes(
literal_kind: LiteralKind,
s: &[u8],
output: &mut impl GrowableBytes,
) -> Result<(), InvalidString> {
struct Scanner<'a> {
s: &'a [u8],
i: usize,
}
impl<'a> Scanner<'a> {
fn new(s: &'a [u8]) -> Self {
Self { s, i: 0 }
}
fn is_empty(&self) -> bool {
self.i >= self.s.len()
}
fn next(&mut self) -> Result<u8, InvalidString> {
if self.i >= self.s.len() {
return Err("string ended early".into());
}
let r = self.s[self.i];
self.i += 1;
Ok(r)
}
fn take_if(&mut self, f: impl Fn(u8) -> bool, size: usize) -> &'a [u8] {
let l = usize::min(size + self.i, self.s.len());
let mut c = self.i;
while c < l && f(self.s[c]) {
c += 1;
}
let r = &self.s[self.i..c];
self.i = c;
r
}
fn peek(&self) -> Option<u8> {
if self.i < self.s.len() {
Some(self.s[self.i])
} else {
None
}
}
fn back(&mut self) {
if self.i > 0 {
self.i -= 1;
}
}
}
let mut s = Scanner::new(s);
while !s.is_empty() {
let c = s.next()?;
if c != b'\\' || s.is_empty() {
output.push(c);
} else {
let c = s.next()?;
match c {
b'a' if literal_kind == LiteralKind::LiteralLongString => output.push(b'\x07'),
b'b' if literal_kind == LiteralKind::LiteralLongString => output.push(b'\x08'),
b'\'' => output.extend_from_slice(b"\\\'"),
b'n' => match literal_kind {
LiteralKind::LiteralLongString => {}
_ => output.push(b'\n'),
},
b'r' => match literal_kind {
LiteralKind::LiteralLongString => {}
_ => output.push(b'\r'),
},
b't' => output.push(b'\t'),
b'v' => output.push(b'\x0b'),
b'e' => output.push(b'\x1b'),
b'f' => output.push(b'\x0c'),
b'\\' => output.push(b'\\'),
b'?' if literal_kind == LiteralKind::LiteralLongString => output.push(b'\x3f'),
b'$' if literal_kind != LiteralKind::LiteralLongString => output.push(b'$'),
b'\"' => match literal_kind {
LiteralKind::LiteralDoubleQuote | LiteralKind::LiteralLongString => {
output.push(b'\"')
}
_ => output.extend_from_slice(b"\\\""),
},
b'u' if literal_kind != LiteralKind::LiteralLongString
&& s.peek() == Some(b'{') =>
{
let _ = s.next()?;
let unicode = s.take_if(|c| c != b'}', 6);
let n = parse_int(unicode, 16)?;
codepoint_to_utf8(n, output)?;
let n = s.next()?;
if n != b'}' {
return Err("Invalid UTF-8 escape sequence".into());
}
}
b'x' | b'X' => {
let hex = s.take_if(is_hex, 2);
if hex.is_empty() {
output.push(b'\\');
output.push(c);
} else {
let c = parse_numeric_escape(false, hex, 16)?;
output.push(c);
}
}
c if is_oct(c) => {
s.back();
let oct = s.take_if(is_oct, 3);
let c = parse_numeric_escape(true, oct, 8)?;
output.push(c);
}
c => {
output.push(b'\\');
output.push(c);
}
}
}
}
Ok(())
}
fn unescape_literal_into_string(
literal_kind: LiteralKind,
s: &str,
) -> Result<BString, InvalidString> {
let mut output = Vec::with_capacity(s.len());
unescape_literal(literal_kind, s, &mut output)?;
Ok(output.into())
}
fn unescape_literal_into_arena<'a>(
literal_kind: LiteralKind,
s: &str,
arena: &'a Bump,
) -> Result<&'a BStr, InvalidString> {
let mut output = bumpalo::collections::Vec::with_capacity_in(s.len(), arena);
unescape_literal(literal_kind, s, &mut output)?;
Ok(output.into_bump_slice().into())
}
fn unescape_literal_bytes_into_vec_u8(
literal_kind: LiteralKind,
s: &[u8],
) -> Result<Vec<u8>, InvalidString> {
let mut output = Vec::with_capacity(s.len());
unescape_literal_bytes(literal_kind, s, &mut output)?;
Ok(output)
}
pub fn unescape_literal_bytes_into_vec_bytes(s: &[u8]) -> Result<Vec<u8>, InvalidString> {
unescape_literal_bytes_into_vec_u8(LiteralKind::LiteralDoubleQuote, s)
}
pub fn unescape_double(s: &str) -> Result<BString, InvalidString> {
unescape_literal_into_string(LiteralKind::LiteralDoubleQuote, s)
}
pub fn unescape_heredoc(s: &str) -> Result<BString, InvalidString> {
unescape_literal_into_string(LiteralKind::LiteralHeredoc, s)
}
pub fn unescape_double_in<'a>(s: &str, arena: &'a Bump) -> Result<&'a BStr, InvalidString> {
unescape_literal_into_arena(LiteralKind::LiteralDoubleQuote, s, arena)
}
pub fn unescape_heredoc_in<'a>(s: &str, arena: &'a Bump) -> Result<&'a BStr, InvalidString> {
unescape_literal_into_arena(LiteralKind::LiteralHeredoc, s, arena)
}
/// Copies `s` into `output`, replacing escape sequences with the characters
/// they represent. The bytes added to `output` will be valid UTF-8.
fn unescape_single_or_nowdoc(
is_nowdoc: bool,
s: &str,
output: &mut impl GrowableBytes,
) -> Result<(), InvalidString> {
let s = s.as_bytes();
unescape_bytes_to_gb(is_nowdoc, s, output)
}
/// Copies `s` into `output`, replacing escape sequences with the characters
/// they represent. They bytes added to `output` are not guaranteed to be valid UTF-8, unless
/// `s` is solely valid UTF-8.
fn unescape_bytes_to_gb(
is_nowdoc: bool,
s: &[u8],
output: &mut impl GrowableBytes,
) -> Result<(), InvalidString> {
let len = s.len();
let mut idx = 0;
while idx < len {
let c = s[idx];
if is_nowdoc || c != b'\\' {
output.push(c)
} else {
idx += 1;
if !idx < len {
return Err("string ended early".into());
}
let c = s[idx];
match c {
b'\'' | b'\\' => output.push(c),
// unrecognized escapes are just copied over
_ => {
output.push(b'\\');
output.push(c);
}
}
}
idx += 1;
}
Ok(())
}
fn unescape_single_or_nowdoc_into_string(
is_nowdoc: bool,
s: &str,
) -> Result<String, InvalidString> {
let mut output = Vec::with_capacity(s.len());
unescape_single_or_nowdoc(is_nowdoc, s, &mut output)?;
// Safety: s is a valid &str, and unescape_single_or_nowdoc copies it into
// output, only adding and removing valid UTF-8 codepoints.
Ok(unsafe { String::from_utf8_unchecked(output) })
}
fn unescape_single_or_nowdoc_into_arena<'a>(
is_nowdoc: bool,
s: &str,
arena: &'a Bump,
) -> Result<&'a str, InvalidString> {
let mut output = bumpalo::collections::Vec::with_capacity_in(s.len(), arena);
unescape_single_or_nowdoc(is_nowdoc, s, &mut output)?;
// Safety: s is a valid &str, and unescape_single_or_nowdoc copies it into
// output, only adding and removing valid UTF-8 codepoints.
let string = unsafe { bumpalo::collections::String::from_utf8_unchecked(output) };
Ok(string.into_bump_str())
}
pub fn unescape_bytes(s: &[u8]) -> Result<Vec<u8>, InvalidString> {
let mut v8 = Vec::new();
unescape_bytes_to_gb(false, s, &mut v8)?;
Ok(v8)
}
pub fn unescape_single(s: &str) -> Result<String, InvalidString> {
unescape_single_or_nowdoc_into_string(false, s)
}
pub fn unescape_nowdoc(s: &str) -> Result<String, InvalidString> {
unescape_single_or_nowdoc_into_string(true, s)
}
pub fn unescape_single_in<'a>(s: &str, arena: &'a Bump) -> Result<&'a str, InvalidString> {
unescape_single_or_nowdoc_into_arena(false, s, arena)
}
pub fn unescape_nowdoc_in<'a>(s: &str, arena: &'a Bump) -> Result<&'a str, InvalidString> {
unescape_single_or_nowdoc_into_arena(true, s, arena)
}
pub fn unescape_long_string(s: &str) -> Result<BString, InvalidString> {
unescape_literal_into_string(LiteralKind::LiteralLongString, s)
}
pub fn unescape_long_string_in<'a>(s: &str, arena: &'a Bump) -> Result<&'a BStr, InvalidString> {
unescape_literal_into_arena(LiteralKind::LiteralLongString, s, arena)
}
pub fn extract_unquoted_string(
content: &str,
start: usize,
len: usize,
) -> Result<String, InvalidString> {
let substr = content
.get(start..start + len)
.ok_or_else(|| InvalidString::from("out of bounds or sliced at non-codepoint-boundary"))?;
Ok(unquote_str(substr).into())
}
/// Remove single quotes, double quotes, backticks, or heredoc/nowdoc delimiters
/// surrounding a string literal.
pub fn unquote_str(content: &str) -> &str {
let unquoted = unquote_slice(content.as_bytes());
// Safety: content is a valid &str. unquote_slice finds ASCII delimiters and
// removes the prefix and suffix surrounding them. Because it uses ASCII
// delimiters, we know it is slicing at codepoint boundaries.
unsafe { std::str::from_utf8_unchecked(unquoted) }
}
fn find(s: &[u8], needle: u8) -> Option<usize> {
for (i, &c) in s.iter().enumerate() {
if c == needle {
return Some(i);
}
}
None
}
fn rfind(s: &[u8], needle: u8) -> Option<usize> {
let mut i = s.len();
while i > 0 {
i -= 1;
if s[i] == needle {
return Some(i);
}
}
None
}
/// Remove single quotes, double quotes, backticks, or heredoc/nowdoc delimiters
/// surrounding a string literal. If the input slice is valid UTF-8, the output
/// slice will also be valid UTF-8.
pub fn unquote_slice(content: &[u8]) -> &[u8] {
if content.len() < 2 {
content
} else if content.starts_with(b"<<<") {
// The heredoc case
// These types of strings begin with an opening line containing <<<
// followed by a string to use as a terminator (which is optionally
// quoted), and end with a line containing only the terminator.
// We need to drop the opening line and terminator line.
match (find(content, b'\n'), rfind(content, b'\n')) {
(Some(start), Some(end)) => {
// An empty heredoc, this way, will have start >= end
if start >= end {
&[]
} else {
&content[start + 1..end]
}
}
_ => content,
}
} else {
let c1 = content[0];
let c2 = content[content.len() - 1];
if c1 == c2 && (c1 == b'\'' || c1 == b'"' || c1 == b'`') {
&content[1..content.len() - 1]
} else {
content
}
}
}
#[cfg(test)]
mod tests {
use bstr::B;
use pretty_assertions::assert_eq;
use super::*; // make assert_eq print huge diffs more human-readable
#[test]
fn unescape_single_or_nowdoc() {
assert_eq!(unescape_single("").unwrap(), "");
assert_eq!(unescape_nowdoc("").unwrap(), "");
assert_eq!(unescape_long_string("").unwrap(), "");
assert_eq!(unescape_double("").unwrap(), "");
assert_eq!(unescape_heredoc("").unwrap(), "");
assert_eq!(
unescape_single("home \\\\$").unwrap(),
"home \\$".to_string()
);
assert_eq!(unescape_nowdoc("home \\$").unwrap(), "home \\$".to_string());
assert_eq!(unescape_single("home \\'").unwrap(), "home '".to_string());
assert_eq!(unescape_nowdoc("home \\'").unwrap(), "home \\'".to_string());
assert_eq!(unescape_nowdoc("\\`").unwrap(), "\\`");
assert_eq!(unescape_single("\\a\\\'").unwrap(), "\\a'");
assert_eq!(unescape_long_string("\\a").unwrap(), "\x07");
assert_eq!(unescape_long_string("\\v").unwrap(), "\x0b");
assert_eq!(unescape_long_string("\\\'").unwrap(), "\\\'");
assert_eq!(unescape_long_string("\\\\").unwrap(), "\\");
assert_eq!(unescape_long_string("?").unwrap(), "\x3f");
assert_eq!(unescape_long_string("$").unwrap(), "$");
assert_eq!(unescape_long_string("\\b").unwrap(), "\x08");
assert_eq!(unescape_long_string("\\e").unwrap(), "\x1b");
assert_eq!(unescape_long_string("\\f").unwrap(), "\x0c");
assert_eq!(unescape_long_string("\\\"").unwrap(), "\"");
assert_eq!(unescape_long_string("\\`").unwrap(), "\\`");
assert_eq!(unescape_heredoc("\\\"").unwrap(), "\\\"");
assert_eq!(unescape_heredoc("\\p").unwrap(), "\\p");
assert_eq!(unescape_long_string("\\r").unwrap(), "");
assert_eq!(unescape_double("\\u{b1}").unwrap(), "±");
assert_eq!(unescape_double("\\x27\\x22").unwrap(), "\'\"");
assert_eq!(unescape_double("\\X27\\X22").unwrap(), "\'\"");
assert_eq!(
unescape_double("\\141\\156\\143\\150\\157\\162").unwrap(),
"anchor"
);
assert_eq!(unescape_long_string("\\xb1").unwrap(), B(&[177u8]));
let euro = "\u{20AC}"; // as bytes [226, 130, 172]
assert_eq!(
unescape_long_string(euro).unwrap(),
B(&[226u8, 130u8, 172u8])
);
assert_eq!(unescape_long_string("\\xb1").unwrap(), B(&[177u8]));
let euro = "\u{20AC}"; // as bytes [226, 130, 172]
assert_eq!(
unescape_long_string(euro).unwrap(),
B(&[226u8, 130u8, 172u8])
);
let invalid = r#"\u{D800}\u{DF1E}"#;
assert_eq!(
unescape_double(invalid).unwrap(),
B(&[237u8, 160u8, 128u8, 237u8, 188u8, 158u8])
);
}
#[test]
fn parse_int_test() {
assert_eq!(parse_int(b"2", 10).unwrap(), 2);
assert!(parse_int(b"h", 10).is_err());
assert_eq!(parse_int(b"12", 8).unwrap(), 10);
assert_eq!(parse_int(b"b1", 16).unwrap(), 177)
}
#[test]
fn escape_char_test() {
let escape_char_ = |c: u8| -> String {
let r = escape_char(c)
.unwrap_or_else(|| vec![c].into())
.into_owned();
unsafe { String::from_utf8_unchecked(r) }
};
assert_eq!(escape_char_(b'a'), "a");
assert_eq!(escape_char_(b'$'), "$");
assert_eq!(escape_char_(b'\"'), "\\\"");
assert_eq!(escape_char_(0), "\\000");
assert_eq!(escape("house"), "house");
assert_eq!(escape("\n"), "\\n");
assert_eq!(escape("red\n\t\r$?"), "red\\n\\t\\r$?");
assert!(is_oct(b'5'));
assert!(!is_oct(b'a'));
}
#[test]
fn extract_unquoted_string_test() {
assert_eq!(extract_unquoted_string("'a'", 0, 3).unwrap(), "a");
assert_eq!(extract_unquoted_string("\"a\"", 0, 3).unwrap(), "a");
assert_eq!(extract_unquoted_string("`a`", 0, 3).unwrap(), "a");
assert_eq!(extract_unquoted_string("", 0, 0).unwrap(), "");
assert_eq!(extract_unquoted_string("''", 0, 2).unwrap(), "");
assert_eq!(extract_unquoted_string("'a", 0, 2).unwrap(), "'a");
assert_eq!(extract_unquoted_string("a", 0, 1).unwrap(), "a");
assert_eq!(extract_unquoted_string("<<<EOT\n\nEOT", 0, 11).unwrap(), "");
assert_eq!(
extract_unquoted_string("<<<EOT\na\nEOT", 0, 12).unwrap(),
"a"
);
}
#[test]
fn rfind_test() {
assert_eq!(rfind(b"", b'a'), None);
assert_eq!(rfind(b"a", b'a'), Some(0));
assert_eq!(rfind(b"b", b'a'), None);
assert_eq!(rfind(b"ba", b'a'), Some(1));
}
#[test]
fn unquote_str_test() {
assert_eq!(unquote_str(""), "");
assert_eq!(unquote_str("''"), "");
assert_eq!(unquote_str("\"\""), "");
assert_eq!(unquote_str("``"), "");
assert_eq!(unquote_str("'a'"), "a");
assert_eq!(unquote_str("\"a\""), "a");
assert_eq!(unquote_str("`a`"), "a");
assert_eq!(unquote_str(r#"`a\``"#), r#"a\`"#);
assert_eq!(unquote_str("<<<EOT\nEOT"), "");
assert_eq!(unquote_str("<<<EOT\n\nEOT"), "");
assert_eq!(unquote_str("<<<EOT\n\n\nEOT"), "\n");
assert_eq!(unquote_str("<<<EOT\na\nEOT"), "a");
assert_eq!(unquote_str("<<<EOT\n\na\n\nEOT"), "\na\n");
assert_eq!(unquote_str("'"), "'");
assert_eq!(unquote_str("\""), "\"");
assert_eq!(unquote_str("`"), "`");
assert_eq!(unquote_str("a"), "a");
assert_eq!(unquote_str("`a"), "`a");
assert_eq!(unquote_str(" `a`"), " `a`");
assert_eq!(unquote_str("'a\""), "'a\"");
assert_eq!(unquote_str("<<<"), "<<<");
assert_eq!(unquote_str("<<<EOTEOT"), "<<<EOTEOT");
}
#[test]
fn unquote_slice_test() {
let s = "abc\"".as_bytes();
assert_eq!(unquote_slice(s), s);
}
} |
OCaml | hhvm/hphp/hack/src/utils/exit.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 Option = Base.Option
let hook_upon_clean_exit : (Exit_status.finale_data -> unit) list ref = ref []
let add_hook_upon_clean_exit (hook : Exit_status.finale_data -> unit) : unit =
hook_upon_clean_exit := hook :: !hook_upon_clean_exit
let exit
?(msg : string option)
?(telemetry : Telemetry.t option)
?(stack : string option)
(exit_status : Exit_status.t) : 'a =
(* is there additional inforamtion in exit_status to pick up? *)
let (emsg, estack) =
match exit_status with
| Exit_status.Uncaught_exception e ->
( Some (Exception.get_ctor_string e),
Some (Exception.get_backtrace_string e |> Exception.clean_stack) )
| Exit_status.(
( Server_hung_up_should_abort (Some finale_data)
| Server_hung_up_should_retry (Some finale_data) )) ->
let { Exit_status.exit_status; stack = Utils.Callstack stack; _ } =
finale_data
in
(Some (Exit_status.show exit_status), Some stack)
| _ -> (None, None)
in
let stack =
Option.value
~default:
(Exception.get_current_callstack_string 99 |> Exception.clean_stack)
stack
in
let stack =
match estack with
| None -> stack
| Some estack -> stack ^ "\n\n" ^ estack
in
let msg = Option.first_some msg emsg in
let server_finale_data =
{ Exit_status.exit_status; msg; stack = Utils.Callstack stack; telemetry }
in
List.iter
(fun hook ->
try hook server_finale_data with
| _ -> ())
!hook_upon_clean_exit;
let exit_code = Exit_status.exit_code exit_status in
(* What's the difference between [Stdlib.exit] and [exit]? The former first calls
all installed exit handlers and if any of them throw then it itself throws
rather than exiting; the latter skips exit handlers and for-sure throws.
As a concrete example: imagine if stdout has been closed, and we detect this
and try to call [Exit.exit Exit_status.Client_broken_pipe], but this first runs
exit-handlers before exiting, and one of the exit handlers attempts to flush
stdout, but the flush attempt raises an exception, and therefore we raise
an exception rather than exiting the program! That doesn't feel right. Therefore,
the following will guarantee to exit the program even if exit-handlers fail. *)
try Stdlib.exit exit_code with
| _ -> exit exit_code |
OCaml Interface | hhvm/hphp/hack/src/utils/exit.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 exit :
?msg:string -> ?telemetry:Telemetry.t -> ?stack:string -> Exit_status.t -> 'a
val add_hook_upon_clean_exit : (Exit_status.finale_data -> unit) -> unit |
Rust | hhvm/hphp/hack/src/utils/files_to_ignore.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::path::Path;
use regex::bytes::RegexSet;
// These VCS paths are already omitted from our Watchman Subscription, but we
// also index the repo without using Watchman in some tools. Hardcode these to
// be filtered away for the non-Watchman use cases.
static VCS_REGEX: &str = r"[.](hg|git|svn)/.*";
static PHPUNIT_RE: &str = r".*flib/intern/third-party/phpunit/phpunit.*\.phpt";
pub struct FilesToIgnore {
regexes: RegexSet,
}
impl Default for FilesToIgnore {
fn default() -> Self {
Self {
regexes: RegexSet::new([VCS_REGEX, PHPUNIT_RE].into_iter()).unwrap(),
}
}
}
impl FilesToIgnore {
pub fn new(regexes_to_ignore: &[String]) -> Result<Self, regex::Error> {
Ok(Self {
regexes: RegexSet::new(
[VCS_REGEX, PHPUNIT_RE]
.into_iter()
.chain(regexes_to_ignore.iter().map(String::as_str)),
)?,
})
}
pub fn should_ignore(&self, path: impl AsRef<Path>) -> bool {
let path = path.as_ref();
self.should_ignore_impl(path)
}
#[cfg(unix)]
fn should_ignore_impl(&self, path: &Path) -> bool {
use std::os::unix::ffi::OsStrExt;
let path_bytes = path.as_os_str().as_bytes();
self.regexes.is_match(path_bytes)
}
} |
OCaml | hhvm/hphp/hack/src/utils/file_pos_large.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
(* See documentation in mli file *)
type t = {
pos_lnum: int;
pos_bol: int;
pos_offset: int;
}
[@@deriving eq, hash, ord]
let pp fmt pos =
Format.pp_print_int fmt pos.pos_lnum;
Format.pp_print_string fmt ":";
Format.pp_print_int fmt (pos.pos_offset - pos.pos_bol + 1)
let show : t -> string =
fun pos ->
pp Format.str_formatter pos;
Format.flush_str_formatter ()
let compare : t -> t -> int = compare
let dummy = { pos_lnum = 0; pos_bol = 0; pos_offset = -1 }
let is_dummy = equal dummy
let beg_of_file = { pos_lnum = 1; pos_bol = 0; pos_offset = 0 }
(* constructors *)
let of_line_column_offset ~line ~column ~offset =
{ pos_lnum = line; pos_bol = offset - column; pos_offset = offset }
let of_lexing_pos lp =
{
pos_lnum = lp.Lexing.pos_lnum;
pos_bol = lp.Lexing.pos_bol;
pos_offset = lp.Lexing.pos_cnum;
}
let of_lnum_bol_offset ~pos_lnum ~pos_bol ~pos_offset =
{ pos_lnum; pos_bol; pos_offset }
(* accessors *)
let offset t = t.pos_offset
let line t = t.pos_lnum
let column t = t.pos_offset - t.pos_bol
let beg_of_line t = t.pos_bol
let set_column c p =
{ pos_lnum = p.pos_lnum; pos_bol = p.pos_bol; pos_offset = p.pos_bol + c }
let line_beg t = (t.pos_lnum, t.pos_bol)
let line_column t = (t.pos_lnum, t.pos_offset - t.pos_bol)
let line_column_beg t = (t.pos_lnum, t.pos_offset - t.pos_bol, t.pos_bol)
let line_column_offset t = (t.pos_lnum, t.pos_offset - t.pos_bol, t.pos_offset)
let line_beg_offset t = (t.pos_lnum, t.pos_bol, t.pos_offset)
let to_lexing_pos pos_fname t =
{
Lexing.pos_fname;
Lexing.pos_lnum = t.pos_lnum;
Lexing.pos_bol = t.pos_bol;
Lexing.pos_cnum = t.pos_offset;
} |
OCaml Interface | hhvm/hphp/hack/src/utils/file_pos_large.mli | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* This `.mli` file was generated automatically. It may include extra
definitions that should not actually be exposed to the caller. If you notice
that this interface file is a poor interface, please take a few minutes to
clean it up manually, and then delete this comment once the interface is in
shape. *)
type t = {
pos_lnum: int; (** line number. Starts at 1. *)
pos_bol: int;
(** character number of the beginning of line of this position.
The column number is therefore offset - bol.
Starts at 0. *)
pos_offset: int;
(** character offset from the beginning of the file. Starts at 0. *)
}
[@@deriving eq, hash]
val pp : Format.formatter -> t -> unit
val show : t -> string
val compare : t -> t -> int
val dummy : t
val is_dummy : t -> bool
val beg_of_file : t
val of_line_column_offset : line:int -> column:int -> offset:int -> t
val of_lexing_pos : Lexing.position -> t
val of_lnum_bol_offset : pos_lnum:int -> pos_bol:int -> pos_offset:int -> t
val offset : t -> int
val line : t -> int
val column : t -> int
val beg_of_line : t -> int
val set_column : int -> t -> t
val line_beg : t -> int * int
val line_column : t -> int * int
val line_column_beg : t -> int * int * int
val line_column_offset : t -> int * int * int
val line_beg_offset : t -> int * int * int
val to_lexing_pos : string -> t -> Lexing.position |
OCaml | hhvm/hphp/hack/src/utils/file_pos_small.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
(**
* Three values packed into one 64-bit integer:
*
* 6 5 4 3 2 1 0
* 3210987654321098765432109876543210987654321098765432109876543210
* <----------------------------><----------------------><------->X
* beginning of line line column
*
* - (bol) beginning of line (byte offset from start of file) starts at 0,
maximum is 2^30-1 = 1,073,741,823
* - (line) line number starts at 1, maximum is 2^24-1 = 16,777,215
* - (col) column number starts at 0, maximum is 2^9-1 = 511
* This is saturating, i.e. every column past 511 has column
* number 511 (so as not to raise exceptions).
* - (X) OCaml's tagged integer representation; 1 if int, 0 if pointer
*
*
*)
type t = int [@@deriving eq, hash, ord]
let column_bits = 9
let line_bits = 24
let bol_bits = 30
let mask bits = (1 lsl bits) - 1
let mask_by ~bits x = x land mask bits
let max_column = mask column_bits
let max_line = mask line_bits
let max_bol = mask bol_bits
let dummy = -1
let is_dummy t = t = dummy
let beg_of_line (pos : t) =
if is_dummy pos then
0
else
mask_by ~bits:bol_bits (pos lsr (line_bits + column_bits))
let line (pos : t) =
if is_dummy pos then
0
else
mask_by ~bits:line_bits (pos lsr column_bits)
let column (pos : t) =
if is_dummy pos then
-1
else
mask_by ~bits:column_bits pos
let bol_line_col_unchecked bol line col =
if col < 0 then
dummy
else
(bol lsl (column_bits + line_bits)) + (line lsl column_bits) + col
let bol_line_col bol line col =
if col > max_column || line > max_line || bol > max_bol then
None
else
Some (bol_line_col_unchecked bol line col)
let pp fmt pos =
Format.pp_print_int fmt (line pos);
Format.pp_print_string fmt ":";
Format.pp_print_int fmt (column pos + 1)
let compare : t -> t -> int = compare
let beg_of_file = bol_line_col_unchecked 0 1 0
(* constructors *)
let of_lexing_pos lp =
bol_line_col
lp.Lexing.pos_bol
lp.Lexing.pos_lnum
(lp.Lexing.pos_cnum - lp.Lexing.pos_bol)
let of_lnum_bol_offset ~pos_lnum ~pos_bol ~pos_offset =
bol_line_col pos_bol pos_lnum (pos_offset - pos_bol)
(* accessors *)
let offset t = beg_of_line t + column t
let line_beg t = (line t, beg_of_line t)
let line_column t = (line t, column t)
let line_column_beg t = (line t, column t, beg_of_line t)
let line_column_offset t = (line t, column t, offset t)
let line_beg_offset t = (line t, beg_of_line t, offset t)
let set_column_unchecked c p = bol_line_col_unchecked (beg_of_line p) (line p) c
let set_column c p = bol_line_col (beg_of_line p) (line p) c
let to_lexing_pos pos_fname t =
{
Lexing.pos_fname;
Lexing.pos_lnum = line t;
Lexing.pos_bol = beg_of_line t;
Lexing.pos_cnum = offset t;
}
let as_large_pos p =
let (lnum, col, bol) = line_column_beg p in
File_pos_large.of_lnum_bol_offset
~pos_lnum:lnum
~pos_bol:bol
~pos_offset:(bol + col)
let of_large_pos : File_pos_large.t -> t option =
fun { File_pos_large.pos_bol; pos_offset; pos_lnum } ->
of_lnum_bol_offset ~pos_lnum ~pos_bol ~pos_offset |
OCaml Interface | hhvm/hphp/hack/src/utils/file_pos_small.mli | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type t = int [@@deriving eq, hash]
val dummy : t
val is_dummy : t -> bool
val beg_of_line : t -> int
val line : t -> int
val column : t -> int
val pp : Format.formatter -> t -> unit
val compare : t -> t -> int
val beg_of_file : t
val of_lexing_pos : Lexing.position -> t option
val of_lnum_bol_offset :
pos_lnum:int -> pos_bol:int -> pos_offset:int -> t option
val offset : t -> int
val line_beg : t -> int * int
val line_column : t -> int * int
val line_column_beg : t -> int * int * int
val line_column_offset : t -> int * int * int
val line_beg_offset : t -> int * int * int
val set_column_unchecked : int -> t -> t
val set_column : int -> t -> t option
val to_lexing_pos : string -> t -> Lexing.position
val as_large_pos : t -> File_pos_large.t
val of_large_pos : File_pos_large.t -> t option |
OCaml | hhvm/hphp/hack/src/utils/findUtils.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
(*****************************************************************************)
(* The file extensions we are interested in *)
(*****************************************************************************)
let extensions =
[
".php";
(* normal php file *)
".phpt";
(* our php template or test files *)
".hack";
(* strict-mode files (Hack) *)
".hackpartial";
(* partial-mode files (Hack) *)
".hck";
(* open source hack: bikeshed entry *)
".hh";
(* open source hack: biekshed entry *)
".hhi";
(* interface files only visible to the type checker *)
".xhp";
(* XHP extensions *)
]
let is_dot_file path =
let filename = Filename.basename path in
String.length filename > 0 && Char.equal filename.[0] '.'
let is_hack path =
(not (is_dot_file path))
&& List.exists extensions ~f:(Filename.check_suffix path)
(* Returns whether one of the ancestral directories of path has the given
* name. *)
let rec has_ancestor path ancestor_name =
let dirname = Filename.dirname path in
if String.equal dirname path then
(* Terminal condition *)
false
else if String.equal (Filename.basename dirname) ancestor_name then
true
else
has_ancestor dirname ancestor_name
let file_filter f =
(* Filter the relative path *)
let f = Relative_path.strip_root_if_possible f |> Option.value ~default:f in
is_hack f && not (FilesToIgnore.should_ignore f)
let path_filter f = Relative_path.suffix f |> file_filter
let post_watchman_filter_from_fully_qualified_raw_updates
~(root : Path.t) ~(raw_updates : SSet.t) : Relative_path.Set.t =
let root = Path.to_string root in
(* Because of symlinks, we can have updates from files that aren't in
* the .hhconfig directory *)
let updates =
SSet.filter (fun p -> String.is_prefix p ~prefix:root) raw_updates
in
let updates = Relative_path.(relativize_set Root updates) in
Relative_path.Set.filter updates ~f:(fun update ->
file_filter (Relative_path.to_absolute update)) |
OCaml Interface | hhvm/hphp/hack/src/utils/findUtils.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.
*
*)
(** The file extensions we are interested, each in the form ".ext" *)
val extensions : string list
val is_dot_file : string -> bool
val is_hack : string -> bool
val has_ancestor : string -> string -> bool
(** Filter the relative path. This will reject files not in [extensions] and maybe more. *)
val file_filter : string -> bool
val path_filter : Relative_path.t -> bool
(** It can be hard to be precise about what each filtering function does. This
function there is explained in the role it plays. We must ask watchman to give
files that satisfy FilesToIgnore.watchman_server_expression_terms, and once watchman
has given us its raw updates, then we must put them through this function.
If this function says there are any changes, then hh_server will necessarily take some
action in its recheck loop -- maybe do a recheck, or maybe restart because
.hhconfig has changed or similar.
This function takes as input a set of strings representing fully-qualified pathnames
that came out of watchman. They might be symlinks, e.g. if we watch root ~/dir,
and watchman tells us that ~/dir/a.php has changed, it might be that a.php
is really a symlink to something outside the root. This function accordingly
takes in the fully-qualified pathnames from watchman, resolves symlinks,
excludes the ones where the resolved paths are outside root, and runs the same
file_filter as above. *)
val post_watchman_filter_from_fully_qualified_raw_updates :
root:Path.t -> raw_updates:SSet.t -> Relative_path.Set.t |
Rust | hhvm/hphp/hack/src/utils/find_utils.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::path::Path;
use files_to_ignore::FilesToIgnore;
use relative_path::RelativePath;
const EXTENSIONS: [&str; 8] = [
"php", // normal php file
"phpt", // our php template or test files
"hack", // strict-mode files (Hack)
"hackpartial", // partial-mode files (Hack)
"hck", // open source hack: bikeshed entry
"hh", // open source hack: bikeshed entry
"hhi", // interface files only visible to the type checker
"xhp", // XHP extensions
];
// There's an interesting difference in behavior with findUtils.ml with paths
// like "/my/path/foo.php/.". With findUtils.ml, that path would be ignored.
// With find_utils.rs, we would consider this file, because it's effectively
// "/my/path/foo.php".
fn is_dot_file_or_dir(path: &Path) -> bool {
match path.file_name() {
Some(base_name) => match base_name.to_str() {
Some(base_name_str) => base_name_str.starts_with('.'),
None => false,
},
None => false,
}
}
pub fn is_hack(path: &Path) -> bool {
!(is_dot_file_or_dir(path))
&& match path.extension() {
Some(ext) => EXTENSIONS.iter().any(|x| std::ffi::OsStr::new(x) == ext),
None => false,
}
}
/// Returns true if path is a hack file, is not under any of (.hg, .git, .svn),
/// and is not a .phpt file under phpunit/.
pub fn is_non_ignored_hack(files_to_ignore: &FilesToIgnore, path: &Path) -> bool {
is_hack(path) && !files_to_ignore.should_ignore(path)
}
/// Traverse the directory `root` and yield the non-ignored Hack files under it
/// in parallel using `jwalk`. The root will be stripped from each path and
/// replaced with the given `Prefix`.
pub fn find_hack_files<'a>(
files_to_ignore: &'a FilesToIgnore,
root: &'a Path,
prefix: relative_path::Prefix,
) -> impl Iterator<Item = anyhow::Result<RelativePath>> + 'a {
jwalk::WalkDir::new(root)
.into_iter()
.filter_map(move |entry_result| {
let entry = match entry_result {
Ok(entry) => entry,
Err(err) => return Some(Err(anyhow::anyhow!(err))),
};
if entry.file_type().is_dir() {
return None;
}
let path = entry.path();
if !is_hack(&path) {
return None;
}
let suffix = path.strip_prefix(root).unwrap();
if files_to_ignore.should_ignore(suffix) {
return None;
}
let path = RelativePath::make(prefix, suffix.to_owned());
Some(Ok(path))
})
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn dot_files() {
assert!(is_dot_file_or_dir(Path::new("/my/path/.hello")));
assert!(is_dot_file_or_dir(Path::new("/my/path/.hello/")));
assert!(is_dot_file_or_dir(Path::new("/my/path/.hello/.")));
assert!(!is_dot_file_or_dir(Path::new(" ")));
assert!(!is_dot_file_or_dir(Path::new(".")));
assert!(!is_dot_file_or_dir(Path::new("/my/path/.")));
assert!(!is_dot_file_or_dir(Path::new("/my/path/hello")));
}
#[test]
fn is_hack_file() {
assert!(is_hack(Path::new("hello.php")));
assert!(is_hack(Path::new("/my/path/hello.php")));
assert!(is_hack(Path::new("/my/path/hello.phpt")));
assert!(is_hack(Path::new("/my/path/hello.hack")));
assert!(is_hack(Path::new("/my/path/foo.hackpartial")));
assert!(is_hack(Path::new("/my/path/ack.hck")));
assert!(is_hack(Path::new("/my/path/bar.hh")));
assert!(is_hack(Path::new("/my/path/foo.hhi")));
assert!(is_hack(Path::new("/my/path/ack.xhp")));
// hidden file
assert!(!is_hack(Path::new("/my/path/.hello.xhp")));
// wrong extension
assert!(!is_hack(Path::new("/my/path/hello.txt")));
// no extension
assert!(!is_hack(Path::new("/my/path/foo")));
}
#[test]
fn consider_files_test() {
let paths = vec![
PathBuf::from("/a/b/.git/hello.php"),
PathBuf::from("alpha.hack"),
PathBuf::from("/my/path/flib/intern/third-party/phpunit/phpunit/hello.phpt"),
PathBuf::from("/my/path/check.hh"),
PathBuf::from("some/other/.hg/path/uhoh.php"),
PathBuf::from("/wrong/extension/oops.txt"),
];
assert_eq!(
paths
.iter()
.map(PathBuf::as_path)
.filter(|path| is_non_ignored_hack(&Default::default(), path))
.collect::<Vec<_>>(),
vec![Path::new("alpha.hack"), Path::new("/my/path/check.hh")]
);
}
} |
OCaml | hhvm/hphp/hack/src/utils/gc_utils.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type megabytes = int
let get_heap_size () = Gc.((quick_stat ()).Stat.heap_words) * 8 / 1024 / 1024 |
OCaml Interface | hhvm/hphp/hack/src/utils/gc_utils.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type megabytes = int
val get_heap_size : unit -> megabytes |
Rust | hhvm/hphp/hack/src/utils/hh24_test.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::collections::BTreeMap;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use anyhow::Result;
use bumpalo::Bump;
use hh24_types::Checksum;
use hh24_types::ToplevelSymbolHash;
use names::FileSummary;
use relative_path::Prefix;
use relative_path::RelativePath;
use tempdir::TempDir;
pub struct TestRepo {
root: TempDir,
}
impl TestRepo {
/// Creates a repo with `files`, a map of filename to its contents. Also
/// creates a .hhconfig.
///
/// Supports nested directories.
///
/// See tests for example usage.
pub fn new(files: &BTreeMap<&str, &str>) -> Result<Self> {
let tmpdir = TempDir::new("test_repo")?;
create_repo(tmpdir.path(), files)?;
Ok(Self { root: tmpdir })
}
pub fn write(&self, rel_path: &dyn AsRef<Path>, text: &str) -> Result<RelativePath> {
self.write_bytes(rel_path, text.as_bytes())
}
pub fn write_bytes(&self, rel_path: &dyn AsRef<Path>, content: &[u8]) -> Result<RelativePath> {
let mut file = std::fs::File::create(self.root.path().join(rel_path.as_ref()))?;
file.write_all(content)?;
Ok(RelativePath::make(
relative_path::Prefix::Root,
PathBuf::from(rel_path.as_ref()),
))
}
pub fn delete(&self, rel_path: &dyn AsRef<Path>) -> Result<RelativePath> {
std::fs::remove_file(self.root.path().join(rel_path.as_ref()))?;
Ok(RelativePath::make(
relative_path::Prefix::Root,
PathBuf::from(rel_path.as_ref()),
))
}
pub fn path<'a>(&'a self) -> &'a Path {
self.root.path()
}
}
pub fn create_naming_table(path: &Path, files: &BTreeMap<&str, &str>) -> Result<()> {
names::Names::build_from_iterator(
path,
files
.iter()
.map(|(path, text)| {
let relpath = root_path(path);
let summary = parse_and_summarize(&relpath, text)?;
Ok((relpath, summary))
})
.collect::<Result<Vec<_>>>()?,
)?;
Ok(())
}
pub fn parse_and_summarize(relpath: &RelativePath, text: &str) -> Result<FileSummary> {
let arena = &Bump::new();
let parsed_file = direct_decl_parser::parse_decls_for_typechecking(
&Default::default(),
relpath.clone(),
text.as_bytes(),
arena,
);
let remove_php_stdlib_if_hhi = true;
let prefix = relpath.prefix();
let parsed_file_with_hashes = oxidized_by_ref::direct_decl_parser::ParsedFileWithHashes::new(
parsed_file,
remove_php_stdlib_if_hhi,
prefix,
arena,
);
Ok(names::FileSummary::new(&parsed_file_with_hashes))
}
pub fn calculate_checksum(summaries: &[(RelativePath, FileSummary)]) -> Checksum {
// Checksum calculations are based on the winner, in case of duplicates.
// We'll gather all winning decls...
let mut decls = BTreeMap::new();
for (relpath, summary) in summaries {
for (symbol_hash, decl_hash) in summary.decl_hashes() {
use std::collections::btree_map::Entry;
match decls.entry(symbol_hash) {
Entry::Vacant(v) => {
v.insert((decl_hash, relpath.clone()));
}
Entry::Occupied(mut o) => {
let (_, existing_path) = o.get();
if relpath < existing_path {
o.insert((decl_hash, relpath.clone()));
}
}
}
}
}
// Now that we know the winners, we can calculate checksum
let mut expected_checksum = Checksum(0);
for (symbol_hash, (decl_hash, relpath)) in decls {
expected_checksum.addremove(symbol_hash, decl_hash, &relpath);
}
expected_checksum
}
pub fn type_hash(symbol: &str) -> ToplevelSymbolHash {
let symbol = if symbol.starts_with('\\') {
symbol.to_owned()
} else {
String::from("\\") + symbol
};
ToplevelSymbolHash::from_type(&symbol)
}
pub fn fun_hash(symbol: &str) -> ToplevelSymbolHash {
let symbol = if symbol.starts_with('\\') {
symbol.to_owned()
} else {
String::from("\\") + symbol
};
ToplevelSymbolHash::from_fun(&symbol)
}
pub fn root_path(path: &str) -> RelativePath {
RelativePath::make(Prefix::Root, PathBuf::from(path))
}
/// Guarantee the file exists, but don't truncate it if it does.
pub fn touch(path: &Path) -> Result<()> {
std::fs::OpenOptions::new()
.create(true)
.write(true)
.open(path)?;
Ok(())
}
// Fills the given `root` with `files`, a map of filename to its contents. Also
// creates a .hhconfig in `root`.
//
// Supports nested directories.
fn create_repo(root: &Path, files: &BTreeMap<&str, &str>) -> Result<()> {
// touch .hhconfig
touch(&root.join(".hhconfig"))?;
for (path, text) in files {
let full_path = root.join(path);
if let Some(prefix) = full_path.parent() {
std::fs::create_dir_all(prefix)?;
}
let mut file = std::fs::File::create(full_path)?;
file.write_all(text.as_bytes())?;
}
Ok(())
}
#[cfg(test)]
mod test {
use std::collections::BTreeMap;
use maplit::btreemap;
use maplit::convert_args;
use super::*;
#[test]
fn test_repo_expected_files() {
let files: BTreeMap<&str, &str> = convert_args!(btreemap!(
"foo.php" => r#"
<?hh // strict
class Foo {
public function get(): int { return 0; }
}
"#,
"nested/bar.php" => r#"
<?hh // strict
class Bar {
public function get(): int { return 0; }
}
"#,
));
let repo = TestRepo::new(&files).unwrap();
assert!(repo.path().join("foo.php").exists());
assert!(repo.path().join("nested/bar.php").exists());
}
} |
C | hhvm/hphp/hack/src/utils/libcpu_cycles.c | #define CAML_NAME_SPACE
#include <stdint.h>
#include <caml/alloc.h>
#include <caml/memory.h>
#define IGNORE_UNUSED(x) ( (void)(x) )
static inline
uint64_t
CPU_CYCLES()
{
#ifdef __x86_64__
uint32_t high, low;
uint64_t high1, low1;
asm volatile("rdtsc": "=a"((low)), "=d"((high)));
high1 = (uint64_t) high;
low1 = (uint64_t) low;
return low1 | (high1 * 0x100000000 /* 2^32 */);
#elif _MSC_VER
return (uint64_t) __rstdc();
#elif __aarch64__
uint64_t arm_tb;
asm volatile("mrs %0, cntvct_el0" : "=r"((arm_tb)));
return arm_tb;
#else
return 0;
/* default value when not implemented, don't want the complexity of
throwing from OCaml */
#endif
}
CAMLprim value
ocaml_cpu_cycles(value unit)
{
IGNORE_UNUSED(unit);
return Val_int(CPU_CYCLES());
} |
OCaml | hhvm/hphp/hack/src/utils/line_break_map.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.
*
*)
open Hh_prelude
type t = int array [@@deriving show, eq, sexp_of]
let last_offset = ref 0
let curr_index = ref 0
let reset_global_state () =
last_offset := 0;
curr_index := 0
let make text =
reset_global_state ();
(* Clever Tricks Warning
* ---------------------
* We prepend 0, so as to make the invariant hold that there is always a
* perceived line break at the start of the file. We use this in translating
* offsets to line numbers.
*
* Similarly, whether there's a line break at the end or not, the line break
* map will always end with the length of the original string. This solves
* off-by-one issues.
*)
let len = String.length text in
let newline_list =
let result = ref [] in
for i = 1 to len do
let prev = text.[i - 1] in
if
Char.(
(prev = '\r' && (Int.(i = len) || not (text.[i] = '\n')))
|| prev = '\n')
then
result := i :: !result
done;
(match !result with
| r :: _ as rs when r <> len -> result := len :: rs
| _ -> ());
0 :: List.rev !result
in
Array.of_list newline_list
let offset_to_file_pos_triple bolmap offset =
let len = Array.length bolmap in
if !curr_index >= len then curr_index := len - 1;
let rec forward_search i =
let offset_at_i = Array.unsafe_get bolmap i in
if offset < offset_at_i then
i - 1
else if i + 1 >= len then
len - 1
else
forward_search (i + 1)
in
let rec backward_search i =
let offset_at_i = Array.unsafe_get bolmap i in
if offset >= offset_at_i then
i
else if i = 0 then
0
else
backward_search (i - 1)
in
let index =
if !last_offset < offset && !curr_index <> len - 1 then
forward_search (!curr_index + 1)
else if !last_offset > offset then
backward_search !curr_index
else
!curr_index
in
let line_start = bolmap.(index) in
curr_index := index;
last_offset := offset;
(index + 1, line_start, offset)
let offset_to_position bolmap offset =
let (index, line_start, offset) = offset_to_file_pos_triple bolmap offset in
(index, offset - line_start + 1)
(* TODO: add more informative data to the exception *)
exception Position_not_found
let position_to_offset ?(existing = false) bolmap (line, column) =
let len = Array.length bolmap in
let file_line = line in
(* Treat all file_line errors the same: Not_found *)
let line_start =
try bolmap.(file_line - 1) with
| _ -> raise Position_not_found
in
let offset = line_start + column - 1 in
if
(not existing) || (offset >= 0 && offset <= bolmap.(min (len - 1) file_line))
then
offset
else
raise Position_not_found
let offset_to_line_start_offset bolmap offset =
offset - snd (offset_to_position bolmap offset) + 1
let offsets_to_line_lengths bolmap =
let (lengths, _) =
Array.fold_right
~f:(fun offset (acc, mnext) ->
match mnext with
| None -> (acc, Some offset)
| Some next -> ((next - offset) :: acc, Some offset))
bolmap
~init:([], None)
in
lengths |
OCaml Interface | hhvm/hphp/hack/src/utils/line_break_map.mli | (*
* 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.
*
*)
(* A line break map is created for a given string. It contains the offsets (in
* said string) of the first character of a line (i.e. the offset after a line
* break) allowing binary search from an offset to a line number (the index in
* the map itself + 1).
*)
type t [@@deriving show, eq, sexp_of]
val reset_global_state : unit -> unit
(* Creates a line break map from/for the given string. *)
val make : string -> t
val offset_to_file_pos_triple : t -> int -> int * int * int
(* Take a zero-based offset, produce a one-based (line, column) pair.
*
* When cyclic_index is set, negative offsets are taken from the end, i.e. -1
* points to the last position in the original string. For a string of length l,
* an offset x where x < -l defaults to offset 0, i.e. offsets only wrap around\
* once.
*)
val offset_to_position : t -> int -> int * int
exception Position_not_found
(* Take a one-based (line, column) pair, produce a zero-based offset.
*
* By setting existing to true (it's false by default), Not_found is raised for
* a position outside of the range of valid line/column numbers from the
* original string.
*
* Setting cyclic_index translates negative line numbers as offsets from the
* last line in the original string. Without cyclic_index, Invalid_argument is
* raised with an array-out-of-bounds message.
*
* Might raise {!Position_not_found}
*)
val position_to_offset : ?existing:bool -> t -> int * int -> int
(* Does what it says on the tin. *)
val offset_to_line_start_offset : t -> int -> int
(* Returns a list of line lengths *)
val offsets_to_line_lengths : t -> int list |
Rust | hhvm/hphp/hack/src/utils/line_break_map.rs | // Copyright (c) 2019, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::cell::Cell;
#[derive(Debug)]
pub struct LineBreakMap {
lines: Box<[usize]>,
last_offset: Cell<usize>,
curr_idnex: Cell<usize>,
}
impl LineBreakMap {
pub fn new(text: &[u8]) -> Self {
/* Clever Tricks Warning
* ---------------------
* We prepend 0, so as to make the invariant hold that there is always a
* perceived line break at the start of the file. We use this in translating
* offsets to line numbers.
*
* Similarly, whether there's a line break at the end or not, the line break
* map will always end with the length of the original string. This solves
* off-by-one issues.
*/
let len = text.len();
// Vec capacity grows exponentically, but it starts from 1.
// Start with (len / 80) + 1, assuming 80 is average char count in a line.
let mut result = Vec::with_capacity((len / 80) + 1);
result.push(0);
for i in 1..(len + 1) {
let prev = text[i - 1];
if prev == b'\r' && text[i] != b'\n' || prev == b'\n' {
result.push(i);
}
}
if result.len() > 1 {
if let Some(i) = result.last() {
if *i != len {
result.push(len);
}
}
}
LineBreakMap {
lines: result.into_boxed_slice(),
last_offset: Cell::new(0),
curr_idnex: Cell::new(0),
}
}
#[inline]
fn to_isize(u: usize) -> isize {
assert!(u as isize >= 0, "{} can not convert to isize", u);
u as isize
}
pub fn offset_to_file_pos_triple_original(&self, offset: isize) -> (isize, isize, isize) {
if offset < 0 {
return (1, 0, offset);
}
let (i, s, o) = self.offset_to_file_pos_triple(offset as usize);
(Self::to_isize(i), Self::to_isize(s), Self::to_isize(o))
}
pub fn offset_to_file_pos_triple(&self, offset: usize) -> (usize, usize, usize) {
let curr_index = self.curr_idnex.get();
let last_offset = self.last_offset.get();
let mut index = 0;
if last_offset == offset {
index = curr_index;
} else {
if offset > self.lines[curr_index] {
index = self.lines.len() - 1;
for i in curr_index..self.lines.len() {
if offset < self.lines[i] {
index = i - 1;
break;
}
}
} else {
let mut i = curr_index;
while i > 0 {
if self.lines[i] <= offset {
index = i;
break;
}
i -= 1;
}
}
self.curr_idnex.set(index);
self.last_offset.set(offset);
}
(index + 1, self.lines[index], offset)
}
pub fn offset_to_position(&self, offset: isize) -> (isize, isize) {
let (index, line_start, offset) = self.offset_to_file_pos_triple_original(offset);
(index, offset - line_start + 1)
}
pub fn position_to_offset(&self, existing: bool, line: isize, column: isize) -> Option<isize> {
fn get(v: &[usize], i: isize) -> isize {
v[i as usize] as isize
}
let len = self.lines.len() as isize;
let file_line = line;
/* Treat all file_line errors the same */
if file_line <= 0 || file_line > len {
None
} else {
let line_start = get(self.lines.as_ref(), file_line - 1);
let offset = line_start + column - 1;
if !existing
|| offset >= 0
&& offset <= get(self.lines.as_ref(), std::cmp::min(len - 1, file_line))
{
Some(offset)
} else {
None
}
}
}
pub fn offset_to_line_start_offset(&self, offset: isize) -> isize {
offset - self.offset_to_position(offset).1 + 1
}
pub fn offset_to_line_lengths(&self) -> Vec<isize> {
panic!("Not implemented")
}
} |
OCaml | hhvm/hphp/hack/src/utils/lwt_message_queue.ml | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type 'a t = {
mutable messages: 'a ImmQueue.t;
mutable is_open: bool;
cv: unit Lwt_condition.t;
(** Broadcasted whenever any of the above state changes. *)
}
let create () : 'a t =
{ messages = ImmQueue.empty; is_open = true; cv = Lwt_condition.create () }
let set_messages (queue : 'a t) (messages : 'a ImmQueue.t) : unit =
queue.messages <- messages;
Lwt_condition.broadcast queue.cv ()
let set_is_open (queue : 'a t) (is_open : bool) : unit =
queue.is_open <- is_open;
Lwt_condition.broadcast queue.cv ()
let push (queue : 'a t) (message : 'a) : bool =
if queue.is_open then (
set_messages queue (ImmQueue.push queue.messages message);
true
) else
false
let rec pop (queue : 'a t) : 'a option Lwt.t =
match (queue.is_open, ImmQueue.pop queue.messages) with
| (false, _) -> Lwt.return None
| (true, (None, _)) ->
let%lwt () = Lwt_condition.wait queue.cv in
pop queue
| (true, (Some hd, tl)) ->
set_messages queue tl;
Lwt.return (Some hd)
let close (queue : 'a t) : unit =
set_messages queue ImmQueue.empty;
set_is_open queue false
let is_empty (queue : 'a t) : bool = ImmQueue.is_empty queue.messages
let length (queue : 'a t) : int = ImmQueue.length queue.messages
let exists (queue : 'a t) ~(f : 'a -> bool) : bool =
ImmQueue.exists ~f queue.messages |
OCaml Interface | hhvm/hphp/hack/src/utils/lwt_message_queue.mli | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(** A mutable queue containing messages of type ['a]. *)
type 'a t
(** Create a new [Lwt_message_queue.t]. *)
val create : unit -> 'a t
(** Push a message into the queue. Wakes up the task waiting to [pop] from it,
if any. *)
val push : 'a t -> 'a -> bool
(** Get and remove the next message in the queue. If there are currently no
messages in the queue, wait until one becomes available. If the queue is or
becomes closed, returns [None]; otherwise returns [Some message].
The behavior of multiple tasks waiting to [pop] the queue simultaneously is
unspecified (similar to issues raised in
https://github.com/ocsigen/lwt/issues/250). Only one task should [pop] at a
time. The message queue is therefore mostly useful for code organization
purposes, making it possible to split the code for the producer and consumer of
the message queue in a principled way. *)
val pop : 'a t -> 'a option Lwt.t
(** Close the message queue for further reads and writes. All messages currently
in the queue will be dropped. Future calls to [push] will return [false], and
future calls to [pop] will return [None].
Either the producer or consumer end of the queue may close it. *)
val close : 'a t -> unit
(** Whether or not the queue has any pending messages at this moment. *)
val is_empty : 'a t -> bool
(** Returns the number of messages currently in the queue. If the queue is
closed, returns [0]. *)
val length : 'a t -> int
(** Returns whether or not a message satisfying predicate [f] exists in the
current queue. *)
val exists : 'a t -> f:('a -> bool) -> bool |
OCaml | hhvm/hphp/hack/src/utils/lwt_utils.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
exception WrappedException of Exception.t
(** Use this instead of [Lwt_main.run] to ensure that the right engine is set, and to
improve stack traces. *)
let run_main f =
(* TODO: Lwt defaults to libev when it's installed. Historically, it wasn't installed
and so we haven't tested it. Here we explicitly choose to use select instead, but
should test libev. *)
Lwt_engine.set (new Lwt_engine.select);
try
Lwt_main.run
(try%lwt f () with
| exn ->
(* Lwt_main.run loses backtraces when its callback errors. To work around it, we
catch exceptions within the callback, store their traces using Exception.wrap,
then re-raise them outside the Lwt_main.run.
https://github.com/ocsigen/lwt/issues/720 is tracking a more holistic fix. *)
let exn = Exception.wrap exn in
raise (WrappedException exn))
with
| WrappedException exn -> Exception.reraise exn
let select
(read_fds : Unix.file_descr list)
(write_fds : Unix.file_descr list)
(exn_fds : Unix.file_descr list)
(timeout : float) :
(Unix.file_descr list * Unix.file_descr list * Unix.file_descr list) Lwt.t =
let make_task
~(fds : Unix.file_descr list)
~(condition : Lwt_unix.file_descr -> bool)
~(wait_f : Lwt_unix.file_descr -> unit Lwt.t) :
(Unix.file_descr list, Unix.file_descr list) result Lwt.t =
try%lwt
let fds = List.map fds ~f:Lwt_unix.of_unix_file_descr in
let%lwt () = Lwt.pick (List.map fds ~f:wait_f) in
let actionable_fds =
fds |> List.filter ~f:condition |> List.map ~f:Lwt_unix.unix_file_descr
in
Lwt.return (Ok actionable_fds)
with
| _ ->
(* Although we gather a list of exceptional file descriptors here, it
happens that no call site of `Unix.select` in the codebase has checked
this list, so we could in theory just return any list (or not return any
exceptional file descriptors at all). *)
let exceptional_fds =
List.filter exn_fds ~f:(fun fd -> List.mem ~equal:Poly.( = ) fds fd)
in
Lwt.return (Error exceptional_fds)
in
let tasks = [] in
(* WRITE TASK *)
let tasks =
match write_fds with
| [] -> tasks
| _ ->
let write_task =
let%lwt writeable_fds =
make_task
~fds:write_fds
~condition:Lwt_unix.writable
~wait_f:Lwt_unix.wait_write
in
match writeable_fds with
| Ok fds -> Lwt.return ([], fds, [])
| Error fds -> Lwt.return ([], [], fds)
in
write_task :: tasks
in
(* READ TASK *)
let tasks =
match read_fds with
| [] -> tasks
| _ ->
let read_task =
let%lwt readable_fds =
make_task
~fds:read_fds
~condition:Lwt_unix.readable
~wait_f:Lwt_unix.wait_read
in
match readable_fds with
| Ok fds -> Lwt.return (fds, [], [])
| Error fds -> Lwt.return ([], [], fds)
in
read_task :: tasks
in
(* TIMEOUT TASK *)
let tasks =
if Float.(timeout > 0.0) then
let timeout_task =
let%lwt () = Lwt_unix.sleep timeout in
Lwt.return ([], [], [])
in
timeout_task :: tasks
else
failwith "Timeout <= 0 not implemented"
in
Lwt.pick tasks
module Process_success = struct
type t = {
command_line: string;
stdout: string;
stderr: string;
start_time: float;
end_time: float;
}
end
module Process_failure = struct
type t = {
command_line: string;
process_status: Unix.process_status;
stdout: string;
stderr: string;
exn: exn option;
start_time: float;
end_time: float;
}
let to_string (process_failure : t) : string =
let exn_message =
match process_failure.exn with
| Some exn -> Exn.to_string exn
| None -> "<none>"
in
let exit_code =
match process_failure.process_status with
| Unix.WEXITED exit_code ->
Printf.sprintf
"WEXITED %d (%s)"
exit_code
(Exit_status.exit_code_to_string exit_code)
| Unix.WSIGNALED exit_code ->
Printf.sprintf
"WSIGNALLED %d (%s)%s"
exit_code
(PrintSignal.string_of_signal exit_code)
(if exit_code = Sys.sigkill then
" - this often indicates a timeout"
else
"")
| Unix.WSTOPPED exit_code ->
Printf.sprintf
"WSTOPPED %d (%s)"
exit_code
(PrintSignal.string_of_signal exit_code)
in
let stderr =
match process_failure.stderr with
| "" -> "<none>"
| stderr -> stderr
in
Printf.sprintf
("Process '%s' failed with\n"
^^ "Exit code: %s\n"
^^ "%s -- %s\n"
^^ "Exception: %s\n"
^^ "Stderr: %s\n"
^^ "Stdout: %s")
process_failure.command_line
exit_code
(Utils.timestring process_failure.start_time)
(Utils.timestring process_failure.end_time)
exn_message
stderr
process_failure.stdout
end
let exec_checked
?(input : string option)
?(env : string array option)
?(timeout : float option)
?(cancel : unit Lwt.t option)
(program : Exec_command.t)
(args : string array) : (Process_success.t, Process_failure.t) Lwt_result.t
=
let start_time = Unix.gettimeofday () in
let command =
match (program, args) with
| (Exec_command.Shell, [| script |]) -> Lwt_process.shell script
| (Exec_command.Shell, _) ->
failwith "Exec_command.Shell needs exactly one arg"
| (program, args) ->
let program = Exec_command.to_string program in
(program, Array.append [| program |] args)
in
let command_line = snd command |> String.concat_array ~sep:" " in
let process = Lwt_process.open_process_full command ?timeout ?env in
let cancel_watcher =
match cancel with
| None -> []
| Some cancel ->
[
(let%lwt () = cancel in
process#kill Sys.sigkill;
Lwt.return_unit);
]
in
(let%lwt (exn, stdout, stderr) =
let exn = ref None in
let stdout = ref "" in
let stderr = ref "" in
let%lwt () =
try%lwt
let%lwt () =
match input with
| Some input ->
let%lwt () = Lwt_io.write process#stdin input in
let%lwt () = Lwt_io.close process#stdin in
Lwt.return_unit
| None -> Lwt.return_unit
and () =
let%lwt result = Lwt_io.read process#stdout in
stdout := result;
Lwt.return_unit
and () =
let%lwt result = Lwt_io.read process#stderr in
stderr := result;
Lwt.return_unit
and () =
Lwt.choose
(cancel_watcher
@ [
(let%lwt _ = process#status in
Lwt.return_unit);
])
in
Lwt.return_unit
with
| e ->
exn := Some e;
Lwt.return_unit
in
Lwt.return (!exn, !stdout, !stderr)
in
let%lwt state = process#close in
let end_time = Unix.gettimeofday () in
match state with
| Unix.WEXITED 0 ->
Lwt.return_ok
{ Process_success.command_line; stdout; stderr; start_time; end_time }
| process_status ->
Lwt.return_error
{
Process_failure.command_line;
process_status;
stdout;
stderr;
exn;
start_time;
end_time;
})
[%finally
let%lwt (_ : Unix.process_status) = process#close in
Lwt.return_unit]
let try_finally ~(f : unit -> 'a Lwt.t) ~(finally : unit -> unit Lwt.t) :
'a Lwt.t =
let%lwt res =
try%lwt
let%lwt result = f () in
Lwt.return result
with
| exn ->
let e = Exception.wrap exn in
let%lwt () = finally () in
Exception.reraise e
in
let%lwt () = finally () in
Lwt.return res
let with_context
~(enter : unit -> unit Lwt.t)
~(exit : unit -> unit Lwt.t)
~(do_ : unit -> 'a Lwt.t) : 'a Lwt.t =
let%lwt () = enter () in
try_finally ~f:do_ ~finally:exit
let read_all (path : string) : (string, string) Lwt_result.t =
try%lwt
let%lwt contents =
Lwt_io.with_file ~mode:Lwt_io.Input path (fun ic ->
let%lwt contents = Lwt_io.read ic in
Lwt.return contents)
in
Lwt.return (Ok contents)
with
| _ ->
Lwt.return
(Error
(Printf.sprintf
"Could not read the contents of the file at path %s"
path))
module Promise = struct
type 'a t = 'a Lwt.t
let return = Lwt.return
let map e f = Lwt.map f e
let bind = Lwt.bind
let both = Lwt.both
end |
OCaml Interface | hhvm/hphp/hack/src/utils/lwt_utils.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(** Use this instead of [Lwt_main.run] to ensure that the right engine is set, and to
improve stack traces. *)
val run_main : (unit -> 'a Lwt.t) -> 'a
(** Drop-in replacement for [Unix.select] that works even when the Lwt main loop
is running (i.e. your function has [Lwt_main.run] somewhere higher up in the
call stack).
The Lwt main loop is an event loop pumped by [Unix.select], and so regular
[Unix.select] calls are prone to raising `EINTR`. The implementation of this
function does not use [Unix.select] at all, but Lwt primitives that accomplish
the same thing.
*)
val select :
Unix.file_descr list ->
Unix.file_descr list ->
Unix.file_descr list ->
float ->
(Unix.file_descr list * Unix.file_descr list * Unix.file_descr list) Lwt.t
module Process_success : sig
type t = {
command_line: string;
stdout: string;
stderr: string;
start_time: float;
end_time: float;
}
end
module Process_failure : sig
type t = {
command_line: string;
process_status: Unix.process_status;
stdout: string;
stderr: string;
exn: exn option;
start_time: float;
end_time: float;
}
(** Human-readable multi-line fairly verbose explanation of the failure,
aimed for logging and hack developers, not for end users *)
val to_string : t -> string
end
(** Run a command with a given input and return the output. If the command exits
with an exit status other than zero, returns [Process_failure] instead.
There are several ways for it to be cancelled:
* [cancel] parameter
e.g. `let (cancel, u) = Lwt.bind(); Lwt.wakeup_later u (); exec_checked ~cancel`
Upon the cancel parameter being completed, we will send a SIGKILL to the underlying
process. In Unix, this cannot be ignored nor blocked. It will result in
Process_failure.status=WSIGNALED Sys.sigkill, and .stdout/.stderr will contain
whatever the process had sent before that.
* [timeout] parameter
e.g. `exec_checked ~timeout:30.0`
This parameter is passed straight through to Lwt_process.open_process_full.
Its behavior is to aggressively closes stdout/stderr pipes and also send a SIGKILL.
It will result in Process_failure.status=WSIGNALED Sys.sigkill, and .stdout/.stderr
will be empty because of the closed pipes, and .exn will likely be something about
those closed pipes too.
* Lwt.cancel
e.g. `Lwt.pick [exec_checked ...; Lwt.return_none]`.
This has been deprecated as a cancellation mechanism by the Lwt folks.
This will *NOT* kill the underlying process. It will close the pipes.
As to what happens to the promise? you shouldn't really even be asking,
and indeed varies depending on the process. *)
val exec_checked :
?input:string ->
?env:string array ->
?timeout:float ->
?cancel:unit Lwt.t ->
Exec_command.t ->
string array ->
(Process_success.t, Process_failure.t) Lwt_result.t
(** Asynchronous version of [Utils.try_finally]. Run and wait for [f] to
complete, and be sure to invoke [finally] asynchronously afterward, even if [f]
raises an exception. *)
val try_finally :
f:(unit -> 'a Lwt.t) -> finally:(unit -> unit Lwt.t) -> 'a Lwt.t
(** Asynchronous version of [Utils.with_context]. Call [enter], then run and
wait for [do_] to complete, and finally call [exit], even if [f] raises an exception. *)
val with_context :
enter:(unit -> unit Lwt.t) ->
exit:(unit -> unit Lwt.t) ->
do_:(unit -> 'a Lwt.t) ->
'a Lwt.t
(** Reads all the contents from the given file on disk, or returns an error
message if unable to do so. *)
val read_all : string -> (string, string) Lwt_result.t
module Promise : Promise.S with type 'a t = 'a Lwt.t |
OCaml | hhvm/hphp/hack/src/utils/memory_stats.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 Base.Option.Monad_infix
let lines path =
try Some (Str.split (Str.regexp_string "\n") (Path.cat (Path.make path))) with
| _ -> None
let read_status pid_str =
let colon = Str.regexp_string ":" in
let to_pairs line =
match Str.split colon line with
| [k; v] -> Some (Caml.String.trim k, Caml.String.trim v)
| _ -> None
in
lines (Printf.sprintf "/proc/%s/status" pid_str)
|> Option.map ~f:(List.filter_map ~f:to_pairs)
(*
Convert the human-readable format of /proc/[pid]/status back to bytes
Because the machine-readable /proc/[pid]/stat,statm files do not have the
VmHWM we need
*)
let to_bytes_opt str =
match Str.split (Str.regexp_string " ") str with
| [amount; "kB"] -> Some (int_of_string amount * 1024)
| _ -> None
let get_status_entry status ~key =
List.Assoc.find status ~equal:String.( = ) key >>= to_bytes_opt
let get_vm_rss () = read_status "self" >>= get_status_entry ~key:"VmRSS"
let get_vm_hwm () = read_status "self" >>= get_status_entry ~key:"VmHWM"
(** Some interesting files are made of lines like "a : b". This function
reads the file and splits it into [(a,b),...] pairs. *)
let colon_file_to_pairs ~(fn : string) : (string * string) list =
match Sys_utils.cat_or_failed fn with
| None -> []
| Some text ->
let colon = Str.regexp_string ":" in
Str.split (Str.regexp_string "\n") text
|> List.filter_map ~f:(fun line ->
match Str.split colon line with
| [k; v] -> Some (String.strip k, String.strip v)
| _ -> None)
(** If we wish to store an arbitrary string as a json key, let's make it
friendly for json path accessors, by retaining only alphanumerics,
replacing everything else with _, and coalescing multiple _.
E.g. "foo:bar" will become "foo_bar". *)
let json_friendly_key (k : string) : string =
k
|> Str.global_replace (Str.regexp "[^a-zA-Z0-9]") "_"
|> Str.global_replace (Str.regexp "_+") "_"
module Histogram = struct
type t = int SMap.t
let add (v : string) (hist : t) : t =
match SMap.find_opt v hist with
| None -> SMap.add v 1 hist
| Some count -> SMap.add v (count + 1) hist
let singleton (v : string) : t = SMap.singleton v 1
(** If there is only one value in the histogram, just output this value.
Else if all values have cardinality one, output values as a list.
Else output the histogram as a dict. *)
let add_to_telemetry (key : string) (hist : t) (telemetry : Telemetry.t) :
Telemetry.t =
if SMap.cardinal hist |> Int.equal 1 then
Telemetry.string_ ~key ~value:(SMap.choose hist |> fst) telemetry
else if SMap.for_all (fun _ -> Int.equal 1) hist then
Telemetry.string_list
~key
~value:(SMap.keys hist |> List.sort ~compare:String.compare)
telemetry
else
let hist_as_telemetry =
hist
|> SMap.bindings
|> List.sort ~compare:(fun (k1, _) (k2, _) -> String.compare k1 k2)
|> List.fold
~init:(Telemetry.create ())
~f:(fun telemetry (value, count) ->
Telemetry.int_ ~key:value ~value:count telemetry)
in
Telemetry.object_ ~key ~value:hist_as_telemetry telemetry
end
(** Turns an assoc-list [(k,v),...] in an SMap. If there are multiple entries for a key
and they're all the same then we'll keep it, k->v. If there are multiple entries for
a key and any of them differ then we'll associate k with a histogram of values for v. *)
let assoc_to_dict (keyvals : (string * string) list) : Histogram.t SMap.t =
(* first, turn it into a map {k -> [v1,v2,...]} for all values associated with a key *)
List.fold keyvals ~init:SMap.empty ~f:(fun acc (k, v) ->
match SMap.find_opt k acc with
| None -> SMap.add k (Histogram.singleton v) acc
| Some histogram -> SMap.add k (Histogram.add v histogram) acc)
let get_host_hw_telemetry () =
(* this regexp will turn arbitrary ("key", "<number> <suffix>") into ("key__suffix", "<number>"),
most usefully for thing like "Mem : 12345 kB" which becomes ("Mem__kB", "12345"). *)
let re_suffix = Str.regexp "\\([0-9.]+\\) \\([a-zA-Z]+\\)" in
let file_to_telemetry fn =
let dict =
colon_file_to_pairs ~fn
|> List.map ~f:(fun (k, v) -> (json_friendly_key k, v))
|> List.map ~f:(fun (k, v) ->
if Str.string_match re_suffix v 0 then
(k ^ "__" ^ Str.matched_group 2 v, Str.matched_group 1 v)
else
(k, v))
|> assoc_to_dict
in
SMap.fold Histogram.add_to_telemetry dict (Telemetry.create ())
in
let sandcastle_capabilities =
match
Sys_utils.cat_or_failed "/data/sandcastle/run/sandcastle.capabilities"
with
| None -> Hh_json.JSON_Null
| Some s ->
(try Hh_json.json_of_string s with
| _ -> Hh_json.string_ s)
in
Telemetry.create ()
|> Telemetry.object_ ~key:"meminfo" ~value:(file_to_telemetry "/proc/meminfo")
|> Telemetry.object_ ~key:"cpuinfo" ~value:(file_to_telemetry "/proc/cpuinfo")
|> Telemetry.json_
~key:"sandcastle_capabilities"
~value:sandcastle_capabilities |
OCaml Interface | hhvm/hphp/hack/src/utils/memory_stats.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 get_vm_hwm : unit -> int option
val get_vm_rss : unit -> int option
(** A collection of telemetry about the host we're on - cpus, memory etc *)
val get_host_hw_telemetry : unit -> Telemetry.t |
OCaml | hhvm/hphp/hack/src/utils/multifile.ml | (*
* Copyright (c) 2015-present, 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
(** This allows one to fake having multiple files in one file. This
is used only in unit test files.
Indeed, there are some features that require mutliple files to be tested.
For example, newtype has a different meaning depending on the file. *)
type path = string
type content = string
let delim_regexp = "////.*\n"
let delim = Str.regexp delim_regexp
let short_suffix path =
Relative_path.suffix path |> Str.replace_first (Str.regexp "^.*--") ""
let split_multifile_content content =
let rec make_files = function
| [] -> []
| Str.Delim header :: Str.Text content :: rl ->
let pattern = Str.regexp "\n////" in
let header = Str.global_replace pattern "" header in
let pattern = Str.regexp "[ |\n]*" in
let filename = Str.global_replace pattern "" header in
(filename, content) :: make_files rl
| _ -> assert false
in
let contents =
Str.full_split (Str.regexp ("\n" ^ delim_regexp)) ("\n" ^ content)
in
make_files contents
(* We have some hacky "syntax extensions" to have one file contain multiple
* files, which can be located at arbitrary paths. This is useful e.g. for
* testing lint rules, some of which activate only on certain paths. It's also
* useful for testing abstract types, since the abstraction is enforced at the
* file boundary.
* Takes the path to a single file, returns a map of filenames to file contents.
*)
let file_to_file_list file =
let join_path p1 p2 =
let open Char in
if String.(p1 <> "" && p2 <> "") then
if p1.[String.length p1 - 1] = '/' && p2.[0] = '/' then
p1 ^ Str.string_after p2 1
else if p1.[String.length p1 - 1] <> '/' && p2.[0] <> '/' then
p1 ^ "/" ^ p2
else
p1 ^ p2
else
p1 ^ p2
in
let abs_fn = Relative_path.to_absolute file in
let content = Sys_utils.cat abs_fn in
if Str.string_match delim content 0 then
let files = split_multifile_content content in
List.map files ~f:(fun (sub_fn, c) ->
(Relative_path.create Relative_path.Dummy (abs_fn ^ "--" ^ sub_fn), c))
else if String.is_prefix content ~prefix:"// @directory " then (
let contentl = Str.split (Str.regexp "\n") content in
let first_line = List.hd_exn contentl in
let regexp =
Str.regexp "^// @directory *\\([^ ]*\\) *\\(@file *\\([^ ]*\\)*\\)?"
in
let has_match = Str.string_match regexp first_line 0 in
assert has_match;
let dir = Str.matched_group 1 first_line in
let file_name =
try Str.matched_group 3 first_line with
| Caml.Not_found -> abs_fn
in
let file =
Relative_path.create Relative_path.Dummy (join_path dir file_name)
in
let content = String.concat ~sep:"\n" (List.tl_exn contentl) in
[(file, content)]
) else
[(file, content)]
let file_to_files file = file_to_file_list file |> Relative_path.Map.of_list
(** Given a path of the form `sample/file/name.php--another/file/name.php`,
read in the portion of multifile `sample/file/name.php` corresponding
to `another/file/name.php`. *)
let read_file_from_multifile path : string list =
let splitter = ".php--" in
let ix = String_utils.substring_index splitter path in
if ix >= 0 then
let abs_fn =
String_utils.string_before path (ix + String.length ".php")
|> Relative_path.create Relative_path.Dummy
in
let rel_path = Relative_path.create Relative_path.Dummy path in
let files = file_to_files abs_fn in
match Relative_path.Map.find_opt files rel_path with
| None -> []
| Some content -> Str.split (Str.regexp "\n") content
else
[]
let print_files_as_multifile files =
if Int.equal (Relative_path.Map.cardinal files) 1 then
Out_channel.output_string stdout (Relative_path.Map.choose files |> snd)
else
Relative_path.Map.fold files ~init:[] ~f:(fun fn content acc ->
content
:: Printf.sprintf "//// %s" (Relative_path.to_absolute fn)
:: acc)
|> List.rev
|> String.concat ~sep:"\n"
|> Out_channel.output_string stdout
(** This module handles multifiles with internal file names like
'base-xxx.php' and 'changed-xxx.php' *)
module States : sig
val base_files : path -> content Relative_path.Map.t
val changed_files : path -> content Relative_path.Map.t
end = struct
let files path ~prefix =
let content = Sys_utils.cat path in
let files = split_multifile_content content in
List.filter_map files ~f:(fun (sub_fn, content) ->
match String.chop_prefix sub_fn ~prefix:(prefix ^ "-") with
| None -> None
| Some sub_fn ->
Some
( Relative_path.create Relative_path.Dummy (path ^ "--" ^ sub_fn),
content ))
|> Relative_path.Map.of_list
let base_files = files ~prefix:"base"
let changed_files = files ~prefix:"changed"
end |
OCaml Interface | hhvm/hphp/hack/src/utils/multifile.mli | (*
* Copyright (c) 2015-present, 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 allows one to fake having multiple files in one file. This
is used only in unit test files.
Indeed, there are some features that require mutliple files to be tested.
For example, newtype has a different meaning depending on the file. *)
type path = string
type content = string
val file_to_file_list : Relative_path.t -> (Relative_path.t * content) list
(** Takes the path of a "multifile".
For example if a multifile a.php has the following lines
```
//// x.php
<?hh
type F = int
//// y.php
<?hh
type G = float
```
[file_to_files] will return a map
[
"a.php--x.php" -> "<?hh
type F = int
";
"a.php--y.php" -> "<?hh
type G = float
";
]
*)
val file_to_files : Relative_path.t -> content Relative_path.Map.t
(** Multifile pathnames are like (DummyRoot, "/home/ljw/a.php--chess.php"),
or just (DummyRoot, "/home/ljw/chess.php") if there weren't any multifiles within the file.
This function strips both to "chess.php", a more appropriate rendering for test output. *)
val short_suffix : Relative_path.t -> string
(** Given a path of the form `sample/file/name.php--another/file/name.php`,
read in the portion of multifile `sample/file/name.php` corresponding
to `another/file/name.php`. *)
val read_file_from_multifile : path -> content list
val print_files_as_multifile : content Relative_path.Map.t -> unit
(** This module handles multifiles with internal file names like
'base-xxx.php' and 'changed-xxx.php' *)
module States : sig
(** Get the base files from a multifile, simarly to [file_to_files],
stripping the "base-" prefix for internal file names. *)
val base_files : path -> content Relative_path.Map.t
(** Get the changed files from a multifile, simarly to [file_to_files],
stripping the "changed-" prefix for internal file names. *)
val changed_files : path -> content Relative_path.Map.t
end |
Rust | hhvm/hphp/hack/src/utils/multifile.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
//! Multifiles fake having multiple files in one file. This is intended for use
//! only in unit test files.
//!
//! Example features that require multiple files in tests include the `newtype`
//! feature.
use std::borrow::Cow;
use std::ffi::OsStr;
use std::path::Path;
use std::path::PathBuf;
use std::str;
use anyhow::anyhow;
use lazy_static::lazy_static;
use regex::bytes::Regex;
lazy_static! {
// Matches a line denoting a single file within the multifile, and captures
// the filename.
// For example, the following line (ending with a newline)
//
// `//// foo.php`
//
// will result in a match, with "foo.php" captured.
// Note: `(?x)` ignores whitespace in the regex string.
static ref MULTIFILE_DELIM: Regex = Regex::new(r#"(?x)
(?m) # allow matching on multiple lines
^////\s*
(.+\S) # capture filename up to last non-whitespace character
\s*\n"#).unwrap();
// Matches a line of the format
//
// `// @directory some/path/here`
//
// optionally containing a @file tag followed by some file name; e.g.,
//
// `// @directory some/path/here @file foo.php`
static ref DIRECTORY: Regex =
Regex::new(r#"^// @directory \s*(\S+)\s*(?:@file\s*(\S+))?\n"#).unwrap();
}
/// Processes multifile `content` into a list of files. This function expects `content` in one of the following formats:
/// 1. A series of files.
/// 2. A single file with a specific directory.
///
/// # "series of files" format:
/// `content` represents multiple files. Each file starts with a line in the format `//// filename.php`, followed by content.
///
/// //// foo.php
///
/// function foo(): void {}
/// //// bar.php
///
/// class Bar {}
///
/// # "specific dir" format:
/// `content` represents a single file in a specific directory, denoted by
///
/// `// @directory some/dir/here`
///
/// You can optionally include a `@file` tag followed by a file name that would
/// be appended to the given directory.
///
/// See the tests for examples.
pub fn to_files<'p>(
path: &'p Path,
content: impl AsRef<[u8]> + Into<Vec<u8>>,
) -> anyhow::Result<Vec<(Cow<'p, Path>, Vec<u8>)>> {
let content = content.as_ref();
// A multifile always starts with 4 forward slashes.
if MULTIFILE_DELIM.is_match(content) {
let filename_and_content = split_multifile(&content)?;
Ok(filename_and_content
.into_iter()
.map(|(filename, content)| {
let filename = str::from_utf8(filename)?;
let filename = PathBuf::from(format!("{}--{}", path.display(), filename));
Ok((filename.into(), content))
})
.collect::<anyhow::Result<Vec<_>>>()?)
} else if let Some(captures) = DIRECTORY.captures(content) {
let dir = str::from_utf8(&captures[1])?;
let file = captures.get(2).map_or_else(
|| strip_root(path).as_os_str(),
|m| OsStr::new(str::from_utf8(m.as_bytes()).unwrap()),
);
let mut newpath = PathBuf::from(dir);
newpath.push(file);
let mut content: Vec<u8> = DIRECTORY.replace(content, &b""[..]).into();
if let Some(b'\n') = content.last() {
content.pop();
}
Ok(vec![(newpath.into(), content)])
} else {
Ok(vec![(path.into(), content.into())])
}
}
/// Given a multifile where files are prefixed either with "base-" or
/// "changed-", return the list of files prefixed with "base-", and the list of
/// files prefixed with "changed-". These prefixes are removed from the
/// resulting lists.
///
/// See the tests for an example multifile.
pub fn base_and_changed_files(
content: impl AsRef<[u8]> + Into<Vec<u8>>,
) -> anyhow::Result<(Vec<(PathBuf, Vec<u8>)>, Vec<(PathBuf, Vec<u8>)>)> {
let file_to_content = split_multifile(&content)?;
let mut base_files = vec![];
let mut changed_files = vec![];
for (file, content) in file_to_content {
let file = str::from_utf8(file)?;
let file = Path::new(file);
if let Some(base) = strip_file_name_prefix(file, "base-") {
base_files.push((base, content));
} else if let Some(changed) = strip_file_name_prefix(file, "changed-") {
changed_files.push((changed, content));
}
}
Ok((base_files, changed_files))
}
fn split_multifile<'t, T>(content: &'t T) -> anyhow::Result<Vec<(&'t [u8], Vec<u8>)>>
where
T: AsRef<[u8]> + Into<Vec<u8>>,
{
let filenames: Vec<_> = MULTIFILE_DELIM
.captures_iter(content.as_ref())
.map(|c| {
c.get(1)
.expect("delim regex should capture filename")
.as_bytes()
})
.collect();
let mut contents: Vec<Vec<u8>> = MULTIFILE_DELIM
.split(content.as_ref())
.skip(1) // skips the 0th entry (empty string)
.map(|c| c.into())
.collect();
if contents.len() + 1 == filenames.len() {
contents.push(vec![]);
} else if contents.len() != filenames.len() {
return Err(anyhow!(
"filenames len {} and content len {} mismatch.",
filenames.len(),
contents.len()
));
}
Ok(filenames.into_iter().zip(contents.into_iter()).collect())
}
// If `file`'s file name component starts with `prefix`, return `file` with that prefix removed.
fn strip_file_name_prefix(file: impl AsRef<Path>, prefix: &str) -> Option<PathBuf> {
let file_name = file.as_ref().file_name()?.to_str()?;
file_name
.strip_prefix(prefix)
.map(|stripped_file_name| file.as_ref().with_file_name(stripped_file_name))
}
fn strip_root(p: &Path) -> &Path {
if p.starts_with("/") {
p.strip_prefix("/").unwrap()
} else {
p
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn two_files() {
let p = PathBuf::from("test.php");
let c = b"//// file1.php
a
//// file2.php
b
";
let r = to_files(&p, &c[..]).unwrap();
assert_eq!(r.len(), 2);
assert_eq!(r[0].0.as_ref(), &PathBuf::from("test.php--file1.php"));
assert_eq!(r[1].0.as_ref(), &PathBuf::from("test.php--file2.php"));
assert_eq!(&r[0].1, b"a\n");
assert_eq!(&r[1].1, b"b\n");
}
#[test]
fn last_empty() {
let p = PathBuf::from("test.php");
let c = b"//// file1.php
a
////file2.php
";
let r = to_files(&p, &c[..]).unwrap();
assert_eq!(r.len(), 2);
assert_eq!(r[0].0.as_ref(), &PathBuf::from("test.php--file1.php"));
assert_eq!(r[1].0.as_ref(), &PathBuf::from("test.php--file2.php"));
assert_eq!(&r[0].1, b"a\n");
assert_eq!(&r[1].1, b"");
}
#[test]
fn mid_empty() {
let p = PathBuf::from("test.php");
let c = b"//// file1.php
//// file2.php
a
";
let r = to_files(&p, &c[..]).unwrap();
assert_eq!(r.len(), 2);
assert_eq!(r[0].0.as_ref(), &PathBuf::from("test.php--file1.php"));
assert_eq!(r[1].0.as_ref(), &PathBuf::from("test.php--file2.php"));
assert_eq!(&r[0].1, b"");
assert_eq!(&r[1].1, b"a\n");
}
#[test]
fn dir_only() {
let p = PathBuf::from("test.php");
let c = b"// @directory a/b/c
";
let r = to_files(&p, &c[..]).unwrap();
assert_eq!(r.len(), 1);
assert_eq!(r[0].0.as_ref(), &PathBuf::from("a/b/c/test.php"));
assert_eq!(&r[0].1, b"");
}
#[test]
fn dir() {
let p = PathBuf::from("test.php");
let c = b"// @directory a/b/c
a
";
let r = to_files(&p, &c[..]).unwrap();
assert_eq!(r.len(), 1);
assert_eq!(r[0].0.as_ref(), &PathBuf::from("a/b/c/test.php"));
assert_eq!(&r[0].1, b"a");
}
#[test]
fn dir_with_file() {
let p = PathBuf::from("test.php");
let c = b"// @directory a/b/c @file f.php
a
";
let r = to_files(&p, &c[..]).unwrap();
assert_eq!(r.len(), 1);
assert_eq!(r[0].0.as_ref(), &PathBuf::from("a/b/c/f.php"));
assert_eq!(&r[0].1, b"a");
}
#[test]
fn normal_file() {
let p = PathBuf::from("test.php");
let c = b"a";
let r = to_files(&p, &c[..]).unwrap();
assert_eq!(r.len(), 1);
assert_eq!(r[0].0.as_ref(), &PathBuf::from("test.php"));
assert_eq!(&r[0].1, b"a");
}
#[test]
fn test_base_and_changed_files() {
let c = b"//// base-foo.php
a
//// a/base-bar.php
b
//// changed-foo.php
c
";
let (base_files, changed_files) = base_and_changed_files(*c).unwrap();
assert_eq!(
base_files,
vec![
(PathBuf::from("foo.php"), b"a\n".to_vec()),
(PathBuf::from("a/bar.php"), b"b\n".to_vec()),
],
);
assert_eq!(
changed_files,
vec![(PathBuf::from("foo.php"), b"c\n".to_vec())]
);
}
} |
OCaml | hhvm/hphp/hack/src/utils/mutable_accumulator.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 'a t = 'a list ref
let create () = ref []
let add t s = t := s :: !t
let segments t = List.rev !t |
OCaml Interface | hhvm/hphp/hack/src/utils/mutable_accumulator.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.
*
*)
type 'a t
val create : unit -> 'a t
val add : 'a t -> 'a -> unit
val segments : 'a t -> 'a list |
Rust | hhvm/hphp/hack/src/utils/ocaml_helper.rs | // Copyright (c) 2019, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::borrow::Cow;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IntKind {
Dec,
Hex,
Oct,
Bin,
}
impl IntKind {
fn to_base(self) -> u8 {
match self {
Self::Bin => 2,
Self::Oct => 8,
Self::Dec => 10,
Self::Hex => 16,
}
}
}
impl std::fmt::Display for IntKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.write_str(match self {
Self::Dec => "decimal",
Self::Hex => "hexadecimal",
Self::Oct => "octal",
Self::Bin => "binary",
})
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum ParseIntError {
/// Valid digits are
/// - dec [0-9],
/// - hex [0-9a-fA-F],
/// - oct [0-7]
/// - bin [0|1]
InvalidDigit(IntKind),
OutOfRange,
Empty,
}
// Port from https://github.com/ocaml/ocaml/blob/6efe8fea5b6c3f1db22e50e8b164d6ffec85578d/runtime/ints.c
fn parse_sign_and_base(p: &[u8], preceding_zero_as_oct: bool) -> (i8, IntKind, &[u8]) {
let mut sign = 1i8;
if p.is_empty() {
return (sign, IntKind::Dec, p);
}
let mut i = 0;
if p[i] == b'-' {
sign = -1;
i += 1;
} else if p[i] == b'+' {
i += 1;
}
if p.len() > i + 1 && p[i] == b'0' {
match p[i + 1] {
b'x' | b'X' => (sign, IntKind::Hex, &p[i + 2..]),
b'o' | b'O' => (sign, IntKind::Oct, &p[i + 2..]),
b'b' | b'B' => (sign, IntKind::Bin, &p[i + 2..]),
_ => {
if preceding_zero_as_oct {
(sign, IntKind::Oct, &p[i + 1..])
} else {
(sign, IntKind::Dec, &p[i..])
}
}
}
} else {
(sign, IntKind::Dec, &p[i..])
}
}
fn parse_digit(c: u8, int_kind: IntKind) -> Result<u8, ParseIntError> {
if (b'0'..=b'9').contains(&c) {
Ok(c - b'0')
} else if (b'A'..=b'F').contains(&c) {
Ok(c - b'A' + 10)
} else if (b'a'..=b'f').contains(&c) {
Ok(c - b'a' + 10)
} else {
Err(ParseIntError::InvalidDigit(int_kind))
}
}
pub fn parse_int(p: impl AsRef<[u8]>) -> Result<i64, ParseIntError> {
parse(p.as_ref(), true)
}
pub fn int_of_string_opt(p: impl AsRef<[u8]>) -> Option<i64> {
parse(p.as_ref(), false).ok()
}
fn parse(p: &[u8], preceding_zero_as_oct: bool) -> Result<i64, ParseIntError> {
let (sign, int_kind, p) = parse_sign_and_base(p, preceding_zero_as_oct);
let base = int_kind.to_base();
if p.is_empty() {
return Err(ParseIntError::Empty);
}
let mut r = 0i64;
for (i, digit) in p.iter().copied().enumerate() {
if i != 0 && digit == b'_' {
continue;
}
let d = parse_digit(digit, int_kind)?;
if d >= base {
return Err(ParseIntError::InvalidDigit(int_kind));
} else {
r = i64::checked_mul(r, base as i64).ok_or(ParseIntError::OutOfRange)?;
if sign >= 0 {
r = i64::checked_add(r, d as i64).ok_or(ParseIntError::OutOfRange)?;
} else {
r = i64::checked_sub(r, d as i64).ok_or(ParseIntError::OutOfRange)?;
}
}
}
Ok(r)
}
pub fn int_of_string_wrap(p: &[u8]) -> Result<i64, ParseIntError> {
let (sign, int_kind, p) = parse_sign_and_base(p, false);
let base = int_kind.to_base();
if p.is_empty() {
return Err(ParseIntError::Empty);
}
let mut r = 0i64;
for (i, digit) in p.iter().copied().enumerate() {
if i != 0 && digit == b'_' {
continue;
}
let d = parse_digit(digit, int_kind)?;
if d >= base {
return Err(ParseIntError::InvalidDigit(int_kind));
} else {
r = i64::overflowing_mul(r, base as i64).0;
if sign >= 0 {
r = i64::overflowing_add(r, d as i64).0;
} else {
r = i64::overflowing_sub(r, d as i64).0;
}
}
}
Ok(r)
}
pub fn int_of_str_opt(s: impl AsRef<str>) -> Option<i64> {
int_of_string_opt(s.as_ref().as_bytes())
}
/// ported from supercaml/share/dotopam/default/lib/ocaml/bytes.ml
/// github link: https://github.com/ocaml/ocaml/blob/4.09.1/stdlib/bytes.ml#L170-L208
pub fn escaped(s: &str) -> Cow<'_, str> {
let es = escaped_bytes(s.as_bytes());
match es {
Cow::Borrowed(_) => s.into(),
Cow::Owned(es) => {
// Safety - since the input is &str this should be safe.
unsafe { String::from_utf8_unchecked(es) }.into()
}
}
}
pub fn escaped_bytes(s: &[u8]) -> Cow<'_, [u8]> {
let mut n: usize = 0;
for i in s {
n += match i {
b'"' | b'\\' | b'\n' | b'\t' | b'\r' | 8 => 2,
b' '..=b'~' => 1,
_ => 4,
};
}
if n == s.len() {
s.into()
} else {
let mut es: Vec<u8> = Vec::with_capacity(n);
n = 0;
for i in s {
match i {
b'"' | b'\\' => {
es.push(b'\\');
n += 1;
es.push(*i);
}
b'\n' => {
es.push(b'\\');
n += 1;
es.push(b'n');
}
b'\t' => {
es.push(b'\\');
n += 1;
es.push(b't');
}
b'\r' => {
es.push(b'\\');
n += 1;
es.push(b'r');
}
8 => {
es.push(b'\\');
n += 1;
es.push(b'b');
}
x @ b' '..=b'~' => es.push(*x),
_ => {
es.push(b'\\');
n += 1;
es.push(48 + i / 100);
n += 1;
es.push(48 + (i / 10) % 10);
n += 1;
es.push(48 + i % 10);
}
}
n += 1;
}
es.into()
}
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn parse_digit_tests() {
use parse_digit as f;
assert_eq!(f(b'0', IntKind::Dec), Ok(0));
assert_eq!(f(b'1', IntKind::Dec), Ok(1));
assert_eq!(f(b'9', IntKind::Dec), Ok(9));
assert_eq!(f(b'A', IntKind::Hex), Ok(10));
assert_eq!(f(b'a', IntKind::Hex), Ok(10));
assert_eq!(f(b'F', IntKind::Hex), Ok(15));
assert_eq!(f(b'f', IntKind::Hex), Ok(15));
assert_eq!(
f(b'-', IntKind::Dec),
Err(ParseIntError::InvalidDigit(IntKind::Dec))
);
assert_eq!(
f(b'z', IntKind::Dec),
Err(ParseIntError::InvalidDigit(IntKind::Dec))
);
}
#[test]
fn parse_sign_and_base_tests() {
let f = |s| parse_sign_and_base(s, false);
assert_eq!(f(b""), (1, IntKind::Dec, &b""[..]));
assert_eq!(f(b"-"), (-1, IntKind::Dec, &b""[..]));
assert_eq!(f(b"+"), (1, IntKind::Dec, &b""[..]));
assert_eq!(f(b"z"), (1, IntKind::Dec, &b"z"[..]));
assert_eq!(f(b"0"), (1, IntKind::Dec, &b"0"[..]));
assert_eq!(f(b"0x"), (1, IntKind::Hex, &b""[..]));
assert_eq!(f(b"0X"), (1, IntKind::Hex, &b""[..]));
assert_eq!(f(b"0o"), (1, IntKind::Oct, &b""[..]));
assert_eq!(f(b"0O"), (1, IntKind::Oct, &b""[..]));
assert_eq!(f(b"0b"), (1, IntKind::Bin, &b""[..]));
assert_eq!(f(b"0B"), (1, IntKind::Bin, &b""[..]));
assert_eq!(f(b"-1"), (-1, IntKind::Dec, &b"1"[..]));
assert_eq!(f(b"+1"), (1, IntKind::Dec, &b"1"[..]));
assert_eq!(f(b"-x"), (-1, IntKind::Dec, &b"x"[..]));
assert_eq!(f(b"+B"), (1, IntKind::Dec, &b"B"[..]));
assert_eq!(f(b"-O1"), (-1, IntKind::Dec, &b"O1"[..]));
assert_eq!(f(b"-0O1"), (-1, IntKind::Oct, &b"1"[..]));
assert_eq!(f(b"-0"), (-1, IntKind::Dec, &b"0"[..]));
assert_eq!(f(b"+0"), (1, IntKind::Dec, &b"0"[..]));
}
#[test]
fn int_of_string_opt_tests() {
use int_of_string_opt as f;
assert_eq!(f(""), None);
assert_eq!(f("-"), None);
assert_eq!(f("+"), None);
assert_eq!(f("0x"), None);
assert_eq!(f("0x"), None);
assert_eq!(f("10"), Some(10));
assert_eq!(f("1_0"), Some(10));
assert_eq!(f("_10"), None);
assert_eq!(f("0x10"), Some(16));
assert_eq!(f("9223372036854775807"), Some(std::i64::MAX));
assert_eq!(f("9223372036854775808"), None);
assert_eq!(f("0x7FFFFFFFFFFFFFFF"), Some(std::i64::MAX));
assert_eq!(f("-0x8000000000000000"), Some(std::i64::MIN));
assert_eq!(f("0x8000000000000000"), None);
assert_eq!(f("-0x8000000000000001"), None);
assert_eq!(
f("0b111111111111111111111111111111111111111111111111111111111111111"),
Some(std::i64::MAX)
);
assert_eq!(
f("-0b1000000000000000000000000000000000000000000000000000000000000000"),
Some(std::i64::MIN)
);
assert_eq!(f("-_10"), None);
assert_eq!(f("-0b10"), Some(-2));
assert_eq!(f("-0b10"), Some(-2));
assert_eq!(f("-9223372036854775808"), Some(std::i64::MIN));
assert_eq!(f("-9223372036854775809"), None);
assert_eq!(f("-0"), Some(0));
assert_eq!(f("-0_"), Some(0));
assert_eq!(f("+0"), Some(0));
}
#[test]
fn parse_int_tests() {
use parse_int as f;
assert_eq!(f(""), Err(ParseIntError::Empty));
assert_eq!(f("-"), Err(ParseIntError::Empty));
assert_eq!(f("+"), Err(ParseIntError::Empty));
assert_eq!(f("0x"), Err(ParseIntError::Empty));
assert_eq!(f("0x"), Err(ParseIntError::Empty));
assert_eq!(f("10"), Ok(10));
assert_eq!(f("1_0"), Ok(10));
assert_eq!(f("_10"), Err(ParseIntError::InvalidDigit(IntKind::Dec)));
assert_eq!(f("0x10"), Ok(16));
assert_eq!(f("9223372036854775807"), Ok(std::i64::MAX));
assert_eq!(f("9223372036854775808"), Err(ParseIntError::OutOfRange));
assert_eq!(f("0x7FFFFFFFFFFFFFFF"), Ok(std::i64::MAX));
assert_eq!(f("-0x8000000000000000"), Ok(std::i64::MIN));
assert_eq!(f("0x8000000000000000"), Err(ParseIntError::OutOfRange));
assert_eq!(f("-0x8000000000000001"), Err(ParseIntError::OutOfRange));
assert_eq!(
f("0b111111111111111111111111111111111111111111111111111111111111111"),
Ok(std::i64::MAX)
);
assert_eq!(
f("-0b1000000000000000000000000000000000000000000000000000000000000000"),
Ok(std::i64::MIN)
);
assert_eq!(f("-_10"), Err(ParseIntError::InvalidDigit(IntKind::Dec)));
assert_eq!(f("-0b10"), Ok(-2));
assert_eq!(f("-0b10"), Ok(-2));
assert_eq!(f("-9223372036854775808"), Ok(std::i64::MIN));
assert_eq!(f("-9223372036854775809"), Err(ParseIntError::OutOfRange));
assert_eq!(f("-0"), Ok(0));
assert_eq!(f("+0"), Ok(0));
assert_eq!(f("010"), Ok(8));
assert_eq!(f("-010"), Ok(-8));
assert_eq!(f("0777777777777777777777"), Ok(std::i64::MAX));
assert_eq!(f("-01000000000000000000000"), Ok(std::i64::MIN));
assert_eq!(f("01000000000000000000000"), Err(ParseIntError::OutOfRange));
assert_eq!(
f("-01000000000000000000001"),
Err(ParseIntError::OutOfRange)
);
}
#[test]
fn test_escaped() {
use escaped as e;
assert_eq!(e(""), "");
assert_eq!(e("a"), "a");
assert_eq!(e("\n"), "\\n");
assert_eq!(e("\t"), "\\t");
assert_eq!(e("\r"), "\\r");
assert_eq!(e("'"), "'");
assert_eq!(e("\""), "\\\"");
assert_eq!(e("\\"), "\\\\");
assert_eq!(e(String::from_utf8(vec![127]).unwrap().as_str()), "\\127");
assert_eq!(e(String::from_utf8(vec![8]).unwrap().as_str()), "\\b");
assert_eq!(
e(unsafe { String::from_utf8_unchecked(vec![255]) }.as_str()),
"\\255"
);
}
} |
OCaml | hhvm/hphp/hack/src/utils/ocaml_overrides.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.
*
*)
(**
* We override some things in the Ocaml system so that we can have our own
* implementations. This is useful for mocking/testing/injecting modules
* that override Ocaml's default behavior.
*
* Please include this everywhere you use Sys and Unix.
*)
module Ocaml_unix = Unix
module Ocaml_Sys = Sys
module Unix = struct
include Ocaml_unix
let getcwd () = Disk.getcwd ()
let chdir = Disk.chdir
let mkdir = Disk.mkdir
let rename = Disk.rename
end
module Sys = struct
include Ocaml_Sys
let getcwd () = Disk.getcwd ()
let chdir = Disk.chdir
let is_directory = Disk.is_directory
let rename = Disk.rename
let file_exists = Disk.file_exists
let readdir = Disk.readdir
end |
OCaml Interface | hhvm/hphp/hack/src/utils/ocaml_overrides.mli | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module Ocaml_unix = Unix
module Ocaml_Sys = Sys
module Unix : sig
(* Import ocaml's Unix module signature *)
include module type of Ocaml_unix
end
module Sys : sig
(* Import ocaml's Sys module signature *)
include module type of Ocaml_Sys
(* Shadow the ones we redeclare cause they all have `external` in the
* original signature.
*)
val getcwd : unit -> string
val chdir : string -> unit
val is_directory : string -> bool
val rename : string -> string -> unit
val file_exists : string -> bool
val readdir : string -> string array
end |
OCaml | hhvm/hphp/hack/src/utils/php_escaping.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.
*
*)
(* Implementation of string escaping stuff. Ugggggggh.
* See http://php.net/manual/en/language.types.string.php *)
open Hh_prelude
let is_printable c =
let open Char in
c >= ' ' && c <= '~'
let is_lit_printable c =
let open Char in
is_printable c && c <> '\\' && c <> '\"'
let escape_char = function
| '\n' -> "\\n"
| '\r' -> "\\r"
| '\t' -> "\\t"
| '\\' -> "\\\\"
| '"' -> "\\\""
| '$' -> "$"
| c when is_lit_printable c -> String.make 1 c
| c -> Printf.sprintf "\\%03o" (Char.to_int c)
let escape ?(f = escape_char) s =
let buf = Buffer.create (String.length s) in
Caml.String.iter (fun c -> Buffer.add_string buf @@ f c) s;
Buffer.contents buf |
OCaml Interface | hhvm/hphp/hack/src/utils/php_escaping.mli | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val is_lit_printable : char -> bool
val escape_char : char -> string
val escape : ?f:(char -> string) -> string -> string |
OCaml | hhvm/hphp/hack/src/utils/pos.ml | (** Positions embedded with full position info inside its
* data structure. See "type 'a pos"
*
* Note: This module can only be used with the Lexbuf Pos_source
* module, as it will not compile with other Pos_source modules. So,
* when choosing a different Pos module, you must also choose its
* compatible Pos_source module. *)
open Hh_prelude
open Lexing
type b = Pos_source.t
(* Note: While Pos.string and Pos.info_pos return positions as closed intervals,
* pos_start and pos_end actually form a half-open interval (i.e. pos_end points
* to the character *after* the last character of the relevant lexeme.) *)
[@@@warning "-32"]
type 'a pos =
| Pos_small of {
pos_file: 'a;
pos_start: File_pos_small.t;
pos_end: File_pos_small.t;
}
| Pos_large of {
pos_file: 'a;
pos_start: File_pos_large.t;
pos_end: File_pos_large.t;
}
| Pos_tiny of {
pos_file: 'a;
pos_span: Pos_span_tiny.t;
}
| Pos_from_reason of 'a pos
[@@deriving eq, hash, show]
type t = Relative_path.t pos [@@deriving eq, hash, show]
type absolute = string pos [@@deriving eq, show]
[@@@warning "+32"]
let none =
Pos_tiny { pos_file = Relative_path.default; pos_span = Pos_span_tiny.dummy }
let rec pp fmt pos =
if equal pos none then
Format.pp_print_string fmt "[Pos.none]"
else (
Format.pp_print_string fmt "[";
begin
match pos with
| Pos_small { pos_start; pos_end; _ } ->
File_pos_small.pp fmt pos_start;
Format.pp_print_string fmt "-";
if File_pos_small.line pos_start = File_pos_small.line pos_end then
Format.pp_print_int fmt @@ (File_pos_small.column pos_end + 1)
else
File_pos_small.pp fmt pos_end
| Pos_large { pos_start; pos_end; _ } ->
File_pos_large.pp fmt pos_start;
Format.pp_print_string fmt "-";
if File_pos_large.line pos_start = File_pos_large.line pos_end then
Format.pp_print_int fmt @@ (File_pos_large.column pos_end + 1)
else
File_pos_large.pp fmt pos_end
| Pos_tiny { pos_span; pos_file = _ } -> Pos_span_tiny.pp fmt pos_span
| Pos_from_reason p -> pp fmt p
end;
Format.pp_print_string fmt "]"
)
let rec filename p =
match p with
| Pos_small { pos_file; _ }
| Pos_large { pos_file; _ }
| Pos_tiny { pos_file; _ } ->
pos_file
| Pos_from_reason p -> filename p
(** This returns a closed interval that's incorrect for multi-line spans. *)
let rec info_pos p =
match p with
| Pos_small { pos_start; pos_end; _ } ->
let (line, start_minus1, bol) = File_pos_small.line_column_beg pos_start in
let start = start_minus1 + 1 in
let end_offset = File_pos_small.offset pos_end in
let end_ = end_offset - bol in
(* To represent the empty interval, pos_start and pos_end are equal because
end_offset is exclusive. Here, it's best for error messages to the user if
we print characters N to N (highlighting a single character) rather than characters
N to (N-1), which is very unintuitive.
*)
let end_ =
if start = end_ + 1 then
start
else
end_
in
(line, start, end_)
| Pos_large { pos_start; pos_end; _ } ->
let (line, start_minus1, bol) = File_pos_large.line_column_beg pos_start in
let start = start_minus1 + 1 in
let end_offset = File_pos_large.offset pos_end in
let end_ = end_offset - bol in
(* To represent the empty interval, pos_start and pos_end are equal because
end_offset is exclusive. Here, it's best for error messages to the user if
we print characters N to N (highlighting a single character) rather than characters
N to (N-1), which is very unintuitive.
*)
let end_ =
if start = end_ + 1 then
start
else
end_
in
(line, start, end_)
| Pos_tiny { pos_span = span; pos_file = _ } ->
let line = Pos_span_tiny.start_line_number span in
let start_column = Pos_span_tiny.start_column span + 1 in
let end_column = Pos_span_tiny.end_column span in
let end_column =
if start_column = end_column + 1 then
start_column
else
end_column
in
(line, start_column, end_column)
| Pos_from_reason p -> info_pos p
(* This returns a closed interval. *)
let rec info_pos_extended p =
let (line_begin, start, end_) = info_pos p in
match p with
| Pos_small { pos_end; _ } ->
let (line_end, _, _) = File_pos_small.line_column_beg pos_end in
(line_begin, line_end, start, end_)
| Pos_large { pos_end; _ } ->
let (line_end, _, _) = File_pos_large.line_column_beg pos_end in
(line_begin, line_end, start, end_)
| Pos_tiny { pos_span; pos_file = _ } ->
let line_end = Pos_span_tiny.end_line_number pos_span in
(line_begin, line_end, start, end_)
| Pos_from_reason p -> info_pos_extended p
let rec info_raw p =
match p with
| Pos_small { pos_start; pos_end; _ } ->
(File_pos_small.offset pos_start, File_pos_small.offset pos_end)
| Pos_large { pos_start; pos_end; _ } ->
(File_pos_large.offset pos_start, File_pos_large.offset pos_end)
| Pos_tiny { pos_span; pos_file = _ } ->
(Pos_span_tiny.start_offset pos_span, Pos_span_tiny.end_offset pos_span)
| Pos_from_reason p -> info_raw p
let rec length p =
match p with
| Pos_small { pos_start; pos_end; _ } ->
File_pos_small.offset pos_end - File_pos_small.offset pos_start
| Pos_large { pos_start; pos_end; _ } ->
File_pos_large.offset pos_end - File_pos_large.offset pos_start
| Pos_tiny { pos_span; pos_file = _ } ->
Pos_span_tiny.end_offset pos_span - Pos_span_tiny.start_offset pos_span
| Pos_from_reason p -> length p
let rec start_offset p =
match p with
| Pos_small { pos_start; _ } -> File_pos_small.offset pos_start
| Pos_large { pos_start; _ } -> File_pos_large.offset pos_start
| Pos_tiny { pos_span; _ } -> Pos_span_tiny.start_offset pos_span
| Pos_from_reason p -> start_offset p
let rec end_offset p =
match p with
| Pos_small { pos_end; _ } -> File_pos_small.offset pos_end
| Pos_large { pos_end; _ } -> File_pos_large.offset pos_end
| Pos_tiny { pos_span; _ } -> Pos_span_tiny.end_offset pos_span
| Pos_from_reason p -> end_offset p
let rec line p =
match p with
| Pos_small { pos_start; _ } -> File_pos_small.line pos_start
| Pos_large { pos_start; _ } -> File_pos_large.line pos_start
| Pos_tiny { pos_span; _ } -> Pos_span_tiny.start_line_number pos_span
| Pos_from_reason p -> line p
let rec end_line p =
match p with
| Pos_small { pos_end; _ } -> File_pos_small.line pos_end
| Pos_large { pos_end; _ } -> File_pos_large.line pos_end
| Pos_tiny { pos_span; _ } -> Pos_span_tiny.end_line_number pos_span
| Pos_from_reason p -> end_line p
(* This returns a closed interval. *)
let string t =
let (line, start, end_) = info_pos t in
let path = filename t in
let hhi_path =
try Relative_path.path_of_prefix Relative_path.Hhi with
| Invalid_argument _ ->
(* .hhi path hasn't been set (e.g. when running tests). *)
""
in
(* Strip temporary .hhi directories from the path shown. *)
let path =
match String.chop_prefix path ~prefix:hhi_path with
| Some file_path -> file_path
| None -> path
in
Printf.sprintf "File %S, line %d, characters %d-%d:" path line start end_
(* Some positions, like those in buffers sent by IDE/created by unit tests might
* not have a file specified.
* This returns a closed interval. *)
let string_no_file t =
let (line, start, end_) = info_pos t in
Printf.sprintf "line %d, characters %d-%d" line start end_
(* This returns a closed interval. *)
let json pos =
let (line, start, end_) = info_pos pos in
let fn = filename pos in
Hh_json.JSON_Object
[
("filename", Hh_json.JSON_String fn);
("line", Hh_json.int_ line);
("char_start", Hh_json.int_ start);
("char_end", Hh_json.int_ end_);
]
let json_no_filename pos =
let (line, start, end_) = info_pos pos in
Hh_json.JSON_Object
[
("line", Hh_json.int_ line);
("char_start", Hh_json.int_ start);
("char_end", Hh_json.int_ end_);
]
(*
* !!! Be careful !!!
* This method returns zero-based column numbers, but one-based line numbers.
* Consider using info_pos instead.
*)
let rec line_column p =
match p with
| Pos_small { pos_start; _ } -> File_pos_small.line_column pos_start
| Pos_large { pos_start; _ } -> File_pos_large.line_column pos_start
| Pos_tiny { pos_span; _ } ->
( Pos_span_tiny.start_line_number pos_span,
Pos_span_tiny.start_column pos_span )
| Pos_from_reason p -> line_column p
let rec end_line_column p =
match p with
| Pos_small { pos_end; _ } -> File_pos_small.line_column pos_end
| Pos_large { pos_end; _ } -> File_pos_large.line_column pos_end
| Pos_tiny { pos_span; _ } ->
(Pos_span_tiny.end_line_number pos_span, Pos_span_tiny.end_column pos_span)
| Pos_from_reason p -> end_line_column p
let inside p line char_pos =
let (first_line, first_col) = line_column p in
let (last_line, last_col) = end_line_column p in
if first_line = last_line then
first_line = line && first_col + 1 <= char_pos && char_pos <= last_col
else if line = first_line then
char_pos > first_col
else if line = last_line then
char_pos <= last_col
else
line > first_line && line < last_line
let exactly_matches_range p ~start_line ~start_col ~end_line ~end_col =
let (p_start_line, p_start_col) = line_column p in
let (p_end_line, p_end_col) = end_line_column p in
p_start_line = start_line
&& p_start_col = start_col - 1
&& p_end_line = end_line
&& p_end_col = end_col - 1
let contains pos_container pos =
let (cstart, cend) = info_raw pos_container in
let (pstart, pend) = info_raw pos in
Relative_path.equal (filename pos_container) (filename pos)
&& pstart >= cstart
&& pend <= cend
let overlaps pos1 pos2 =
let (start1, end1) = info_raw pos1 in
let (start2, end2) = info_raw pos2 in
Relative_path.equal (filename pos1) (filename pos2)
&& end1 > start2
&& start1 < end2
let is_hhi pos = Relative_path.is_hhi (Relative_path.prefix (filename pos))
let rec compress p =
match p with
| Pos_tiny _ -> p
| Pos_small { pos_file; pos_start; pos_end } ->
(match
Pos_span_tiny.make
~pos_start:(File_pos_small.as_large_pos pos_start)
~pos_end:(File_pos_small.as_large_pos pos_end)
with
| None -> p
| Some pos_span -> Pos_tiny { pos_file; pos_span })
| Pos_large { pos_file; pos_start; pos_end } ->
(match Pos_span_tiny.make ~pos_start ~pos_end with
| Some pos_span -> Pos_tiny { pos_file; pos_span }
| None ->
(match File_pos_small.of_large_pos pos_start with
| None -> p
| Some pos_start ->
(match File_pos_small.of_large_pos pos_end with
| None -> p
| Some pos_end -> Pos_small { pos_file; pos_start; pos_end })))
| Pos_from_reason p -> Pos_from_reason (compress p)
let make_from_lexing_pos pos_file pos_start pos_end =
compress
@@ Pos_large
{
pos_file;
pos_start = File_pos_large.of_lexing_pos pos_start;
pos_end = File_pos_large.of_lexing_pos pos_end;
}
let make file (lb : b) =
let pos_start = lexeme_start_p lb in
let pos_end = lexeme_end_p lb in
make_from_lexing_pos file pos_start pos_end
let make_from file =
Pos_tiny { pos_file = file; pos_span = Pos_span_tiny.dummy }
let rec as_large_pos p =
match p with
| Pos_tiny { pos_file; pos_span } ->
let (pos_start, pos_end) = Pos_span_tiny.as_large_span pos_span in
Pos_large { pos_file; pos_start; pos_end }
| Pos_small { pos_file; pos_start; pos_end } ->
Pos_large
{
pos_file;
pos_start = File_pos_small.as_large_pos pos_start;
pos_end = File_pos_small.as_large_pos pos_end;
}
| Pos_large _ -> p
| Pos_from_reason p -> Pos_from_reason (as_large_pos p)
let rec btw_nocheck x1 x2 =
match (x1, x2) with
| (Pos_small { pos_file; pos_start; _ }, Pos_small { pos_end; _ }) ->
Pos_small { pos_file; pos_start; pos_end }
| (Pos_large { pos_file; pos_start; _ }, Pos_large { pos_end; _ }) ->
Pos_large { pos_file; pos_start; pos_end }
| (Pos_small { pos_file; pos_start; _ }, Pos_large { pos_end; _ }) ->
Pos_large
{ pos_file; pos_start = File_pos_small.as_large_pos pos_start; pos_end }
| (Pos_large { pos_file; pos_start; _ }, Pos_small { pos_end; _ }) ->
Pos_large
{ pos_file; pos_start; pos_end = File_pos_small.as_large_pos pos_end }
| (Pos_from_reason p1, p2) -> btw_nocheck p1 p2
| (p1, Pos_from_reason p2) -> btw_nocheck p1 p2
| (Pos_tiny _, _)
| (_, Pos_tiny _) ->
let p1 = as_large_pos x1 in
let p2 = as_large_pos x2 in
btw_nocheck p1 p2 |> compress
let rec set_file pos_file pos =
match pos with
| Pos_small { pos_start; pos_end; _ } ->
Pos_small { pos_file; pos_start; pos_end }
| Pos_large { pos_start; pos_end; _ } ->
Pos_large { pos_file; pos_start; pos_end }
| Pos_tiny { pos_span; pos_file = _ } -> Pos_tiny { pos_file; pos_span }
| Pos_from_reason p -> Pos_from_reason (set_file pos_file p)
let set_col_start pos_cnum pos =
let pos = as_large_pos pos in
match pos with
| Pos_large { pos_file; pos_start; pos_end } ->
let pos_start = File_pos_large.set_column pos_cnum pos_start in
Pos_large { pos_file; pos_start; pos_end }
| _ -> pos
let set_col_end pos_cnum pos =
let pos = as_large_pos pos in
match pos with
| Pos_large { pos_file; pos_start; pos_end } ->
let pos_end = File_pos_large.set_column pos_cnum pos_end in
Pos_large { pos_file; pos_start; pos_end }
| _ -> pos
let rec shrink_to_start pos =
let pos = as_large_pos pos in
match pos with
| Pos_large { pos_file; pos_start; _ } ->
Pos_large { pos_file; pos_start; pos_end = pos_start }
| Pos_from_reason p -> Pos_from_reason (shrink_to_start p)
| _ -> pos
let rec shrink_to_end pos =
let pos = as_large_pos pos in
match pos with
| Pos_large { pos_file; pos_end; _ } ->
Pos_large { pos_file; pos_start = pos_end; pos_end }
| Pos_from_reason p -> Pos_from_reason (shrink_to_end p)
| _ -> pos
let set_from_reason pos =
match pos with
| Pos_from_reason _ -> pos
| _ -> Pos_from_reason pos
let get_from_reason pos =
match pos with
| Pos_from_reason _ -> true
| _ -> false
let to_absolute p = set_file (Relative_path.to_absolute (filename p)) p
let to_relative p = set_file (Relative_path.create_detect_prefix (filename p)) p
let btw x1 x2 =
if not (Relative_path.equal (filename x1) (filename x2)) then
failwith "Position in separate files";
if end_offset x1 > end_offset x2 then
failwith
(Printf.sprintf
"btw: invalid positions %s and %s"
(string (to_absolute x1))
(string (to_absolute x2)));
btw_nocheck x1 x2
let rec merge x1 x2 =
match (x1, x2) with
| ( Pos_small { pos_file = file1; pos_start = start1; pos_end = end1 },
Pos_small { pos_file = _; pos_start = start2; pos_end = end2; _ } ) ->
let pos_start =
if File_pos_small.is_dummy start1 then
start2
else if File_pos_small.is_dummy start2 then
start1
else if start_offset x1 < start_offset x2 then
start1
else
start2
in
let pos_end =
if File_pos_small.is_dummy end1 then
end2
else if File_pos_small.is_dummy end2 then
end1
else if end_offset x1 < end_offset x2 then
end2
else
end1
in
Pos_small { pos_file = file1; pos_start; pos_end }
| ( Pos_large { pos_file = file1; pos_start = start1; pos_end = end1 },
Pos_large { pos_file = _; pos_start = start2; pos_end = end2; _ } ) ->
let pos_start =
if File_pos_large.is_dummy start1 then
start2
else if File_pos_large.is_dummy start2 then
start1
else if start_offset x1 < start_offset x2 then
start1
else
start2
in
let pos_end =
if File_pos_large.is_dummy end1 then
end2
else if File_pos_large.is_dummy end2 then
end1
else if end_offset x1 < end_offset x2 then
end2
else
end1
in
Pos_large { pos_file = file1; pos_start; pos_end }
| (Pos_from_reason p1, Pos_from_reason p2) -> Pos_from_reason (merge p1 p2)
| (Pos_from_reason p1, p2) -> Pos_from_reason (merge p1 p2)
| (p1, Pos_from_reason p2) -> Pos_from_reason (merge p1 p2)
| (_, _) -> merge (as_large_pos x1) (as_large_pos x2) |> compress
let rec last_char p =
if equal p none then
none
else
(match p with
| Pos_small { pos_start = _; pos_end; pos_file } ->
Pos_small { pos_start = pos_end; pos_end; pos_file }
| Pos_large { pos_start = _; pos_end; pos_file } ->
Pos_large { pos_start = pos_end; pos_end; pos_file }
| Pos_tiny { pos_span; pos_file } ->
let (_pos_start, pos_end) = Pos_span_tiny.as_large_span pos_span in
Pos_large { pos_file; pos_start = pos_end; pos_end }
| Pos_from_reason p -> last_char p)
|> compress
let rec first_char_of_line p =
if equal p none then
none
else
(match p with
| Pos_small { pos_start; pos_end = _; pos_file } ->
let start = File_pos_small.set_column_unchecked 0 pos_start in
Pos_small { pos_start = start; pos_end = start; pos_file }
| Pos_large { pos_start; pos_end = _; pos_file } ->
let start = File_pos_large.set_column 0 pos_start in
Pos_large { pos_start = start; pos_end = start; pos_file }
| Pos_tiny { pos_span; pos_file } ->
let (pos_start, _pos_end) = Pos_span_tiny.as_large_span pos_span in
let start = File_pos_large.set_column 0 pos_start in
Pos_large { pos_file; pos_start = start; pos_end = start }
| Pos_from_reason p -> first_char_of_line p)
|> compress
let to_relative_string p = set_file (Relative_path.suffix (filename p)) p
let get_text_from_pos ~content pos =
let pos_length = length pos in
let offset = start_offset pos in
String.sub content ~pos:offset ~len:pos_length
(** Compare by filename, then tie-break by start position, and finally by the
end position *)
let compare_pos :
type file. (file -> file -> int) -> file pos -> file pos -> int =
fun compare_files x y ->
let r = compare_files (filename x) (filename y) in
if r <> 0 then
r
else
let (xstart, xend) = info_raw x in
let (ystart, yend) = info_raw y in
let r = xstart - ystart in
if r <> 0 then
r
else
xend - yend
let compare = compare_pos Relative_path.compare
let compare_absolute = compare_pos String.compare
(* This returns a half-open interval. *)
let destruct_range (p : 'a pos) : int * int * int * int =
let (line_start, col_start_minus1) = line_column p in
let (line_end, col_end_minus1) = end_line_column p in
(line_start, col_start_minus1 + 1, line_end, col_end_minus1 + 1)
let rec advance_one (p : 'a pos) : 'a pos =
match p with
| Pos_small { pos_file; pos_start; pos_end } ->
let end_column = File_pos_small.column pos_end in
(match File_pos_small.set_column (end_column + 1) pos_end with
| Some pos_end -> Pos_small { pos_file; pos_start; pos_end }
| None ->
let pos_start = File_pos_small.as_large_pos pos_start in
let pos_end = File_pos_small.as_large_pos pos_end in
let pos_end = File_pos_large.set_column (end_column + 1) pos_end in
Pos_large { pos_file; pos_start; pos_end })
| Pos_large { pos_file; pos_start; pos_end } ->
Pos_large
{
pos_file;
pos_start;
pos_end =
(let column = File_pos_large.column pos_end in
File_pos_large.set_column (column + 1) pos_end);
}
| Pos_tiny _ -> p |> as_large_pos |> advance_one |> compress
| Pos_from_reason p -> Pos_from_reason (advance_one p)
(* This function is used when we have captured a position that includes
* outside boundary characters like apostrophes. If we need to remove these
* apostrophes, this function shrinks by one character in each direction. *)
let rec shrink_by_one_char_both_sides (p : 'a pos) : 'a pos =
match p with
| Pos_small { pos_file; pos_start; pos_end } ->
let pos_end =
let column = File_pos_small.column pos_end in
File_pos_small.set_column_unchecked (column - 1) pos_end
in
let start_column = File_pos_small.column pos_start in
(match File_pos_small.set_column (start_column + 1) pos_start with
| None ->
let pos_start = File_pos_small.as_large_pos pos_start in
let pos_start = File_pos_large.set_column (start_column + 1) pos_start in
let pos_end = File_pos_small.as_large_pos pos_end in
Pos_large { pos_file; pos_start; pos_end }
| Some pos_start -> Pos_small { pos_file; pos_start; pos_end })
| Pos_large { pos_file; pos_start; pos_end } ->
let new_pos_start =
let column = File_pos_large.column pos_start in
File_pos_large.set_column (column + 1) pos_start
in
let new_pos_end =
let column = File_pos_large.column pos_end in
File_pos_large.set_column (column - 1) pos_end
in
Pos_large { pos_file; pos_start = new_pos_start; pos_end = new_pos_end }
| Pos_tiny _ -> p |> as_large_pos |> shrink_by_one_char_both_sides |> compress
| Pos_from_reason p -> Pos_from_reason (shrink_by_one_char_both_sides p)
(* This returns a half-open interval. *)
let multiline_string t =
let (line_start, char_start, line_end, char_end) = destruct_range t in
Printf.sprintf
"File %S, line %d, character %d - line %d, character %d:"
(String.strip (filename t))
line_start
char_start
line_end
(char_end - 1)
(* This returns a half-open interval. *)
let multiline_string_no_file t =
let (line_start, char_start, line_end, char_end) = destruct_range t in
Printf.sprintf
"line %d, character %d - line %d, character %d"
line_start
char_start
line_end
(char_end - 1)
(* This returns a half-open interval. *)
let multiline_json t =
let (line_start, char_start, line_end, char_end) = destruct_range t in
let fn = filename t in
Hh_json.JSON_Object
[
("filename", Hh_json.JSON_String fn);
("line_start", Hh_json.int_ line_start);
("char_start", Hh_json.int_ char_start);
("line_end", Hh_json.int_ line_end);
("char_end", Hh_json.int_ (char_end - 1));
]
let multiline_json_no_filename t =
let (line_start, char_start, line_end, char_end) = destruct_range t in
Hh_json.JSON_Object
[
("line_start", Hh_json.int_ line_start);
("char_start", Hh_json.int_ char_start);
("line_end", Hh_json.int_ line_end);
("char_end", Hh_json.int_ (char_end - 1));
]
let rec line_beg_offset p =
match p with
| Pos_small { pos_start; _ } -> File_pos_small.line_beg_offset pos_start
| Pos_large { pos_start; _ } -> File_pos_large.line_beg_offset pos_start
| Pos_tiny { pos_span; _ } ->
let (pos_start, _pos_end) = Pos_span_tiny.as_large_span pos_span in
File_pos_large.line_beg_offset pos_start
| Pos_from_reason p -> line_beg_offset p
let rec end_line_beg_offset p =
match p with
| Pos_small { pos_end; _ } -> File_pos_small.line_beg_offset pos_end
| Pos_large { pos_end; _ } -> File_pos_large.line_beg_offset pos_end
| Pos_tiny { pos_span; _ } ->
let (_pos_start, pos_end) = Pos_span_tiny.as_large_span pos_span in
File_pos_large.line_beg_offset pos_end
| Pos_from_reason p -> end_line_beg_offset p
let make_from_lnum_bol_offset ~pos_file ~pos_start ~pos_end =
let (lnum_start, bol_start, offset_start) = pos_start in
let (lnum_end, bol_end, offset_end) = pos_end in
compress
@@ Pos_large
{
pos_file;
pos_start =
File_pos_large.of_lnum_bol_offset
~pos_lnum:lnum_start
~pos_bol:bol_start
~pos_offset:offset_start;
pos_end =
File_pos_large.of_lnum_bol_offset
~pos_lnum:lnum_end
~pos_bol:bol_end
~pos_offset:offset_end;
}
let pessimize_enabled pos pessimize_coefficient =
let path = filename pos in
let open Float in
match Relative_path.prefix path with
| Relative_path.Root when pessimize_coefficient > 0.0 ->
let range = 2000000 in
let filename = Relative_path.suffix path in
let hash = Hashtbl.hash filename in
let r = Int.( % ) hash range in
Float.of_int r /. Float.of_int range <= pessimize_coefficient
| _ -> Float.equal pessimize_coefficient 1.0
(* hack for test cases *)
let print_verbose_absolute p =
let (a, b, c) = line_beg_offset p in
let (d, e, f) = end_line_beg_offset p in
Printf.sprintf "Pos('%s', <%d,%d,%d>, <%d,%d,%d>)" (filename p) a b c d e f
let print_verbose_relative p = print_verbose_absolute (to_absolute p)
module Pos = struct
type path = t
(* The definition below needs to refer to the t in the outer scope, but WrappedMap
* expects a module with a type of name t, so we define t in a second step *)
type t = path
let compare = compare
end
module Map = WrappedMap.Make (Pos)
module AbsolutePosMap = WrappedMap.Make (struct
type t = absolute
let compare = compare_absolute
end)
module Set = Caml.Set.Make (Pos) |
OCaml Interface | hhvm/hphp/hack/src/utils/pos.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.
*
*)
(* Note: While Pos.string prints out positions as closed intervals, pos_start
* and pos_end actually form a half-open interval (i.e. pos_end points to the
* character *after* the last character of the relevant lexeme.) *)
type 'a pos [@@deriving eq, hash, ord, show]
(** The underlying type used to construct Pos instances.
*
* See "val make: 'a -> b -> 'a pos" *)
type b = Pos_source.t
type t = Relative_path.t pos [@@deriving eq, hash]
val pp : Format.formatter -> t -> unit
type absolute = string pos [@@deriving eq, ord, show]
val none : t
val hash : t -> int
val filename : 'a pos -> 'a
val start_offset : 'a pos -> int
val end_offset : 'a pos -> int
val line : 'a pos -> int
val line_column : 'a pos -> int * int
val end_line : 'a pos -> int
val end_line_column : 'a pos -> int * int
(** Return line number, beginning of line character number and character number of start position. *)
val line_beg_offset : t -> int * int * int
val end_line_beg_offset : t -> int * int * int
(** For spans over just one line, return the line number, start column and end column.
This returns a closed interval.
Undefined for multi-line spans. *)
val info_pos : 'a pos -> int * int * int
(** Return start line, end line, start column and end column.
This returns a closed interval. *)
val info_pos_extended : 'a pos -> int * int * int * int
(** Return start character number and end character number. *)
val info_raw : 'a pos -> int * int
(** Return start line, start column, end line and end column.
This returns a half-open interval. *)
val destruct_range : 'a pos -> int * int * int * int
val length : 'a pos -> int
(* This returns a closed interval. *)
val string : absolute -> string
(* This returns a half-open interval. *)
val multiline_string : absolute -> string
(* This returns a closed interval. *)
val string_no_file : 'a pos -> string
(* This returns a half-open interval. *)
val multiline_string_no_file : 'a pos -> string
(* This returns a closed interval. *)
val json : absolute -> Hh_json.json
val json_no_filename : absolute -> Hh_json.json
(* This returns a half-open interval. *)
val multiline_json : absolute -> Hh_json.json
val multiline_json_no_filename : 'a pos -> Hh_json.json
val inside : 'a pos -> int -> int -> bool
val exactly_matches_range :
'a pos ->
start_line:int ->
start_col:int ->
end_line:int ->
end_col:int ->
bool
val contains : t -> t -> bool
(* Does first position strictly overlap the second position? *)
val overlaps : t -> t -> bool
val make : 'a -> b -> 'a pos
val make_from_lexing_pos : 'a -> Lexing.position -> Lexing.position -> 'a pos
val make_from : 'a -> 'a pos
val btw_nocheck : 'a pos -> 'a pos -> 'a pos
val is_hhi : t -> bool
(** Fill in the gap "between" first position and second position.
Not valid if from different files or second position precedes first *)
val btw : t -> t -> t
(* Symmetric version of above: order doesn't matter *)
val merge : 'a pos -> 'a pos -> 'a pos
val last_char : t -> t
val first_char_of_line : t -> t
val to_absolute : t -> absolute
val to_relative : absolute -> t
val to_relative_string : t -> string pos
val get_text_from_pos : content:string -> 'a pos -> string
(* Advance the ending position by one character *)
val advance_one : 'a pos -> 'a pos
(* Reduce the size of this position element by one character on the left and
* one character on the right. For example, if you've captured a position
* that includes outside apostrophes, this will shrink it to only the contents
* within the apostrophes. *)
val shrink_by_one_char_both_sides : 'a pos -> 'a pos
(* Compare by filename, then tie-break by start position, and finally by the
* end position *)
val compare : t -> t -> int
val set_file : 'a -> 'b pos -> 'a pos
(* Return a zero-width position that occurs at the start of input position. *)
val shrink_to_start : 'a pos -> 'a pos
(* Return a zero-width position that occurs at the end of input position. *)
val shrink_to_end : 'a pos -> 'a pos
val set_col_start : int -> 'a pos -> 'a pos
val set_col_end : int -> 'a pos -> 'a pos
val make_from_lnum_bol_offset :
pos_file:Relative_path.t ->
pos_start:int * int * int ->
pos_end:int * int * int ->
t
module Map : WrappedMap.S with type key = t
module AbsolutePosMap : WrappedMap.S with type key = absolute
module Set : Set.S with type elt = t
val print_verbose_absolute : absolute -> string
val print_verbose_relative : t -> string
val pessimize_enabled : t -> float -> bool
val set_from_reason : 'a pos -> 'a pos
val get_from_reason : 'a pos -> bool |
OCaml | hhvm/hphp/hack/src/utils/pos_source.ml | (** Pos_source is the underlying structure that provides position information.
*
* There will be two kinds of Pos_source
* Lexbuf_based - this is used by the original Hack lexer.
* Node_based - position data is held by a node.
*)
module Lexbuf_based_pos_source = struct
type t = Lexing.lexbuf
end
include Lexbuf_based_pos_source |
OCaml Interface | hhvm/hphp/hack/src/utils/pos_source.mli | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* This `.mli` file was generated automatically. It may include extra
definitions that should not actually be exposed to the caller. If you notice
that this interface file is a poor interface, please take a few minutes to
clean it up manually, and then delete this comment once the interface is in
shape. *)
module Lexbuf_based_pos_source : sig
type t = Lexing.lexbuf
end
type t = Lexing.lexbuf |
OCaml | hhvm/hphp/hack/src/utils/pos_span_tiny.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
(** A compressed representation of a position span, i.e. a start and an end position. *)
(**
* Pos_span_tiny.t packs multiple fields into one 63-bit integer:
*
* 6 5 4 3 2 1 0
* 3210987654321098765432109876543210987654321098765432109876543210
* <-------------------><--------------><------------------><---->X
* byte offset of line line number column number width
*)
type t = int [@@deriving eq, hash, ord]
let start_beginning_of_line_bits = 21
let start_line_number_bits = 16
let start_column_number_bits = 20
let beginning_of_line_increment_bits = 0
let line_number_increment_bits = 0
let width_bits = 6
(* The offset of each field (i.e., the number of bits to the right of it) is
* the offset of the field to the right plus that field's bit width. *)
let width_offset = 0
let line_number_increment_offset = width_offset + width_bits
let beginning_of_line_increment_offset =
line_number_increment_offset + line_number_increment_bits
let start_column_number_offset =
beginning_of_line_increment_offset + beginning_of_line_increment_bits
let start_line_number_offset =
start_column_number_offset + start_column_number_bits
let start_beginning_of_line_offset =
start_line_number_offset + start_line_number_bits
(* The total number of bits used must be 63 (OCaml reserves one bit). *)
let () =
assert (63 = start_beginning_of_line_bits + start_beginning_of_line_offset)
let mask bits = (1 lsl bits) - 1
let mask_by ~bits x = x land mask bits
let max_start_beginning_of_line = mask start_beginning_of_line_bits
let max_start_line_number = mask start_line_number_bits
let max_start_column_number = mask start_column_number_bits
let max_beginning_of_line_increment = mask beginning_of_line_increment_bits
let max_line_number_increment = mask line_number_increment_bits
let max_width = mask width_bits
let dummy = -1
let is_dummy t = t = dummy
let start_beginning_of_line (span : t) =
if is_dummy span then
0
else
mask_by
~bits:start_beginning_of_line_bits
(span lsr start_beginning_of_line_offset)
let start_line_number (span : t) =
if is_dummy span then
0
else
mask_by ~bits:start_line_number_bits (span lsr start_line_number_offset)
let start_column (span : t) =
if is_dummy span then
-1
else
mask_by ~bits:start_column_number_bits (span lsr start_column_number_offset)
let beginning_of_line_increment (span : t) =
if is_dummy span then
0
else
mask_by
~bits:beginning_of_line_increment_bits
(span lsr beginning_of_line_increment_offset)
let line_number_increment (span : t) =
if is_dummy span then
0
else
mask_by
~bits:line_number_increment_bits
(span lsr line_number_increment_offset)
let width (span : t) =
if is_dummy span then
0
else
mask_by ~bits:width_bits (span lsr width_offset)
let start_offset span = start_beginning_of_line span + start_column span
let end_line_number span = start_line_number span + line_number_increment span
let end_beginning_of_line span =
start_beginning_of_line span + beginning_of_line_increment span
let end_offset span = start_offset span + width span
let end_column span = end_offset span - end_beginning_of_line span
let make : pos_start:File_pos_large.t -> pos_end:File_pos_large.t -> t option =
fun ~pos_start ~pos_end ->
if File_pos_large.is_dummy pos_start || File_pos_large.is_dummy pos_end then
Some dummy
else
let {
File_pos_large.pos_lnum = start_line;
pos_bol = start_bol;
pos_offset = start_offset;
} =
pos_start
in
let {
File_pos_large.pos_lnum = end_line;
pos_bol = end_bol;
pos_offset = end_offset;
} =
pos_end
in
if
start_offset < start_bol
|| end_bol < start_bol
|| end_line < start_line
|| end_offset < start_offset
then
None
else
let start_col = start_offset - start_bol in
let bol_increment = end_bol - start_bol in
let line_increment = end_line - start_line in
let width = end_offset - start_offset in
if
start_bol > max_start_beginning_of_line
|| start_line > max_start_line_number
|| start_col > max_start_column_number
|| bol_increment > max_beginning_of_line_increment
|| line_increment > max_line_number_increment
|| width > max_width
then
None
else
Some
((start_bol lsl start_beginning_of_line_offset)
lor (start_line lsl start_line_number_offset)
lor (start_col lsl start_column_number_offset)
lor (bol_increment lsl beginning_of_line_increment_offset)
lor (line_increment lsl line_number_increment_offset)
lor (width lsl width_offset))
let as_large_span : t -> File_pos_large.t * File_pos_large.t =
fun span ->
if is_dummy span then
(File_pos_large.dummy, File_pos_large.dummy)
else
let start_lnum = start_line_number span in
let start_bol = start_beginning_of_line span in
let start_offset = start_offset span in
let end_lnum = end_line_number span in
let end_bol = end_beginning_of_line span in
let end_offset = end_offset span in
let pos_start =
{
File_pos_large.pos_lnum = start_lnum;
pos_bol = start_bol;
pos_offset = start_offset;
}
in
let pos_end =
{
File_pos_large.pos_lnum = end_lnum;
pos_bol = end_bol;
pos_offset = end_offset;
}
in
(pos_start, pos_end)
let pp fmt span =
Format.pp_print_int fmt (start_line_number span);
Format.pp_print_string fmt ":";
Format.pp_print_int fmt (start_column span + 1);
Format.pp_print_string fmt "-";
if start_line_number span = end_line_number span then
Format.pp_print_int fmt @@ (end_column span + 1)
else (
Format.pp_print_int fmt (end_line_number span);
Format.pp_print_string fmt ":";
Format.pp_print_int fmt (end_column span + 1)
)
let show : t -> string =
fun p ->
let buffer = Buffer.create 255 in
pp (Format.formatter_of_buffer buffer) p;
Buffer.contents buffer |
OCaml Interface | hhvm/hphp/hack/src/utils/pos_span_tiny.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.
*
*)
(** A compressed representation of a position span, i.e. a start and an end position. *)
type t [@@deriving eq, hash, show, ord]
val dummy : t
val make : pos_start:File_pos_large.t -> pos_end:File_pos_large.t -> t option
val as_large_span : t -> File_pos_large.t * File_pos_large.t
val start_line_number : t -> int
val start_beginning_of_line : t -> int
val start_column : t -> int
val start_offset : t -> int
val end_line_number : t -> int
val end_beginning_of_line : t -> int
val end_column : t -> int
val end_offset : t -> int |
OCaml | hhvm/hphp/hack/src/utils/promise.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 type S = sig
type 'value t
(** Creates a promise that returns the given value immediately. *)
val return : 'value -> 'value t
(** Returns a new promise that will map the result of the given one. *)
val map : 'value t -> ('value -> 'next_value) -> 'next_value t
(** Returns a new promise generated from the results of the given one. *)
val bind : 'value t -> ('value -> 'next_value t) -> 'next_value t
val both : 'a t -> 'b t -> ('a * 'b) t
end |
OCaml | hhvm/hphp/hack/src/utils/regexp_utils.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.
*
*)
(* Utility functions implemented with regular expressions.
* Needs to be duplicated between regular ocaml and JS since the
* JS regexp library differs. *)
let nonempty_ws_regexp = Str.regexp "[ \n\t\r\012]+"
(* Squash the whitespace in a string down the way that xhp expects it.
* In particular, replace all whitespace with spaces and replace all
* strings of multiple spaces with a single space. *)
let squash_whitespace s = Str.global_replace nonempty_ws_regexp " " s |
OCaml Interface | hhvm/hphp/hack/src/utils/regexp_utils.mli | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* This `.mli` file was generated automatically. It may include extra
definitions that should not actually be exposed to the caller. If you notice
that this interface file is a poor interface, please take a few minutes to
clean it up manually, and then delete this comment once the interface is in
shape. *)
val nonempty_ws_regexp : Str.regexp
val squash_whitespace : string -> string |
OCaml | hhvm/hphp/hack/src/utils/relative_path.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
open Utils
type prefix =
| Root
| Hhi
| Dummy
| Tmp
[@@deriving eq, hash, show, enum, ord, sexp_of, yojson]
let is_hhi = function
| Hhi -> true
| Root
| Dummy
| Tmp ->
false
let is_root = function
| Root -> true
| Hhi
| Dummy
| Tmp ->
false
let root = ref None
let hhi = ref None
let tmp = ref None
let path_ref_of_prefix = function
| Root -> root
| Hhi -> hhi
| Tmp -> tmp
| Dummy -> ref (Some "")
let string_of_prefix = function
| Root -> "root"
| Hhi -> "hhi"
| Tmp -> "tmp"
| Dummy -> ""
let path_of_prefix prefix =
match !(path_ref_of_prefix prefix) with
| Some path -> path
| None ->
let message =
Printf.sprintf "Prefix '%s' has not been set!" (string_of_prefix prefix)
in
raise (Invalid_argument message)
let enforce_trailing_slash v =
if String.is_suffix v ~suffix:Filename.dir_sep then
v
else
v ^ Filename.dir_sep
let set_path_prefix prefix v =
let v = Path.to_string v in
assert (String.length v > 0);
match prefix with
| Dummy -> raise (Failure "Dummy is always represented by an empty string")
| _ -> path_ref_of_prefix prefix := Some (enforce_trailing_slash v)
type t = prefix * string [@@deriving eq, hash, show, ord, sexp_of, yojson]
type relative_path = t
let prefix (p : t) = fst p
let suffix (p : t) = snd p
let default = (Dummy, "")
(* We could have simply used Marshal.to_string here, but this does slightly
* better on space usage. *)
let storage_to_string (p, rest) = string_of_prefix p ^ "|" ^ rest
let index_opt str ch = String.index str ch
let storage_of_string str =
match index_opt str '|' with
| Some idx ->
let (a, a') = (0, idx) in
let b = idx + 1 in
let b' = String.length str - b in
let prefix = String.sub str ~pos:a ~len:a' in
let content = String.sub str ~pos:b ~len:b' in
let prefix =
match prefix with
| "root" -> Root
| "hhi" -> Hhi
| "tmp" -> Tmp
| "" -> Dummy
| _ -> failwith "invalid prefix"
in
(prefix, content)
| None -> failwith "not a Relative_path.t"
module S = struct
type t = relative_path
let compare : t -> t -> int = compare
let to_string = storage_to_string
end
let to_absolute (p, rest) = path_of_prefix p ^ rest
let to_absolute_with_prefix ~www ~hhi (p, rest) =
let path_concat p rest = enforce_trailing_slash (Path.to_string p) ^ rest in
match p with
| Root -> path_concat www rest
| Hhi -> path_concat hhi rest
| Dummy -> rest
| _ -> failwith "invalid prefix"
let to_tmp (_, rest) = (Tmp, rest)
let to_root (_, rest) = (Root, rest)
module Set = struct
include Reordered_argument_set (Caml.Set.Make (S))
let pp_limit ?(max_items = None) fmt x =
Format.fprintf fmt "@[<2>{";
ignore
@@ List.fold_left (elements x) ~init:0 ~f:(fun i s ->
(match max_items with
| Some max_items when i >= max_items -> ()
| _ ->
if i > 0 then Format.fprintf fmt ";@ ";
pp fmt s);
i + 1);
Format.fprintf fmt "@,}@]"
let pp = pp_limit ~max_items:None
let show x = Format.asprintf "%a" pp x
let pp_large ?(max_items = 5) fmt sset =
let l = cardinal sset in
if l <= max_items then
pp fmt sset
else
Format.fprintf
fmt
"<only showing %d of %d elems: %a>"
max_items
l
(pp_limit ~max_items:(Some max_items))
sset
let show_large ?(max_items = 5) sset =
Format.asprintf "%a" (pp_large ~max_items) sset
end
module Map = struct
include Reordered_argument_map (WrappedMap.Make (S))
let pp pp_data = make_pp pp pp_data
let show pp_data x = Format.asprintf "%a" (pp pp_data) x
let yojson_of_t x = make_yojson_of_t suffix x
end
let create prefix s =
let prefix_s = path_of_prefix prefix in
let prefix_len = String.length prefix_s in
if not (String.is_prefix s ~prefix:prefix_s) then (
Printf.eprintf "%s is not a prefix of %s" prefix_s s;
assert_false_log_backtrace None
);
(prefix, String.sub s ~pos:prefix_len ~len:(String.length s - prefix_len))
let create_detect_prefix s =
let file_prefix =
[Root; Hhi; Tmp]
|> List.find ~f:(fun prefix ->
String.is_prefix s ~prefix:(path_of_prefix prefix))
|> fun x ->
match x with
| Some prefix -> prefix
| None -> Dummy
in
create file_prefix s
(* Strips the root and relativizes the file if possible, otherwise returns
original string *)
let strip_root_if_possible s =
let prefix_s = path_of_prefix Root in
let prefix_len = String.length prefix_s in
if not (String.is_prefix s ~prefix:prefix_s) then
None
else
Some (String.sub s ~pos:prefix_len ~len:(String.length s - prefix_len))
let from_root ~(suffix : string) : t = (Root, suffix)
let relativize_set prefix m =
SSet.fold m ~init:Set.empty ~f:(fun k a -> Set.add a (create prefix k))
let set_of_list xs = List.fold_left xs ~f:Set.add ~init:Set.empty |
OCaml Interface | hhvm/hphp/hack/src/utils/relative_path.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 Reordered_argument_collections
type prefix =
| Root
| Hhi
| Dummy
| Tmp
[@@deriving eq, hash, show, enum]
val is_hhi : prefix -> bool
val is_root : prefix -> bool
val set_path_prefix : prefix -> Path.t -> unit
val path_of_prefix : prefix -> string
module S : sig
type t
val compare : t -> t -> int
val to_string : t -> string
end
type t = S.t [@@deriving eq, hash, show, ord, sexp_of]
val default : t
(** Checks that the provided string indeed has the given prefix before constructing path *)
val create : prefix -> string -> t
(** Creates a new path, inferring the prefix. Will default to Dummy. *)
val create_detect_prefix : string -> t
(** Creates a Relative_path.t relative to the root. The argument must be
a *relative* path (the path suffix). If you wish to construct
a Relative_path.t from an absolute path, use
`create_detect_prefix` instead. *)
val from_root : suffix:string -> t
val prefix : t -> prefix
val suffix : t -> string
val to_absolute : t -> string
val to_absolute_with_prefix : www:Path.t -> hhi:Path.t -> t -> string
val to_tmp : t -> t
val to_root : t -> t
val strip_root_if_possible : string -> string option
module Set : sig
include module type of Reordered_argument_set (Set.Make (S))
val pp : Format.formatter -> t -> unit
val show : t -> string
val pp_large : ?max_items:int -> Format.formatter -> t -> unit
val show_large : ?max_items:int -> t -> string
end
module Map : sig
include module type of Reordered_argument_map (WrappedMap.Make (S))
val pp : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit
val show : (Format.formatter -> 'a -> unit) -> 'a t -> string
val yojson_of_t : ('a -> Yojson.Safe.t) -> 'a t -> Yojson.Safe.t
end
val relativize_set : prefix -> SSet.t -> Set.t
val set_of_list : t list -> Set.t
val storage_to_string : t -> string
val storage_of_string : string -> t |
OCaml | hhvm/hphp/hack/src/utils/serverLoadFlag.ml | (* TODO: turn this into a bool option with None indicating
* an uninitialized state for greater strictness *)
let no_load_ref : bool ref = ref false
let set_no_load b = no_load_ref := b
let get_no_load () = !no_load_ref |
OCaml | hhvm/hphp/hack/src/utils/signed_source.ml | (*
* Copyright (c) 2018-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(* This file is based on fbsource/tools/signedsource.py *)
(* This old token was historically used as the signing token. It was replaced
because it is 2 characters shorter than the final signature, and as a result,
signing data with the old token forced the entire string to be rewritten
(everything after the token needs to be shifted forwards 2 bytes).
In this implementation, we rewrite the entire string anyway. *)
let old_token = "<<SignedSource::*O*zOeWoEQle#+L!plEphiEmie@I>>"
let token = "<<SignedSource::*O*zOeWoEQle#+L!plEphiEmie@IsG>>"
let make_signing_token = Printf.sprintf "@%s %s" "generated"
let signature_re = "SignedSource<<\\([a-f0-9]+\\)>>"
let sign_or_old_token = Str.regexp (signature_re ^ "|" ^ Str.quote old_token)
let signing_regexp = Str.regexp (make_signing_token signature_re)
let token_regexp = Str.regexp_string token
let hash data = Digest.to_hex (Digest.string data)
let signing_token = make_signing_token token
exception Token_not_found
let sign_file data =
let data = Str.global_replace sign_or_old_token token data in
if not @@ Core.String.is_substring ~substring:token data then
raise Token_not_found;
let signature = "SignedSource<<" ^ hash data ^ ">>" in
Str.global_replace token_regexp signature data
let is_signed data =
try
let (_ : int) = Str.search_forward signing_regexp data 0 in
true
with
| Not_found -> false
type sign_check_response =
| Sign_ok
| Sign_unsigned
| Sign_invalid
let verify_signature data =
if not @@ is_signed data then
Sign_unsigned
else
let expected_md5 = Str.matched_group 1 data in
let valid =
[token; old_token]
|> List.exists @@ fun tok ->
let replacement = make_signing_token tok in
let unsigned_data =
Str.global_replace signing_regexp replacement data
in
let actual_md5 = hash unsigned_data in
expected_md5 = actual_md5
in
if valid then
Sign_ok
else
Sign_invalid |
OCaml Interface | hhvm/hphp/hack/src/utils/signed_source.mli | (*
* Copyright (c) 2018-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(** The signing token, which you must embed in the file you wish to sign.
Generally, you should put this in a header comment. *)
val signing_token : string
exception Token_not_found
(** Sign a source file into which you have previously embedded a signing token.
Signing modifies only the signing token, so the semantics of the file will
not change if the token is put in a comment.
@raise {!Token_not_found} if no signing token is present. *)
val sign_file : string -> string
(** Determine if a file is signed or not. This does NOT verify the signature. *)
val is_signed : string -> bool
type sign_check_response =
| Sign_ok
| Sign_unsigned
| Sign_invalid
(** Verify a file's signature. *)
val verify_signature : string -> sign_check_response |
Rust | hhvm/hphp/hack/src/utils/si_addendum.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use oxidized::search_types::SiAddendum;
use oxidized_by_ref::direct_decl_parser::ParsedFileWithHashes;
/// From a `ParsedFileWithHashes<'a>` generated by some decl parse, collect all
/// the necessary information to update the symbol index.
pub fn get_si_addenda<'a>(with_hashes: &ParsedFileWithHashes<'a>) -> Vec<SiAddendum> {
with_hashes
.iter()
.filter_map(|(name, decl, _hash)| {
use oxidized::search_types::SiKind::*;
use oxidized_by_ref::shallow_decl_defs::Decl;
let kind = match decl {
Decl::Class(class) => {
use oxidized::ast_defs::ClassishKind::*;
match class.kind {
Cclass(_) => SIClass,
Cinterface => SIInterface,
Ctrait => SITrait,
Cenum | CenumClass(_) => SIEnum,
}
}
Decl::Fun(_) => SIFunction,
Decl::Typedef(_) => SITypedef,
Decl::Const(_) => SIGlobalConstant,
Decl::Module(_) => {
// TODO: SymbolIndex doesn't currently represent modules
return None;
}
};
let (is_abstract, is_final) = match decl {
Decl::Class(class) => (class.abstract_, class.final_),
_ => (false, false),
};
Some(SiAddendum {
name: core_utils_rust::strip_ns(name).to_owned(),
kind,
is_abstract,
is_final,
})
})
.collect()
} |
OCaml | hhvm/hphp/hack/src/utils/stack_utils.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.
*
*)
(** Adds some utilities to the Stack module *)
module Ocaml_stack = Stack
module Stack = struct
include Ocaml_stack
let merge_bytes : string Stack.t -> string = function
| stack ->
let strs = Stack.fold (fun acc x -> x :: acc) [] stack in
String.concat "" strs
end |
OCaml Interface | hhvm/hphp/hack/src/utils/stack_utils.mli | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* This `.mli` file was generated automatically. It may include extra
definitions that should not actually be exposed to the caller. If you notice
that this interface file is a poor interface, please take a few minutes to
clean it up manually, and then delete this comment once the interface is in
shape. *)
module Ocaml_stack = Stack
module Stack : sig
type 'a t = 'a Stack.t
exception Empty
val create : unit -> 'a t
val push : 'a -> 'a t -> unit
val pop : 'a t -> 'a
val top : 'a t -> 'a
val clear : 'a t -> unit
val copy : 'a t -> 'a t
val is_empty : 'a t -> bool
val length : 'a t -> int
val iter : ('a -> unit) -> 'a t -> unit
val fold : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b
val merge_bytes : string Stack.t -> string
end |
OCaml | hhvm/hphp/hack/src/utils/symbolDefinition.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type kind =
| Function
| Class
| Method
| Property
| ClassConst
| GlobalConst
| Enum
| Interface
| Trait
| LocalVar
| TypeVar
| Typeconst
| Param
| Typedef
| Module
[@@deriving ord, show]
type modifier =
| Final
| Static
| Abstract
| Private
| Public
| Protected
| Async
| Inout
| Internal
[@@deriving ord, show]
type 'a t = {
kind: kind;
name: string;
full_name: string;
class_name: string option;
id: string option;
pos: 'a Pos.pos;
(* covers the span of just the identifier *)
span: 'a Pos.pos;
(* covers the span of the entire construct, including children *)
modifiers: modifier list;
children: 'a t list option;
params: 'a t list option;
docblock: string option;
}
[@@deriving ord, show]
let rec to_absolute x =
{
x with
pos = Pos.to_absolute x.pos;
span = Pos.to_absolute x.span;
children = Option.map x.children ~f:(fun x -> List.map x ~f:to_absolute);
params = Option.map x.params ~f:(fun x -> List.map x ~f:to_absolute);
docblock = x.docblock;
}
let rec to_relative x =
{
x with
pos = Pos.to_relative x.pos;
span = Pos.to_relative x.span;
children = Option.map x.children ~f:(fun x -> List.map x ~f:to_relative);
params = Option.map x.params ~f:(fun x -> List.map x ~f:to_relative);
}
let string_of_kind = function
| Function -> "function"
| Class -> "class"
| Method -> "method"
| Property -> "property"
| ClassConst -> "class constant"
| GlobalConst -> "const"
| Enum -> "enum"
| Interface -> "interface"
| Trait -> "trait"
| Typeconst -> "typeconst"
| LocalVar -> "local"
| TypeVar -> "type_var"
| Param -> "param"
| Typedef -> "typedef"
| Module -> "module"
let string_of_modifier = function
| Final -> "final"
| Static -> "static"
| Abstract -> "abstract"
| Private -> "private"
| Public -> "public"
| Protected -> "protected"
| Async -> "async"
| Inout -> "inout"
| Internal -> "internal"
let function_kind_name = "function"
let type_id_kind_name = "type_id"
let method_kind_name = "method"
let property_kind_name = "property"
let class_const_kind_name = "class_const"
let global_const_kind_name = "global_const"
let module_kind_name = "module"
let get_symbol_id kind parent_class name =
let prefix =
match kind with
| Function -> Some function_kind_name
| Class
| Typedef
| Enum
| Interface
| Trait ->
Some type_id_kind_name
| Method -> Some method_kind_name
| Property -> Some property_kind_name
| Typeconst
| ClassConst ->
Some class_const_kind_name
| GlobalConst -> Some global_const_kind_name
| Module -> Some module_kind_name
| LocalVar
| TypeVar
| Param ->
None
in
match (prefix, parent_class) with
| (Some prefix, Some parent_class) ->
Some (Printf.sprintf "%s::%s::%s" prefix parent_class name)
| (Some prefix, None) -> Some (Printf.sprintf "%s::%s" prefix name)
| (None, _) -> None |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.