language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
OCaml Interface
hhvm/hphp/hack/src/utils/symbolDefinition.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 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] val to_absolute : Relative_path.t t -> string t val to_relative : string t -> Relative_path.t t val string_of_kind : kind -> string val string_of_modifier : modifier -> string val function_kind_name : string val type_id_kind_name : string val method_kind_name : string val property_kind_name : string val class_const_kind_name : string val get_symbol_id : kind -> string option -> string -> string option
OCaml
hhvm/hphp/hack/src/utils/symbolOccurrence.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type override_info = { class_name: string; method_name: string; is_static: bool; } [@@deriving ord, eq, show] type class_id_type = | ClassId | Other [@@deriving ord, eq, show] type receiver_class = | ClassName of string | UnknownClass (* invoked dynamically *) [@@deriving ord, eq, show] type keyword_with_hover_docs = | Class | Interface | Trait | Enum | EnumClass | Type | Newtype | FinalOnClass | FinalOnMethod | AbstractOnClass | AbstractOnMethod | ExtendsOnClass | ExtendsOnInterface | ReadonlyOnMethod | ReadonlyOnParameter | ReadonlyOnReturnType | ReadonlyOnExpression | XhpAttribute | XhpChildren | ConstGlobal | ConstOnClass | ConstType | StaticOnMethod | StaticOnProperty | Use | FunctionGlobal | FunctionOnMethod | Async | AsyncBlock | Await | Concurrent | Public | Protected | Private | Internal | ModuleInModuleDeclaration | ModuleInModuleMembershipDeclaration [@@deriving ord, eq, show] type built_in_type_hint = | BIprimitive of Aast_defs.tprim | BImixed | BIdynamic | BInothing | BInonnull | BIshape (* TODO: support self and static too.*) | BIthis | BIoption [@@deriving ord, eq, show] type receiver = | FunctionReceiver of string | MethodReceiver of { cls_name: string; meth_name: string; is_static: bool; } [@@deriving ord, eq, show] type kind = | Class of class_id_type | BuiltInType of built_in_type_hint | Function | Method of receiver_class * string | LocalVar | TypeVar | Property of receiver_class * string | XhpLiteralAttr of string * string | ClassConst of receiver_class * string | Typeconst of string * string | GConst (* For __Override occurrences, we track the associated method and class. *) | Attribute of override_info option (* enum class name, label name *) | EnumClassLabel of string * string | Keyword of keyword_with_hover_docs | PureFunctionContext (* The nth argument of receiver, used for looking up the parameter name at the declaration site. Zero-indexed. This is purely for IDE hover information, and is only used when we can easily find a concrete receiver (e.g. no complex generics). *) | BestEffortArgument of receiver * int | HhFixme | Module [@@deriving ord, eq, show] type 'a t = { name: string; type_: kind; is_declaration: bool; (* Span of the symbol itself *) pos: 'a Pos.pos; } [@@deriving ord] let to_absolute x = { x with pos = Pos.to_absolute x.pos } let kind_to_string = function | Class _ -> "class" | BuiltInType _ -> "built_in_type" | Method _ -> "method" | Function -> "function" | LocalVar -> "local" | Property _ -> "property" | XhpLiteralAttr _ -> "xhp_literal_attribute" | ClassConst _ -> "member_const" | Typeconst _ -> "typeconst" | GConst -> "global_const" | TypeVar -> "generic_type_var" | Attribute _ -> "attribute" | EnumClassLabel _ -> "enum_class_label" | Keyword _ -> "keyword" | PureFunctionContext -> "context_braces" | BestEffortArgument _ -> "argument" | HhFixme -> "hh_fixme" | Module -> "module" let enclosing_class occurrence = match occurrence.type_ with | Method (ClassName c, _) | Property (ClassName c, _) | XhpLiteralAttr (c, _) | ClassConst (ClassName c, _) | Typeconst (c, _) | EnumClassLabel (c, _) -> Some c | _ -> None let get_class_name occurrence = match enclosing_class occurrence with | Some _ as res -> res | None -> (match occurrence.type_ with | Class _ | Attribute _ -> Some occurrence.name | _ -> None) let is_constructor occurrence = match occurrence.type_ with | Method (_, name) when name = Naming_special_names.Members.__construct -> true | _ -> false let is_class occurrence = match occurrence.type_ with | Class _ -> true | _ -> false let is_xhp_literal_attr occurrence = match occurrence.type_ with | XhpLiteralAttr _ -> true | _ -> false let built_in_type_hover (bt : built_in_type_hint) : string = match bt with | BIprimitive prim -> (match prim with | Aast_defs.Tnull -> "The value `null`. The opposite of `nonnull`." | Aast_defs.Tvoid -> "A `void` return type indicates a function that never returns a value. `void` functions usually have side effects." | Aast_defs.Tint -> "A 64-bit integer." | Aast_defs.Tbool -> "A boolean value, `true` or `false`." | Aast_defs.Tfloat -> "A 64-bit floating-point number." | Aast_defs.Tstring -> "A sequence of characters." | Aast_defs.Tresource -> "An external resource, such as a file handle or database connection." | Aast_defs.Tnum -> "An `int` or a `float`." | Aast_defs.Tarraykey -> "An `int` or a `string`. `arraykey` is a common key type for `dict`s." | Aast_defs.Tnoreturn -> "A `noreturn` function always errors or loops forever.") | BImixed -> "Any value at all. It's usually better to use a more specific type, or a generic." | BIdynamic -> "Any value at all. Unlike `mixed`, the type checker allows any operation on a `dynamic` value, even if e.g. a method doesn't actually exist.\n\n" ^ "All operations on a `dynamic` value return another `dynamic` value. Prefer more specific types so the type checker can help you.\n\n" ^ "To convert a `generic` value to something specific, use `$foo as SomeSpecificType`. This will check the type at runtime and the " ^ "type checker will verify types after this point." | BInothing -> "The `nothing` type has no values, it's the empty type.\n\nA function returning `nothing` either loops forever or throws an exception. A `vec<nothing>` is always empty." | BInonnull -> "Any value except `null`." | BIshape -> "A shape is a key-value data structure where the keys are known." ^ " Shapes are value types, just like `dict` and `vec`.\n\n" ^ " A closed shape, such as `shape('x' => int)`, has a fixed number of keys. " ^ " An open shape, such as `shape('x' => int, ...)`, may have additional keys." | BIthis -> "`this` represents the current class.\n\n" ^ "`this` refers to the type of the current instance at runtime. In a child class, `this` refers to the child class, even if the method is defined in the parent." | BIoption -> "The type `?Foo` allows either `Foo` or `null`."
OCaml Interface
hhvm/hphp/hack/src/utils/symbolOccurrence.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 override_info = { class_name: string; method_name: string; is_static: bool; } [@@deriving eq] type class_id_type = | ClassId | Other [@@deriving ord, eq] type receiver_class = | ClassName of string | UnknownClass (* invoked dynamically *) [@@deriving ord, eq] type keyword_with_hover_docs = | Class | Interface | Trait | Enum | EnumClass | Type | Newtype | FinalOnClass | FinalOnMethod | AbstractOnClass | AbstractOnMethod | ExtendsOnClass | ExtendsOnInterface | ReadonlyOnMethod | ReadonlyOnParameter | ReadonlyOnReturnType | ReadonlyOnExpression | XhpAttribute | XhpChildren | ConstGlobal | ConstOnClass | ConstType | StaticOnMethod | StaticOnProperty | Use | FunctionGlobal | FunctionOnMethod | Async | AsyncBlock | Await | Concurrent | Public | Protected | Private | Internal | ModuleInModuleDeclaration | ModuleInModuleMembershipDeclaration [@@deriving ord, eq] type built_in_type_hint = | BIprimitive of Aast_defs.tprim | BImixed | BIdynamic | BInothing | BInonnull | BIshape | BIthis | BIoption [@@deriving eq] type receiver = | FunctionReceiver of string | MethodReceiver of { cls_name: string; meth_name: string; is_static: bool; } [@@deriving eq] type kind = | Class of class_id_type | BuiltInType of built_in_type_hint | Function | Method of receiver_class * string | LocalVar | TypeVar | Property of receiver_class * string (* XhpLiteralAttr is only used for attributes in XHP literals. i.e. <foo:bar my-attribute={} /> For all other cases, Property is used. i.e. $x->:my-attribute or attributes in class definitions *) | XhpLiteralAttr of string * string | ClassConst of receiver_class * string | Typeconst of string * string | GConst | Attribute of override_info option | EnumClassLabel of string * string | Keyword of keyword_with_hover_docs | PureFunctionContext | BestEffortArgument of receiver * int | HhFixme | Module [@@deriving eq, show] type 'a t = { name: string; type_: kind; is_declaration: bool; (* Span of the symbol itself *) pos: 'a Pos.pos; } [@@deriving ord] val to_absolute : Relative_path.t t -> string t val kind_to_string : kind -> string val enclosing_class : 'a t -> string option val get_class_name : 'a t -> string option val is_constructor : 'a t -> bool val is_class : 'a t -> bool val is_xhp_literal_attr : 'a t -> bool val built_in_type_hover : built_in_type_hint -> string
OCaml
hhvm/hphp/hack/src/utils/tempfile.ml
exception Out_of_retries let rec mkdtemp ~(dir : Path.t) ~(skip_mocking : bool) ~(retries : int) : Path.t = if retries < 0 then raise Out_of_retries else let name = Random_id.short_string () in let tmp_dir = Path.concat dir name in try let () = Sys_utils.mkdir_p (Path.to_string tmp_dir) ~skip_mocking in tmp_dir with | Unix.Unix_error _ -> mkdtemp ~dir ~skip_mocking ~retries:(retries - 1) let mkdtemp_with_dir (dir : Path.t) = mkdtemp ~dir ~skip_mocking:false ~retries:30 let mkdtemp ~skip_mocking = mkdtemp ~dir:(Path.make Sys_utils.temp_dir_name) ~skip_mocking ~retries:30 let with_tempdir ~skip_mocking g = let dir = mkdtemp ~skip_mocking in let f () = g dir in Utils.try_finally ~f ~finally:(fun () -> Sys_utils.rm_dir_tree (Path.to_string dir) ~skip_mocking) let with_real_tempdir g = Random.self_init (); with_tempdir ~skip_mocking:true g let with_tempdir g = with_tempdir ~skip_mocking:false g
OCaml Interface
hhvm/hphp/hack/src/utils/tempfile.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. *) exception Out_of_retries val mkdtemp : skip_mocking:bool -> Path.t val mkdtemp_with_dir : Path.t -> Path.t val with_real_tempdir : (Path.t -> 'a) -> 'a val with_tempdir : (Path.t -> 'a) -> 'a
OCaml
hhvm/hphp/hack/src/utils/tempfile_lwt.ml
exception Out_of_retries let rec mkdtemp ~skip_mocking ~retries = if retries < 0 then raise Out_of_retries else let tmp_dir = Sys_utils.temp_dir_name in let tmp_dir = Path.make tmp_dir in let name = Random_id.short_string () in let tmp_dir = Path.concat tmp_dir name in try let () = Sys_utils.mkdir_p (Path.to_string tmp_dir) ~skip_mocking in tmp_dir with | Unix.Unix_error _ -> mkdtemp ~skip_mocking ~retries:(retries - 1) let mkdtemp ~skip_mocking = mkdtemp ~skip_mocking ~retries:30 let with_tempdir ~skip_mocking g = let dir = mkdtemp ~skip_mocking in let f () = g dir in let%lwt result = Lwt_utils.try_finally ~f ~finally:(fun () -> Sys_utils.rm_dir_tree (Path.to_string dir) ~skip_mocking; Lwt.return_unit) in Lwt.return result let with_real_tempdir g = Random.self_init (); with_tempdir ~skip_mocking:true g let with_tempdir g = with_tempdir ~skip_mocking:false g
OCaml Interface
hhvm/hphp/hack/src/utils/tempfile_lwt.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. *) exception Out_of_retries val mkdtemp : skip_mocking:bool -> Path.t val with_real_tempdir : (Path.t -> 'a Lwt.t) -> 'a Lwt.t val with_tempdir : (Path.t -> 'a Lwt.t) -> 'a Lwt.t
OCaml
hhvm/hphp/hack/src/utils/trie.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 (* Utility functions *) let make_pair (a : 'a) (b : 'b) : 'a * 'b = (a, b) let common_prefix (s1 : string) (s2 : string) : int = let i = ref 0 in let l1 = String.length s1 in let l2 = String.length s2 in while !i < l1 && !i < l2 && Char.equal s1.[!i] s2.[!i] do i := !i + 1 done; !i let drop s c = let l = String.length s in String.sub s ~pos:c ~len:(l - c) let take s c = String.sub s ~pos:0 ~len:c let ( |> ) (o : 'a) (f : 'a -> 'b) : 'b = f o let id (x : 'a) : 'a = x type 'a return = { return: 'b. 'a -> 'b } let with_return (type t) (f : _ -> t) = let module Capture = struct exception Return of t end in let return = { return = (fun x -> raise (Capture.Return x)) } in try f return with | Capture.Return x -> x (* Trie implementation *) type 'a t = | Leaf of 'a | Node of 'a t SMap.t ref let create () : 'a t = Node (ref SMap.empty) exception Inconsistent_trie of string let get_node (trie : 'a t) : 'a t SMap.t ref = match trie with | Node n -> n | _ -> raise (Inconsistent_trie "Cannot match to leaf") let get_leaf (trie : 'a t) : 'a = match trie with | Leaf v -> v | _ -> raise (Inconsistent_trie "Cannot match to node") (* Match a string s with a key; return a tuple: i : int -- position where the match ends k : string -- the full key matched n : 'a t -- the node associated with key k *) let trie_assoc_partial (trie : 'a t) (w : string) : (int * string * 'a t) option = with_return (fun e -> !(get_node trie) |> SMap.iter (fun key elt -> let c = common_prefix key w in if (not (c = 0)) || (String.equal key "" && String.equal w "") then e.return (Some (c, key, elt))); None) let rec mem (trie : 'a t) (w : string) : bool = with_return (fun e -> let (i, key, child) = match trie_assoc_partial trie w with | Some x -> x | None -> e.return false in if String.equal key "" then e.return true; if String.length key = i then e.return (mem child (drop w i)); false) let add_one (node : 'a t) (c : string) (inner : 'a t) : unit = let elts = get_node node in elts := SMap.add c inner !elts (* split key in position c, put left part as new key to a new node n * and put right part as child of n, then return n *) let split_key (parent : 'a t) (key : string) (child : 'a t) (c : int) : 'a t = let left_key = take key c in let right_key = drop key c in let parent_list = get_node parent in parent_list := SMap.remove key !parent_list; let n = create () in add_one parent left_key n; add_one n right_key child; n let add_leaf (node : 'a t) (key : string) (v : 'a) : unit = let leaf = match key with | "" -> Leaf v | _ -> let res = create () in add_one res "" (Leaf v); res in add_one node key leaf let rec add ?(if_exist : 'b -> 'a -> unit = (fun _ _ -> ())) ~(transform : 'a -> 'b) (trie : 'b t) (w : string) (v : 'a) : unit = with_return (fun e -> let (c, key, child) = match trie_assoc_partial trie w with | Some x -> x | None -> e.return (add_leaf trie w (transform v)) in if String.length key = c && String.equal w "" then (* leaf exists; use if_exists callback *) e.return (if_exist (get_leaf child) v); if c = String.length key then (* full key match; do final recursive call *) e.return (add child (drop w c) v ~if_exist ~transform); (* Partial match: need to split key with common parts *) let n = split_key trie key child c in add_leaf n (drop w c) (transform v)) let to_list (limit : int option) (trie : 'b t) (kmap : string -> 'a) (vmap : 'a -> 'b -> 'c) : 'c list = with_return (fun e -> let reslist = ref [] in let rescount = ref 0 in let more () = match limit with | Some i -> i > !rescount | None -> true in let rec to_list_aux t s = match t with | Leaf v -> if more () then ( reslist := vmap (kmap s) v :: !reslist; incr rescount ) else e.return (List.rev !reslist) | Node cs -> SMap.fold (fun tail rhs _acc -> to_list_aux rhs (s ^ tail)) !cs () in to_list_aux trie ""; List.rev !reslist) let find_impl ?(limit : int option = None) (exact : bool) (trie : 'a t) (pre : string) (vmap : string -> 'a -> 'c) : 'c list = with_return (fun e -> let append = ( ^ ) pre in let rec find_impl_aux trie p = let (c, key, child) = match trie_assoc_partial trie p with | Some x -> x | None -> e.return [] in match (String.length key = c, (not exact) && String.length p = c) with | (true, _) when String.length p = 0 -> to_list limit child append vmap | (true, true) -> to_list limit child append vmap | (true, _) -> find_impl_aux child (drop p c) | (false, true) -> to_list limit child (fun k -> pre ^ drop key c ^ k) vmap | _ -> [] in find_impl_aux trie pre) let find (trie : 'a t) (s : string) : 'a option = match find_impl true trie s make_pair with | (_s, v) :: _tl -> Some v | _ -> None let find_prefix (trie : 'a t) (s : string) (vmap : string -> 'a -> 'b) : 'b list = find_impl false trie s vmap let find_prefix_limit (i : int) (trie : 'a t) (s : string) (vmap : string -> 'a -> 'b) : 'b list = find_impl false trie s vmap ~limit:(Some i) let remove_one (trie : 'a t) (key : string) : unit = let elts = get_node trie in elts := SMap.remove key !elts let rec remove_impl (exact : bool) (trie : 'a t) (s : string) : unit = with_return (fun e -> let (c, key, child) = match trie_assoc_partial trie s with | Some x -> x | None -> e.return () in match (String.length key = c, exact, String.length s = c) with | (true, true, true) when c = 0 -> remove_one trie (take s c) | (true, false, true) -> remove_one trie (take s c) | (true, _, _) -> remove_impl exact child (drop s c) | _ -> ()) let remove (trie : 'a t) (s : string) : unit = remove_impl true trie s let remove_prefix (trie : 'a t) (s : string) : unit = remove_impl false trie s (* let rec merge ?(if_exist : 'a -> 'a -> unit = fun _ _ -> ()) *) (* (trieDes : 'a t) *) (* (trieSrc : 'a t) : unit = *) (* let rec merge_one des s n = *) (* try *) (* let (c, key, child) = trie_assoc_partial des s in *) (* if String.length key = c then begin *) (* (\* matched whole key. *) (* * Either continue to merge child, if whole s matched, *) (* * or continue to match in des's path, if some s left*\) *) (* if (String.length s = c) && (not (s = "")) then *) (* merge child n ~if_exist *) (* else if (not (s = "")) then *) (* merge_one child (string_drop s c) n *) (* else *) (* (\* empty key match, means same value exist *) (* * resolve use if_exist *\) *) (* let desv = get_leaf child in *) (* let srcv = get_leaf n in *) (* if_exist desv srcv *) (* end *) (* else *) (* (\* partially match key, need to split key, and merge into *\) *) (* let common = string_take s c in *) (* remove_one des key; *) (* if (c = String.length s) then begin *) (* (\* when s is fully match, just take the node keyed by s *) (* * no need to create new one *\) *) (* add_one des common n; *) (* merge_one n (string_drop key c) child *) (* end *) (* else begin *) (* let t = create () in *) (* add_one t (string_drop key c) child; *) (* add_one t (string_drop s c) n; *) (* add_one des common t *) (* end *) (* with Not_found -> *) (* add_one des s n *) (* in *) (* let l = get_node trieSrc in *) (* List.iter (fun (s, n) -> merge_one trieDes s n) !l *) let rec to_string_impl (buf : Buffer.t) (trie : 'a t) : unit = match trie with | Node elts -> SMap.fold (fun k v _ -> Printf.bprintf buf "%S:{" k; to_string_impl buf v; Printf.bprintf buf "}") !elts () | Leaf _v -> () let to_string (trie : 'a t) : string = let buf = Buffer.create 250 in to_string_impl buf trie; Buffer.contents buf
OCaml Interface
hhvm/hphp/hack/src/utils/trie.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 'a t val make_pair : 'a -> 'b -> 'a * 'b val common_prefix : string -> string -> int val drop : string -> int -> string val take : string -> int -> string val ( |> ) : 'a -> ('a -> 'b) -> 'b val id : 'a -> 'a type 'a return = { return: 'b. 'a -> 'b } val with_return : ('a return -> 'a) -> 'a val create : unit -> 'a t exception Inconsistent_trie of string val get_node : 'a t -> 'a t SMap.t ref val get_leaf : 'a t -> 'a val trie_assoc_partial : 'a t -> string -> (int * string * 'a t) option val mem : 'a t -> string -> bool val add_one : 'a t -> string -> 'a t -> unit val split_key : 'a t -> string -> 'a t -> int -> 'a t val add_leaf : 'a t -> string -> 'a -> unit val add : ?if_exist:('b -> 'a -> unit) -> transform:('a -> 'b) -> 'b t -> string -> 'a -> unit val to_list : int option -> 'b t -> (string -> 'a) -> ('a -> 'b -> 'c) -> 'c list val find_impl : ?limit:int option -> bool -> 'a t -> string -> (string -> 'a -> 'c) -> 'c list val find : 'a t -> string -> 'a option val find_prefix : 'a t -> string -> (string -> 'a -> 'b) -> 'b list val find_prefix_limit : int -> 'a t -> string -> (string -> 'a -> 'b) -> 'b list val remove_one : 'a t -> string -> unit val remove_impl : bool -> 'a t -> string -> unit val remove : 'a t -> string -> unit val remove_prefix : 'a t -> string -> unit val to_string_impl : Buffer.t -> 'a t -> unit val to_string : 'a t -> string
Rust
hhvm/hphp/hack/src/utils/unwrap_ocaml.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. extern "C" { fn caml_failwith(msg: *const libc::c_char); } /// This trait is to provide .unwrap_ocaml() on a Result<T,E>. /// Its behavior upon Err is to caml_failwith, i.e. exactly the same /// behavior as ocaml's "failwith" primitive. The exception string /// includes a debug-print of E which, for anyhow-backed errors, /// includes a stack trace. /// It must only be called from within an ocaml FFI, and indeed can only /// be linked when inside an ocaml binary. pub trait UnwrapOcaml<T> { fn unwrap_ocaml(self) -> T; } impl<T, E: std::fmt::Debug + std::fmt::Display> UnwrapOcaml<T> for Result<T, E> { fn unwrap_ocaml(self) -> T { match self { Ok(t) => t, Err(e) => { eprintln!("Gathering error callstacks... [{e}]"); // It can honestly take 45s to fetch the backtrace ":?" in an ocaml binary. Crazy. let msg = format!("{e:?}"); let msg = std::ffi::CString::new(msg).expect("null byte in error"); // Safety: through the unenforced convention that we're only ever invoked by ocaml ffi unsafe { caml_failwith(msg.into_raw()) }; unreachable!() } } } }
OCaml
hhvm/hphp/hack/src/utils/visitors_runtime.ml
(* * Copyright (c) 2017, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (** We didn't have access to the VisitorsRuntime module from OPAM when we * originally added visitors, so we redefined the base classes ourselves here. * * Now, we have access to the VisitorsRuntime module, but we can't directly use * it because we've used the "on_" prefix for all our visit methods instead of * "visit_". So instead, this module provides classes containing methods with * the "on_" prefix (for all the VisitorsRuntime methods we happen to use) * and which inherit from the real VisitorsRuntime classes. * * It also provides abstract base classes for the [iter], [map], [reduce], and * [endo] classes, making it possible to have multiple inheritance of visitor * classes without overriding the VisitorsRuntime methods. * * For example, if we have: * * type foo = int [@@deriving visitors { variety = "iter"; name = "iter_foo" }] * type bar = int [@@deriving visitors { variety = "iter"; name = "iter_bar" }] * type baz = foo * bar [@@deriving visitors { * variety = "iter"; * ancestors = ["iter_foo"; "iter_bar"]; * }] * * Then the [iter_foo] class and [iter_bar] class will both inherit from * [VisitorsRuntime.iter]. This makes the [ancestors] clause for [baz] a * problem: [iter_bar]'s inherited implementations of the [VisitorsRuntime.iter] * methods will override [iter_foo]'s (even though they are the same * implementations). This triggers a compiler warning. * * We could suppress the warning, or instead, we could have [foo] and [bar]'s * visitors inherit from abstract base classes which do not define any concrete * implementations: * * type foo = int [@@deriving visitors { * variety = "iter"; * name = "iter_foo"; * nude = true; * visit_prefix = "on_"; * ancestors = ["Visitors_runtime.iter_base"]; * }] * type bar = int [@@deriving visitors { * variety = "iter"; * name = "iter_bar"; * nude = true; * visit_prefix = "on_"; * ancestors = ["Visitors_runtime.iter_base"]; * }] * type baz = foo * bar [@@deriving visitors { * variety = "iter"; * nude = true; * visit_prefix = "on_"; * ancestors = ["Visitors_runtime.iter"; "iter_foo"; "iter_bar"]; * }] * * Note that [baz] inherits from [Visitors_runtime.iter] rather than * [iter_base]. This should be done for the root type we are interested in * visiting (i.e., the visitor class which consumers will inherit from). If the * type will be included in some other type we are interested in visiting (like * [foo] and [bar] are), the abstract base class should be used instead. *) open Core class virtual ['s] monoid = ['s] VisitorsRuntime.monoid class ['s] addition_monoid = ['s] VisitorsRuntime.addition_monoid class ['s] unit_monoid = ['s] VisitorsRuntime.unit_monoid class virtual ['a] option_monoid = object (self) inherit ['a option] monoid method virtual private merge : 'a -> 'a -> 'a method private zero = None method private plus = Option.merge ~f:self#merge end class virtual ['self] map_base = object (_ : 'self) method virtual private on_string : 'env -> string -> string method virtual private on_int : 'env -> int -> int method virtual private on_bool : 'env -> bool -> bool method virtual private on_list : 'env 'a 'b. ('env -> 'a -> 'b) -> 'env -> 'a list -> 'b list method virtual private on_option : 'env 'a 'b. ('env -> 'a -> 'b) -> 'env -> 'a option -> 'b option end class virtual ['self] map = object (self : 'self) inherit [_] map_base inherit [_] VisitorsRuntime.map method private on_string = self#visit_string method private on_int = self#visit_int method private on_bool = self#visit_bool method private on_list = self#visit_list method private on_option = self#visit_option end class virtual ['self] iter_base = object (_ : 'self) method virtual private on_string : 'env -> string -> unit method virtual private on_int : 'env -> int -> unit method virtual private on_bool : 'env -> bool -> unit method virtual private on_list : 'env 'a. ('env -> 'a -> unit) -> 'env -> 'a list -> unit method virtual private on_option : 'env 'a. ('env -> 'a -> unit) -> 'env -> 'a option -> unit end class virtual ['self] iter = object (self : 'self) inherit [_] iter_base inherit [_] VisitorsRuntime.iter method private on_string = self#visit_string method private on_int = self#visit_int method private on_bool = self#visit_bool method private on_list = self#visit_list method private on_option = self#visit_option end class virtual ['self] endo_base = object (_ : 'self) method virtual private on_string : 'env -> string -> string method virtual private on_int : 'env -> int -> int method virtual private on_bool : 'env -> bool -> bool method virtual private on_list : 'env 'a. ('env -> 'a -> 'a) -> 'env -> 'a list -> 'a list method virtual private on_option : 'env 'a. ('env -> 'a -> 'a) -> 'env -> 'a option -> 'a option end class virtual ['self] endo = object (self : 'self) inherit [_] endo_base inherit [_] VisitorsRuntime.endo method private on_string = self#visit_string method private on_int = self#visit_int method private on_bool = self#visit_bool method private on_list = self#visit_list method private on_option = self#visit_option end class virtual ['self] reduce_base = object (_ : 'self) inherit ['acc] monoid method virtual private on_string : 'env -> string -> 'acc method virtual private on_int : 'env -> int -> 'acc method virtual private on_bool : 'env -> bool -> 'acc method virtual private on_list : 'env 'a. ('env -> 'a -> 'acc) -> 'env -> 'a list -> 'acc method virtual private list_fold_left : 'env 'a. ('env -> 'a -> 'acc) -> 'env -> 'acc -> 'a list -> 'acc method virtual private on_option : 'env 'a. ('env -> 'a -> 'acc) -> 'env -> 'a option -> 'acc end class virtual ['self] reduce = object (self : 'self) inherit ['self] reduce_base inherit [_] VisitorsRuntime.reduce method private on_string = self#visit_string method private on_int = self#visit_int method private on_bool = self#visit_bool method private on_list = self#visit_list method private on_option = self#visit_option end
OCaml
hhvm/hphp/hack/src/utils/wwwroot.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. * *) (* Keep in sync with //hphp/hack/src/facebook/utils/repo_root.rs *) (** * Checks if x is a www directory by looking for ".hhconfig". *) let is_www_directory ?(config = ".hhconfig") (path : Path.t) : bool = let arcconfig = Path.concat path config in Path.file_exists arcconfig let assert_www_directory ?(config = ".hhconfig") (path : Path.t) : unit = if not (Path.file_exists path && Path.is_directory path) then ( Printf.eprintf "Error: %s is not a directory\n%!" (Path.to_string path); exit 1 ); if not (is_www_directory ~config path) then ( Printf.fprintf stderr "Error: could not find a %s file in %s or any of its parent directories. Do you have a %s in your code's root directory?\n%s\n" config (Path.to_string path) config (Exception.get_current_callstack_string 99 |> Exception.clean_stack); flush stderr; exit 1 ) let rec guess_root config start ~recursion_limit : Path.t option = if start = Path.parent start then None (* Reached file system root *) else if is_www_directory ~config start then Some start else if recursion_limit <= 0 then None else guess_root config (Path.parent start) ~recursion_limit:(recursion_limit - 1) let interpret_command_line_root_parameter ?(config = ".hhconfig") (paths : string list) : Path.t = let path = match paths with | [] -> None | [path] -> Some path | _ -> Printf.fprintf stderr "Error: please provide at most one www directory\n%!"; exit 1 in let start_str = match path with | None -> "." | Some s -> s in let start_path = Path.make start_str in let root = match guess_root config start_path ~recursion_limit:50 with | None -> start_path | Some r -> r in assert_www_directory ~config root; root
OCaml Interface
hhvm/hphp/hack/src/utils/wwwroot.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_www_directory : ?config:string -> Path.t -> bool val assert_www_directory : ?config:string -> Path.t -> unit (** Our command-line tools generally take a "root" parameter, and if none is supplied then they fall back to a search based on the current directory. This code implements that -- it ensures that either 0 or 1 root parameters were passed (and prints to stderr and exits with code 1 if there were more); if there were 0 parameters then it walks from CWD to find .hhconfig and if there was 1 then it walks from that to find .hhconfig. Then it validates that .hhconfig really is there, and prints to stderr and exits with code 1 if it wasn't. CARE! Don't call this from arbitrary code in client or server, passing in None in the hope that you'll pick up the root directory for your current process. Doing so will mean you ignore the "root" parameter at the command-line! *) val interpret_command_line_root_parameter : ?config:string -> string list -> Path.t
TOML
hhvm/hphp/hack/src/utils/arena_deserializer/Cargo.toml
# @generated by autocargo [package] name = "arena_deserializer" version = "0.0.0" edition = "2021" [lib] path = "lib.rs" [dependencies] bstr = { version = "1.4.0", features = ["serde", "std", "unicode"] } bumpalo = { version = "3.11.1", features = ["collections"] } ocamlrep_caml_builtins = { version = "0.1.0", git = "https://github.com/facebook/ocamlrep/", branch = "main" } serde = { version = "1.0.176", features = ["derive", "rc"] }
Rust
hhvm/hphp/hack/src/utils/arena_deserializer/deserializer.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::any; use std::fmt; use std::marker::PhantomData; use std::mem; use bumpalo::Bump; use serde::de::DeserializeSeed; use serde::de::Deserializer; use serde::de::EnumAccess; use serde::de::MapAccess; use serde::de::SeqAccess; use serde::de::VariantAccess; use serde::de::Visitor; #[repr(C)] pub struct ArenaDeserializer<'arena, 'de, D> { arena: &'arena Bump, // must be first field delegate: D, marker: PhantomData<fn() -> &'de ()>, } impl<'arena, 'de, D> ArenaDeserializer<'arena, 'de, D> { pub fn new(arena: &'arena Bump, delegate: D) -> Self { ArenaDeserializer { arena, delegate, marker: PhantomData, } } } impl<'arena, 'de, D> Deserializer<'arena> for ArenaDeserializer<'arena, 'de, D> where D: Deserializer<'de>, { type Error = <D as Deserializer<'de>>::Error; fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_any(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_bool(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_i8(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_i16(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_i32(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_i64(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_u8(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_u16(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_u32(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_u64(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_f32(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_f64(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_char(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_str(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_string(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_bytes(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_byte_buf(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_option(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_unit(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_unit_struct<V>( self, name: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_unit_struct( name, ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }, ) } fn deserialize_newtype_struct<V>( self, name: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_newtype_struct( name, ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }, ) } fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_seq(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_tuple( len, ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }, ) } fn deserialize_tuple_struct<V>( self, name: &'static str, len: usize, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_tuple_struct( name, len, ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }, ) } fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_map(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_struct<V>( self, name: &'static str, fields: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_struct( name, fields, ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }, ) } fn deserialize_enum<V>( self, name: &'static str, variants: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_enum( name, variants, ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }, ) } fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_identifier(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.deserialize_ignored_any(ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }) } } impl<'arena, 'de, V> Visitor<'de> for ArenaDeserializer<'arena, 'de, V> where V: Visitor<'arena>, { type Value = <V as Visitor<'arena>>::Value; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { self.delegate.expecting(formatter) } fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_bool(v) } fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_i8(v) } fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_i16(v) } fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_i32(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_i64(v) } fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_u8(v) } fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_u16(v) } fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_u32(v) } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_u64(v) } fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_f32(v) } fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_f64(v) } fn visit_char<E>(self, v: char) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_char(v) } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_str(v) } fn visit_string<E>(self, v: String) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_string(v) } fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_bytes(v) } fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_byte_buf(v) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_none() } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { self.delegate.visit_some(ArenaDeserializer { arena: self.arena, delegate: deserializer, marker: PhantomData, }) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: serde::de::Error, { self.delegate.visit_unit() } fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { self.delegate.visit_newtype_struct(ArenaDeserializer { arena: self.arena, delegate: deserializer, marker: PhantomData, }) } fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de>, { self.delegate.visit_seq(ArenaDeserializer { arena: self.arena, delegate: seq, marker: PhantomData, }) } fn visit_map<M>(self, map: M) -> Result<Self::Value, M::Error> where M: MapAccess<'de>, { self.delegate.visit_map(ArenaDeserializer { arena: self.arena, delegate: map, marker: PhantomData, }) } fn visit_enum<E>(self, data: E) -> Result<Self::Value, E::Error> where E: EnumAccess<'de>, { self.delegate.visit_enum(ArenaDeserializer { arena: self.arena, delegate: data, marker: PhantomData, }) } } impl<'arena, 'de, S> SeqAccess<'arena> for ArenaDeserializer<'arena, 'de, S> where S: SeqAccess<'de>, { type Error = <S as SeqAccess<'de>>::Error; fn next_element_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> where K: DeserializeSeed<'arena>, { self.delegate.next_element_seed(ArenaDeserializer { arena: self.arena, delegate: seed, marker: PhantomData, }) } } impl<'arena, 'de, M> MapAccess<'arena> for ArenaDeserializer<'arena, 'de, M> where M: MapAccess<'de>, { type Error = <M as MapAccess<'de>>::Error; fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> where K: DeserializeSeed<'arena>, { self.delegate.next_key_seed(ArenaDeserializer { arena: self.arena, delegate: seed, marker: PhantomData, }) } fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error> where V: DeserializeSeed<'arena>, { self.delegate.next_value_seed(ArenaDeserializer { arena: self.arena, delegate: seed, marker: PhantomData, }) } } impl<'arena, 'de, E> EnumAccess<'arena> for ArenaDeserializer<'arena, 'de, E> where E: EnumAccess<'de>, { type Error = <E as EnumAccess<'de>>::Error; type Variant = ArenaDeserializer<'arena, 'de, <E as EnumAccess<'de>>::Variant>; fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> where V: DeserializeSeed<'arena>, { let (value, variant) = self.delegate.variant_seed(ArenaDeserializer { arena: self.arena, delegate: seed, marker: PhantomData, })?; Ok(( value, ArenaDeserializer { arena: self.arena, delegate: variant, marker: PhantomData, }, )) } } impl<'arena, 'de, E> VariantAccess<'arena> for ArenaDeserializer<'arena, 'de, E> where E: VariantAccess<'de>, { type Error = <E as VariantAccess<'de>>::Error; fn unit_variant(self) -> Result<(), Self::Error> { self.delegate.unit_variant() } fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error> where T: DeserializeSeed<'arena>, { self.delegate.newtype_variant_seed(ArenaDeserializer { arena: self.arena, delegate: seed, marker: PhantomData, }) } fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.tuple_variant( len, ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }, ) } fn struct_variant<V>( self, fields: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'arena>, { self.delegate.struct_variant( fields, ArenaDeserializer { arena: self.arena, delegate: visitor, marker: PhantomData, }, ) } } impl<'arena, 'de, S> DeserializeSeed<'de> for ArenaDeserializer<'arena, 'de, S> where S: DeserializeSeed<'arena>, { type Value = <S as DeserializeSeed<'arena>>::Value; fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { self.delegate.deserialize(ArenaDeserializer { arena: self.arena, delegate: deserializer, marker: PhantomData, }) } } pub(crate) fn obtain_arena<'arena, D>(deserializer: &D) -> Result<&'arena Bump, D::Error> where D: Deserializer<'arena>, { // Not 100% bulletproof. The failure mode is if somebody were to make a // different crate with the same crate name and type name, and pass one of // their deserializers into here. This would only happen if somebody is // deliberately attacking this code, which realistically we do not expect. let deserializer_type_name = any::type_name::<D>(); if !deserializer_type_name.starts_with("arena_deserializer::deserializer::ArenaDeserializer<") { return Err(serde::de::Error::custom(format!( "#[serde(deserialize_with = \"arena\")] used with non-ArenaDeserializer: {}", deserializer_type_name, ))); } // So D is ArenaDeserializer<'?a, '?b, ?C> for some unknown '?a, '?b, 'C. // // The Deserializer impl for ArenaDeserializer is: // // impl<'arena, 'de, D> Deserializer<'arena> for ArenaDeserializer<'arena, 'de, D> // where // D: Deserializer<'de>; // // and we know ArenaDeserializer<'?a, '?b, ?C> impls Deserializer<'arena>, // therefore '?a == 'arena. // // The first field of ArenaDeserializer<'arena, '?b, ?C> is &'arena Bump so // we can grab that. let arena = unsafe { mem::transmute_copy::<D, &'arena Bump>(deserializer) }; Ok(arena) }
Rust
hhvm/hphp/hack/src/utils/arena_deserializer/impls.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::fmt; use std::marker::PhantomData; use bumpalo::collections::Vec as ArenaVec; use bumpalo::Bump; use ocamlrep_caml_builtins::Int64; use serde::de::Deserializer; use serde::de::SeqAccess; use serde::de::Visitor; use serde::Deserialize; use crate::seed::ArenaSeed; pub trait DeserializeInArena<'arena>: Sized { fn deserialize_in_arena<D>(arena: &'arena Bump, deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'arena>; } #[macro_export] macro_rules! impl_deserialize_in_arena{ ($ty:ident < $($lt:lifetime),* $(,)? $($tp:ident),* >) => { impl<'arena, $($tp : 'arena + $crate::DeserializeInArena<'arena>),*> $crate::DeserializeInArena<'arena> for $ty<$($lt,)* $($tp,)* > { fn deserialize_in_arena<__D>( arena: &'arena $crate::bumpalo::Bump, deserializer: __D, ) -> Result<Self, __D::Error> where __D: $crate::serde::Deserializer<'arena>, { let _ = arena; $crate::serde::Deserialize::deserialize(deserializer) } } impl<'arena, $($tp : $crate::DeserializeInArena<'arena>),*> $crate::DeserializeInArena<'arena> for &'arena $ty<$($lt,)* $($tp,)* > { fn deserialize_in_arena<__D>( arena: &'arena $crate::bumpalo::Bump, deserializer: __D, ) -> Result<Self, __D::Error> where __D: $crate::serde::Deserializer<'arena>, { let value = <$ty<$($tp,)*>>::deserialize_in_arena(arena, deserializer)?; Ok(arena.alloc(value)) } } }; ($ty:ty) => { impl<'arena> $crate::DeserializeInArena<'arena> for $ty { fn deserialize_in_arena<__D>( arena: &'arena $crate::bumpalo::Bump, deserializer: __D, ) -> Result<Self, __D::Error> where __D: $crate::serde::Deserializer<'arena>, { let _ = arena; $crate::serde::Deserialize::deserialize(deserializer) } } impl<'arena> $crate::DeserializeInArena<'arena> for &'arena $ty { fn deserialize_in_arena<__D>( arena: &'arena $crate::bumpalo::Bump, deserializer: __D, ) -> Result<Self, __D::Error> where __D: $crate::serde::Deserializer<'arena>, { let value = <$ty>::deserialize(deserializer)?; Ok(arena.alloc(value)) } } }; } impl_deserialize_in_arena!(()); impl_deserialize_in_arena!(bool); impl_deserialize_in_arena!(i8); impl_deserialize_in_arena!(i16); impl_deserialize_in_arena!(i32); impl_deserialize_in_arena!(i64); impl_deserialize_in_arena!(isize); impl_deserialize_in_arena!(u8); impl_deserialize_in_arena!(u16); impl_deserialize_in_arena!(u32); impl_deserialize_in_arena!(u64); impl_deserialize_in_arena!(usize); impl_deserialize_in_arena!(f32); impl_deserialize_in_arena!(f64); impl_deserialize_in_arena!(char); impl_deserialize_in_arena!(Int64); impl<'arena> DeserializeInArena<'arena> for &'arena str { fn deserialize_in_arena<D>(arena: &'arena Bump, deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'arena>, { struct StrInArena<'arena> { arena: &'arena Bump, } impl<'arena, 'de> Visitor<'de> for StrInArena<'arena> { type Value = &'arena str; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("a string") } fn visit_str<E>(self, string: &str) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(self.arena.alloc_str(string)) } } deserializer.deserialize_str(StrInArena { arena }) } } impl<'arena> DeserializeInArena<'arena> for &'arena bstr::BStr { fn deserialize_in_arena<D>(arena: &'arena Bump, deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'arena>, { struct BStrVisitor<'arena> { arena: &'arena Bump, } impl<'arena, 'de> Visitor<'de> for BStrVisitor<'arena> { type Value = &'arena bstr::BStr; fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("a borrowed byte string") } #[inline] fn visit_seq<V: SeqAccess<'de>>(self, mut visitor: V) -> Result<Self::Value, V::Error> { let len = std::cmp::min(visitor.size_hint().unwrap_or(0), 256); let mut bytes = ArenaVec::with_capacity_in(len, self.arena); while let Some(v) = visitor.next_element()? { bytes.push(v); } Ok(bytes.into_bump_slice().into()) } #[inline] fn visit_borrowed_bytes<E>(self, value: &'de [u8]) -> Result<Self::Value, E> where E: serde::de::Error, { Ok((self.arena.alloc_slice_copy(value) as &[u8]).into()) } #[inline] fn visit_borrowed_str<E>(self, value: &'de str) -> Result<Self::Value, E> where E: serde::de::Error, { Ok((self.arena.alloc_str(value) as &str).into()) } #[inline] fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E> where E: serde::de::Error, { Ok((self.arena.alloc_slice_copy(value) as &[u8]).into()) } } deserializer.deserialize_bytes(BStrVisitor { arena }) } } impl<'arena, T> DeserializeInArena<'arena> for &'arena [T] where T: DeserializeInArena<'arena>, { fn deserialize_in_arena<D>(arena: &'arena Bump, deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'arena>, { struct SliceInArena<'arena, T> { arena: &'arena Bump, marker: PhantomData<fn() -> T>, } impl<'arena, T> Visitor<'arena> for SliceInArena<'arena, T> where T: DeserializeInArena<'arena> + 'arena, { type Value = &'arena [T]; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("an array") } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'arena>, { let mut vec = Vec::with_capacity(seq.size_hint().unwrap_or(0)); let seed = ArenaSeed::new(); while let Some(value) = seq.next_element_seed(seed)? { vec.push(value); } Ok(self.arena.alloc_slice_fill_iter(vec)) } } deserializer.deserialize_seq(SliceInArena { arena, marker: PhantomData, }) } } impl<'arena, T> DeserializeInArena<'arena> for Option<T> where T: DeserializeInArena<'arena>, { fn deserialize_in_arena<D>(arena: &'arena Bump, deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'arena>, { struct OptionVisitor<'arena, T> { arena: &'arena Bump, marker: PhantomData<fn() -> T>, } impl<'arena, T: DeserializeInArena<'arena>> Visitor<'arena> for OptionVisitor<'arena, T> { type Value = Option<T>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("option") } #[inline] fn visit_unit<E>(self) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(None) } #[inline] fn visit_none<E>(self) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(None) } #[inline] fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'arena>, { T::deserialize_in_arena(self.arena, deserializer).map(Some) } } deserializer.deserialize_option(OptionVisitor { arena, marker: PhantomData, }) } } impl<'arena, T> DeserializeInArena<'arena> for &'arena Option<T> where T: DeserializeInArena<'arena>, { fn deserialize_in_arena<D>(arena: &'arena Bump, deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'arena>, { let v = <Option<T>>::deserialize_in_arena(arena, deserializer)?; Ok(arena.alloc(v)) } } macro_rules! tuple_impls { ($($len:tt => ($($n:tt $name:ident)+))+) => { $( impl<'arena, $($name: DeserializeInArena<'arena>),+> DeserializeInArena<'arena> for ($($name,)+) { #[inline] fn deserialize_in_arena<D>(_arena: &'arena Bump, deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'arena>, { struct TupleVisitor<$($name,)+> { marker: PhantomData<($($name,)+)>, } impl<'arena, $($name: DeserializeInArena<'arena>),+> Visitor<'arena> for TupleVisitor<$($name,)+> { type Value = ($($name,)+); fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str(concat!("a tuple of size ", $len)) } #[inline] #[allow(non_snake_case)] fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'arena>, { $( let seed = ArenaSeed::new(); let $name = match seq.next_element_seed(seed)? { Some(value) => value, None => return Err(serde::de::Error::invalid_length($n, &self)), }; )+ Ok(($($name,)+)) } } deserializer.deserialize_tuple($len, TupleVisitor { marker: PhantomData }) } } impl<'arena, $($name: DeserializeInArena<'arena>),+> DeserializeInArena<'arena> for &'arena ($($name,)+) { #[inline] fn deserialize_in_arena<D>(arena: &'arena Bump, deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'arena>, { let v = <($($name,)+)>::deserialize_in_arena(arena, deserializer)?; Ok(arena.alloc(v)) } } )+ } } tuple_impls! { 1 => (0 T0) 2 => (0 T0 1 T1) 3 => (0 T0 1 T1 2 T2) 4 => (0 T0 1 T1 2 T2 3 T3) 5 => (0 T0 1 T1 2 T2 3 T3 4 T4) 6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5) 7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6) 8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7) 9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8) 10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9) 11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10) 12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11) 13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12) 14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13) 15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14) 16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15) }
Rust
hhvm/hphp/hack/src/utils/arena_deserializer/lib.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. mod deserializer; mod impls; mod seed; pub use bumpalo; pub use serde; use serde::de::DeserializeSeed; use serde::de::Deserializer; pub use crate::deserializer::ArenaDeserializer; pub use crate::impls::DeserializeInArena; pub use crate::seed::ArenaSeed; pub fn arena<'arena, D, T>(deserializer: D) -> Result<T, D::Error> where D: Deserializer<'arena>, T: DeserializeInArena<'arena>, { ArenaSeed::new().deserialize(deserializer) }
Rust
hhvm/hphp/hack/src/utils/arena_deserializer/seed.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::marker::PhantomData; use serde::de::DeserializeSeed; use serde::de::Deserializer; use crate::deserializer::obtain_arena; use crate::impls::DeserializeInArena; pub struct ArenaSeed<T> { marker: PhantomData<fn() -> T>, } impl<T> ArenaSeed<T> { pub fn new() -> Self { let marker = PhantomData; ArenaSeed { marker } } } impl<T> Copy for ArenaSeed<T> {} impl<T> Clone for ArenaSeed<T> { fn clone(&self) -> Self { *self } } impl<'arena, T> DeserializeSeed<'arena> for ArenaSeed<T> where T: DeserializeInArena<'arena>, { type Value = T; fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'arena>, { let arena = obtain_arena(&deserializer)?; T::deserialize_in_arena(arena, deserializer) } }
hhvm/hphp/hack/src/utils/artifact_store/dune
(* -*- tuareg -*- *) let library_entry name suffix = Printf.sprintf "(library (name %s) (wrapped false) (modules) (libraries %s_%s))" name name suffix let fb_entry name = library_entry name "fb" let stubs_entry name = library_entry name "stubs" let entry is_fb name = if is_fb then fb_entry name else stubs_entry name let () = (* test presence of fb subfolder *) let current_dir = Sys.getcwd () in (* we are in src/utils/artifact_store, locate src/facebook *) let src_dir = Filename.dirname @@ Filename.dirname current_dir in let fb_dir = Filename.concat src_dir "facebook" in (* locate src/facebook/dune *) let fb_dune = Filename.concat fb_dir "dune" in let is_fb = Sys.file_exists fb_dune in let lib_entry = entry is_fb "artifact_store" in Jbuild_plugin.V1.send lib_entry
OCaml
hhvm/hphp/hack/src/utils/bser/bser.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. * *) exception ParseException of int exception ParseStateException of int exception CallbackNotImplementedException type 'a callbacks_type = { template_start: 'a -> string array -> int -> 'a; template_end: 'a -> 'a; template_object_start: 'a -> 'a; template_object_end: 'a -> 'a; template_field_start: 'a -> int -> 'a; template_field_end: 'a -> 'a; array_start: 'a -> int -> 'a; array_end: 'a -> 'a; array_item_end: 'a -> 'a; integer_value: 'a -> int -> 'a; string_value: 'a -> string -> 'a; object_start: 'a -> int -> 'a; object_end: 'a -> 'a; field_start: 'a -> string -> 'a; field_end: 'a -> 'a; boolean_value: 'a -> bool -> 'a; null_value: 'a -> 'a; } (* `input_byte` grabs 8 bits from a channel and stores them in the least significant byte of an `int`, which is 31 bits wide on 32-bit systems, and 63 bits wide on 64-bit systems. This sign extends in either case. *) let sign_extend_byte i = let mask = 0x80 in let ones = -1 lxor 0xFF in if i land mask <> 0 then ones lor i else i (* Note: this ignores overflow, so e.g. on a 64-bit machine, values in [-2^64; -2^62) (half open range) get truncated. *) let parse_int_value tag ic = let size_bytes = match tag with | '\x03' -> 1 | '\x04' -> 2 | '\x05' -> 4 | '\x06' -> 8 | _ -> raise (ParseException (pos_in ic)) in let rec inner acc i = if i = 0 then acc else let thebyte = input_byte ic in let acc = (acc lsl 8) lor thebyte in inner acc (i - 1) in let initial = input_byte ic |> sign_extend_byte in inner initial (size_bytes - 1) let parse_int ic = let tag = input_char ic in parse_int_value tag ic let parse_string_value ic = let size = parse_int ic in if size < 0 then raise (ParseStateException (pos_in ic)); really_input_string ic size let expect_string ic acc callbacks = let value = parse_string_value ic in callbacks.string_value acc value let expect_int_value tag ic acc callbacks = let value = parse_int_value tag ic in callbacks.integer_value acc value let expect_real _ic _acc _callbacks = failwith "expect_real not implemented" (* Entry point. Parse any bser value and make the appropriate callbacks. For the tags and a general description of the format: https://facebook.github.io/watchman/docs/bser.html *) let rec expect_toplevel ic acc callbacks = let tag = input_char ic in match tag with | '\x00' -> expect_array ic acc callbacks | '\x01' -> expect_object ic acc callbacks | '\x02' -> expect_string ic acc callbacks | '\x03' | '\x04' | '\x05' | '\x06' -> expect_int_value tag ic acc callbacks | '\x07' -> expect_real ic acc callbacks | '\x08' -> callbacks.boolean_value acc true | '\x09' -> callbacks.boolean_value acc false | '\x0a' -> callbacks.null_value acc | '\x0b' -> expect_template ic acc callbacks | '\x0c' -> acc | _ -> raise (ParseException (pos_in ic)) and expect_array ic acc callbacks = let size = parse_int ic in if size < 0 then raise (ParseStateException (pos_in ic)); let acc = callbacks.array_start acc size in let rec inner acc i = if i = 0 then acc else let acc = expect_toplevel ic acc callbacks in let acc = callbacks.array_item_end acc in inner acc (i - 1) in let acc = inner acc size in callbacks.array_end acc and expect_object ic acc callbacks = let fieldcount = parse_int ic in if fieldcount < 0 then raise (ParseStateException (pos_in ic)); let acc = callbacks.object_start acc fieldcount in let rec inner acc i = if i = 0 then acc else ( if input_char ic <> '\x02' then raise (ParseException (pos_in ic)); let fieldname = parse_string_value ic in let acc = callbacks.field_start acc fieldname in let acc = expect_toplevel ic acc callbacks in let acc = callbacks.field_end acc in inner acc (i - 1) ) in let acc = inner acc fieldcount in callbacks.object_end acc and expect_template ic acc callbacks = if input_char ic <> '\x00' then raise (ParseException (pos_in ic)); let fieldcount = parse_int ic in if fieldcount < 0 then raise (ParseStateException (pos_in ic)); let rec fieldnames_inner acc i = if i = 0 then acc else let tag = input_char ic in if tag <> '\x02' then raise (ParseException (pos_in ic)); let fieldname = parse_string_value ic in fieldnames_inner (fieldname :: acc) (i - 1) in let field_array = fieldnames_inner [] fieldcount |> Array.of_list in let rowcount = parse_int ic in if rowcount < 0 then raise (ParseStateException (pos_in ic)); let acc = callbacks.template_start acc field_array rowcount in let rec object_inner acc i = if i = 0 then acc else let acc = callbacks.template_field_start acc (i - 1) in let acc = expect_toplevel ic acc callbacks in let acc = callbacks.template_field_end acc in object_inner acc (i - 1) in let rec row_inner acc i = if i = 0 then acc else let acc = callbacks.template_object_start acc in let acc = object_inner acc fieldcount in let acc = callbacks.template_object_end acc in row_inner acc (i - 1) in let acc = row_inner acc rowcount in callbacks.template_end acc let throws_visitor = { template_start = (fun _ _ _ -> raise CallbackNotImplementedException); template_end = (fun _ -> raise CallbackNotImplementedException); template_object_start = (fun _ -> raise CallbackNotImplementedException); template_object_end = (fun _ -> raise CallbackNotImplementedException); template_field_start = (fun _ _ -> raise CallbackNotImplementedException); template_field_end = (fun _ -> raise CallbackNotImplementedException); array_start = (fun _ _ -> raise CallbackNotImplementedException); array_end = (fun _ -> raise CallbackNotImplementedException); array_item_end = (fun _ -> raise CallbackNotImplementedException); integer_value = (fun _ _ -> raise CallbackNotImplementedException); string_value = (fun _ _ -> raise CallbackNotImplementedException); object_start = (fun _ _ -> raise CallbackNotImplementedException); object_end = (fun _ -> raise CallbackNotImplementedException); field_start = (fun _ _ -> raise CallbackNotImplementedException); field_end = (fun _ -> raise CallbackNotImplementedException); boolean_value = (fun _ _ -> raise CallbackNotImplementedException); null_value = (fun _ -> raise CallbackNotImplementedException); } type json_state = | Js_value of Hh_json.json | Js_buildingArray of Hh_json.json list | Js_buildingObject of (string * Hh_json.json) list | Js_buildingField of string | Js_buildingTemplate of string array * Hh_json.json list type json_acc = json_state list let json_callbacks = { array_start = (fun acc _size -> Js_buildingArray [] :: acc); array_end = (function | Js_buildingArray elts :: rest -> Js_value (Hh_json.JSON_Array (List.rev elts)) :: rest | _ -> raise (ParseStateException (-1))); array_item_end = (function | Js_value x :: Js_buildingArray elts :: rest -> Js_buildingArray (x :: elts) :: rest | _ -> raise (ParseStateException (-1))); integer_value = (fun acc i -> Js_value (Hh_json.JSON_Number (string_of_int i)) :: acc); string_value = (fun acc w -> Js_value (Hh_json.JSON_String w) :: acc); object_start = (fun acc _size -> Js_buildingObject [] :: acc); object_end = (function | Js_buildingObject elts :: rest -> (* note: no order fixup of name value pairs here *) Js_value (Hh_json.JSON_Object elts) :: rest | _ -> raise (ParseStateException (-1))); field_start = (fun acc name -> match acc with | Js_buildingObject _ :: _ -> Js_buildingField name :: acc | _ -> raise (ParseStateException (-1))); field_end = (function | Js_value x :: Js_buildingField f :: Js_buildingObject elts :: xs -> Js_buildingObject ((f, x) :: elts) :: xs | _ -> raise (ParseStateException (-1))); boolean_value = (fun acc b -> Js_value (Hh_json.JSON_Bool b) :: acc); null_value = (fun acc -> Js_value Hh_json.JSON_Null :: acc); template_start = (fun acc fields _size -> Js_buildingTemplate (fields, []) :: acc); template_end = (function | Js_buildingTemplate (_, elts) :: rest -> Js_value (Hh_json.JSON_Array (List.rev elts)) :: rest | _ -> raise (ParseStateException (-1))); template_object_start = (fun acc -> match acc with | Js_buildingTemplate _ :: _ -> Js_buildingObject [] :: acc | _ -> raise (ParseStateException (-1))); template_object_end = (fun acc -> match acc with | Js_buildingObject fields :: Js_buildingTemplate (names, elts) :: rest -> Js_buildingTemplate (names, Hh_json.JSON_Object fields :: elts) :: rest | _ -> raise (ParseStateException (-1))); template_field_start = (fun acc i -> match acc with | Js_buildingObject _fields :: Js_buildingTemplate (names, _) :: _ -> Js_buildingField names.(i) :: acc | _ -> raise (ParseStateException (-1))); template_field_end = (function | Js_value x :: Js_buildingField f :: Js_buildingObject elts :: xs -> Js_buildingObject ((f, x) :: elts) :: xs | Js_buildingField _f :: tail -> tail | _ -> raise (ParseStateException (-1))); } let json_of_bser_file path : Hh_json.json = let ic = Sys_utils.open_in_bin_no_fail path in if input_char ic <> '\x00' then raise (ParseException (pos_in ic)); if input_char ic <> '\x01' then raise (ParseException (pos_in ic)); let output = expect_toplevel ic [] json_callbacks in match output with | [Js_value x] -> x | _ -> raise (ParseStateException (pos_in ic)) let json_to_channel oc _json : unit = (* TODO(pieter) test output *) output_string oc "42"
OCaml
hhvm/hphp/hack/src/utils/bser/bser_main_test.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. * *) let usage = "Usage: bser_test [filename] [--to_json|--to_bser|--roundtrip]\n" type mode = | To_bser | To_json | Roundtrip [@@warning "-unused-constructor" (* remove when implemented *)] let run_test mode path : unit = match mode with | To_json -> path |> Bser.json_of_bser_file |> Hh_json.json_to_output stdout; output_string stdout "\n" | To_bser -> path |> Hh_json.json_of_file ~strict:false |> Bser.json_to_channel stdout; output_string stdout "\n" | Roundtrip -> failwith "Not implemented yet" let () = if Array.length Sys.argv != 3 then ( output_string stderr usage; flush stderr; exit 2 ); let path = Sys.argv.(1) in if (not (Sys.file_exists path)) || Sys.is_directory path then ( let message = Printf.sprintf "Path `%s` not found or isn't a regular file\n" Sys.argv.(1) in output_string stderr (usage ^ message); flush stderr; exit 2 ); let mode = match Sys.argv.(2) with | "--to_json" -> To_json | "--to_bser" -> To_bser | _ -> output_string stderr usage; flush stderr; exit 2 in Unix.handle_unix_error run_test mode path
hhvm/hphp/hack/src/utils/bser/dune
(library (name bser) (modules bser) (wrapped false) (libraries hh_json sys_utils)) (executable (name bser_main_test) (modules bser_main_test) (modes exe byte_complete) (link_flags (:standard (:include ../../dune_config/ld-opts.sexp))) (libraries bser default_injector_config))
OCaml
hhvm/hphp/hack/src/utils/buffered_line_reader/buffered_line_reader.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. * *) (* Our Unix systems only allow reading 64KB chunks at a time. * Trying to read more than 64KB results in only 64KB being read. *) let chunk_size = 65536 module Regular_reader : Buffered_line_reader_sig.READER with type 'a result = 'a and type fd = Unix.file_descr = struct type 'a result = 'a type fd = Unix.file_descr let return x = x let fail exn = raise exn let ( >>= ) a f = f a let read fd ~buffer ~offset ~size = Unix.read fd buffer offset size let is_readable fd = let (readable, _, _) = Unix.select [fd] [] [] 0.0 in readable <> [] let open_devnull () = Unix.openfile "/dev/null" [Unix.O_RDONLY] 0o440 end module Functor (Reader : Buffered_line_reader_sig.READER) : Buffered_line_reader_sig.S with type 'a result = 'a Reader.result and type fd = Reader.fd = struct let ( >>= ) = Reader.( >>= ) type fd = Reader.fd type 'a result = 'a Reader.result type t = { fd: Reader.fd; (* The bytes left after the last content that haven't been consumed yet. *) unconsumed_buffer: string option ref; } let set_buffer r b = r.unconsumed_buffer := b let trim_trailing_cr = function | "" -> "" | s -> let len = String.length s in if s.[len - 1] = '\r' then String.sub s 0 (len - 1) else s let merge_chunks last_chunk chunks_rev = let chunks_rev = last_chunk :: chunks_rev in let chunks = List.rev chunks_rev in String.concat "" chunks (* This function reads a line, delimited by LF (unix) or CRLF (internet)... * Recursively read a chunk from the file descriptor until we see a newline * character, building up the chunks accumulator along the way. * Any remaining bytes not consumed (bytes past the newline) are placed in the * reader's unconsumed_buffer which will be consumed on the next * call to get_next_line or get_next_bytes. *) let rec read_line chunks r = let b = Bytes.create chunk_size in Reader.read r.fd ~buffer:b ~offset:0 ~size:chunk_size >>= fun bytes_read -> if bytes_read == 0 then raise End_of_file; let b = Bytes.sub_string b 0 bytes_read in match String.index_opt b '\n' with | None -> read_line (b :: chunks) r | Some i -> let tail = String.sub b 0 i in let result = merge_chunks tail chunks in let () = if i + 1 < bytes_read then (* We read some bytes beyond the first newline character. *) let length = bytes_read - (i + 1) in (* We skip the newline character. *) let remainder = String.sub b (i + 1) length in set_buffer r (Some remainder) else (* We didn't read any bytes beyond the first newline character. *) set_buffer r None in Reader.return @@ trim_trailing_cr result let get_next_line r = match !(r.unconsumed_buffer) with | None -> read_line [] r | Some remainder -> begin match String.index_opt remainder '\n' with | None -> let () = set_buffer r None in read_line [remainder] r | Some i -> let result = String.sub remainder 0 i in let () = if i + 1 < String.length remainder then (* There are some bytes left beyond the first newline character. *) let length = String.length remainder - (i + 1) in let remainder = String.sub remainder (i + 1) length in set_buffer r (Some remainder) else (* No bytes beyond the first newline character. *) set_buffer r None in Reader.return @@ trim_trailing_cr result end let rec read_bytes r size chunks = let bytes_desired = min chunk_size size in let b = Bytes.create bytes_desired in Reader.read r.fd ~buffer:b ~offset:0 ~size:bytes_desired >>= fun bytes_read -> if bytes_read == 0 then raise End_of_file; if bytes_read < size then let b = Bytes.sub_string b 0 bytes_read in read_bytes r (size - bytes_read) (b :: chunks) else let () = set_buffer r None in (* `unsafe_to_string` is acceptable here because `merge_chunks` immediately makes a copy via `concat` *) Reader.return @@ merge_chunks (Bytes.unsafe_to_string b) chunks let get_next_bytes r size = assert (size > 0); match !(r.unconsumed_buffer) with | None -> read_bytes r size [] | Some remainder -> let remainder_length = String.length remainder in if remainder_length < size then let () = set_buffer r None in read_bytes r (size - remainder_length) [remainder] else if remainder_length = size then let () = set_buffer r None in Reader.return @@ remainder else let extra = String.sub remainder size (remainder_length - size) in let () = set_buffer r (Some extra) in Reader.return @@ String.sub remainder 0 size let has_buffered_content r = !(r.unconsumed_buffer) <> None let is_readable r = has_buffered_content r || Reader.is_readable r.fd let create fd = { fd; unconsumed_buffer = ref None } let null_reader_ref = ref None let get_null_reader () = match !null_reader_ref with | Some x -> Reader.return x | None -> Reader.open_devnull () >>= fun fd -> let null_reader = { fd; unconsumed_buffer = ref None } in null_reader_ref := Some null_reader; Reader.return null_reader let get_fd r = r.fd end include Functor (Regular_reader)
OCaml Interface
hhvm/hphp/hack/src/utils/buffered_line_reader/buffered_line_reader.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. * *) include Buffered_line_reader_sig.S with type 'a result = 'a and type fd = Unix.file_descr module Functor (Reader : Buffered_line_reader_sig.READER) : Buffered_line_reader_sig.S with type 'a result = 'a Reader.result and type fd = Reader.fd
OCaml
hhvm/hphp/hack/src/utils/buffered_line_reader/buffered_line_reader_lwt.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. * *) module Regular_reader : Buffered_line_reader_sig.READER with type 'a result = 'a Lwt.t and type fd = Lwt_unix.file_descr = struct type 'a result = 'a Lwt.t type fd = Lwt_unix.file_descr let return = Lwt.return let fail = Lwt.fail let ( >>= ) = Lwt.( >>= ) let read fd ~buffer ~offset ~size = Lwt_unix.read fd buffer offset size let is_readable = Lwt_unix.readable let open_devnull () = Lwt_unix.openfile "/dev/null" [Unix.O_RDONLY] 0o440 end include Buffered_line_reader.Functor (Regular_reader)
OCaml Interface
hhvm/hphp/hack/src/utils/buffered_line_reader/buffered_line_reader_lwt.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. * *) include Buffered_line_reader_sig.S with type 'a result = 'a Lwt.t and type fd = Lwt_unix.file_descr
OCaml
hhvm/hphp/hack/src/utils/buffered_line_reader/buffered_line_reader_sig.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. * *) (** * This module is needed because Unix.select doesn't play well with * input_line on Ocaml channels.. i.e., when a buffered read into an * Ocaml channel consumes two complete lines from the file descriptor, the next * select will say there is nothing to read when in fact there is * something in the channel. This wouldn't be a problem if Ocaml channel's API * supported a "has buffered content" call, so you could check if the * buffer contains something as well as doing a Unix select to know for real if * there is content coming. * * The "has_buffered_content" method below does exactly that. * * is_readable is a friendly wrapper around "has_buffered_content" and * non-blocking Unix.select. *) module type S = sig type 'a result type fd type t val create : fd -> t val get_null_reader : unit -> t result val has_buffered_content : t -> bool (** * Returns true if and only if there is content to be read (does not know if * the incoming content is newline-terminated. So we can't actually know * if get_next_line will be non-blocking. *) val is_readable : t -> bool val get_fd : t -> fd val get_next_line : t -> string result val get_next_bytes : t -> int -> string result end module type READER = sig type 'a result type fd val return : 'a -> 'a result val fail : exn -> 'a result val ( >>= ) : 'a result -> ('a -> 'b result) -> 'b result val read : fd -> buffer:bytes -> offset:int -> size:int -> int result val is_readable : fd -> bool val open_devnull : unit -> fd result end
OCaml Interface
hhvm/hphp/hack/src/utils/buffered_line_reader/buffered_line_reader_sig.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 type S = sig type 'a result type fd type t val create : fd -> t val get_null_reader : unit -> t result val has_buffered_content : t -> bool val is_readable : t -> bool val get_fd : t -> fd val get_next_line : t -> string result val get_next_bytes : t -> int -> string result end module type READER = sig type 'a result type fd val return : 'a -> 'a result val fail : exn -> 'a result val ( >>= ) : 'a result -> ('a -> 'b result) -> 'b result val read : fd -> buffer:bytes -> offset:int -> size:int -> int result val is_readable : fd -> bool val open_devnull : unit -> fd result end
hhvm/hphp/hack/src/utils/buffered_line_reader/dune
(library (name buffered_line_reader) (wrapped false) (modules buffered_line_reader buffered_line_reader_sig) (libraries utils_core)) (library (name buffered_line_reader_lwt) (wrapped false) (modules buffered_line_reader_lwt) (libraries buffered_line_reader lwt lwt.unix))
OCaml
hhvm/hphp/hack/src/utils/build_mode/dev/build_mode.ml
(** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "flow" directory of this source tree. * *) let dev = true
OCaml
hhvm/hphp/hack/src/utils/build_mode/prod/build_mode.ml
(** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "flow" directory of this source tree. * *) let dev = false
Rust
hhvm/hphp/hack/src/utils/caml_startup/caml_startup.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::ffi::CString; use std::os::raw::c_char; extern "C" { fn caml_startup(argv: *const *const c_char); } /// Initialize the OCaml runtime. /// /// # Safety /// /// Must be invoked from the main thread. Must be invoked only once. Must /// precede any other interaction with the OCaml runtime. /// /// # Panics /// /// Panics if any argument in argv contains a nul byte. pub unsafe fn startup() { let mut argv: Vec<*const c_char> = (std::env::args().into_iter()) .map(|arg| CString::new(arg.as_str()).unwrap().into_raw() as _) .collect(); argv.push(std::ptr::null()); caml_startup(argv.leak().as_ptr()); }
TOML
hhvm/hphp/hack/src/utils/caml_startup/Cargo.toml
# @generated by autocargo [package] name = "caml_startup" version = "0.0.0" edition = "2021" [lib] path = "caml_startup.rs"
TOML
hhvm/hphp/hack/src/utils/cargo/hh24_test/Cargo.toml
# @generated by autocargo [package] name = "hh24_test" version = "0.0.0" edition = "2021" [lib] path = "../../hh24_test.rs" [dependencies] anyhow = "1.0.71" bumpalo = { version = "3.11.1", features = ["collections"] } direct_decl_parser = { version = "0.0.0", path = "../../../parser/api/cargo/direct_decl_parser" } hh24_types = { version = "0.0.0", path = "../../hh24_types" } names = { version = "0.0.0", path = "../../../naming/names_rust" } oxidized_by_ref = { version = "0.0.0", path = "../../../oxidized_by_ref" } relative_path = { version = "0.0.0", path = "../../rust/relative_path" } tempdir = "0.3" [dev-dependencies] maplit = "1.0"
TOML
hhvm/hphp/hack/src/utils/cargo/si_addendum/Cargo.toml
# @generated by autocargo [package] name = "si_addendum" version = "0.0.0" edition = "2021" [lib] path = "../../si_addendum.rs" test = false doctest = false [dependencies] core_utils_rust = { version = "0.0.0", path = "../../core" } oxidized = { version = "0.0.0", path = "../../../oxidized" } oxidized_by_ref = { version = "0.0.0", path = "../../../oxidized_by_ref" }
OCaml
hhvm/hphp/hack/src/utils/cgroup/cGroup.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 module Unix = Caml_unix module Sys = Stdlib.Sys open Result.Monad_infix let spf = Printf.sprintf (* Little helper module to help memoize things. Probably could be pulled out into its own module * at some point *) module Memoize : sig val forever : f:(unit -> 'a) -> unit -> 'a val until : seconds:float -> f:(unit -> 'a) -> unit -> 'a end = struct let forever ~f = let memoized_result = ref None in fun () -> match !memoized_result with | None -> let result = f () in memoized_result := Some result; result | Some result -> result let until ~seconds ~f = let memoized_result = ref None in let fetch () = let result = f () in memoized_result := Some (Unix.gettimeofday () +. seconds, result); result in fun () -> match !memoized_result with | Some (good_until, result) when Float.(Unix.gettimeofday () < good_until) -> result | _ -> fetch () end (* I've never seen cgroup mounted elsewhere, so it's probably fine to hardcode this for now *) let cgroup_dir = "/sys/fs/cgroup" let assert_is_using_cgroup_v2 = Memoize.forever ~f:(fun () -> if Sys.file_exists cgroup_dir then (* /sys/fs/cgroup/memory exists for cgroup v1 but not v2. It's an easy way to tell the * difference between versions *) if Sys.file_exists (spf "%s/memory" cgroup_dir) then Error (spf "cgroup v1 is mounted at %s. We need v2" cgroup_dir) else Ok () else Error (spf "%s doesn't exist" cgroup_dir)) (* I don't really expect us to switch cgroups often, but let's only cache for 5 seconds *) let get_cgroup_name = Memoize.until ~seconds:5.0 ~f:(fun () -> ProcFS.first_cgroup_for_pid (Unix.getpid ())) type stats = { memory_current: int; memory_swap_current: int; total: int; anon: int; shmem: int; file: int; cgroup_name: string; } (* Some cgroup files contain only a single integer *) let read_single_number_file path = try Ok (Sys_utils.cat path |> String.strip |> int_of_string) with | Failure _ | Sys_error _ -> Error "Failed to parse memory.current" let parse_stat stat_contents = let stats = String.split stat_contents ~on:'\n' |> List.fold_left ~init:SMap.empty ~f:(fun stats line -> match String.split line ~on:' ' with | [key; raw_stat] -> int_of_string_opt raw_stat |> Option.value_map ~default:stats ~f:(fun stat -> SMap.add key stat stats) | _ -> stats) in let get key = match SMap.find_opt key stats with | Some stat -> Ok stat | None -> Error (spf "Failed to find %S in memory.stat" key) in get "anon" >>= fun anon -> get "file" >>= fun file -> get "shmem" >>| fun shmem -> (* In `memory.stat` the `file` stat includes `shmem` *) (anon, file - shmem, shmem) let get_stats_for_cgroup (cgroup_name : string) : (stats, string) result = (* cgroup_name starts with a /, like /my_cgroup *) let dir = spf "%s%s" cgroup_dir cgroup_name in let memory_current_result = read_single_number_file (Filename.concat dir "memory.current") and memory_swap_current_result = read_single_number_file (Filename.concat dir "memory.swap.current") and stat_contents_result = try Ok (Sys_utils.cat (Filename.concat dir "memory.stat")) with | Failure _ | Sys_error _ -> Error "Failed to parse memory.stat" in memory_current_result >>= fun memory_current -> memory_swap_current_result >>= fun memory_swap_current -> stat_contents_result >>= fun stat_contents -> parse_stat stat_contents >>= fun (anon, file, shmem) -> let total = memory_current + memory_swap_current in Ok { total; memory_current; memory_swap_current; anon; file; shmem; cgroup_name; } let get_stats () = assert_is_using_cgroup_v2 () >>= get_cgroup_name >>= get_stats_for_cgroup
OCaml Interface
hhvm/hphp/hack/src/utils/cgroup/cGroup.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. *) type stats = { memory_current: int; (** cgroup/memory.current - the total physical memory for the cgroup *) memory_swap_current: int; (** cgroup/memory.swap.current - the total amount of anonymous memory paged out to swap. *) total: int; (** sum of [memory_current] plus [memory_swap_current] - this is the best measure we have about total memory burden. *) anon: int; (** cgroup/memory.stat:anon - the amount of physical anonymous memory not used for shared memory *) shmem: int; (** cgroup/memory.stat:shmem - the amount of physical anonymous memory being used as shared memory *) file: int; (** cgroup/memory.stat:file-shmem - the amount of physical memory which is not anonymous *) cgroup_name: string; (** the cgroup we queried, obtained dynamically based on our pid *) } (** Reads the current PID, figures out which cgroup it's in (if cgroups are available), and queries it. *) val get_stats : unit -> (stats, string) result
OCaml
hhvm/hphp/hack/src/utils/cgroup/cgroupProfiler.ml
open Hh_prelude (** `cgroup_watcher_start filename subtract_kb_for_array` will reset cgroup_watcher counters, and have it start monitoring the two filenames (e.g. "/sys/fs/.../memory.current" and ".../memory.swap.current") and adds them together. See [cgroup_watcher_get] for the meaning of [subtract_kb_for_array]. *) external cgroup_watcher_start : string -> string -> subtract_kb_for_array:int -> unit = "cgroup_watcher_start" (** This returns (hwm_kb, num_readings, seconds_at_gb[||]) that have been tallied since [cgroup_watcher_start]. Hwm_kb is the high water mark of the cgroup. Num_readings is the number of readings that succeeded. The meaning of seconds_at_gb.(i) is that we spent this many seconds with the value between (subtract_kb_for_array+i) and (subtract_kb_for_array+i+1) gb. *) external cgroup_watcher_get : unit -> int * int * float array = "cgroup_watcher_get" type initial_reading = HackEventLogger.ProfileTypeCheck.stats * (CGroup.stats, string) result (** This is the [initial_reading] that we capture upon module load, i.e. process startup *) let initial_reading_capture : initial_reading = let stats = HackEventLogger.ProfileTypeCheck.get_stats ~include_current_process:false ~include_slightly_costly_stats:true ~shmem_heap_size:0 (Telemetry.create ()) in (stats, CGroup.get_stats ()) (** This is the [initial_reading] that we'll actually use, i.e. we'll record data relative to this. None means we won't use anything. *) let initial_reading : initial_reading option ref = ref None let get_initial_reading () : initial_reading = match !initial_reading with | None -> initial_reading_capture | Some initial_reading -> initial_reading let use_initial_reading (new_initial_reading : initial_reading) : unit = initial_reading := Some new_initial_reading let get_initial_stats () = get_initial_reading () |> fst (** A small helper: returns either (initial_reading, f initial_reading) if (1) someone has previously called [use_initial_reading] and provided an Ok one, (2) the [current_cgroup] parameter is Ok, (3) the [current_cgroup] has the same cgroup name as the initial one. Otherwise, it returns ({0...}, default). *) let initial_value_map current_cgroup ~f ~default = let open CGroup in match (!initial_reading, current_cgroup) with | (Some (_stats, Ok initial_cgroup), Ok current_cgroup) when String.equal initial_cgroup.cgroup_name current_cgroup.cgroup_name -> (initial_cgroup, f initial_cgroup) | _ -> ( { CGroup.total = 0; memory_current = 0; memory_swap_current = 0; anon = 0; shmem = 0; file = 0; cgroup_name = ""; }, default ) type step_summary = { time: float; log_label_and_suffix: string; step_total: int; } type step_group = { name: string; (** e.g. "lazy_init" *) step_count: int ref; (** used to prefix the step-names for telemetry+logging *) log: bool; (** should it be logged to Hh_logger? *) last_printed_total: int ref; (** we only print to Hh_logger if it's markedly changed since last we printed. *) prev_step_to_show: step_summary option ref; (** in case we print, we might want to include something about the previous one, if it hasn't already been printed *) } (** We'll only bother writing to the log if the total has changed by at least this many bytes *) let threshold_for_logging = 100 * 1024 * 1024 (** to avoid flooding logs with errors *) let has_logged_error = ref SSet.empty (** prints bytes in gb *) let pretty_num i = Printf.sprintf "%0.2fGiB" (float i /. 1073741824.0) (** Records to Hh_logger if it differs from the previous total, and update total *) let log_cgroup_total cgroup ~step_group ~step ~suffix ~total_hwm = let (initial, initial_msg) = initial_value_map cgroup ~default:"" ~f:(fun i -> Printf.sprintf " (relative to initial %s)" (pretty_num i.CGroup.total)) in match cgroup with | Error _ -> () | Ok cgroup -> let log_label_and_suffix = Printf.sprintf "%s/%s%s" step_group.name step suffix in let prev = !(step_group.prev_step_to_show) in let current = { time = Unix.gettimeofday (); log_label_and_suffix; step_total = cgroup.CGroup.total; } in if abs (cgroup.CGroup.total - !(step_group.last_printed_total)) < threshold_for_logging then (* We didn't print this current step. But if the *next* step proves to have a big increase in memory, then when we print the next step, we'll also print this one. *) step_group.prev_step_to_show := Some current else begin (* This step is being shown right now. So if the next step proves to have a big increase in memory, we won't need to show this one again! *) step_group.prev_step_to_show := None; step_group.last_printed_total := cgroup.CGroup.total; let hwm = if cgroup.CGroup.total >= total_hwm then "" else Printf.sprintf " (hwm %s)" (pretty_num (total_hwm - initial.CGroup.total)) in let prev = match prev with | None -> "" | Some prev -> Printf.sprintf "\n >%s %s [@%s] previous measurement" (Utils.timestring prev.time) (pretty_num (prev.step_total - initial.CGroup.total)) prev.log_label_and_suffix in Hh_logger.log "Cgroup: %s%s [@%s]%s%s" (pretty_num (cgroup.CGroup.total - initial.CGroup.total)) hwm current.log_label_and_suffix initial_msg prev end (** Given a float array [secs_at_gb] where secs_at_gb[0] says how many secs were spent at cgroup memory 0gb, secs_at_gb[1] says how many secs were spent at cgroup memory 1gb, and so on, produces an SMap where keys are some arbitrary thresholds "secs_above_20gb" and values are (int) number of seconds spent at that memory or higher. We pick just a few arbitrary thresholds that we think are useful for telemetry, and their sole purpose is telemetry. *) let secs_above_gb_summary (secs_at_gb : float array) : int SMap.t = if Array.is_empty secs_at_gb then SMap.empty else List.init 15 ~f:(fun i -> i * 5) (* 0gb, 5gb, ..., 70gb) *) |> List.filter_map ~f:(fun threshold -> let title = Printf.sprintf "secs_above_%02dgb" threshold in let secs = Array.foldi secs_at_gb ~init:0. ~f:(fun i acc s -> acc +. if i < threshold then 0. else s) in let secs = Float.round secs |> int_of_float in Option.some_if (secs > 0) (title, secs)) |> SMap.of_list (** Records to HackEventLogger *) let log_telemetry ~step_group ~step ~start_time ~total_hwm ~start_cgroup ~cgroup ~telemetry_ref ~secs_at_total_gb = let open CGroup in let (initial, initial_opt) = initial_value_map cgroup ~default:false ~f:(fun _ -> true) in match (start_cgroup, cgroup) with | (Some (Error e), _) | (_, Error e) -> telemetry_ref := Telemetry.create () |> Telemetry.error ~e |> Option.some; if SSet.mem e !has_logged_error then () else begin has_logged_error := SSet.add e !has_logged_error; HackEventLogger.CGroup.error e end | (Some (Ok start_cgroup), Ok cgroup) -> let total_hwm = max (max start_cgroup.total cgroup.total) total_hwm in let secs_above_total_gb_summary = secs_above_gb_summary secs_at_total_gb in let sysinfo = Sys_utils.sysinfo () in telemetry_ref := Telemetry.create () |> SMap.fold (fun key value -> Telemetry.int_ ~key ~value) secs_above_total_gb_summary |> Telemetry.int_ ~key:"start_bytes" ~value:(start_cgroup.total - initial.total) |> Telemetry.int_ ~key:"end_bytes" ~value:(cgroup.total - initial.total) |> Telemetry.int_ ~key:"hwm_bytes" ~value:(total_hwm - initial.total) |> Telemetry.int_opt ~key:"relative_to_initial" ~value:(Option.some_if initial_opt initial.total) |> Telemetry.int_opt ~key:"sysinfo_freeram" ~value:(Option.map sysinfo ~f:(fun si -> si.Sys_utils.freeram)) |> Telemetry.int_opt ~key:"sysinfo_freeswap" ~value:(Option.map sysinfo ~f:(fun si -> si.Sys_utils.freeswap)) |> Telemetry.int_opt ~key:"sysinfo_totalswap" ~value:(Option.map sysinfo ~f:(fun si -> si.Sys_utils.totalswap)) |> Option.some; HackEventLogger.CGroup.step ~cgroup:cgroup.cgroup_name ~step_group:step_group.name ~step ~start_time ~total_relative_to:(Option.some_if initial_opt initial.total) ~anon_relative_to:(Option.some_if initial_opt initial.anon) ~shmem_relative_to:(Option.some_if initial_opt initial.shmem) ~file_relative_to:(Option.some_if initial_opt initial.file) ~total_start:(Some (start_cgroup.total - initial.total)) ~anon_start:(Some (start_cgroup.anon - initial.anon)) ~shmem_start:(Some (start_cgroup.shmem - initial.shmem)) ~file_start:(Some (start_cgroup.file - initial.file)) ~total_hwm:(total_hwm - initial.total) ~total:(cgroup.total - initial.total) ~anon:(cgroup.anon - initial.anon) ~shmem:(cgroup.shmem - initial.shmem) ~file:(cgroup.file - initial.file) ~secs_at_total_gb:(Some (secs_at_total_gb |> Array.to_list)) ~secs_above_total_gb_summary | (None, Ok cgroup) -> telemetry_ref := Telemetry.create () |> Telemetry.int_ ~key:"end" ~value:cgroup.total |> Option.some; HackEventLogger.CGroup.step ~cgroup:cgroup.cgroup_name ~step_group:step_group.name ~step ~start_time:None ~total_relative_to:(Option.some_if initial_opt initial.total) ~anon_relative_to:(Option.some_if initial_opt initial.anon) ~shmem_relative_to:(Option.some_if initial_opt initial.shmem) ~file_relative_to:(Option.some_if initial_opt initial.file) ~total_start:None ~anon_start:None ~shmem_start:None ~file_start:None ~total_hwm:(cgroup.total - initial.total) ~total:(cgroup.total - initial.total) ~anon:(cgroup.anon - initial.anon) ~shmem:(cgroup.shmem - initial.shmem) ~file:(cgroup.file - initial.file) ~secs_at_total_gb:None ~secs_above_total_gb_summary:SMap.empty let step_group name ~log f = let log = log && Sys_utils.enable_telemetry () in let profiling = { name; log; step_count = ref 0; last_printed_total = ref 0; prev_step_to_show = ref None; } in f profiling let step step_group ?(telemetry_ref = ref None) name = if not step_group.log then () else begin step_group.step_count := !(step_group.step_count) + 1; let step = Printf.sprintf "%02d_%s" !(step_group.step_count) name in let cgroup = CGroup.get_stats () in log_cgroup_total cgroup ~step_group ~step ~suffix:"" ~total_hwm:0; log_telemetry ~step_group ~step ~start_time:None ~total_hwm:0 ~start_cgroup:None ~cgroup ~telemetry_ref ~secs_at_total_gb:[||] end let step_start_end step_group ?(telemetry_ref = ref None) name f = if not step_group.log then f () else begin step_group.step_count := !(step_group.step_count) + 1; let step = Printf.sprintf "%02d_%s" !(step_group.step_count) name in let start_time = Unix.gettimeofday () in let start_cgroup = CGroup.get_stats () in log_cgroup_total start_cgroup ~step_group ~step ~suffix:" start" ~total_hwm:0; let (initial, ()) = initial_value_map start_cgroup ~default:() ~f:(fun _ -> ()) in Result.iter start_cgroup ~f:(fun { CGroup.cgroup_name; _ } -> let path1 = "/sys/fs/cgroup/" ^ cgroup_name ^ "/memory.current" in let path2 = "/sys/fs/cgroup/" ^ cgroup_name ^ "/memory.swap.current" in cgroup_watcher_start path1 path2 ~subtract_kb_for_array:(initial.CGroup.total / 1024)); Utils.try_finally ~f ~finally:(fun () -> try let cgroup = CGroup.get_stats () in let (hwm_kb, _num_readings, secs_at_total_gb) = cgroup_watcher_get () in let total_hwm = hwm_kb * 1024 in log_cgroup_total cgroup ~step_group ~step ~suffix:" end" ~total_hwm; log_telemetry ~step_group ~step ~start_time:(Some start_time) ~total_hwm ~start_cgroup:(Some start_cgroup) ~cgroup ~telemetry_ref ~secs_at_total_gb with | exn -> let e = Exception.wrap exn in telemetry_ref := Telemetry.create () |> Telemetry.exception_ ~e |> Option.some; Hh_logger.log "cgroup - failed to log. %s" (Exception.to_string e)) end
OCaml Interface
hhvm/hphp/hack/src/utils/cgroup/cgroupProfiler.mli
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (* The CgroupProfiler module is to help us keep track of how cgroup memory usage evolves during the various steps of work done by hh_server. It helps to group steps into groups. An example step-group is "init", which is made up of steps "update naming table" then "update depgraph". *) (** Represents a step-group that's underway; created by [step_group] *) type step_group (** `step_group "foo" ~log:true callback` indicates that group "foo" will span all the steps created within callback. If [log] is true then each step will be logged to Hh_logger and HackEventLogger. *) val step_group : string -> log:bool -> (step_group -> 'a) -> 'a (** This records cgroup stats at a point in time *) val step : step_group -> ?telemetry_ref:Telemetry.t option ref -> string -> unit (** `step_start_end phase "bar" callback` records cgroup stats immediately, then executes the callback, then records cgroup a second time. *) val step_start_end : step_group -> ?telemetry_ref:Telemetry.t option ref -> string -> (unit -> 'a) -> 'a (** This captures the cgroup name, and what initial values it had upon process startup. It's so that subsequent measurements of cgroup memory can be recorded relative to this value. *) type initial_reading (** Upon module load, this module takes an [initial_reading] and stores it in mutable state. This function lets us retrieve it. Except: if someone has subsequently called [use_initial_reading], then the captured value will be irretrievable, and we'll return the [use_initial_reading] instead. *) val get_initial_reading : unit -> initial_reading (** This module doesn't actually respect the [initial_reading] it took upon program startup; it only uses a reading that was passed to it by this function. Why? imagine if after some heavy allocation, serverMain used Daemon.spawn to spawn a child process; we'd usually prefer that child process to record numbers relative to the intial_reading that was captured by the initial process upon its initial startup, not the one captured by the child upon child process startup. *) val use_initial_reading : initial_reading -> unit (** A helper to fetch just the HackEventLogger-related parts of the initial reading *) val get_initial_stats : unit -> HackEventLogger.ProfileTypeCheck.stats
C
hhvm/hphp/hack/src/utils/cgroup/cgroupWatcher.c
// (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. #define CAML_NAME_SPACE #include <caml/mlvalues.h> #include <caml/memory.h> #include <caml/alloc.h> #include <stdio.h> #include <string.h> #include <pthread.h> #include <time.h> #include <stdint.h> #include <inttypes.h> // Highest expected peak cgroup memory. We only write to scuba as many // entries as there actually are, so it's fine for this to be large. // If it were too small then we'd "clip", i.e, anything bigger than // GB_MAX would be ascribed to GB_MAX. #define GB_MAX 1024 // We'll have a background thread which reads cgroup this frequently. // I don't know if there'll be adverse perf impact of having it more frequent. // If it's too infrequent, then we'll fail to capture short-lived peaks. #define INTERVAL_MS 20 // This lock protects all the following static data pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; // Accumulates how many seconds have been spent at each total cgroup size. // This is reset by [cgroup_watcher_start], and read by [cgroup_watcher_get]. // The final entry in the array accumulates time spent at GB_MAX or higher. static double seconds_at_gb[GB_MAX]; // Records the high-water-mark static int hwm_kb; // How many cgroup readings have we taken since the last reset static int num_readings; // These are the cgroup memory.current and memory.swap.current file we'll read // for the current value. We'll add them together. The paths // include the leading "/sys/fs/group/" and the trailing "/memory.current" static char *path1 = NULL; static char *path2 = NULL; // The seconds_at_gb array will be relative to this, e.g. a reading of Xgb // would increment the tally kept at seconds_at_gb[X-subtract_kb_for_array/1GiB]. static int subtract_kb_for_array; // 1 or 0 for whether the thread has been launched static int thread_is_running = 0; // Reads the current unsigned long long from the contents of 'path1+path2', and returns it /1024. // If it fails to open the file, -1. If it fails to parse the contents, -2. static int get_mem_kb(void) { FILE *file1 = fopen(path1, "r"); FILE *file2 = fopen(path2, "r"); if (file1 == NULL || file2 == NULL) { return -1; } unsigned long long mem1, mem2; int i1 = fscanf(file1, "%llu", &mem1); int i2 = fscanf(file2, "%llu", &mem2); fclose(file1); fclose(file2); return (i1 == 1 && i2 == 1) ? (mem1 + mem2) / 1024 : -2; } #define UNUSED(x) ((void)(x)) // This is the background thread code. Every INTERVAL_MS, it reads the cgroup // memory.current from [path], and updates the counters [hwm_kb, seconds_at_gb, num_readings]. // If there are any errors, then the counters simply won't be updated. static void *threadfunc(void *arg) { UNUSED(arg); struct timespec tprev, t; clock_gettime(CLOCK_MONOTONIC_RAW, &tprev); while (1) { if (pthread_mutex_lock(&lock) == 0) { clock_gettime(CLOCK_MONOTONIC_RAW, &t); const double seconds = (double)( t.tv_sec - tprev.tv_sec ) + (((double)(t.tv_nsec - tprev.tv_nsec)) / 1000000000.0); tprev = t; int kb = get_mem_kb(); int kb0 = kb; if (kb >= 0) { hwm_kb = kb > hwm_kb ? kb : hwm_kb; kb -= subtract_kb_for_array; if (kb < 0) { // Underflow, because the value dropped below what it was initially. // We'll "clip" it, tallying it under seconds_at_gb[0] kb = 0; } int gb = kb / 1024 / 1024; if (gb >= GB_MAX) { // Overflow, because the value was higher than we ever dreamt. // We'll "clip" it, tallying it under seconds_at_gb[GB_MAX-1] gb = GB_MAX-1; } seconds_at_gb[gb] += seconds; num_readings += 1; } pthread_mutex_unlock(&lock); } nanosleep((const struct timespec[]){{0, INTERVAL_MS * 1000 * 1000}}, NULL); } return NULL; // to silence -Werror=return-type "no return statement in function returning non-void" } // This will (1) reset the counters and update [path1],[path2] so threadfunc // will pick up the new value next tick, (2) starts the thread if it's not already running. // Any failures aren't reported here; they're manifest in [cgroup_watcher_get] CAMLprim value cgroup_watcher_start(value path1_, value path2_, value subtract_kb_for_array_) { CAMLparam3(path1_, path2_, subtract_kb_for_array_); const char *cpath1 = String_val(path1_); const char *cpath2 = String_val(path2_); int csubtract_kb_for_array = Int_val(subtract_kb_for_array_); int rc; if (pthread_mutex_lock(&lock) == 0) { if (path1 != NULL) free(path1); path1 = malloc(strlen(cpath1) + 1); strcpy(path1, cpath1); if (path2 != NULL) free(path2); path2 = malloc(strlen(cpath2) + 1); strcpy(path2, cpath2); subtract_kb_for_array = csubtract_kb_for_array; hwm_kb = 0; num_readings = 0; for (int i=0; i<GB_MAX; i++) { seconds_at_gb[i] = 0.0; } if (thread_is_running == 0) { pthread_t thread; pthread_create(&thread, NULL, threadfunc, NULL); thread_is_running = 1; } pthread_mutex_unlock(&lock); } CAMLreturn(Val_unit); } // Fetch the current total so far of hwm/seconds. // Returns (hwm_kb, num_readings, seconds_at_gb[||]). // If there had been failures along the way, e.g. the path was invalid // or cgroups don't exist, then it will return (0,0,[||]). CAMLprim value cgroup_watcher_get(void) { CAMLparam0(); CAMLlocal2(list, result); // We'll copy values out of the mutex, before doing any ocaml allocation double ss[GB_MAX]; int hwm=0; int readings=0; int max=0; if (pthread_mutex_lock(&lock) == 0) { memcpy(ss, seconds_at_gb, GB_MAX*sizeof(ss[0])); hwm = hwm_kb; readings = num_readings; pthread_mutex_unlock(&lock); for (int i=0; i<GB_MAX; i++) { max = ss[i] > 0.0 ? i+1 : max; } } list = caml_alloc(max, Double_array_tag); for (int i=0; i<max; i++) { Store_double_field(list, i, ss[i]); } result = caml_alloc_tuple(3); Store_field(result, 0, Val_int(hwm)); Store_field(result, 1, Val_int(readings)); Store_field(result, 2, list); CAMLreturn(result); }
hhvm/hphp/hack/src/utils/cgroup/dune
(library (name cgroupprofiler) (wrapped false) (modules CgroupProfiler) (libraries cgroup core_kernel heap_shared_mem logging utils_core) (foreign_stubs (language c) (names cgroupWatcher)) (preprocess (pps lwt_ppx))) (library (name cgroup) (wrapped false) (modules CGroup) (libraries core_kernel core_kernel.caml_unix procfs))
hhvm/hphp/hack/src/utils/ci_util/dune
(* -*- tuareg -*- *) let library_entry name suffix = Printf.sprintf "(library (name %s) (wrapped false) (modules) (libraries %s_%s))" name name suffix let fb_entry name = library_entry name "fb" let stubs_entry name = library_entry name "stubs" let entry is_fb name = if is_fb then fb_entry name else stubs_entry name let () = (* test presence of fb subfolder *) let current_dir = Sys.getcwd () in (* we are in src/utils/ci_util, locate src/facebook *) let src_dir = Filename.dirname @@ Filename.dirname current_dir in let fb_dir = Filename.concat src_dir "facebook" in (* locate src/facebook/dune *) let fb_dune = Filename.concat fb_dir "dune" in let is_fb = Sys.file_exists fb_dune in let lib_entry = entry is_fb "ci_util" in Jbuild_plugin.V1.send lib_entry
hhvm/hphp/hack/src/utils/clowder_paste/dune
(* -*- tuareg -*- *) let library_entry name suffix = Printf.sprintf "(library (name %s) (wrapped false) (modules) (libraries %s_%s))" name name suffix let fb_entry name = library_entry name "fb" let stubs_entry name = library_entry name "stubs" let entry is_fb name = if is_fb then fb_entry name else stubs_entry name let () = (* test presence of fb subfolder *) let current_dir = Sys.getcwd () in (* we are in src/utils/xxx, locate src/facebook *) let src_dir = Filename.dirname @@ Filename.dirname current_dir in let fb_dir = Filename.concat src_dir "facebook" in (* locate src/facebook/dune *) let fb_dune = Filename.concat fb_dir "dune" in let is_fb = Sys.file_exists fb_dune in let lib_name = entry is_fb "clowder_paste" in Jbuild_plugin.V1.send lib_name
OCaml
hhvm/hphp/hack/src/utils/collections/cSet.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) include Set.Make (Char)
hhvm/hphp/hack/src/utils/collections/dune
(library (name collections) (wrapped false) (libraries common core_kernel yojson) (preprocess (pps ppx_hash)))
OCaml
hhvm/hphp/hack/src/utils/collections/hashSet.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 Core type 'a t = ('a, unit) Hashtbl.t let create () = Hashtbl.Poly.create () let clear = Hashtbl.clear let copy = Hashtbl.copy let add set x = Hashtbl.set set ~key:x ~data:() let mem = Hashtbl.mem let remove = Hashtbl.remove let iter = Hashtbl.iter_keys let union set ~other = iter other ~f:(add set) let fold set ~init ~f = Hashtbl.fold set ~init ~f:(fun ~key ~data:_ acc -> f key acc) let filter set ~f = let to_remove = fold set ~init:[] ~f:(fun elt acc -> if not (f elt) then elt :: acc else acc) in List.iter to_remove ~f:(remove set) let intersect set ~other = filter ~f:(mem other) set let length = Hashtbl.length let is_empty = Hashtbl.is_empty let to_list = Hashtbl.keys let of_list list = let set = Hashtbl.Poly.create ~size:(List.length list) () in List.iter list ~f:(add set); set
OCaml Interface
hhvm/hphp/hack/src/utils/collections/hashSet.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. * *) (* HashSet is just a HashTable where the keys are actually the values, and we * ignore the actual values inside the HashTable. *) type 'a t val create : unit -> 'a t val clear : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> 'a -> unit val union : 'a t -> other:'a t -> unit val mem : 'a t -> 'a -> bool val remove : 'a t -> 'a -> unit val filter : 'a t -> f:('a -> bool) -> unit val intersect : 'a t -> other:'a t -> unit val iter : 'a t -> f:('a -> unit) -> unit val fold : 'a t -> init:'b -> f:('a -> 'b -> 'b) -> 'b val length : 'a t -> int val is_empty : 'a t -> bool val to_list : 'a t -> 'a list val of_list : 'a list -> 'a t
OCaml
hhvm/hphp/hack/src/utils/collections/i64Map.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) include WrappedMap.Make (Int64Key) let pp : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit = fun pp_data -> make_pp (fun fmt s -> Format.fprintf fmt "%S" (Int64.to_string s)) pp_data let show pp_data x = Format.asprintf "%a" (pp pp_data) x
OCaml
hhvm/hphp/hack/src/utils/collections/i64Set.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) include Set.Make (Int64)
OCaml
hhvm/hphp/hack/src/utils/collections/iMap.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) include WrappedMap.Make (IntKey) let pp : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit = (fun pp_data -> make_pp Format.pp_print_int pp_data) let show pp_data x = Format.asprintf "%a" (pp pp_data) x
OCaml
hhvm/hphp/hack/src/utils/collections/immQueue.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. * *) type 'a t = { incoming: 'a list; outgoing: 'a list; length: int; } exception Empty let empty = { incoming = []; outgoing = []; length = 0 } let length t = t.length let is_empty t = length t = 0 let push t x = { t with incoming = x :: t.incoming; length = t.length + 1 } let prepare_for_read t = match t.outgoing with | [] -> { t with incoming = []; outgoing = List.rev t.incoming } | _ -> t let pop t = let t = prepare_for_read t in match t.outgoing with | [] -> (None, t) | hd :: tl -> (Some hd, { t with outgoing = tl; length = t.length - 1 }) let peek t = let t = prepare_for_read t in match t.outgoing with | [] -> (None, t) | hd :: _ -> (Some hd, t) let pop_unsafe t = match pop t with | (Some x, t) -> (x, t) | (None, _) -> raise Empty let exists t ~f = List.exists f t.outgoing || List.exists f t.incoming let iter t ~f = List.iter f t.outgoing; List.iter f (List.rev t.incoming) let from_list x = { incoming = []; outgoing = x; length = List.length x } let to_list x = x.outgoing @ List.rev x.incoming let concat t = { incoming = []; outgoing = List.map to_list t |> List.concat; length = List.map (fun u -> u.length) t |> List.fold_left ( + ) 0; }
OCaml Interface
hhvm/hphp/hack/src/utils/collections/immQueue.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. * *) (* * Immutable queue implementation. Modeled loosely after the mutable stdlib * Queue. push, pop, etc. are amortized O(1). *) type 'a t exception Empty val empty : 'a t val push : 'a t -> 'a -> 'a t val pop : 'a t -> 'a option * 'a t val peek : 'a t -> 'a option * 'a t (* Raises Empty if the queue is empty *) val pop_unsafe : 'a t -> 'a * 'a t val is_empty : 'a t -> bool val length : 'a t -> int val exists : 'a t -> f:('a -> bool) -> bool val iter : 'a t -> f:('a -> unit) -> unit (* from_list: the head of the list is the first one to be popped *) val from_list : 'a list -> 'a t (* to_list: the head of the list is the first one to be popped *) val to_list : 'a t -> 'a list val concat : 'a t list -> 'a t
OCaml
hhvm/hphp/hack/src/utils/collections/int64Key.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type t = int64 let compare = Int64.compare
OCaml
hhvm/hphp/hack/src/utils/collections/intKey.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type t = int let compare = Int.compare
OCaml
hhvm/hphp/hack/src/utils/collections/iSet.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) include Set.Make (IntKey) let pp fmt iset = Format.fprintf fmt "@[<2>{"; let elements = elements iset in (match elements with | [] -> () | _ -> Format.fprintf fmt " "); ignore (List.fold_left (fun sep s -> if sep then Format.fprintf fmt ";@ "; Format.pp_print_int fmt s; true) false elements); (match elements with | [] -> () | _ -> Format.fprintf fmt " "); Format.fprintf fmt "@,}@]" let show iset = Format.asprintf "%a" pp iset let to_string = show
OCaml
hhvm/hphp/hack/src/utils/collections/lazy_string_table.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 Core open Option.Monad_infix (** This is made of sequence [seq] and a hash table [tbl]. Initially, the hash table is empty while the sequence is not. As we traverse the sequence to search for keys, we add them in the hash table for future lookups. *) type 'a t = { tbl: ('a * bool) String.Table.t; mutable get_single_seq: (string -> 'a Sequence.t) option; mutable seq: (string * 'a) Sequence.t; is_canonical: 'a -> bool; merge: earlier:'a -> later:'a -> 'a; } let make ~is_canonical ~merge ?get_single_seq seq = let tbl = String.Table.create () in { tbl; get_single_seq; seq; is_canonical; merge } type 'a advance_result = | Complete (** The cache's [seq] has been exhausted, and its [tbl] now contains the complete mapping of all elements. *) | Skipped (** The cache's [seq] emitted some non-canonical element, which may or may not have replaced a previously emitted element stored in the [tbl]. *) | Yield of string * 'a (** The cache's [seq] emitted this canonical element (along with its ID). This element may be immediately used without traversing the rest of the sequence (since canonical elements cannot be replaced or updated as we traverse the rest of the sequence). *) (** Fetch the next value from the cache's [seq]. Update its [tbl] by storing the new value, ignoring the new value, or merging the new value with an existing value as necessary. *) let advance t = match Sequence.next t.seq with | None -> t.get_single_seq <- None; Complete | Some ((id, v), rest) -> t.seq <- rest; let (extant_value, extant_value_is_canonical) = match Hashtbl.find t.tbl id with | None -> (None, false) | Some (v, canonical) -> (Some v, canonical) in if extant_value_is_canonical then Skipped else let replace_with v = let canonical = t.is_canonical v in Hashtbl.set t.tbl ~key:id ~data:(v, canonical); if canonical then Yield (id, v) else Skipped in (match extant_value with | None -> replace_with v | Some extant_value -> let v = t.merge ~earlier:extant_value ~later:v in if phys_equal v extant_value then Skipped else replace_with v) (** Advance the sequence until we have the final version of that element*) let rec get_from_single_seq t seq result = match result with | Some (v, true) -> Some v | _ -> (match Sequence.next seq with | None -> Option.map result ~f:fst | Some (v, rest) -> let result = match result with | None -> (v, t.is_canonical v) | Some ((extant_value, _) as extant_result) -> let v = t.merge ~earlier:extant_value ~later:v in if phys_equal v extant_value then extant_result else (v, t.is_canonical v) in get_from_single_seq t rest (Some result)) let get t id = let rec search_in_seq () = match advance t with | Complete -> (* We've traversed the entire seq, so whatever element we have cached (canonical or not) is the correct value. *) Hashtbl.find t.tbl id >>| fst | Yield (id', v) when String.equal id' id -> Some v | Skipped | Yield _ -> search_in_seq () in match Hashtbl.find t.tbl id with | Some (v, true) -> Some v | None | Some (_, false) -> (match t.get_single_seq with | None -> search_in_seq () | Some get_sub_seq -> let result = get_from_single_seq t (get_sub_seq id) None in Option.iter result ~f:(fun v -> Hashtbl.set t.tbl ~key:id ~data:(v, true)); result) let mem t id = let rec go () = if Hashtbl.mem t.tbl id then true else match advance t with | Complete -> false | Yield (id', _) when String.equal id' id -> true | Skipped | Yield _ -> go () in if Hashtbl.mem t.tbl id then true else match t.get_single_seq with | None -> go () | Some f -> let result = get_from_single_seq t (f id) None in Option.iter result ~f:(fun v -> Hashtbl.set t.tbl ~key:id ~data:(v, true)); Option.is_some result let rec to_list t = match advance t with | Skipped | Yield _ -> to_list t | Complete -> Hashtbl.fold t.tbl ~init:[] ~f:(fun ~key ~data acc -> (key, fst data) :: acc)
OCaml Interface
hhvm/hphp/hack/src/utils/collections/lazy_string_table.mli
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Core (** [Lazy_string_table.t] provides a memoization cache for any [(string * 'a) Sequence.t] where: + It is desirable to look up elements in the sequence by their [string] key + Conflicts between multiple elements with the same key can be resolved by a [merge] function The cache will advance the provided sequence only as needed, and the user-provided [is_canonical] function helps to enable this (see {!make} for more details). The cache is guaranteed to traverse the input sequence only once (so it will behave correctly if the input sequence depends on mutable state). Originally written for caches of class members, where we want to lazily parse ancestor classes only as necessary, and our implementation of [merge] provides the logic for member overriding. *) type 'a t (** Create a new [Lazy_string_table.t] memoizing the given sequence. A good implementation of [merge] is necessary for correctness, since [merge] is used when a key-value pair emitted later in the sequence has the same key as a pair emitted earlier in the sequence. [merge] is provided with the value emitted earlier in the sequence (or, potentially, the output of a prior invocation of [merge]) and the value emitted later in the sequence. It may return one or the other, or create a new value to be stored instead of either. A good implementation of [is_canonical] is not necessary for correctness, but it is necessary for performance. The contract of [is_canonical] is as follows: [is_canonical v] must return [true] only when [merge v u] would return [v] for all possible values of [u] that could be emitted later in the sequence. Canonicity is what allows the cache to return results from {!get} and {!mem} without traversing the entire sequence (i.e., the trivial implementation [fun _ -> false] for [is_canonical] is always correct, but will always force the cache to traverse the entire sequence on the first lookup). A [get_single_seq] function should be supplied if there is a more efficient method to answer a single get/mem query. This will be used up until to_list is called. *) val make : is_canonical:('a -> bool) -> merge:(earlier:'a -> later:'a -> 'a) -> ?get_single_seq:(string -> 'a Sequence.t) -> (string * 'a) Sequence.t -> 'a t (** Return the value associated with the given key. If the value is canonical and was already emitted by the input sequence, or if the input sequence has been exhausted, this function is guaranteed to complete in constant time. Otherwise, its worst-case runtime is proportional to the length of the input sequence (provided that [is_canonical] and [merge] complete in constant time, and ignoring any time required to compute elements of the sequence). Guaranteed not to advance the input sequence if the sequence has previously emitted a canonical value for the given key. *) val get : 'a t -> string -> 'a option (** Return [true] if a value associated with the given key exists. If a value associated with this key was already emitted by the input sequence, or if the input sequence has been exhausted, this function is guaranteed to complete in constant time. Otherwise, its worst-case runtime is proportional to the length of the input sequence (provided that [is_canonical] and [merge] complete in constant time, and ignoring any time required to compute elements of the sequence). Guaranteed not to advance the input sequence if the sequence has previously emitted any value for the given key. *) val mem : 'a t -> string -> bool (** Eagerly exhaust the input sequence, then return all values, in undefined order. *) val to_list : 'a t -> (string * 'a) list
OCaml
hhvm/hphp/hack/src/utils/collections/lowerStringKey.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 t = string let compare (x : t) (y : t) = String.compare (String.lowercase_ascii x) (String.lowercase_ascii y)
OCaml
hhvm/hphp/hack/src/utils/collections/lSMap.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) include WrappedMap.Make (LowerStringKey) let pp : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit = (fun pp_data -> make_pp Format.pp_print_string pp_data)
OCaml
hhvm/hphp/hack/src/utils/collections/priorityQueue.ml
(* * Copyright (c) 2017, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module Make (Ord : Set.OrderedType) = struct type elt = Ord.t type t = { mutable __queue: elt option array; mutable size: int; } let rec make_empty n = { __queue = Array.make n None; size = 0 } and is_empty t = t.size = 0 and pop t = if t.size = 0 then failwith "Popping from an empty priority queue"; let v = t.__queue.(0) in t.size <- t.size - 1; if t.size <> 0 then ( let last = t.__queue.(t.size) in t.__queue.(t.size) <- None; __bubble_down t.__queue t.size last 0 ); match v with | None -> failwith "Attempting to return a null value" | Some v -> v and push t element = if Array.length t.__queue = t.size then ( let new_queue = Array.make ((Array.length t.__queue * 2) + 1) None in Array.blit t.__queue 0 new_queue 0 (Array.length t.__queue); t.__queue <- new_queue ); t.__queue.(t.size) <- Some element; __bubble_up t.__queue t.size; t.size <- t.size + 1; () and __swap arr i j = let tmp = arr.(i) in arr.(i) <- arr.(j); arr.(j) <- tmp and __bubble_up arr index = let pindex = (index - 1) / 2 in match (arr.(index), arr.(pindex)) with | (None, _) | (_, None) -> failwith "Unexpected null index found when calling __bubble_up" | (Some e, Some p) -> if Ord.compare e p < 0 then ( __swap arr index pindex; __bubble_up arr pindex ) and __bubble_down arr size value index = let right_child_index = (index * 2) + 2 in let left_child_index = right_child_index - 1 in if right_child_index < size then match (arr.(right_child_index), arr.(left_child_index), value) with | (None, _, _) | (_, None, _) | (_, _, None) -> failwith "Unexpected null index found when calling __bubble_down" | (Some r, Some l, Some v) -> let (smaller_child, smaller_child_index) = if Ord.compare r l < 0 then (r, right_child_index) else (l, left_child_index) in if Ord.compare v smaller_child <= 0 then arr.(index) <- value else ( arr.(index) <- arr.(smaller_child_index); __bubble_down arr size value smaller_child_index ) else if left_child_index < size then match (arr.(left_child_index), value) with | (None, _) | (_, None) -> failwith "Unexpected null index found when calling __bubble_down" | (Some l, Some v) -> if Ord.compare v l <= 0 then arr.(index) <- value else ( arr.(index) <- arr.(left_child_index); arr.(left_child_index) <- value ) else arr.(index) <- value end
OCaml
hhvm/hphp/hack/src/utils/collections/reordered_argument_collections.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. * *) module type Map_S = Reordered_argument_collections_sig.Map_S module Reordered_argument_map (S : WrappedMap.S) : Map_S with type key = S.key with type 'a t = 'a S.t = struct include S let add m ~key ~data = add key data m let filter m ~f = filter f m let filter_map m ~f = filter_map f m let fold m ~init ~f = fold f m init let find_opt m k = find_opt k m let find m k = find k m let iter m ~f = iter f m let map m ~f = map f m let mapi m ~f = mapi f m let mem m v = mem v m let remove m v = remove v m let exists m ~f = exists f m let merge m1 m2 ~f = merge f m1 m2 let partition m ~f = partition f m end module type Set_S = Reordered_argument_collections_sig.Set_S module Reordered_argument_set (S : Set.S) : Set_S with type elt = S.elt with type t = S.t = struct include S let add s v = add v s let filter s ~f = filter f s let fold s ~init ~f = fold f s init let iter s ~f = iter f s let mem s v = mem v s let remove s v = remove v s let exists s ~f = exists f s let of_list l = List.fold_left add empty l let make_pp pp fmt x = Format.fprintf fmt "@[<hv 2>{"; let elts = elements x in (match elts with | [] -> () | _ -> Format.fprintf fmt " "); ignore (List.fold_left (fun sep elt -> if sep then Format.fprintf fmt ";@ "; let () = pp fmt elt in true) false elts); (match elts with | [] -> () | _ -> Format.fprintf fmt " "); Format.fprintf fmt "}@]" (** Find an element that satisfies some boolean predicate. No other guarantees are given (decidability, ordering, ...). *) let find_one_opt elts ~f = let exception FoundFirst of elt in try iter ~f:(fun elt -> if f elt then raise (FoundFirst elt)) elts; None with | FoundFirst elt -> Some elt end module type SSet_S = Reordered_argument_collections_sig.SSet_S module SSet = struct include Reordered_argument_set (SSet) let pp = SSet.pp let show = SSet.show end module type SMap_S = Reordered_argument_collections_sig.SMap_S module SMap = struct include Reordered_argument_map (SMap) let pp = SMap.pp let show = SMap.show end
OCaml Interface
hhvm/hphp/hack/src/utils/collections/reordered_argument_collections.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 type Map_S = Reordered_argument_collections_sig.Map_S module Reordered_argument_map (S : WrappedMap.S) : Map_S with type key = S.key with type 'a t = 'a S.t module type Set_S = Reordered_argument_collections_sig.Set_S module Reordered_argument_set (S : Set.S) : Set_S with type elt = S.elt with type t = S.t module type SSet_S = Reordered_argument_collections_sig.SSet_S module SSet : SSet_S with type elt = Reordered_argument_set(SSet).elt with type t = Reordered_argument_set(SSet).t module type SMap_S = Reordered_argument_collections_sig.SMap_S module SMap : SMap_S with type key = Reordered_argument_map(SMap).key with type 'a t = 'a Reordered_argument_map(SMap).t
OCaml
hhvm/hphp/hack/src/utils/collections/reordered_argument_collections_sig.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 type Map_S = sig include WrappedMap.S val add : 'a t -> key:key -> data:'a -> 'a t val filter : 'a t -> f:(key -> 'a -> bool) -> 'a t val filter_map : 'a t -> f:(key -> 'a -> 'b option) -> 'b t val fold : 'a t -> init:'b -> f:(key -> 'a -> 'b -> 'b) -> 'b val find_opt : 'a t -> key -> 'a option val find : 'a t -> key -> 'a val iter : 'a t -> f:(key -> 'a -> unit) -> unit val map : 'a t -> f:('a -> 'b) -> 'b t val mapi : 'a t -> f:(key -> 'a -> 'b) -> 'b t val mem : 'a t -> key -> bool val remove : 'a t -> key -> 'a t val exists : 'a t -> f:(key -> 'a -> bool) -> bool val merge : 'a t -> 'b t -> f:(key -> 'a option -> 'b option -> 'c option) -> 'c t val partition : 'a t -> f:(key -> 'a -> bool) -> 'a t * 'a t end module type Set_S = sig include Set.S val add : t -> elt -> t val filter : t -> f:(elt -> bool) -> t val fold : t -> init:'a -> f:(elt -> 'a -> 'a) -> 'a val iter : t -> f:(elt -> unit) -> unit val mem : t -> elt -> bool val remove : t -> elt -> t val exists : t -> f:(elt -> bool) -> bool val of_list : elt list -> t val make_pp : (Format.formatter -> elt -> unit) -> Format.formatter -> t -> unit (** Find an element that satisfies some boolean predicate. No other guarantees are given (decidability, ordering, ...). *) val find_one_opt : t -> f:(elt -> bool) -> elt option val find_first : (elt -> bool) -> t -> elt [@@alert deprecated "`find_first f` requires f to be monotone which is rarely the case, please consider using first_one_opt instead"] val find_first_opt : (elt -> bool) -> t -> elt option [@@alert deprecated "`find_first_opt f` requires f to be monotone which is rarely the case, please consider using first_one_opt instead"] end module type SSet_S = sig include Set_S val pp : Format.formatter -> t -> unit val show : t -> string end module type SMap_S = sig include Map_S val pp : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit val show : (Format.formatter -> 'a -> unit) -> 'a t -> string end
OCaml
hhvm/hphp/hack/src/utils/collections/sMap.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 Core include WrappedMap.Make (StringKey) let pp : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit = (fun pp_data -> make_pp (fun fmt s -> Format.fprintf fmt "%S" s) pp_data) let show pp_data x = Format.asprintf "%a" (pp pp_data) x let hash_fold_t x = make_hash_fold_t hash_fold_string x let yojson_of_t x = make_yojson_of_t (fun x -> x) x
OCaml
hhvm/hphp/hack/src/utils/collections/sSet.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) include Set.Make (StringKey) let pp_limit ?(max_elts = None) fmt sset = Format.fprintf fmt "@[<2>{"; let elements = elements sset in (match elements with | [] -> () | _ -> Format.fprintf fmt " "); let (_ : int) = List.fold_left (fun i s -> (match max_elts with | Some max_elts when i >= max_elts -> () | _ -> if i > 0 then Format.fprintf fmt ";@ "; Format.fprintf fmt "%S" s); i + 1) 0 elements in (match elements with | [] -> () | _ -> Format.fprintf fmt " "); Format.fprintf fmt "@,}@]" let pp = pp_limit ~max_elts:None let show sset = Format.asprintf "%a" pp sset let to_string = show let pp_large ?(max_elts = 5) fmt sset = let l = cardinal sset in if l <= max_elts then pp fmt sset else Format.fprintf fmt "<only showing %d of %d elems: %a>" max_elts l (pp_limit ~max_elts:(Some max_elts)) sset let show_large ?(max_elts = 5) sset = Format.asprintf "%a" (pp_large ~max_elts) sset
OCaml
hhvm/hphp/hack/src/utils/collections/stringKey.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type t = string let compare (x : t) (y : t) = String.compare x y let to_string x = x
OCaml
hhvm/hphp/hack/src/utils/collections/wrappedMap.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 Core module type S = WrappedMap_sig.S module Make (Ord : Caml.Map.OrderedType) : S with type key = Ord.t = struct include Caml.Map.Make (Ord) let union ?combine x y = let combine = match combine with | None -> (fun _ fst _ -> Some fst) | Some f -> f in union combine x y let merge_env env s1 s2 ~combine = let (env, map) = Common.List.fold_left_env env ~init:empty ~f:(fun env map (key, v2) -> let v1opt = find_opt key s1 in let (env, vopt) = combine env key v1opt (Some v2) in let map = match vopt with | None -> map | Some v -> add key v map in (env, map)) (bindings s2) in Common.List.fold_left_env env ~init:map ~f:(fun env map (key, v1) -> let v2opt = find_opt key s2 in match v2opt with | None -> let (env, vopt) = combine env key (Some v1) None in let map = match vopt with | None -> map | Some v -> add key v map in (env, map) | Some _ -> (env, map)) (bindings s1) let union_env env s1 s2 ~combine = let f env key o1 o2 = match (o1, o2) with | (None, None) -> (env, None) | (Some v, None) | (None, Some v) -> (env, Some v) | (Some v1, Some v2) -> combine env key v1 v2 in merge_env env s1 s2 ~combine:f let keys m = fold (fun k _ acc -> k :: acc) m [] let ordered_keys m = Base.List.map ~f:fst (bindings m) let values m = fold (fun _ v acc -> v :: acc) m [] let fold_env env f m init = fold (fun key v (env, acc) -> f env key v acc) m (env, init) let fold_env_ty_err_opt env f m init = fold (fun key v ((env, errs), acc) -> match f env key v acc with | ((env, Some err), acc) -> ((env, err :: errs), acc) | ((env, _), acc) -> ((env, errs), acc)) m ((env, []), init) let elements m = fold (fun k v acc -> (k, v) :: acc) m [] let map_env f env m = fold_env env (fun env key v map -> let (env, v) = f env key v in (env, add key v map)) m empty let map_env_ty_err_opt f env m ~combine_ty_errs = let ((env, errs), res) = fold_env_ty_err_opt env (fun env key v map -> let (env, v) = f env key v in (env, add key v map)) m empty in ((env, combine_ty_errs errs), res) let filter_opt m = filter_map (fun _key x -> x) m let of_list elts = List.fold ~f:(fun acc (key, value) -> add key value acc) ~init:empty elts let of_function domain f = List.fold ~f:(fun acc key -> add key (f key) acc) ~init:empty domain let add ?combine key new_value map = match combine with | None -> add key new_value map | Some combine -> begin match find_opt key map with | None -> add key new_value map | Some old_value -> add key (combine old_value new_value) map end let ident_map f map = let (map_, changed) = fold (fun key item (map_, changed) -> let item_ = f item in (add key item_ map_, changed || not (phys_equal item_ item))) map (empty, false) in if changed then map_ else map let ident_map_key ?combine f map = let (map_, changed) = fold (fun key item (map_, changed) -> let new_key = f key in ( add ?combine new_key item map_, changed || not (phys_equal new_key key) )) map (empty, false) in if changed then map_ else map let for_all2 ~f m1 m2 = let key_bool_map = merge (fun k v1opt v2opt -> Some (f k v1opt v2opt)) m1 m2 in for_all (fun _k b -> b) key_bool_map let make_pp pp_key pp_data fmt x = Format.fprintf fmt "@[<hv 2>{"; let bindings = bindings x in (match bindings with | [] -> () | _ -> Format.fprintf fmt " "); ignore (List.fold ~f:(fun sep (key, data) -> if sep then Format.fprintf fmt ";@ "; Format.fprintf fmt "@["; pp_key fmt key; Format.fprintf fmt " ->@ "; pp_data fmt data; Format.fprintf fmt "@]"; true) ~init:false bindings); (match bindings with | [] -> () | _ -> Format.fprintf fmt " "); Format.fprintf fmt "}@]" type ('a, 'b) tuple = 'a * 'b [@@deriving hash] let make_hash_fold_t (hash_fold_ord : Hash.state -> Ord.t -> Hash.state) (hash_fold_a : Hash.state -> 'a -> Hash.state) (hsv : Hash.state) (map : 'a t) = hash_fold_list (hash_fold_tuple hash_fold_ord hash_fold_a) hsv (bindings map) let make_yojson_of_t (show_ord : Ord.t -> string) (yojson_of_a : 'a -> Yojson.Safe.t) (map : 'a t) : Yojson.Safe.t = `Assoc (bindings map |> List.map ~f:(fun (key, value) -> (show_ord key, yojson_of_a value))) end
OCaml Interface
hhvm/hphp/hack/src/utils/collections/wrappedMap.mli
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module type S = WrappedMap_sig.S module Make (Ord : Map.OrderedType) : S with type key = Ord.t
OCaml
hhvm/hphp/hack/src/utils/collections/wrappedMap_sig.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 Core module type S = sig include Caml.Map.S val add : ?combine:('a -> 'a -> 'a) -> key -> 'a -> 'a t -> 'a t (** [combine] defaults to picking the first value argument. *) val union : ?combine:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t val union_env : 'a -> 'b t -> 'b t -> combine:('a -> key -> 'b -> 'b -> 'a * 'b option) -> 'a * 'b t val merge_env : 'a -> 'b t -> 'c t -> combine:('a -> key -> 'b option -> 'c option -> 'a * 'd option) -> 'a * 'd t val keys : 'a t -> key list val ordered_keys : 'a t -> key list val values : 'a t -> 'a list val fold_env : 'a -> ('a -> key -> 'b -> 'c -> 'a * 'c) -> 'b t -> 'c -> 'a * 'c val map_env : ('c -> key -> 'a -> 'c * 'b) -> 'c -> 'a t -> 'c * 'b t val map_env_ty_err_opt : ('a -> key -> 'b -> ('a * 'c option) * 'd) -> 'a -> 'b t -> combine_ty_errs:('c list -> 'e) -> ('a * 'e) * 'd t val filter_opt : 'a option t -> 'a t val of_list : (key * 'a) list -> 'a t val of_function : key list -> (key -> 'a) -> 'a t val elements : 'a t -> (key * 'a) list val ident_map : ('a -> 'a) -> 'a t -> 'a t val ident_map_key : ?combine:('a -> 'a -> 'a) -> (key -> key) -> 'a t -> 'a t val for_all2 : f:(key -> 'a option -> 'b option -> bool) -> 'a t -> 'b t -> bool val make_pp : (Format.formatter -> key -> unit) -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit val make_hash_fold_t : (Hash.state -> key -> Hash.state) -> (Hash.state -> 'a -> Hash.state) -> Hash.state -> 'a t -> Hash.state val make_yojson_of_t : (key -> string) -> ('a -> Yojson.Safe.t) -> 'a t -> Yojson.Safe.t end
OCaml
hhvm/hphp/hack/src/utils/config_file/config_file.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) include Config_file_version type t = Config_file_common.t let file_path_relative_to_repo_root = Config_file_common.file_path_relative_to_repo_root let pkgs_config_path_relative_to_repo_root = Config_file_common.pkgs_config_path_relative_to_repo_root let empty = Config_file_common.empty let print_to_stderr = Config_file_common.print_to_stderr let apply_overrides = Config_file_common.apply_overrides let parse_contents = Config_file_common.parse_contents module Getters = Config_file_common.Getters let cat_packages_file (fn : string) = if Disk.file_exists fn then ( try Sys_utils.cat fn with | exn -> let e = Exception.wrap exn in Hh_logger.exception_ ~prefix:"PACKAGES.toml deleted: " e; "" ) else "" let parse_hhconfig (fn : string) : string * t = let contents = try Sys_utils.cat fn with | exn -> let e = Exception.wrap exn in Hh_logger.exception_ ~prefix:".hhconfig deleted: " e; Exit.exit Exit_status.Hhconfig_deleted in let parsed = Config_file_common.parse_contents contents in (* Take the PACKAGES.toml in the same directory as the .hhconfig *) let package_path = Config_file_common.get_packages_absolute_path ~hhconfig_path:fn in let package_config = Some (cat_packages_file package_path) in let hash = Config_file_common.hash parsed ~config_contents:contents ~package_config in (hash, parsed) let parse_local_config = Config_file_common.parse_local_config let of_list = Config_file_common.of_list let keys = Config_file_common.keys module Utils = struct let parse_hhconfig_and_hh_conf_to_json ~(root : Path.t) ~(server_local_config_path : string) = let server_local_config = parse_local_config server_local_config_path in let hh_config = parse_local_config (Path.to_string (Path.concat root file_path_relative_to_repo_root)) in Hh_json.JSON_Object [ ("hh.conf", Config_file_common.to_json server_local_config); ("hhconfig", Config_file_common.to_json hh_config); ] end
OCaml Interface
hhvm/hphp/hack/src/utils/config_file/config_file.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 = Config_file_common.t type version_components = Config_file_version.version_components = { major: int; minor: int; build: int; } type version = Config_file_version.version = | Opaque_version of string option | Version_components of version_components val version_to_string_opt : ?pad:bool -> version -> string option val file_path_relative_to_repo_root : string val pkgs_config_path_relative_to_repo_root : string val compare_versions : version -> version -> int val parse_version : string option -> version val empty : unit -> t val print_to_stderr : t -> unit val parse_contents : string -> t (** [parse_hhconfig file_path] parses the content of [file_path] concatenated with the content of the package config. The first returned value is a hash of that concatenated content. *) val parse_hhconfig : string -> string * t val parse_local_config : string -> t (** Apply overrides using provided overrides. [log_reason] is solely used for logging, so we can write to stderr indicating where these overrides came from and what they were. *) val apply_overrides : config:t -> overrides:t -> log_reason:string option -> t val of_list : (string * string) list -> t val keys : t -> string list module Getters : Config_file_common.Getters_S module Utils : sig val parse_hhconfig_and_hh_conf_to_json : root:Path.t -> server_local_config_path:string -> Hh_json.json end
OCaml
hhvm/hphp/hack/src/utils/config_file/config_file_common.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Option.Monad_infix type t = Config_file_ffi_externs.config let file_path_relative_to_repo_root = ".hhconfig" let pkgs_config_path_relative_to_repo_root = "PACKAGES.toml" let empty = Config_file_ffi_externs.empty let is_empty = Config_file_ffi_externs.is_empty let print_to_stderr (config : t) : unit = Config_file_ffi_externs.print_to_stderr config module type Getters_S = sig val string_opt : string -> t -> string option val string_ : string -> default:string -> t -> string val int_ : string -> default:int -> t -> int val int_opt_result : string -> t -> (int, string) result option val int_opt : string -> t -> int option val float_ : string -> default:float -> t -> float val float_opt : string -> t -> float option val bool_ : string -> default:bool -> t -> bool val bool_opt : string -> t -> bool option val string_list_opt : string -> t -> string list option val string_list : string -> default:string list -> t -> string list val int_list_opt : string -> t -> int list option val bool_if_min_version : string -> default:bool -> current_version:Config_file_version.version -> t -> bool end module Getters : Getters_S = struct let ok_or_invalid_arg = function | Ok x -> x | Error e -> invalid_arg e let string_opt key config = Config_file_ffi_externs.get_string_opt config key (* Does not immediately raise if key is not an int *) let int_opt_result key config = Config_file_ffi_externs.get_int_opt config key let int_opt key config = Config_file_ffi_externs.get_int_opt config key |> Option.map ~f:ok_or_invalid_arg let float_opt key config = Config_file_ffi_externs.get_float_opt config key |> Option.map ~f:ok_or_invalid_arg let bool_opt key config = Config_file_ffi_externs.get_bool_opt config key |> Option.map ~f:ok_or_invalid_arg let string_list_opt key config = Config_file_ffi_externs.get_string_list_opt config key let int_list_opt key config : int list option = try string_list_opt key config >>| List.map ~f:Int.of_string with | Failure _ -> None let string_ key ~default config = Option.value (string_opt key config) ~default let int_ key ~default config = Option.value (int_opt key config) ~default let float_ key ~default config = Option.value (float_opt key config) ~default let bool_ key ~default config = Option.value (bool_opt key config) ~default let string_list key ~default config = Option.value (string_list_opt key config) ~default let bool_if_min_version key ~default ~current_version config : bool = let version_value = string_ key ~default:(string_of_bool default) config in match version_value with | "true" -> true | "false" -> false | version_value -> let version_value = Config_file_version.parse_version (Some version_value) in if Config_file_version.compare_versions current_version version_value >= 0 then true else false end let apply_overrides ~(config : t) ~(overrides : t) ~(log_reason : string option) : t = if is_empty overrides then config else let config = Config_file_ffi_externs.apply_overrides config overrides in Option.iter log_reason ~f:(fun from -> Printf.eprintf "*** Overrides from %s:\n%!" from; print_to_stderr overrides; Printf.eprintf "\n%!"); config (* Given an hhconfig_path, get the path to the PACKAGES.toml file in the same directory *) let get_packages_absolute_path ~(hhconfig_path : string) = Path.make hhconfig_path |> Path.dirname |> (fun p -> Path.concat p pkgs_config_path_relative_to_repo_root) |> Path.to_string (* * Config file format: * # Some comment. Indicate by a pound sign at the start of a new line * key = a possibly space-separated value *) let parse_contents (contents : string) : t = Config_file_ffi_externs.parse_contents contents let hash (parsed : t) ~(config_contents : string) ~(package_config : string option) : string = match Getters.string_opt "override_hhconfig_hash" parsed with | Some hash -> hash | None -> let contents = match package_config with | Some package_config -> config_contents ^ package_config | None -> config_contents in Sha1.digest contents (* Non-lwt implementation of parse *) let parse (fn : string) : string * t = let contents = Sys_utils.cat fn in let parsed = parse_contents contents in let hash = hash parsed ~config_contents:contents ~package_config:None in (hash, parsed) let parse_local_config (fn : string) : t = try let (_hash, config) = parse fn in config with | e -> Hh_logger.log "Loading config exception: %s" (Exn.to_string e); Hh_logger.log "Could not load config at %s" fn; empty () let to_json t = match Config_file_ffi_externs.to_json t with | Ok json -> Hh_json.json_of_string json | Error e -> failwith e let of_list = Config_file_ffi_externs.of_list let keys = Config_file_ffi_externs.keys
OCaml Interface
hhvm/hphp/hack/src/utils/config_file/config_file_common.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 val file_path_relative_to_repo_root : string val pkgs_config_path_relative_to_repo_root : string val get_packages_absolute_path : hhconfig_path:string -> string val empty : unit -> t val print_to_stderr : t -> unit (** Apply overrides using provided overrides. [log_reason] is solely used for logging, so we can write to stderr indicating where these overrides came from and what they were. *) val apply_overrides : config:t -> overrides:t -> log_reason:string option -> t val parse_contents : string -> t val parse_local_config : string -> t (** Compute the hhconfig hash *) val hash : t -> config_contents:string -> package_config:string option -> string val to_json : t -> Hh_json.json val of_list : (string * string) list -> t val keys : t -> string list module type Getters_S = sig val string_opt : string -> t -> string option val string_ : string -> default:string -> t -> string val int_ : string -> default:int -> t -> int val int_opt_result : string -> t -> (int, string) result option val int_opt : string -> t -> int option val float_ : string -> default:float -> t -> float val float_opt : string -> t -> float option val bool_ : string -> default:bool -> t -> bool val bool_opt : string -> t -> bool option val string_list_opt : string -> t -> string list option val string_list : string -> default:string list -> t -> string list val int_list_opt : string -> t -> int list option val bool_if_min_version : string -> default:bool -> current_version:Config_file_version.version -> t -> bool end module Getters : Getters_S
OCaml
hhvm/hphp/hack/src/utils/config_file/config_file_ffi_externs.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 config external empty : unit -> config = "hh_config_file_empty" external is_empty : config -> bool = "hh_config_file_is_empty" [@@noalloc] external parse_contents : string -> config = "hh_config_file_parse_contents" external print_to_stderr : config -> unit = "hh_config_file_print_to_stderr" [@@noalloc] external apply_overrides : config -> config -> config = "hh_config_file_apply_overrides" external to_json : config -> (string, string) result = "hh_config_file_to_json" external of_list : (string * string) list -> config = "hh_config_file_of_list" external keys : config -> string list = "hh_config_file_keys" external get_string_opt : config -> string -> string option = "hh_config_file_get_string_opt" external get_int_opt : config -> string -> (int, string) result option = "hh_config_file_get_int_opt" external get_float_opt : config -> string -> (float, string) result option = "hh_config_file_get_float_opt" external get_bool_opt : config -> string -> (bool, string) result option = "hh_config_file_get_bool_opt" external get_string_list_opt : config -> string -> string list option = "hh_config_file_get_string_list_opt"
OCaml
hhvm/hphp/hack/src/utils/config_file/config_file_lwt.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 Core include Config_file_version type t = Config_file_common.t let file_path_relative_to_repo_root = Config_file_common.file_path_relative_to_repo_root let empty = Config_file_common.empty let read_package_config (fn : string) : (string, string) Lwt_result.t = let%lwt contents = Lwt_utils.read_all fn in match contents with | Ok c -> Lwt.return_ok c | Error _ -> Lwt.return_ok "" (* If file doesn't exist return empty string *) let parse_hhconfig (fn : string) : (string * t, string) Lwt_result.t = let%lwt contents = Lwt_utils.read_all fn in match contents with | Ok contents -> let parsed = Config_file_common.parse_contents contents in let package_path = Config_file_common.get_packages_absolute_path ~hhconfig_path:fn in let%lwt package_config = read_package_config package_path |> Lwt.map Result.ok in let hash = Config_file_common.hash parsed ~config_contents:contents ~package_config in Lwt.return_ok (hash, parsed) | Error message -> Lwt.return_error (Printf.sprintf "Could not load hhconfig: %s" message)
OCaml Interface
hhvm/hphp/hack/src/utils/config_file/config_file_lwt.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 = Config_file_common.t type version_components = Config_file_version.version_components = { major: int; minor: int; build: int; } type version = Config_file_version.version = | Opaque_version of string option | Version_components of version_components val parse_version : string option -> version val version_to_string_opt : ?pad:bool -> version -> string option val file_path_relative_to_repo_root : string val empty : unit -> t val parse_hhconfig : string -> (string * t, string) Lwt_result.t
OCaml
hhvm/hphp/hack/src/utils/config_file/config_file_version.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 version_components = { major: int; minor: int; build: int; } type version = | Opaque_version of string option | Version_components of version_components let version_to_string_opt ?(pad : bool = true) (v : version) : string option = match v with | Opaque_version s -> s | Version_components { major; minor; build } -> if pad then Some (Printf.sprintf "%d.%02d.%d" major minor build) else Some (Printf.sprintf "%d.%d.%d" major minor build) let version_re_str = {|\^\([0-9]+\)\.\([0-9]+\)\.\([0-9]+\)|} let version_re = Str.regexp version_re_str let parse_version (version : string option) = match version with | Some version when Str.string_match version_re version 0 -> begin try let major = int_of_string (Str.matched_group 1 version) in let minor = int_of_string (Str.matched_group 2 version) in let build = int_of_string (Str.matched_group 3 version) in Version_components { major; minor; build } with | _ -> Hh_logger.log "Failed to parse server version '%s', treating it as an opaque string" version; Opaque_version (Some version) end | Some version -> Hh_logger.log "Server version '%s' does not match version pattern %s, treating it as an opaque string" version version_re_str; Opaque_version (Some version) | None -> Hh_logger.log "Server version is not set"; Opaque_version None let compare_versions v1 v2 = match (v1, v2) with | (Version_components c1, Version_components c2) -> compare c1 c2 | (Opaque_version (Some s1), Opaque_version (Some s2)) -> compare s1 s2 | (Opaque_version None, Opaque_version None) -> 0 | (Opaque_version None, Opaque_version (Some _)) | (Opaque_version _, Version_components _) -> -1 | (Opaque_version (Some _), Opaque_version None) | (Version_components _, Opaque_version _) -> 1
OCaml Interface
hhvm/hphp/hack/src/utils/config_file/config_file_version.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 version_components = { major: int; minor: int; build: int; } type version = | Opaque_version of string option | Version_components of version_components val version_to_string_opt : ?pad:bool -> version -> string option val parse_version : string option -> version val compare_versions : version -> version -> int
hhvm/hphp/hack/src/utils/config_file/dune
(library (name utils_config_file_common) (wrapped false) (modules config_file_common config_file_version) (libraries config_file_ffi_externs core_kernel relative_path sys_utils utils_core utils_hash) (preprocess (pps lwt_ppx))) (library (name utils_config_file) (wrapped false) (modules config_file) (libraries core_kernel sys_utils utils_config_file_common utils_core utils_exit utils_hash) (preprocess (pps lwt_ppx))) (library (name utils_config_file_lwt) (wrapped false) (modules config_file_lwt) (libraries core_kernel lwt lwt.unix lwt_utils sys_utils utils_config_file_common utils_core utils_hash) (preprocess (pps lwt_ppx))) (data_only_dirs rust) (library (name config_file_ffi) (modules) (wrapped false) (foreign_archives config_file_ffi)) (rule (targets libconfig_file_ffi.a) (deps (source_tree %{workspace_root}/hack/src)) (locks /cargo) (action (run %{workspace_root}/hack/scripts/invoke_cargo.sh config_file_ffi config_file_ffi))) (library (name config_file_ffi_externs) (modules config_file_ffi_externs) (libraries config_file_ffi) (preprocess (pps lwt_ppx)))
TOML
hhvm/hphp/hack/src/utils/config_file/rust/Cargo.toml
# @generated by autocargo [package] name = "config_file" version = "0.0.0" edition = "2021" [lib] path = "config_file.rs" [dependencies] bstr = { version = "1.4.0", features = ["serde", "std", "unicode"] } lazy_static = "1.4" regex = "1.9.2" serde_json = { version = "1.0.100", features = ["float_roundtrip", "unbounded_depth"] } sha1 = "0.10.5"
Rust
hhvm/hphp/hack/src/utils/config_file/rust/config_file.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::path::Path; use bstr::ByteSlice; use sha1::Digest; use sha1::Sha1; #[derive(Debug, Clone, Default)] pub struct ConfigFile { map: BTreeMap<String, String>, } impl ConfigFile { pub fn from_file(path: impl AsRef<Path>) -> std::io::Result<Self> { let contents = std::fs::read(path.as_ref())?; Ok(Self::from_slice(&contents)) } pub fn from_file_with_contents(path: impl AsRef<Path>) -> std::io::Result<(String, Self)> { let contents = std::fs::read(path.as_ref())?; Ok(( String::from_utf8(contents.clone()).unwrap(), Self::from_slice(&contents), )) } pub fn from_file_with_sha1(path: impl AsRef<Path>) -> std::io::Result<(String, Self)> { let path = path.as_ref(); let contents = std::fs::read(path)?; Ok(Self::from_slice_with_sha1(&contents)) } pub fn from_slice_with_sha1(bytes: &[u8]) -> (String, Self) { let hash = format!("{:x}", Sha1::digest(bytes)); let config = Self::from_slice(bytes); (hash, config) } fn parse_line(line: &[u8]) -> Option<(String, String)> { let mut key_value_iter = line.splitn(2, |&c| c == b'='); let key = key_value_iter.next()?.trim(); let value = key_value_iter.next()?.trim(); Some(( String::from_utf8_lossy(key).into_owned(), String::from_utf8_lossy(value).into_owned(), )) } pub fn from_slice(bytes: &[u8]) -> Self { let map = (bytes.lines()) .filter_map(|line| match line.first() { Some(b'#') => None, _ => Self::parse_line(line), }) .collect(); Self { map } } pub fn from_args<'i, I>(kvs: I) -> Self where I: IntoIterator<Item = &'i [u8]>, { Self { map: kvs.into_iter().filter_map(Self::parse_line).collect(), } } pub fn is_empty(&self) -> bool { self.map.is_empty() } pub fn apply_overrides(&mut self, overrides: &Self) { for (key, value) in overrides.map.iter() { self.map.insert(key.clone(), value.clone()); } } pub fn to_json(&self) -> serde_json::Result<String> { serde_json::to_string(&self.map) } pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> { self.map.iter().map(|(k, v)| (k.as_str(), v.as_str())) } pub fn keys(&self) -> impl Iterator<Item = &str> { self.map.keys().map(|s| s.as_str()) } pub fn get_str(&self, key: &str) -> Option<&str> { self.map.get(key).map(|s| s.as_str()) } pub fn get_int(&self, key: &str) -> Option<Result<isize, std::num::ParseIntError>> { self.map.get(key).map(|s| parse_int(s)) } pub fn get_float(&self, key: &str) -> Option<Result<f64, std::num::ParseFloatError>> { self.map.get(key).map(|s| s.parse()) } pub fn get_bool(&self, key: &str) -> Option<Result<bool, std::str::ParseBoolError>> { self.map.get(key).map(|s| s.parse()) } pub fn bool_if_min_version( &self, key: &str, _current_version: Option<&str>, ) -> Option<Result<bool, std::str::ParseBoolError>> { Some(match self.get_bool(key)? { Ok(b) => Ok(b), Err(e) => { // TODO handle versions Err(e) } }) } pub fn get_str_list(&self, key: &str) -> Option<impl Iterator<Item = &str>> { lazy_static::lazy_static! { static ref RE: regex::Regex = regex::Regex::new(",[ \n\r\x0c\t]*").unwrap(); } self.map.get(key).map(|s| RE.split(s.as_str())) } } impl FromIterator<(String, String)> for ConfigFile { fn from_iter<I: IntoIterator<Item = (String, String)>>(iter: I) -> Self { Self { map: BTreeMap::from_iter(iter), } } } impl IntoIterator for ConfigFile { type Item = (String, String); type IntoIter = std::collections::btree_map::IntoIter<String, String>; fn into_iter(self) -> Self::IntoIter { self.map.into_iter() } } // Intended to behave like `caml_int_of_string`. fn parse_int(input: &str) -> Result<isize, std::num::ParseIntError> { use std::borrow::Cow; let input = if input.contains('_') { Cow::Owned(input.chars().filter(|&c| c != '_').collect()) } else { Cow::Borrowed(input) }; if input.starts_with("0b") { isize::from_str_radix(input.trim_start_matches("0b"), 2) } else if input.starts_with("0o") { isize::from_str_radix(input.trim_start_matches("0o"), 8) } else if input.starts_with("0x") { isize::from_str_radix(input.trim_start_matches("0x"), 16) } else { input.parse() } } #[cfg(test)] mod test_parse_int { use super::parse_int; #[test] fn test() { // These test cases assert the same behavior as `caml_int_of_string`. assert_eq!(parse_int("42"), Ok(42)); assert_eq!(parse_int("-42"), Ok(-42)); assert_eq!(parse_int("0x42"), Ok(66)); assert_eq!(parse_int("0o42"), Ok(34)); assert_eq!(parse_int("042"), Ok(42)); assert_eq!(parse_int("0b0110"), Ok(6)); assert_eq!(parse_int("0b0110_0110"), Ok(102)); assert_eq!(parse_int("0x0110_0110"), Ok(17_826_064)); assert_eq!(parse_int("0o0110_0110"), Ok(294_984)); assert_eq!(parse_int("1_100_110"), Ok(1_100_110)); assert_eq!(parse_int("0110_0110"), Ok(1_100_110)); } }
Rust
hhvm/hphp/hack/src/utils/config_file/rust/ffi.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 config_file::ConfigFile; use ocamlrep_custom::Custom; struct Config(ConfigFile); impl ocamlrep_custom::CamlSerialize for Config { ocamlrep_custom::caml_serialize_default_impls!(); } fn wrap(config: ConfigFile) -> Custom<Config> { Custom::from(Config(config)) } ocamlrep_ocamlpool::ocaml_ffi! { fn hh_config_file_empty() -> Custom<Config> { wrap(ConfigFile::default()) } fn hh_config_file_parse_contents(contents: Vec<u8>) -> Custom<Config> { wrap(ConfigFile::from_slice(&contents)) } fn hh_config_file_is_empty(config: Custom<Config>) -> bool { config.0.is_empty() } fn hh_config_file_print_to_stderr(config: Custom<Config>) { for (key, value) in config.0.iter() { eprintln!("{} = {}", key, value); } use std::io::Write; let _ = std::io::stderr().flush(); } fn hh_config_file_apply_overrides( config: Custom<Config>, overrides: Custom<Config>, ) -> Custom<Config> { let mut config = config.0.clone(); config.apply_overrides(&overrides.0); wrap(config) } fn hh_config_file_to_json(config: Custom<Config>) -> Result<String, String> { config.0.to_json().map_err(|e| e.to_string()) } fn hh_config_file_of_list(list: Vec<(String, String)>) -> Custom<Config> { wrap(list.into_iter().collect()) } fn hh_config_file_keys(config: Custom<Config>) -> Vec<String> { config.0.keys().map(|s| s.to_owned()).collect() } fn hh_config_file_get_string_opt(config: Custom<Config>, key: String) -> Option<String> { config.0.get_str(&key).map(|s| s.to_owned()) } fn hh_config_file_get_int_opt( config: Custom<Config>, key: String, ) -> Option<Result<isize, String>> { config.0.get_int(&key) .map(|r| r.map_err(|e| e.to_string())) } fn hh_config_file_get_float_opt( config: Custom<Config>, key: String, ) -> Option<Result<f64, String>> { config.0.get_float(&key) .map(|r| r.map_err(|e| e.to_string())) } fn hh_config_file_get_bool_opt( config: Custom<Config>, key: String, ) -> Option<Result<bool, String>> { config.0.get_bool(&key) .map(|r| r.map_err(|e| e.to_string())) } fn hh_config_file_get_string_list_opt( config: Custom<Config>, key: String, ) -> Option<Vec<String>> { config.0.get_str_list(&key) .map(|iter| iter.map(|s| s.to_owned()).collect()) } }
TOML
hhvm/hphp/hack/src/utils/config_file/rust/ffi/Cargo.toml
# @generated by autocargo [package] name = "config_file_ffi" version = "0.0.0" edition = "2021" [lib] path = "../ffi.rs" test = false doctest = false crate-type = ["lib", "staticlib"] [dependencies] config_file = { version = "0.0.0", path = ".." } ocamlrep_custom = { version = "0.1.0", git = "https://github.com/facebook/ocamlrep/", branch = "main" } ocamlrep_ocamlpool = { version = "0.1.0", git = "https://github.com/facebook/ocamlrep/", branch = "main" }
OCaml
hhvm/hphp/hack/src/utils/core/build_id.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 external get_build_revision : unit -> string = "hh_get_build_revision" external get_build_commit_time : unit -> int = "hh_get_build_commit_time" external get_build_commit_time_string : unit -> string = "hh_get_build_commit_time_string" external get_build_mode : unit -> string = "hh_get_build_mode" let build_revision = get_build_revision () let build_commit_time = get_build_commit_time () let build_commit_time_string = get_build_commit_time_string () let build_mode = get_build_mode () let is_build_optimized = String.is_prefix build_mode ~prefix:"dbgo" || String.is_prefix build_mode ~prefix:"opt" || String.equal build_mode "" let is_dev_build = (* FB development build hashes are empty. *) String.equal build_revision "" (* Dune build hashes are short. *) || String.length build_revision <= 16 (* fail open if we don't know build mode *)
OCaml Interface
hhvm/hphp/hack/src/utils/core/build_id.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 build_revision : string val build_commit_time : int val build_commit_time_string : string val build_mode : string val is_build_optimized : bool val is_dev_build : bool
TOML
hhvm/hphp/hack/src/utils/core/Cargo.toml
# @generated by autocargo [package] name = "core_utils_rust" version = "0.0.0" edition = "2021" [lib] path = "utils.rs" [dev-dependencies] pretty_assertions = { version = "1.2", features = ["alloc"], default-features = false }
hhvm/hphp/hack/src/utils/core/dune
(copy_files ../../../scripts/get_build_id_gen.c) (library (name utils_core) (wrapped false) (foreign_stubs (language c) (names get_build_id get_build_id_gen) (flags (:standard (:include config/build-timestamp-opt)))) (libraries base core_kernel.caml_unix string hh_json str unix measure_ffi) (preprocess (pps lwt_ppx ppx_deriving.std ppx_deriving.enum ppx_hash))) (data_only_dirs rust) (library (name measure_ffi) (modules) (wrapped false) (foreign_archives measure_ffi)) (rule (targets libmeasure_ffi.a) (deps (source_tree %{workspace_root}/hack/src)) (locks /cargo) (action (run %{workspace_root}/hack/scripts/invoke_cargo.sh measure_ffi measure_ffi)))
OCaml
hhvm/hphp/hack/src/utils/core/exception.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. *) type t = { exn: exn; backtrace: Printexc.raw_backtrace; } (* In ocaml, backtraces (the path that the exception bubbled up after being thrown) are stored as * global state and NOT with the exception itself. This means the only safe place to ever read the * backtrace is immediately after the exception is caught in the `with` block of a `try...with`. * * Proper use of this module is something like * * try * ... * with exn -> * let e = Exception.wrap exn in (* DO THIS FIRST!!! *) * my_fun e; (* If this code throws internally it will overwrite the global backtrace *) * Exception.reraise e *) let wrap exn = let backtrace = Printexc.get_raw_backtrace () in { exn; backtrace } (* The inverse of `wrap`, returns the wrapped `exn`. You might use this to pattern match on the raw exception or print it, but should not reraise it since it will not include the correct backtrace; use `reraise` or `to_exn` instead. *) let unwrap { exn; backtrace = _ } = exn let reraise { exn; backtrace } = Printexc.raise_with_backtrace exn backtrace (* Converts back to an `exn` with the right backtrace. Generally, avoid this in favor of the helpers in this module, like `to_string` and `get_backtrace_string`. *) let to_exn t = try reraise t with | exn -> exn (* Like `wrap`, but for the unusual case where you want to create an `Exception` for an un-raised `exn`, capturing its stack trace. If you've caught an exception, you should use `wrap` instead, since it already has a stack trace. *) let wrap_unraised ?(frames = 100) exn = let frames = if Printexc.backtrace_status () then frames else 0 in let backtrace = Printexc.get_callstack frames in { exn; backtrace } let get_ctor_string { exn; backtrace = _ } = Printexc.to_string exn let register_printer printer = Printexc.register_printer printer let get_backtrace_string { exn = _; backtrace } = Printexc.raw_backtrace_to_string backtrace let to_string t = let ctor = get_ctor_string t in let bt = get_backtrace_string t in if bt = "" then ctor else ctor ^ "\n" ^ bt let get_current_callstack_string n = Printexc.get_callstack n |> Printexc.raw_backtrace_to_string let record_backtrace = Printexc.record_backtrace (** We want to include all stack lines that come from our code, and exclude ones that come from the standard library. That's easy for stack lines that include a module: if the module starts "Stdlib" or "Base" then exclude it; if it starts with anything else then include it. But for stack lines that don't include a module then we'll use a heuristic that only works on some build systems. Some build systems like buck include absolute pathnames so that "/.../hack/src/hh_client.ml" implies it's our code and "src/list.ml" implies it's not. Other build systems like dune are relative and there's no way we can distinguish "src/hh_client.ml" from "src/list.ml". These regular expressions extract all that information. Our heuristic in [clean_stack] will simply assume buck-style absolute pathnames. *) let (stack_re, file_re) = ( Str.regexp {|^\(Called from\|Raised by primitive operation at\|Raised at\|Re-raised at\)\( \([^ ]*\) in\)? file "\([^"]*\)"\( (inlined)\)?, line \([0-9]+\), character.*$|}, Str.regexp {|^.*/hack/\(.*\)$|} ) let clean_stack (stack : string) : string = let format_one_line (s : string) : string option = let open Hh_prelude in if Str.string_match stack_re s 0 then let module_ = try Str.matched_group 3 s with | _ -> "" in let file = Str.matched_group 4 s in let line = Str.matched_group 6 s in let (file, file_is_in_hack_src_tree) = if Str.string_match file_re file 0 then (Str.matched_group 1 file, true) else (file, false) in if String.equal module_ "" then if file_is_in_hack_src_tree then Some (Printf.sprintf "%s @ %s" file line) else None else if String.is_prefix module_ ~prefix:"Base" || String.is_prefix module_ ~prefix:"Stdlib" || String.is_prefix module_ ~prefix:"Lwt" then None else Some (Printf.sprintf "%s @ %s" file line) else Some s in String_utils.split_on_newlines stack |> List.filter_map format_one_line |> String.concat "\n" let pp ppf t = Format.fprintf ppf "@[<1>%s: %s@]@." (get_ctor_string t) (get_backtrace_string t |> clean_stack) let show t = get_ctor_string t
OCaml Interface
hhvm/hphp/hack/src/utils/core/exception.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. *) type t [@@deriving show] val wrap : exn -> t val wrap_unraised : ?frames:int -> exn -> t val unwrap : t -> exn val reraise : t -> 'a val to_exn : t -> exn val to_string : t -> string val register_printer : (exn -> string option) -> unit val get_ctor_string : t -> string val get_backtrace_string : t -> string val get_current_callstack_string : int -> string val record_backtrace : bool -> unit val clean_stack : string -> string
OCaml
hhvm/hphp/hack/src/utils/core/exit_status.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type t = | No_error | Checkpoint_error | Input_error | Kill_error | No_server_running_should_retry | Server_hung_up_should_retry of finale_data option [@printer (fun fmt _t -> fprintf fmt "Exit_status.Server_hung_up_should_retry")] | Server_hung_up_should_abort of finale_data option [@printer (fun fmt _t -> fprintf fmt "Exit_status.Server_hung_up_should_abort")] | Out_of_time | Out_of_retries | Server_already_exists | Type_error | Build_id_mismatch | Monitor_connection_failure | Unused_server | Lock_stolen | Lost_parent_monitor | Server_got_eof_from_monitor | Interrupted | Client_broken_pipe | Worker_oomed | Worker_busy (* An uncaught Not_found exception in the worker. *) | Worker_not_found_exception | Worker_failed_to_send_job | Socket_error | Missing_hhi | Dfind_died | Dfind_unresponsive | EventLogger_Timeout | EventLogger_restart_out_of_retries | EventLogger_broken_pipe | CantRunAI | Watchman_failed (** Watchman_failed is used both as an exit status from hh_client because this means it can't safely compute streaming errors, and also as an exit status from server/monitor because it'ss faster to exit the server (and have the Monitor restart the server) on a Watchman fresh instance than to compute the files that have been deleted and do an incremental check. *) | Watchman_fresh_instance | Watchman_invalid_result | File_provider_stale | Hhconfig_deleted | Hhconfig_changed | Package_config_changed | Typecheck_restarted (** an exit status of hh_client check, e.g. because files-on-disk changed *) | Typecheck_abandoned (** an exit status of hh_client check, e.g. because the server was killed mid-check *) | Server_shutting_down_due_to_sigusr2 | IDE_malformed_request | IDE_no_server | IDE_out_of_retries | Nfs_root | IDE_init_failure | IDE_typechecker_died | Redecl_heap_overflow | Out_of_shared_memory | Shared_mem_assertion_failure | Hash_table_full | IDE_new_client_connected | Lazy_decl_bug | Decl_heap_elems_bug | Parser_heap_build_error | Heap_full | Sql_assertion_failure | Local_type_env_stale | Sql_cantopen | Sql_corrupt | Sql_misuse | Uncaught_exception of Exception.t [@printer (fun fmt _t -> fprintf fmt "Exit_status.Uncaught_exception")] | Decl_not_found | Big_rebase_detected | Failed_to_load_should_retry | Failed_to_load_should_abort | Server_non_opt_build_mode | Not_restarting_server_with_precomputed_saved_state | Config_error [@@deriving show] and finale_data = { exit_status: t; msg: string option; stack: Utils.callstack; telemetry: Telemetry.t option; } exception Exit_with of t (* Please note that AI(zoncolan) calls hack and might exit with these codes, and also uses own defined codes from ai_exit_status.ml. When adding a new code here, ensure not to overlap with ai_exit_status *) let exit_code = function | Interrupted -> 130 (* standard unix exit code for SIGINT, generated by hh_client. Also generated by MonitorMain for a SIGINT, SIGTERM, SIGHUP, SIGQUIT. *) | Client_broken_pipe -> 141 (* standard unix code for SIGPIPE, generated by hh_client *) | No_error -> 0 | Kill_error -> 1 (* used in clientStop/Start/Restart *) | Server_shutting_down_due_to_sigusr2 -> 1 (* used in server *) (* CARE! exit code 2 is also used when an ocaml binary exits with an unhandled exception. It's a shame that we can't distinguish such exits from the following two codes. *) | Type_error -> 2 (* used in clientCheck *) | Uncaught_exception _ -> 221 | Hhconfig_changed -> 4 | Package_config_changed -> 4 | Typecheck_restarted -> (* gen by clientCheck/clientCheckStatus, read by find_hh.sh *) 19 | Typecheck_abandoned -> (* gen by clientCheck/clientCheckStatus, read by find_hh.sh *) 20 | Unused_server -> 5 | No_server_running_should_retry -> (* gen by clientConnect, read by find_hh.sh *) 6 | Server_hung_up_should_retry _ -> (* gen by clientConnect, read by find_hh.sh *) 6 | Out_of_time -> 7 | Out_of_retries -> 7 | Checkpoint_error -> 8 | Build_id_mismatch -> 9 | Monitor_connection_failure -> 9 | Input_error -> 10 | Lock_stolen -> 11 | Lost_parent_monitor -> 12 | Server_got_eof_from_monitor -> 18 | Shared_mem_assertion_failure -> 14 | Out_of_shared_memory -> 15 | Hash_table_full -> 16 | Heap_full -> 17 | Worker_oomed -> 30 | Worker_busy -> 31 | Worker_not_found_exception -> 32 | Worker_failed_to_send_job -> 33 | Server_already_exists -> 77 | Missing_hhi -> 97 | Socket_error -> 98 | Dfind_died -> 99 | Dfind_unresponsive -> 100 | EventLogger_Timeout -> 101 | CantRunAI -> 102 | Watchman_failed -> 103 | Hhconfig_deleted -> 104 | EventLogger_broken_pipe -> 106 | Redecl_heap_overflow -> 107 | EventLogger_restart_out_of_retries -> 108 | Watchman_fresh_instance -> 109 | Watchman_invalid_result -> 110 | Big_rebase_detected -> 111 | IDE_malformed_request -> 201 | IDE_no_server -> 202 | IDE_out_of_retries -> 203 | Nfs_root -> 204 | IDE_init_failure -> 205 | IDE_typechecker_died -> 206 | IDE_new_client_connected -> 207 | Lazy_decl_bug -> 208 | Decl_heap_elems_bug -> 209 | Parser_heap_build_error -> 210 | File_provider_stale -> 211 | Sql_assertion_failure -> 212 | Local_type_env_stale -> 213 | Sql_cantopen -> 214 | Sql_corrupt -> 215 | Sql_misuse -> 216 | Decl_not_found -> 217 | Failed_to_load_should_retry -> 218 (* gen by serverInit, read by serverMonitor+clientConnect *) | Failed_to_load_should_abort -> 219 (* gen by serverInit, read by serverMonitor+clientConnect *) | Server_hung_up_should_abort _ -> (* generated by clientConnect, read by find_hh.sh *) 220 | Server_non_opt_build_mode -> 222 | Not_restarting_server_with_precomputed_saved_state -> 223 | Config_error -> 224 let exit_code_to_string (code : int) : string = (* We will return the string "See Exit_status.ml for meaning of this code". But, let's hard-code a few of the more common ones just as a convenience to the reader. *) let common_codes = [ Interrupted; Client_broken_pipe; No_error; Kill_error; Type_error; Uncaught_exception (try failwith "dummy" with | exn -> Exception.wrap exn); Hhconfig_changed; Package_config_changed; Typecheck_restarted; Typecheck_abandoned; No_server_running_should_retry; Server_hung_up_should_retry None; Out_of_time; Out_of_retries; Build_id_mismatch; Monitor_connection_failure; Failed_to_load_should_retry; Failed_to_load_should_abort; Server_hung_up_should_abort None; Watchman_failed; Server_non_opt_build_mode; ] in let matches = List.filter_map (fun exit_status -> if exit_code exit_status = code then Some (show exit_status) else None) common_codes in (* If an ocaml binary exits with an uncaught exception, it produces exit code 2. We'll reconstruct that fact here. However our binaries should avoid exiting in this manner, since exit code 2 also means "hh_check completed successfully"! *) let matches = if code = 2 then "Uncaught_exception_ocaml" :: matches else matches in match matches with | [] -> Printf.sprintf "(see Exit_status.exit_code for meaning of code %d)" code | _ -> String.concat "/" matches let unpack = function | Unix.WEXITED n -> ("exit", n) | Unix.WSIGNALED n -> (* * Ocaml signal numbers are mapped from System signal numbers. * They are negative. * See caml_convert_signal_number byterun/signals.c in Ocaml system source code * to convert from Ocaml number to System number *) ("signaled", n) | Unix.WSTOPPED n -> ("stopped", n) let () = Exception.register_printer (function | Exit_with exit_status -> Some (Printf.sprintf "Exit_status.Exit_with(%s)" (show exit_status)) | _ -> None) let get_finale_data (server_finale_file : string) : finale_data option = try let ic = Stdlib.open_in_bin server_finale_file in let contents : finale_data = Marshal.from_channel ic in Stdlib.close_in ic; Some contents with | _ -> None let show_expanded (t : t) : string = match t with | Server_hung_up_should_abort (Some finale_data) | Server_hung_up_should_retry (Some finale_data) -> let { exit_status; msg; stack = Utils.Callstack stack; telemetry } = finale_data in let telemetry = telemetry |> Option.map Telemetry.to_string |> Option.value ~default:"" in Printf.sprintf "%s exit_code=%d [%s] %s %s\n%s" (show t) (exit_code t) (show exit_status) (Option.value msg ~default:"") telemetry (Exception.clean_stack stack) | Uncaught_exception e -> Printf.sprintf "%s exit_code=%d [%s]\n%s" (show t) (exit_code t) (Exception.get_ctor_string e) (Exception.get_backtrace_string e |> Exception.clean_stack) | _ -> Printf.sprintf "%s exit_code=%d" (show t) (exit_code t)
OCaml Interface
hhvm/hphp/hack/src/utils/core/exit_status.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 = | No_error | Checkpoint_error | Input_error | Kill_error | No_server_running_should_retry | Server_hung_up_should_retry of finale_data option | Server_hung_up_should_abort of finale_data option | Out_of_time | Out_of_retries | Server_already_exists | Type_error | Build_id_mismatch | Monitor_connection_failure | Unused_server | Lock_stolen | Lost_parent_monitor | Server_got_eof_from_monitor | Interrupted (** hh_client installs a SIGINT handler which raises [Exit_with Interrupted]. Also, MonitorMain installs SIGINT, SIGQUIT, SIGTERM, SIGHUP handlers which call [Exit.exit Interrupted]. *) | Client_broken_pipe (** hh_client code tried to write to stdout, but was thwarted by Sys_error("Broken pipe") *) | Worker_oomed | Worker_busy | Worker_not_found_exception | Worker_failed_to_send_job | Socket_error | Missing_hhi | Dfind_died | Dfind_unresponsive | EventLogger_Timeout | EventLogger_restart_out_of_retries | EventLogger_broken_pipe | CantRunAI | Watchman_failed | Watchman_fresh_instance | Watchman_invalid_result | File_provider_stale | Hhconfig_deleted | Hhconfig_changed | Package_config_changed | Typecheck_restarted (** an exit status of hh_client check, e.g. because files-on-disk changed *) | Typecheck_abandoned (** an exit status of hh_client check, e.g. because the server was killed mid-check *) | Server_shutting_down_due_to_sigusr2 | IDE_malformed_request | IDE_no_server | IDE_out_of_retries | Nfs_root | IDE_init_failure | IDE_typechecker_died | Redecl_heap_overflow | Out_of_shared_memory | Shared_mem_assertion_failure | Hash_table_full | IDE_new_client_connected | Lazy_decl_bug | Decl_heap_elems_bug | Parser_heap_build_error | Heap_full | Sql_assertion_failure | Local_type_env_stale | Sql_cantopen | Sql_corrupt | Sql_misuse | Uncaught_exception of Exception.t | Decl_not_found | Big_rebase_detected | Failed_to_load_should_retry | Failed_to_load_should_abort | Server_non_opt_build_mode | Not_restarting_server_with_precomputed_saved_state | Config_error [@@deriving show] and finale_data = { exit_status: t; (** exit_status is shown to the user in CLI and LSP, just so they have an error code they can quote back at developers. It's also used by hh_client to decide, on the basis of that hh_server exit_status, whether to auto-restart hh_server or not. And it appears in logs and telemetry. *) msg: string option; (** msg is a human-readable message for the end-user to explain why hh_server stopped. It appears in the CLI, and in LSP in a hover tooltip. It also is copied into the logs. *) stack: Utils.callstack; telemetry: Telemetry.t option; (** telemetry is unstructured data, for logging, not shown to users *) } exception Exit_with of t val exit_code : t -> int val exit_code_to_string : int -> string val unpack : Unix.process_status -> string * int (** If the server dies through a controlled exit, it leaves behind a "finale file" <pid>.fin with json-formatted data describing the detailed nature of the exit including callstack. This method retrieves that file, if it exists. *) val get_finale_data : string -> finale_data option (** like [show], but prints a lot more information including callstacks *) val show_expanded : t -> string
C
hhvm/hphp/hack/src/utils/core/get_build_id.c
/** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * */ #define CAML_NAME_SPACE #include <caml/memory.h> #include <caml/alloc.h> #include <assert.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <time.h> extern const char* const BuildInfo_kRevision; extern const uint64_t BuildInfo_kRevisionCommitTimeUnix; extern const char* const BuildInfo_kBuildMode; /** * Export the constants provided by Facebook's build system to ocaml-land, since * their FFI only allows you to call functions, not reference variables. Doing * it this way makes sense for Facebook internally since our build system has * machinery for providing these two constants automatically (and no machinery * for doing codegen in a consistent way to build an ocaml file with them) but * is very roundabout for external users who have to have CMake codegen these * constants anyways. Sorry about that. */ value hh_get_build_revision(void) { CAMLparam0(); CAMLlocal1(result); const char* const buf = BuildInfo_kRevision; const size_t len = strlen(buf); result = caml_alloc_initialized_string(len, buf); CAMLreturn(result); } static struct tm *get_built_timestamp(void) { unsigned long timestamp = BuildInfo_kRevisionCommitTimeUnix; #ifdef HH_BUILD_TIMESTAMP if (timestamp == 0) { timestamp = HH_BUILD_TIMESTAMP; } #endif // A previous version used localtime_r, which is not available on Windows return localtime((time_t*)&timestamp); } value hh_get_build_commit_time_string(void) { CAMLparam0(); CAMLlocal1(result); char timestamp_string[25]; struct tm *timestamp = get_built_timestamp(); strftime(timestamp_string, sizeof(timestamp_string), "%c", timestamp); result = caml_copy_string(timestamp_string); CAMLreturn(result); } value hh_get_build_commit_time(void) { return Val_long(BuildInfo_kRevisionCommitTimeUnix); } value hh_get_build_mode(void) { CAMLparam0(); CAMLlocal1(result); const size_t len = strlen(BuildInfo_kBuildMode); result = caml_alloc_initialized_string(len, BuildInfo_kBuildMode); CAMLreturn(result); }
OCaml
hhvm/hphp/hack/src/utils/core/hh_logger.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 (* We might want to log to both stderr and a file. Shelling out to tee isn't cross-platform. * We could dup2 stderr to a pipe and have a child process write to both original stderr and the * file, but that's kind of overkill. This is good enough *) let dupe_log : Out_channel.t option ref = ref None let set_log filename = Option.iter !dupe_log ~f:(fun fd -> Out_channel.close fd); dupe_log := Some (Out_channel.create filename ~append:true); () let id : string option ref = ref None let set_id passed_id = id := Some passed_id let get_id () = !id let id_string () = match !id with | None -> "" | Some id -> Printf.sprintf "[%s] " id let category_string category = match category with | None -> "" | Some category -> Printf.sprintf "[%s] " category type passes = { passes_file: bool; passes_stderr: bool; } let print_with_newline_internal ?category ~passes ?exn fmt = let print_raw ?exn s = let exn_str = Option.value_map exn ~default:"" ~f:(fun exn -> let bt = String_utils.indent 8 @@ String.strip @@ Exception.get_backtrace_string exn in let bt = if String.equal bt "" then "" else "\n Backtrace:\n" ^ bt in Printf.sprintf "\n Exception: %s%s" (Exception.get_ctor_string exn) bt) in let time = Utils.timestring (Unix.gettimeofday ()) in let id_str = id_string () in let category_str = category_string category in begin match (!dupe_log, passes.passes_file) with | (Some dupe_log_oc, true) -> Printf.fprintf dupe_log_oc "%s %s%s%s%s\n%!" time id_str category_str s exn_str | (_, _) -> () end; if passes.passes_stderr then Printf.eprintf "%s %s%s%s%s\n%!" time id_str category_str s exn_str in Printf.ksprintf (print_raw ?exn) fmt let print_with_newline ?exn fmt = print_with_newline_internal ~passes:{ passes_file = true; passes_stderr = true } ?exn fmt let print_duration name t = let t2 = Unix.gettimeofday () in print_with_newline "%s: %f" name (t2 -. t); t2 let exc ?(prefix : string = "") ~(stack : string) (e : exn) : unit = print_with_newline "%s%s\n%s" prefix (Exn.to_string e) stack let exception_ ?(prefix : string = "") (e : Exception.t) : unit = exc ~prefix ~stack:(Exception.get_backtrace_string e) (Exception.unwrap e) module Level : sig type t = | Off | Fatal | Error | Warn | Info | Debug [@@deriving enum] val of_enum_string : string -> t option val to_enum_string : t -> string val min_level_file : unit -> t val min_level_stderr : unit -> t val set_min_level : t -> unit val set_min_level_file : t -> unit val set_min_level_stderr : t -> unit val passes_min_level : t -> bool val set_categories : string list -> unit val log : t -> ?category:string -> ?exn:Exception.t -> ('a, unit, string, string, string, unit) format6 -> 'a val log_lazy : t -> ?category:string -> ?exn:Exception.t -> string lazy_t -> unit val log_duration : t -> ?category:string -> string -> float -> float end = struct type t = | Off [@value 6] | Fatal [@value 5] | Error [@value 4] | Warn [@value 3] | Info [@value 2] | Debug [@value 1] [@@deriving enum] let to_enum_string = function | Off -> "off" | Fatal -> "fatal" | Error -> "error" | Warn -> "warn" | Info -> "info" | Debug -> "debug" let of_enum_string = function | "off" -> Some Off | "fatal" -> Some Fatal | "error" -> Some Error | "warn" -> Some Warn | "info" -> Some Info | "debug" -> Some Debug | _ -> None let min_level_file_ref = ref Info let min_level_stderr_ref = ref Info let categories_ref = ref SSet.empty let set_min_level_file level = min_level_file_ref := level let set_min_level_stderr level = min_level_stderr_ref := level let set_min_level level = set_min_level_file level; set_min_level_stderr level; () let min_level_file () = !min_level_file_ref let min_level_stderr () = !min_level_stderr_ref let set_categories categories = categories_ref := SSet.of_list categories let passes level ~category = let passes_category = match category with | None -> true | Some category -> SSet.mem category !categories_ref in if not passes_category then None else let ilevel = to_enum level in let passes_file = ilevel >= to_enum !min_level_file_ref in let passes_stderr = ilevel >= to_enum !min_level_stderr_ref in if passes_file || passes_stderr then Some { passes_file; passes_stderr } else None let passes_min_level level = passes level ~category:None |> Option.is_some let log level ?category ?exn fmt = match passes level ~category with | Some passes -> print_with_newline_internal ?category ~passes ?exn fmt | None -> Printf.ifprintf () fmt let log_lazy level ?category ?exn s = match passes level ~category with | Some passes -> print_with_newline_internal ?category ~passes ?exn "%s" (Lazy.force s) | None -> () let log_duration level ?category name t = let t2 = Unix.gettimeofday () in begin match passes level ~category with | Some passes -> print_with_newline_internal ?category ~passes "%s: %f" name (t2 -. t) | None -> () end; t2 end (* Default log instructions to INFO level *) let log ?(lvl = Level.Info) ?category fmt = Level.log lvl ?category fmt let log_lazy ?(lvl = Level.Info) ?category str = Level.log_lazy lvl ?category str let log_duration ?(lvl = Level.Info) ?category fmt t = Level.log_duration lvl ?category fmt t let fatal ?category ?exn fmt = Level.log Level.Fatal ?category ?exn fmt let error ?category ?exn fmt = Level.log Level.Error ?category ?exn fmt let warn ?category ?exn fmt = Level.log Level.Warn ?category ?exn fmt let info ?category ?exn fmt = Level.log Level.Info ?category ?exn fmt let debug ?category ?exn fmt = Level.log Level.Debug ?category ?exn fmt
OCaml Interface
hhvm/hphp/hack/src/utils/core/hh_logger.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. * *) (** enables logging to a file (in addition to stderr which is always enabled) *) val set_log : string -> unit val set_id : string -> unit val get_id : unit -> string option val print_with_newline : ?exn:Exception.t -> ('a, unit, string, unit) format4 -> 'a val print_duration : string -> float -> float val exception_ : ?prefix:string -> Exception.t -> unit module Level : sig type t = | Off | Fatal | Error | Warn | Info | Debug [@@deriving enum] val of_enum_string : string -> t option val to_enum_string : t -> string (** returns the min file log level *) val min_level_file : unit -> t (** returns the min stderr log level *) val min_level_stderr : unit -> t (** overwrites min level for both stderr and file (if enabled) *) val set_min_level : t -> unit (** overwrites min level for file (if enabled), but leaves stderr as is *) val set_min_level_file : t -> unit (** overwrites min level for stderr, but leaves file (if enabled) as is *) val set_min_level_stderr : t -> unit (** overwrites the set of categories that be checked for log level before being output; when logs are logged with no category, then only the log level is used to decide whether the log entry should be output; if a category is specified when logging, then this list of categories will be checked in addition to the log level *) val set_categories : string list -> unit (** returns true if t passes either stderr or file min level (regardless whether file is enabled) *) val passes_min_level : t -> bool (** logs the message and how long the presumed operation took, assuming that the float argument is the start time and that the end time is now *) val log_duration : t -> ?category:string -> string -> float -> float end val log : ?lvl:Level.t -> ?category:string -> ('a, unit, string, string, string, unit) format6 -> 'a val log_lazy : ?lvl:Level.t -> ?category:string -> string lazy_t -> unit val log_duration : ?lvl:Level.t -> ?category:string -> string -> float -> float val fatal : ?category:string -> ?exn:Exception.t -> ('a, unit, string, string, string, unit) format6 -> 'a val error : ?category:string -> ?exn:Exception.t -> ('a, unit, string, string, string, unit) format6 -> 'a val warn : ?category:string -> ?exn:Exception.t -> ('a, unit, string, string, string, unit) format6 -> 'a val info : ?category:string -> ?exn:Exception.t -> ('a, unit, string, string, string, unit) format6 -> 'a val debug : ?category:string -> ?exn:Exception.t -> ('a, unit, string, string, string, unit) format6 -> 'a
OCaml
hhvm/hphp/hack/src/utils/core/hh_prelude.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. * *) include Core (** The equality function in Pervasives is backed by compiler magic (called compare_val), which operates on the memory representation of values to perform a comparison between values of any type. This is convenient, but it has the wrong semantics for stdlib sets and maps (since the same value may be represented with trees of differing structure), will not compare on-heap values with off-heap values (unless the compiler was configured with the -no-naked-pointers option), and is slower than monomorphic comparison functions. As a result, we forbid the use of the = operator from Pervasives here. Instead of using polymorphic equality, use ppx_deriving to derive eq for your data type and use the derived `equal` function. If you are performing many comparisons of the same kind, consider binding the = operator locally with something like `let ( = ) = Int.equal`. If your module only compares values of a single builtin type (e.g., int or string), you can add `open Int.Replace_polymorphic_compare` to the top of the file. With ocaml 4.08 and later, Core/Core_kernel is binding (=) to Int.equal, let's do the same. *) let ( = ) : int -> int -> bool = Int.equal (** The nonequal function in Pervasives is backed by compiler magic (called compare_val), which operates on the memory representation of values to perform a comparison between values of any type. This is convenient, but it has the wrong semantics for stdlib sets and maps (since the same value may be represented with trees of differing structure), will not compare on-heap values with off-heap values (unless the compiler was configured with the -no-naked-pointers option), and is slower than monomorphic comparison functions. As a result, we forbid the use of the <> operator from Pervasives here. Instead of using polymorphic equality, use ppx_deriving to derive eq for your data type and use the derived `equal` function. If you are performing many comparisons of the same kind, consider binding the <> operator locally with something like `let ( <> ) = Int.( <> )`. If your module only compares values of a single builtin type (e.g., int or string), you can add `open Int.Replace_polymorphic_compare` to the top of the file. *) let ( <> ) (x : int) (y : int) = not (Int.equal x y) module Unix = Caml_unix module Sys = Stdlib.Sys module Option = struct include Option module Let_syntax = struct include Option.Let_syntax let ( let* ) = Option.( >>= ) let ( and* ) = Option.both let ( let+ ) = Option.( >>| ) let ( and+ ) = Option.both end end module List = struct include List module Let_syntax = struct include List.Let_syntax let ( let* ) = List.( >>= ) let ( let+ ) = List.( >>| ) end end module Result = struct include Result module Let_syntax = struct include Result.Let_syntax let ( let* ) = Result.( >>= ) let ( let+ ) = Result.( >>| ) end end
OCaml
hhvm/hphp/hack/src/utils/core/local_id.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude module S = struct type t = int * string [@@deriving ord, hash, eq] let compare = compare end include S let ctr = ref 1 let next () = incr ctr; !ctr let to_string x = snd x let pp : Format.formatter -> int * string -> unit = (fun fmt x -> Format.pp_print_string fmt (to_string x)) let to_int x = fst x let get_name x = to_string x let is_user_denotable (lid : t) : bool = let lid_s = to_string lid in (* Allow $foo or $_bar1 but not $#foo or $0bar. *) let local_regexp = Str.regexp "^\\$[a-zA-z_][a-zA-Z0-9_]*$" in Str.string_match local_regexp lid_s 0 || String.equal lid_s "$$" let make_scoped x = (next (), x) let make_unscoped x = (0, x) let make i x = (i, x) let tmp () = let res = next () in (res, "__tmp" ^ string_of_int res) module Set = Caml.Set.Make (S) module Map = struct include WrappedMap.Make (S) let pp pp_data = make_pp (fun fmt id -> Format.fprintf fmt "%a" pp id) pp_data let show pp_data x = Format.asprintf "%a" (pp pp_data) x let hash_fold_t x = make_hash_fold_t S.hash_fold_t x end
OCaml Interface
hhvm/hphp/hack/src/utils/core/local_id.mli
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude (** Used to represent local variables in the named AST. *) module S : sig type t [@@deriving eq] val compare : t -> t -> int end type t = S.t [@@deriving eq, hash] val pp : Format.formatter -> t -> unit val compare : t -> t -> int val to_string : t -> string val to_int : t -> int val get_name : t -> string (** Is this local variable something a user could write, or an internally generated variable? Yes: $foo, $_bar1, $$ No: $#foo, $0bar *) val is_user_denotable : t -> bool (** Make an id for a scoped variable. Return a fresh id every time. This is used to enforce that two locals with the same name but with different scopes have different ids. *) val make_scoped : string -> t (** Make an id for an unscoped variable. Two calls with the same input * string will return the same id. *) val make_unscoped : string -> t val make : int -> string -> t val tmp : unit -> t module Set : module type of Caml.Set.Make (S) module Map : sig include module type of WrappedMap.Make (S) val pp : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit val show : (Format.formatter -> 'a -> unit) -> 'a t -> string val hash_fold_t : (Hash.state -> 'a -> Hash.state) -> Hash.state -> 'a t -> Hash.state end
OCaml
hhvm/hphp/hack/src/utils/core/measure.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (** * The Measure module is primarily useful for debugging. It's particularly * useful for gathering stats about something that happens a lot. Let's say you * have some code like this * * let number_bunnies = count_bunnies () in * * If you want to debug how many bunnies are being counted, you could do * something like * * let number_bunnies = count_bunnies () in * Utils.prerr_endlinef "Num bunnies: %d" number_bunnies; * * but what if this code is called 1000 times? Then you end up with log spew. * Using the Measure module helps with this. You can now do * * let number_bunnies = count_bunnies () in * Measure.sample "num_bunnies" number_bunnies; * * and then later you do * * Measure.print_stats (); * * which will print the number of samples, the total, the average, the * variance, the max and the min. * * Measure can keep track of the distribution of measurements if you give it a * bucket size. Before we collect our measurements, call * * Measure.track_distribution "num_bunnies" ~bucket_size:10 = * ...do logging * Measure.print_distribution (); * * And this will print how many samples fall in the 0-9 bucket, how many fall * into the 10-19 bucket, etc * * A common use case is timing, and there's an easy helper method. Let's say we * wanted to see how long our code takes * * let number_bunnies = Measure.time "count_bunnies_time" (fun () -> * count_bunnies () * ) in * * now when we call print_stats we'll see how fast count_bunnies is and how * much total time we spend counting bunnies. * * Measurements are stored in a stateful way in a record. You can either use a * global record or a local record. * * Using a global record: * Measure.sample "num_bunnies" number_bunnies; * Measure.print_stats (); * * You can push and pop the global record. This is useful if you want to reset * some counters without throwing away that data * * Measure.push_global (); * ...measure stuff * let record = Measure.pop_global () in * Measure.print_stats ~record (); * * Using a local record: * let record = Measure.create () in * Measure.sample ~record "num_bunnies" number_bunnies; * Measure.print_stats ~record (); * * A record does not store the individual measurements, just the aggregate * stats, which are updated online. Records can be serialized in order to be * sent across pipes. *) open Base module FloatMap = WrappedMap.Make (struct type t = float let compare = Float.compare end) type distribution = { bucket_size: float; buckets: float FloatMap.t; } type record_entry = { count: float; mean: float; variance_sum: float; max: float; min: float; distribution: distribution option; } type record_data = record_entry SMap.t type record = record_data ref (* Creates a new empty record *) let create () = ref SMap.empty let global : record list ref = ref [create ()] let serialize record = !record let deserialize data = ref data let new_entry = { count = 0.0; mean = 0.0; variance_sum = 0.0; max = Float.min_value; min = Float.max_value; distribution = None; } let new_distribution ~bucket_size = Some { bucket_size; buckets = FloatMap.empty } let get_record = function | Some record -> record | None -> (match List.hd !global with | Some record -> record | None -> failwith ("No global record available! " ^ "Did you forget to call Measure.push_global?")) (* Measure can track how the values are distributed by creating buckets and * keeping track of how many samples fall into each buckets. It will not track * distribution by default, so call this function to turn it on *) let track_distribution ?record name ~bucket_size = let record = get_record record in let entry = match SMap.find_opt name !record with | None -> new_entry | Some entry -> entry in let entry = { entry with distribution = new_distribution ~bucket_size } in record := SMap.add name entry !record let round_down ~bucket_size value = bucket_size *. Float.round_down (value /. bucket_size) let update_distribution ~weight value = function | None -> None | Some { bucket_size; buckets } -> let bucket = round_down ~bucket_size value in let bucket_count = match FloatMap.find_opt bucket buckets with | None -> weight | Some count -> count +. weight in let buckets = FloatMap.add bucket bucket_count buckets in Some { bucket_size; buckets } let sample ?record ?(weight = 1.0) name value = let record = get_record record in let { count = old_count; mean = old_mean; variance_sum; max; min; distribution; } = match SMap.find_opt name !record with | None -> new_entry | Some entry -> entry in (* Add 1 * weight to the count *) let count = old_count +. weight in let mean = old_mean +. (weight *. (value -. old_mean) /. count) in (* Knuth's online variance approximation algorithm, updated for weights. * Weighted version from http://people.ds.cam.ac.uk/fanf2/hermes/doc/antiforgery/stats.pdf *) let variance_sum = variance_sum +. (weight *. (value -. old_mean) *. (value -. mean)) in let max = Stdlib.max max value in let min = Stdlib.min min value in let distribution = update_distribution ~weight value distribution in let entry = { count; mean; variance_sum; max; min; distribution } in record := SMap.add name entry !record let delete ?record name = let record = get_record record in record := SMap.remove name !record let merge_entries name from into = match (from, into) with | (None, into) -> into | (from, None) -> from | (Some from, into) when Float.equal from.count 0. -> into | (from, Some into) when Float.equal into.count 0. -> from | (Some from, Some into) -> let count = from.count +. into.count in (* Using this algorithm to combine the variance sums * https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm *) (* d = meanB - meanA *) let delta = from.mean -. into.mean in (* mean = meanA + delta * (countB/count) *) let mean = into.mean +. (delta *. from.count /. count) in (* VarSum = VarSumA + VarSumB + delta * delta * countA * countB / count *) let variance_sum = from.variance_sum +. into.variance_sum +. (delta *. delta *. into.count *. from.count /. count) in let max = Stdlib.max from.max into.max in let min = Stdlib.min from.min into.min in let distribution = match (from.distribution, into.distribution) with | (None, into) -> into | (from, None) -> from | (Some { bucket_size = from; _ }, Some { bucket_size = into; _ }) when not (Float.equal from into) -> Printf.ksprintf failwith "Merging buckets for %s failed: bucket sizes %f, %f" name from into | (Some { bucket_size; buckets = from }, Some { buckets = into; _ }) -> let buckets = FloatMap.merge (fun _bucket from_count into_count -> match (from_count, into_count) with | (None, into) -> into | (from, None) -> from | (Some from_count, Some into_count) -> Some (from_count +. into_count)) from into in Some { bucket_size; buckets } in Some { count; mean; variance_sum; max; min; distribution } (* Merges all the samples from "from" into "record". If "record" is omitted * then it uses the global record *) let merge ?record from = let into = get_record record in into := SMap.merge merge_entries !from !into let time (type a) ?record name (f : unit -> a) : a = let record = get_record record in let start_time = Unix.gettimeofday () in let ret = f () in let end_time = Unix.gettimeofday () in sample ~record name (end_time -. start_time); ret let get_helper f ?record name = let record = get_record record in match SMap.find_opt name !record with | None -> None | Some entry -> Some (f entry) let get_sum = get_helper (fun { count; mean; _ } -> count *. mean) let get_mean = get_helper (fun { mean; _ } -> mean) let get_count = get_helper (fun { count; _ } -> count) let get_max = get_helper (fun { max; _ } -> max) let pretty_num f = if Float.(f > 1000000000.0) then Printf.sprintf "%.3fG" (f /. 1000000000.0) else if Float.(f > 1000000.0) then Printf.sprintf "%.3fM" (f /. 1000000.0) else if Float.(f > 1000.0) then Printf.sprintf "%.3fK" (f /. 1000.0) else if Float.(f = Float.round_down f) then Printf.sprintf "%d" (Int.of_float f) else Printf.sprintf "%f" f let print_entry_stats ?record ?print_raw name = let print_raw = Option.value print_raw ~default:Stdio.prerr_endline in let record = get_record record in let prefix = Printf.sprintf "%s stats --" name in match SMap.find_opt name !record with | None | Some { count = 0.0; _ } -> Printf.ksprintf print_raw "%s NO DATA" prefix | Some { count; mean; variance_sum; max; min; distribution = _ } -> let total = count *. mean in let std_dev = Float.sqrt (variance_sum /. count) in Printf.ksprintf print_raw "%s samples: %s, total: %s, avg: %s, stddev: %s, max: %s, min: %s)" prefix (pretty_num count) (pretty_num total) (pretty_num mean) (pretty_num std_dev) (pretty_num max) (pretty_num min) let print_stats ?record ?print_raw () = let record = get_record record in SMap.iter (fun name _ -> print_entry_stats ~record ?print_raw name) !record let stats_to_telemetry ?record () = let record = get_record record in let entry_to_json { count; mean; variance_sum; max; min; distribution = _ } = Telemetry.create () |> Telemetry.float_ ~key:"count" ~value:count |> Telemetry.float_ ~key:"mean" ~value:mean |> Telemetry.float_ ~key:"stddev" ~value:(Float.sqrt (variance_sum /. count)) |> Telemetry.float_ ~key:"min" ~value:min |> Telemetry.float_ ~key:"max" ~value:max in let init = Telemetry.create () in let f key entry acc = Telemetry.object_ acc ~key ~value:(entry_to_json entry) in SMap.fold f !record init let rec print_buckets ~low ~high ~bucket_size buckets = if Float.(low <= high) then ( let count = match FloatMap.find_opt low buckets with | None -> 0.0 | Some count -> count in Stdlib.Printf.eprintf "[%s: %s] " (pretty_num low) (pretty_num count); let low = low +. bucket_size in print_buckets ~low ~high ~bucket_size buckets ) let print_entry_distribution ?record name = let record = get_record record in Stdlib.Printf.eprintf "%s distribution -- " name; match SMap.find_opt name !record with | None | Some { count = 0.0; _ } -> Stdio.prerr_endline "NO DATA" | Some { distribution = None; _ } -> Stdio.prerr_endline "NO DATA (did you forget to call track_distribution?)" | Some { max; min; distribution = Some { bucket_size; buckets }; _ } -> let low = round_down ~bucket_size min in let high = round_down ~bucket_size max in print_buckets ~low ~high ~bucket_size buckets; Stdio.prerr_endline "" let print_distributions ?record () = let record = get_record record in SMap.iter (fun name { distribution; _ } -> match distribution with | None -> () | Some _ -> print_entry_distribution ~record name) !record external rust_push_global : unit -> unit = "hh_measure_push_global" external rust_pop_global : unit -> record_data = "hh_measure_pop_global" let push_global () = global := create () :: !global; rust_push_global () let pop_global () = match !global with | ret :: globals -> global := globals; let rust_record = deserialize (rust_pop_global ()) in merge ~record:ret rust_record; ret | _ -> failwith "Measure.pop_global called with empty stack"
OCaml Interface
hhvm/hphp/hack/src/utils/core/measure.mli
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type record type record_data val create : unit -> record val push_global : unit -> unit val pop_global : unit -> record val serialize : record -> record_data val deserialize : record_data -> record val track_distribution : ?record:record -> string -> bucket_size:float -> unit val sample : ?record:record -> ?weight:float -> string -> float -> unit val time : ?record:record -> string -> (unit -> 'a) -> 'a val delete : ?record:record -> string -> unit val merge : ?record:record -> record -> unit val get_sum : ?record:record -> string -> float option val get_mean : ?record:record -> string -> float option val get_count : ?record:record -> string -> float option val get_max : ?record:record -> string -> float option val print_entry_stats : ?record:record -> ?print_raw:(string -> unit) -> string -> unit val print_stats : ?record:record -> ?print_raw:(string -> unit) -> unit -> unit val stats_to_telemetry : ?record:record -> unit -> Telemetry.t val print_entry_distribution : ?record:record -> string -> unit val print_distributions : ?record:record -> unit -> unit
OCaml
hhvm/hphp/hack/src/utils/core/prim_defs.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. * ** * * "Primitive" definitions; fighting the dependency web, this module is a leaf * on the dependency tree. It may only depend on external libraries and not on * a single module inside the repository. * *) type comment = | CmtLine of string | CmtBlock of string [@@deriving eq, show] let is_line_comment = function | CmtLine _ -> true | _ -> false let string_of_comment = function | CmtLine s | CmtBlock s -> s