language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
OCaml | hhvm/hphp/hack/src/hh_oxidize/rust_type.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
open Utils
type lifetime = string
let lifetime x = x
type t =
| Var of string
| Ref of (lifetime * t)
| Type of {
name: string;
lifetimes: lifetime list;
params: t list;
}
let rust_type_var (v : string) : t = Var v
let rust_ref (lt : lifetime) (inner : t) : t = Ref (lt, inner)
let rust_type (name : string) (lifetimes : lifetime list) (params : t list) : t
=
Type { name; lifetimes; params }
let rust_simple_type (name : string) : t = rust_type name [] []
let is_ref (ty : t) : bool =
match ty with
| Ref _ -> true
| _ -> false
let rec contains_ref (ty : t) : bool =
match ty with
| Var _ -> false
| Ref _ -> true
| Type { name = _; lifetimes = []; params } ->
List.fold ~f:(fun a p -> a || is_ref p || contains_ref p) ~init:false params
| Type _ -> true
let rec rust_type_to_string (ty : t) : string =
match ty with
| Var v -> v
| Ref (lt, t) -> sprintf "&'%s %s" lt (rust_type_to_string t)
| Type { name = "[]"; lifetimes = _; params } ->
sprintf "[%s]" (map_and_concat ~f:rust_type_to_string ~sep:"," params)
| Type { name = "()"; lifetimes = _; params } ->
sprintf "(%s)" (map_and_concat ~f:rust_type_to_string ~sep:"," params)
| Type { name; lifetimes = []; params = [] } -> name
| Type { name; lifetimes; params } ->
sprintf "%s%s" name (type_params_to_string lifetimes params)
and type_params_to_string
?(bound : string = "") (lts : lifetime list) (tys : t list) : string =
let bound =
if String.is_empty bound then
bound
else
":" ^ bound
in
let lts = map_and_concat ~f:(sprintf "'%s") ~sep:"," lts in
let ps =
map_and_concat ~f:(fun ty -> rust_type_to_string ty ^ bound) ~sep:"," tys
in
sprintf
"<%s%s%s>"
lts
(if String.is_empty lts || String.is_empty ps then
""
else
",")
ps
let deref (ty : t) : t =
match ty with
| Ref (_, t) -> t
| _ -> ty
let rec type_name_and_params (ty : t) : string * t list =
match ty with
| Var n -> (n, [])
| Ref (_, r) -> type_name_and_params r
| Type { name; lifetimes = _; params } -> (name, params)
let is_var (ty : t) : bool =
match ty with
| Var _ -> true
| _ -> false |
OCaml Interface | hhvm/hphp/hack/src/hh_oxidize/rust_type.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 lifetime
val lifetime : string -> lifetime
type t
val rust_ref : lifetime -> t -> t
val rust_type : string -> lifetime list -> t list -> t
val rust_simple_type : string -> t
val rust_type_var : string -> t
val is_ref : t -> bool
val is_var : t -> bool
val deref : t -> t
val contains_ref : t -> bool
val rust_type_to_string : t -> string
val type_params_to_string : ?bound:string -> lifetime list -> t list -> string
val type_name_and_params : t -> string * t list |
OCaml | hhvm/hphp/hack/src/hh_oxidize/state.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Core
let curr_module_name_ref = ref None
let curr_module_name () = Option.value_exn !curr_module_name_ref
let with_module_name s f =
try
assert (not (String.is_empty s));
assert (Option.is_none !curr_module_name_ref);
curr_module_name_ref := Some s;
let res = f () in
curr_module_name_ref := None;
res
with
| exn ->
curr_module_name_ref := None;
raise exn
let self_ref = ref None
let self () = Option.value_exn !self_ref
let with_self s f =
try
assert (not (String.is_empty s));
assert (Option.is_none !self_ref);
self_ref := Some s;
let res = f () in
self_ref := None;
res
with
| exn ->
self_ref := None;
raise exn |
OCaml Interface | hhvm/hphp/hack/src/hh_oxidize/state.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(** The name of the module currently being converted. *)
val curr_module_name : unit -> string
(** Run the given function in a context where {!curr_module_name} will return
the given module name. Not re-entrant. *)
val with_module_name : string -> (unit -> 'a) -> 'a
(** The name of the type currently being converted. *)
val self : unit -> string
(** Run the given function in a context where {!self} will return the given type
name. Not re-entrant. *)
val with_self : string -> (unit -> 'a) -> 'a |
OCaml | hhvm/hphp/hack/src/hh_oxidize/stringify.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
open Reordered_argument_collections
open Oxidized_module
let stringify m =
let { extern_uses; glob_uses; aliases; includes; ty_reexports; decls } = m in
let extern_uses =
extern_uses
|> SSet.elements
|> List.map ~f:(sprintf "use %s;")
|> String.concat ~sep:"\n"
in
let uses = "#[allow(unused_imports)]\nuse crate::*;" in
let glob_uses =
glob_uses
|> SSet.elements
|> List.map ~f:(sprintf "pub use %s::*;")
|> String.concat ~sep:"\n"
in
let bound_aliases =
aliases
|> List.map ~f:snd
|> List.fold ~init:SSet.empty ~f:(fun bound alias -> SSet.add bound alias)
in
let aliases =
aliases
|> List.map ~f:(fun (m, a) ->
(* Annoyingly, we can't seem to write an alias or re-export for a
module imported via the glob-import in `uses`. If the crate
exports a module `map`, we and write in foo.rs:
use crate::*;
pub use map;
Then other modules will be unable to `use foo::map;`. It is as if
`use crate::*;` introduces an implicit private submodule named
`map` (which is an alias to `crate::map`), and while publicly
exporting it (via `pub use map;`) is apparently allowed, it is not
actually visible to other modules. We must write instead:
use crate::*;
pub use crate::map;
We cannot prefix every alias with `crate::`, however, since we
would like to allow referencing aliases in other aliases within
the same file. For instance, if we have this OCaml:
mod F = Foo
mod M = F.Map
We ought to generate this Rust:
use crate::*;
pub use crate::foo as f;
pub use f::map as m;
So we do not add the `crate::` prefix when referring to an alias
bound in the same file. *)
let root_module = String.split m ~on:':' |> List.hd_exn in
if
SSet.mem bound_aliases root_module
|| String.equal root_module "crate"
then
sprintf "pub use %s as %s;" m a
else
sprintf "pub use crate::%s as %s;" m a)
|> String.concat ~sep:"\n"
in
let includes =
includes
|> SSet.elements
|> List.map ~f:(fun m -> sprintf "pub use %s::*;" m)
|> String.concat ~sep:"\n"
in
let ty_reexports =
ty_reexports
|> List.map ~f:(sprintf "pub use %s;")
|> List.dedup_and_sort ~compare:String.compare
|> String.concat ~sep:"\n"
in
let decls = decls |> List.rev_map ~f:snd |> String.concat ~sep:"\n\n" in
sprintf
"%s\n\n%s\n\n%s\n\n%s\n\n%s%s\n\n%s\n"
extern_uses
uses
glob_uses
aliases
includes
ty_reexports
decls |
OCaml | hhvm/hphp/hack/src/hh_oxidize/utils.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
open Reordered_argument_collections
module Unix = Caml_unix
(** HACK: Raised when we encounter a construct in a type declaration which we
have chosen not to handle (because it occurs in a type declaration which we
do not need to convert at this time). *)
exception Skip_type_decl of string
let log_indent = ref 0
let log fmt =
ksprintf (Printf.eprintf "%s%s\n%!" (String.make !log_indent ' ')) fmt
let with_log_indent f =
let old_indent = !log_indent in
try
log_indent := old_indent + 2;
let result = f () in
log_indent := old_indent;
result
with
| exn ->
log_indent := old_indent;
raise exn
let with_tempfile f =
Random.self_init ();
let name = "hh_oxidize_" ^ string_of_int (Random.int Int.max_value) in
let temp_file = Filename.concat "/tmp" name in
try
f temp_file;
Unix.unlink temp_file
with
| exn ->
(try Unix.unlink temp_file with
| _ -> ());
raise exn
let rust_keywords =
SSet.of_list
[
"as";
"break";
"const";
"continue";
"crate";
"else";
"enum";
"extern";
"false";
"fn";
"for";
"if";
"impl";
"in";
"let";
"loop";
"match";
"mod";
"move";
"mut";
"pub";
"ref";
"return";
"self";
"Self";
"static";
"struct";
"super";
"trait";
"true";
"type";
"unsafe";
"use";
"where";
"while";
"dyn";
"abstract";
"become";
"box";
"do";
"final";
"macro";
"override";
"priv";
"typeof";
"unsized";
"virtual";
"yield";
"async";
"await";
"try";
"union";
]
let map_and_concat ?sep l ~f = List.map l ~f |> String.concat ?sep
let common_prefix a b =
let len = min (String.length a) (String.length b) in
let rec aux i =
if i = len || not (Char.equal a.[i] b.[i]) then
String.sub a ~pos:0 ~len:i
else
aux (i + 1)
in
aux 0
let common_prefix_of_list strs =
match strs with
| []
| [_] ->
""
| _ -> List.reduce_exn strs ~f:common_prefix
let split_on_uppercase str =
let len = String.length str in
let rec loop acc last_pos pos =
if pos = -1 then
String.sub str ~pos:0 ~len:last_pos :: acc
else if Char.is_uppercase str.[pos] then
let sub_str = String.sub str ~pos ~len:(last_pos - pos) in
loop (sub_str :: acc) pos (pos - 1)
else
loop acc last_pos (pos - 1)
in
loop [] len (len - 1)
let add_trailing_underscore original_name name =
if
Char.equal original_name.[String.length original_name - 1] '_'
|| SSet.mem rust_keywords name
then
name ^ "_"
else
name
let convert_type_name name =
name
|> String.split ~on:'_'
|> map_and_concat ~f:String.capitalize
|> add_trailing_underscore name
let convert_module_name name =
name
|> String.uncapitalize
|> split_on_uppercase
|> map_and_concat ~f:String.uncapitalize ~sep:"_"
|> add_trailing_underscore name
let convert_field_name name = add_trailing_underscore name name |
OCaml | hhvm/hphp/hack/src/hh_quickfix_lint/hh_quickfix_lint.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module JSON = Hh_json
type patch = {
path: string;
start_offset: int;
line: int;
column: int;
width: int;
original: string;
replacement: string;
}
type error_count = {
overlapping: int;
original_not_found: int;
}
type input =
| Stdin
| File of string
type options = {
verbose: bool;
overwrite: bool;
input: input;
}
let log_dropped ~verbose error_count patch =
if verbose then
Printf.eprintf
"An overlapping patch is dropped %s:%d:%d\n"
patch.path
patch.line
patch.column;
{ error_count with overlapping = error_count.overlapping + 1 }
let log_original_not_found ~verbose error_count patch =
if verbose then
Printf.eprintf
"Could not find the original pattern at %s:%d:%d.\n"
patch.path
patch.line
patch.column;
{ error_count with original_not_found = error_count.original_not_found + 1 }
let usage_str =
let str =
Format.sprintf
"usage: %s [--input-file FILE] [--overwrite] [--verbose]\n"
Sys.argv.(0)
in
let str =
Format.sprintf
"%s The input file can be a JSON array of lints or an object with an `errors` field containing that array. \n"
str
in
str
let usage_err () =
Printf.eprintf "%s" usage_str;
exit 1
let path = "path"
let start_offset = "start_offset"
let line = "line"
let start = "start"
let width = "width"
let original = "original"
let replacement = "replacement"
let field_type_err field ty =
Printf.eprintf
"There is an object with a '%s' field that is not an %s\n\n"
field
ty;
usage_err ()
let int_field_opt = function
| JSON.JSON_Number n -> begin
try Some (Int.of_string n) with
| _ -> None
end
| _ -> None
let int_field field json =
match int_field_opt json with
| Some value -> value
| None -> field_type_err field "int"
let string_field_opt = function
| JSON.JSON_String n -> Some n
| _ -> None
let string_field field json =
match string_field_opt json with
| Some str -> str
| None -> field_type_err field "string"
let find_field_value obj target =
let value_opt =
List.find_map obj ~f:(function
| (field, value) when String.equal field target -> Some value
| _ -> None)
in
match value_opt with
| Some value -> value
| None ->
Printf.eprintf
"Input JSON has an object with a missing '%s' field\n\n"
target;
usage_err ()
let patch_of_object json =
let obj =
match json with
| JSON.JSON_Object obj -> obj
| _ ->
Printf.eprintf "Input JSON array has a non-object.\n\n";
usage_err ()
in
let find_field_value = find_field_value obj in
let path = find_field_value path |> string_field path in
let line = find_field_value line |> int_field line in
let column = find_field_value start |> int_field start in
let start_offset_opt = find_field_value start_offset |> int_field_opt in
let width_opt = find_field_value width |> int_field_opt in
let original_opt = find_field_value original |> string_field_opt in
let replacement_opt = find_field_value replacement |> string_field_opt in
match (start_offset_opt, width_opt, original_opt, replacement_opt) with
| (Some start_offset, Some width, Some original, Some replacement) ->
Some { path; start_offset; line; column; width; original; replacement }
| _ -> None
let sanitise_and_extract_patches json =
let err () =
Printf.eprintf
"Input JSON is not an array or an object with 'errors' field.\n\n";
usage_err ()
in
let jsonl =
match json with
| JSON.JSON_Object fields ->
let errors_opt =
List.find fields ~f:(fun (field, _) -> String.equal field "errors")
in
begin
match errors_opt with
| Some (_, JSON.JSON_Array jsonl) -> jsonl
| _ -> err ()
end
| JSON.JSON_Array jsonl -> jsonl
| _ -> err ()
in
List.filter_map jsonl ~f:patch_of_object
let apply_patch
~verbose
(error_count, contents)
({ start_offset; original; replacement; _ } as patch) =
match String.substr_index contents ~pos:start_offset ~pattern:original with
| Some n when n = start_offset ->
let contents =
String.substr_replace_first
contents
~pos:start_offset
~pattern:original
~with_:replacement
in
(error_count, contents)
| _ ->
let error_count = log_original_not_found ~verbose error_count patch in
(error_count, contents)
let apply_patch_group ~verbose error_count contents group =
let group =
let compare a b = Int.compare a.start_offset b.start_offset in
List.sort ~compare group
in
let rec drop_super_patches acc error_count = function
| patch :: patch' :: patches ->
if patch'.start_offset <= patch.start_offset + patch.width then begin
let error_count = log_dropped ~verbose error_count patch in
drop_super_patches acc error_count (patch' :: patches)
end else
drop_super_patches (patch :: acc) error_count (patch' :: patches)
| [patch] -> (error_count, patch :: acc)
| [] -> (error_count, acc)
in
let (error_count, group) = drop_super_patches [] error_count group in
List.fold ~f:(apply_patch ~verbose) ~init:(error_count, contents) group
let parse_and_validate_options () =
let verbose = ref false in
let overwrite = ref false in
let input = ref Stdin in
let rec process = function
| "--verbose" :: rest ->
verbose := true;
process rest
| "--overwrite" :: rest ->
overwrite := true;
process rest
| "--input-file" :: path :: rest ->
input := File path;
process rest
| arg :: _ ->
Printf.eprintf "Unrecognised CLI argument %s\n\n" arg;
usage_err ()
| [] -> ()
in
process (List.tl_exn @@ Array.to_list Sys.argv);
{ verbose = !verbose; overwrite = !overwrite; input = !input }
let output ~overwrite path contents =
if overwrite then begin
let open Out_channel in
with_file path ~f:(fun fd -> output_string fd contents)
end else begin
Format.printf "//// %s\n" path;
Format.printf "%s\n\n" contents
end
let () =
let args = parse_and_validate_options () in
let json_str =
let open In_channel in
match args.input with
| Stdin -> input_all stdin
| File json_path -> with_file json_path ~f:input_all
in
let json = JSON.json_of_string json_str in
let patches = sanitise_and_extract_patches json in
let patch_groups =
patches
|> List.sort ~compare:(fun a b -> String.compare a.path b.path)
|> List.group ~break:(fun a b -> not @@ String.equal a.path b.path)
in
let error_count = { overlapping = 0; original_not_found = 0 } in
let error_count =
List.fold patch_groups ~init:error_count ~f:(fun error_count group ->
let path = (List.hd_exn group).path in
let open In_channel in
let (error_count, patched_contents) =
with_file path ~f:(fun fd ->
let contents = input_all fd in
apply_patch_group ~verbose:args.verbose error_count contents group)
in
output ~overwrite:args.overwrite path patched_contents;
error_count)
in
Format.printf
"There were input %d patches for %d files.\n"
(List.length patches)
(List.length patch_groups);
Format.printf
"Dropped patch count: %d (%d overlapping, %d original not found)\n"
(error_count.overlapping + error_count.original_not_found)
error_count.overlapping
error_count.original_not_found |
OCaml Interface | hhvm/hphp/hack/src/hh_quickfix_lint/hh_quickfix_lint.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* This interface file is for a module containing an executable with no public
facing API. It is used for documentation and to make sure deadcode is caught
by the compiler. *)
(* Given `hh --lint --json` output, this binary applies the quickfixes found in
lints. The input is supplied either through `STDIN` or via a JSON file through
the `--input-file` flag. In addition to handling the standard `hh --lint
--json` output, the tool can also handle a JSON array of lints (which is
equivalent to accessing the `"errors"` field of the `hh --lint --json`
output).
By default, the file output with the quickfix applied is printed to STDOUT.
If the `--overwrite` flag is set, then the output overwrites the contents of
file with the lint.
The tool also takes a `--verbose` flag which prints out the positions for
dropped lints for debugging purposes.
LIMITATIONS:
Currently, the tool cannot handle nested patches and drops the enclosing
patch on the floor. However, the tool will report if the patch
was dropped and for what reason.
For reliability reasons, we double check that the "original" field is found
at the starting offset of the quickfix. If not, we again drop the patch on
the floor. *) |
hhvm/hphp/hack/src/hips/dune | (library
(name hips)
(wrapped false)
(flags
(:standard -linkall))
(modules
hips_solver
hips_types)
(libraries
core_kernel
ast)
(preprocess
(pps visitors.ppx ppx_deriving.std))
) |
|
OCaml | hhvm/hphp/hack/src/hips/hips_solver.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Hips_types
module Inter (I : Intra) = struct
open Hips_types
type inter_constraint = I.inter_constraint
type intra_constraint = I.intra_constraint
type any_constraint = I.any_constraint
type solution =
| Divergent of any_constraint list SMap.t
| Convergent of any_constraint list SMap.t
let equiv
(constraint_map_1 : any_constraint list SMap.t)
(constraint_map_2 : any_constraint list SMap.t) : bool =
SMap.equal I.equiv constraint_map_1 constraint_map_2
let debug_constraint_map label m =
Format.printf "%s:\n" label;
m
|> SMap.iter (fun key cs ->
Format.printf " key %s:\n" key;
cs
|> List.iter ~f:(fun c ->
Format.printf " %s\n" @@ I.debug_any_constraint c));
m
let substitute_inter_any_backwards
(inter_constr_1 : inter_constraint) (constr : any_constraint) :
any_constraint option =
match constr with
| Intra intra_constr ->
Option.map
~f:(fun x -> Intra x)
(I.substitute_inter_intra_backwards inter_constr_1 intra_constr)
| Inter _inter_constr_2 -> None
let substitute_inter_any_forwards
(inter_constr_1 : inter_constraint) (constr : any_constraint) :
any_constraint option =
match constr with
| Intra intra_constr ->
Option.map
~f:(fun x -> Intra x)
(I.substitute_inter_intra_forwards inter_constr_1 intra_constr)
| Inter _ -> None
let string_of_const_ident_ent
({ class_name_opt; const_name; _ } : constant_identifier_entity) : string
=
match class_name_opt with
| Some class_name -> class_name ^ "::" ^ const_name
| None -> const_name
let is_const_initial_constr = function
| Inter (ConstantInitial _) -> true
| _ -> false
let is_const_constr = function
| Inter (Constant _) -> true
| _ -> false
let is_class_extends_constr = function
| Inter (ClassExtends _) -> true
| _ -> false
let const_constraint_of (constr_list : any_constraint list) :
any_constraint option =
List.find ~f:is_const_constr constr_list
let const_initial_ent_of (constr_list : any_constraint list) :
I.intra_entity option =
match List.find ~f:is_const_initial_constr constr_list with
| Some (Inter (ConstantInitial const_initial_ent)) -> Some const_initial_ent
| _ -> None
let find_const_in_ancestors ~constraint_map ~const_name class_name :
(any_constraint list * string) option =
let rec aux class_name =
let open Option.Monad_infix in
SMap.find_opt class_name constraint_map
>>= List.find ~f:is_class_extends_constr
>>= function
| Inter (ClassExtends class_identifier_ent) ->
let new_class_name = snd class_identifier_ent in
let new_const_ident_string = new_class_name ^ "::" ^ const_name in
(match SMap.find_opt new_const_ident_string constraint_map with
| Some constr_list_at_const_ent ->
Some (constr_list_at_const_ent, new_const_ident_string)
| None -> aux new_class_name)
| _ -> None
in
aux class_name
let find_const_in_current_class
(qualified_name : string)
(base_constraint_map : any_constraint list SMap.t) :
(any_constraint list * string) option =
match SMap.find_opt qualified_name base_constraint_map with
| Some constr_list -> Some (constr_list, qualified_name)
| None -> None
let find_const
({ class_name_opt; const_name; _ } as ident_ent :
constant_identifier_entity)
(constraint_map : any_constraint list SMap.t) :
(any_constraint list * string) option =
let current_class_qualified_name = string_of_const_ident_ent ident_ent in
let current_class_const =
find_const_in_current_class current_class_qualified_name constraint_map
in
if Option.is_some current_class_const then
current_class_const
else
Option.bind
class_name_opt
~f:(find_const_in_ancestors ~constraint_map ~const_name)
let propagate_const_initializer_and_identifier_constraints
~current_func_constr_list
~current_func_id
(ident_ent : constant_identifier_entity)
(new_const_ident_string : string)
(constr_list_at_const_ent : any_constraint list)
(input_constr_list_map : any_constraint list SMap.t) :
any_constraint list SMap.t =
let to_append_at_current_func_opt =
Option.map
(const_initial_ent_of constr_list_at_const_ent)
~f:(fun const_initial_ent ->
List.filter_map
constr_list_at_const_ent
~f:
(substitute_inter_any_backwards
(ConstantInitial const_initial_ent)))
in
let to_append_at_const =
List.filter_map
current_func_constr_list
~f:(substitute_inter_any_backwards (ConstantIdentifier ident_ent))
in
input_constr_list_map
|> SMap.update
current_func_id
(Option.map2 to_append_at_current_func_opt ~f:(fun to_append x ->
x @ to_append))
|> SMap.update
new_const_ident_string
(Option.map ~f:(fun x -> x @ to_append_at_const))
let propagate_const_inheritance_constraints
(constr_list_at_const_ent : any_constraint list)
(new_const_ident_string : string)
(input_constr_list_map : any_constraint list SMap.t) :
any_constraint list SMap.t =
match const_constraint_of constr_list_at_const_ent with
| Some (Inter (Constant const_ent)) ->
let to_append_at_const_ident =
List.filter_map
constr_list_at_const_ent
~f:(substitute_inter_any_backwards (Constant const_ent))
in
input_constr_list_map
|> SMap.update
new_const_ident_string
(Option.map ~f:(fun x -> x @ to_append_at_const_ident))
| _ -> input_constr_list_map
(**
example: `"C::DICT_NAME" -> Some ("C", "DICT_NAME")`
This is silly, but saves memory compared to storing more information in `const` *)
let split_const_name (qualified_name : string) : (string * string) option =
let matches = Caml.String.split_on_char ':' qualified_name in
match matches with
| [class_name; _; const_name] -> Some (class_name, const_name)
| _ -> None
let find_matching_param_like constr_list_at f f_idx : param_like_entity option
=
let open Option.Monad_infix in
( constr_list_at >>= fun constr_list_at_ ->
List.find
~f:(function
| Inter (ParamLike ((_, g), g_idx)) ->
String.equal f g && equal_param_like_index f_idx g_idx
| _ -> false)
constr_list_at_ )
>>= function
| Inter (ParamLike param_ent) -> Some param_ent
| _ -> None
let substitute (constraint_map : any_constraint list SMap.t) :
any_constraint list SMap.t =
let open Option.Monad_infix in
let substitute_any_list
(current_func_id : string)
(current_func_constr_list : any_constraint list)
(input_constr_list_map2 : any_constraint list SMap.t) :
any_constraint list SMap.t =
let substitute_any
(input_constr_list_map : any_constraint list SMap.t)
(constr : any_constraint) : any_constraint list SMap.t =
match constr with
| Intra _ -> input_constr_list_map
| Inter inter_constr ->
(match inter_constr with
| ArgLike (((_, f), f_idx), intra_ent) ->
let constr_list_at = SMap.find_opt f constraint_map in
let param_constr_opt : inter_constraint option =
find_matching_param_like constr_list_at f f_idx
>>| fun param_ent -> ArgLike (param_ent, intra_ent)
in
let constr_list_backwards =
match constr_list_at with
| None -> []
| Some constr_list_at_ ->
List.filter_map
constr_list_at_
~f:(substitute_inter_any_backwards inter_constr)
in
let constr_list_forwards =
param_constr_opt
>>| (fun param_constr ->
List.filter_map
current_func_constr_list
~f:(substitute_inter_any_forwards param_constr))
|> Option.value ~default:[]
in
input_constr_list_map
|> SMap.update f (Option.map ~f:(fun x -> x @ constr_list_forwards))
|> SMap.update
current_func_id
(Option.map ~f:(fun x -> x @ constr_list_backwards))
| ConstantIdentifier ident_ent ->
(match find_const ident_ent constraint_map with
| Some (constr_list_at_const_ent, new_const_ident_string) ->
propagate_const_initializer_and_identifier_constraints
~current_func_constr_list
~current_func_id
ident_ent
new_const_ident_string
constr_list_at_const_ent
input_constr_list_map
| None -> input_constr_list_map)
| Constant (_, qualified_name) ->
let open Option.Let_syntax in
Option.value ~default:input_constr_list_map
@@ let* (class_name, const_name) =
split_const_name qualified_name
in
let* (constr_list_at_const, _) =
find_const_in_current_class
qualified_name
input_constr_list_map
in
let+ (_, ancestor_const_name) =
find_const_in_ancestors
~constraint_map:input_constr_list_map
~const_name
class_name
in
input_constr_list_map
|> propagate_const_inheritance_constraints
constr_list_at_const
ancestor_const_name
| _ -> input_constr_list_map)
in
List.fold_left
~f:substitute_any
~init:input_constr_list_map2
current_func_constr_list
in
SMap.fold substitute_any_list constraint_map constraint_map
(** Modifies input_constr_map by adding:
i) to the constraints at the key corresponding to the constant const_ent
in constr_list_at_const_ent: a subset constraint between constant identifier
ident_ent and the constant const_ent;
ii) to the constraints at the key f: a subset constraint between the constant
initializer const_initial_ent in constr_list_at_const_ent and the constant
identifier ident_ent. *)
let add_const_identifier_and_initializer_subset_constraints
(constr_list_at_const_ent : any_constraint list)
(ident_ent : constant_identifier_entity)
(input_constr_map : any_constraint list SMap.t)
(f : string) : any_constraint list SMap.t =
let const_constraint_opt = const_constraint_of constr_list_at_const_ent in
let const_initial_constraint_opt =
List.find ~f:is_const_initial_constr constr_list_at_const_ent
in
let append_using_ents const_ent const_initial_ent =
let subset_any_constr =
Intra
(I.subsets
(I.embed_entity (ConstantIdentifier ident_ent))
(I.embed_entity (Constant const_ent)))
in
let subset_initial_any_constr =
Intra
(I.subsets
const_initial_ent
(I.embed_entity (ConstantIdentifier ident_ent)))
in
let append_opt = Option.map ~f:(fun x -> subset_any_constr :: x) in
let append_initial_opt =
Option.map ~f:(fun x -> subset_initial_any_constr :: x)
in
SMap.update (snd const_ent) append_opt input_constr_map
|> SMap.update f append_initial_opt
in
match Option.both const_constraint_opt const_initial_constraint_opt with
| None -> input_constr_map
| Some
(Inter (Constant const_ent), Inter (ConstantInitial const_initial_ent))
->
append_using_ents const_ent const_initial_ent
| _ -> failwith "should be unreachable"
let add_const_identifier_constraints ~key constraint_map const_identifier =
match find_const const_identifier constraint_map with
| Some (constr_list_at_const_ent, _) ->
add_const_identifier_and_initializer_subset_constraints
constr_list_at_const_ent
const_identifier
constraint_map
key
| None -> constraint_map
let add_const_inheritance_constraints
~(ent1_constraints : any_constraint list)
~(ent2_constraints : any_constraint list)
(input_constr_map : any_constraint list SMap.t) :
any_constraint list SMap.t =
let const_constraint_1 = const_constraint_of ent1_constraints in
let const_constraint_2 = const_constraint_of ent2_constraints in
let append_using_ents const_ent_1 const_ent_2 =
let subset_any_constr =
Intra
(I.subsets
(I.embed_entity (Constant const_ent_1))
(I.embed_entity (Constant const_ent_2)))
in
let append_opt = Option.map ~f:(fun x -> subset_any_constr :: x) in
SMap.update (snd const_ent_2) append_opt input_constr_map
in
match Option.both const_constraint_1 const_constraint_2 with
| Some (Inter (Constant const_ent_1), Inter (Constant const_ent_2)) ->
append_using_ents const_ent_1 const_ent_2
| None -> input_constr_map
| _ -> failwith "should be unreachable"
(** Add subset constraints for constant overrides.
```
% Datalog:
subset(constant1, constant2) :- overrides(constant1, constant2).
overrides(constant1, constant2) :-
member_of(constant1, class1),
inherits_from(class1, class2),
constant_name(constant1) == constant_name(constant2).
```
*)
let add_const_constraints constraint_map const =
let open Option.Monad_infix in
split_const_name (snd const)
>>= (fun (class_name, const_name) ->
let current_class_const =
find_const_in_current_class (snd const) constraint_map
in
let ancestor_class_const =
find_const_in_ancestors ~constraint_map ~const_name class_name
in
Option.both current_class_const ancestor_class_const)
>>| (fun ((constr_list_in_class, _), (constr_list_in_ancestor, _)) ->
add_const_inheritance_constraints
~ent1_constraints:constr_list_in_class
~ent2_constraints:constr_list_in_ancestor
constraint_map)
|> Option.value ~default:constraint_map
(* add new interprocedural constraints by examining the cross-join of all constraints *)
let close (constraint_map : any_constraint list SMap.t) :
any_constraint list SMap.t =
let add_constraints_for_key
(key : string)
(constr_list : any_constraint list)
(constraint_map : any_constraint list SMap.t) :
any_constraint list SMap.t =
let add_constraints_for_constraint
(constraint_map : any_constraint list SMap.t)
(constr : any_constraint) : any_constraint list SMap.t =
match constr with
| Inter (ConstantIdentifier const_identifier) ->
add_const_identifier_constraints ~key constraint_map const_identifier
| Inter (Constant const) -> add_const_constraints constraint_map const
| _ -> constraint_map
in
List.fold_left
~f:add_constraints_for_constraint
~init:constraint_map
constr_list
in
SMap.fold add_constraints_for_key constraint_map constraint_map
let find_entities_to_widen (constraint_map : any_constraint list SMap.t) :
I.intra_entity list SMap.t =
let find_in_inter_constraint = function
| ArgLike (((_, f), f_idx), intra_ent) ->
let constr_list_at = SMap.find_opt f constraint_map in
begin
match find_matching_param_like constr_list_at f f_idx with
| Some _ -> None
| None -> Some intra_ent
end
| ConstantIdentifier _ ->
(*TODO(T139295663) invalidation here. Hard with current handling of constants. *)
None
| Constant _
| ClassExtends _ ->
(* TODO(T139295663): This unsoundness can likely be fixed with folded decls *)
None
(* safe to ignore these cases *)
| ConstantInitial _
| ParamLike _ ->
None
in
let find_in_any_constraint = function
| Intra _ -> None
| Inter c -> find_in_inter_constraint c
in
constraint_map |> SMap.map (List.filter_map ~f:find_in_any_constraint)
(** see `widen` in Hips_types.mli for docs *)
let widen constraint_map =
let to_widen_by_id = find_entities_to_widen constraint_map in
let append_widened id existing_constraints =
match SMap.find_opt id to_widen_by_id with
| Some entities_to_widen ->
entities_to_widen
|> I.widen
|> List.map ~f:(fun intra_constraint -> Intra intra_constraint)
|> List.rev_append existing_constraints
| None -> existing_constraints
in
constraint_map |> SMap.mapi append_widened
let analyse (base_constraint_map : any_constraint list SMap.t) ~verbose :
solution =
let debug =
if verbose then
debug_constraint_map
else
fun _ m ->
m
in
let deduce_any_list (any_constraint_list : any_constraint list) :
any_constraint list =
let destruct (any_constraint_list : any_constraint list) :
intra_constraint list * inter_constraint list =
let f (any_constraint : any_constraint) :
(intra_constraint, inter_constraint) Base__.Either0.t =
match any_constraint with
| Intra intra_constr -> First intra_constr
| Inter inter_constr -> Second inter_constr
in
List.partition_map ~f any_constraint_list
in
let construct
((intra_constraint_list, inter_constraint_list) :
intra_constraint list * inter_constraint list) : any_constraint list
=
List.map
~f:(fun intra_constr -> Intra intra_constr)
intra_constraint_list
@ List.map
~f:(fun inter_constr -> Inter inter_constr)
inter_constraint_list
in
destruct any_constraint_list
|> (fun (intra_constr_list, inter_constr_list) ->
(I.deduce intra_constr_list, inter_constr_list))
|> construct
in
let rec analyse_help
(completed_iterations : int)
(argument_constraint_map : any_constraint list SMap.t) : solution =
if verbose then Format.printf "\n=== iteration: %d\n" completed_iterations;
if Int.equal completed_iterations I.max_iteration then
Divergent argument_constraint_map
else
let substituted_constraint_map =
debug "substituted_constraint_map"
@@ substitute argument_constraint_map
in
let deduced_constraint_map =
debug "deduced_constraint_map"
@@ SMap.map deduce_any_list substituted_constraint_map
in
let no_dupl_deduced_constraint_map =
SMap.map
(List.dedup_and_sort ~compare:I.compare_any_constraint)
deduced_constraint_map
in
let no_dupl_argument_constraint_map =
SMap.map
(List.dedup_and_sort ~compare:I.compare_any_constraint)
argument_constraint_map
in
if equiv no_dupl_argument_constraint_map no_dupl_deduced_constraint_map
then
Convergent no_dupl_argument_constraint_map
else
analyse_help (completed_iterations + 1) no_dupl_deduced_constraint_map
in
let base_constraint_map =
base_constraint_map
|> close
|> debug "closed base_constraint_map"
|> widen
|> debug "widened base_constraint_map"
in
analyse_help 0 base_constraint_map
end |
OCaml Interface | hhvm/hphp/hack/src/hips/hips_solver.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hips_types
(** Generates an inter-procedural constraint solver from domain-specific
intra-procedural data. *)
module Inter (I : Intra) : sig
(** Output type of analyse: applying substitution repeatedly either
converges, or diverges *)
type solution =
| Divergent of I.any_constraint list SMap.t
| Convergent of I.any_constraint list SMap.t
(** The call "analyse base" repeatedly applies constraint substitution with
respect to "base" postcomposed with constraint deduction, beginning with
"base" itself. It either finds a fixpoint, in which case it outputs
"Convergent fp", or terminates early, in which case it outputs
"Divergent p". *)
val analyse : I.any_constraint list SMap.t -> verbose:bool -> solution
end |
OCaml | hhvm/hphp/hack/src/hips/hips_types.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module A = Ast_defs
type const_entity = A.id [@@deriving ord, show]
type constant_identifier_entity = {
ident_pos: A.pos;
class_name_opt: string option;
const_name: string;
}
[@@deriving ord, show { with_path = false }]
type param_like_index =
| Index of int
| Return
[@@deriving eq, ord, show { with_path = false }]
type param_like_entity = A.id * param_like_index [@@deriving ord, show]
type class_identifier_entity = A.id [@@deriving ord, show]
type entity =
| ParamLike of param_like_entity
| Constant of const_entity
| ConstantIdentifier of constant_identifier_entity
[@@deriving ord, show { with_path = false }]
type ('a, 'b) any_constraint_ =
| Intra of 'a
| Inter of 'b
[@@deriving ord]
type 'a inter_constraint_ =
| ArgLike of param_like_entity * 'a
| Constant of const_entity
| ConstantInitial of 'a
| ConstantIdentifier of constant_identifier_entity
| ParamLike of param_like_entity
| ClassExtends of class_identifier_entity
[@@deriving ord]
module type Intra = sig
type intra_entity
type intra_constraint
type inter_constraint = intra_entity inter_constraint_
type any_constraint = (intra_constraint, inter_constraint) any_constraint_
[@@deriving ord]
val debug_any_constraint : any_constraint -> string
val is_same_entity : intra_entity -> intra_entity -> bool
val embed_entity : entity -> intra_entity
val max_iteration : int
val equiv : any_constraint list -> any_constraint list -> bool
val widen : intra_entity list -> intra_constraint list
val substitute_inter_intra_backwards :
inter_constraint -> intra_constraint -> intra_constraint option
val substitute_inter_intra_forwards :
inter_constraint -> intra_constraint -> intra_constraint option
val deduce : intra_constraint list -> intra_constraint list
val subsets : intra_entity -> intra_entity -> intra_constraint
end
let equal_entity (ent1 : entity) (ent2 : entity) : bool =
match (ent1, ent2) with
| (ParamLike ((_, f_id), f_idx), ParamLike ((_, g_id), g_idx)) ->
String.equal f_id g_id && equal_param_like_index f_idx g_idx
| (Constant (pos1, id1), Constant (pos2, id2)) ->
A.equal_pos pos1 pos2 && String.equal id1 id2
| ( ConstantIdentifier
{
ident_pos = pos1;
class_name_opt = Some class_name1;
const_name = constant_name1;
},
ConstantIdentifier
{
ident_pos = pos2;
class_name_opt = Some class_name2;
const_name = constant_name2;
} ) ->
A.equal_pos pos1 pos2
&& String.equal class_name1 class_name2
&& String.equal constant_name1 constant_name2
| ( ConstantIdentifier
{ ident_pos = pos1; class_name_opt = None; const_name = constant_name1 },
ConstantIdentifier
{ ident_pos = pos2; class_name_opt = None; const_name = constant_name2 }
) ->
A.equal_pos pos1 pos2 && String.equal constant_name1 constant_name2
| _ -> false |
OCaml Interface | hhvm/hphp/hack/src/hips/hips_types.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module A = Ast_defs
type const_entity = A.id [@@deriving ord, show]
type constant_identifier_entity = {
ident_pos: A.pos;
class_name_opt: string option;
const_name: string;
}
[@@deriving ord, show { with_path = false }]
type param_like_index =
| Index of int
| Return
[@@deriving eq, ord, show { with_path = false }]
type param_like_entity = A.id * param_like_index [@@deriving ord, show]
type class_identifier_entity = A.id [@@deriving ord, show]
type entity =
| ParamLike of param_like_entity
| Constant of const_entity
| ConstantIdentifier of constant_identifier_entity
[@@deriving ord, show]
type ('a, 'b) any_constraint_ =
| Intra of 'a
| Inter of 'b
[@@deriving ord]
type 'a inter_constraint_ =
| ArgLike of param_like_entity * 'a
(** Captures function calls, e.g. "ArgLike (f, Index 0, p)" denotes a call of "f" with
"p" as first argument, "f(p, ...)". "ArgLike(f, Return, p)" denotes the return value of "f" *)
| Constant of const_entity
(** Captures global constant entities, e.g. "const dict<string, mixed> DICT". *)
| ConstantInitial of 'a
(** Captures the initial entity of a global constant, e.g. the right hand side of
"const dict<string, mixed> DICT = dict['a' => 42];". *)
| ConstantIdentifier of constant_identifier_entity
(** Captures global and class constant identifier entities e.g. the "DICT" part in
"DICT['b'];", which identifies a global constant "const dict<string, mixed>
DICT". For class constants, the optional string specifies the class name. *)
| ParamLike of param_like_entity
(** Captures function parameter entities and return values, e.g. "$x", "$y", and "$r"
in "function $r = f(int $x, bool $y)". This constraint is used for function call constraint
substitution, where it interacts with "ArgLike of param_like_entity * 'a". *)
| ClassExtends of class_identifier_entity
(** Captures single class inheritance, e.g. the position and the name "C" in
"class D extends C" *)
[@@deriving ord]
(** Domain-specific intra-procedural data that can be used to instantiate an
inter-procedural constraint solver. Examples we have in mind include the
shape-like-dict analysis and the detection of function upcasts to dynamic. *)
module type Intra = sig
(** This entity type models "p" in inter-procedural constraints of the shape
"ArgLike("f", 0, p)" and "Ret("f", p)" *)
type intra_entity
(** Intra-procedural constraint type, e.g. Has_static_key(p, 'a', int) *)
type intra_constraint
(** Inter-procedural constraints type, e.g. "ArgLike("f", 1, q)" for f(_, q, _). *)
type inter_constraint = intra_entity inter_constraint_
(** The union of inter- and intra-procedural constraint types. For example,
"Intra Has_static_key(f0, 'a', int)" or "Inter ArgLike("f", 1, p)". *)
type any_constraint = (intra_constraint, inter_constraint) any_constraint_
[@@deriving ord]
val debug_any_constraint : any_constraint -> string
(** Verifies whether an entity is the nth argument of a given function.
For instance, calling with ("f", 0) and "p" should result in "true",
if p is the first argument of f, and "false" otherwise. *)
val is_same_entity : intra_entity -> intra_entity -> bool
(** Interprets a parameter entity as an intra-procedural entity *)
val embed_entity : entity -> intra_entity
(** The maximum number of iterations constraint substitution should be
performed without reaching a fixpoint. *)
val max_iteration : int
(** The constraint substitution fixpoint is defined up to the following
equivalence of lists of constraints. *)
val equiv : any_constraint list -> any_constraint list -> bool
(** The Intra analysis should conservatively approximate these constraints.
An example of when this happens is when HIPS cannot see
certain definitions or does not understand them yet.
A specific example:
// assume we're doing source-file-granularity analysis
// file1.php
function foo(int $_): void {}
// file2.php
function main(): void {
// our analysis cannot "see" the definition, so we must widen any constraints related to the arg
foo(3);
}
*)
val widen : intra_entity list -> intra_constraint list
(** Backwards substitutes the intra-procedural constraint in the second argument
with respect to the inter-procedural constraint in the first argument.
For instance, calling it with the first argument "(("f", 0), p)" and
the second argument "Has_static_key(q, 'a', int)" should result in
"Has_static_key(p, 'a', int)", if q is the first argument of f, and
"Has_static_key(q, 'a', int)" otherwise. *)
val substitute_inter_intra_backwards :
inter_constraint -> intra_constraint -> intra_constraint option
(** Forwards substitutes the intra-procedural constraint in the second argument
with respect to the inter-procedural constraint in the first argument.
Calling it with the first argument "(("f", 0), p)" and
the second argument "Has_static_key(q, 'a', int)" should result in
"Has_static_key(("f", 0), 'a', int)", if q=p, and
"Has_static_key(q, 'a', int)" otherwise. *)
val substitute_inter_intra_forwards :
inter_constraint -> intra_constraint -> intra_constraint option
(** Deduces a simplified list of intra-procedural constraints. *)
val deduce : intra_constraint list -> intra_constraint list
(** Captures an abstract subset relation, e.g. between identifiers and constants *)
val subsets : intra_entity -> intra_entity -> intra_constraint
end
val equal_entity : entity -> entity -> bool |
hhvm/hphp/hack/src/hips2/dune | (library
(name hips2)
(wrapped true) ; only hips2.mli is visible
(flags
(:standard -linkall))
(libraries
core_kernel
utils_core
sys_utils)
(preprocess
(pps visitors.ppx ppx_deriving.std ppx_hash ppx_sexp_conv))) |
|
OCaml | hhvm/hphp/hack/src/hips2/hips2.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module Store = Hips2_store
include Hips2_intf
let hashset_size = 0
let hashtbl_size = 0
module Make (Intra : Intra) = struct
type intra_constraint_ = Intra.constraint_ [@@deriving hash, eq]
type custom_inter_constraint_ = Intra.custom_inter_constraint_
[@@deriving hash, eq, ord, show { with_path = false }]
module Id = struct
type t =
| ClassLike of string
| Function of string
[@@deriving hash, eq, ord, sexp, show { with_path = false }]
let hash : t -> int = Obj.magic hash (* workaround for T92019055 *)
let sid_of_t = function
| ClassLike sid -> sid
| Function sid -> sid
end
type inter_constraint_ =
| Inherits of Id.t
| CustomInterConstraint of custom_inter_constraint_
[@@deriving eq, hash, ord, show { with_path = false }]
let hash_inter_constraint_ : inter_constraint_ -> int =
Obj.magic hash_inter_constraint_ (* workaround for T92019055 *)
let hash_intra_constraint_ : intra_constraint_ -> int =
Obj.magic hash_intra_constraint_ (* workaround for T92019055 *)
(**
internal. Mutable total map from ids to sets of constraints. Returns an empty set when an id is not found.
Uses `Caml`'s.HashTbl instead of `Base`'s for marshallability, see T146711502.
*)
module DefaultTbl (SetOf : Caml.Hashtbl.HashedType) = struct
module TblImpl = Caml.Hashtbl.Make (Id)
module Set = struct
module SetImpl = Caml.Hashtbl.Make (SetOf)
(* it's a Hashtbl where the values are always `unit` *)
type t = unit SetImpl.t
let create () = SetImpl.create hashset_size
let add (t : t) v : bool =
if SetImpl.mem t v then
false
else (
SetImpl.add t v ();
true
)
let union ~from_set ~to_set : bool =
let fold_add c () has_changed = add to_set c || has_changed in
SetImpl.fold fold_add from_set false
let to_sequence t = SetImpl.to_seq_keys t |> Sequence.of_seq
end
type t = Set.t TblImpl.t
let create () : t = TblImpl.create hashtbl_size
let to_sequence_keys t : Id.t Sequence.t =
TblImpl.to_seq_keys t |> Sequence.of_seq
let find t key : Set.t =
match TblImpl.find_opt t key with
| None ->
let set : Set.t = Set.create () in
TblImpl.add t key set;
set
| Some set -> set
end
module InterHash = struct
type t = inter_constraint_
let equal = equal_inter_constraint_
let hash = hash_inter_constraint_
end
module InterTbl = DefaultTbl (InterHash)
module IntraHash = struct
type t = intra_constraint_
let equal = equal_intra_constraint_
let hash = hash_intra_constraint_
end
module IntraTbl = DefaultTbl (IntraHash)
type t = {
intras: IntraTbl.t;
inters: InterTbl.t;
}
let get_inters_set { inters; _ } id = InterTbl.find inters id
let get_inters t id = get_inters_set t id |> InterTbl.Set.to_sequence
let get_intras_set { intras; _ } id = IntraTbl.find intras id
let get_intras t id = get_intras_set t id |> IntraTbl.Set.to_sequence
let get_keys { inters; _ } : Id.t Sequence.t =
(* OK to just check inters because add_keys adds keys to inters *)
inters |> InterTbl.to_sequence_keys
let all_inter_constraints (t : t) =
get_keys t
|> Sequence.bind ~f:(fun id ->
get_inters t id |> Sequence.map ~f:(fun c -> (id, c)))
let create () = { inters = InterTbl.create (); intras = IntraTbl.create () }
module Write = struct
type nonrec t = t
type flush = unit -> unit
(** Continue using existing in-memory storage where possible to reduce the number of distinct files we have to flush to *)
let cached = ref None
let create ~db_dir ~worker_id =
match !cached with
| Some (prev_db_dir, prev_worker_id, prev_flush, prev_t)
when String.(equal prev_db_dir db_dir) && prev_worker_id = worker_id ->
(prev_flush, prev_t)
| Some _
| None ->
let t = create () in
let flush () = Store.persist ~db_dir ~worker_id t in
at_exit flush;
cached := Some (db_dir, worker_id, flush, t);
(flush, t)
let add_id { inters; _ } id =
(* We use `inters` to store ids.
* The next line works because `InterTbl.find` creates a set for the key if it doesn't exist
* *)
ignore @@ InterTbl.find inters id
let add_intra t id (c : Intra.constraint_) : unit =
(* we use the keys of `inters` to represent seen ids *)
add_id t id;
let set = IntraTbl.find t.intras id in
ignore (IntraTbl.Set.add set c : bool)
let add_inter { inters; _ } id (c : inter_constraint_) : unit =
let set = InterTbl.find inters id in
ignore (InterTbl.Set.add set c : bool)
end
module Read = struct
type nonrec t = t
let get_intras = get_intras
let get_inters = get_inters
let get_keys = get_keys
end
let solve_t t : Read.t =
let rec loop () =
let at_inter_constraint_mut id = function
| Inherits parent_id ->
let from_set = get_intras_set t parent_id in
let to_set = get_intras_set t id in
let changed = IntraTbl.Set.union ~from_set ~to_set in
changed
| CustomInterConstraint _ ->
false (* the solver ignores custom inter constraints *)
in
let has_changes =
all_inter_constraints t
|> Sequence.map ~f:(Tuple2.uncurry at_inter_constraint_mut)
|> Sequence.fold ~init:false ~f:( || )
in
if has_changes then loop ()
in
loop ();
t
let un_persist ~db_dir : t =
let t_dst = create () in
let merge_in t_src =
get_keys t_src
|> Sequence.iter ~f:(fun id ->
Write.add_id t_dst id;
get_inters_set t_src id
|> InterTbl.Set.to_sequence
|> Sequence.iter ~f:(Write.add_inter t_dst id);
get_intras_set t_src id
|> IntraTbl.Set.to_sequence
|> Sequence.iter ~f:(Write.add_intra t_dst id))
in
Store.un_persist ~db_dir |> Sequence.iter ~f:merge_in;
t_dst
let debug_dump ~db_dir : Read.t = un_persist ~db_dir
let solve ~db_dir : Read.t = solve_t @@ un_persist ~db_dir
end |
OCaml Interface | hhvm/hphp/hack/src/hips2/hips2.mli | include module type of Hips2_intf
module Make (Intra : Intra) :
T
with type intra_constraint_ = Intra.constraint_
and type custom_inter_constraint_ = Intra.custom_inter_constraint_ |
OCaml | hhvm/hphp/hack/src/hips2/hips2_intf.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module type Intra = sig
type constraint_ [@@deriving eq, hash, show]
type custom_inter_constraint_ [@@deriving eq, hash, ord, show]
end
module type T = sig
type intra_constraint_
type custom_inter_constraint_ [@@deriving eq, hash, ord, show]
module Id : sig
type t =
| ClassLike of string
| Function of string
[@@deriving ord, show { with_path = false }]
(** drop the tag: [ClassLike "Foo"] to `"Foo"] *)
val sid_of_t : t -> string
end
type inter_constraint_ =
| Inherits of Id.t
(** Interpreted broadly: extends+implements+trait require *)
| CustomInterConstraint of custom_inter_constraint_
[@@deriving ord, show { with_path = false }]
module Read : sig
type t
val get_inters : t -> Id.t -> inter_constraint_ Sequence.t
val get_intras : t -> Id.t -> intra_constraint_ Sequence.t
val get_keys : t -> Id.t Sequence.t
end
module Write : sig
type t
(** enables flushing to disk. You may not need this, since flushing happens automatically `at_exit` *)
type flush = unit -> unit
val create : db_dir:string -> worker_id:int -> flush * t
val add_id : t -> Id.t -> unit
val add_inter : t -> Id.t -> inter_constraint_ -> unit
val add_intra : t -> Id.t -> intra_constraint_ -> unit
end
(** read the constraints provided with `add_inter` and `add_intra`, without modification *)
val debug_dump : db_dir:string -> Read.t
val solve : db_dir:string -> Read.t
end |
OCaml | hhvm/hphp/hack/src/hips2/hips2_store.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
let marshal_flags = []
let suffix = ".hips2"
let persist ~db_dir ~worker_id t =
Sys_utils.mkdir_p db_dir ~skip_mocking:true;
let basename =
Format.sprintf
"%d-%d-%d%s"
worker_id
(Unix.getpid ())
(Random.int 999999999)
suffix
in
let path = Filename.concat db_dir @@ basename in
let out_channel = Out_channel.create path in
Marshal.to_channel out_channel t marshal_flags;
Out_channel.close out_channel
let un_persist_one path =
let in_channel = In_channel.create path in
Marshal.from_channel in_channel
let un_persist ~db_dir =
Sys.readdir db_dir
|> Array.to_sequence
|> Sequence.filter ~f:(String.is_suffix ~suffix)
|> Sequence.map ~f:(Filename.concat db_dir)
|> Sequence.map ~f:un_persist_one |
OCaml Interface | hhvm/hphp/hack/src/hips2/hips2_store.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
val persist : db_dir:string -> worker_id:int -> 'a -> unit
val un_persist : db_dir:string -> 'a Sequence.t |
hhvm/hphp/hack/src/ide_rpc/dune | (library
(name ide_rpc_api_types)
(wrapped false)
(modules ide_api_types)
(preprocess
(pps ppx_deriving.std))
(libraries core_kernel file_content pos))
(library
(name nuclide_rpc_message_printer)
(wrapped false)
(modules nuclide_rpc_message_printer)
(preprocess
(pps ppx_deriving.std))
(libraries ide_rpc_api_types pos symbol utils_core)) |
|
OCaml | hhvm/hphp/hack/src/ide_rpc/ide_api_types.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
(* 1-based position is used here *)
type position = {
line: int;
column: int;
}
[@@deriving show]
type range = {
st: position;
ed: position;
}
[@@deriving show]
type file_position = {
filename: string;
position: position;
}
type file_range = {
range_filename: string;
file_range: range;
}
type text_edit = {
range: range option;
text: string;
}
[@@deriving show]
let ide_pos_to_fc (x : position) : File_content.position =
let (line, column) = (x.line, x.column) in
{ File_content.line; column }
let ide_range_to_fc (x : range) : File_content.range =
let (st, ed) = (x.st |> ide_pos_to_fc, x.ed |> ide_pos_to_fc) in
{ File_content.st; ed }
let ide_text_edit_to_fc (x : text_edit) : File_content.text_edit =
let (text, range) = (x.text, x.range |> Option.map ~f:ide_range_to_fc) in
{ File_content.text; range }
let ide_pos_from_fc (x : File_content.position) : position =
let (line, column) = (x.File_content.line, x.File_content.column) in
{ line; column }
let ide_range_from_fc (x : File_content.range) : range =
let (st, ed) =
(x.File_content.st |> ide_pos_from_fc, x.File_content.ed |> ide_pos_from_fc)
in
{ st; ed }
let pos_to_range x =
let (st_line, st_column, ed_line, ed_column) = Pos.destruct_range x in
{
st = { line = st_line; column = st_column };
ed = { line = ed_line; column = ed_column };
}
let pos_to_file_range x =
{ range_filename = Pos.filename x; file_range = pos_to_range x }
let range_to_string_single_line x =
Printf.sprintf "line %d, characters %d-%d" x.st.line x.st.column x.ed.column |
OCaml | hhvm/hphp/hack/src/ide_rpc/nuclide_rpc_message_printer.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Hh_json
let opt_field ~v_opt ~label ~f =
Option.value_map v_opt ~f:(fun x -> [(label, f x)]) ~default:[]
(* There are fields that Nuclide doesn't use anymore, but the RPC framework
* still requires them in responses. Stub them with some default values in the
* meantime *)
let deprecated_pos_field = Pos.json (Pos.to_absolute Pos.none)
let deprecated_int_field = Hh_json.int_ 0
let deprecated_bool_field = JSON_Bool false
(* Instead of "assert false" *)
let should_not_happen = JSON_Object [("this_should", JSON_String "not_happen")]
let infer_type_response_to_json (type_string, type_json) =
Hh_json.JSON_Object
([("type", opt_string_to_json type_string); ("pos", deprecated_pos_field)]
@
match type_json with
| Some json -> [("full_type", json_of_string json)]
| _ -> [])
let infer_type_error_response_to_json
( actual_type_string,
actual_type_json,
expected_type_string,
expected_type_json ) =
Hh_json.JSON_Object
(List.filter_map
~f:Fn.id
[
Some ("actual_type", opt_string_to_json actual_type_string);
Option.map
~f:(fun ty -> ("full_actual_type", json_of_string ty))
actual_type_json;
Some ("expected_type", opt_string_to_json expected_type_string);
Option.map
~f:(fun ty -> ("full_expected_type", json_of_string ty))
expected_type_json;
])
let tast_holes_response_to_json ~print_file holes =
let printer pos =
if print_file then
Pos.to_absolute pos |> Pos.multiline_json
else
Pos.multiline_json_no_filename pos
in
let f
( actual_type_str,
actual_type_json,
expected_type_str,
expected_type_json,
pos ) =
Hh_json.JSON_Object
[
("actual_type", Hh_json.string_ actual_type_str);
("full_actual_type", json_of_string actual_type_json);
("expected_type", Hh_json.string_ expected_type_str);
("full_expected_type", json_of_string expected_type_json);
("pos", printer pos);
]
in
Hh_json.JSON_Array (List.map ~f holes)
let identify_symbol_response_to_json results =
let get_definition_data = function
| Some x ->
SymbolDefinition.(
let pos = Pos.json x.pos in
let span = Pos.multiline_json x.span in
let id = opt_string_to_json x.id in
(pos, span, id))
| None -> (JSON_Null, JSON_Null, JSON_Null)
in
let symbol_to_json (occurrence, definition) =
let (definition_pos, definition_span, definition_id) =
get_definition_data definition
in
SymbolOccurrence.(
JSON_Object
[
("name", JSON_String occurrence.name);
("result_type", JSON_String (kind_to_string occurrence.type_));
("pos", Pos.json occurrence.pos);
("definition_pos", definition_pos);
("definition_span", definition_span);
("definition_id", definition_id);
])
in
JSON_Array (List.map results ~f:symbol_to_json)
let rec definition_to_json def =
SymbolDefinition.(
let modifiers =
JSON_Array
(List.map def.modifiers ~f:(fun x -> JSON_String (string_of_modifier x)))
in
let children =
opt_field
~v_opt:def.children
~label:"children"
~f:outline_response_to_json
in
let params =
opt_field ~v_opt:def.params ~label:"params" ~f:outline_response_to_json
in
let docblock =
opt_field ~v_opt:def.docblock ~label:"docblock" ~f:(fun x ->
JSON_String x)
in
JSON_Object
([
("kind", JSON_String (string_of_kind def.kind));
("name", JSON_String def.name);
("id", opt_string_to_json def.id);
("position", Pos.json def.pos);
("span", Pos.multiline_json def.span);
("modifiers", modifiers);
]
@ children
@ params
@ docblock))
and outline_response_to_json x =
Hh_json.JSON_Array (List.map x ~f:definition_to_json)
let symbol_by_id_response_to_json = function
| Some def -> definition_to_json def
| None -> JSON_Null
let highlight_references_response_to_json l =
JSON_Array
(List.map l ~f:(fun x ->
Ide_api_types.(
Hh_json.JSON_Object
[
("line", Hh_json.int_ x.st.line);
("char_start", Hh_json.int_ x.st.column);
("char_end", Hh_json.int_ x.ed.column);
])))
let print_json json = Hh_json.json_to_string json |> print_endline |
hhvm/hphp/hack/src/ifc/dune | (include_subdirs unqualified)
(library
(name ifc)
(wrapped false)
(flags
(:standard -linkall))
(modules ifc_main)
(libraries
core_kernel
decl_provider
full_fidelity
global_options
heap_global_storage
hhi
ifc_lib
naming_global
naming_special_names
nast
provider_context
aast_names_utils
relative_path
sys_utils
tast_provider
typechecker_options
typing_defs
typing_heap
version)
(preprocess
(pps visitors.ppx ppx_deriving.std)))
(library
(name ifc_lib)
(wrapped false)
(flags
(:standard -linkall))
(modules
ifc
ifc_decl
ifc_env
ifc_lift
ifc_logic
ifc_mapper
ifc_options
ifc_pretty
ifc_scope
ifc_security_lattice
ifc_solver
ifc_types
ifc_utils)
(libraries
core_kernel
decl_provider
full_fidelity
global_options
heap_global_storage
hhi
naming_global
naming_special_names
nast
provider_context
aast_names_utils
relative_path
sys_utils
typechecker_options
typing_defs
typing_env_types
typing_heap
typing_utils
version)
(preprocess
(pps visitors.ppx ppx_deriving.std))) |
|
OCaml | hhvm/hphp/hack/src/ifc/ifc.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 Common
open Ifc_types
module Decl = Ifc_decl
module Env = Ifc_env
module Logic = Ifc_logic
module Pp = Ifc_pretty
module Lift = Ifc_lift
module Solver = Ifc_solver
module Utils = Ifc_utils
module A = Aast
module T = Typing_defs
module L = Logic.Infix
module K = Typing_cont_key
module LSet = Local_id.Set
let should_print ~user_mode ~phase =
equal_mode user_mode Mdebug || equal_mode user_mode phase
let fail fmt =
Format.kasprintf (fun s -> raise (IFCError (FlowInference s))) fmt
(* Returns the policies appearing in a type split in three sets
of occurrences (covariant, invariant, contravariant) *)
let rec policy_occurrences pty =
let emp = PSet.empty in
let pol = PSet.singleton in
let on_list =
List.fold ~init:(emp, emp, emp) ~f:(fun (s1, s2, s3) (t1, t2, t3) ->
(PSet.union s1 t1, PSet.union s2 t2, PSet.union s3 t3))
in
match pty with
| Tnull p
| Tprim p ->
(pol p, emp, emp)
| Tnonnull (pself, plump) -> (pol pself, pol plump, emp)
| Tgeneric p -> (emp, pol p, emp)
| Tdynamic p -> (emp, pol p, emp)
| Tinter tl
| Tunion tl
| Ttuple tl ->
on_list (List.map ~f:policy_occurrences tl)
| Tclass cls -> (pol cls.c_self, pol cls.c_lump, emp)
| Tfun { f_pc; f_self; f_args; f_ret; f_exn } ->
let swap_policy_occurrences t =
let (cov, inv, cnt) = policy_occurrences t in
(cnt, inv, cov)
in
on_list
((pol f_self, emp, pol f_pc)
:: policy_occurrences f_ret
:: policy_occurrences f_exn
:: List.map ~f:swap_policy_occurrences f_args)
| Tcow_array { a_key; a_value; a_length; _ } ->
on_list
[
(pol a_length, emp, emp);
policy_occurrences a_key;
policy_occurrences a_value;
]
| Tshape { sh_kind; sh_fields } ->
let f acc { sft_ty; sft_policy; _ } =
(pol sft_policy, emp, emp) :: policy_occurrences sft_ty :: acc
in
let init =
match sh_kind with
| Closed_shape -> []
| Open_shape ty -> [policy_occurrences ty]
in
Typing_defs.TShapeMap.values sh_fields |> List.fold ~f ~init |> on_list
exception SubtypeFailure of string * ptype * ptype
(* A constraint accumulator that registers a subtyping
requirement t1 <: t2 *)
let rec subtype ~pos t1 t2 acc =
let subtype = subtype ~pos in
let err msg = raise (SubtypeFailure (msg, t1, t2)) in
let rec first_ok ~f msg = function
| [] -> err msg
| x :: l -> begin
try f x with
| SubtypeFailure (msg, _, _) -> first_ok ~f msg l
end
in
match (t1, t2) with
| (Tnull p1, Tnull p2)
| (Tprim p1, Tprim p2) ->
L.(p1 < p2) ~pos acc
| (Tnull _, Tnonnull _) -> err "null is not a subtype of nonnull"
| (_, Tnonnull (pself, plump)) ->
let (cov, inv, _cnt) = policy_occurrences t1 in
(* we leave contravariant policies unconstrained;
that is sound and should not pose precision problems
since function types are seldom refined from `mixed` *)
L.(PSet.elements cov <* [pself] && [plump] =* PSet.elements inv) ~pos acc
| ((Tgeneric p1 | Tdynamic p1), _) ->
let (cov, inv, cnt) = policy_occurrences t2 in
L.(
[p1] <* PSet.elements cov
&& [p1] =* PSet.elements inv
&& PSet.elements cnt <* [p1])
~pos
acc
| (_, (Tgeneric p2 | Tdynamic p2)) ->
let (cov, inv, cnt) = policy_occurrences t1 in
L.(
PSet.elements cov <* [p2]
&& [p2] =* PSet.elements inv
&& [p2] <* PSet.elements cnt)
~pos
acc
| (Ttuple tl1, Ttuple tl2) ->
(match List.zip tl1 tl2 with
| List.Or_unequal_lengths.Ok zip ->
List.fold zip ~init:acc ~f:(fun acc (t1, t2) -> subtype t1 t2 acc)
| List.Or_unequal_lengths.Unequal_lengths -> err "incompatible tuple types")
| (Tclass cl1, Tclass cl2) ->
(* We do not attempt to replicate the work Hack did and instead
only act on policies. A bit of precision could be gained when
dealing with disjunctive subtyping queries if we realize that,
for example, cl1 and cl2 are incompatible; but let's keep it
simple for now. *)
L.(cl1.c_lump = cl2.c_lump && cl1.c_self < cl2.c_self) ~pos acc
| (Tfun f1, Tfun f2) ->
(* TODO(T70139741): Account for variadic argument lists. *)
(* Truncate argument list on the right, in case the left one is shorter
due to omitted arguments to functions with default values.
TODO(T79395145): Default values can be arbitrary expressions and hence
they need to be conditionally executed and joined with the
environment. *)
let truncated_size = List.length f2.f_args in
let truncated_f1_args = List.take f1.f_args truncated_size in
let zipped_args =
match List.zip truncated_f1_args f2.f_args with
| List.Or_unequal_lengths.Ok zip -> zip
| List.Or_unequal_lengths.Unequal_lengths ->
err "functions have different number of arguments"
in
(* Contravariant in argument types *)
List.fold ~f:(fun acc (t1, t2) -> subtype t2 t1 acc) ~init:acc zipped_args
(* Contravariant in PC *)
|> L.(f2.f_pc < f1.f_pc) ~pos
(* Covariant in its own identity *)
|> L.(f1.f_self < f2.f_self) ~pos
(* Covariant in return type and exceptions *)
|> subtype f1.f_ret f2.f_ret
|> subtype f1.f_exn f2.f_exn
| (Tcow_array arr1, Tcow_array arr2) ->
acc
|> subtype arr1.a_key arr2.a_key
|> subtype arr1.a_value arr2.a_value
|> L.(arr1.a_length < arr2.a_length) ~pos
| (Tcow_array _, Tclass cl) ->
let (cov, inv, _con) = policy_occurrences t1 in
acc
|> L.(PSet.elements cov <* [cl.c_self]) ~pos
|> L.(PSet.elements inv =* [cl.c_lump]) ~pos
| (Tshape s1, Tshape s2) ->
let acc =
match (s1.sh_kind, s2.sh_kind) with
| (Open_shape _, Closed_shape) ->
err "An open shape cannot subtype a closed shape"
| (Open_shape t1, Open_shape t2) -> subtype t1 t2 acc
| _ -> acc
in
let preprocess kind = function
(* A missing field of an open shape becomes an optional field of type mixed *)
| None -> begin
match kind with
| Open_shape sft_ty ->
Some { sft_optional = true; sft_policy = pbot; sft_ty }
| Closed_shape -> None
end
(* If a field is optional with type nothing, consider it missing.
Since it has type nothing, it can never be assigned and therefore
we do not need to consider its policy *)
| Some { sft_ty = Tunion []; sft_optional = true; _ } -> None
| sft -> sft
in
let combine acc _ f1 f2 =
let f1 = preprocess s1.sh_kind f1 in
let f2 = preprocess s2.sh_kind f2 in
match (f1, f2) with
| (Some { sft_optional = true; _ }, Some { sft_optional = false; _ }) ->
err "optional field cannot be subtype of required"
| ( Some { sft_ty = t1; sft_policy = p1; _ },
Some { sft_ty = t2; sft_policy = p2; _ } ) ->
(L.(p1 < p2) ~pos acc |> subtype t1 t2, None)
| (Some _, None) -> err "missing field"
| (None, Some { sft_optional; _ }) ->
if sft_optional then
(acc, None)
else
err "missing field"
| (None, None) -> (acc, None)
in
let (acc, _) =
Typing_defs.TShapeMap.merge_env ~combine acc s1.sh_fields s2.sh_fields
in
acc
| (Tunion tl, _) ->
List.fold tl ~init:acc ~f:(fun acc t1 -> subtype t1 t2 acc)
| (_, Tinter tl) ->
List.fold tl ~init:acc ~f:(fun acc t2 -> subtype t1 t2 acc)
| (_, Tunion tl) ->
(* It is not complete to try all the RHS elements in sequence
but that's how typing_subtype.ml works today *)
first_ok "nothing" tl ~f:(fun t2 -> subtype t1 t2 acc)
| (Tinter tl, _) ->
(* Same remark as for (_ <: Tunion _) *)
first_ok "mixed" tl ~f:(fun t1 -> subtype t1 t2 acc)
| _ -> err "unhandled subtyping query"
(* Overwrite subtype and equivalent catching the SubtypeFailure
exception *)
let subtype =
let wrap f ~pos t1 t2 acc =
try f ~pos t1 t2 acc with
| SubtypeFailure (msg, tsub, tsup) ->
fail "subtype: %s (%a <: %a)" msg Pp.ptype tsub Pp.ptype tsup
in
wrap subtype
(* Returns the list of free policy variables in a type *)
let free_pvars pty =
let (cov, inv, cnt) = policy_occurrences pty in
let all_vars =
PSet.fold (fun pol vset ->
match pol with
| Pfree_var (v, s) -> VarSet.add (v, s) vset
| _ -> vset)
in
VarSet.empty |> all_vars cov |> all_vars inv |> all_vars cnt
(* Type refinements happen when the typechecker realizes that a dynamic
check ensures a code path is taken only when a local has a given type.
The refined type Tref is in a subtyping relation with the original
type Tori (Tref <: Tori).
Refinement gets tricky when the reference type and original type
are parameterized (either with type parameters, or with policy
parameters). In plain Hack, type parameters are not constrained by
dynamic checks (e.g., one can only say ($x is vec<_>)), so we have
to ensure that the code type-checked under a refinement is valid
regardless of the parameter's value. In practice, the Hack
typechecker introduces a generic type on the spot (i.e., a rigid
type variable); it is however improperly scoped, and that leads
to soundness bugs.
In Hack IFC, we will not bother too much with type parameters until
Hack is fixed. However, we will properly handle policy variables.
Doing so requires generating universally quantified policy variables
in the constraint. Let's consider an example.
$x: mixed<=pm>
if ($x is A<+pcls, =pfld>) {
/* some code */
}
The variances were marked with + and = for covariant and invariant,
respectively. Inside the if statement, the type for $x is refined
(from mixed). Hack IFC mints a new type A<pcls, pfld> for $x then
generates the constraint Cif for the body of the conditional, the
complete constraint is then assembled as such:
(forall pcls pfld. (A<pcls, pfld> <: mixed<pm>) ==> Cif)
which, expanding the action of subtyping, is the same as
(forall pcls pfld. (pcls < pm && pfld = pm) ==> Cif)
Note how pcls and pfld are local to the part of the constraint
that deals with the body of the if conditional. This is how Hack
IFC controls the (potentially unsound) escaping of the fresh
parameters induced by refinements.
It is clear that we can get rid of pfld, and replace it with pm
everywhere it appears in Cif. But what about pcls? The key to
eliminating it early is that pcls appears covariantly in the
type of a live value accessible via $x. Consequently, all the
constraints in Cif involving pcls must be of the form (pcls < X).
Because of this observation, it is sound (and complete) to replace
pcls in Cif by pm. In contrast, if there had been constraints of
the form (X < pcls) in Cif, we'd have had to replace pcls with bot
in those.
*)
let refine renv tyori pos ltyref =
let ref_scope = Scope.alloc () in
let tyref = Lift.ty { renv with re_scope = ref_scope } ltyref in
let acc = subtype ~pos tyref tyori [] in
(* we know the three sets are disjoint, because Lift.ty above
will not reuse the same variable multiple times *)
let (cov, _inv, cnt) = policy_occurrences tyref in
(* analyze the result of the subtyping call; we build a map
that associates a bound to each policy variable in tyref.
Depending on whether the refined variable is in cov/inv/cnt
the bound is to be interpreted as an upper bound, an
equality, or a lower bound.
*)
let rec collect vmap acc =
let set_bound pref pori vmap =
(* only store bounds that apply to the refined type and
are from the origin type *)
match pref with
| Pfree_var (var, s) when Scope.equal s ref_scope -> begin
match pori with
| Pfree_var (_, s) when Scope.equal s ref_scope -> vmap
| _ -> SMap.add var pori vmap
end
| _ -> vmap
in
match acc with
| [] -> vmap
| Ctrue :: acc -> collect vmap acc
| Cconj (Cflow (_, p1, p2), Cflow (_, p3, p4)) :: acc
when equal_policy p1 p4 && equal_policy p2 p3 ->
collect (set_bound p1 p2 @@ set_bound p2 p1 @@ vmap) acc
| Cflow (_, p1, p2) :: acc when PSet.mem p1 cov ->
collect (set_bound p1 p2 vmap) acc
| Cflow (_, p1, p2) :: acc when PSet.mem p2 cnt ->
collect (set_bound p2 p1 vmap) acc
| c :: acc ->
(* soundness is not compromised by ignoring the constraint,
however, for debugging purposes it is good to know this
happened *)
Format.eprintf "Duh?! unhandled subtype constraint: %a" Pp.prop c;
collect vmap acc
in
let vmap = collect SMap.empty acc in
(* replace policy variables in tyref with their bounds *)
let rec replace_vars ty =
let on_policy = function
| Pfree_var (var, s) ->
(* sanity check *)
assert (Scope.equal s ref_scope);
begin
match SMap.find_opt var vmap with
| None ->
(* this is what happens when the refined type has a
policy variable that is not related to anything in
the original type; it happens, for instance, if the
refined type is a class C<...> and the original
type is a policy-free empty intersection (Tinter[])
in this case, we cannot get rid of the universal
quantification; for now we simply fail *)
fail "univ refinement (%a ~> %a)" Pp.ptype tyori Pp.ptype tyref
| Some bnd -> bnd
end
| pol -> pol
in
Ifc_mapper.ptype replace_vars on_policy ty
in
(* finally, we have the refined type!
some examples of refine's behavior in common cases:
original refined locl result
(int<pi>|C<pc,pl>) int --> int<pi>
(int<pi>|I<pc,pl>) C --> C<pc,pl> (C implements I)
mixed<pm> C --> C<pm,pm> (policied mixed is TODO)
*)
replace_vars tyref
(* Generates a fresh sub/super policy of the argument polic *)
let adjust_policy ?(prefix = "weak") ~pos ~adjustment renv env policy =
match (adjustment, policy) with
| (Astrengthen, Pbot _)
| (Aweaken, Ptop _) ->
(env, policy)
| (Astrengthen, _) ->
let new_policy = Env.new_policy_var renv prefix in
let prop = L.(new_policy < policy) ~pos in
(Env.acc env prop, new_policy)
| (Aweaken, _) ->
let new_policy = Env.new_policy_var renv prefix in
let prop = L.(policy < new_policy) ~pos in
(Env.acc env prop, new_policy)
(* Generates a fresh sub/super ptype of the argument ptype *)
let adjust_ptype ?prefix ~pos ~adjustment renv env ty =
let adjust_policy = adjust_policy ?prefix ~pos renv in
let flip = function
| Astrengthen -> Aweaken
| Aweaken -> Astrengthen
in
let rec freshen adjustment env ty =
let freshen_cov = freshen adjustment in
let freshen_con = freshen @@ flip adjustment in
let freshen_pol_cov = adjust_policy ~adjustment in
let freshen_pol_con = adjust_policy ~adjustment:(flip adjustment) in
let simple_freshen env f p =
let (env, p) = freshen_pol_cov env p in
(env, f p)
in
let on_list env mk tl =
let (env, tl') = List.map_env env tl ~f:freshen_cov in
(env, mk tl')
in
match ty with
| Tnull p -> simple_freshen env (fun p -> Tnull p) p
| Tprim p -> simple_freshen env (fun p -> Tprim p) p
| Tnonnull (pself, plump) ->
(* plump is invariant, so we do not adjust it *)
simple_freshen env (fun pself -> Tnonnull (pself, plump)) pself
| Tgeneric p -> (env, Tgeneric p)
| Tdynamic p -> (env, Tdynamic p)
| Ttuple tl -> on_list env (fun l -> Ttuple l) tl
| Tunion tl -> on_list env (fun l -> Tunion l) tl
| Tinter tl -> on_list env (fun l -> Tinter l) tl
| Tclass class_ ->
let (env, super_pol) = freshen_pol_cov env class_.c_self in
(env, Tclass { class_ with c_self = super_pol })
| Tfun fun_ ->
let (env, f_pc) = freshen_pol_con env fun_.f_pc in
let (env, f_self) = freshen_pol_cov env fun_.f_self in
let (env, f_args) = List.map_env env ~f:freshen_con fun_.f_args in
let (env, f_ret) = freshen_cov env fun_.f_ret in
let (env, f_exn) = freshen_cov env fun_.f_exn in
(env, Tfun { f_pc; f_self; f_args; f_ret; f_exn })
| Tcow_array arr ->
let (env, a_key) = freshen_cov env arr.a_key in
let (env, a_value) = freshen_cov env arr.a_value in
let (env, a_length) = freshen_pol_cov env arr.a_length in
(env, Tcow_array { a_kind = arr.a_kind; a_key; a_value; a_length })
| Tshape { sh_kind; sh_fields } ->
let f env _ sft =
let (env, ty) = freshen_cov env sft.sft_ty in
let (env, p) = freshen_pol_cov env sft.sft_policy in
(env, { sft_ty = ty; sft_policy = p; sft_optional = sft.sft_optional })
in
let (env, sh_fields) = Typing_defs.TShapeMap.map_env f env sh_fields in
let (env, sh_kind) =
match sh_kind with
| Open_shape ty ->
let (env, ty) = freshen_cov env ty in
(env, Open_shape ty)
| Closed_shape -> (env, Closed_shape)
in
(env, Tshape { sh_kind; sh_fields })
in
freshen adjustment env ty
(* Returns the set of policies, to be understood as a join,
that governs an object with the argument type *)
let rec object_policy = function
| Tnull pol
| Tprim pol
| Tnonnull (pol, _)
| Tgeneric pol
| Tdynamic pol
| Tclass { c_self = pol; _ }
| Tfun { f_self = pol; _ } ->
PSet.singleton pol
| Tinter tl
| Tunion tl
| Ttuple tl ->
let f set t = PSet.union (object_policy t) set in
List.fold tl ~init:PSet.empty ~f
| Tcow_array { a_key; a_value; a_length; _ } ->
PSet.union (object_policy a_key) (object_policy a_value)
|> PSet.add a_length
| Tshape { sh_kind; sh_fields; _ } ->
let f _ { sft_ty; sft_policy; _ } acc =
acc |> PSet.add sft_policy |> PSet.union (object_policy sft_ty)
in
let pols =
match sh_kind with
| Open_shape ty -> object_policy ty
| Closed_shape -> PSet.empty
in
Typing_defs.TShapeMap.fold f sh_fields pols
let add_dependencies pl t = L.(pl <* PSet.elements (object_policy t))
let join_policies ?(prefix = "join") ~pos renv env pl =
let drop_pbot (Pbot _ :: pl | pl) = pl in
match drop_pbot (List.dedup_and_sort ~compare:compare_policy pl) with
| [] -> (env, pbot)
| [p] -> (env, p)
| (Ptop _ as ptop) :: _ -> (env, ptop)
| pl ->
let pv = Env.new_policy_var renv prefix in
let env = Env.acc env (L.(pl <* [pv]) ~pos) in
(env, pv)
let get_local_type ~pos:_ env lid =
match Env.get_local_type env lid with
| None -> None
| pty_opt -> pty_opt
(* Uses a Hack-inferred type to update the flow type of a local
variable *)
let refresh_local_type ?(force = false) ~pos renv env lid lty =
let is_simple pty =
match pty with
| Tunion _ -> false
| _ -> true
in
let pty =
match get_local_type ~pos env lid with
| Some pty -> pty
| None -> Lift.ty renv lty
in
if (not force) && is_simple pty then
(* if the type is already simple, do not refresh it with
what Hack found *)
(env, pty)
else
let prefix = Local_id.to_string lid in
let new_pty = Lift.ty renv lty ~prefix in
let env = Env.acc env (subtype ~pos pty new_pty) in
let env = Env.set_local_type env lid new_pty in
(env, new_pty)
let lift_params renv =
let lift_param p =
let prefix = p.A.param_name in
let pty = Lift.ty ~prefix renv (fst p.A.param_type_hint) in
let lid = Local_id.make_unscoped p.A.param_name in
(lid, pty)
in
List.map ~f:lift_param
let set_local_types env =
List.fold ~init:env ~f:(fun env (lid, pty) -> Env.set_local_type env lid pty)
let class_ _pos msg ty =
let rec find_class = function
| Tclass class_ -> Some class_
| Tdynamic pol ->
(* While it is sound to set the class's lump policy to be the dynamic's
(invariant) policy, we do not know if the property we are looking for
is policied, therefore we guess that it has the lump policy and emit an
error in case we are wrong *)
Some { c_name = "<dynamic>"; c_self = pol; c_lump = pol }
| Tinter tys -> List.find_map ~f:find_class tys
| _ -> None
in
match find_class ty with
| Some pty -> pty
| None -> fail "%s" msg
let receiver_of_obj_get pos obj_ptype property =
let msg =
Format.asprintf "couldn't find a class for the property '%s'" property
in
class_ pos msg obj_ptype
(* We generate a ptype out of the property type and fill it with either the
* purpose of property or the lump policy of some object root. *)
let property_ptype pos renv obj_ptype property property_ty =
let class_ = receiver_of_obj_get pos obj_ptype property in
let prop_pol =
match Decl.property_policy renv.re_decl class_.c_name property with
| Some policy -> policy
| None -> class_.c_lump
in
Lift.ty ~prefix:property ~lump:prop_pol renv property_ty
(* may_throw registers that the expression being checked may
throw an exception of type exn_ty; the throwing is conditioned
on data whose policy is in pc_deps.
If pc_deps is empty an exception is unconditionally thrown *)
let may_throw ~pos renv env pc_deps exn_ty =
let env = Env.throw env pc_deps in
let deps = PSet.elements (Env.get_lpc env) in
let env = Env.acc env (subtype exn_ty renv.re_exn ~pos) in
let env = Env.acc env (add_dependencies deps renv.re_exn ~pos) in
env
let shape_field_name_ this field =
Aast.(
match field with
| (p, Int name) -> Ok (Ast_defs.SFlit_int (p, name))
| (p, String name) -> Ok (Ast_defs.SFlit_str (p, name))
| (_, Class_const ((_, _, CI x), y)) -> Ok (Ast_defs.SFclass_const (x, y))
| (_, Class_const ((_, _, CIself), y)) ->
(match force this with
| Some sid -> Ok (Ast_defs.SFclass_const (sid, y))
| None -> Error `Expected_class)
| _ -> Error `Invalid_shape_field_name)
let shape_field_name : ptype renv_ -> _ -> Typing_defs.tshape_field_name option
=
fun renv ix ->
let ix =
(* The utility function does not expect a TAST *)
let (_, p, e) = ix in
(p, e)
in
(* TODO(T72024862): This does not support late static binding *)
let this =
lazy
(match renv.re_this with
| Some (Tclass cls) -> Some (fst ix, cls.c_name)
| _ -> None)
in
match shape_field_name_ this ix with
| Ok fld -> Some (Typing_defs.TShapeField.of_ast Pos_or_decl.of_raw_pos fld)
| Error _ -> None
let call_special ~pos renv env args ret = function
| StaticMethod ("\\HH\\Shapes", "idx") ->
let (ty, key, def) =
match args with
| [(ty, _); (_, Some (_, key))] -> (ty, key, None)
| [(ty, _); (_, Some (_, key)); (def, _)] -> (ty, key, Some def)
| _ -> fail "incorrect arguments to Shapes::idx"
in
let key =
match shape_field_name renv key with
| Some k -> k
| None -> fail "invalid shape key"
in
let field =
{
sft_policy = Env.new_policy_var renv "shape";
sft_ty = ret;
sft_optional = true;
}
in
let tshape =
let sh_fields = Typing_defs.TShapeMap.singleton key field in
Tshape { sh_fields; sh_kind = Open_shape (Tinter []) }
in
let env =
Env.acc env
@@ L.(subtype ty tshape && add_dependencies [field.sft_policy] ret) ~pos
in
let env =
match def with
| None -> env
| Some def -> Env.acc env @@ subtype ~pos def ret
in
Some (env, ret)
| _ -> None
let call_regular ~pos renv env call_type name that_pty_opt args_pty ret_pty =
let callee = Env.new_policy_var renv (name ^ "_self") in
let env = Env.acc env (add_dependencies ~pos [callee] ret_pty) in
let (env, callee_exn) =
let exn = Lift.class_ty ~prefix:(name ^ "_exn") renv Decl.exception_id in
let env = may_throw ~pos renv env (object_policy exn) exn in
(env, exn)
in
(* The PC of the function being called depends on the join of the current
* PC dependencies, as well as the function's own self policy *)
let (env, pc_joined) =
let pc_list = PSet.elements (Env.get_gpc renv env) in
join_policies ~pos renv env ~prefix:"pcjoin" pc_list
in
let hole_ty =
{
f_pc = pc_joined;
f_self = callee;
f_args = args_pty;
f_ret = ret_pty;
f_exn = callee_exn;
}
in
let result_from_fun_decl fp callable_name = function
| { fd_kind = FDPolicied policy; fd_args } ->
let scheme = Decl.make_callable_scheme renv policy fp fd_args in
let prop =
(* because cipp_scheme is created after fp they cannot
mismatch and call_constraint will not fail *)
Option.value_exn (Solver.call_constraint ~subtype ~pos fp scheme)
in
(env, prop)
| { fd_kind = FDInferFlows; _ } ->
let env = Env.add_dep env (Decl.callable_name_to_string callable_name) in
(env, Chole (pos, fp))
in
match call_type with
| Clocal fun_ ->
let env = Env.acc env @@ subtype ~pos (Tfun fun_) (Tfun hole_ty) in
(env, ret_pty)
| Cglobal (callable_name, fty) ->
let fp = { fp_name = name; fp_this = that_pty_opt; fp_type = hole_ty } in
let (env, call_constraint) =
let fun_decl = Decl.convert_fun_type renv.re_ctx fty in
result_from_fun_decl fp callable_name fun_decl
in
let env = Env.acc env (fun acc -> call_constraint :: acc) in
(env, ret_pty)
| Cconstructor callable_name ->
(* We don't have the function type on the TAST with constructors, so grab it from
decl heap. *)
let fp = { fp_name = name; fp_this = that_pty_opt; fp_type = hole_ty } in
let (env, call_constraint) =
match Decl.get_callable_decl renv.re_ctx callable_name with
| Some decl -> result_from_fun_decl fp callable_name decl
| None -> fail "Could not find %s in declarations" name
in
let env = Env.acc env (fun acc -> call_constraint :: acc) in
(env, ret_pty)
let call ~pos renv env call_type that_pty_opt args ret_pty =
let name =
match call_type with
| Cconstructor callable_name
| Cglobal (callable_name, _) ->
Decl.callable_name_to_string callable_name
| Clocal _ -> "anonymous"
in
let special =
match call_type with
| Cglobal (cn, _) -> call_special ~pos renv env args ret_pty cn
| _ -> None
in
match special with
| Some res -> res
| None ->
let args_pty = List.map ~f:fst args in
call_regular ~pos renv env call_type name that_pty_opt args_pty ret_pty
let array_like ~cow ~shape ~klass ~tuple ~dynamic ty =
let rec search ty =
match ty with
| Tcow_array _ when cow -> Some ty
| Tshape _ when shape -> Some ty
| Tclass _ when klass -> Some ty
| Ttuple _ when tuple -> Some ty
| Tdynamic _ when dynamic -> Some ty
| Tinter tys -> List.find_map tys ~f:search
| _ -> None
in
search ty
let array_like_with_default ~cow ~shape ~klass ~tuple ~dynamic ~pos:_ renv ty =
match array_like ~cow ~shape ~klass ~tuple ~dynamic ty with
| Some ty -> ty
| None ->
(* The default is completely arbitrary but it should be the least
precisely handled array structure given the search options. *)
if dynamic then
Tdynamic (Env.new_policy_var renv "fake_dynamic")
else if klass then
Tclass
{
c_name = "fake";
c_self = Env.new_policy_var renv "fake_self";
c_lump = Env.new_policy_var renv "fake_lump";
}
else if cow then
Tcow_array
{
a_kind = Adict;
a_key = Tprim (Env.new_policy_var renv "fake_key");
a_value = Tprim (Env.new_policy_var renv "fake_value");
a_length = Env.new_policy_var renv "fake_length";
}
else if shape then
Tshape { sh_kind = Closed_shape; sh_fields = Typing_defs.TShapeMap.empty }
else if tuple then
Ttuple []
else
fail "`array_like_with_default` has no options turned on"
let cow_array ~pos renv ty =
let cow_array =
array_like_with_default
~cow:true
~shape:false
~klass:false
~tuple:false
~dynamic:false
~pos
renv
ty
in
match cow_array with
| Tcow_array arry -> arry
| _ -> fail "expected Hack array"
(* Deals with an assignment to a local variable or an object property *)
let assign_helper
?(use_pc = true) ~expr ~pos renv env (lhs_ty, _, lhs_exp) rhs_pty =
match lhs_exp with
| A.(Lvar (_, lid) | Dollardollar (_, lid)) ->
let prefix = Local_id.to_string lid in
let lhs_pty = Lift.ty ~prefix renv lhs_ty in
let env = Env.set_local_type env lid lhs_pty in
let env =
if use_pc then
let deps = PSet.elements (Env.get_lpc env) in
Env.acc env (add_dependencies ~pos deps lhs_pty)
else
env
in
let env = Env.acc env (subtype ~pos rhs_pty lhs_pty) in
env
| A.Obj_get (obj, (_, _, A.Id (_, property)), _, _) ->
let (env, obj_pty) = expr env obj in
let obj_pol = (receiver_of_obj_get pos obj_pty property).c_self in
let lhs_pty = property_ptype pos renv obj_pty property lhs_ty in
let pc =
if use_pc then
PSet.elements (Env.get_gpc renv env)
else
[]
in
let deps = obj_pol :: pc in
let env = Env.acc env (add_dependencies ~pos deps lhs_pty) in
let env = Env.acc env (subtype ~pos rhs_pty lhs_pty) in
env
| _ -> env
(* Hack array accesses and mutations may throw when the indexed
element is not in the array. may_throw_out_of_bounds_exn is
used to register this fact. *)
let may_throw_out_of_bounds_exn ~pos renv env length_pol ix_pty =
let exn_ty = Lift.class_ty renv Decl.out_of_bounds_exception_id in
(* both the indexing expression and the array length influence
whether an exception is thrown or not; indeed, the check
performed by the indexing is of the form:
if ($ix >= $arry->length) { throw ...; } *)
let pc_deps = PSet.add length_pol (object_policy ix_pty) in
may_throw ~pos renv env pc_deps exn_ty
let int_of_exp ix_exp =
match ix_exp with
| (_, _, A.Int i) -> int_of_string i
| _ -> fail "expected an integer literal while indexing a tuple"
let nth_tuple_pty ptys ix_exp =
let ix = int_of_exp ix_exp in
match List.nth ptys ix with
| Some pty -> pty
| None -> fail "tuple arity is too little"
let overwrite_nth_pty tuple_pty ix_exp pty =
let ix = int_of_exp ix_exp in
match tuple_pty with
| Ttuple ptys ->
let ptys = List.take ptys ix @ (pty :: List.drop ptys (ix + 1)) in
Ttuple ptys
| _ -> fail "policy type overwrite expected a tuple"
(* A wrapper around assign_helper that deals with Hack arrays' syntactic
sugar; this accounts for the CoW semantics of Hack arrays:
$x->p[4][] = "hi";
does not mutate an array cell, but the property p of
the object $x instead. *)
let rec assign
?(use_pc = true) ~expr ~pos renv env ((lhs_ty, _, lhs_expr_) as lhs) rhs_pty
=
match lhs_expr_ with
| A.Array_get (((arry_ty, _, _) as arry_exp), ix_opt) ->
let handle_collection
env ~should_skip_exn old_array new_array key value length =
(* TODO(T68269878): track flows due to length changes *)
let env = Env.acc env (subtype ~pos old_array new_array) in
(* Evaluate the index *)
let (env, ix_pty_opt) =
match ix_opt with
| Some ix ->
let (env, ix_pty) = expr env ix in
(* The index flows to they key of the collection *)
let env = Env.acc env (subtype ~pos ix_pty key) in
(env, Some ix_pty)
| None -> (env, None)
in
(* Potentially raise `OutOfBoundsException` *)
let env =
match ix_pty_opt with
(* When there is no index, we add a new element, hence no exception. *)
| None -> env
(* Dictionaries don't throw on assignment, they register a new key. *)
| Some _ when should_skip_exn -> env
| Some ix_pty -> may_throw_out_of_bounds_exn ~pos renv env length ix_pty
in
(* Do the assignment *)
let env = Env.acc env (subtype ~pos rhs_pty value) in
(env, true)
in
(* Evaluate the array *)
let (env, old_arry_pty) = expr env arry_exp in
let new_arry_pty = Lift.ty ~prefix:"arr" renv arry_ty in
(* If the array is in an intersection, we pull it out and if we cannot
find find something suitable return a fake type to make the analysis go
through. *)
let new_arry_pty =
array_like_with_default
~cow:true
~shape:true
~klass:true
~tuple:true
~dynamic:false
~pos
renv
new_arry_pty
in
let (env, use_pc) =
match new_arry_pty with
| Tcow_array arry ->
let should_skip_exn = equal_array_kind arry.a_kind Adict in
handle_collection
env
~should_skip_exn
old_arry_pty
new_arry_pty
arry.a_key
arry.a_value
arry.a_length
| Tshape { sh_kind; sh_fields } -> begin
match Option.(ix_opt >>= shape_field_name renv) with
| Some key ->
(* The key can only be a literal (int, string) or class const, so
it is always public *)
let p = Env.new_policy_var renv "field" in
let pc = Env.get_lpc env |> PSet.elements in
let env =
Env.acc env @@ L.(pc <* [p] && add_dependencies pc rhs_pty) ~pos
in
let sh_fields =
Typing_defs.TShapeMap.add
key
{ sft_optional = false; sft_policy = p; sft_ty = rhs_pty }
sh_fields
in
let tshape = Tshape { sh_kind; sh_fields } in
let env = Env.acc env (subtype ~pos tshape new_arry_pty) in
(env, false)
| None -> (env, true)
end
| Ttuple _ ->
let ix =
match ix_opt with
| Some ix_exp -> ix_exp
| _ -> fail "indexed tuple assignment requires an index"
in
let tuple_pty = overwrite_nth_pty old_arry_pty ix rhs_pty in
let env = Env.acc env (subtype ~pos tuple_pty new_arry_pty) in
(env, true)
| Tclass { c_name; c_lump; c_self } ->
let should_skip_exn = String.equal c_name "\\HH\\Map" in
(* The key is an arraykey so it will always be a Tprim *)
let key_pty = Tprim c_lump in
let env = Env.acc env (add_dependencies ~pos [c_self] key_pty) in
(* The value is constructed as if a property access is made *)
let value_pty = Lift.ty ~lump:c_lump renv lhs_ty in
let env = Env.acc env (add_dependencies ~pos [c_self] value_pty) in
handle_collection
env
~should_skip_exn
old_arry_pty
new_arry_pty
key_pty
value_pty
c_lump
| _ -> fail "the default type for array assignment is not handled"
in
(* assign the array/shape to itself *)
assign ~use_pc ~expr ~pos renv env arry_exp new_arry_pty
| _ -> assign_helper ~use_pc ~expr ~pos renv env lhs rhs_pty
let seq ~run (env, out) x =
let (out, next_opt) = Env.strip_cont out K.Next in
match next_opt with
| None ->
(* we are looking at dead code *)
(env, out)
| Some cont ->
let env = Env.prep_stmt env cont in
let (env, out_exceptional) = run env x in
(* we have to merge the exceptional outcomes from
before `x` with the ones after `x` *)
(env, Env.merge_out out_exceptional out)
(* Generate flow constraints for an expression *)
let rec expr ~pos renv (env : Env.expr_env) ((ety, epos, e) : Tast.expr) =
let expr = expr ~pos renv in
let expr_with_deps env deps e =
Env.expr_with_pc_deps env deps (fun env -> expr env e)
in
let add_element_dependencies env exprs element_pty =
let mk_element_subtype env exp =
let (env, pty) = expr env exp in
Env.acc env (subtype ~pos pty element_pty)
in
List.fold ~f:mk_element_subtype ~init:env exprs
in
(* Any copy-on-write collection with only values such as vec, keyset,
ImmVector. *)
let cow_array_literal ~prefix exprs =
let arry_pty = Lift.ty ~prefix renv ety in
let element_pty = (cow_array ~pos renv arry_pty).a_value in
(* Each element is a subtype of the collection's value. *)
let env = add_element_dependencies env exprs element_pty in
(env, arry_pty)
in
(* Anything class that is a Collection, but in particular Vector and Set. *)
let mut_array_literal ~prefix exprs =
let class_pty = Lift.ty ~prefix renv ety in
let class_ = class_ pos "mutable array literal is not a class" class_pty in
let rec find_element_ty ty =
match T.get_node ty with
| T.Tclass (_, _, [element_ty]) -> Some element_ty
| T.Tintersection tys -> List.find_map tys ~f:find_element_ty
| _ -> None
in
let element_pty =
match find_element_ty ety with
| Some element_ty -> Lift.ty ~lump:class_.c_lump renv element_ty
| None -> Tprim (Env.new_policy_var renv "fake_element")
in
let env = Env.acc env (add_dependencies ~pos [class_.c_self] element_pty) in
(* Each element is a subtype of the collection's value. *)
let env = add_element_dependencies env exprs element_pty in
(env, class_pty)
in
let add_key_value_dependencies env fields key_pty value_pty =
let mk_field_subtype env (key, value) =
let subtype = subtype ~pos in
let (env, key_pty') = expr env key in
let (env, value_pty') = expr env value in
Env.acc env @@ fun acc ->
acc |> subtype key_pty' key_pty |> subtype value_pty' value_pty
in
List.fold ~f:mk_field_subtype ~init:env fields
in
(* Any copy-on-write collection with keys and values such as dict, ImmMap,
ConstMap. *)
let cow_keyed_array_literal ~prefix fields =
let dict_pty = Lift.ty ~prefix renv ety in
let arr = cow_array ~pos renv dict_pty in
(* Each field is a subtype of collection keys and values. *)
let env = add_key_value_dependencies env fields arr.a_key arr.a_value in
(env, dict_pty)
in
(* Any class that is a KeyedCollection, but in particular Map. *)
let mut_keyed_array_literal ~prefix fields =
(* Each element of the array is a subtype of the array's value parameter. *)
let class_pty = Lift.ty ~prefix renv ety in
let class_ = class_ pos "mutable array literal is not a class" class_pty in
let rec find_key_value_tys ty =
match T.get_node ty with
| T.Tclass (_, _, [key_ty; value_ty]) -> Some (key_ty, value_ty)
| T.Tintersection tys -> List.find_map tys ~f:find_key_value_tys
| _ -> None
in
let (key_pty, value_pty) =
match find_key_value_tys ety with
| Some (key_ty, value_ty) ->
( Lift.ty ~lump:class_.c_lump renv key_ty,
Lift.ty ~lump:class_.c_lump renv value_ty )
| None ->
( Tprim (Env.new_policy_var renv "fake_key"),
Tprim (Env.new_policy_var renv "fake_value") )
in
let env = Env.acc env (add_dependencies ~pos [class_.c_self] key_pty) in
let env = Env.acc env (add_dependencies ~pos [class_.c_self] value_pty) in
(* Each field is a subtype of collection keys and values. *)
let env = add_key_value_dependencies env fields key_pty value_pty in
(env, class_pty)
in
let funargs env =
let f env (pk, e) =
let (env, ty) = expr env e in
(env, (ty, Some (pk, e)))
in
List.map_env env ~f
in
match e with
| A.Null -> (env, Tnull (Env.new_policy_var renv "null"))
| A.True
| A.False
| A.Int _
| A.Float _
| A.String _ ->
(* literals are public *)
(env, Tprim (Env.new_policy_var renv "lit"))
| A.(Binop { bop = Ast_defs.Eq None; lhs; rhs }) ->
let (env, ty2) = expr env rhs in
let env = assign ~expr ~pos renv env lhs ty2 in
(env, ty2)
| A.(Binop { bop = Ast_defs.Eq (Some op); lhs; rhs }) ->
(* it is simpler to create a fake expression lhs = lhs op rhs to
make sure all operations (e.g., ??) are handled correctly *)
expr
env
( ety,
epos,
A.(
Binop
{
bop = Ast_defs.Eq None;
lhs;
rhs = (ety, epos, Binop { bop = op; lhs; rhs });
}) )
| A.(Binop { bop = Ast_defs.QuestionQuestion; lhs = e1; rhs = e2 })
| A.Eif (e1, None, e2) ->
let (env, ty1) = expr env e1 in
let (env, ty2) = expr_with_deps env (object_policy ty1) e2 in
let ty = Lift.ty ~prefix:"qq" renv ety in
let null_policy = Env.new_policy_var renv "nullqq" in
let env =
Env.acc env
@@ L.(
subtype ty1 (Tunion [ty; Tnull null_policy])
&& subtype ty2 ty
&& add_dependencies [null_policy] ty)
~pos
in
(env, ty)
| A.Eif (e1, Some e2, e3) ->
let (env, ty1) = expr env e1 in
let (env, ty2) = expr_with_deps env (object_policy ty1) e2 in
let (env, ty3) = expr_with_deps env (object_policy ty1) e3 in
let ty = Lift.ty ~prefix:"eif" renv ety in
let env = Env.acc env (L.(subtype ty2 ty && subtype ty3 ty) ~pos) in
(env, ty)
| A.(
Binop
{
bop =
Ast_defs.(
( Plus | Minus | Star | Slash | Starstar | Percent | Ltlt | Gtgt
| Xor | Amp | Bar | Dot ));
lhs = e1;
rhs = e2;
}) ->
(* arithmetic and bitwise operations all take primitive types
and return a primitive type; string concatenation (Dot) is
also handled here although it might need special casing
because of HH\FormatString<T> (TODO) *)
let (env, ty1) = expr env e1 in
let (env, ty2) = expr env e2 in
let ty = Tprim (Env.new_policy_var renv "arith") in
let env = Env.acc env (subtype ~pos ty1 ty) in
let env = Env.acc env (subtype ~pos ty2 ty) in
(env, ty)
| A.(
Binop
{
bop =
Ast_defs.(
( Eqeqeq | Diff2 | Barbar | Ampamp | Eqeq | Diff | Lt | Lte | Gt
| Gte | Cmp )) as op;
lhs = e1;
rhs = e2;
}) ->
let (env, ty1) = expr env e1 in
let (env, ty2) = expr env e2 in
let deps =
let gather_policies =
match op with
| Ast_defs.(Eqeqeq | Diff2 | Barbar | Ampamp) ->
(* === and !== check for object identity, the resulting
boolean is thus governed by the object policies of
the two operands
|| and && are also safely handled by object_policy
since they either look at a boolean value or test
if an object is null *)
object_policy
| _ ->
(* other comparison operators can inspect mutable fields
when applied to DateTime objects, so we conservatively
use all policies of both arguments *)
fun t ->
let (cov, inv, cnt) = policy_occurrences t in
PSet.union cov (PSet.union inv cnt)
in
PSet.union (gather_policies ty1) (gather_policies ty2)
in
let (env, cmp_policy) =
join_policies ~pos ~prefix:"cmp" renv env (PSet.elements deps)
in
(env, Tprim cmp_policy)
| A.Unop (op, e) -> begin
match op with
(* Operators that mutate *)
| Ast_defs.Uincr
| Ast_defs.Udecr
| Ast_defs.Upincr
| Ast_defs.Updecr ->
(* register constraints that'd be generated if
e = e +/- 1 were being analyzed *)
let (env, tye) = expr env e in
let env = assign ~expr ~pos renv env e tye in
(env, tye)
(* Prim operators that don't mutate *)
| Ast_defs.Unot ->
let (env, tye) = expr env e in
(* use object_policy to account for both booleans
and null checks *)
let (env, not_policy) =
join_policies
~prefix:"not"
~pos
renv
env
(PSet.elements (object_policy tye))
in
(env, Tprim not_policy)
| Ast_defs.Utild
| Ast_defs.Uplus
| Ast_defs.Uminus ->
expr env e
| Ast_defs.Usilence -> expr env e
end
| A.Lvar (_pos, lid) -> refresh_local_type ~pos renv env lid ety
| A.Obj_get (obj, (_, _, A.Id (_, property)), _, _) ->
let (env, obj_ptype) = expr env obj in
let prop_pty = property_ptype pos renv obj_ptype property ety in
let prefix = "." ^ property in
let (env, super_pty) =
adjust_ptype ~pos ~prefix ~adjustment:Aweaken renv env prop_pty
in
let obj_pol = (receiver_of_obj_get pos obj_ptype property).c_self in
let env = Env.acc env (add_dependencies ~pos [obj_pol] super_pty) in
(env, super_pty)
| A.This ->
(match renv.re_this with
| Some ptype -> (env, ptype)
| None -> fail "encountered $this outside of a class context")
| A.ET_Splice e
| A.ExpressionTree { A.et_runtime_expr = e; _ } ->
(* TODO: IFC should consider spliced values too *)
expr env e
(* TODO(T68414656): Support calls with type arguments *)
| A.(Call { func; args; _ }) ->
let fty = Tast.get_type func in
let (env, args_pty) = funargs env args in
let ret_pty = Lift.ty ~prefix:"ret" renv ety in
let call env call_type this_pty =
call ~pos renv env call_type this_pty args_pty ret_pty
in
begin
match func with
(* Generally a function call *)
| (_, _, A.Id (_, name)) ->
let call_id = Decl.make_callable_name ~is_static:false None name in
call env (Cglobal (call_id, fty)) None
(* Regular method call *)
| (_, _, A.Obj_get (obj, (_, _, A.Id (_, meth_name)), _, _)) ->
let (env, obj_pty) = expr env obj in
begin
match obj_pty with
| Tclass { c_name; _ } ->
let call_id =
Decl.make_callable_name ~is_static:false (Some c_name) meth_name
in
call env (Cglobal (call_id, fty)) (Some obj_pty)
| _ -> fail "unhandled method call on %a" Pp.ptype obj_pty
end
(* Static method call*)
| (_, _, A.Class_const ((ty, _, cid), (_, meth_name))) ->
let env =
match cid with
| A.CIexpr e -> fst @@ expr env e
| A.CIstatic ->
(* TODO(T72024862): Handle late static binding *)
env
| _ -> env
in
let find_class_name ty =
match T.get_node ty with
| T.Tclass ((_, class_name), _, _) -> class_name
| _ -> fail "unhandled method call on a non-class"
in
let class_name = find_class_name ty in
let call_id =
Decl.make_callable_name ~is_static:true (Some class_name) meth_name
in
let this_pty =
if String.equal meth_name Decl.construct_id then begin
(* The only legal class id is `parent` which is invoked as if it
is invoked on the object being constructed, hence it uses the same
`$this` as the caller. *)
assert (Option.is_some renv.re_this);
renv.re_this
end else
None
in
call env (Cglobal (call_id, fty)) this_pty
| _ ->
let (env, func_ty) = expr env func in
let ifc_fty =
match func_ty with
| Tfun fty -> fty
| _ -> failwith "calling something that is not a function"
in
call env (Clocal ifc_fty) None
end
| A.FunctionPointer (id, _) ->
let ty = Lift.ty renv ety in
let fty =
match ty with
| Tfun fty -> fty
| _ -> fail "FunctionPointer does not have a function type"
in
let ctype =
match id with
| A.FP_id (_, name) ->
let call_id = Decl.make_callable_name ~is_static:false None name in
Cglobal (call_id, ety)
| A.FP_class_const _ ->
(* TODO(T72024862): Handle late static binding *)
Clocal fty
in
(* Act as though we are defining a lambda that wraps a call to the function
pointer. *)
let renv = { renv with re_gpc = fty.f_pc; re_exn = fty.f_exn } in
let args = List.map ~f:(fun t -> (t, None)) fty.f_args in
let (env, _ret_ty) = call ~pos renv env ctype None args fty.f_ret in
(env, ty)
| A.Varray (_, exprs) -> cow_array_literal ~prefix:"varray" exprs
| A.ValCollection
((_, ((A.Vec | A.Keyset | A.ImmSet | A.ImmVector) as kind)), _, exprs) ->
let prefix = A.show_vc_kind kind in
cow_array_literal ~prefix exprs
| A.ValCollection ((_, ((A.Vector | A.Set) as kind)), _, exprs) ->
let prefix = A.show_vc_kind kind in
mut_array_literal ~prefix exprs
| A.Darray (_, fields) -> cow_keyed_array_literal ~prefix:"darray" fields
| A.KeyValCollection ((_, ((A.Dict | A.ImmMap) as kind)), _, fields) ->
let prefix = A.show_kvc_kind kind in
cow_keyed_array_literal ~prefix fields
| A.KeyValCollection ((_, (A.Map as kind)), _, fields) ->
let prefix = A.show_kvc_kind kind in
mut_keyed_array_literal ~prefix fields
| A.Array_get (arry, ix_opt) ->
(* Evaluate the array *)
let (env, arry_pty) = expr env arry in
let arry =
array_like_with_default
~cow:true
~shape:true
~klass:true
~tuple:true
~dynamic:false
~pos
renv
arry_pty
in
(* Evaluate the index, it might have side-effects! *)
let (env, ix_exp, ix_pty) =
match ix_opt with
| Some ix ->
let (env, ty) = expr env ix in
(env, ix, ty)
| None -> fail "cannot have an empty index when reading"
in
begin
match arry with
| Tcow_array arry ->
(* The index flows into the array key which flows into the array value *)
let env = Env.acc env @@ subtype ~pos ix_pty arry.a_key in
let env =
may_throw_out_of_bounds_exn ~pos renv env arry.a_length ix_pty
in
(env, arry.a_value)
| Tshape { sh_fields; _ } ->
let sft =
Option.(
shape_field_name renv ix_exp >>= fun f ->
Typing_defs.TShapeMap.find_opt f sh_fields)
in
begin
match sft with
| Some { sft_ty; _ } -> (env, sft_ty)
| None -> (env, Lift.ty renv ety)
end
| Ttuple ptys ->
let indexed_pty = nth_tuple_pty ptys ix_exp in
(env, indexed_pty)
| Tclass { c_self = self; c_lump = lump; _ } ->
let value_pty = Lift.ty ~lump renv ety in
let env = Env.acc env (add_dependencies ~pos [self] value_pty) in
(* Collection keys are arraykey's which are Tprims. *)
let key_pty = Tprim lump in
let env = Env.acc env (add_dependencies ~pos [self] key_pty) in
(* Indexing expression flows into the key policy type of the collection . *)
let env = Env.acc env @@ subtype ~pos ix_pty key_pty in
(* Join of lump and self governs the length of the collection as well. *)
let (env, join_pol) = join_policies ~pos renv env [lump; self] in
let env = may_throw_out_of_bounds_exn ~pos renv env join_pol ix_pty in
(env, value_pty)
| _ -> fail "the default type for array access is not handled"
end
| A.New ((lty, _, cid), _targs, args, _extra_args, _) ->
(* TODO(T70139741): support variadic functions and constructors
* TODO(T70139893): support classes with type parameters
*)
let (env, args_pty) =
funargs env (List.map ~f:(fun e -> (Ast_defs.Pnormal, e)) args)
in
let env =
match cid with
| A.CIexpr e -> fst @@ expr env e
| A.CIstatic ->
(* TODO(T72024862): Handle late static binding *)
env
| _ -> env
in
let obj_pty = Lift.ty renv lty in
begin
match obj_pty with
| Tclass { c_name; _ } ->
let call_id =
Decl.make_callable_name
~is_static:false
(Some c_name)
Decl.construct_id
in
let lty = T.mk (Typing_reason.Rnone, T.Tprim A.Tvoid) |> Lift.ty renv in
let (env, _) =
call ~pos renv env (Cconstructor call_id) (Some obj_pty) args_pty lty
in
(env, obj_pty)
| _ -> fail "unhandled method call on %a" Pp.ptype obj_pty
end
| A.Efun { A.ef_fun = fun_; ef_use = captured_ids; _ }
| A.Lfun (fun_, captured_ids) ->
(* weaken all the captured local variables and reset the local
pc to create the initial continuation we'll use to check the
lambda literal *)
let (env, start_cont) =
let (env, k_vars) =
let lids =
List.map ~f:(fun (_, (_, id)) -> id) captured_ids |> LSet.of_list
in
Env.get_locals env
|> LMap.filter (fun lid _ -> LSet.mem lid lids)
|> LMap.map_env
(fun env _ -> adjust_ptype ~pos ~adjustment:Aweaken renv env)
env
in
(env, { k_pc = PSet.empty; k_vars })
in
let pc = Env.new_policy_var renv "pc" in
let self = Env.new_policy_var renv "lambda" in
let exn = Lift.class_ty renv Decl.exception_id in
let ret = Lift.ty ~prefix:"ret" renv (fst fun_.A.f_ret) in
let ptys = lift_params renv fun_.A.f_params in
let args = List.map ~f:snd ptys in
let env =
Env.analyze_lambda_body env @@ fun env ->
let env = Env.prep_stmt env start_cont in
let env = set_local_types env ptys in
let renv = { renv with re_ret = ret; re_exn = exn; re_gpc = pc } in
let (env, _out) = block renv env fun_.A.f_body.A.fb_ast in
env
in
let ty =
Tfun { f_pc = pc; f_self = self; f_args = args; f_ret = ret; f_exn = exn }
in
(env, ty)
| A.Await e -> expr env e
| A.Pair (_, e0, e1) ->
let (env, ptys) = List.map_env env [e0; e1] ~f:expr in
(env, Ttuple ptys)
| A.List es ->
let (env, ptys) = List.map_env env es ~f:expr in
(env, Ttuple ptys)
| A.Tuple es ->
let (env, ptys) = List.map_env env es ~f:expr in
(env, Ttuple ptys)
| A.Pipe ((_, dollardollar), e1, e2) ->
let (env, t1) = expr env e1 in
let dd_old = Env.get_local_type env dollardollar in
let env = Env.set_local_type env dollardollar t1 in
let (env, t2) = expr env e2 in
let env = Env.set_local_type_opt env dollardollar dd_old in
(env, t2)
| A.Dollardollar (_, lid) -> refresh_local_type ~pos renv env lid ety
| A.Shape s ->
let p = Env.new_policy_var renv "field" in
let pc = Env.get_lpc env |> PSet.elements in
let env = Env.acc env @@ L.(pc <* [p]) ~pos in
let f (env, m) (key, e) =
let (env, t) = expr env e in
let sft = { sft_ty = t; sft_optional = false; sft_policy = p } in
( env,
Typing_defs.TShapeMap.add
(Typing_defs.TShapeField.of_ast Pos_or_decl.of_raw_pos key)
sft
m )
in
let (env, sh_fields) =
List.fold ~f ~init:(env, Typing_defs.TShapeMap.empty) s
in
(env, Tshape { sh_kind = Closed_shape; sh_fields })
| A.Is (e, _hint) ->
let (env, ety) = expr env e in
(* whether an object has one tag or another is governed
by its object policy *)
let (env, tag_policy) =
let tag_policy_list = PSet.elements (object_policy ety) in
join_policies ~pos ~prefix:"tag" renv env tag_policy_list
in
(env, Tprim tag_policy)
| A.As (e, _hint, is_nullable) ->
let (env, ty) = expr env e in
let tag_policies = object_policy ty in
let (env, tag_test_ty) =
if is_nullable then
(* The 'e ?as Thint' construct can be seen as
((e is Thint) ? e : null) as ?Thint
that is, we can see the construct as *first* setting e's
value to null if it is not a subtype of Thint, *then*
performing a refinement with ?Thint. Note that the 'as'
refinement above will always succeed because the ternary
evaluates either to e that has type Thint (<: ?Thint), or
null that has type null (<: ?Thint).
The result of this as refinement is in ety, so here, we
construct the type of ternary expression. *)
let (env, tag_policy) =
join_policies ~pos ~prefix:"tag" renv env (PSet.elements tag_policies)
in
(env, Tunion [ty; Tnull tag_policy])
else
let exn = Lift.class_ty ~prefix:"as" renv Decl.exception_id in
let env = may_throw ~pos renv env tag_policies exn in
(env, ty)
in
(env, refine renv tag_test_ty pos ety)
(* --- A valid AST does not contain these nodes *)
| A.Import _
| A.Collection _ ->
failwith "AST should not contain these nodes"
(* --- expressions below are not yet supported *)
| _ -> (env, Lift.ty renv ety)
and stmt renv (env : Env.stmt_env) ((pos, s) : Tast.stmt) =
let expr_ = expr
and expr ?(pos = pos) renv env e =
let (env, ety) = expr ~pos renv (Env.prep_expr env) e in
let (env, ethrow) = Env.close_expr env in
(env, ety, ethrow)
in
let untainted_pc = Env.get_lpc env in
let clear_pc_deps out =
(* if the outcome of a statement is unconditional, the
outcome control flow has exactly the same dependencies
as the statement itself *)
if KMap.cardinal out = 1 then
KMap.map (fun k -> { k with k_pc = untainted_pc }) out
else
out
in
let refresh_with_tymap ~pos renv env tymap =
let refresh var (_, lty) env =
fst @@ refresh_local_type ~force:true ~pos renv env var lty
in
Local_id.Map.fold refresh tymap env
in
let loop_the_env ~pos env out_blk beg_locals =
(* issue a subtype call between the type of the locals at
the end of loop and their invariant type; this constrains
their IFC type to indeed be invariant and spares us from
running a more classic fixpoint computation *)
Env.acc env
@@
match KMap.find_opt K.Next out_blk with
| None -> Utils.identity
| Some { k_vars = end_locals; _ } ->
let update_lid lid end_type =
match LMap.find_opt lid beg_locals with
| None -> Utils.identity
| Some beg_type -> subtype ~pos end_type beg_type
in
LMap.fold update_lid end_locals
in
match s with
| A.AssertEnv (A.Refinement, tymap) ->
(* The typechecker refined the type of some locals due
to a runtime check, update ifc types to match the
refined types *)
let env =
Local_id.Map.fold
(fun var (_, hint) env ->
match get_local_type ~pos env var with
| None -> env
| Some pty ->
let new_pty = refine renv pty pos hint in
Env.set_local_type env var new_pty)
tymap
env
in
Env.close_stmt env K.Next
| A.Awaitall (el, b) ->
let (env, out) =
List.fold_left el ~init:(env, KMap.empty) ~f:(fun (env, out) (lvar, e) ->
let expr = expr_ ~pos renv in
let (env, ety) = expr (Env.prep_expr env) e in
let env =
match lvar with
| Some lid ->
let (pty, p, _) = e in
assign ~expr ~pos renv env (pty, p, A.Lvar lid) ety
| None -> env
in
let (env, ethrow) = Env.close_expr env in
(env, Env.merge_out out ethrow))
in
let (env, out1) = block renv env b in
let out = Env.merge_out out out1 in
(env, out)
| A.Expr e ->
let (env, _ety, ethrow) = expr renv env e in
Env.close_stmt ~merge:ethrow env K.Next
| A.If (cond, b1, b2) ->
let (_, pos, _) = cond in
let (env, cty, cthrow) = expr ~pos renv env cond in
(* use object_policy to account for both booleans
and null checks *)
Env.with_pc_deps env (object_policy cty) @@ fun env ->
let beg_cont = Env.get_next env in
let (env, out1) = block renv env b1 in
let (env, out2) = block renv (Env.prep_stmt env beg_cont) b2 in
let out = Env.merge_out out1 out2 in
let out = Env.merge_out out cthrow in
let out = clear_pc_deps out in
(env, out)
| A.While (cond, (_, A.AssertEnv (A.Join, tymap)) :: blk) ->
let (_, pos, _) = cond in
let env = refresh_with_tymap ~pos renv env tymap in
let beg_locals = Env.get_locals env in
(* TODO: pc_pols should also flow into cty because the condition is evaluated
unconditionally only the first time around the loop. *)
let (env, cty, cthrow) = expr ~pos renv env cond in
let pc_policies = object_policy cty in
Env.with_pc_deps env pc_policies @@ fun env ->
let tainted_lpc = Env.get_lpc env in
let (env, out_blk) = block renv env blk in
let out_blk = Env.merge_out out_blk cthrow in
let out_blk = Env.merge_in_next out_blk K.Continue in
let env = loop_the_env ~pos env out_blk beg_locals in
let out =
(* overwrite the Next outcome to use the type for local
variables as they are at the beginning of the loop,
then merge the Break outcome in Next *)
let next = { k_pc = tainted_lpc; k_vars = beg_locals } in
Env.merge_in_next (KMap.add K.Next next out_blk) K.Break
in
let out = clear_pc_deps out in
(env, out)
| A.For (inits, cond_opt, incrs, (_, A.AssertEnv (A.Join, tymap)) :: blk) ->
(* Helper that evaluates an expression, but discards its type *)
let discarding_expr env ((_, pos, _) as exp) =
let (env, _, out_exceptional) = expr ~pos renv env exp in
Env.close_stmt ~merge:out_exceptional env K.Next
in
(* Evaluate the initialisers of the loop *)
let init = Env.close_stmt env K.Next in
let (env, out) = List.fold_left ~f:(seq ~run:discarding_expr) ~init inits in
let env = Env.prep_stmt env (KMap.find K.Next out) in
(* Use the position of the condition if awailable; entire loop's position
otherwise. *)
let pos =
match cond_opt with
| Some (_, cond_pos, _) -> cond_pos
| None -> pos
in
let env = refresh_with_tymap ~pos renv env tymap in
let beg_locals = Env.get_locals env in
(* TODO: pc_pols should also flow into cty because the condition is evaluated
unconditionally only the first time around the loop. *)
let (env, pc_policies, cthrow) =
match cond_opt with
| Some cond ->
let (env, cty, cthrow) = expr ~pos renv env cond in
(env, object_policy cty, cthrow)
| None -> (env, PSet.empty, KMap.empty)
in
Env.with_pc_deps env pc_policies @@ fun env ->
let tainted_lpc = Env.get_lpc env in
let (env, out_blk) = block renv env blk in
let out_blk = Env.merge_out out_blk cthrow in
let out_blk = Env.merge_in_next out_blk K.Continue in
(* Handle loop increments *)
let init = (env, out_blk) in
let (env, out) = List.fold_left ~f:(seq ~run:discarding_expr) ~init incrs in
let env = loop_the_env ~pos env out beg_locals in
let out =
(* overwrite the Next outcome to use the type for local
variables as they are at the beginning of the loop,
then merge the Break outcome in Next *)
let next = { k_pc = tainted_lpc; k_vars = beg_locals } in
Env.merge_in_next (KMap.add K.Next next out_blk) K.Break
in
let out = clear_pc_deps out in
(env, out)
| A.Foreach (collection, as_exp, (_, A.AssertEnv (A.Join, tymap)) :: blk) ->
let (_, pos, _) = collection in
let env = refresh_with_tymap ~pos renv env tymap in
let beg_locals = Env.get_locals env in
(* TODO: pc should also flow into cty because the condition is evaluated
unconditionally only the first time around the loop. *)
let (env, collection_pty, cthrow) = expr ~pos renv env collection in
let collection_pty =
array_like_with_default
~cow:true
~shape:false
~klass:true
~tuple:false
~dynamic:true
~pos
renv
collection_pty
in
let env = Env.prep_expr env in
let expr = expr_ ~pos renv in
let (env, pc_policies) =
match as_exp with
| Aast.As_v ((value_ty, _, _) as value)
| Aast.Await_as_v (_, ((value_ty, _, _) as value)) ->
let (env, value_pty, pc_policies) =
match collection_pty with
| Tcow_array arry -> (env, arry.a_value, PSet.singleton arry.a_length)
| Tclass class_ ->
(* TODO(T80403715): Ensure during class definition that Iterable
instances behave sensibly. Otherwise, this treatment is unsound. *)
(* Value is, in effect, a field access, hence governed by the
lump policy of the class. *)
let value_pty = Lift.ty ~lump:class_.c_lump renv value_ty in
(* Length, key, and value are governed by the self policy if the
class is in fact a Hack array and by the lump policy otherwise. *)
let cl_pols = [class_.c_self; class_.c_lump] in
let env = Env.acc env (add_dependencies ~pos cl_pols value_pty) in
(env, value_pty, PSet.of_list cl_pols)
| Tdynamic dyn_pol ->
(* Deconstruction of dynamic also produces dynamic *)
(env, collection_pty, PSet.singleton dyn_pol)
| _ -> fail "Collection is neither a class nor a cow array"
in
let env = assign_helper ~expr ~pos renv env value value_pty in
(env, pc_policies)
| Aast.As_kv (((key_ty, _, _) as key), ((value_ty, _, _) as value))
| Aast.Await_as_kv
(_, ((key_ty, _, _) as key), ((value_ty, _, _) as value)) ->
let (env, key_pty, value_pty, pc_policies) =
match collection_pty with
| Tcow_array arry ->
(env, arry.a_key, arry.a_value, PSet.singleton arry.a_length)
| Tclass class_ ->
(* TODO(T80403715): Ensure during class definition that Iterable
instances behave sensibly. Otherwise, this treatment is unsound. *)
(* Key and value are, in effect, a field accesses, hence governed
by the lump policy of the class. *)
let key_pty = Lift.ty ~lump:class_.c_lump renv key_ty in
let value_pty = Lift.ty ~lump:class_.c_lump renv value_ty in
(* Length, key, and value are governed by the self policy if the
class is in fact a Hack array and by the lump policy otherwise. *)
let cl_pols = [class_.c_self; class_.c_lump] in
let env = Env.acc env (add_dependencies ~pos cl_pols value_pty) in
let env = Env.acc env (add_dependencies ~pos cl_pols key_pty) in
(env, key_pty, value_pty, PSet.of_list cl_pols)
| Tdynamic dyn_pol ->
(* Deconstruction of dynamic also produces dynamic *)
(env, collection_pty, collection_pty, PSet.singleton dyn_pol)
| _ -> fail "Collection is neither a class nor a cow array"
in
let env = assign_helper ~expr ~pos renv env key key_pty in
let env = assign_helper ~expr ~pos renv env value value_pty in
(env, pc_policies)
in
let (env, ethrow) = Env.close_expr env in
if not @@ KMap.is_empty ethrow then fail "foreach collection threw";
Env.with_pc_deps env pc_policies @@ fun env ->
let tainted_lpc = Env.get_lpc env in
let (env, out_blk) = block renv env blk in
let out_blk = Env.merge_out out_blk cthrow in
let out_blk = Env.merge_in_next out_blk K.Continue in
let env = loop_the_env ~pos env out_blk beg_locals in
let out =
(* overwrite the Next outcome to use the type for local
variables as they are at the beginning of the loop,
then merge the Break outcome in Next *)
let next = { k_pc = tainted_lpc; k_vars = beg_locals } in
Env.merge_in_next (KMap.add K.Next next out_blk) K.Break
in
let out = clear_pc_deps out in
(env, out)
| A.Break -> Env.close_stmt env K.Break
| A.Continue -> Env.close_stmt env K.Continue
| A.Fallthrough -> Env.close_stmt env K.Fallthrough
| A.Return e ->
let (env, ethrow) =
match e with
| None -> (env, KMap.empty)
| Some e ->
let (env, ety, ethrow) = expr renv env e in
let deps = PSet.elements (Env.get_lpc env) in
let env = Env.acc env (subtype ety renv.re_ret ~pos) in
let env = Env.acc env (add_dependencies deps renv.re_ret ~pos) in
(env, ethrow)
in
Env.close_stmt ~merge:ethrow env K.Exit
| A.Throw e ->
let (env, ety) = expr_ ~pos renv (Env.prep_expr env) e in
let env = may_throw ~pos renv env PSet.empty ety in
let (env, ethrow) = Env.close_expr env in
Env.close_stmt ~merge:ethrow env K.Catch
| A.Try (try_blk, cs, finally) ->
(* Note: unlike the Hack typechecker which accumulates the environments
for exceptional outcomes in 'env' itself we have a more explicit
handling of outcomes (stmt *returns* the outcome map). This explicit
style makes it much easier to process the difficult semantics of
finally blocks; in particular, we have no use of the K.Finally
cont key that was used as some kind of temporary variable by the
Hack typechecker. *)
(* use a fresh exception type to check the try block so that we
do not influence the current exception type in case there is
a catch-all block (`catch (Exception ...) { ... }`) *)
let fresh_exn = Lift.class_ty renv Decl.exception_id in
let (env, out_try) =
let renv = { renv with re_exn = fresh_exn } in
block renv env try_blk
in
(* strip out_try from its Catch continuation; it will be used
at the beginning of catch blocks *)
let (out_try, catch_cont) = Env.strip_cont out_try K.Catch in
(* in case there is no catch all, the exception still lingers *)
let (env, out_try) =
let is_Exception ((_, exn), _, _) = String.equal exn Decl.exception_id in
match catch_cont with
| Some catch_cont when not (List.exists ~f:is_Exception cs) ->
let out_try = KMap.add K.Catch catch_cont out_try in
let env = Env.acc env (subtype ~pos fresh_exn renv.re_exn) in
(env, out_try)
| _ -> (env, out_try)
in
(* merge the outcome of all the catch blocks started from the Catch
outcome of the try block *)
let (env, out_catch) =
match catch_cont with
| None ->
(* the try block does not throw, we can just return an empty
outcome for the catch blocks since they will never run *)
(env, KMap.empty)
| Some catch_cont ->
let catch (env, out) (_, (_, exn_var), blk) =
let env = Env.prep_stmt env catch_cont in
let env = Env.set_local_type env exn_var fresh_exn in
let (env, out_blk) = block renv env blk in
(env, Env.merge_out out out_blk)
in
List.fold ~f:catch ~init:(env, KMap.empty) cs
in
(* now we simply merge the outcomes of all the catch blocks with the
one of the try block *)
let out_try_catch = Env.merge_out out_try out_catch in
let out_try_catch = clear_pc_deps out_try_catch in
(* for each continuation in out_try_catch we will perform an
analysis of the finally block; this improves precision of
the analysis a bit and mimicks what Hack does *)
KMap.fold
(fun k cont (env, out_finally) ->
(* analyze the finally block for the outcome k *)
let env = Env.prep_stmt env cont in
(* we use the untainted pc when processing the finally
block because it will run exactly as often as the
Try statement itself *)
Env.with_pc env untainted_pc @@ fun env ->
let (env, out) = block renv env finally in
let out = Env.merge_next_in out k in
(* restore all the pc dependencies for the outcomes
of the finally block *)
let out =
let add_deps pc = PSet.union pc cont.k_pc in
KMap.map (fun c -> { c with k_pc = add_deps c.k_pc }) out
in
(env, Env.merge_out out_finally out))
out_try_catch
(env, KMap.empty)
| A.Switch (e, cl, dfl) ->
let (_, pos, _) = e in
let (env, ety, ethrow) = expr ~pos renv env e in
let (env, out_cond) = Env.close_stmt ~merge:ethrow env K.Fallthrough in
let case_gen (env, (out, deps)) c =
let out = Env.merge_out out_cond out in
let (out, ft_cont_opt) = Env.strip_cont out K.Fallthrough in
(* out_cond has a Fallthrough so ft_cont_opt cannot be None *)
let env = Env.prep_stmt env (Option.value_exn ft_cont_opt) in
Env.with_pc_deps env deps @@ fun env ->
let (env, out, new_deps, b) =
match c with
| Aast.Default (_, b) -> (env, out, PSet.empty, b)
| Aast.Case (e, b) ->
let (_, pos, _) = e in
let (env, ety, ethrow) = expr ~pos renv env e in
let out = Env.merge_out out ethrow in
(env, out, object_policy ety, b)
in
Env.with_pc_deps env new_deps @@ fun env ->
let (env, out_blk) = block renv env b in
let out = Env.merge_out out out_blk in
(* deps is accumulated monotonically because going
through each 'case' reveals increasingly more
information about the scrutinee and the cases *)
(env, (out, PSet.union deps new_deps))
in
let case state c = case_gen state (Aast.Case c) in
let default_case state c = case_gen state (Aast.Default c) in
let (env, (out, _final_deps)) =
let initial_deps = object_policy ety in
let state = (env, (out_cond, initial_deps)) in
let state = List.fold ~f:case ~init:state cl in
let state = Option.fold ~f:default_case ~init:state dfl in
state
in
let out = Env.merge_in_next out K.Continue in
let out = Env.merge_in_next out K.Break in
let out = Env.merge_in_next out K.Fallthrough in
let out = clear_pc_deps out in
(env, out)
| A.Noop -> Env.close_stmt env K.Next
(* --- These nodes do not appear after naming *)
| A.Block _
| A.Markup _ ->
failwith
"Unexpected nodes in AST. These nodes should have been removed in naming."
(* --- These nodes are not yet supported *)
| _ -> Env.close_stmt env K.Next
and block renv env (blk : Tast.block) =
let init = Env.close_stmt env K.Next in
List.fold_left ~f:(seq ~run:(stmt renv)) ~init blk
(* Checks that two type schemes are in a subtyping relationship. The
* skeletons of the two input type schemes are expected to be same.
* A list of invalid flows is returned, if the list is empty the
* type schemes are in a subtyping relationship. *)
let check_subtype_scheme ~pos sub_scheme sup_scheme : pos_flow list =
let (Fscheme (sub_scope, sub_proto, sub_prop)) = sub_scheme in
let (Fscheme (sup_scope, sup_proto, sup_prop)) = sup_scheme in
assert (not (Scope.equal sub_scope sup_scope));
(* To compare them, we need the two constraints to use the same set
of free variables. For example, if sub_scheme and sup_scheme are
- ((function():int{p1}), Csub) and,
- ((function():int{p2}), Csup)
we rename p2 into p1 by conjoining p2 = p1 to Csup and
quantifying p2 away. *)
let sup_props =
let accum = ref [sup_prop] in
let rec equate pt1 pt2 =
let eqpol p1 p2 = accum := L.(p1 = p2) ~pos !accum in
Ifc_mapper.iter_ptype2 equate eqpol pt1 pt2
in
equate (Tfun sub_proto.fp_type) (Tfun sup_proto.fp_type);
begin
match (sub_proto.fp_this, sup_proto.fp_this) with
| (Some sub_this_ty, Some sup_this_ty) -> equate sub_this_ty sup_this_ty
| (None, None) -> ()
| _ -> invalid_arg "method/function mismatch"
end;
!accum
in
let sub_vars =
let fp_vars = free_pvars (Tfun sub_proto.fp_type) in
match sub_proto.fp_this with
| Some sub_this_ty -> VarSet.union fp_vars (free_pvars sub_this_ty)
| None -> fp_vars
in
let pred v = not @@ VarSet.mem v sub_vars in
let sup_lattice =
Logic.conjoin sup_props
|> Logic.quantify ~pred ~quant:Qexists
|> Logic.simplify
|> Logic.flatten_prop
|> Ifc_security_lattice.transitive_closure
in
let sub_prop =
sub_prop |> Logic.quantify ~pred ~quant:Qexists |> Logic.simplify
in
Logic.entailment_violations sup_lattice sub_prop
let analyse_callable
?class_name
~pos
~opts
~decl_env
~is_static
~saved_env
~ctx
name
params
body
return =
try
(* Setup the read-only environment *)
let scope = Scope.alloc () in
let renv = Env.new_renv scope decl_env saved_env ctx in
let global_pc = Env.new_policy_var renv "pc" in
let exn = Lift.class_ty ~prefix:"exn" renv Decl.exception_id in
(* Here, we ignore the type parameters of this because at the moment we
* lack Tgeneric policy type. This will be fixed (T68414656) in the future.
*)
let this_ty =
match class_name with
| Some cname when not is_static -> Some (Lift.class_ty renv cname)
| _ -> None
in
let ret_ty = Lift.ty ~prefix:"ret" renv return in
let renv = Env.prep_renv renv this_ty ret_ty exn global_pc in
(* Initialise the mutable environment *)
let env = Env.prep_stmt Env.empty_env Env.empty_cont in
let params = lift_params renv params in
let env = set_local_types env params in
(* Run the analysis *)
let beg_env = env in
let (env, out_blk) = block renv env body.A.fb_ast in
let out_blk = Env.merge_next_in out_blk K.Exit in
let end_env = env in
(* Display the analysis results *)
if should_print ~user_mode:opts.opt_mode ~phase:Manalyse then begin
Format.printf "Analyzing %s:@." name;
Format.printf "%a@." Pp.renv renv;
Format.printf "* Params:@, %a@." Pp.cont (Env.get_next beg_env);
Format.printf "* Final environment:@, %a@." Pp.env end_env;
begin
match KMap.find_opt K.Exit out_blk with
| Some cont -> Format.printf " Locals:@, %a@." Pp.cont cont
| None -> ()
end;
Format.printf "@."
end;
let callable_name = Decl.make_callable_name ~is_static class_name name in
let callable_name_str = Decl.callable_name_to_string callable_name in
let f_self = Env.new_policy_var renv callable_name_str in
let proto =
{
fp_name = callable_name_str;
fp_this = this_ty;
fp_type =
{
f_pc = global_pc;
f_self;
f_args = List.map ~f:snd params;
f_ret = ret_ty;
f_exn = exn;
};
}
in
let entailment =
match Decl.get_callable_decl renv.re_ctx callable_name with
| Some { fd_kind = FDPolicied policy; fd_args } ->
let scheme = Decl.make_callable_scheme renv policy proto fd_args in
fun prop ->
let fun_scheme = Fscheme (scope, proto, prop) in
check_subtype_scheme ~pos fun_scheme scheme
| _ -> const []
in
(* Return the results *)
let res =
{
res_span = pos;
res_proto = proto;
res_scope = scope;
res_constraint = Logic.conjoin (Env.get_constraints env);
res_deps = Env.get_deps env;
res_entailment = entailment;
}
in
Some res
with
| IFCError (FlowInference s) ->
if should_print ~user_mode:opts.opt_mode ~phase:Manalyse then
Format.printf "Analyzing %s:@. Failure: %s@.@." name s;
None
let walk_tast opts decl_env ctx =
let def = function
| A.Fun fd ->
let (_, name) = fd.A.fd_name in
let {
A.f_annotation = saved_env;
f_params = params;
f_body = body;
f_ret = (return, _);
f_span = pos;
_;
} =
fd.A.fd_fun
in
let is_static = false in
let callable_res =
analyse_callable
~opts
~pos
~decl_env
~is_static
~saved_env
~ctx
name
params
body
return
in
Option.map ~f:(fun x -> [x]) callable_res
| A.Class { A.c_name = (_, class_name); c_methods = methods; _ } ->
let handle_method
{
A.m_name = (_, name);
m_annotation = saved_env;
m_params = params;
m_body = body;
m_ret = (return, _);
m_span = pos;
m_static = is_static;
_;
} =
analyse_callable
~opts
~class_name
~pos
~decl_env
~is_static
~saved_env
~ctx
name
params
body
return
in
Some (List.filter_map ~f:handle_method methods)
| _ -> None
in
(fun tast -> List.concat (List.filter_map ~f:def tast))
let check_valid_flow _opts _ (_result, _implicit, _simple) = ()
let simplify result =
let pred = const true in
( result,
result.res_entailment result.res_constraint,
Logic.simplify @@ Logic.quantify ~pred ~quant:Qexists result.res_constraint
)
let get_solver_result results =
try Ifc_solver.global_exn ~subtype results with
| Ifc_solver.Error Ifc_solver.RecursiveCycle ->
fail "solver error: cyclic call graph"
| Ifc_solver.Error (Ifc_solver.MissingResults callable) ->
fail "solver error: missing results for callable '%s'" callable
| Ifc_solver.Error (Ifc_solver.InvalidCall (caller, callee)) ->
fail "solver error: invalid call to '%s' in '%s'" callee caller
let check opts tast ctx =
(* Declaration phase *)
let decl_env = Decl.collect_sigs tast in
if should_print ~user_mode:opts.opt_mode ~phase:Mdecl then
Format.printf "%a@." Pp.decl_env decl_env;
(* Flow analysis phase *)
let results = walk_tast opts decl_env ctx tast in
(* Solver phase *)
let results = get_solver_result results in
let simplified_results = SMap.map simplify results in
let log_solver name (result, _, simplified) =
Format.printf "@[<v>";
Format.printf "Flow constraints for %s:@. @[<v>" name;
Format.printf "@,@[<hov>Simplified:@ @[<hov>%a@]@]" Pp.prop simplified;
let raw = result.res_constraint in
Format.printf "@,@[<hov>Raw:@ @[<hov>%a@]@]" Pp.prop raw;
Format.printf "@]";
Format.printf "@]\n\n"
in
if should_print ~user_mode:opts.opt_mode ~phase:Msolve then
SMap.iter log_solver simplified_results;
SMap.iter (check_valid_flow opts) simplified_results |
OCaml Interface | hhvm/hphp/hack/src/ifc/ifc.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val should_print : user_mode:Ifc_types.mode -> phase:Ifc_types.mode -> bool
val check : Ifc_types.options -> Tast.def list -> Provider_context.t -> unit
val get_solver_result :
Ifc_types.callable_result list -> Ifc_types.callable_result SMap.t
val simplify :
Ifc_types.callable_result ->
Ifc_types.callable_result * Ifc_types.pos_flow list * Ifc_types.prop
val check_valid_flow :
Ifc_types.options ->
'a ->
Ifc_types.callable_result
* (Ifc_types.PosSet.t * Ifc_types.policy * Ifc_types.policy) list
* Ifc_types.prop ->
unit
val analyse_callable :
?class_name:Ifc_types.purpose ->
pos:Pos.t ->
opts:Ifc_types.options ->
decl_env:Ifc_types.decl_env ->
is_static:bool ->
saved_env:Tast.saved_env ->
ctx:Provider_context.t ->
Ifc_types.purpose ->
Tast.fun_param list ->
Tast.func_body ->
Typing_defs.locl_ty ->
Ifc_types.callable_result option |
OCaml | hhvm/hphp/hack/src/ifc/ifc_decl.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Common
open Ifc_types
module Env = Ifc_env
module Logic = Ifc_logic
module Mapper = Ifc_mapper
module Lattice = Ifc_security_lattice
module L = Logic.Infix
module A = Aast
module T = Typing_defs
module SN = Naming_special_names
(* Everything done in this file should eventually be merged in Hack's
regular decl phase. Right now it is more convenient to keep things
simple and separate here. *)
exception FlowDecl of string
let fail s = raise (FlowDecl s)
let policied_id = SN.UserAttributes.uaPolicied
let infer_flows_id = SN.UserAttributes.uaInferFlows
let exception_id = "\\Exception"
let out_of_bounds_exception_id = "\\OutOfBoundsException"
let vec_id = "\\HH\\vec"
let dict_id = "\\HH\\dict"
let keyset_id = "\\HH\\keyset"
let awaitable_id = "\\HH\\Awaitable"
let construct_id = SN.Members.__construct
let external_id = SN.UserAttributes.uaExternal
let callable_id = SN.UserAttributes.uaCanCall
let convert_ifc_fun_decl pos (tfd : T.ifc_fun_decl) : fun_decl_kind =
match tfd with
| T.FDInferFlows -> FDInferFlows
| T.FDPolicied None -> FDPolicied None
| T.FDPolicied (Some purpose) ->
FDPolicied (Some (Lattice.parse_policy (PosSet.singleton pos) purpose))
let get_method_from_provider ~static ctx class_name method_name =
match Decl_provider.get_class ctx class_name with
| None -> None
| Some cls when static -> Decl_provider.Class.get_smethod cls method_name
| Some cls when String.equal method_name construct_id ->
let (construct_opt, _) = Typing_classes_heap.Api.construct cls in
construct_opt
| Some cls -> Decl_provider.Class.get_method cls method_name
let convert_fun_type ctx fun_ty =
let open Typing_defs in
let resolve = Naming_provider.resolve_position ctx in
let pos = get_pos fun_ty |> resolve in
let fty = get_node fun_ty in
match fty with
| Tfun { ft_params; ft_ifc_decl; _ } ->
let fd_kind = convert_ifc_fun_decl pos ft_ifc_decl in
let mk_arg fp =
let pos = resolve fp.fp_pos in
match (T.get_fp_ifc_can_call fp, T.get_fp_ifc_external fp) with
| (_, true) -> AKExternal pos
| (true, _) -> AKCallable pos
| (false, false) -> AKDefault
in
let fd_args = List.map ft_params ~f:mk_arg in
{ fd_kind; fd_args }
| _ -> fail "Expected a Tfun type from function declaration"
(* Grab a function from the decl heap and convert it into a fun decl*)
let get_fun (ctx : Provider_context.t) (fun_name : string) : fun_decl option =
let open Typing_defs in
match Decl_provider.get_fun ctx fun_name with
| None -> None
| Some { fe_type; _ } -> Some (convert_fun_type ctx fe_type)
(* Grab a method from the decl heap and convert it into a fun_decl *)
let get_method
(ctx : Provider_context.t) (class_name : string) (method_name : string) :
fun_decl option =
let open Typing_defs in
match get_method_from_provider ~static:false ctx class_name method_name with
(* The default constructor for classes is public and takes no arguments *)
| None when String.equal method_name construct_id ->
let default_kind =
convert_ifc_fun_decl Pos.none Typing_defs.default_ifc_fun_decl
in
Some { fd_kind = default_kind; fd_args = [] }
| None -> None
| Some { ce_type = (lazy fun_type); _ } ->
Some (convert_fun_type ctx fun_type)
let get_static_method
(ctx : Provider_context.t) (class_name : string) (method_name : string) :
fun_decl option =
let open Typing_defs in
match get_method_from_provider ~static:true ctx class_name method_name with
| None -> None
| Some { ce_type = (lazy fun_type); _ } ->
Some (convert_fun_type ctx fun_type)
(* Grab any callable from the decl heap *)
let get_callable_decl (ctx : Provider_context.t) (callable_name : callable_name)
: fun_decl option =
match callable_name with
| Method (cls, name) -> get_method ctx cls name
| StaticMethod (cls, name) -> get_static_method ctx cls name
| Function name -> get_fun ctx name
let callable_name_to_string = function
| StaticMethod (cls, name)
| Method (cls, name) ->
cls ^ "#" ^ name
| Function name -> name
let make_callable_name ~is_static cls_name_opt name =
match cls_name_opt with
| None -> Function name
| Some cls_name when is_static -> StaticMethod (cls_name, name)
| Some cls_name -> Method (cls_name, name)
(* Grab an attribute from a list of attrs. Only used for policy properties *)
let get_attr attr attrs =
let is_attr a = String.equal (snd a.A.ua_name) attr in
match List.filter ~f:is_attr attrs with
| [] -> None
| [a] -> Some a
| _ -> fail ("multiple '" ^ attr ^ "' attributes found")
let immediate_supers { A.c_uses; A.c_extends; _ } =
let id_of_hint = function
| (_, A.Happly (id, _)) -> snd id
| _ -> fail "unexpected hint in inheritance hierarchy"
in
List.map ~f:id_of_hint (c_extends @ c_uses)
(* A property declared in a trait T can be redeclared in a class or a trait
* inheriting from T. When this property is policied it will be inherited with a
* (possibly) different policied annotation. We need to pick one.
*
* Our criteria for resolution is:
* 1. If both declarations are unpolicied, it is not a policied property;
* 2. If only one is policied, it is a policied property (possibly with a purpose);
* 3. If both of them are policied and
* a. neither has a purpose, property is policied without a purpose
* b. only one has a purpose, property is policied with that purpose
* c. both have the same purpose, property is policied with that purpose
* d. have differing purposes, it is an error
*
* (1) and (2) are enforced automatically by the virtue of only keeping track
* of policied properties. The following function enforces (3).
*)
let resolve_duplicate_policied_properties policied_properties =
let err_msg name purp1 purp2 =
name ^ " has purpose " ^ purp1 ^ " and " ^ purp2 ^ " due to inheritance"
in
let prop_table = Caml.Hashtbl.create 10 in
let go pprop =
match Caml.Hashtbl.find_opt prop_table pprop.pp_name with
| Some pprop' ->
if not @@ String.equal pprop.pp_purpose pprop'.pp_purpose then
fail @@ err_msg pprop.pp_name pprop.pp_purpose pprop'.pp_purpose
| None -> Caml.Hashtbl.add prop_table pprop.pp_name pprop
in
List.iter ~f:go policied_properties;
Caml.Hashtbl.fold (fun _ pprop acc -> pprop :: acc) prop_table []
let is_visible pp = not @@ A.equal_visibility A.Private pp.pp_visibility
let add_super class_decl_env class_decl_acc super =
match SMap.find_opt super class_decl_env with
| Some { cd_policied_properties } ->
let super_props = List.filter ~f:is_visible cd_policied_properties in
let props = super_props @ class_decl_acc.cd_policied_properties in
{ cd_policied_properties = props }
| None ->
(* Must be a builtin. Assume that builtins don't have policied properties *)
class_decl_acc
let mk_policied_prop
{
A.cv_span = pp_pos;
cv_id = (_, pp_name);
cv_visibility = pp_visibility;
cv_user_attributes = attrs;
_;
} =
let find_policy attributes =
match get_attr policied_id attributes with
| None -> `No_policy
| Some attr ->
(match attr.A.ua_params with
| [(_, _, A.String purpose)] -> `Policy purpose
| _ -> fail "expected a string literal as a purpose argument")
in
match find_policy attrs with
| `No_policy -> None
| `Policy pp_purpose -> Some { pp_name; pp_visibility; pp_purpose; pp_pos }
let class_ class_decl_env class_ =
let { A.c_name = (_, name); c_vars = properties; _ } = class_ in
(* Class decl using the immediately available information of the base class *)
let cd_policied_properties = List.filter_map ~f:mk_policied_prop properties in
let base_class_decl = { cd_policied_properties } in
(* Class decl extended with inherited policied properties *)
let supers = immediate_supers class_ in
let class_decl =
let f = add_super class_decl_env in
List.fold ~f ~init:base_class_decl supers
in
let cd_policied_properties =
resolve_duplicate_policied_properties class_decl.cd_policied_properties
|> List.sort ~compare:(fun p1 p2 -> String.compare p1.pp_name p2.pp_name)
in
let class_decl = { cd_policied_properties } in
(name, class_decl)
let topsort_classes classes =
(* Record the class hierarchy *)
let dependency_table = Caml.Hashtbl.create 10 in
let id_of_hint = function
| (_, A.Happly (id, _)) -> snd id
| _ -> fail "unexpected hint in inheritance hierarchy"
in
let go ({ A.c_name; A.c_extends; A.c_uses; _ } as class_) =
let supers = List.map ~f:id_of_hint (c_extends @ c_uses) in
Caml.Hashtbl.add dependency_table (snd c_name) (class_, supers, false)
in
List.iter ~f:go classes;
(* Put classes, traits, and interfaces in topological order *)
let schedule = ref [] in
let rec process id =
match Caml.Hashtbl.find_opt dependency_table id with
| Some (class_, dependencies, is_visited) ->
if not is_visited then begin
Caml.Hashtbl.replace dependency_table id (class_, dependencies, true);
List.iter ~f:process dependencies;
schedule := class_ :: !schedule
end
| None ->
(* Must be a builtin. Assume that builtins don't have policied properties *)
()
in
List.iter ~f:process (List.map ~f:(fun c -> snd c.A.c_name) classes);
List.rev !schedule
(* Removes all the auxiliary info needed only during declaration analysis. *)
let collect_sigs defs =
let pick = function
| A.Class class_ -> Some class_
| _ -> None
in
let classes = List.filter_map ~f:pick defs |> topsort_classes in
(* Process and accumulate class decls *)
let init = { de_class = SMap.empty } in
let add_class_decl { de_class } cls =
let (class_name, class_decl) = class_ de_class cls in
let de_class = SMap.add class_name class_decl de_class in
{ de_class }
in
List.fold ~f:add_class_decl ~init classes
let property_policy { de_class } cname pname =
Option.(
SMap.find_opt cname de_class >>= fun cls ->
List.find
~f:(fun p -> String.equal p.pp_name pname)
cls.cd_policied_properties
>>= fun p ->
return
(Ifc_security_lattice.parse_policy
(PosSet.singleton p.pp_pos)
p.pp_purpose))
(* Builds the type scheme for a callable *)
let make_callable_scheme renv pol fp args =
let renv = { renv with re_scope = Scope.alloc () } in
let policy =
match pol with
| Some policy -> policy
| None -> Env.new_policy_var renv "implicit"
in
let rec set_policy p pty = Mapper.ptype (set_policy p) (const p) pty in
let (acc, args) =
let f acc ty = function
| AKDefault -> (acc, set_policy policy ty)
| AKExternal pos ->
let ext = Env.new_policy_var renv "external" in
(L.(ext < policy) ~pos acc, set_policy ext ty)
| AKCallable pos ->
let c = Env.new_policy_var renv "callable" in
(L.(policy < c) ~pos acc, set_policy c ty)
in
(* The length of arguments in the function type may not match that of
argument kinds which is derived from the decl. Since all default
arguments are public, we simply truncate the list. *)
let fp_args = fp.fp_type.f_args in
List.map2_env [] ~f fp_args (List.take args @@ List.length fp_args)
in
let fp' =
{
fp_name = fp.fp_name;
fp_this = Option.map ~f:(set_policy policy) fp.fp_this;
fp_type =
{
f_pc = policy;
f_args = args;
f_ret = set_policy policy fp.fp_type.f_ret;
f_exn = set_policy policy fp.fp_type.f_exn;
f_self = pbot;
};
}
in
Fscheme (renv.re_scope, fp', Logic.conjoin acc) |
OCaml | hhvm/hphp/hack/src/ifc/ifc_env.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Ifc_types
module Utils = Ifc_utils
module K = Typing_cont_key
(* See ifc_env.mli for the docmentation *)
(* Only elementary logic about the environments should
be in this file to avoid circular dependencies;
use higher-order functions to parameterize complex
behavior! *)
(* - Read-only environments (renv) - *)
let new_policy_var { re_scope; re_pvar_counters; _ } prefix =
let prefix = String.lstrip ~drop:(Char.equal '\\') prefix in
let suffix =
match Caml.Hashtbl.find_opt re_pvar_counters prefix with
| Some counter ->
incr counter;
"'" ^ string_of_int !counter
| None ->
Caml.Hashtbl.add re_pvar_counters prefix (ref 0);
""
in
Pfree_var (prefix ^ suffix, re_scope)
let new_renv scope decl_env saved_tenv ctx =
{
re_scope = scope;
re_decl = decl_env;
re_pvar_counters = Caml.Hashtbl.create 10;
re_tenv = saved_tenv;
(* the fields below are initialized with dummy values *)
re_this = None;
re_ret = ();
re_gpc = pbot;
re_exn = ();
re_ctx = ctx;
}
let prep_renv renv this_ty_opt ret_ty exn_ty gpc_pol =
{
re_scope = renv.re_scope;
re_decl = renv.re_decl;
re_pvar_counters = renv.re_pvar_counters;
re_tenv = renv.re_tenv;
re_this = this_ty_opt;
re_ret = ret_ty;
re_gpc = gpc_pol;
re_exn = exn_ty;
re_ctx = renv.re_ctx;
}
(* - Read/write environments (env) - *)
type yes = unit
type no = unit
type ('has_locals, 'can_throw) env = {
e_nxt: cont;
e_exn: cont option;
e_acc: prop list;
e_deps: SSet.t;
}
type blank_env = (no, no) env
type stmt_env = (yes, no) env
type expr_env = (yes, yes) env
let empty_cont = { k_pc = PSet.empty; k_vars = LMap.empty }
let empty_env =
{ e_nxt = empty_cont; e_exn = None; e_acc = []; e_deps = SSet.empty }
let prep_stmt env cont = { env with e_nxt = cont; e_exn = None }
let prep_expr env = { env with e_exn = None }
let get_lpc env = env.e_nxt.k_pc
let get_gpc renv env = PSet.add renv.re_gpc (get_lpc env)
let get_deps env = env.e_deps
let get_constraints env = env.e_acc
let get_locals env = env.e_nxt.k_vars
let get_next env = env.e_nxt
(* Not exported, see with_pc, with_pc_deps, and throw *)
let set_pc env pc = { env with e_nxt = { env.e_nxt with k_pc = pc } }
let with_pc env pc (fn : stmt_env -> blank_env * 'a) =
let env = set_pc env pc in
(* there is nothing to restore in the resulting env because
fn returns a blank env (i.e., with e_nxt cleared) *)
fn env
let with_pc_deps env deps = with_pc env (PSet.union (get_lpc env) deps)
let expr_with_pc_deps env deps (fn : expr_env -> expr_env * 'a) =
let lpc = get_lpc env in
let env = set_pc env (PSet.union lpc deps) in
let (env, res) = fn env in
(set_pc env lpc, res)
let acc env update = { env with e_acc = update env.e_acc }
let add_dep env name = { env with e_deps = SSet.add name env.e_deps }
let close_expr env =
let out_throw =
match env.e_exn with
| None -> KMap.empty
| Some cont -> KMap.singleton K.Catch cont
in
let env = prep_stmt env env.e_nxt in
(env, out_throw)
(* To merge contexts we need to compute union types for local variables;
we don't want to be smart here, to avoid lagging behind the fancy
heuristics in the Hack typechecker, so we are instead very dumb!
This lack of sophistication is mitigated by the logic in the IFC
analysis that keeps looking for better types in the annotated AST *)
let union_types t1 t2 =
if phys_equal t1 t2 then
t1
else
Tunion [t1; t2]
(* Merge two local envs, if a variable appears only in one local
env, it will not appear in the result env *)
let merge_cont cont1 cont2 =
let combine _ = Utils.combine_opts false union_types in
let k_vars = LMap.merge combine cont1.k_vars cont2.k_vars in
let k_pc = PSet.union cont1.k_pc cont2.k_pc in
{ k_vars; k_pc }
let merge_cont_opt = Utils.combine_opts true merge_cont
let throw env deps =
let env = set_pc env (PSet.union (get_lpc env) deps) in
{ env with e_exn = merge_cont_opt env.e_exn (Some (get_next env)) }
let analyze_lambda_body env fn =
let e_nxt = get_next env in
let e_exn = env.e_exn in
let env = fn env in
{ env with e_nxt; e_exn }
let get_local_type env lid = LMap.find_opt lid env.e_nxt.k_vars
let set_local_type env lid pty =
let k_vars = LMap.add lid pty env.e_nxt.k_vars in
{ env with e_nxt = { env.e_nxt with k_vars } }
let set_local_type_opt env lid pty =
let k_vars = LMap.update lid (fun _ -> pty) env.e_nxt.k_vars in
{ env with e_nxt = { env.e_nxt with k_vars } }
(* - Outcomes - *)
let merge_out out1 out2 = KMap.merge (fun _ -> merge_cont_opt) out1 out2
let close_stmt ?(merge = KMap.empty) env k =
let out = KMap.singleton k (get_next env) in
let out = merge_out out merge in
let env = { env with e_nxt = empty_cont; e_exn = None } in
(env, out)
let strip_cont out k = (KMap.remove k out, KMap.find_opt k out)
let merge_in_next out k =
let (out, cont_k) = strip_cont out k in
let (out, cont_next) = strip_cont out K.Next in
match merge_cont_opt cont_k cont_next with
| None -> out
| Some cont -> KMap.add K.Next cont out
let merge_next_in out k =
let (out, cont_k) = strip_cont out k in
let (out, cont_next) = strip_cont out K.Next in
match merge_cont_opt cont_k cont_next with
| None -> out
| Some cont -> KMap.add k cont out |
OCaml Interface | hhvm/hphp/hack/src/ifc/ifc_env.mli | open Ifc_types
(* - Read-only environments (renv) - *)
(* Creates a read-only environment sufficient to call functions
from ifc_lift.ml *)
val new_renv :
Ifc_scope.t -> decl_env -> Tast.saved_env -> Provider_context.t -> proto_renv
(* Prepares a read-only environment to type-check a function *)
val prep_renv : proto_renv -> ptype option -> ptype -> ptype -> policy -> renv
val new_policy_var : 'a renv_ -> string -> policy
(* - Read/write environments (env) - *)
(* To provide a safe API for environments that prevents
programming errors, the env type is abstract and has
two phantom parameters *)
type yes
and no
(* The first parameter is yes iff the environment has meaningful
type information about the local variables.
The second parameter is yes iff the environment can be used
to register that an exception might be thrown (using the
throw function below). *)
type ('has_locals, 'can_throw) env
(* blank_env, stmt_env, and expr_env are handy aliases; a
blank_env cannot do much, stmt_env and expr_env are used
to typecheck statements and expressions, respecitively *)
type blank_env = (no, no) env
type stmt_env = (yes, no) env
type expr_env = (yes, yes) env
val empty_env : blank_env
(* prep_stmt turns a blank_env into a stmt_env using a continuation
that contains the control flow dependencies and the type of local
variables *)
val prep_stmt : blank_env -> cont -> stmt_env
val prep_expr : stmt_env -> expr_env
val close_expr : expr_env -> stmt_env * cont KMap.t
(* close_stmt is used to finish the analysis of a statement; if
the 'merge' outcome is provided it is merged in the final
outcome.
The Typing_cont_key.t parameter indicates the main outcome of
the statement. *)
val close_stmt :
?merge:cont KMap.t -> stmt_env -> Typing_cont_key.t -> blank_env * cont KMap.t
(* get_gpc returns the current global pc policy *)
val get_gpc : renv -> (yes, 'a) env -> PSet.t
(* get_lpc returns the current local pc policy *)
val get_lpc : (yes, 'a) env -> PSet.t
(* with_pc runs the sub-analysis provided as function argument with
updated control-flow dependencies.
This API ensures that pc dependencies evolve according to
a stack discipline in envs *)
val with_pc :
stmt_env -> PSet.t -> (stmt_env -> blank_env * 'a) -> blank_env * 'a
(* Same as with_pc but adds to the existing control-flow dependencies
instead of replacing them *)
val with_pc_deps :
stmt_env -> PSet.t -> (stmt_env -> blank_env * 'a) -> blank_env * 'a
(* expr_with_pc_deps runs a closure in an environment locally extended
with additional control flow dependencies *)
val expr_with_pc_deps :
expr_env -> PSet.t -> (expr_env -> expr_env * 'a) -> expr_env * 'a
val get_locals : (yes, 'a) env -> ptype LMap.t
val get_next : (yes, 'a) env -> cont
(* get_deps return the set of static callables which were accumulated
in the environment *)
val get_deps : ('a, 'b) env -> SSet.t
(* add_dep adds a dependency in the dependency accumulator of th
environment *)
val add_dep : ('a, 'b) env -> string -> ('a, 'b) env
(* acc is used to accumulate constraints in the environment *)
val acc : ('a, 'b) env -> (prop list -> prop list) -> ('a, 'b) env
val get_constraints : ('a, 'b) env -> prop list
(* throw registers that the expression currently being checked
can throw an exception; the exception may or may not be thrown
depending on the value of some data subject to the policies
passed as second argument *)
val throw : expr_env -> PSet.t -> expr_env
(* analyze_lambda_body is used to check the body of a lambda; it
is necessary to transition to a stmt_env in an expr_env
(the environment in which the lambda occured) without having
to close the expr_env *)
val analyze_lambda_body : expr_env -> (blank_env -> blank_env) -> expr_env
val get_local_type : (yes, 'a) env -> Local_id.t -> ptype option
val set_local_type : (yes, 'a) env -> Local_id.t -> ptype -> (yes, 'a) env
(* Update or remove a local from the env *)
val set_local_type_opt :
(yes, 'a) env -> Local_id.t -> ptype option -> (yes, 'a) env
(* - Outcomes - *)
val empty_cont : cont
(* merge_out merges outcomes; if a continuation is assigned
a local env only in one of the arguments it will be kept
as is in the result. This is because lack of a continuation
means that some code was, up to now, dead code. *)
val merge_out : cont KMap.t -> cont KMap.t -> cont KMap.t
(* strip_cont removes and returns a continuation of an outcome *)
val strip_cont : cont KMap.t -> Typing_cont_key.t -> cont KMap.t * cont option
(* merge_in_next will erase the outcome designated by its second
argument and merge it in the fallthrough (Next) outcome; this
function also works when the argument continuation is Next
itself (in this case, it does not change the outcome map) *)
val merge_in_next : cont KMap.t -> Typing_cont_key.t -> cont KMap.t
(* Same as merge_in_next except that it merges the fallthrough
outcome in the one designated by the second argument *)
val merge_next_in : cont KMap.t -> Typing_cont_key.t -> cont KMap.t |
OCaml | hhvm/hphp/hack/src/ifc/ifc_lift.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 Ifc_types
module Decl = Ifc_decl
module Env = Ifc_env
module T = Typing_defs
module TClass = Decl_provider.Class
module TReason = Typing_reason
let fail fmt = Format.kasprintf (fun s -> raise (IFCError (LiftError s))) fmt
let expand_var renv id =
(* Drops the environment. Var expansion only compresses paths, so this is
* safe (but less efficient than threading the environment). *)
let (_, ty) =
Typing_inference_env.expand_var
renv.re_tenv.Tast.inference_env
Typing_reason.Rnone
id
in
ty
(* Returns the lump policy if there is one in effect, otherwise
generates a fresh policy variable *)
let get_policy ?prefix lump renv =
match lump with
| Some policy -> policy
| None ->
let prefix = Option.value prefix ~default:"v" in
Env.new_policy_var renv prefix
let class_ty ?prefix ?lump renv name =
let prefix = Option.value ~default:name prefix in
Tclass
{
c_name = name;
c_self = get_policy lump renv ~prefix;
c_lump = get_policy lump renv ~prefix:(prefix ^ "_lump");
}
(* Turns a locl_ty into a type with policy annotations;
the policy annotations are fresh policy variables *)
let rec ty ?prefix ?lump renv (t : T.locl_ty) =
let ty = ty ?prefix ?lump renv in
match T.get_node t with
| T.Tprim Aast.Tnull -> Tnull (get_policy ?prefix lump renv)
| T.Tprim _ -> Tprim (get_policy ?prefix lump renv)
| T.Tnonnull ->
let pself = get_policy ?prefix lump renv
and plump = get_policy ?prefix lump renv in
Tnonnull (pself, plump)
| T.Tdynamic -> Tdynamic (get_policy ?prefix lump renv)
| T.Tgeneric (_name, _targs) ->
(* TODO(T69551141) Handle type arguments *)
Tgeneric (get_policy ?prefix lump renv)
| T.Tclass ((_, "\\HH\\Pair"), _, tyl)
| T.Ttuple tyl ->
Ttuple (List.map ~f:ty tyl)
| T.Tunion tyl -> Tunion (List.map ~f:ty tyl)
| T.Tintersection tyl -> Tinter (List.map ~f:ty tyl)
| T.Tclass ((_, "\\HH\\ConstSet"), _, [element_ty])
| T.Tclass ((_, "\\HH\\ConstVector"), _, [element_ty])
| T.Tclass ((_, "\\HH\\ImmSet"), _, [element_ty])
| T.Tclass ((_, "\\HH\\ImmVector"), _, [element_ty])
| T.Tclass ((_, "\\HH\\vec"), _, [element_ty]) ->
Tcow_array
{
a_kind = Avec;
(* Inventing a policy type for indices out of thin air *)
a_key = Tprim (get_policy ~prefix:"key" lump renv);
a_value = ty element_ty;
a_length = get_policy ~prefix:"len" lump renv;
}
| T.Tvec_or_dict (key_ty, value_ty)
| T.Tclass ((_, "\\HH\\ConstMap"), _, [key_ty; value_ty])
| T.Tclass ((_, "\\HH\\ImmMap"), _, [key_ty; value_ty])
| T.Tclass ((_, "\\HH\\dict"), _, [key_ty; value_ty]) ->
Tcow_array
{
a_kind = Adict;
a_key = ty key_ty;
a_value = ty value_ty;
a_length = get_policy ~prefix:"len" lump renv;
}
| T.Tclass ((_, "\\HH\\keyset"), _, [value_ty]) ->
let element_pty = ty value_ty in
Tcow_array
{
a_kind = Akeyset;
(* Keysets have identical keys and values with identity
$keyset[$ix] === $ix (as bizarre as it is) *)
a_key = element_pty;
a_value = element_pty;
a_length = get_policy ~prefix:"len" lump renv;
}
| T.Tclass ((_, name), _, targs) when String.equal name Decl.awaitable_id ->
begin
match targs with
(* NOTE: Strip Awaitable out of the type since it has no affect on
information flow *)
| [inner_ty] -> ty inner_ty
| _ -> fail "Awaitable needs one type parameter"
end
| T.Tclass ((_, name), _, _) -> class_ty ?lump renv name
| T.Tvar id -> ty (expand_var renv id)
| T.Tfun fun_ty ->
Tfun
{
f_pc = get_policy ~prefix:"pc" lump renv;
f_self = get_policy ?prefix lump renv;
f_args =
List.map ~f:(fun p -> ty p.T.fp_type.T.et_type) fun_ty.T.ft_params;
f_ret = ty fun_ty.T.ft_ret.T.et_type;
f_exn = class_ty ?lump renv Decl.exception_id;
}
| T.Toption t ->
let tnull = Tnull (get_policy ?prefix lump renv) in
Tunion [tnull; ty t]
| T.(Tshape { s_origin = _; s_unknown_value = kind; s_fields = fields }) ->
let lift sft =
{
sft_optional = sft.T.sft_optional;
sft_policy = get_policy ?prefix lump renv;
sft_ty = ty sft.T.sft_ty;
}
in
let sh_kind =
if T.is_nothing kind then
Closed_shape
else
Open_shape (ty kind)
in
Tshape { sh_kind; sh_fields = Typing_defs.TShapeMap.map lift fields }
(* --- types below are not yet supported *)
| T.Tdependent (_, _ty) -> fail "Tdependent"
| T.Tany _sentinel -> fail "Tany"
| T.Tnewtype (_name, _ty_list, _as_bound) -> fail "Tnewtype"
| T.Taccess (_locl_ty, _ids) -> fail "Taccess"
| T.Tunapplied_alias _ -> fail "Tunapplied_alias"
| T.Tneg _ -> fail "Tneg" |
OCaml | hhvm/hphp/hack/src/ifc/ifc_logic.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Ifc_utils
open Ifc_types
module IMap = Int.Map
module Mapper = Ifc_mapper
(* A note on the lattice. Policies form a lattice with the
partial order <. This relation reads 'flows to'. Bottom,
the least policy can flow into all other policies, so it
is used for public data. Top, on the other hand, is used
for private data. *)
(* A small DSL to accumulate constraints *)
module Infix = struct
let on_lists ~pos l1 l2 ~op acc =
List.fold_left
(List.cartesian_product l1 l2)
~init:acc
~f:(fun acc (a, b) -> op ~pos a b acc)
let ( < ) ~pos a b acc =
match (a, b) with
| (Pbot _, _) -> acc
| (_, Ptop _) -> acc
| _ when equal_policy a b -> acc
| _ -> Cflow (PosSet.singleton pos, a, b) :: acc
let ( <* ) ~pos al bl = on_lists ~pos al bl ~op:( < )
let ( = ) ~pos a b acc =
Cconj
(Cflow (PosSet.singleton pos, a, b), Cflow (PosSet.singleton pos, b, a))
:: acc
let ( =* ) ~pos al bl = on_lists ~pos al bl ~op:( = )
let ( && ) ~pos c1 c2 env = c2 ~pos (c1 ~pos env)
end
(* Compute the meet of two policies, returns None if
one of the two policies is a variable. *)
let policy_meet p1 p2 =
let pos = PosSet.union (pos_set_of_policy p1) (pos_set_of_policy p2) in
match (p1, p2) with
| (Ptop _, p)
| (p, Ptop _) ->
Some (set_pos_set_of_policy pos p)
| (Ppurpose (_, n1), Ppurpose (_, n2)) ->
if String.equal n1 n2 then
Some (set_pos_set_of_policy pos p1)
else
Some (Pbot pos)
| (Pbot _, _)
| (_, Pbot _) ->
Some (Pbot pos)
| _ -> None
let policy_join p1 p2 =
let pos = PosSet.union (pos_set_of_policy p1) (pos_set_of_policy p2) in
match (p1, p2) with
| (Ptop _, _)
| (_, Ptop _) ->
Some (Ptop pos)
| (Pbot _, p)
| (p, Pbot _) ->
Some (set_pos_set_of_policy pos p)
| (Ppurpose (_, n1), Ppurpose (_, n2)) ->
if String.equal n1 n2 then
Some (set_pos_set_of_policy pos p1)
else
Some (Ptop pos)
| _ -> None
let conjoin = function
| [] -> Ctrue
| f :: l -> List.fold_left ~f:(fun c f -> Cconj (f, c)) ~init:f l
(* Shift bound variables by 'delta' in a policy *)
let shift ?(delta = -1) = function
| Pbound_var v ->
let v = v + delta in
assert (v >= 0);
Pbound_var v
| c -> c
(* Quantify variables matching a predicate in
a constraint; when the quantification happens
under D binders, ~depth:D should be passed *)
let quantify ~pred ~quant:q ?(depth = 0) c =
let n = ref 0 in
(* idx maps a free variable name to a bound
variable index *)
let idx =
let m = ref SMap.empty in
fun v ->
match SMap.find_opt v !m with
| Some i -> i
| None ->
let i = !n in
incr n;
m := SMap.add v i !m;
i
in
(* quantifies all free variables matching the predicate
"pred" inside a policy under d binders *)
let quantpol d = function
| Pfree_var (v, s) when pred (v, s) -> Pbound_var (d + idx v)
| c -> c
in
(* lifts quantpol to work on constraints *)
let rec quant d = Mapper.prop (quantpol d) quant d in
let quant_c = quant depth c in
if !n = 0 then
(* no free variable matched the predicate,
simply return the original constraint *)
c
else
Cquant (q, !n, quant_c)
(* A intermediate form for constraints where conditionals
are pushed as far outside as possible and no quantifiers
are left; it is used internally in the simplify function
below *)
type if_tree =
| ITE of (Pos.t * policy * purpose) * if_tree * if_tree
| FLW of (PosSet.t * policy * policy) list
(* Slow simplification procedure for constraints.
A correctness proof for the quantifier elimination is here:
https://github.com/mpu/hol/blob/master/hol4/constraintScript.sml *)
let simplify (c : prop) =
let split3 l =
(* Split a list of flow constraints as:
- lower bounds for (Pbound_var 0)
- upper bounds for (Pbound_var 0)
- the rest
*)
List.partition3_map l ~f:(function
| (poss, l, Pbound_var 0) -> `Fst (poss, l)
| (poss, Pbound_var 0, u) -> `Snd (poss, u)
| f -> `Trd f)
in
let elim_exists l =
(* Eliminate (Pbound_var 0) from a list of simple flow
constraints assuming it is existentially quantified *)
let (lbs, ubs, oth) = split3 l in
let merge ((poss1, pol1), (poss2, pol2)) =
(PosSet.union poss1 poss2, pol1, pol2)
in
List.cartesian_product lbs ubs
|> List.map ~f:merge
|> List.unordered_append oth
in
let elim_forall ~max l =
(* Eliminate (Pbound_var 0) from a list of simple flow
constraints assuming it is universally quantified, and
has 'max' as upper bound *)
let (lbs, ubs, oth) = split3 l in
List.concat
[
oth;
List.map ~f:(fun (pos, l) -> (pos, l, Pbot PosSet.empty)) lbs;
List.map ~f:(fun (pos, u) -> (pos, max, u)) ubs;
]
in
let dedup l =
let cpol = compare_policy in
let compare = Tuple3.compare ~cmp1:(fun _ _ -> 0) ~cmp2:cpol ~cmp3:cpol in
List.filter
~f:(fun (_, p1, p2) -> not (equal_policy p1 p2))
(List.dedup_and_sort ~compare l)
in
let rec pop = function
(* Shift all the indices of bound variables by one down;
this will crash if (Pbound_var 0) appears in the
constraint *)
| FLW l ->
let f (pos, a, b) = (pos, shift a, shift b) in
FLW (List.map ~f l)
| ITE ((pos, p, x), t1, t2) -> ITE ((pos, shift p, x), pop t1, pop t2)
in
let rec elim_exists_ift = function
(* Same as exelim above, but for if_tree constraints *)
| FLW l -> FLW (dedup (elim_exists l))
| ITE (((_, pol, _) as c), t1, t2) ->
assert (not (equal_policy pol (Pbound_var 0)));
ITE (c, elim_exists_ift t1, elim_exists_ift t2)
in
let rec cat t1 t2 =
(* Conjoin two if_tree constraints *)
match (t1, t2) with
| (FLW l1, FLW l2) -> FLW (dedup (l1 @ l2))
| (t, ITE (c, t1, t2))
| (ITE (c, t1, t2), t) ->
ITE (c, cat t t1, cat t t2)
in
let rec elim_forall_ift max = function
(* Same as alelim above, but for if_tree constraints *)
| FLW l -> FLW (elim_forall ~max l)
| ITE ((pos, Pbound_var 0, x), t1, t2) ->
let max_if =
Option.value_exn (policy_meet max (Ppurpose (PosSet.singleton pos, x)))
in
cat (elim_forall_ift max_if t1) (elim_forall_ift max t2)
| ITE (c, t1, t2) -> ITE (c, elim_forall_ift max t1, elim_forall_ift max t2)
in
let rec qelim c =
(* Stitching all of the above together lets us
eliminate all quantifiers from a constraint *)
match c with
| Cquant (q, n, c) ->
let elim =
match q with
| Qexists -> elim_exists_ift
| Qforall -> elim_forall_ift (Ptop PosSet.empty)
in
let elim l = pop (elim l) in
funpow n ~f:elim ~init:(qelim c)
| Ccond (c, ct, ce) -> ITE (c, qelim ct, qelim ce)
| Cflow (pos, p1, p2) -> FLW [(pos, p1, p2)]
| Cconj (cl, cr) -> cat (qelim cl) (qelim cr)
| Ctrue -> FLW []
| Chole _ -> invalid_arg "cannot simplify constraint with hole"
in
let rec import = function
(* Convert an if_tree constraint into a regular constraint *)
| FLW l -> conjoin (List.map ~f:(fun f -> Cflow f) l)
| ITE (c, t1, t2) -> Ccond (c, import t1, import t2)
in
import (qelim c)
(* Entailment procedure for props. This function decides C1 |= C2 where C1 is
* the transitive closure of flows and C2 is some prop where all holes are
* closed and all quantifiers are eliminated (via simplify). This function
* returns all flows that do not follow from the input lattice.
*)
let rec entailment_violations lattice = function
| Ctrue -> []
| Ccond ((pos, p1, p2), c1, c2) ->
let pos = PosSet.singleton pos in
let flow = (pos, p1, Ppurpose (pos, p2)) in
if List.is_empty @@ entailment_violations lattice (Cflow flow) then
entailment_violations lattice c1
else
entailment_violations lattice c2
| Cconj (c1, c2) ->
entailment_violations lattice c1 @ entailment_violations lattice c2
| Cflow (_, _, Ptop _)
| Cflow (_, Pbot _, _) ->
[]
| Cflow (_, p1, p2) when equal_policy p1 p2 -> []
| Cflow ((_, pol1, pol2) as flow) ->
if
FlowSet.mem (pol1, pol2) lattice
(* If some policy flows into PUBLIC then it flows into anything. If PRIVATE
flows into a policy, then anything flows into it. We include these rules
in case we encounter constraints relating free variables to unknown
purposes *)
|| FlowSet.mem (pol1, Pbot PosSet.empty) lattice
|| FlowSet.mem (Ptop PosSet.empty, pol2) lattice
then
[]
else
[flow]
(* Quantifiers and Holes should have been eliminated before this point *)
| Cquant _ -> failwith "Cquant"
| Chole _ -> failwith "Chole"
(* Flatten a prop into a set of flows. Note: this only works for conjuctions of
* simple flows. Quantifiers, conditions, and holes are not allowed
*)
let rec flatten_prop = function
| Ctrue -> FlowSet.empty
| Cconj (c1, c2) -> FlowSet.union (flatten_prop c1) (flatten_prop c2)
| Cflow (_, l, r) -> FlowSet.singleton (l, r)
(* Not supported *)
| Ccond _ -> failwith "Ccond"
| Cquant _ -> failwith "Cquant"
| Chole _ -> failwith "Chole" |
OCaml | hhvm/hphp/hack/src/ifc/ifc_main.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 Ifc_types
let do_ opts files_info ctx =
(if Ifc.should_print ~user_mode:opts.opt_mode ~phase:Mlattice then
let lattice = opts.opt_security_lattice in
Format.printf "@[Lattice:@. %a@]\n\n" Ifc_pretty.security_lattice lattice);
let handle_file path info errors =
match info.FileInfo.file_mode with
| Some FileInfo.Mstrict ->
let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path in
let { Tast_provider.Compute_tast.tast; _ } =
Tast_provider.compute_tast_unquarantined ~ctx ~entry
in
let check () =
Ifc.check opts tast.Tast_with_dynamic.under_normal_assumptions ctx
in
let (new_errors, _) = Errors.do_with_context path check in
errors @ Errors.get_error_list new_errors
| _ -> errors
in
Relative_path.Map.fold files_info ~init:[] ~f:handle_file |
OCaml | hhvm/hphp/hack/src/ifc/ifc_mapper.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 Ifc_types
(* Shallow mappers *)
let rec ptype fty fpol = function
| Tnull pol -> Tnull (fpol pol)
| Tprim pol -> Tprim (fpol pol)
| Tnonnull (pself, plump) -> Tnonnull (fpol pself, fpol plump)
| Tgeneric pol -> Tgeneric (fpol pol)
| Ttuple tl -> Ttuple (List.map ~f:fty tl)
| Tunion tl -> Tunion (List.map ~f:fty tl)
| Tinter tl -> Tinter (List.map ~f:fty tl)
| Tclass cls ->
Tclass
{
c_name = cls.c_name;
c_self = fpol cls.c_self;
c_lump = fpol cls.c_lump;
}
| Tfun f -> Tfun (fun_ fty fpol f)
| Tcow_array { a_kind; a_key; a_value; a_length } ->
Tcow_array
{
a_kind;
a_key = fty a_key;
a_value = fty a_value;
a_length = fpol a_length;
}
| Tshape { sh_kind; sh_fields } ->
let sh_kind =
match sh_kind with
| Open_shape ty -> Open_shape (fty ty)
| Closed_shape -> Closed_shape
in
let field { sft_optional; sft_policy; sft_ty } =
{ sft_optional; sft_policy = fpol sft_policy; sft_ty = fty sft_ty }
in
Tshape { sh_kind; sh_fields = Typing_defs.TShapeMap.map field sh_fields }
| Tdynamic pol -> Tdynamic (fpol pol)
and fun_ fty fpol f =
let ptype = ptype fty fpol in
{
f_pc = fpol f.f_pc;
f_self = fpol f.f_self;
f_args = List.map ~f:ptype f.f_args;
f_ret = ptype f.f_ret;
f_exn = ptype f.f_exn;
}
let iter_ptype2 fty fpol pt1 pt2 =
let flist l1 l2 =
match List.iter2 ~f:fty l1 l2 with
| List.Or_unequal_lengths.Ok () -> ()
| _ -> invalid_arg "iter_ptype2"
in
match (pt1, pt2) with
| (Tnull p1, Tnull p2)
| (Tprim p1, Tprim p2)
| (Tgeneric p1, Tgeneric p2)
| (Tdynamic p1, Tdynamic p2) ->
fpol p1 p2
| (Tnonnull (ps1, pl1), Tnonnull (ps2, pl2)) ->
fpol ps1 ps2;
fpol pl1 pl2
| (Ttuple tl1, Ttuple tl2)
| (Tunion tl1, Tunion tl2)
| (Tinter tl1, Tinter tl2) ->
flist tl1 tl2
| (Tclass cls1, Tclass cls2) ->
(* ignore property map, it is going away soon *)
fpol cls1.c_self cls2.c_self;
fpol cls1.c_lump cls2.c_lump
| (Tfun f1, Tfun f2) ->
fpol f1.f_pc f2.f_pc;
fpol f1.f_self f2.f_self;
flist f1.f_args f2.f_args;
fty f1.f_ret f2.f_ret;
fty f1.f_exn f2.f_exn
| (Tcow_array a1, Tcow_array a2) ->
(* Assume the array kinds are ok *)
fty a1.a_key a2.a_key;
fty a1.a_value a2.a_value;
fpol a1.a_length a2.a_length
| (Tshape s1, Tshape s2) ->
let combine _ f1 f2 =
match (f1, f2) with
| (Some t1, Some t2) ->
fpol t1.sft_policy t2.sft_policy;
fty t1.sft_ty t2.sft_ty;
None
| _ -> invalid_arg "iter_ptype2"
in
begin
match (s1.sh_kind, s2.sh_kind) with
| (Closed_shape, Closed_shape) -> ()
| (Open_shape t1, Open_shape t2) -> fty t1 t2
| (_, _) -> invalid_arg "iter_ptype2"
end;
ignore (Typing_defs.TShapeMap.merge combine s1.sh_fields s2.sh_fields)
| _ -> invalid_arg "iter_ptype2"
(* "fprop: int -> prop -> prop" takes as first argument the
number of binders under which the prop argument is; it is
initialized by the "depth" argument *)
let prop fpol fprop depth = function
| Ctrue -> Ctrue
| Cquant (q, n, c) -> Cquant (q, n, fprop (depth + n) c)
| Ccond ((pos, p, x), ct, ce) ->
Ccond ((pos, fpol p, x), fprop depth ct, fprop depth ce)
| Cconj (cl, cr) -> Cconj (fprop depth cl, fprop depth cr)
| Cflow (pos, p1, p2) -> Cflow (pos, fpol p1, fpol p2)
| Chole (pos, proto) ->
if phys_equal fpol Ifc_utils.identity then
Chole (pos, proto)
else
(* "pty_map pty" applies fpol to all the policies in the
flow type pty *)
let rec pty_map pty = ptype pty_map fpol pty in
let proto =
{
fp_name = proto.fp_name;
fp_this = Option.map ~f:pty_map proto.fp_this;
fp_type = fun_ pty_map fpol proto.fp_type;
}
in
Chole (pos, proto) |
OCaml | hhvm/hphp/hack/src/ifc/ifc_options.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Ifc_types
module Lattice = Ifc_security_lattice
exception Invalid_ifc_mode of string
let parse_mode_exn mode_str =
match String.uppercase mode_str with
| "LATTICE" -> Mlattice
| "DECL" -> Mdecl
| "ANALYSE" -> Manalyse
| "SOLVE" -> Msolve
| "CHECK" -> Mcheck
| "DEBUG" -> Mdebug
| _ -> raise @@ Invalid_ifc_mode mode_str
let parse ~mode ~lattice =
try
let opt_mode = parse_mode_exn mode in
let opt_security_lattice = Lattice.mk_exn lattice in
Ok { opt_mode; opt_security_lattice }
with
| Lattice.Invalid_security_lattice ->
Error
("option error: lattice specification should be basic flux "
^ "constraints, e.g., `A < B` separated by `;`")
| Invalid_ifc_mode mode ->
Error (Printf.sprintf "option error: %s is not a recognised mode" mode) |
OCaml | hhvm/hphp/hack/src/ifc/ifc_pretty.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Format
open Ifc_types
module Env = Ifc_env
module Logic = Ifc_logic
module Utils = Ifc_utils
module T = Typing_defs
let ifc_error_to_string (e : ifc_error_ty) : string =
match e with
| LiftError s -> "LiftError: " ^ s
| FlowInference s -> "FlowInference: " ^ s
let comma_sep fmt () = fprintf fmt ",@ "
let blank_sep fmt () = fprintf fmt "@ "
let newline_sep fmt () = fprintf fmt "@,"
let rec list pp_sep pp fmt = function
| [] -> ()
| [x] -> fprintf fmt "%a" pp x
| x :: xs -> fprintf fmt "%a%a%a" pp x pp_sep () (list pp_sep pp) xs
let smap pp_sep pp fmt map =
let prop_pol fmt (prop, pol) = fprintf fmt "%s=%a" prop pp pol in
list pp_sep prop_pol fmt (SMap.bindings map)
let option pp fmt opt =
match opt with
| Some x -> fprintf fmt "%a" pp x
| None -> fprintf fmt "None"
let show_policy = function
| Pbot _ -> "PUBLIC"
| Ptop _ -> "PRIVATE"
| Ppurpose (_, p) -> p
| Pfree_var (v, _s) -> v
| Pbound_var n -> Printf.sprintf "<bound%d>" n
let policy fmt p = fprintf fmt "%s" (show_policy p)
let array_kind fmt = function
| Avec -> fprintf fmt "vec"
| Adict -> fprintf fmt "dict"
| Akeyset -> fprintf fmt "keyset"
let rec ptype fmt ty =
let list' sep l =
let pp_sep fmt () = fprintf fmt "%s@ " sep in
fprintf fmt "(@[<hov2>%a@])" (list pp_sep ptype) l
in
match ty with
| Tnull p -> fprintf fmt "null<%a>" policy p
| Tprim p
| Tgeneric p
| Tdynamic p ->
fprintf fmt "<%a>" policy p
| Tnonnull (pself, plump) ->
fprintf fmt "nonnull<%a,%a>" policy pself policy plump
| Ttuple tl -> list' "," tl
| Tunion [] -> fprintf fmt "nothing"
| Tunion tl -> list' " |" tl
| Tinter tl -> list' " &" tl
| Tclass { c_name; c_self; c_lump } ->
fprintf fmt "%s<@[<hov2>%a,@ %a@]>" c_name policy c_self policy c_lump
| Tfun fn -> fun_ fmt fn
| Tcow_array { a_key; a_value; a_length; a_kind } ->
fprintf fmt "%a" array_kind a_kind;
fprintf fmt "<%a => %a; |%a|>" ptype a_key ptype a_value policy a_length
| Tshape { sh_kind; sh_fields } ->
let field fmt { sft_policy; sft_optional; sft_ty } =
if sft_optional then fprintf fmt "?";
fprintf fmt "<%a, %a>" policy sft_policy ptype sft_ty
in
fprintf fmt "shape(";
Typing_defs.TShapeMap.pp field fmt sh_fields;
(match sh_kind with
| Closed_shape -> fprintf fmt ")"
| Open_shape ty -> fprintf fmt ", <%a>)" ptype ty)
(* Format: <pc, self>(arg1, arg2, ...): ret [exn] *)
and fun_ fmt fn =
fprintf fmt "<%a, %a>" policy fn.f_pc policy fn.f_self;
fprintf fmt "(@[<hov>%a@])" (list comma_sep ptype) fn.f_args;
fprintf fmt ":@ %a [%a]" ptype fn.f_ret ptype fn.f_exn
let fun_proto fmt fp =
Option.iter ~f:(fprintf fmt "(this: %a)->" ptype) fp.fp_this;
fprintf fmt "%s%a" fp.fp_name fun_ fp.fp_type
let prop =
let is_symmetric = function
| (Cflow (_, a, b), Cflow (_, c, d)) -> equal_policy a d && equal_policy b c
| _ -> false
in
let equate a b =
if Policy.compare a b <= 0 then
`q (a, b)
else
`q (b, a)
in
let rec conjuncts = function
| Cconj ((Cflow (_, a, b) as f1), Cconj ((Cflow _ as f2), prop))
when is_symmetric (f1, f2) ->
equate a b :: conjuncts prop
| Cconj ((Cflow (_, a, b) as f1), (Cflow _ as f2)) when is_symmetric (f1, f2)
->
[equate a b]
| Cconj (cl, cr) -> conjuncts cl @ conjuncts cr
| Ctrue -> []
| c -> [`c c]
in
let bv =
let rec f = function
| [] -> ['a']
| 'z' :: n -> 'a' :: f n
| c :: n -> Char.(of_int_exn (1 + to_int c)) :: n
in
(fun i -> String.of_char_list (Utils.funpow i ~f ~init:[]))
in
let pp_policy b fmt = function
| Pbound_var n -> fprintf fmt "%s" (bv (b - n))
| p -> policy fmt p
in
let rec aux b fmt =
let pol = pp_policy b in
function
| [] -> fprintf fmt "True"
| [`q (p1, p2)] -> fprintf fmt "%a = %a" pol p1 pol p2
| [`c (Cflow (_, p1, p2))] -> fprintf fmt "%a < %a" pol p1 pol p2
| [`c (Cquant (q, n, c))] ->
fprintf
fmt
"@[<hov2>%s @[<h>%a@].@ %a@]"
(match q with
| Qexists -> "exists"
| Qforall -> "forall")
(list blank_sep pp_print_string)
(snd
(Utils.funpow
n
~f:(fun (i, l) -> (i + 1, l @ [bv i]))
~init:(b + 1, [])))
(aux (b + n))
(conjuncts c)
| [`c (Ccond ((_, p, x), ct, ce))] ->
fprintf fmt "@[<hov>if %a < %s@" pol p x;
let cct = conjuncts ct in
let cce = conjuncts ce in
fprintf fmt "then %a@ else %a@]" (aux b) cct (aux b) cce
| [`c (Chole (_, fp))] -> fprintf fmt "@[<h>{%a}@]" fun_proto fp
| l ->
let pp = list comma_sep (fun fmt c -> aux b fmt [c]) in
fprintf fmt "@[<hov>%a@]" pp l
in
(fun fmt c -> aux 0 fmt (conjuncts c))
let cont fmt k =
pp_open_vbox fmt 0;
fprintf fmt "@[<hov2>%a@]" (LMap.make_pp Local_id.pp ptype) k.k_vars;
let policy_set fmt s = list comma_sep policy fmt (PSet.elements s) in
if not (PSet.is_empty k.k_pc) then
fprintf fmt "@,@[<hov2>pc: @[<hov>%a@]@]" policy_set k.k_pc;
pp_close_box fmt ()
let renv fmt renv =
pp_open_vbox fmt 0;
fprintf fmt "* @[<hov2>pc: @[<hov>%a@]@]" policy renv.re_gpc;
fprintf fmt "@,* @[<hov2>This:@ @[<hov>%a@]@]" (option ptype) renv.re_this;
fprintf fmt "@,* @[<hov2>Return:@ @[<hov>%a@]@]" ptype renv.re_ret;
fprintf fmt "@,* @[<hov2>Exception: @[<hov>%a@]@]" ptype renv.re_exn;
pp_close_box fmt ()
let env fmt env =
let rec flatten = function
| Cconj (p1, p2) -> flatten p1 @ flatten p2
| prop -> [prop]
in
let rec group_by_line =
let has_same_pos p1 p2 =
Option.equal Pos.equal (unique_pos_of_prop p1) (unique_pos_of_prop p2)
in
function
| [] -> []
| prop :: props ->
let (group, rest) = List.partition_tf ~f:(has_same_pos prop) props in
let pos_opt = unique_pos_of_prop prop in
let prop = Logic.conjoin (prop :: group) in
(pos_opt, prop) :: group_by_line rest
in
let group fmt (pos_opt, p) =
match pos_opt with
| Some pos -> fprintf fmt "@[<hov2>%a@ %a@]" Pos.pp pos prop p
| None -> fprintf fmt "@[<hov2>[no pos]@ %a@]" prop p
in
let groups = list newline_sep group in
pp_open_vbox fmt 0;
fprintf fmt "@[<hov2>Deps:@ %a@]" SSet.pp (Env.get_deps env);
let props = List.concat_map ~f:flatten (Env.get_constraints env) in
let prop_groups =
let compare (pos1, _) (pos2, _) = Option.compare Pos.compare pos1 pos2 in
group_by_line props |> List.sort ~compare
in
fprintf fmt "@,Constraints:@, @[<v>%a@]" groups prop_groups;
pp_close_box fmt ()
let class_decl fmt { cd_policied_properties = props; _ } =
let policied_property fmt { pp_name; pp_purpose; _ } =
fprintf fmt "%s:%s" pp_name pp_purpose
in
let properties fmt = list comma_sep policied_property fmt in
fprintf fmt "{ policied_props = [@[<hov>%a@]] }" properties props
let decl_env fmt de =
let handle_class name decl =
fprintf fmt "class %s: %a@ " name class_decl decl
in
fprintf fmt "Decls:@. @[<v>";
SMap.iter handle_class de.de_class;
fprintf fmt "@]"
let implicit_violation fmt (l, r) =
fprintf
fmt
"Data with an implicit policy is leaked by %a in context %a."
policy
l
policy
r
let security_lattice fmt lattice =
let flow fmt (l, r) = fprintf fmt "%a < %a" policy l policy r in
let flows = FlowSet.elements lattice in
fprintf fmt "{%a}" (list comma_sep flow) flows |
OCaml | hhvm/hphp/hack/src/ifc/ifc_scope.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type t = int
let pp fmt n = Format.fprintf fmt "<scope%d>" n
let compare = Int.compare
let equal = Int.equal
let alloc =
let next = ref 0 in
fun () ->
incr next;
!next |
OCaml Interface | hhvm/hphp/hack/src/ifc/ifc_scope.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 pp : Format.formatter -> t -> unit
val equal : t -> t -> bool
val compare : t -> t -> int
val alloc : unit -> t |
OCaml | hhvm/hphp/hack/src/ifc/ifc_security_lattice.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 Ifc_types
(* This file contains code related to the security lattice we use to
* check our constraint results against.
*)
exception Invalid_security_lattice
let parse_policy pos purpose_str =
match String.uppercase purpose_str with
| "PUBLIC" -> Pbot pos
| "PRIVATE" -> Ptop pos
| purpose -> Ppurpose (pos, purpose)
(* Parses a Hasse diagram written in a ';' separated format,
* e.g., "A < B; B < C; A < D"
*)
let parse_exn str =
let pos = PosSet.empty in
String.filter ~f:(fun chr -> not @@ Char.equal ' ' chr) str
|> String.split ~on:';'
|> (fun xs ->
if List.equal String.equal xs [""] then
[]
else
xs)
|> List.map ~f:(fun str ->
match String.lsplit2 ~on:'<' str with
| Some (l, r) -> (parse_policy pos l, parse_policy pos r)
| None -> raise Invalid_security_lattice)
|> FlowSet.of_list
(* A naive implementation of transitive closure *)
let rec transitive_closure set =
let immediate_consequence (x, y) set =
let add (y', z) set =
if equal_policy y y' then
FlowSet.add (x, z) set
else
set
in
FlowSet.fold add set set
in
let new_set = FlowSet.fold immediate_consequence set set in
if FlowSet.cardinal new_set = FlowSet.cardinal set then
set
else
transitive_closure new_set
let mk_exn str = parse_exn str |> transitive_closure |
OCaml | hhvm/hphp/hack/src/ifc/ifc_solver.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 Ifc_types
module Logic = Ifc_logic
module Mapper = Ifc_mapper
module Utils = Ifc_utils
module L = Logic.Infix
type solving_error =
| RecursiveCycle
| MissingResults of string
(* InvalidCall (caller, callee) *)
| InvalidCall of string * string
exception Error of solving_error
let call_constraint ~subtype ~pos ?(depth = 0) proto scheme =
let (Fscheme (callee_scope, callee_proto, callee_constraint)) = scheme in
let pred (_, s) = Scope.equal s callee_scope in
let make_constraint this_types =
Some
([callee_constraint]
|> subtype ~pos (Tfun callee_proto.fp_type) (Tfun proto.fp_type)
|> (match this_types with
| Some (t1, t2) -> subtype ~pos t1 t2
| None -> Utils.identity)
|> Logic.conjoin
(* the assertion on scopes in close_one below ensures that
we quantify only the callee policy variables *)
|> Logic.quantify ~pred ~quant:Qexists ~depth)
in
match (proto.fp_this, callee_proto.fp_this) with
| (Some this1, Some this2) -> make_constraint (Some (this1, this2))
| (None, None) -> make_constraint None
| _ -> None
(* Combine the results of each individual function into a global
constraint. If the resulting constraint is satisfiable all the
flows in the program are safe *)
let global_exn ~subtype callable_results =
let results_map =
let add_result resm res = SMap.add res.res_proto.fp_name res resm in
List.fold ~init:SMap.empty ~f:add_result callable_results
in
let topsort_schedule =
let schedule = ref [] in
let rec dfs seen name =
if SSet.mem name seen then raise (Error RecursiveCycle);
match SMap.find_opt name results_map with
| None -> raise (Error (MissingResults name))
| Some res ->
SSet.iter (dfs (SSet.add name seen)) res.res_deps;
if not (List.exists ~f:(String.equal name) !schedule) then
schedule := name :: !schedule
in
SMap.iter (fun name _ -> dfs SSet.empty name) results_map;
List.rev !schedule
in
let close_one closed_results_map res_name =
let result = SMap.find res_name results_map in
let rec subst depth = function
| Chole (pos, proto) ->
let callee = SMap.find proto.fp_name closed_results_map in
assert (not (Scope.equal callee.res_scope result.res_scope));
let scheme =
Fscheme (callee.res_scope, callee.res_proto, callee.res_constraint)
in
begin
match call_constraint ~subtype ~depth ~pos proto scheme with
| Some prop -> prop
| None -> raise (Error (InvalidCall (res_name, proto.fp_name)))
end
| c -> Mapper.prop Utils.identity subst depth c
in
let closed_constr = subst 0 result.res_constraint in
let closed_result = { result with res_constraint = closed_constr } in
SMap.add res_name closed_result closed_results_map
in
List.fold_left ~init:SMap.empty ~f:close_one topsort_schedule |
OCaml | hhvm/hphp/hack/src/ifc/ifc_types.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module KMap = Typing_continuations.Map
module LMap = Local_id.Map
module Scope = Ifc_scope
module Type = Typing_defs
type ifc_error_ty =
| LiftError of string
| FlowInference of string
[@@deriving show]
exception IFCError of ifc_error_ty
(* Most types should live here. *)
type purpose = string [@@deriving ord, eq, show]
(* A policy variable *)
type policy_var = string [@@deriving ord, eq, show]
module PosSet = Set.Make (Pos)
(* In policies, variables are handled using a locally-nameless
representation. This means that variables bound in a
constraints use de Bruijn indices while free variables use
a name. The scope in a Pvar is used to store inline the
creation point of a purpose variable. *)
type policy =
(* Bottom policy; public *)
| Pbot of (PosSet.t[@equal (fun _ _ -> true)] [@compare (fun _ _ -> 0)])
(* Top policy; private *)
| Ptop of (PosSet.t[@equal (fun _ _ -> true)] [@compare (fun _ _ -> 0)])
(* Bound variable; represented with a de Bruijn index *)
| Pbound_var of int
(* Free variable; relative to a scope *)
| Pfree_var of policy_var * Ifc_scope.t
(* A policy allowing use for a single purpose *)
| Ppurpose of
(PosSet.t[@equal (fun _ _ -> true)] [@compare (fun _ _ -> 0)]) * purpose
[@@deriving eq, ord]
let pbot = Pbot PosSet.empty
let pos_set_of_policy = function
| Ppurpose (poss, _)
| Ptop poss
| Pbot poss ->
poss
| _ -> PosSet.empty
let set_pos_set_of_policy pos = function
| Ppurpose (_, name) -> Ppurpose (pos, name)
| Ptop _ -> Ptop pos
| Pbot _ -> Pbot pos
| pol -> pol
(* Two kinds of quantification in constraints, universal and
existential *)
type quant =
| Qforall
| Qexists
type class_ = {
c_name: string;
c_self: policy;
c_lump: policy;
}
type array_kind =
| Avec
| Adict
| Akeyset
[@@deriving eq]
(* Types with policies *)
type ptype =
| Tnull of policy
| Tprim of policy
| Tnonnull of policy * policy (* self(covariant), lump(invariant) *)
| Tgeneric of policy
| Ttuple of ptype list
| Tunion of ptype list
| Tinter of ptype list
| Tclass of class_
| Tfun of fun_
| Tcow_array of cow_array
| Tshape of shape
| Tdynamic of policy
(* Copy-on-write indexed collection used for Hack containers i.e. vec, dict,
keyset, varray, and darray *)
and cow_array = {
a_kind: array_kind;
a_key: ptype;
a_value: ptype;
a_length: policy;
}
and shape = {
sh_kind: shape_kind;
sh_fields: shape_field_type Typing_defs.TShapeMap.t;
}
and shape_kind =
(* An open shape has a "magic" field of type mixed that holds the policy of
all the unnamed data *)
| Open_shape of ptype
| Closed_shape
and shape_field_type = {
(* The policy of the field is essentially the PC at the time that it is
assigned. We need to keep track of this separately because for optional
fields, we may still learn information based on whether or not the value is
present. *)
sft_policy: policy;
sft_optional: bool;
sft_ty: ptype;
}
and fun_ = {
(* The PC guards a function's effects *)
f_pc: policy;
(* Policy that the function's computational contents depend on *)
f_self: policy;
f_args: ptype list;
f_ret: ptype;
f_exn: ptype;
}
type callable_name =
| Method of string * string (* Classname, method name *)
| StaticMethod of string * string (* Classname, static meth name *)
(* toplevel function *)
| Function of string
type fun_proto = {
fp_name: string;
fp_this: ptype option;
fp_type: fun_;
}
(* A flow between two policies with positions justifying it *)
type pos_flow = PosSet.t * policy * policy
(* Flow constraints with quantifiers and implication *)
type prop =
| Ctrue
| Cquant of quant * int * prop
(* if policy <= purpose then prop0 else prop1 *)
| Ccond of (Pos.t * policy * purpose) * prop * prop
| Cconj of prop * prop
| Cflow of pos_flow
(* holes are introduced by calls to functions for which
we do not have a flow type at hand *)
| Chole of (Pos.t * fun_proto)
let is_open = function
| Open_shape _ -> true
| Closed_shape -> false
let unique_pos_of_prop =
let is_real pos = not @@ Pos.equal pos Pos.none in
function
| Cflow (posset, _, _) -> begin
match PosSet.elements posset with
| [pos] when is_real pos -> Some pos
| _ -> None
end
| Ccond ((pos, _, _), _, _) when is_real pos -> Some pos
| Chole (pos, _) when not @@ is_real pos -> Some pos
| _ -> None
type fun_scheme = Fscheme of Scope.t * fun_proto * prop
module Flow = struct
type t = policy * policy
let compare (a, b) (c, d) =
match compare_policy a c with
| 0 -> compare_policy b d
| x -> x
end
module FlowSet = Set.Make (Flow)
type security_lattice = FlowSet.t
module Policy = struct
type t = policy
let compare = compare_policy
end
module PSet = Set.Make (Policy)
module Var = struct
type t = string * Ifc_scope.t
let compare = compare
end
module VarSet = Set.Make (Var)
(* A cont represents the typing environment for one
outcome (fallthrough, break, throw, ...) of a
statement *)
type cont = {
k_vars: ptype LMap.t;
(* Policy tracking the dependencies of the current
outcome. NB: only dependencies *local* to the
function are tracked here (i.e., the function's
pc policy is not included) *)
k_pc: PSet.t;
}
type policied_property = {
pp_pos: Pos.t;
pp_name: string;
pp_purpose: purpose;
(* Visibility is not needed beyond the decl phase, but OCaml makes
* it difficult to map between collections, so it is carried to the analysis. *)
pp_visibility: Aast.visibility;
}
type class_decl = {
(* the list of policied properties in the class *)
cd_policied_properties: policied_property list;
}
type magic_decl = {
ma_class_decl: class_decl;
ma_tparams: Type.locl_ty list;
ma_variances: Ast_defs.variance list;
}
type fun_decl_kind =
| FDPolicied of policy option
| FDInferFlows
type arg_kind =
| AKDefault
| AKExternal of Pos.t
| AKCallable of Pos.t
type fun_decl = {
fd_kind: fun_decl_kind;
fd_args: arg_kind list;
}
type decl_env = {
(* policy decls for classes indexed by class name *)
de_class: class_decl SMap.t;
}
(* Mode of operation.
* The constructors should be topologically sorted with respect to the
* dependency partial order between different modes. *)
type mode =
(* Constructs the security lattice. *)
| Mlattice
(* Performs declaration analysis *)
| Mdecl
(* Analyses function/method bodies for flux constraints *)
| Manalyse
(* Invokes the constraint solver simplifying constraints *)
| Msolve
(* Checks simplified constraints against a security lattice *)
| Mcheck
(* Run and print everything for debugging *)
| Mdebug
[@@deriving eq]
(* Structured/parsed/sanitised options. *)
type options = {
(* Mode of operation that determines how much of the analysis is executed
* and what to printout. *)
opt_mode: mode;
(* Security lattice to check results against. *)
opt_security_lattice: security_lattice;
}
(* Read-only environment information managed following a stack discipline
when walking the Hack syntax *)
type 'ptype renv_ = {
(* during flow inference, types are always given relative to a scope. *)
re_scope: Scope.t;
(* hash table keeping track of counters to generate variable names *)
re_pvar_counters: (string, int ref) Hashtbl.t;
(* extended decls for IFC *)
re_decl: decl_env;
(* Hack type environment *)
re_tenv: Tast.saved_env;
(* policy type of $this *)
re_this: 'ptype option;
(* return type of the function being checked *)
re_ret: 'ptype;
(* the program counter policy of the current function *)
re_gpc: policy;
(* Exception thrown from the callable *)
re_exn: 'ptype;
(* Decl provider context for accessing the decl heap *)
re_ctx: Provider_context.t;
}
type proto_renv = unit renv_
type renv = ptype renv_
(* The analysis result for a callable *)
type callable_result = {
(* Position of the callable the result pertains to *)
res_span: Pos.t;
(* The callable signature, with flow types *)
res_proto: fun_proto;
(* The scope of the free policy variables in res_proto
and res_constraint *)
res_scope: Scope.t;
(* Constraints abstracting the callable body; the
constrain the policies appearing in res_proto *)
res_constraint: prop;
(* The set of callable that appear in holes of
res_constraint *)
res_deps: SSet.t;
(* Entailment based on the function's assumed prototype *)
res_entailment: prop -> pos_flow list;
}
type adjustment =
| Astrengthen
| Aweaken
type call_type =
| Cglobal of (callable_name * Typing_defs.locl_ty)
| Cconstructor of callable_name
| Clocal of fun_ |
OCaml | hhvm/hphp/hack/src/ifc/ifc_utils.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module A = Aast
let identity x = x
let rec funpow n ~f ~init =
if n <= 0 then
init
else
funpow (n - 1) ~f ~init:(f init)
let combine_opts keep_some combine x y =
match (x, y) with
| (Some z, None)
| (None, Some z) ->
if keep_some then
Some z
else
None
| (Some x, Some y) -> Some (combine x y)
| (None, None) -> None
let rec fold3 ~f ~init xs ys zs =
List.Or_unequal_lengths.(
match (xs, ys, zs) with
| ([], [], []) -> Ok init
| (x :: xs, y :: ys, z :: zs) -> begin
match fold3 ~f ~init xs ys zs with
| Ok acc -> Ok (f acc x y z)
| err -> err
end
| _ -> Unequal_lengths) |
OCaml Interface | hhvm/hphp/hack/src/injection/injector_config.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* This file provides only the interface, so injector configuration
* can be retreived without depending on the *actual* implementation
* file. This is because we want libraries to be able to refer to the config,
* but the actual injector to be chosen by the binary being built.
*
* Note: Buck doesn't currently have a build rule to only build .mli files
* into .cmi, so you need to compile against this file directly. *)
val use_test_stubbing : bool |
hhvm/hphp/hack/src/libancillary/dune | (library
(name libancillary)
(wrapped false)
(foreign_stubs
(language c)
(names libancillary-stubs)
(flags
(:standard -I%{env:CMAKE_SOURCE_DIR=xxx})))
(libraries libancillary_c)) |
|
C | hhvm/hphp/hack/src/libancillary/libancillary-stubs.c | /**
* 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.
*
*/
#define CAML_NAME_SPACE
#include <caml/mlvalues.h>
#include <caml/memory.h>
#include <caml/alloc.h>
#include <caml/custom.h>
#include <caml/fail.h>
#include <caml/signals.h>
#include <caml/callback.h>
#undef CAML_NAME_SPACE
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include "hphp/hack/src/third-party/libancillary/ancillary.h"
CAMLprim value stub_ancil_send_fd(value int_val_socket, value int_val_fd) {
CAMLparam2(int_val_socket, int_val_fd);
int socket = Int_val(int_val_socket);
int fd = Int_val(int_val_fd);
CAMLreturn(Val_int(ancil_send_fd(socket, fd)));
}
/** Returns -1 on failure, or non-negative file descriptor on success. */
CAMLprim value stub_ancil_recv_fd(value int_val_socket) {
CAMLparam1(int_val_socket);
CAMLlocal3(ret, result_val, error_val);
int fd = 0;
int result;
int socket = Int_val(int_val_socket);
int error_code;
char errmsg[64];
result = ancil_recv_fd(socket, &fd);
error_code = errno; /* read errno here to make sure we don't loose it */
if (result >= 0) {
error_val = caml_copy_string("");
result_val = Val_int(fd);
} else {
snprintf(errmsg, sizeof(errmsg), "(errno=%d) %s", error_code, strerror(error_code));
error_val = caml_copy_string(errmsg);
result_val = Val_int(result);
}
ret = caml_alloc_tuple(2);
Store_field(ret, 0, result_val);
Store_field(ret, 1, error_val);
CAMLreturn(ret);
} |
OCaml | hhvm/hphp/hack/src/libancillary/libancillary.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 int_to_fd (i : int) : Unix.file_descr = Obj.magic i
exception Receiving_Fd_Exception of string
external ancil_send_fd :
Unix.file_descr (* The fd of the socket to send the payload over *) ->
Unix.file_descr (* The file descriptor you want to send *) ->
int (* Returns 0 for success, -1 on failure. *) = "stub_ancil_send_fd"
external ancil_recv_fd_ :
Unix.file_descr (* The fd of the socket to receive the payload over *) ->
int (* The fd received *) * string (* error message on error *)
= "stub_ancil_recv_fd"
(** Receives a file descriptor from socket_fd. Throws exception on error. *)
let ancil_recv_fd socket_fd =
let (fd, errmsg) = ancil_recv_fd_ socket_fd in
if fd = -1 then
raise (Receiving_Fd_Exception errmsg)
else
int_to_fd fd |
OCaml Interface | hhvm/hphp/hack/src/libancillary/libancillary.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.
*
*)
exception Receiving_Fd_Exception of string
(** Returns 0 for success, -1 on failure. *)
val ancil_send_fd :
Unix.file_descr (** The fd of the socket to send the payload over *) ->
Unix.file_descr (** The file descriptor you want to send *) ->
int
(** The fd received *)
val ancil_recv_fd :
Unix.file_descr (** The fd of the socket to receive the payload over *) ->
Unix.file_descr |
hhvm/hphp/hack/src/lints/dune | (library
(name lints_core)
(wrapped false)
(modules lints_core)
(preprocess
(pps ppx_deriving.std))
(libraries typing_ast user_error pos))
(library
(name linting_main)
(wrapped false)
(preprocess
(pps ppx_deriving.std))
(modules linting_main)
(libraries
provider_context
linting
linting_visitors
other_visitors
tast_check
typing_check_job))
(library
(name lints_codes)
(wrapped false)
(preprocess
(pps ppx_deriving.std))
(modules lints_codes))
(library
(name lints_errors)
(wrapped false)
(modules lints_errors)
(preprocess
(pps ppx_deriving.std))
(libraries lints_core lints_codes utils_core))
(library
(name linting_visitors)
(wrapped false)
(modules linting_visitors)
(preprocess
(pps ppx_deriving.std))
(libraries
annotated_ast
annotated_ast_utils
naming
nast
typechecker_options
parser
typing
utils_core
pos
relative_path))
(library
(name other_visitors)
(preprocess
(pps ppx_deriving.std))
(wrapped false)
(modules
(:standard
\
lints_core
linting_main
lints_codes
lints_errors
linting_visitors))
(libraries
decl
decl_provider
linting_visitors
lints_errors
tast_env
utils_core)) |
|
OCaml | hhvm/hphp/hack/src/lints/linter_ast.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 Aast
open Hh_prelude
let go (ast : Nast.program) =
List.iter ast ~f:(function
| Stmt (_, Expr (_, p, Import ((Include | IncludeOnce), _))) ->
Lints_errors.include_use
p
"Prefer `require` and `require_once` to `include` and `include_once`."
| _ -> ()) |
OCaml | hhvm/hphp/hack/src/lints/linter_async_lambda.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.
*
*)
(** This lint advises users to use
`async params ==> await ...`
instead of
`params ==> ...`
when `...` is an `Awaitable`.
The reason is the former produces better stack traces and gets optimised
more aggressively.
*)
module T = Typing_defs
module A = Aast_defs
module Reason = Typing_reason
module MakeType = Typing_make_type
module SN = Naming_special_names
let is_awaitable env ty =
let (_env, ty) = Tast_env.expand_type env ty in
match T.get_node ty with
| T.Tclass ((_, id), _, _) -> String.equal id SN.Classes.cAwaitable
| _ -> false
let strip_dynamic env ty =
let tenv = Tast_env.tast_env_as_typing_env env in
Typing_utils.strip_dynamic tenv ty
let is_awaitable_awaitable env ty =
let ty = strip_dynamic env ty in
let (env, ty) = Tast_env.expand_type env ty in
match T.get_node ty with
| T.Tclass ((_, id), _, [ty]) when String.equal id SN.Classes.cAwaitable ->
let ty = strip_dynamic env ty in
let (_env, ty) = Tast_env.expand_type env ty in
begin
match T.get_node ty with
| T.Tclass ((_, id), _, _) -> String.equal id SN.Classes.cAwaitable
| _ -> false
end
| _ -> false
let is_fsync = function
| Ast_defs.FSync -> true
| _ -> false
let is_await = function
| A.Await _ -> true
| _ -> false
let simple_body = function
| [(_, A.Return (Some (ty, _, e)))] -> Some (ty, e)
| _ -> None
let async_lambda_cond env ty e f_fun_kind =
is_awaitable env ty && (not (is_await e)) && is_fsync f_fun_kind
let awaitable_awaitable_cond env = function
| (ty, None) -> is_awaitable_awaitable env ty
| _ -> false
let handler =
object
inherit Tast_visitor.handler_base
method! at_expr env =
function
| ( _,
pos,
A.(
( Lfun ({ f_fun_kind; f_ret; f_body = { fb_ast }; _ }, _)
| Efun { ef_fun = { f_fun_kind; f_ret; f_body = { fb_ast }; _ }; _ }
)) ) ->
(match simple_body fb_ast with
| Some (ty, e) ->
if async_lambda_cond env ty e f_fun_kind then
Lints_errors.async_lambda pos
else if awaitable_awaitable_cond env f_ret then
Lints_errors.awaitable_awaitable pos
| None ->
if awaitable_awaitable_cond env f_ret then
Lints_errors.awaitable_awaitable pos)
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/lints/linter_await_in_loop.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 Linting_visitors
open Aast
class await_visitor =
object (this)
inherit [unit] Nast.Visitor_DEPRECATED.visitor as parent
method on_elfun f =
let block = f.f_body.fb_ast in
(new loop_visitor)#on_block () block
(* Skip lambdas created inside for loops *)
method! on_efun () efun = this#on_elfun efun.ef_fun
method! on_lfun () f _ = this#on_elfun f
method! on_stmt () stmt =
begin
match snd stmt with
| Expr
(_, p, Binop { bop = Ast_defs.Eq _; lhs = _; rhs = (_, _, Await _) })
| Expr (_, p, Await _) ->
Lints_errors.await_in_loop p
| _ -> ()
end;
parent#on_stmt () stmt
end
and loop_visitor =
object
inherit [unit] Nast.Visitor_DEPRECATED.visitor as parent
method! on_stmt () stmt =
match snd stmt with
| Do (block, _)
| While (_, block)
| For (_, _, _, block)
| Foreach (_, As_v _, block)
| Foreach (_, As_kv _, block) ->
(new await_visitor)#on_block () block
| _ -> parent#on_stmt () stmt
end
module VisitorFunctor (Parent : BodyVisitorModule) : BodyVisitorModule = struct
class visitor env =
object
inherit Parent.visitor env as parent
method! on_body () block =
(new loop_visitor)#on_block () block;
parent#on_body () block
end
end
let go = lint_all_bodies (module VisitorFunctor) |
OCaml | hhvm/hphp/hack/src/lints/linter_branches_return_same_value.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Aast
open Hh_prelude
(**
Lint on functions/methods that always return the same value. This
is usually a copy-paste error.
function some_predicate(Whatever $value): bool {
if ($value->foo()) {
return false;
}
if ($value->bar()) {
return false;
}
return false; // oops!
} *)
let is_expr_same ((_, _, expr1) : Tast.expr) ((_, _, expr2) : Tast.expr) : bool
=
match (expr1, expr2) with
| (Aast.True, Aast.True)
| (Aast.False, Aast.False) ->
true
| (Aast.Int s1, Aast.Int s2)
| (Aast.Float s1, Aast.Float s2)
| (Aast.String s1, Aast.String s2)
| (Aast.Id (_, s1), Aast.Id (_, s2))
when String.equal s1 s2 ->
true
| ( Aast.Class_const ((_, _, Aast.CI (_, enum1)), (_, name1)),
Aast.Class_const ((_, _, Aast.CI (_, enum2)), (_, name2)) )
when String.equal enum1 enum2 && String.equal name1 name2 ->
true
| _ -> false
(* Does this value look like a success exit code? We don't want to
lint on code like this:
function my_main(): int {
if (quick_check()) { return 0; }
normal_work();
return 0;
} *)
let is_success_ish ((_, _, e_) : Tast.expr) : bool =
match e_ with
| Aast.Int "0" -> true
| Aast.Class_const (_, (_, "SUCCESS")) -> true
| _ -> false
let rec are_return_expressions_same (ret_list : Tast.expr list) : bool =
match ret_list with
| expr1 :: expr2 :: tail ->
if is_expr_same expr1 expr2 then
are_return_expressions_same (expr2 :: tail)
else
false
| [_] -> true
| [] -> true
(* This function returns a list of all the expressions that follow each of the return statements in a block *)
let get_return_expr_visitor =
object
inherit [_] Aast.reduce as super
method zero = []
method plus = ( @ )
method! on_stmt env s =
match snd s with
| Aast.Return (Some expr) -> [expr]
| _ -> super#on_stmt env s
(* we ignore the return expressions within lambda statements *)
method! on_expr_ env e =
match e with
| Aast.Efun _ -> []
| Aast.Lfun _ -> []
| _ -> super#on_expr_ env e
end
let get_return_exprs (stmts : Tast.stmt list) : Tast.expr list =
get_return_expr_visitor#on_block () stmts
let check_block (block : Tast.block) : unit =
let ret_list = get_return_exprs block in
match ret_list with
| expr1 :: _ :: _ when are_return_expressions_same ret_list ->
if not (is_success_ish expr1) then
List.iter ret_list ~f:(fun (_, pos, _) ->
Lints_errors.branches_return_same_value pos)
| _ -> ()
let handler =
object
inherit Tast_visitor.handler_base
method! at_fun_def _env f = check_block f.fd_fun.f_body.fb_ast
method! at_method_ _env m = check_block m.m_body.fb_ast
end |
OCaml | hhvm/hphp/hack/src/lints/linter_cast_non_primitive.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 T = Typing_defs
module A = Aast_defs
module TUtils = Typing_utils
module Env = Tast_env
let is_always_castable env ty =
let open Typing_make_type in
let r = Reason.Rnone in
let mixed = mixed r in
let castable_ty =
locl_like r
@@ nullable r
@@ union r [arraykey r; num r; bool r; hh_formatstring r mixed]
in
Env.is_sub_type env ty castable_ty
let is_bool_castable env ty =
let open Typing_make_type in
let r = Reason.Rnone in
let mixed = mixed r in
let bool_castable_ty =
locl_like r
@@ nullable r
@@ union r [vec_or_dict r (arraykey r) mixed; keyset r (arraykey r)]
in
Env.is_sub_type env ty bool_castable_ty
let is_not_castable_but_leads_to_too_many_false_positives env ty =
let (env, ty) = Env.expand_type env ty in
let open Typing_make_type in
let r = Reason.Rnone in
let nonnull = nonnull r in
let dynamic = dynamic r in
Env.is_sub_type env nonnull ty
|| Env.is_sub_type env dynamic ty
||
match T.get_node ty with
| T.Tgeneric _
| T.Tnewtype _ ->
true
| _ -> false
let handler =
object
inherit Tast_visitor.handler_base
method! at_expr env =
let typing_env = Env.tast_env_as_typing_env env in
function
| (_, pos, Aast.Cast (hint, (ty, _, _)))
when (not (TUtils.is_nothing typing_env ty))
&& (not (is_always_castable env ty))
&& (not
(is_bool_castable env ty
&& A.(equal_hint_ (snd hint) (Hprim Tbool))))
&& not
(is_not_castable_but_leads_to_too_many_false_positives env ty)
->
Lints_errors.cast_non_primitive pos
| _ -> ()
end |
OCaml Interface | hhvm/hphp/hack/src/lints/linter_cast_non_primitive.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(** This linter catches dangerous uses of `(int)`, `(string)`, `(bool)`, and
`(float)` casts. These are safe to perform on the following inductive set
- primitives
- format strings
- nullables of safe types to perform casts.
Additionally, collections can be cast using `(bool)`.
Although, it is not known to be safe to perform casts on `mixed`,
`dynamic`, `nothing`, or genericly typed values, we do not lint against
them to prevent excessive false positives.
*)
val handler : Tast_visitor.handler |
OCaml | hhvm/hphp/hack/src/lints/linter_class_overrides_trait.ml | (*
* Copyright (c) 2020, 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 linter warns if a class overrides all instance/static methods
and properties of a trait the class uses *)
open Hh_prelude
open Aast
module Cls = Decl_provider.Class
let trait_name_from_hint th =
match th with
| Happly ((_, tid), _) -> Some tid
| _ -> None
(* collect the names of properties and methods of a Cls.t *)
let names_and_origins_defined_by_cls_t cls =
(* static properties in decls have a $ prefix, removing it *)
let remove_trailing_dollar s =
match String.chop_prefix s ~prefix:"$" with
| None -> s
| Some s -> s
in
let accessors =
[
(Cls.methods, (fun m -> not (Typing_defs.get_ce_abstract (snd m))), fst);
(Cls.smethods, (fun m -> not (Typing_defs.get_ce_abstract (snd m))), fst);
(Cls.props, (fun _ -> true), fst);
(Cls.sprops, (fun _ -> true), (fun p -> remove_trailing_dollar (fst p)));
]
in
List.fold_left
~init:(SSet.empty, SMap.empty)
~f:(fun set (accessor, condition, sanitize) ->
List.fold_left
~init:set
~f:(fun (names, origins) el ->
if condition el then
let name = sanitize el in
let element = snd el in
( SSet.add name names,
SMap.add name element.Typing_defs.ce_origin origins )
else
(names, origins))
(accessor cls))
accessors
(* collect the names of properties and methods of a class_ *)
let names_and_pos_defined_by_class_ class_ =
let method_names_pos =
List.fold_left
~init:(SSet.empty, SMap.empty)
~f:(fun (names, pos) m ->
( SSet.add (snd m.m_name) names,
SMap.add (snd m.m_name) (fst m.m_name) pos ))
class_.c_methods
in
List.fold_left
~init:method_names_pos
~f:(fun (names, pos) cv ->
(SSet.add (snd cv.cv_id) names, SMap.add (snd cv.cv_id) (fst cv.cv_id) pos))
class_.c_vars
(* Does this [trait] implement any interfaces?
This looks for traits of the form:
trait X implements I {} // true
It does not include traits with requirements.
trait X { require implements I; } // false
*)
let trait_implements_interfaces ctx (trait : Cls.t) : bool =
let is_interface name : bool =
match Decl_provider.get_class ctx name with
| Some decl ->
(match Cls.kind decl with
| Ast_defs.Cinterface -> true
| _ -> false)
| None ->
(* If we can't find this type (e.g. the user hasn't finished
writing it), conservatively assume it's an interface. *)
true
in
let interface_ancestors =
List.filter ~f:is_interface (Cls.all_ancestor_names trait)
in
not (List.is_empty interface_ancestors)
let handler =
object
inherit Tast_visitor.handler_base
method! at_class_ env c =
let (pos, bid) = c.c_name in
let ctx = Tast_env.get_ctx env in
let (base_names, base_pos_map) = names_and_pos_defined_by_class_ c in
let used_trait_names =
List.filter_map ~f:(fun u -> trait_name_from_hint (snd u)) c.c_uses
in
let required_classes =
List.filter_map
~f:(fun (u, k) ->
match k with
| RequireClass -> trait_name_from_hint (snd u)
| RequireExtends
| RequireImplements ->
None)
c.c_reqs
in
(* if the class or trait uses a trait that does not have require class constraints,
* and does not implement an interface, then ensure that at least one method or
* property of the trait is not overridden by the using class.
*)
List.iter
~f:(fun tid ->
match Decl_provider.get_class ctx tid with
| None -> ()
| Some t_cls ->
let trait_names = fst (names_and_origins_defined_by_cls_t t_cls) in
if
List.is_empty (Cls.all_ancestor_req_class_requirements t_cls)
&& (not (SSet.is_empty trait_names))
&& SSet.subset trait_names base_names
&& not (trait_implements_interfaces ctx t_cls)
then
Lints_errors.class_overrides_all_trait_methods
pos
bid
(Cls.name t_cls)
else
())
used_trait_names;
(* if the trait has a require class C constraint, ensure that the class C does
* not override any property or method of the trait
*)
List.iter
~f:(fun cid ->
match Decl_provider.get_class ctx cid with
| None -> ()
| Some c_cls ->
let (class_names, origins) =
names_and_origins_defined_by_cls_t c_cls
in
let dead_names = SSet.inter class_names base_names in
SSet.iter
(fun n ->
let origin = SMap.find n origins in
if not (String.equal origin bid) then
Lints_errors.trait_requires_class_that_overrides_method
(SMap.find n base_pos_map)
cid
bid
n)
dead_names)
required_classes
end |
OCaml | hhvm/hphp/hack/src/lints/linter_clone.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 Linting_visitors
module VisitorFunctor (Parent : BodyVisitorModule) : BodyVisitorModule = struct
class visitor env =
object
inherit Parent.visitor env as parent
method! on_clone () (ty, p, e) =
Lints_errors.clone_use p;
parent#on_clone () (ty, p, e)
end
end
let go = lint_all_bodies (module VisitorFunctor) |
OCaml | hhvm/hphp/hack/src/lints/linter_comparing_booleans.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
let as_lvar_and_literal ((_, _, lhs) : Tast.expr) ((_, _, rhs) : Tast.expr) :
(string * bool) option =
match (lhs, rhs) with
| (Aast.Lvar (_, id), Aast.True) -> Some (Local_id.get_name id, true)
| (Aast.Lvar (_, id), Aast.False) -> Some (Local_id.get_name id, false)
| _ -> None
let which_boolean_literal ((_ty, _pos, expr_) : Tast.expr) =
match expr_ with
| Aast.True -> Some true
| Aast.False -> Some false
| _ -> None
let is_boolean_variable ((ty, _pos, _expr_) : Tast.expr) =
Typing_defs.is_prim Aast.Tbool ty
let checking_the_expression exp1 exp2 =
if is_boolean_variable exp1 then
as_lvar_and_literal exp1 exp2
else
None
let handler =
object
inherit Tast_visitor.handler_base
method! at_expr _env (_, pos, expr_) =
match expr_ with
| Aast.(Binop { bop; lhs; rhs }) ->
(match bop with
| Ast_defs.Eqeq
| Ast_defs.Eqeqeq ->
(match checking_the_expression lhs rhs with
| Some (name, boolean_var) ->
(match lhs with
| (_, pos_exp1, _) ->
Lints_errors.comparing_booleans pos pos_exp1 name boolean_var)
| None ->
(match checking_the_expression rhs lhs with
| Some (name, boolean_var) ->
(match rhs with
| (_, pos_exp2, _) ->
Lints_errors.comparing_booleans pos pos_exp2 name boolean_var)
| None -> ()))
| _ -> ())
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/lints/linter_disjoint_types.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 Common
open Aast
open Typing_defs
module Cls = Decl_provider.Class
module Env = Tast_env
module SN = Naming_special_names
let check_non_disjoint env p name ty1 ty2 =
let tenv = Tast_env.tast_env_as_typing_env env in
if
Typing_utils.(
(not (is_nothing tenv ty1))
&& (not (is_nothing tenv ty2))
&& is_type_disjoint tenv ty1 ty2)
then
Lints_errors.invalid_disjointness_check
p
(Utils.strip_ns name)
(Env.print_ty env ty1)
(Env.print_ty env ty2)
let rec check_non_disjoint_tyl env p name tyl =
match tyl with
| [] -> ()
| ty :: tyl ->
List.iter tyl ~f:(check_non_disjoint env p name ty);
check_non_disjoint_tyl env p name tyl
let has_non_disjoint_attr tp =
Attributes.mem SN.UserAttributes.uaNonDisjoint tp.tp_user_attributes
let handler =
object
inherit Tast_visitor.handler_base
method! at_expr env =
function
| (_, p, Call { func = (_, _, Id (_, name)); targs = _ :: _ as tal; _ })
-> begin
match Decl_provider.get_fun (Tast_env.get_ctx env) name with
| Some { fe_type; _ } -> begin
match get_node fe_type with
| Tfun { ft_tparams = tpl; _ } ->
if List.exists tpl ~f:has_non_disjoint_attr then
let (pairs, _) = List.zip_with_remainder tpl tal in
let tyl =
List.filter_map pairs ~f:(fun (tp, (ty, _)) ->
if has_non_disjoint_attr tp then
Some ty
else
None)
in
check_non_disjoint_tyl env p name tyl
| _ -> ()
end
| _ -> ()
end
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/lints/linter_duplicate_properties.ml | (*
* Copyright (c) 2020, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
open Typing_defs
module Cls = Decl_provider.Class
(* efficient check for List.length l > 1 *)
let more_than_one l =
match l with
| _ :: _ :: _ -> true
| _ -> false
(* All the trait names that appear in a use T statement inside class c *)
let traits c : (Pos.t * string) list =
List.filter_map c.c_uses ~f:(fun (pos, trait_hint) ->
match trait_hint with
| Happly ((_, trait_name), _) -> Some (pos, trait_name)
| _ -> None)
(* All the properites of class or trait [type name], flattened *)
let properties ctx (type_name : string) : (string * Typing_defs.class_elt) list
=
let decl = Decl_provider.get_class ctx type_name in
match decl with
| Some decl -> Cls.props decl @ Cls.sprops decl
| None -> []
let is_trait_name ctx (type_name : string) : bool =
let decl = Decl_provider.get_class ctx type_name in
match decl with
| Some decl -> Ast_defs.is_c_trait (Cls.kind decl)
| None -> false
(* All the parent classes, used traits, and implemented interfaces of
[type_name]. This is the flattened inheritance tree. *)
let all_ancestor_names ctx (type_name : string) : string list =
let decl = Decl_provider.get_class ctx type_name in
match decl with
| Some decl -> Decl_provider.Class.all_ancestor_names decl
| None -> []
(* All the used traits of [type_name]. This is the flattened inheritance tree. *)
let all_trait_ancestors ctx (trait_name : string) : string list =
let ancestors = all_ancestor_names ctx trait_name in
(* Trait ancestors can be other traits or interfaces. *)
let ancestor_traits = List.filter ancestors ~f:(is_trait_name ctx) in
trait_name :: ancestor_traits
let get_class_nast ctx file_path c_name =
let open Option in
let ast = Ast_provider.find_class_in_file ~full:true ctx file_path c_name in
ast >>| fun ast -> Naming.class_ ctx ast
let check_initialisation ast expr : bool =
let checker =
object (_ : 'self)
val mutable result = false
method result = result
inherit [_] Aast.iter as super
method! on_expr ast ((_, _, expr_) as expr) =
super#on_expr ast expr;
match expr_ with
| Class_const (_, (_, s)) ->
if String.( <> ) s Naming_special_names.Members.mClass then
result <- true
| _ -> ()
end
in
checker#on_expr ast expr;
checker#result
let handler =
object
inherit Tast_visitor.handler_base
method! at_class_ env c =
let ctx = Tast_env.get_ctx env in
let (cls_pos, cls_name) = c.c_name in
(* props_seen maps
* - the property names of each trait used by cls to their origin
* - the properties defined by cls itself to cls
* If a property is inherited multiple times, props_seen will report multiple origins*)
let props_seen = Hashtbl.create (module Base.String) in
(* in decls static properties are stored with a leading dollar, in class_var without:
* normalise removing leading dollars *)
let strip_dollar s = String.lstrip s ~drop:(fun c -> Char.equal c '$') in
(* add the properties defined in the class itself to props_seen *)
List.iter c.c_vars ~f:(fun v ->
Hashtbl.add_multi props_seen ~key:(snd v.cv_id) ~data:cls_name);
(* for each used trait add the properties defined in the trait, mapped to their origin *)
List.iter (traits c) ~f:(fun (_, type_name) ->
let all_trait_ancestors =
SSet.of_list (all_trait_ancestors ctx type_name)
in
List.iter (properties ctx type_name) ~f:(fun (prop_name, prop_elt) ->
(* but do not add properties that are imported via require extends *)
if SSet.mem prop_elt.ce_origin all_trait_ancestors then
Hashtbl.add_multi
props_seen
~key:(strip_dollar prop_name)
~data:prop_elt.ce_origin));
(* if the props_seen reports multiple origins for a property,
* ensure that in none of the origins it is initialisedl
* with an enum or class constant *)
Hashtbl.iteri props_seen ~f:(fun ~key ~data ->
if more_than_one data then
(* property key is inherited multiple times, possibly via diamond inclusion
* ensure that is never initialised with an enum or class constant *)
let is_initialised_with_class_constant =
List.fold data ~init:false ~f:(fun status origin ->
let open Option in
let res =
let opt_origin_file_path =
Naming_provider.get_class_path ctx origin
in
opt_origin_file_path >>= fun file_path ->
get_class_nast ctx file_path origin >>= fun ast ->
let opt_var =
List.find ast.c_vars ~f:(fun v ->
String.equal (snd v.cv_id) key)
in
opt_var >>= fun var ->
var.cv_expr >>| fun expr ->
status || check_initialisation ast expr
in
Option.value ~default:status res)
in
(* remove duplicate trait names arising from diamond inclusion from data *)
let dedup_data = List.dedup_and_sort data ~compare:String.compare in
if is_initialised_with_class_constant then
(* HHVM will unconditinally fatal, so report a linter error *)
Lints_errors.duplicate_property_class_constant_init
cls_pos
~class_name:cls_name
~prop_name:key
~class_names:dedup_data
else if more_than_one dedup_data then
(* there is a duplicate property not arising from diamond inclusion, warn about it *)
Lints_errors.duplicate_property
cls_pos
~class_name:cls_name
~prop_name:key
~class_names:dedup_data)
end |
OCaml | hhvm/hphp/hack/src/lints/linter_equality_check.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
open Tast
open Ast_defs
open Typing_defs
module Cls = Decl_provider.Class
module Env = Tast_env
module MakeType = Typing_make_type
module SN = Naming_special_names
let enum_base_type env cid =
match Decl_provider.get_class (Typing_env.get_ctx env) cid with
| None -> (env, None)
| Some cls ->
(match Cls.enum_type cls with
| None -> (env, None)
| Some te ->
let ((env, ty_err_opt), ty) =
Typing_phase.localize_no_subst env ~ignore_errors:true te.te_base
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
(env, Some ty))
let opaque_enum_expander =
object
inherit Type_mapper.deep_type_mapper as super
inherit! Type_mapper.tvar_expanding_type_mapper
method! on_tnewtype env r cid tyl cstr =
match get_node cstr with
| Tprim Tarraykey when Typing_env.is_enum env cid ->
let (env, cstr') = enum_base_type env cid in
begin
match cstr' with
| None -> (env, mk (r, Tnewtype (cid, tyl, cstr)))
| Some ty ->
(match get_node ty with
| Tprim Tarraykey -> (env, mk (r, Tnewtype (cid, tyl, cstr)))
| _ -> (env, ty))
end
| _ -> super#on_tnewtype env r cid tyl cstr
end
let is_nothing env ty =
let nothing = MakeType.nothing Reason.Rnone in
Tast_env.is_sub_type env ty nothing
let error_if_inequatable env ty1 ty2 err =
let expand_tydef =
Typing_tdef.force_expand_typedef ~ety_env:empty_expand_env
in
let expand_enum = opaque_enum_expander#on_type in
(* Break all type abstractions *)
let expand env ty =
let (env, ty) = expand_enum env ty in
expand_tydef env ty
in
let typing_env = Env.tast_env_as_typing_env env in
let ((typing_env, _), ety1, _) = expand typing_env ty1 in
let ((typing_env, _), ety2, _) = expand typing_env ty2 in
if is_nothing env ety1 || is_nothing env ety2 then
()
else if Typing_subtype.is_type_disjoint typing_env ety1 ety2 then
err (Env.print_ty env ty1) (Env.print_ty env ty2)
let ensure_valid_equality_check env p bop e1 e2 =
let ty1 = get_type e1 in
let ty2 = get_type e2 in
error_if_inequatable
env
ty1
ty2
(Lints_errors.non_equatable_comparison p (equal_bop bop Diff2))
let ensure_valid_contains_check env p trv_val_ty val_ty =
error_if_inequatable
env
trv_val_ty
val_ty
(Lints_errors.invalid_contains_check p)
let ensure_valid_contains_key_check env p trv_key_ty key_ty =
error_if_inequatable
env
trv_key_ty
key_ty
(Lints_errors.invalid_contains_key_check p)
let handler =
object
inherit Tast_visitor.handler_base
method! at_expr env =
function
| (_, p, Binop { bop = (Diff | Diff2 | Eqeqeq | Eqeq) as bop; lhs; rhs })
->
ensure_valid_equality_check env p bop lhs rhs
| ( _,
p,
Call { func = (_, _, Id (_, id)); targs = [(tv1, _); (tv2, _)]; _ } )
when String.equal id SN.HH.contains ->
ensure_valid_contains_check env p tv1 tv2
| ( _,
p,
Call { func = (_, _, Id (_, id)); targs = [(tk1, _); (tk2, _); _]; _ }
)
when String.equal id SN.HH.contains_key ->
ensure_valid_contains_key_check env p tk1 tk2
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/lints/linter_expr_tree_types.ml | (*
* Copyright (c) 2021, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
let handler =
object
inherit Tast_visitor.handler_base
(* Require that methods named __bool should return a bool. *)
method! at_method_ _env m =
let (_, name) = m.m_name in
if String.equal name "__bool" then
let (_, hint) = m.m_ret in
match hint with
| Some (_, Hprim Tbool) -> ()
| Some (p, _) -> Lints_errors.bad_virtualized_method p
| None -> ()
end |
OCaml | hhvm/hphp/hack/src/lints/linter_foreach_shadow.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 Linting_visitors
open Aast
(**
Lint on loop or catch variables that shadow local variables.
function foo(): void {
$x = 99;
// Lint on this $x:
foreach (vec[1, 2] as $x) {
}
// $x is 2 here.
$x;
}
*)
let lvar_visitor =
object
inherit [lid list] Nast.Visitor_DEPRECATED.visitor
method! on_lvar ids id = id :: ids
end
let expr_lvars = lvar_visitor#on_expr []
let as_expr_lvars = lvar_visitor#on_as_expr []
module VisitorFunctor (Parent : BodyVisitorModule) : BodyVisitorModule = struct
class visitor env =
object (this)
inherit Parent.visitor env as parent
val mutable frames : lid list list = [[]]
method private env = List.concat frames
method private extend_env vars =
frames <- List.rev_append vars (List.hd frames) :: List.tl frames
method private push_empty_frame = frames <- [] :: frames
method private pop_frame = frames <- List.tl frames
method private on_block_with_local_vars vars block =
this#push_empty_frame;
this#extend_env vars;
parent#on_block () block;
this#pop_frame
method! on_block () = this#on_block_with_local_vars []
method! on_stmt () stmt =
begin
match snd stmt with
| Expr (_, _, Binop { bop = Ast_defs.Eq _; lhs = e; _ }) ->
this#extend_env (expr_lvars e)
| _ -> ()
end;
parent#on_stmt () stmt
method! on_foreach () expr as_expr block =
this#on_expr () expr;
this#on_as_expr () as_expr;
this#on_block_with_local_vars (as_expr_lvars as_expr) block
method! on_as_expr () as_expr =
let env = this#env in
List.iter
(fun (p1, id1) ->
if String.equal (Local_id.get_name id1) "$_" then
()
else
match List.find_opt (fun (_, id2) -> id1 = id2) env with
| None -> ()
| Some (p2, _) ->
Lints_errors.loop_variable_shadows_local_variable p1 id1 p2)
(as_expr_lvars as_expr);
parent#on_as_expr () as_expr
method! on_catch () (_, var, block) =
this#on_block_with_local_vars [var] block
method! on_expr () ((_, _, e_) as e) =
match e_ with
| Efun _
| Lfun _ ->
let old_frames = frames in
frames <- [[]];
parent#on_expr () e;
frames <- old_frames
| _ -> parent#on_expr () e
end
end
let go = lint_all_bodies (module VisitorFunctor) |
OCaml | hhvm/hphp/hack/src/lints/linter_internal_class.ml | (*
* Copyright (c) 2023, Meta, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
module Env = Tast_env
module Cls = Decl_provider.Class
module SN = Naming_special_names
let check_internal_classname pos ci env =
let tenv = Env.tast_env_as_typing_env env in
let class_result =
match ci with
| CI cls -> Typing_env.get_class tenv (snd cls)
| CIself
| CIstatic ->
Typing_env.get_self_class tenv
| CIparent -> Typing_env.get_parent_class tenv
| _ -> None
in
match class_result with
| Some cls when Cls.internal cls -> Lints_errors.internal_classname pos
| _ -> ()
(* Checks creation of a ::class from an internal class *)
let handler =
object
inherit Tast_visitor.handler_base
method! at_expr env (_, _, expr) =
match expr with
| Class_const ((_, p, ci), pstr) when String.equal (snd pstr) "class" ->
check_internal_classname p ci env
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/lints/linter_invariant_violation.ml | open Linting_visitors
open Nast
module Nast = Aast
type conditionKind =
| CKString
| CKLiteral of bool
| CKUnaryNot of bool
| CKUnknown
(* checks if condition consists only of literal values and unary not operator *)
class condition_visitor =
object
inherit [conditionKind] Visitor_DEPRECATED.visitor as parent
method! on_expr_ acc e =
match e with
| Nast.String _ -> CKString
| Nast.True -> CKLiteral true
| Nast.False -> CKLiteral false
| Nast.Unop (Ast_defs.Unot, e') -> begin
match parent#on_expr acc e' with
| CKLiteral v -> CKUnaryNot v
| CKUnaryNot v -> CKUnaryNot (not v)
| e -> e
end
| _ -> CKUnknown
end
module VisitorFunctor (Parent : BodyVisitorModule) : BodyVisitorModule = struct
class visitor lint_env =
object
inherit Parent.visitor lint_env as parent
method! on_if _ (ty, p, e) b1 b2 =
let is_invariant_violation_call =
(* invariant() is not actually a function - both the typechecker and
* the runtime transform it into an if statement with a call to
* invariant_violation() inside.
*)
match b1 with
| [
( _,
Nast.Expr
( _,
_,
Nast.(
Call
{
func = (_, _, Nast.Id (_, "\\HH\\invariant_violation"));
_;
}) ) );
] ->
true
| _ -> false
in
let err_msg =
match (new condition_visitor)#on_expr CKUnknown (ty, p, e) with
| CKUnknown -> None
| CKString ->
let err_msg =
if is_invariant_violation_call then
"invariant('error message') will never or always crash. Did you mean invariant_violation()?"
else
"Putting a string literal in the condition of an if statement guarantees it will always or never trigger."
in
Some err_msg
| CKUnaryNot true when is_invariant_violation_call ->
let err_msg =
"Your expression always evaluates to true. Because of this, invariant() will never throw an exception here. If this is the behavior you want simply remove or comment out the line."
in
Some err_msg
| CKUnaryNot false when is_invariant_violation_call ->
let err_msg =
"Your expression always evaluates to false. Because of this, invariant() will always throw an exception here. If this is the behavior you want, please use invariant_violation() explicitly instead."
in
Some err_msg
| _ -> None
in
begin
match err_msg with
| Some err_msg -> Lints_errors.if_literal p err_msg
| None -> ()
end;
parent#on_if () (ty, p, e) b1 b2
end
end
let go = lint_all_bodies (module VisitorFunctor) |
OCaml | hhvm/hphp/hack/src/lints/linter_is_checks.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
module Env = Tast_env
module TUtils = Typing_utils
module T = Typing_defs
let nothing_ty = Typing_make_type.nothing Typing_reason.Rnone
(* To handle typechecking against placeholder, e.g., `... as C<_>`, we convert
the generic the placeholder is elaborated to into a type variable so that
the subtyping query can be discharged. *)
let replace_placeholders_with_tvars env ty =
let replace_placeholder env ty =
match T.get_node ty with
| T.Tgeneric (name, []) when String.contains name '#' ->
Typing_env.fresh_type env Pos.none
| _ -> (env, ty)
in
match T.get_node ty with
| T.Tclass (id, exact, targs) ->
let (env, targs) = List.fold_map ~f:replace_placeholder ~init:env targs in
(env, T.mk (Typing_reason.Rnone, T.Tclass (id, exact, targs)))
| _ -> (env, ty)
let trivial_check pos env lhs_ty rhs_ty ~always_subtype ~never_subtype =
let (env, lhs_ty) = Env.expand_type env lhs_ty in
let (env, rhs_ty) = Env.expand_type env rhs_ty in
let tenv = Env.tast_env_as_typing_env env in
let tenv = Typing_env.open_tyvars tenv Pos.none in
let (tenv, rhs_ty) = replace_placeholders_with_tvars tenv rhs_ty in
if Env.is_sub_type env lhs_ty nothing_ty then
(* If we have a nothing in our hands, there was a bigger problem
originating from earlier in the program. Don't flag it here, as it is
merely a symptom. *)
()
else
(* We can't just use the `is_subtype` API which will discharge the
propositions with the fresh type variables. Instead, we use `sub_type`
which feedback the propositions against unconstrained type variables as
assumptions. *)
let callback = Typing_error.Reasons_callback.unify_error_at Pos.none in
let (tenv, err_opt1) = TUtils.sub_type tenv lhs_ty rhs_ty (Some callback) in
let (tenv, err_opt2) = Typing_solver.close_tyvars_and_solve tenv in
let err_opt = Option.merge err_opt1 err_opt2 ~f:Typing_error.both in
let env = Env.typing_env_as_tast_env tenv in
let (env, lhs_ty) = Env.expand_type env lhs_ty in
let (env, rhs_ty) = Env.expand_type env rhs_ty in
let print_ty = Env.print_ty env in
if Option.is_none err_opt then
always_subtype pos (print_ty lhs_ty) (print_ty rhs_ty)
else if TUtils.is_type_disjoint tenv lhs_ty rhs_ty then
never_subtype pos (print_ty lhs_ty) (print_ty rhs_ty)
let handler =
object
inherit Tast_visitor.handler_base
method! at_expr env =
let check_status = Env.get_check_status env in
function
| (_, p, Is ((lhs_ty, _, _), hint)) ->
let (env, hint_ty) = Env.localize_hint_for_refinement env hint in
trivial_check
p
env
lhs_ty
hint_ty
~always_subtype:(Lints_errors.is_always_true ~check_status)
~never_subtype:(Lints_errors.is_always_false ~check_status)
| (_, p, As ((lhs_ty, lhs_pos, lhs_expr), hint, false)) ->
let (env, hint_ty) = Env.localize_hint_for_refinement env hint in
let can_be_captured = Aast_utils.can_be_captured lhs_expr in
let always_subtype p =
Lints_errors.as_always_succeeds
~check_status
~can_be_captured
~as_pos:p
~child_expr_pos:lhs_pos
in
trivial_check
p
env
lhs_ty
hint_ty
~always_subtype
~never_subtype:(Lints_errors.as_always_fails ~check_status)
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/lints/linter_loose_unsafe_cast.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module T = Typing_defs
let handler =
object
inherit Tast_visitor.handler_base
method! at_expr env =
let env = Tast_env.tast_env_as_typing_env env in
let is_mixed = Typing_utils.is_mixed env in
let is_nothing = Typing_utils.is_nothing env in
let pos_of_ty ~hole_pos ty =
let current_decl_and_file = Typing_env.get_current_decl_and_file env in
let ty_pos_opt =
Pos_or_decl.fill_in_filename_if_in_current_decl
~current_decl_and_file
(T.get_pos ty)
in
match ty_pos_opt with
| Some ty_pos -> ty_pos
| None -> hole_pos
in
function
| ( _,
hole_pos,
Aast.Hole
( (expr_ty, expr_pos, expr),
_,
dest_ty,
(Aast.UnsafeCast _ | Aast.UnsafeNonnullCast) ) )
when (not @@ Typing_defs.is_any expr_ty)
&& Typing_subtype.is_sub_type env expr_ty dest_ty ->
let can_be_captured = Aast_utils.can_be_captured expr in
Lints_errors.redundant_unsafe_cast ~can_be_captured hole_pos expr_pos
| (_, _, Aast.Hole ((exp_ty, hole_pos, _), src_ty, _, Aast.UnsafeCast _))
when is_mixed src_ty && (not (is_mixed exp_ty)) && T.is_denotable exp_ty
->
let ty_str = Typing_print.debug env exp_ty in
let ty_str_opt =
if String.length ty_str <= 20 then
Some ty_str
else
None
in
Lints_errors.loose_unsafe_cast_lower_bound
(pos_of_ty ~hole_pos src_ty)
ty_str_opt
| (_, _, Aast.Hole ((_, hole_pos, _), _, dst_ty, Aast.UnsafeCast _))
when is_nothing dst_ty ->
Lints_errors.loose_unsafe_cast_upper_bound (pos_of_ty ~hole_pos dst_ty)
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/lints/linter_missing_override_attribute.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
open Typing_defs
module Cls = Decl_provider.Class
module SN = Naming_special_names
let has_override_attribute m =
List.exists m.m_user_attributes ~f:(fun ua ->
String.equal (snd ua.ua_name) SN.UserAttributes.uaOverride)
let is_interface c = Ast_defs.is_c_interface (Cls.kind c)
(* Do not emit an error for classes implementing an interface method, but do
emit errors for interfaces overriding interface methods, classes overriding
class methods, classes overriding trait methods, etc. *)
let both_are_or_are_not_interfaces c1 c2 =
Bool.equal (is_interface c1) (is_interface c2)
(* Return true only if 1) the given method is public or protected, or 2) the
given ancestor is a trait (since a user of the trait will inherit private
trait methods) *)
let should_check_ancestor_method ancestor_class ancestor_method =
if Ast_defs.is_c_trait (Cls.kind ancestor_class) then
true
else
match ancestor_method.ce_visibility with
| Vpublic
| Vprotected _
| Vinternal _ ->
true
| Vprivate _ -> false
let check_methods ctx c cls ~static =
let ancestor_names = Cls.all_ancestor_names cls in
let reqs = Cls.all_ancestor_req_names cls in
(* filter out interfaces *)
let reqs =
List.filter
~f:(fun class_name ->
match Decl_provider.get_class ctx class_name with
| None -> false
| Some cls -> not (Ast_defs.is_c_interface (Cls.kind cls)))
reqs
in
let ancestor_names = ancestor_names @ reqs in
let get_method =
if static then
Cls.get_smethod
else
Cls.get_method
in
(* For each method, *)
let (_, static_methods, c_methods) = split_methods c.c_methods in
(if static then
static_methods
else
c_methods)
|> Sequence.of_list
(* which doesn't have the override attribute, *)
|> Sequence.filter ~f:(fun m -> not (has_override_attribute m))
(* and is not the constructor, *)
|> Sequence.filter ~f:(fun m ->
not (String.equal (snd m.m_name) SN.Members.__construct))
|> Sequence.iter ~f:(fun m ->
let (p, mid) = m.m_name in
let matching_ancestor =
ancestor_names
(* inspect each ancestor, *)
|> List.filter_map ~f:(Decl_provider.get_class ctx)
(* and if it has a method with the same name, and either that method
is non-private or the ancestor is a trait, *)
|> List.filter_map ~f:(fun ancestor ->
match get_method ancestor mid with
| None -> None
| Some ancestor_method ->
if should_check_ancestor_method ancestor ancestor_method
then
Some ancestor_method
else
None)
(* get the class which defined that method, *)
|> List.filter_map ~f:(fun m ->
Decl_provider.get_class ctx m.ce_origin)
(* as long as it and this class are of the same kind. *)
|> List.filter ~f:(both_are_or_are_not_interfaces cls)
(* If such a class exists... *)
|> List.hd
in
match matching_ancestor with
| Some ancestor ->
(* ...then this method should have had the override attribute. *)
let first_attr_pos =
Option.map
~f:(fun ua -> fst ua.ua_name)
(List.hd m.m_user_attributes)
in
Lints_errors.missing_override_attribute
~meth_pos:m.m_span
~name_pos:p
~first_attr_pos
~class_name:(Cls.name ancestor)
~method_name:mid
| None -> ())
let handler =
object
inherit Tast_visitor.handler_base
method! at_class_ env c =
let cid = snd c.c_name in
let ctx = Tast_env.get_ctx env in
match Decl_provider.get_class ctx cid with
| None -> ()
| Some cls ->
check_methods ctx c cls ~static:false;
check_methods ctx c cls ~static:true
end |
OCaml | hhvm/hphp/hack/src/lints/linter_nullsafe_not_needed.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.
*
*)
[@@@warning "-33"]
open Hh_prelude
[@@@warning "+33"]
open Aast
module Utils = Tast_utils
let handler =
object
inherit Tast_visitor.handler_base
method! at_expr env =
function
| (_, p, Obj_get ((ty, _, _), _, OG_nullsafe, _))
when Utils.type_non_nullable env ty ->
Lints_errors.nullsafe_not_needed p
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/lints/linter_of_enums.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 Linting_visitors
open Aast
let enum_file_visitor =
object
inherit [unit] abstract_file_visitor
val check_parentage =
fun (position, extends) ->
let enum_parents = ["Enum"; "ApiEnum"] in
let check_parent parent =
if extends ("\\" ^ parent) then
Lints_errors.deprecated
position
("Extending "
^ parent
^ " is deprecated, please use Hack enum. https://docs.hhvm.com/hack/enums/"
)
in
List.iter check_parent enum_parents
method! on_class () env class_ =
let (p, c_name) = class_.c_name in
match Decl_provider.get_class env.ctx c_name with
| None -> Lint.internal_error p "Could not find class"
| Some tclass ->
check_parentage (p, Decl_provider.Class.has_ancestor tclass)
end
let go = enum_file_visitor#on_file () |
OCaml | hhvm/hphp/hack/src/lints/linter_pointless_booleans.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
let which_boolean_literal ((_ty, _pos, expr_) : Tast.expr) =
match expr_ with
| Aast.True -> Some Aast.True
| Aast.False -> Some Aast.False
| _ -> None
let is_boolean_expression ((ty, _pos, _expr_) : Tast.expr) =
Typing_defs.is_prim Aast.Tbool ty
let checking_the_expression exp1 exp2 =
match which_boolean_literal exp1 with
| Some x when is_boolean_expression exp2 -> Some x
| _ -> None
let check_the_error logical_op boolean_literal =
match logical_op with
| Ast_defs.Ampamp ->
(match boolean_literal with
| Aast.True -> Some "The boolean expression is pointless"
| Aast.False -> Some "The boolean expression is always false"
| _ -> None)
| Ast_defs.Barbar ->
(match boolean_literal with
| Aast.True -> Some "The boolean expression is always true"
| Aast.False -> Some "The boolean expression is pointless"
| _ -> None)
| _ -> None
let send_to_lint_error pos str line1 line2 bol1 bol2 col1 col2 =
let path_name = Pos.filename (Pos.to_absolute pos) in
let pos_quickfix =
Pos.make_from_lexing_pos
(Pos.filename pos)
Lexing.
{
pos_fname = path_name;
pos_lnum = line1;
pos_bol = bol1;
pos_cnum = col1;
}
Lexing.
{
pos_fname = path_name;
pos_lnum = line2;
pos_bol = bol2;
pos_cnum = col2;
}
in
Lints_errors.calling_pointless_boolean pos pos_quickfix str
let handler =
object
inherit Tast_visitor.handler_base
method! at_expr _env (_, pos, expr_) =
match expr_ with
| Aast.(Binop { bop; lhs; rhs }) ->
(match bop with
| Ast_defs.Ampamp
| Ast_defs.Barbar ->
(* exp1 is the boolean literal (it is of the type true ||, false && etc)*)
(* The original string for quickfix starts from the
start of exp1 and ends at the start of exp2 *)
(match checking_the_expression lhs rhs with
| Some x ->
(match check_the_error bop x with
| Some str ->
(match (lhs, rhs) with
| ((_, pos_exp1, _), (_, pos_exp2, _)) ->
let (line1, bol1, start_col1) = Pos.line_beg_offset pos_exp1 in
let (line2, bol2, start_col2) = Pos.line_beg_offset pos_exp2 in
send_to_lint_error
pos
str
line1
line2
bol1
bol2
start_col1
start_col2)
| None -> ())
| None ->
(* exp2 is the boolean literal (it is of the type && true, || false etc)*)
(* The original string for quickfix starts from the
end of exp1 and ends at the end of exp2 *)
(match checking_the_expression rhs lhs with
| Some x ->
(match check_the_error bop x with
| Some str ->
(match (lhs, rhs) with
| ((_, pos_exp1, _), (_, pos_exp2, _)) ->
let (line1, bol1, end_col1) =
Pos.end_line_beg_offset pos_exp1
in
let (line2, bol2, end_col2) =
Pos.end_line_beg_offset pos_exp2
in
send_to_lint_error
pos
str
line1
line2
bol1
bol2
end_col1
end_col2)
| None -> ())
| None -> ()))
| _ -> ())
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/lints/linter_redundant_cast.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 T = Typing_defs
module A = Aast_defs
let handler =
object
inherit Tast_visitor.handler_base
method! at_expr env =
function
| (_, pos, Aast.Cast (hint, (expr_ty, expr_pos, expr))) ->
(* This check is implemented with pattern matching rather than
subtyping because I don't want to accidentally error on unlawfully
typed code (e.g., on TAnys). Luckily there are only four
combinations to consider. *)
let (env, expr_ty) = Tast_env.expand_type env expr_ty in
begin
match (T.get_node expr_ty, snd hint) with
| (T.Tprim expr_prim, A.Hprim hint_prim) -> begin
match (expr_prim, hint_prim) with
| (A.Tint, A.Tint)
| (A.Tstring, A.Tstring)
| (A.Tbool, A.Tbool)
| (A.Tfloat, A.Tfloat) ->
let typing_env = Tast_env.tast_env_as_typing_env env in
let cast = "(" ^ Typing_print.full typing_env expr_ty ^ ")" in
let check_status = Tast_env.get_check_status env in
let can_be_captured = Aast_utils.can_be_captured expr in
Lints_errors.redundant_cast
~can_be_captured
~check_status
cast
pos
expr_pos
| _ -> ()
end
| _ -> ()
end
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/lints/linter_redundant_generics.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
open Typing_defs
module Cls = Decl_provider.Class
module SN = Naming_special_names
let ft_redundant_tparams env tparams ty =
let tracked =
List.fold_left
tparams
~f:(fun tracked t -> SSet.add (snd t.tp_name) tracked)
~init:SSet.empty
in
let (positive, negative) =
Typing_variance.get_positive_negative_generics
~is_mutable:false
~tracked
(Tast_env.tast_env_as_typing_env env)
(SMap.empty, SMap.empty)
ty
in
List.iter tparams ~f:(fun t ->
let (pos, name) = t.tp_name in
let pos = Naming_provider.resolve_position (Tast_env.get_ctx env) pos in
(* It's only redundant if it's erased and inferred *)
if
equal_reify_kind t.tp_reified Erased
&& (not
(Attributes.mem
SN.UserAttributes.uaNonDisjoint
t.tp_user_attributes))
&& not
(Attributes.mem SN.UserAttributes.uaExplicit t.tp_user_attributes)
then
let super_bounds =
List.filter
~f:(fun (ck, _) ->
Ast_defs.(equal_constraint_kind ck Constraint_super))
t.tp_constraints
in
let as_bounds =
List.filter
~f:(fun (ck, _) ->
Ast_defs.(equal_constraint_kind ck Constraint_as))
t.tp_constraints
in
match (SMap.find_opt name positive, SMap.find_opt name negative) with
| (Some _, Some _) -> ()
| (Some _positions, None) ->
let bounds_message =
if List.is_empty as_bounds then
""
else
" with useless `as` bound"
in
(* If there is more than one `super` bound, we can't replace,
* because we don't support explicit union types
*)
begin
match super_bounds with
| [] ->
Lints_errors.redundant_covariant pos name bounds_message "nothing"
| [(_, t)] ->
Lints_errors.redundant_covariant
pos
name
bounds_message
(Tast_env.print_decl_ty env t)
| _ -> ()
end
| (None, Some _positions) ->
let bounds_message =
if List.is_empty super_bounds then
""
else
" with useless `super` bound"
in
(* If there is more than one `as` bound, we can't replace,
* because we don't support explicit intersection types
*)
begin
match as_bounds with
| [] ->
Lints_errors.redundant_contravariant
pos
name
bounds_message
"mixed"
| [(_, t)] ->
Lints_errors.redundant_contravariant
pos
name
bounds_message
(Tast_env.print_decl_ty env t)
| _ -> ()
end
| (None, None) -> Lints_errors.redundant_generic pos name)
let check_redundant_generics_class_method env (_method_name, method_) =
match method_.ce_type with
| (lazy (ty as ft)) -> begin
match get_node ty with
| Tfun { ft_tparams; _ } -> ft_redundant_tparams env ft_tparams ft
| _ -> assert false
end
let check_redundant_generics_fun env ft =
ft_redundant_tparams env ft.ft_tparams (mk (Reason.Rnone, Tfun ft))
let check_redundant_generics_class env class_name class_type =
Cls.methods class_type
|> ListLabels.filter ~f:(fun (_, meth) ->
String.equal meth.ce_origin class_name)
|> List.iter ~f:(check_redundant_generics_class_method env);
Cls.smethods class_type
|> List.filter ~f:(fun (_, meth) -> String.equal meth.ce_origin class_name)
|> List.iter ~f:(check_redundant_generics_class_method env)
let handler =
object
inherit Tast_visitor.handler_base
method! at_fun_def env fd =
match Decl_provider.get_fun (Tast_env.get_ctx env) (snd fd.fd_name) with
| Some { fe_type; _ } -> begin
match get_node fe_type with
| Tfun ft -> check_redundant_generics_fun env ft
| _ -> ()
end
| _ -> ()
method! at_class_ env c =
let cid = snd c.c_name in
match Decl_provider.get_class (Tast_env.get_ctx env) cid with
| None -> ()
| Some cls -> check_redundant_generics_class env (snd c.c_name) cls
end |
OCaml | hhvm/hphp/hack/src/lints/linter_sketchy_null_check.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Ast_defs
open Aast
open Typing_defs
module Env = Tast_env
let get_lvar_name = function
| Lvar (_, id) -> Some (Local_id.get_name id)
| _ -> None
let rec is_abstract_or_unknown env ty =
let (_, ty) = Env.expand_type env ty in
match get_node ty with
| Tany _
| Tdynamic
| Tvar _
| Tgeneric _
| Tnewtype _
| Tdependent _ ->
true
| Tunion tyl -> List.exists tyl ~f:(is_abstract_or_unknown env)
| Tintersection tyl -> List.for_all tyl ~f:(is_abstract_or_unknown env)
| _ -> false
let sketchy_null_check env (ty, p, e) kind =
if
Env.is_sub_type_for_union env (Typing_make_type.null Reason.none) ty
|| is_abstract_or_unknown env ty
then
let name = get_lvar_name e in
Tast_utils.(
let (env, nonnull_ty) = Env.non_null env (get_pos ty) ty in
match truthiness env nonnull_ty with
| Possibly_falsy -> Lints_errors.sketchy_null_check p name kind
| Always_truthy
| Always_falsy
| Unknown ->
())
let handler =
object
inherit Tast_visitor.handler_base
method! at_expr env (_, _, x) =
match x with
| Eif (e, None, _) -> sketchy_null_check env e `Coalesce
| Unop (Unot, e)
| Binop { bop = Eqeq; lhs = (_, _, Null); rhs = e }
| Binop { bop = Eqeq; lhs = e; rhs = (_, _, Null) } ->
sketchy_null_check env e `Eq
| Eif (e, Some _, _) -> sketchy_null_check env e `Neq
| Binop { bop = Ampamp | Barbar; lhs = e1; rhs = e2 } ->
sketchy_null_check env e1 `Neq;
sketchy_null_check env e2 `Neq
| _ -> ()
method! at_stmt env x =
match snd x with
| If (e, _, _)
| Do (_, e)
| While (e, _)
| For (_, Some e, _, _) ->
sketchy_null_check env e `Neq
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/lints/linter_switch_check.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
module Env = Tast_env
module Reason = Typing_reason
module MakeType = Typing_make_type
module SN = Naming_special_names
module Typing = Typing_defs
module Cls = Decl_provider.Class
let ensure_valid_switch_case_value_types env scrutinee_ty casel =
(* Enum class label === only consider the label name. No type information
* is enforced as they might not be available to the runtime in all
* use cases.
* If one of the two type is a label, we don't run this linter as it
* would fire wrong warnings. Note that if one is a label and the other
* is not, a Hack error 4020 is fired.
*)
let is_label ty =
let open Typing_defs in
match get_node ty with
| Tnewtype (name, [_; _], _) -> String.equal name SN.Classes.cEnumClassLabel
| _ -> false
in
let ensure_valid_switch_case_value_type ((case_value_ty, case_value_p, _), _)
=
let tenv = Tast_env.tast_env_as_typing_env env in
if
(not (is_label case_value_ty || is_label scrutinee_ty))
&& Typing_subtype.is_type_disjoint tenv case_value_ty scrutinee_ty
then
Lints_errors.invalid_switch_case_value_type
case_value_p
(lazy (Env.print_ty env case_value_ty))
(lazy (Env.print_ty env scrutinee_ty))
in
List.iter casel ~f:ensure_valid_switch_case_value_type
let check_exhaustiveness_lint env pos ty has_default =
let rec has_infinite_values ty =
match Typing.get_node ty with
| Typing.Tunion tyl -> List.exists tyl ~f:has_infinite_values
| Typing.Tintersection tyl -> List.for_all tyl ~f:has_infinite_values
| Typing.Tprim (Tstring | Tint | Tfloat | Tarraykey | Tnum) -> true
| Typing.Tclass ((_, name), _, _) -> begin
match Decl_provider.get_class (Env.get_ctx env) name with
| Some class_decl
when not
(Cls.final class_decl
|| Option.is_some (Cls.sealed_whitelist class_decl)) ->
true
| _ -> false
end
| _ -> false
in
let under_dynamic_assumptions =
Tast.is_under_dynamic_assumptions @@ Env.get_check_status env
in
if
(not under_dynamic_assumptions) && has_infinite_values ty && not has_default
then
Lints_errors.switch_nonexhaustive pos
let handler =
object
inherit Tast_visitor.handler_base
method! at_stmt env x =
match snd x with
| Switch ((scrutinee_ty, scrutinee_pos, _), casel, dfl) ->
ensure_valid_switch_case_value_types env scrutinee_ty casel;
check_exhaustiveness_lint
env
scrutinee_pos
scrutinee_ty
(Option.is_some dfl)
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/lints/linter_truthiness_test.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Ast_defs
open Aast
open Typing_defs
module Env = Tast_env
module SN = Naming_special_names
module MakeType = Typing_make_type
let truthiness_test env (ty, p, _e) =
Tast_utils.(
let prim_to_string prim =
Env.print_error_ty env (MakeType.prim_type (get_reason ty) prim)
in
List.iter (find_sketchy_types env ty) ~f:(function
| String ->
let tystr = prim_to_string Aast_defs.Tstring in
Lints_errors.sketchy_truthiness_test p tystr `String
| Arraykey ->
let tystr = prim_to_string Aast_defs.Tarraykey in
Lints_errors.sketchy_truthiness_test p tystr `Arraykey
| Stringish ->
let tystr = Utils.strip_ns SN.Classes.cStringish in
Lints_errors.sketchy_truthiness_test p tystr `Stringish
| XHPChild ->
let tystr = Utils.strip_ns SN.Classes.cXHPChild in
Lints_errors.sketchy_truthiness_test p tystr `XHPChild
| Traversable_interface tystr ->
Lints_errors.sketchy_truthiness_test p tystr `Traversable);
match truthiness env ty with
| Always_truthy ->
Lints_errors.invalid_truthiness_test p (Env.print_ty env ty)
| Always_falsy ->
Lints_errors.invalid_truthiness_test_falsy p (Env.print_ty env ty)
| Possibly_falsy
| Unknown ->
())
let handler =
object
inherit Tast_visitor.handler_base
method! at_expr env (_, _, x) =
match x with
| Unop (Unot, e)
| Eif (e, _, _) ->
truthiness_test env e
| Binop { bop = Ampamp | Barbar; lhs = e1; rhs = e2 } ->
truthiness_test env e1;
truthiness_test env e2
| _ -> ()
method! at_stmt env x =
match snd x with
| If (e, _, _)
| Do (_, e)
| While (e, _)
| For (_, Some e, _, _) ->
truthiness_test env e
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/lints/linter_unconditional_recursion.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Aast
open Hh_prelude
type method_prop = {
method_name: string;
class_name: string;
pos: Pos.t;
}
type fun_prop = {
fun_name: string;
pos: Pos.t;
}
type is_fun_or_method =
| Is_fun of fun_prop
| Is_method of method_prop
let same_name_ignoring_ns (name1 : string) (name2 : string) =
String.equal (Utils.strip_ns name1) (Utils.strip_ns name2)
let check_expr (expr_ : Tast.expr_) (is_fun_or_method : is_fun_or_method) =
match is_fun_or_method with
| Is_fun f_prop ->
(match expr_ with
| Aast.Call { func = (_, _, Aast.Id (_, name)); _ } ->
same_name_ignoring_ns name f_prop.fun_name
| _ -> false)
| Is_method m_prop ->
(match expr_ with
| Aast.Call
{
func =
( _,
_,
Aast.Obj_get
((_, _, Aast.This), (_, _, Aast.Id (_, name)), _, Aast.Is_method)
);
_;
} ->
same_name_ignoring_ns name m_prop.method_name
| Aast.Call
{
func =
( _,
_,
Aast.Class_const ((_, _, Aast.CI (_, name_of_class)), (_, name))
);
_;
}
when same_name_ignoring_ns name_of_class m_prop.class_name ->
same_name_ignoring_ns name m_prop.method_name
| Aast.Call
{
func = (_, _, Aast.Class_const ((_, _, Aast.CIstatic), (_, name)));
_;
} ->
same_name_ignoring_ns name m_prop.method_name
| Aast.Call
{ func = (_, _, Aast.Class_const ((_, _, Aast.CIself), (_, name))); _ }
->
same_name_ignoring_ns name m_prop.method_name
| _ -> false)
let is_recursive_call
((_, stmt_) : Tast.stmt) (is_fun_or_method : is_fun_or_method) =
match stmt_ with
| Aast.Return (Some (_, _, Aast.Await (_, _, await_exp))) ->
check_expr await_exp is_fun_or_method
| Aast.Return (Some (_, _, e)) -> check_expr e is_fun_or_method
| Aast.Throw (_ty, _pos, expr_) -> check_expr expr_ is_fun_or_method
| Aast.Expr (_ty, _pos, Aast.Await (_, _, await_exp)) ->
check_expr await_exp is_fun_or_method
| Aast.Expr (_ty, _pos, expr_) -> check_expr expr_ is_fun_or_method
| _ -> false
(* This function returns true if the recursion can be terminated. This occurs when we find at least one return or throw statment that is followed by any expression other than a recursive call*)
let can_terminate_visitor is_fun_or_method =
object
inherit [_] Aast.reduce as super
method zero = false
method plus = ( || )
method! on_stmt env s =
match snd s with
| Aast.Return _ -> not (is_recursive_call s is_fun_or_method)
| Aast.Throw _ -> not (is_recursive_call s is_fun_or_method)
| _ -> super#on_stmt env s
end
let can_terminate (s : Tast.stmt) (is_fun_or_method : is_fun_or_method) : bool =
(can_terminate_visitor is_fun_or_method)#on_stmt () s
let rec check_unconditional_recursion
(stmt_list : Tast.stmt list) (is_fun_or_method : is_fun_or_method) =
match stmt_list with
| head :: tail ->
if can_terminate head is_fun_or_method then
()
else if is_recursive_call head is_fun_or_method then
match is_fun_or_method with
| Is_fun f_prop -> Lints_errors.unconditional_recursion f_prop.pos
| Is_method m_prop -> Lints_errors.unconditional_recursion m_prop.pos
else
check_unconditional_recursion tail is_fun_or_method
| [] -> ()
let handler =
object
inherit Tast_visitor.handler_base
method! at_fun_def _env f =
let f_properties : fun_prop =
{ fun_name = snd f.fd_name; pos = f.fd_fun.f_span }
in
let is_f_or_m : is_fun_or_method = Is_fun f_properties in
check_unconditional_recursion f.fd_fun.f_body.fb_ast is_f_or_m
method! at_class_ _env c =
List.iter c.c_methods ~f:(fun c_method ->
let m_properties : method_prop =
{
method_name = snd c_method.m_name;
class_name = snd c.c_name;
pos = c_method.m_span;
}
in
let is_f_or_m : is_fun_or_method = Is_method m_properties in
check_unconditional_recursion c_method.m_body.fb_ast is_f_or_m)
end |
OCaml | hhvm/hphp/hack/src/lints/linter_xhp_attr_value.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
module Cls = Decl_provider.Class
(** If [attr_name] is an enum attribute on [cls], return the list of allowed values. *)
let xhp_enum_attr_values env (cls : Cls.t) (attr_name : string) :
Ast_defs.xhp_enum_value list option =
let attr_name = ":" ^ attr_name in
Cls.props cls
|> List.find ~f:(fun (name, _) -> String.equal attr_name name)
|> Option.map ~f:(fun (_, { Typing_defs.ce_origin = n; _ }) -> n)
|> Option.bind ~f:(fun cls_name ->
Decl_provider.get_class (Tast_env.get_ctx env) cls_name)
|> Option.bind ~f:(fun cls ->
SMap.find_opt attr_name (Cls.xhp_enum_values cls))
let split_attr_values (decl_values : Ast_defs.xhp_enum_value list) :
int list * string list =
let rec aux dvs ((int_vals, string_vals) as acc) =
match dvs with
| Ast_defs.XEV_Int i :: dvs -> aux dvs (i :: int_vals, string_vals)
| Ast_defs.XEV_String s :: dvs -> aux dvs (int_vals, s :: string_vals)
| [] -> acc
in
aux decl_values ([], [])
(** Format enum values as Hack literals. *)
let attr_value_literals (decl_values : Ast_defs.xhp_enum_value list) :
string list =
let as_literal = function
| Ast_defs.XEV_Int i -> string_of_int i
| Ast_defs.XEV_String s -> "\"" ^ s ^ "\""
in
List.map decl_values ~f:as_literal
(** Best-effort conversion from a Hack integer literal to its integer value. *)
let int_of_hack_literal (literal : string) : int option =
let parts = String.split ~on:'_' literal in
let clean_literal = String.concat ~sep:"" parts in
int_of_string_opt clean_literal
(** If [attr] is initialized with a literal value that isn't in the
enum declaration, show a lint error. *)
let check_attr_value env (cls : Cls.t) (attr : ('a, 'b) xhp_attribute) : unit =
match attr with
| Xhp_simple
{ xs_name = (_, attr_name); xs_expr = (_, attr_val_pos, attr_val); _ } ->
(match xhp_enum_attr_values env cls attr_name with
| Some attr_values ->
let (int_values, string_values) = split_attr_values attr_values in
(match attr_val with
| Int i ->
(match int_of_hack_literal i with
| Some i ->
if not (List.mem int_values i ~equal:Int.equal) then
Lints_errors.invalid_attribute_value
attr_val_pos
attr_name
(attr_value_literals attr_values)
| None -> ())
| String s ->
if not (List.mem string_values s ~equal:String.equal) then
Lints_errors.invalid_attribute_value
attr_val_pos
attr_name
(attr_value_literals attr_values)
| _ -> ())
| None -> ())
| Xhp_spread _ -> ()
let handler =
object
inherit Tast_visitor.handler_base
method! at_expr env (_, _, e_) =
match e_ with
| Xml ((_, class_name), attrs, _children) ->
(match Decl_provider.get_class (Tast_env.get_ctx env) class_name with
| Some cls -> List.iter attrs ~f:(check_attr_value env cls)
| None -> ())
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/lints/linting_main.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 Linting_visitors
let untyped_linters =
[
Linter_clone.go;
Linter_foreach_shadow.go;
Linter_invariant_violation.go;
Linter_of_enums.go;
Linter_await_in_loop.go;
]
@ Linting_service.untyped_linters
let typed_linters =
[
Linter_equality_check.handler;
Linter_disjoint_types.handler;
Linter_is_checks.handler;
Linter_switch_check.handler;
Linter_missing_override_attribute.handler;
Linter_sketchy_null_check.handler;
Linter_truthiness_test.handler;
Linter_redundant_generics.handler;
Linter_class_overrides_trait.handler;
Linter_expr_tree_types.handler;
Linter_nullsafe_not_needed.handler;
Linter_duplicate_properties.handler;
Linter_loose_unsafe_cast.handler;
Linter_redundant_cast.handler;
Linter_xhp_attr_value.handler;
Linter_pointless_booleans.handler;
Linter_comparing_booleans.handler;
Linter_unconditional_recursion.handler;
Linter_branches_return_same_value.handler;
Linter_internal_class.handler;
Linter_async_lambda.handler;
Linter_cast_non_primitive.handler;
]
@ Linting_service.typed_linters
let lint_tast ctx (tast : Tast.program) =
(Tast_visitor.iter_with typed_linters)#go ctx tast;
Linting_service.lint_tast ctx tast
(* Most lint rules are easier to write against the named AST. However, some
* things that we want to lint for are discarded / simplified by the time we
* reach that stage, so we have a few lint rules that get checked during or
* right after parsing. *)
let parse_and_lint fn content ctx =
let parser_result =
Errors.ignore_ (fun () ->
Full_fidelity_ast.defensive_program
~elaborate_namespaces:true
(Provider_context.get_tcopt ctx)
fn
content)
in
let { Parser_return.ast; _ } = parser_result in
Linter_ast.go ast;
parser_result
let lint_nast tcopt fn pr =
Linting_visitors.reset ();
List.iter (fun go -> go tcopt fn pr) untyped_linters;
(* Run Nast visitors *)
body_visitor_invoker#on_file () tcopt fn pr;
()
let lint ctx fn content =
let orig_trace = !Typing_deps.trace in
Typing_deps.trace := false;
Errors.ignore_ (fun () ->
let parser_return = parse_and_lint fn content ctx in
let { Parser_return.file_mode; ast = full_ast; _ } = parser_return in
(* naming and typing currently don't produce any lint errors *)
(* PHP files generate declarations via some fairly error-prone regexps,
* so only try to lint Hack files *)
match file_mode with
| None -> ()
| Some _ ->
(* Note that the named ASTs that we lint here aren't generated from the
* unnamed ASTs that parse_and_lint generated; we're using the ones
* already in the naming heap, which hh_server keeps up-to-date based
* on inotify events. This is a little ugly, and might be worth
* cleaning up at some point. *)
lint_nast ctx fn parser_return;
(* Get Typed AST and run TAST linters *)
let (_, tast) =
Typing_check_job.calc_errors_and_tast ctx fn ~full_ast
in
(* collect both the dynamic TAST and non-dynamic TAST in a big list,
that's what linting expects! *)
let tasts =
Tast.tasts_as_list tast
|> Tast_with_dynamic.collect
|> Tast_with_dynamic.all
|> List.concat
in
lint_tast ctx tasts);
Typing_deps.trace := orig_trace |
OCaml Interface | hhvm/hphp/hack/src/lints/linting_main.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val lint : Provider_context.t -> Relative_path.t -> string -> unit |
OCaml | hhvm/hphp/hack/src/lints/linting_visitors.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 Hashtbl = Stdlib.Hashtbl
open Aast
open Nast
(****************************************************************************)
(* Attention for lint rule writers: This file contains a fair bit of
* complexity that you probably don't need to bother with. For a simple
* example linter that applies to all files in www, look at linter_js.ml. If
* your lint rule should only apply to specific files / classes / methods,
* look at linter_of_xcontrollers.ml. *)
(****************************************************************************)
type lint_env = {
ctx: Provider_context.t;
(* The file we are currently in *)
cfile: Relative_path.t;
(* The class we are currently in *)
cclass: class_ option;
(* The method we are currently in *)
cmethod: method_ option;
(* The function we are currently in *)
cfun: fun_def option;
}
let default_env ctx cfile =
{ ctx; cfile; cclass = None; cmethod = None; cfun = None }
class body_visitor =
object (this)
inherit [unit] Nast.Visitor_DEPRECATED.visitor
(* This allows lint rules to distinguish between the top-level block (which
* is the function / method body) and the inner if-else / loop blocks *)
method on_body = this#on_block
end
module type BodyVisitorModule = sig
(* each on_* method in the visitor should call its counterpart in the parent
* visitor, so that all linters can be run in one single pass *)
class visitor : lint_env -> body_visitor
end
(* A mapping of lint rule visitors to functions and methods, using the
* position of the function / method as the map key. the various
* file_visiters will add to this mapping. Once that's done,
* body_visitor_invoker is used for running all the lint rules, and it will
* do so in one pass over the named AST. *)
let (body_visitors : (Pos.t, (module BodyVisitorModule)) Hashtbl.t) =
Hashtbl.create 0
let reset () = Hashtbl.reset body_visitors
module type BodyVisitorFunctor = functor (_ : BodyVisitorModule) ->
BodyVisitorModule
module GenericBodyVisitor : BodyVisitorModule = struct
class visitor _env : body_visitor =
object
inherit body_visitor
end
end
let add_visitor (p, _) v =
let module VisitorFunctor = (val v : BodyVisitorFunctor) in
match Hashtbl.find_opt body_visitors p with
| None ->
let module M = VisitorFunctor (GenericBodyVisitor) in
Hashtbl.add body_visitors p (module M : BodyVisitorModule)
| Some v' ->
let module M' = (val v') in
let module M = VisitorFunctor (M') in
Hashtbl.replace body_visitors p (module M : BodyVisitorModule)
class virtual ['a] abstract_file_visitor :
object
method on_file :
'a -> Provider_context.t -> Relative_path.t -> Parser_return.t -> 'a
method on_class : 'a -> lint_env -> Nast.class_ -> 'a
method on_fun_def : 'a -> lint_env -> Nast.fun_def -> 'a
method on_method : 'a -> lint_env -> Nast.class_ -> Nast.method_ -> 'a
end =
object (this)
method on_file context ctx fn pr =
let ast = pr.Parser_return.ast in
let env = default_env ctx fn in
List.fold_left ast ~init:context ~f:(fun context def ->
match def with
| Fun f ->
let f = Errors.ignore_ (fun () -> Naming.fun_def ctx f) in
this#on_fun_def context env f
| Class c ->
let c = Errors.ignore_ (fun () -> Naming.class_ ctx c) in
this#on_class context env c
| _ -> context)
method on_class context env class_ =
let on_method context meth = this#on_method context env class_ meth in
List.fold_left class_.c_methods ~init:context ~f:on_method
method on_fun_def context _env _fun = context
method on_method context _env _class _method = context
end
class type ['a] file_visitor =
object
method on_file :
'a -> Provider_context.t -> Relative_path.t -> Parser_return.t -> 'a
method on_class : 'a -> lint_env -> Nast.class_ -> 'a
method on_fun_def : 'a -> lint_env -> Nast.fun_def -> 'a
method on_method : 'a -> lint_env -> Nast.class_ -> Nast.method_ -> 'a
end
class body_visitor_adder body_visitor =
object
inherit [unit] abstract_file_visitor
method! on_fun_def () _env fd = add_visitor fd.fd_name body_visitor
method! on_method () _env _class meth = add_visitor meth.m_name body_visitor
end
let body_visitor_invoker =
object
inherit [unit] abstract_file_visitor
method! on_fun_def () env fd =
let fun_ = fd.fd_fun in
let module Visitor = (val Hashtbl.find body_visitors (fst fd.fd_name)) in
let nb = fun_.f_body in
let env = { env with cfun = Some fd } in
(new Visitor.visitor env)#on_body () nb.fb_ast
method! on_method () env class_ meth =
let module Visitor = (val Hashtbl.find body_visitors (fst meth.m_name)) in
let nb = meth.m_body in
let env = { env with cclass = Some class_; cmethod = Some meth } in
(new Visitor.visitor env)#on_body () nb.fb_ast
end
(****************************************************************************)
(* Convenience functions *)
(****************************************************************************)
let lint_all_bodies m = (new body_visitor_adder m)#on_file () |
OCaml Interface | hhvm/hphp/hack/src/lints/linting_visitors.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 lint_env = {
ctx: Provider_context.t;
(* The file we are currently in *)
cfile: Relative_path.t;
(* The class we are currently in *)
cclass: Nast.class_ option;
(* The method we are currently in *)
cmethod: Nast.method_ option;
(* The function we are currently in *)
cfun: Nast.fun_def option;
}
class type body_visitor =
object
inherit [unit] Nast.Visitor_DEPRECATED.visitor
(* This allows lint rules to distinguish between the top-level block (which
* is the function / method body) and the inner if-else / loop blocks *)
method on_body : unit -> Nast.block -> unit
end
module type BodyVisitorModule = sig
(* each on_* method in the visitor should call its counterpart in the parent
* visitor, so that all linters can be run in one single pass *)
class visitor : lint_env -> body_visitor
end
module type BodyVisitorFunctor = functor (_ : BodyVisitorModule) ->
BodyVisitorModule
class type ['a] file_visitor =
object
method on_file :
'a -> Provider_context.t -> Relative_path.t -> Parser_return.t -> 'a
method on_class : 'a -> lint_env -> Nast.class_ -> 'a
method on_fun_def : 'a -> lint_env -> Nast.fun_def -> 'a
method on_method : 'a -> lint_env -> Nast.class_ -> Nast.method_ -> 'a
end
class virtual ['a] abstract_file_visitor :
object
method on_file :
'a -> Provider_context.t -> Relative_path.t -> Parser_return.t -> 'a
method on_class : 'a -> lint_env -> Nast.class_ -> 'a
method on_fun_def : 'a -> lint_env -> Nast.fun_def -> 'a
method on_method : 'a -> lint_env -> Nast.class_ -> Nast.method_ -> 'a
end
class body_visitor_adder : (module BodyVisitorFunctor) -> [unit] file_visitor
(* Call this before any using add_visitor *)
val reset : unit -> unit
val add_visitor : Aast.sid -> (module BodyVisitorFunctor) -> unit
val body_visitor_invoker : unit file_visitor
val lint_all_bodies :
(module BodyVisitorFunctor) ->
Provider_context.t ->
Relative_path.t ->
Parser_return.t ->
unit |
OCaml | hhvm/hphp/hack/src/lints/lints_codes.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module Codes = struct
(* 5501 - 5541 reserved for FB. *)
let deprecated = 5542
(* 5543 - 5548 reserved. *)
let include_use = 5549
(* 5550 - 5561 reserved. *)
let clone_use = 5562
(* 5563 - 5567 reserved. *)
let loop_variable_shadows_local_variable = 5568
(* 5569 - 5574 reserved. *)
let duplicate_key = 5575
(* 5576 - 5580 reserved. *)
let if_literal = 5581
(* 5582 reserved. *)
let await_in_loop = 5583
(* 5584 - 5607 reserved. *)
let non_equatable_comparison = 5607
let invalid_contains_check = 5608
let is_always_true = 5609
let is_always_false = 5610
(* let deprecated_invalid_null_check = 5611 *)
let invalid_switch_case_value_type = 5614
(* 5615 reserved. *)
let missing_override_attribute = 5616
let sketchy_null_check = 5618
let invalid_truthiness_test = 5622
let sketchy_truthiness_test = 5623
let redundant_generic = 5624
(* let deprecated_pocket_universes_reserved_syntax = 5625 *)
(* let deprecated_as_invalid_type = 5626 *)
let class_overrides_all_trait_methods = 5627
let as_always_succeeds = 5628
let as_always_fails = 5629
(* let deprecated_redundant_nonnull_assertion = 5630 *)
let bool_method_return_hint = 5631
(* let deprecated_missing_via_label_attribute = 5632 *)
let nullsafe_not_needed = 5633
let duplicate_property_enum_init = 5634
let duplicate_property = 5635
let loose_unsafe_cast_lower_bound = 5636
let loose_unsafe_cast_upper_bound = 5637
let invalid_disjointness_check = 5638
let inferred_variance = 5639 (* DEPRECATED *)
let switch_nonexhaustive = 5640
let bad_xhp_enum_attribute_value = 5641
let unreachable_method_in_trait = 5642
let comparing_booleans = 5643
let pointless_booleans_expression = 5644
let unconditional_recursion = 5645
let branch_return_same_value = 5646
let redundant_unsafe_cast = 5647
let redundant_cast = 5648
let internal_classname = 5649
let async_lambda = 5650
let awaitable_awaitable = 5651
let cast_non_primitive = 5652
end |
OCaml | hhvm/hphp/hack/src/lints/lints_core.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
(** These severity levels are based on those provided by Arcanist. "Advice"
* means notify the user of the lint without requiring confirmation if the lint
* is benign; "Warning" will raise a confirmation prompt if the lint applies to
* a line that was changed in the given diff; and "Error" will always raise a
* confirmation prompt, regardless of where the lint occurs in the file. *)
type severity =
| Lint_error
| Lint_warning
| Lint_advice
[@@deriving show]
let string_of_severity = function
| Lint_error -> "error"
| Lint_warning -> "warning"
| Lint_advice -> "advice"
type 'pos t = {
code: int;
severity: severity;
pos: 'pos; [@opaque]
message: string;
bypass_changed_lines: bool;
(** Normally, lint warnings and lint advice only get shown by arcanist if the
* lines they are raised on overlap with lines changed in a diff. This
* flag bypasses that behavior *)
autofix: (string * Pos.t) option;
check_status: Tast.check_status option;
}
[@@deriving show]
let (lint_list : Pos.t t list option ref) = ref None
let get_code { code; _ } = code
let get_pos { pos; _ } = pos
let add
?(check_status = None)
?(bypass_changed_lines = false)
?(autofix = None)
code
severity
pos
message =
match !lint_list with
| Some lst ->
let lint =
{
code;
severity;
pos;
message;
bypass_changed_lines;
autofix;
check_status;
}
in
lint_list := Some (lint :: lst)
(* by default, we ignore lint errors *)
| None -> ()
let add_lint lint =
add
~bypass_changed_lines:lint.bypass_changed_lines
~autofix:lint.autofix
lint.code
lint.severity
lint.pos
lint.message
let to_absolute ({ pos; _ } as lint) = { lint with pos = Pos.to_absolute pos }
let to_string lint =
let code = User_error.error_code_to_string lint.code in
Printf.sprintf "%s\n%s (%s)" (Pos.string lint.pos) lint.message code
let to_contextual_string lint =
let claim_color =
match lint.severity with
| Lint_error -> Tty.Red
| Lint_warning -> Tty.Yellow
| Lint_advice -> Tty.Default
in
User_error.make_absolute lint.code [(lint.pos, lint.message)]
|> Contextual_error_formatter.to_string ~claim_color
let to_highlighted_string (lint : string Pos.pos t) =
User_error.make_absolute lint.code [(lint.pos, lint.message)]
|> Highlighted_error_formatter.to_string
let to_json { pos; code; severity; message; bypass_changed_lines; autofix; _ } =
let (line, scol, ecol) = Pos.info_pos pos in
let (origin, replacement, start, w) =
match autofix with
| Some (replacement, replacement_pos) ->
let path = Pos.filename (Pos.to_absolute replacement_pos) in
let lines = Errors.read_lines path in
let src = String.concat ~sep:"\n" lines in
let original = Pos.get_text_from_pos ~content:src replacement_pos in
let (start_offset, end_offset) = Pos.info_raw replacement_pos in
let width = end_offset - start_offset in
( Hh_json.JSON_String original,
Hh_json.JSON_String replacement,
Hh_json.int_ start_offset,
Hh_json.int_ width )
| None ->
( Hh_json.JSON_String "",
Hh_json.JSON_String "",
Hh_json.JSON_Null,
Hh_json.JSON_Null )
in
Hh_json.JSON_Object
[
("descr", Hh_json.JSON_String message);
("severity", Hh_json.JSON_String (string_of_severity severity));
("path", Hh_json.JSON_String (Pos.filename pos));
("line", Hh_json.int_ line);
("start", Hh_json.int_ scol);
("end", Hh_json.int_ ecol);
("code", Hh_json.int_ code);
("bypass_changed_lines", Hh_json.JSON_Bool bypass_changed_lines);
("original", origin);
("replacement", replacement);
("start_offset", start);
("width", w);
]
(* If the check_status field is available in a lint, we expect that the
lint is a true positive only if the same lint was produced under both
dynamic and normal assumptions. This helper function filters out the
remaining ones. *)
let filter_out_unsound_lints lints =
let module LintMap = WrappedMap.Make (struct
type t = int * Pos.t [@@deriving ord]
end) in
let module CheckStatusParity = struct
type t = {
under_normal_assumptions: bool;
under_dynamic_assumptions: bool;
}
let default =
{ under_normal_assumptions = false; under_dynamic_assumptions = false }
let set_normal parity_opt =
let set parity = Some { parity with under_normal_assumptions = true } in
Option.value parity_opt ~default |> set
let set_dynamic parity_opt =
let set parity = Some { parity with under_dynamic_assumptions = true } in
Option.value parity_opt ~default |> set
let is_paired parity =
parity.under_dynamic_assumptions && parity.under_normal_assumptions
end in
let lint_parity =
List.fold
~f:(fun m lint ->
let update = LintMap.update (lint.code, lint.pos) in
match lint.check_status with
| Some Tast.CUnderNormalAssumptions ->
update CheckStatusParity.set_normal m
| Some Tast.CUnderDynamicAssumptions ->
update CheckStatusParity.set_dynamic m
| _ -> m)
~init:LintMap.empty
lints
in
let should_keep_lint = function
| { check_status = Some Tast.CUnderDynamicAssumptions; _ } ->
(* There are three cases to consider:
1. we are in any unsound lint rule: this cannot be the case as
`check_status` is set to non-None.
2. we are in a sound lint rule where the lint is only produced under
dynamic assumptions: the result is not reliable, so it should be
eliminated.
3. we are in a sound lint rule where the lint is produced under both
dynamic and normal assumptions: the lint is reliable, but it is
duplicated, so we arbitrarily eliminate the one produced under
dynamic assumptions and keep the one under normal assumptions. *)
false
| { code; pos; _ } -> begin
match LintMap.find_opt (code, pos) lint_parity with
| Some parity -> CheckStatusParity.is_paired parity
| None ->
(* Either it was checked once and no parity is needed or is a lint that
doesn't use sound linting. *)
true
end
in
List.filter ~f:should_keep_lint lints
let do_ f =
let list_copy = !lint_list in
lint_list := Some [];
let result = f () in
let out =
match !lint_list with
| Some lst -> lst
| None -> assert false
in
let out = filter_out_unsound_lints out in
lint_list := list_copy;
(List.rev out, result) |
OCaml Interface | hhvm/hphp/hack/src/lints/lints_core.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 severity =
| Lint_error
| Lint_warning
| Lint_advice
type 'pos t = {
code: int;
severity: severity;
pos: 'pos; [@opaque]
message: string;
bypass_changed_lines: bool;
autofix: (string * Pos.t) option;
check_status: Tast.check_status option;
}
[@@deriving show]
val get_code : 'pos t -> int
val get_pos : 'pos t -> 'pos
val add :
?check_status:Tast.check_status option ->
?bypass_changed_lines:bool ->
?autofix:(string * Pos.t) option ->
int ->
severity ->
Pos.t ->
string ->
unit
val add_lint : Pos.t t -> unit
val to_absolute : Pos.t t -> Pos.absolute t
val to_string : Pos.absolute t -> string
val to_contextual_string : Pos.absolute t -> string
val to_highlighted_string : Pos.absolute t -> string
val to_json : Pos.absolute t -> Hh_json.json
val do_ : (unit -> 'a) -> Pos.t t list * 'a |
OCaml | hhvm/hphp/hack/src/lints/lints_errors.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module Codes = Lints_codes.Codes
open Lints_core
module Lints = Lints_core
let quickfix ~can_be_captured ~original_pos ~replacement_pos =
let path = Pos.filename (Pos.to_absolute original_pos) in
let lines = Errors.read_lines path in
let content = String.concat ~sep:"\n" lines in
let modified = Pos.get_text_from_pos ~content replacement_pos in
let modified =
if can_be_captured then
"(" ^ modified ^ ")"
else
modified
in
(modified, original_pos)
let clone_use p =
Lints.add
Codes.clone_use
Lint_advice
p
("Objects created with `clone` will have references to shared "
^ "deep objects. Prefer to implement your own explicit copy "
^ "method to ensure the semantics you want. See "
^ "http://php.net/manual/en/language.oop5.cloning.php")
let deprecated p msg = Lints.add Codes.deprecated Lint_warning p msg
let include_use p msg = Lints.add Codes.include_use Lint_error p msg
let if_literal p msg = Lints.add Codes.if_literal Lint_warning p msg
let await_in_loop p =
Lints.add
Codes.await_in_loop
Lint_warning
p
("Do not use `await` in a loop. It almost always incurs "
^ "non-obvious serial fetching that is easy to miss. "
^ "See https://fburl.com/awaitinloop for more information.")
let loop_variable_shadows_local_variable p1 id p2 =
Lints.add
Codes.loop_variable_shadows_local_variable
Lint_warning
p1
(Printf.sprintf
"Loop variable %s shadows a local variable defined or last assigned here:\n%s"
(Local_id.get_name id |> Markdown_lite.md_codify)
(Pos.string (Pos.to_relative_string p2)))
let bad_virtualized_method p =
Lints.add
Codes.bool_method_return_hint
Lint_warning
p
"`__bool` methods should return `bool`. They show that an expression tree type can be used in a boolean expression."
let non_equatable_comparison p ret ty1 ty2 =
Lints.add Codes.non_equatable_comparison Lint_warning p
@@ Printf.sprintf
"Invalid comparison: This expression will always return %s.\nA value of type %s can never be equal to a value of type %s"
(string_of_bool ret |> Markdown_lite.md_codify)
(Markdown_lite.md_codify ty1)
(Markdown_lite.md_codify ty2)
let invalid_contains_check p trv_val_ty val_ty =
Lints.add Codes.invalid_contains_check Lint_warning p
@@ Printf.sprintf
"Invalid `C\\contains` check: This call will always return `false`.\nA `Traversable<%s>` cannot contain a value of type %s"
trv_val_ty
(Markdown_lite.md_codify val_ty)
let invalid_contains_key_check p trv_key_ty key_ty =
Lints.add Codes.invalid_contains_check Lint_warning p
@@ Printf.sprintf
"Invalid `C\\contains_key` check: This call will always return `false`.\nA `KeyedTraversable<%s, ...>` cannot contain a key of type %s"
trv_key_ty
(Markdown_lite.md_codify key_ty)
let is_always_true ~check_status p lhs_ty rhs_ty =
let lhs_ty = Markdown_lite.md_codify lhs_ty in
let rhs_ty = Markdown_lite.md_codify rhs_ty in
Lints.add
Codes.is_always_true
~check_status:(Some check_status)
Lint_warning
p
(Printf.sprintf
"This `is` check is always `true`. The expression on the left has type %s which is a subtype of %s."
lhs_ty
rhs_ty)
let is_always_false ~check_status p lhs_ty rhs_ty =
let lhs_ty = Markdown_lite.md_codify lhs_ty in
let rhs_ty = Markdown_lite.md_codify rhs_ty in
Lints.add
Codes.is_always_false
~check_status:(Some check_status)
Lint_warning
p
(Printf.sprintf
"This `is` check is always `false`. The expression on the left has type %s which shares no values with %s."
lhs_ty
rhs_ty)
let as_always_succeeds
~check_status ~can_be_captured ~as_pos ~child_expr_pos lhs_ty rhs_ty =
let lhs_ty = Markdown_lite.md_codify lhs_ty in
let rhs_ty = Markdown_lite.md_codify rhs_ty in
let autofix =
Some
(quickfix
~can_be_captured
~original_pos:as_pos
~replacement_pos:child_expr_pos)
in
Lints.add
~autofix
~check_status:(Some check_status)
Codes.as_always_succeeds
Lint_warning
as_pos
(Printf.sprintf
"This `as` assertion will always succeed and hence is redundant. The expression on the left has a type %s which is a subtype of %s."
lhs_ty
rhs_ty)
let as_always_fails ~check_status p lhs_ty rhs_ty =
let lhs_ty = Markdown_lite.md_codify lhs_ty in
let rhs_ty = Markdown_lite.md_codify rhs_ty in
Lints.add
Codes.as_always_fails
~check_status:(Some check_status)
Lint_warning
p
(Printf.sprintf
"This `as` assertion will always fail and lead to an exception at runtime. The expression on the left has type %s which shares no values with %s."
lhs_ty
rhs_ty)
let class_overrides_all_trait_methods pos class_name trait_name =
Lints.add
Codes.class_overrides_all_trait_methods
Lint_warning
pos
(Printf.sprintf
"Unused trait: %s is overriding all the methods in %s"
(Utils.strip_ns class_name |> Markdown_lite.md_codify)
(Utils.strip_ns trait_name |> Markdown_lite.md_codify))
let trait_requires_class_that_overrides_method
pos class_name trait_name method_name =
Lints.add
Codes.unreachable_method_in_trait
Lint_warning
pos
(Printf.sprintf
"Method %s in trait %s is overriden in class %s and trait %s has `require class %s`. This method is never used."
(Utils.strip_ns method_name |> Markdown_lite.md_codify)
(Utils.strip_ns trait_name |> Markdown_lite.md_codify)
(Utils.strip_ns class_name |> Markdown_lite.md_codify)
(Utils.strip_ns trait_name |> Markdown_lite.md_codify)
(Utils.strip_ns class_name |> Markdown_lite.md_codify))
let invalid_disjointness_check p name ty1 ty2 =
Lints.add Codes.invalid_disjointness_check Lint_warning p
@@ Printf.sprintf
"This call to '%s' will always return the same value, because type %s is disjoint from type %s."
name
ty1
ty2
let invalid_switch_case_value_type
(case_value_p : Ast_defs.pos) case_value_ty scrutinee_ty =
Lints.add Codes.invalid_switch_case_value_type Lint_warning case_value_p
@@ Printf.sprintf
"Switch statements use `===` equality. Comparing values of type %s with %s may not give the desired result."
(Markdown_lite.md_codify @@ Lazy.force case_value_ty)
(Markdown_lite.md_codify @@ Lazy.force scrutinee_ty)
let missing_override_attribute
~meth_pos ~first_attr_pos ~name_pos ~class_name ~method_name =
let msg =
Printf.sprintf
"Method %s is also defined on %s, but this method is missing `<<__Override>>`."
(Markdown_lite.md_codify method_name)
(Utils.strip_ns class_name |> Markdown_lite.md_codify)
in
let autofix =
match first_attr_pos with
| Some first_attr_pos ->
(* The method already has <<Foo, Bar>> attributes, add __Override. *)
let fix_pos = Pos.shrink_to_start first_attr_pos in
Some ("__Override, ", fix_pos)
| None ->
(* The method has no attributes. *)
let fix_pos = Pos.shrink_to_start meth_pos in
Some ("<<__Override>>\n ", fix_pos)
in
Lints.add ~autofix Codes.missing_override_attribute Lint_error name_pos @@ msg
let sketchy_null_check pos name kind =
let name = Option.value name ~default:"$x" in
Lints.add Codes.sketchy_null_check Lint_warning pos
@@ "This is a sketchy null check.\nIt detects nulls, but it will also detect many other falsy values, including `false`, `0`, `0.0`, `\"\"`, `\"0\"`, empty Containers, and more.\nIf you want to test for them, please consider doing so explicitly.\nIf you only meant to test for `null`, "
^
match kind with
| `Coalesce ->
Printf.sprintf "use `%s ?? $default` instead of `%s ?: $default`" name name
| `Eq -> Printf.sprintf "use `%s is null` instead" name
| `Neq -> Printf.sprintf "use `%s is nonnull` instead" name
let invalid_truthiness_test pos ty =
Lints.add Codes.invalid_truthiness_test Lint_warning pos
@@ Printf.sprintf
"Invalid condition: a value of type %s will always be truthy"
(Markdown_lite.md_codify ty)
let invalid_truthiness_test_falsy pos ty =
Lints.add Codes.invalid_truthiness_test Lint_warning pos
@@ Printf.sprintf
"Invalid condition: a value of type %s will always be falsy"
(Markdown_lite.md_codify ty)
let sketchy_truthiness_test pos ty truthiness =
Lints.add Codes.sketchy_truthiness_test Lint_warning pos
@@
match truthiness with
| `String ->
Printf.sprintf
"Sketchy condition: testing the truthiness of %s may not behave as expected.\nThe values `\"\"` and `\"0\"` are both considered falsy. To check for emptiness, use `Str\\is_empty`."
ty
| `Arraykey ->
Printf.sprintf
"Sketchy condition: testing the truthiness of %s may not behave as expected.\nThe values `0`, `\"\"`, and `\"0\"` are all considered falsy. Test for them explicitly."
ty
| `Stringish ->
Printf.sprintf
"Sketchy condition: testing the truthiness of a %s may not behave as expected.\nThe values `\"\"` and `\"0\"` are both considered falsy, but objects will be truthy even if their `__toString` returns `\"\"` or `\"0\"`.\nTo check for emptiness, convert to a string and use `Str\\is_empty`."
ty
| `XHPChild ->
Printf.sprintf
"Sketchy condition: testing the truthiness of an %s may not behave as expected.\nThe values `\"\"` and `\"0\"` are both considered falsy, but objects (including XHP elements) will be truthy even if their `__toString` returns `\"\"` or `\"0\"`."
ty
| `Traversable ->
(* We have a truthiness test on a value with an interface type which is a
subtype of Traversable, but not a subtype of Container.
Since the runtime value may be a falsy-when-empty Container or an
always-truthy Iterable/Generator, we forbid the test. *)
Printf.sprintf
"Sketchy condition: a value of type %s may be truthy even when empty.\nHack collections and arrays are falsy when empty, but user-defined Traversables will always be truthy, even when empty.\nIf you would like to only allow containers which are falsy when empty, use the `Container` or `KeyedContainer` interfaces."
ty
let redundant_covariant pos name msg suggest =
Lints.add Codes.redundant_generic Lint_warning pos
@@ "The generic parameter "
^ Markdown_lite.md_codify name
^ " is redundant because it only appears in a covariant (output) position"
^ msg
^ ". Consider replacing uses of generic parameter with "
^ Markdown_lite.md_codify suggest
^ " or specifying `<<__Explicit>>` on the generic parameter"
let redundant_contravariant pos name msg suggest =
Lints.add Codes.redundant_generic Lint_warning pos
@@ "The generic parameter "
^ Markdown_lite.md_codify name
^ " is redundant because it only appears in a contravariant (input) position"
^ msg
^ ". Consider replacing uses of generic parameter with "
^ Markdown_lite.md_codify suggest
^ " or specifying `<<__Explicit>>` on the generic parameter"
let redundant_generic pos name =
Lints.add Codes.redundant_generic Lint_warning pos
@@ Printf.sprintf
"The generic parameter %s is unused."
(Markdown_lite.md_codify name)
let inferred_variance pos name description syntax =
Lints.add Codes.inferred_variance Lint_advice pos
@@ "The generic parameter "
^ Markdown_lite.md_codify name
^ " could be marked "
^ description
^ ". Consider prefixing it with "
^ syntax
let nullsafe_not_needed pos =
Lints.add Codes.nullsafe_not_needed Lint_advice pos
@@ "You are using the "
^ Markdown_lite.md_codify "?->"
^ " operator but this object cannot be null."
^ " You can use the "
^ Markdown_lite.md_codify "->"
^ " operator instead."
let invalid_attribute_value
pos (attr_name : string) (valid_values : string list) =
let valid_values = List.map valid_values ~f:Markdown_lite.md_codify in
Lints.add
Codes.bad_xhp_enum_attribute_value
Lint_error
pos
(Printf.sprintf
"Invalid value for %s, expected one of %s."
(Markdown_lite.md_codify attr_name)
(String.concat ~sep:", " valid_values))
let parse_error code pos msg = Lints.add code Lint_error pos msg
let rec prettify_class_list names =
match names with
| [] -> ""
| [c] -> c
| [c1; c2] -> c1 ^ " and " ^ c2
| h :: t -> h ^ ", " ^ prettify_class_list t
let duplicate_property_class_constant_init
pos ~class_name ~prop_name ~class_names =
Lints.add
Codes.duplicate_property_enum_init
Lint_error
pos
("Property "
^ (Utils.strip_ns prop_name |> Markdown_lite.md_codify)
^ ", defined in "
^ prettify_class_list (List.map ~f:Utils.strip_ns class_names)
^ ", is inherited multiple times by class "
^ (Utils.strip_ns class_name |> Markdown_lite.md_codify)
^ " and one of its instances is initialised with a class or enum constant")
let duplicate_property pos ~class_name ~prop_name ~class_names =
Lints.add
Codes.duplicate_property
Lint_warning
pos
("Duplicated property "
^ (Utils.strip_ns prop_name |> Markdown_lite.md_codify)
^ " in "
^ (Utils.strip_ns class_name |> Markdown_lite.md_codify)
^ " (defined in "
^ prettify_class_list
(List.map
~f:(fun n -> Utils.strip_ns n |> Markdown_lite.md_codify)
class_names)
^ "): all instances will be aliased at runtime")
let redundant_cast_common
~can_be_captured
?(check_status = None)
cast_type
cast
cast_pos
expr_pos
code
severity =
let msg =
"This use of `"
^ cast
^ "` is redundant since the type of the expression is a subtype of the type being cast to."
^ " Please consider removing this cast."
in
let msg =
match cast_type with
| `UNSAFE_CAST -> msg
| `CAST ->
msg
^ " This cast is runtime significant and types might occasionally lie."
^ " Please be prudent when acting on this lint."
in
let autofix =
Some
(quickfix
~can_be_captured
~original_pos:cast_pos
~replacement_pos:expr_pos)
in
Lints.add ~check_status ~autofix code severity cast_pos msg
let redundant_unsafe_cast ~can_be_captured hole_pos expr_pos =
let cast = "HH\\FIXME\\UNSAFE_CAST" in
let code = Codes.redundant_unsafe_cast in
redundant_cast_common
~can_be_captured
`UNSAFE_CAST
cast
hole_pos
expr_pos
code
Lint_error
let redundant_cast ~can_be_captured ~check_status cast cast_pos expr_pos =
let code = Codes.redundant_cast in
redundant_cast_common
~check_status:(Some check_status)
~can_be_captured
`CAST
cast
cast_pos
expr_pos
code
Lint_advice
let loose_unsafe_cast_lower_bound p ty_str_opt =
let msg =
"The input type to `HH\\FIXME\\UNSAFE_CAST` should be as specific as possible."
in
let (msg, autofix) =
match ty_str_opt with
| Some ty_str ->
( msg ^ " Consider using " ^ Markdown_lite.md_codify ty_str ^ " instead.",
Some (ty_str, p) )
| None -> (msg, None)
in
Lints.add ~autofix Codes.loose_unsafe_cast_lower_bound Lint_error p msg
let loose_unsafe_cast_upper_bound p =
Lints.add
Codes.loose_unsafe_cast_upper_bound
Lint_error
p
"HH\\FIXME\\UNSAFE_CAST output type annotation is too loose, please use a more specific type."
let switch_nonexhaustive p =
Lints.add
Codes.switch_nonexhaustive
Lint_warning
p
("This switch statement is not exhaustive."
^ " The expression it scrutinises has a type with infinitely many values and the statement does not have a default case."
^ " If none of the cases match, an exception will be thrown."
^ " Consider adding a default case.")
let calling_pointless_boolean p_lint p_quickfix txt =
Lints.add
~autofix:(Some ("", p_quickfix))
Codes.pointless_booleans_expression
Lint_warning
p_lint
txt
let comparing_booleans p_expr p_var name value =
let msg =
if value then
"Consider changing this statement to " ^ "(" ^ name ^ ") instead"
else
"Consider changing this statement to " ^ "(!" ^ name ^ ") instead"
in
let path = Pos.filename (Pos.to_absolute p_var) in
let lines = Errors.read_lines path in
let src = String.concat ~sep:"\n" lines in
let replacement =
if value then
Pos.get_text_from_pos ~content:src p_var
else
String.make 1 '!' ^ Pos.get_text_from_pos ~content:src p_var
in
Lints.add
~autofix:(Some (replacement, p_expr))
Codes.comparing_booleans
Lint_advice
p_expr
msg
let unconditional_recursion p =
Lints.add
Codes.unconditional_recursion
Lint_error
p
("This is a recursive function with no base case to terminate. This will result in a Stack Overflow error."
^ " Consider adding a base case.")
let branches_return_same_value p =
Lints.add
Codes.branch_return_same_value
Lint_warning
p
"There are multiple return statements, but they all return the same value."
let internal_classname p =
Lints.add
Codes.internal_classname
Lint_warning
p
("This is a classname of an `internal` class. Internal classnames are dangerous because they are effectively raw strings. "
^ "Please avoid them, or make sure that they are never used outside of the module."
)
let async_lambda pos =
Lints.add
Codes.async_lambda
Lint_advice
pos
"Use `async ... ==> await ...` for lambdas that directly return `Awaitable`s, so stack traces include the lambda position."
let awaitable_awaitable pos =
Lints.add
Codes.awaitable_awaitable
Lint_warning
pos
("This lambda returns an Awaitable of Awaitable."
^ " You probably want to use await inside this async lambda,"
^ " so stack traces include the lambda position."
^ " If this is intentional, please annotate the return type.")
let cast_non_primitive pos =
Lints.add
Codes.cast_non_primitive
Lint_error
pos
("Casting a non-primitive to a primitive rarely yields a "
^ "useful value. Did you mean to extract a value from this object "
^ "before casting it, or to do a null-check?") |
hhvm/hphp/hack/src/monitor/dune | (library
(name server_monitor)
(wrapped false)
(libraries
collections
connection_tracker
core_kernel
exec_command
libancillary
logging
marshal_tools
hh_server_monitor
messages
monitor_rpc
process
process_types
relative_path
server_args
server_command_types
server_files
socket
sys_utils
utils_config_file
watchman)
(preprocess
(pps lwt_ppx ppx_deriving.std))) |
|
OCaml | hhvm/hphp/hack/src/monitor/informant.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type report =
| Move_along (** Nothing to see here. *)
| Restart_server
(** Kill the server (if one is running) and start a new one. *)
[@@deriving show]
type server_state =
| Server_not_yet_started
| Server_alive
| Server_dead
[@@deriving show]
type options = {
root: Path.t;
allow_subscriptions: bool;
(** Disable the informant - use the dummy instead. *)
use_dummy: bool;
(** Don't trigger a server restart if the distance between two
revisions we are moving between is less than this. *)
min_distance_restart: int;
watchman_debug_logging: bool;
(** Informant should ignore the hh_version when doing version checks. *)
ignore_hh_version: bool;
(** Was the server initialized with a precomputed saved-state? *)
is_saved_state_precomputed: bool;
}
type init_env = options
(** We need to query mercurial to convert an hg revision into a numerical
* global revision. These queries need to be non-blocking, so we keep a cache
* of the mapping in here, as well as the Futures corresponding to
* th queries. *)
module Revision_map = struct
(*
* Running and finished queries. A query gets the global_rev for a
* given HG Revision.
*)
type t = {
global_rev_queries: (Hg.hg_rev, Hg.global_rev Future.t) Caml.Hashtbl.t;
}
let create () = { global_rev_queries = Caml.Hashtbl.create 200 }
let add_query ~hg_rev root t =
(* Don't add if we already have an entry for this. *)
if not (Caml.Hashtbl.mem t.global_rev_queries hg_rev) then
let future =
Hg.get_closest_global_ancestor hg_rev (Path.to_string root)
in
Caml.Hashtbl.add t.global_rev_queries hg_rev future
let find_global_rev hg_rev t =
let future = Caml.Hashtbl.find t.global_rev_queries hg_rev in
match Future.check_status future with
| Future.In_progress { age } when Float.(age > 60.0) ->
(* Fail if lookup up global rev number takes more than 60 s.
* Delete the query so we can retry again if we encounter this hg_rev
* again. Return fake "0" global rev number. *)
let () = Caml.Hashtbl.remove t.global_rev_queries hg_rev in
Some 0
| Future.In_progress _ -> None
| Future.Complete_with_result result ->
let result =
result
|> Result.map_error ~f:Future.error_to_string
|> Result.map_error
~f:(HackEventLogger.find_svn_rev_failed (Future.start_t future))
in
Some (result |> Result.ok |> Option.value ~default:0)
end
(**
* The Revision tracker tracks the latest known global revision of the repo,
* the corresponding global revisions of Hg revisions, and the sequence of
* revision changes (from hg update). See record type "env" below.
*
* This machinery is necessary because Watchman state change events give
* us only the HG Revisions of hg updates, but we need to make decisions
* on their global Revision numbers.
*
* We want to be able to:
* 1) Determine when the base global revision (in trunk) has changed
* "significantly" so we can inform the server monitor to trigger
* a server restart (since incremental typechecks can be slower
* than a fresh server using a saved state).
* 2) Fulfill goal 1 without blocking, and while being "highly responsive"
*
* The definition of "significant" can be adjusted according to how fast
* incremental type checking is compared to a fresh restart.
*
* The meaning of "highly responsive" above roughly means using a cache
* for global revisions (because a Mercurial request to get the global revision
* number of an HG Revision is very slow, on the order of seconds).
* Consider the following scenario:
*
* Server is running with Repo at Revision 100. User does hg update to
* Rev 500 (which triggers a server restart) and works on that for
* an hour. Then the user hg updates back to Rev 100.
*
* At this point, the server restart should be triggered because we
* are moving across hundreds of revisions. Without caching the Revision
* 100 result, the restart would be delayed by seconds. With a cache, the
* restart is triggered immediately.
*
* We use an SCM Aware Watchman subscription to follow when the merge base
* changes. We use State Enter and Leave events (which appear before the
* slower SCM Aware notification) to kick off asynchronous computation. In
* particular, we kick off prefetching of a saved state, and shelling out
* to mercurial for mapping the HG Revision to its corresponding global revision
* (since our "distance" measure uses global_revs which are
* monotonically increasing)..
*)
module Revision_tracker = struct
type timestamp = float
type repo_transition =
| State_enter of Hg.hg_rev
| State_leave of Hg.hg_rev
| Changed_merge_base of
Hg.hg_rev * (SSet.t[@printer SSet.pp_large]) * Watchman.clock
[@@deriving show]
let _ = show_repo_transition (* allow unused show *)
type init_settings = {
watchman: Watchman.watchman_instance ref;
root: Path.t;
min_distance_restart: int;
is_saved_state_precomputed: bool;
}
type env = {
inits: init_settings;
(* The 'current' base revision (from the tracker's perspective of the
* repo. This is used to make calculations on distance. This is changed
* when a State_leave is handled. *)
current_base_revision: int ref;
is_in_hg_update_state: bool ref;
is_in_hg_transaction_state: bool ref;
rev_map: Revision_map.t;
(*
* Timestamp and HG revision of state change events.
*
* Why do we keep the entire sequence? It seems like it would be sufficient
* to just consume from the Watchman subscription one-at-a-time,
* processing at most one state change at a time. But consider the case
* of many sequential hg updates, the last of which is very distant
* (i.e. significant), and we happen to have a cached value only for
* the last hg update.
*
* If we processed one-at-a-time as the updates came in, it would be many
* seconds of processing each hg query before deciding at the final one
* to restart the server (so the server restart is delayed by many
* seconds).
*
* By keeping a running queue of state changes and "preprocessing" new
* changes from the watchman subscription (before appending them to this
* queue), we can catch that final hg update early on and proactively
* trigger a server restart.
*)
state_changes: (repo_transition * timestamp) Queue.t;
}
type instance =
| Initializing of init_settings * Hg.global_rev Future.t
| Reinitializing of env * Hg.global_rev Future.t
| Tracking of env
(* Revision_tracker has lots of mutable state anyway, so might as well
* make it responsible for maintaining its own instance. *)
type t = instance ref
let is_hg_updating env =
!(env.is_in_hg_update_state) || !(env.is_in_hg_transaction_state)
let init ~min_distance_restart ~is_saved_state_precomputed watchman root =
let init_settings =
{
watchman = ref watchman;
root;
min_distance_restart;
is_saved_state_precomputed;
}
in
ref
@@ Initializing
(init_settings, Hg.current_working_copy_base_rev (Path.to_string root))
let set_base_revision global_rev env =
if global_rev = !(env.current_base_revision) then
()
else
let () =
Hh_logger.log "Revision_tracker setting base rev: %d" global_rev
in
env.current_base_revision := global_rev
let active_env init_settings base_global_rev =
{
inits = init_settings;
current_base_revision = ref base_global_rev;
rev_map = Revision_map.create ();
state_changes = Queue.create ();
is_in_hg_update_state = ref false;
is_in_hg_transaction_state = ref false;
}
let reinitialized_env env base_global_rev =
{
env with
current_base_revision = ref base_global_rev;
state_changes = Queue.create ();
}
let get_jump_distance global_rev env =
abs @@ (global_rev - !(env.current_base_revision))
let is_significant ~min_distance_restart ~jump_distance elapsed_t =
let () =
Hh_logger.log
"Informant: jump distance %d. elapsed_t: %2f"
jump_distance
elapsed_t
in
(* Allow up to 2 revisions per second for incremental. More than that,
* prefer a server restart. *)
let result =
jump_distance > min_distance_restart
&& Float.(
elapsed_t <= 0.0 || float_of_int jump_distance /. elapsed_t > 2.0)
in
result
(** Form a decision about whether or not we'd like to start a new server.
* transition: The state transition for which we are forming a decision
* global_rev: The corresponding global rev for this transition's hg rev.
*)
let form_decision ~significant transition server_state env =
match (significant, transition, server_state) with
| (_, State_leave _, Server_not_yet_started) ->
(* This is reachable when server stopped in the middle of rebase. Instead
* of restarting immediately, we go back to Server_not_yet_started, and want
* to restart only when hg.update state is vacated *)
Restart_server
| (_, State_leave _, Server_dead) ->
(* Regardless of whether we had a significant change or not, when the
* server is not alive, we restart it on a state leave.*)
Restart_server
| (false, _, _) ->
let () = Hh_logger.log "Informant insignificant transition" in
Move_along
| (true, State_enter _, _)
| (true, State_leave _, _) ->
(* We use the State enter and leave events to kick off asynchronous
* computations off the hg revisions when they arrive (during preprocess)
* But actual actions are taken only on changed_merge_base below. *)
Move_along
| (true, Changed_merge_base _, _) ->
(* If the current server was started using a precomputed saved-state,
* we don't want to relaunch the server. If we do, it'll reuse
* the previously used saved-state for the new mergebase and more
* importantly the **same list of changed files!!!** which is
* totally wrong *)
if env.inits.is_saved_state_precomputed then begin
Hh_logger.log
"Server was started using a precomputed saved-state, not restarting.";
Move_along
end else
Restart_server
(**
* If we have a cached global_rev for this hg_rev, make a decision on
* this transition and returns that decision. If not, returns None.
*
* Nonblocking.
*)
let make_decision timestamp transition server_state env =
let hg_rev =
match transition with
| State_enter hg_rev
| State_leave hg_rev
| Changed_merge_base (hg_rev, _, _) ->
hg_rev
in
match Revision_map.find_global_rev hg_rev env.rev_map with
| None -> None
| Some global_rev ->
let jump_distance = get_jump_distance global_rev env in
let elapsed_t = Unix.time () -. timestamp in
let significant =
is_significant
~min_distance_restart:env.inits.min_distance_restart
~jump_distance
elapsed_t
in
Some (form_decision ~significant transition server_state env, global_rev)
(**
* Keep popping state_changes queue until we reach a non-ready result.
*
* Returns a list of the decisions from processing each ready change
* in the queue; the list is ordered most-recent to oldest.
*
* Non-blocking.
*)
let rec churn_ready_changes ~acc env server_state =
let maybe_set_base_rev transition global_rev env =
match transition with
| State_enter _
| State_leave _ ->
()
| Changed_merge_base _ -> set_base_revision global_rev env
in
if Queue.is_empty env.state_changes then
acc
else
let (transition, timestamp) = Queue.peek_exn env.state_changes in
match make_decision timestamp transition server_state env with
| None -> acc
| Some (decision, global_rev) ->
(* We already peeked the value above. Can ignore here. *)
let _ = Queue.dequeue_exn env.state_changes in
(* Maybe setting the base revision must be done after
* computing distance. *)
maybe_set_base_rev transition global_rev env;
churn_ready_changes ~acc:(decision :: acc) env server_state
(**
* Run through the ready changs in the queue; then make a decision.
*)
let churn_changes server_state env =
if Queue.is_empty env.state_changes then
Move_along
else
let decisions = churn_ready_changes ~acc:[] env server_state in
(* left is more recent transition, so we prefer its saved state target. *)
let select_relevant left right =
match (left, right) with
| (Restart_server, _)
| (_, Restart_server) ->
Restart_server
| (_, _) -> Move_along
in
List.fold_left ~f:select_relevant ~init:Move_along decisions
let get_change env =
let (watchman, change) = Watchman.get_changes !(env.inits.watchman) in
env.inits.watchman := watchman;
match change with
| Watchman.Watchman_unavailable
| Watchman.Watchman_synchronous _ ->
None
| Watchman.Watchman_pushed (Watchman.Changed_merge_base (rev, files, clock))
->
let () = Hh_logger.log "Changed_merge_base: %s" rev in
Some (Changed_merge_base (rev, files, clock))
| Watchman.Watchman_pushed (Watchman.State_enter (state, json))
when String.equal state "hg.update" ->
env.is_in_hg_update_state := true;
Option.(
json >>= Watchman_utils.rev_in_state_change >>= fun hg_rev ->
Hh_logger.log "State_enter: %s" hg_rev;
Some (State_enter hg_rev))
| Watchman.Watchman_pushed (Watchman.State_leave (state, json))
when String.equal state "hg.update" ->
env.is_in_hg_update_state := false;
Option.(
json >>= Watchman_utils.rev_in_state_change >>= fun hg_rev ->
Hh_logger.log "State_leave: %s" hg_rev;
Some (State_leave hg_rev))
| Watchman.Watchman_pushed (Watchman.State_enter (state, _))
when String.equal state "hg.transaction" ->
env.is_in_hg_transaction_state := true;
None
| Watchman.Watchman_pushed (Watchman.State_leave (state, _))
when String.equal state "hg.transaction" ->
env.is_in_hg_transaction_state := false;
None
| Watchman.Watchman_pushed (Watchman.Files_changed _)
| Watchman.Watchman_pushed (Watchman.State_enter _)
| Watchman.Watchman_pushed (Watchman.State_leave _) ->
None
let preprocess server_state transition env =
make_decision (Unix.time ()) transition server_state env
let handle_change_then_churn server_state change env =
let () =
match change with
| None -> ()
| Some (State_enter hg_rev) ->
Queue.enqueue env.state_changes (State_enter hg_rev, Unix.time ())
| Some (State_leave hg_rev) ->
Queue.enqueue env.state_changes (State_leave hg_rev, Unix.time ())
| Some (Changed_merge_base _ as change) ->
Queue.enqueue env.state_changes (change, Unix.time ())
in
churn_changes server_state env
let has_more_watchman_messages env =
match Watchman.get_reader !(env.inits.watchman) with
| None -> false
| Some reader -> Buffered_line_reader.is_readable reader
(**
* This must be a non-blocking call, so it creates Futures and consumes ready
* Futures.
*
* The steps are:
* 1) Get state change event from Watchman.
* 3) Maybe add a needed query
* (if we don't already know the global rev for this hg rev)
* 4) Preprocess new incoming change - this might result in an early
* decision to restart or kill the server, in which case we can dump
* out all the older changes that still need to be handled.
* 5) If no early decision, handle the new change and churn through the
* queue of pending changes.
* *)
let process_once server_state env =
let change = get_change env in
let early_decision =
match change with
| None -> None
| Some (State_enter hg_rev) ->
let () = Revision_map.add_query ~hg_rev env.inits.root env.rev_map in
preprocess server_state (State_enter hg_rev) env
| Some (State_leave hg_rev) ->
let () = Revision_map.add_query ~hg_rev env.inits.root env.rev_map in
preprocess server_state (State_leave hg_rev) env
| Some (Changed_merge_base (hg_rev, _, _) as change) ->
let () = Revision_map.add_query ~hg_rev env.inits.root env.rev_map in
preprocess server_state change env
in
(* If we make an "early" decision to either kill or restart, we toss
* out earlier state changes and don't need to pump the queue anymore.
*
* This is an optimization.
*
* Otherwise, we continue as per usual. *)
let report =
match early_decision with
| Some (Restart_server, global_rev) ->
(* Early decision to restart, so the prior state changes don't
* matter anymore. *)
Hh_logger.log "Informant early decision: restart server";
let () = Queue.clear env.state_changes in
let () = set_base_revision global_rev env in
Restart_server
| Some (Move_along, _)
| None ->
handle_change_then_churn server_state change env
in
(* All the cases that `(change <> None)` cover should be also covered by
* has_more_watchman_messages, but this alternate method of pumping messages
* is heavily used in tests *)
(report, has_more_watchman_messages env || Option.is_some change)
let rec process (server_state, env, reports_acc) =
(* Sometimes Watchman pushes many file changes as many sequential
* notifications instead of all at once. Since make_report is
* only called once per tick, we don't want to take many ticks
* to consume this queue of notifications. So instead we repeatedly consume
* the Watchman pipe here until it has no more changes. *)
let (report, had_watchman_changes) = process_once server_state env in
let reports_acc = report :: reports_acc in
if had_watchman_changes then
process (server_state, env, reports_acc)
else
reports_acc
let process server_state env =
let reports = process (server_state, env, []) in
(* We fold through the reports and take the "most active" one. *)
let max_report a b =
match (a, b) with
| (Restart_server, _)
| (_, Restart_server) ->
Restart_server
| (_, _) -> Move_along
in
let default_decision =
match server_state with
| Server_not_yet_started when not (is_hg_updating env) -> Restart_server
| _ -> Move_along
in
let decision =
List.fold_left ~f:max_report ~init:default_decision reports
in
match decision with
| Restart_server when is_hg_updating env ->
Hh_logger.log
"Ignoring Restart_server because we are already in next hg.update state";
Move_along
| decision -> decision
let reinit t =
(* The results of old initialization query might be stale by now, so we need
* to cancel it and issue a new one *)
let cancel_future future =
(* timeout=0 should immediately kill and cleanup all queries that were not ready by now *)
let (_ : ('a, Future.error) result) = Future.get future ~timeout:0 in
()
in
let make_new_future root =
Hg.current_working_copy_base_rev (Path.to_string root)
in
match !t with
| Initializing (init_settings, future) ->
cancel_future future;
t := Initializing (init_settings, make_new_future init_settings.root)
| Reinitializing (env, future) ->
cancel_future future;
t := Reinitializing (env, make_new_future env.inits.root)
| Tracking env -> t := Reinitializing (env, make_new_future env.inits.root)
let check_init_future future =
if not @@ Future.is_ready future then
None
else
let global_rev =
Future.get future
|> Result.map_error ~f:Future.error_to_string
|> Result.map_error
~f:HackEventLogger.revision_tracker_init_svn_rev_failed
|> Result.ok
|> Option.value ~default:0
in
let () =
Hh_logger.log
"Initialized Revision_tracker to global rev: %d"
global_rev
in
Some global_rev
let make_report server_state t =
match !t with
| Initializing (init_settings, future) -> begin
match check_init_future future with
| Some global_rev ->
let env = active_env init_settings global_rev in
let () = t := Tracking env in
process server_state env
| None -> Move_along
end
| Reinitializing (env, future) -> begin
match check_init_future future with
| Some global_rev ->
let env = reinitialized_env env global_rev in
let () = t := Tracking env in
process server_state env
| None -> Move_along
end
| Tracking env -> process server_state env
end
type env = {
(* Reports for an Active informant are made by pinging the
* revision_tracker. *)
revision_tracker: Revision_tracker.t;
watchman_event_watcher: WatchmanEventWatcherClient.t;
}
type t =
(* Informant is active. *)
| Active of env
(* We don't run the informant if Watchman fails to initialize,
* or if Watchman subscriptions are disabled in the local config,
* or if the informant is disabled in the hhconfig. *)
| Resigned
let init
{
root;
allow_subscriptions;
use_dummy;
min_distance_restart;
watchman_debug_logging;
ignore_hh_version = _;
is_saved_state_precomputed;
} =
if use_dummy then
let () = Printf.eprintf "Informant using dummy - resigning\n" in
Resigned
(* Active informant requires Watchman subscriptions. *)
else if not allow_subscriptions then
let () = Printf.eprintf "Not using subscriptions - Informant resigning\n" in
Resigned
else
let watchman =
Watchman.init
{
Watchman.subscribe_mode = Some Watchman.Scm_aware;
init_timeout = Watchman.Explicit_timeout 30.;
expression_terms = FilesToIgnore.watchman_monitor_expression_terms;
debug_logging = watchman_debug_logging;
(* Should also take an arg *)
sockname = None;
subscription_prefix = "hh_informant_watcher";
roots = [root];
}
()
in
match watchman with
| None ->
let () =
Printf.eprintf "Watchman failed to init - Informant resigning\n"
in
Resigned
| Some watchman_env ->
Active
{
revision_tracker =
Revision_tracker.init
~min_distance_restart
~is_saved_state_precomputed
(Watchman.Watchman_alive watchman_env)
root;
watchman_event_watcher = WatchmanEventWatcherClient.init root;
}
let reinit t =
match t with
| Resigned -> ()
| Active env ->
Hh_logger.log "Reinitializing Informant";
Revision_tracker.reinit env.revision_tracker
let should_start_first_server t =
match t with
| Resigned ->
(* If Informant doesn't control the server lifetime, then the first server
* instance should always be started during startup. *)
true
| Active env ->
let status =
WatchmanEventWatcherClient.get_status env.watchman_event_watcher
in
begin
match status with
| None ->
(*
* Watcher is not running, or connection to watcher collapsed.
* So we let the first server start up.
*)
HackEventLogger.informant_watcher_not_available ();
true
| Some WatchmanEventWatcherConfig.Responses.Unknown ->
(*
* Watcher doens't know what state the repo is. We don't
* know when the next "hg update" will happen, so we let the
* first Hack Server start up to avoid wedging.
*)
HackEventLogger.informant_watcher_unknown_state ();
true
| Some WatchmanEventWatcherConfig.Responses.Mid_update ->
(* Wait until the update is finished *)
HackEventLogger.informant_watcher_mid_update_state ();
false
| Some WatchmanEventWatcherConfig.Responses.Settled ->
HackEventLogger.informant_watcher_settled_state ();
true
end
let should_ignore_hh_version init_env = init_env.ignore_hh_version
let is_managing = function
| Resigned -> false
| Active _ -> true
let report informant server_state =
match (informant, server_state) with
| (Resigned, Server_not_yet_started) ->
(* Actually, this case should never happen. But we force a restart
* to avoid accidental wedged states anyway. *)
Hh_logger.log
"Unexpected Resigned informant without a server started, restarting server";
Restart_server
| (Resigned, _) -> Move_along
| (Active env, Server_not_yet_started) ->
if should_start_first_server informant then (
(* should_start_first_server (as name implies) prevents us from starting first (since
* monitor start) server in the middle of update, when Revision_tracker is not reliable.
* When server crashes/exits, it will go back to Server_not_yet_started, and
* once again we need to avoid starting it during update. This time we can
* defer to Revision_tracker safely. *)
let report =
Revision_tracker.make_report server_state env.revision_tracker
in
(match report with
| Restart_server ->
Hh_logger.log "Informant watcher starting server from settling";
HackEventLogger.informant_watcher_starting_server_from_settling ()
| Move_along -> ());
report
) else
Move_along
| (Active env, _) ->
Revision_tracker.make_report server_state env.revision_tracker |
OCaml Interface | hhvm/hphp/hack/src/monitor/informant.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(** The informant collects information to tell the monitor when to
intelligently kill and restart the server daemon.
For example: An informant may want to watch the repo state and tell
the monitor to restart the server when a significant change in
repo revision occurs since a fresh initialization could be faster
than an incremental type check. *)
type report =
| Move_along (** Nothing to see here. *)
| Restart_server
(** Kill the server (if one is running) and start a new one. *)
[@@deriving show]
type server_state =
| Server_not_yet_started
| Server_alive
| Server_dead
[@@deriving show]
type t
type options = {
root: Path.t;
allow_subscriptions: bool;
(** Disable the informant - use the dummy instead. *)
use_dummy: bool;
(** Don't trigger a server restart if the distance between two
revisions we are moving between is less than this. *)
min_distance_restart: int;
watchman_debug_logging: bool;
(** Informant should ignore the hh_version when doing version checks. *)
ignore_hh_version: bool;
(** Was the server initialized with a precomputed saved-state? *)
is_saved_state_precomputed: bool;
}
type init_env = options
val init : init_env -> t
(* Same as init, except it preserves internal Revision_map cache.
* This is used when server decides to restart itself due to rebase - we don't
* want Informant to then restart the server again. Reinitializing will discard
* the pending queue of state changes, and issue new query for base revision,
* in order to "synchronize" base revision understanding between server and
* monitor. *)
val reinit : t -> unit
val report : t -> server_state -> report
(*
* Returns true if the informant is actually running and will
* manage server lifetime.
*)
val is_managing : t -> bool
val should_start_first_server : t -> bool
val should_ignore_hh_version : init_env -> bool |
OCaml | hhvm/hphp/hack/src/monitor/monitorConnection.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 MonitorUtils
let log s ~tracker =
Hh_logger.log ("[%s] " ^^ s) (Connection_tracker.log_id tracker)
let server_exists lock_file = not (Lock.check lock_file)
let from_channel_without_buffering ?timeout tic =
Marshal_tools.from_fd_with_preamble ?timeout (Timeout.descr_of_in_channel tic)
let hh_monitor_config root =
MonitorUtils.
{
lock_file = ServerFiles.lock_file root;
socket_file = ServerFiles.socket_file root;
server_log_file = ServerFiles.log_link root;
monitor_log_file = ServerFiles.monitor_log_link root;
}
let wait_on_server_restart ic =
(* The server is out of date and is going to exit. Subsequent calls
* to connect on the Unix Domain Socket might succeed, connecting to
* the server that is about to die, and eventually we will be hung
* up on while trying to read from our end.
*
* To avoid that fate, when we know the server is about to exit, we
* wait for the connection to be closed, signaling that the server
* has exited and the OS has cleaned up after it, then we try again.
*
* See also: MonitorMain.client_out_of_date
*)
try
while true do
let (_ : char) = Timeout.input_char ic in
()
done
with
| End_of_file
| Sys_error _ ->
(* Server has exited and hung up on us *)
()
let get_sockaddr config =
let sock_name = Socket.get_path config.MonitorUtils.socket_file in
if Sys.win32 then (
let ic = In_channel.create ~binary:true sock_name in
let port = Option.value_exn (In_channel.input_binary_int ic) in
In_channel.close ic;
Unix.(ADDR_INET (inet_addr_loopback, port))
) else
Unix.ADDR_UNIX sock_name
(* Consume sequence of Prehandoff messages. *)
let rec consume_prehandoff_messages
~(timeout : Timeout.t) (ic : Timeout.in_channel) (oc : Stdlib.out_channel) :
( Timeout.in_channel
* Stdlib.out_channel
* ServerCommandTypes.server_specific_files,
MonitorUtils.connection_error )
result =
let module PH = Prehandoff in
let m : PH.msg = from_channel_without_buffering ~timeout ic in
match m with
| PH.Sentinel server_specific_files -> Ok (ic, oc, server_specific_files)
| PH.Server_dormant_connections_limit_reached ->
Printf.eprintf
@@ "Connections limit on dormant server reached."
^^ " Be patient waiting for a server to be started.";
Error Server_dormant
| PH.Server_not_alive_dormant _ ->
Printf.eprintf
"Waiting for a server to be started...%s\n%!"
ClientMessages.waiting_for_server_to_be_started_doc;
consume_prehandoff_messages ~timeout ic oc
| PH.Server_died_config_change ->
Printf.eprintf
("Last server exited due to config change. Please re-run client"
^^ " to force discovery of the correct version of the client.");
Error Server_died
| PH.Server_died { PH.status; PH.was_oom } ->
(match (was_oom, status) with
| (true, _) -> Printf.eprintf "Last server killed by OOM Manager.\n%!"
| (false, Unix.WEXITED exit_code) ->
Printf.eprintf "Last server exited with code: %d.\n%!" exit_code
| (false, Unix.WSIGNALED signal) ->
Printf.eprintf "Last server killed by signal: %d.\n%!" signal
| (false, Unix.WSTOPPED signal) ->
Printf.eprintf "Last server stopped by signal: %d.\n%!" signal);
(* Monitor will exit now that it has provided a client with a reason
* for the last server dying. Wait for the Monitor to exit. *)
wait_on_server_restart ic;
Error Server_died
let read_and_log_process_information ~timeout =
let process = Process.exec Exec_command.Pgrep ["hh_client"; "-a"] in
match Process.read_and_wait_pid process ~timeout with
| Ok r ->
(* redirecting the output of pgrep from stdout to stderr with no formatting, so users see relevant PID and paths.
Manually pulling out first 5 elements with string handling rather than piping the input into `head`.
The reason being that the use of Process.exec with Exec_command is to avoid the risk of shelling out
failing and throwing some exception that gets caught higher up the chain. Instead, allow pgrep to be a single chance to fail.
Any success can be handled in application code with postprocessing.
Currently we filter out Scuba-related entries from the process list. They should not contribute to notable hh interaction issues, and create noisy logs.
*)
let exclude_scuba_entry =
List.filter ~f:(fun x -> String_utils.substring_index "scuba" x = -1)
in
let process_list =
r.Process_types.stdout
|> String.split_on_chars ~on:['\n']
|> exclude_scuba_entry
in
let matching_processes =
process_list |> (fun x -> List.take x 5) |> String.concat ~sep:"\n"
in
Hh_logger.error
"[monitorConnection] found %d processes when hh took more than 3 seconds to connect to monitor"
(List.length process_list);
Printf.eprintf "%s\n%!" matching_processes;
HackEventLogger.client_connect_to_monitor_slow_log ()
| Error e ->
let failure_msg = Process.failure_msg e in
Printf.eprintf "pgrep failed with reason: %s\n%!" failure_msg;
let telemetry =
match e with
| Process_types.Abnormal_exit { stderr; stdout; status } ->
let status_msg =
match status with
| Unix.WEXITED code -> Printf.sprintf "exited: code = %d" code
| Unix.WSIGNALED code -> Printf.sprintf "signaled: code = %d" code
| Unix.WSTOPPED code -> Printf.sprintf "stopped: code = %d" code
in
Telemetry.create ()
|> Telemetry.string_ ~key:"stderr" ~value:stderr
|> Telemetry.string_ ~key:"stdout" ~value:stdout
|> Telemetry.string_ ~key:"status" ~value:status_msg
| Process_types.Timed_out { stderr; stdout } ->
Telemetry.create ()
|> Telemetry.string_ ~key:"stderr" ~value:stderr
|> Telemetry.string_ ~key:"stdout" ~value:stdout
| Process_types.Overflow_stdin -> Telemetry.create ()
in
let desc = "pgrep_failed_for_monitor_connect" in
Hh_logger.log
"INVARIANT VIOLATION BUG: [%s] [%s]"
desc
(Telemetry.to_string telemetry);
HackEventLogger.invariant_violation_bug desc ~telemetry;
()
let connect_to_monitor
?(log_on_slow_connect = false)
~tracker
~timeout
~terminate_monitor_on_version_mismatch
config =
(* There are some pathological scenarios concerned with high volumes of requests.
1. There's a finite unix pipe between monitor and server, used for handoff. When
that pipe gets full (~30 requests), the monitor will freeze for 4s before closing
the client request.
2. In ClientConnect.connect we allow the monitor only 1s to respond before we
abandon our connection attempt and try again, repeated up to --timeout times (by
default infinite). If the monitor takes >1s to work through its queue, then every
item placed there will be expired before the monitor gets to handle it, and we'll
never recover.
3. The monitor's finite incoming queue will become full too, disallowing clients from
even connecting.
4. Aside from those concerns, just practically, the commonest mode of failure I've observed
is that the monitor actually just gets stuck -- sometimes stuck on a "read" call to
read requests parameters where it should make progress or get an EOF but just sits there
indefinitely, sometimes stuck on a "select" call to see if there's a request on the queue
where I know there are outstanding requests but again it doesn't see them. I have no
explanation for these phemona. *)
let open Connection_tracker in
let phase = ref MonitorUtils.Connect_open_socket in
let finally_close : Timeout.in_channel option ref = ref None in
let warn_of_busy_server_timer : Timer.t option ref = ref None in
Utils.try_finally
~f:(fun () ->
try
(* Note: Timeout.with_timeout is accomplished internally by an exception;
hence, our "try/with exn ->" catch-all must be outside with_timeout. *)
Timeout.with_timeout
~timeout
~do_:(fun timeout ->
(* 1. open the socket *)
phase := MonitorUtils.Connect_open_socket;
let monitor_daemon_is_running =
match
Process.read_and_wait_pid
(Process.exec
Exec_command.Pgrep
["-af"; "monitor_daemon_main"])
~timeout:2
with
| Ok _ -> true
| Error _ -> false
in
if log_on_slow_connect && monitor_daemon_is_running then
(* Setting up a timer to fire a notice to the user when hh seems to be slower.
Since connect_to_monitor allows a 60 second timeout by default, it's possible that hh appears to be hanging from a user's perspective.
We can show people after some time (3 seconds arbitrarily) what processes might be slowing the response. *)
let callback () =
Printf.eprintf
"The Hack server seems busy and overloaded. The following processes are making requests to hh_server (limited to first 5 shown): \n%!";
read_and_log_process_information ~timeout:2
in
warn_of_busy_server_timer :=
Some (Timer.set_timer ~interval:3.0 ~callback)
else
();
let sockaddr = get_sockaddr config in
let (ic, oc) = Timeout.open_connection ~timeout sockaddr in
finally_close := Some ic;
let tracker =
Connection_tracker.track tracker ~key:Client_opened_socket
in
(* 2. send version, followed by newline *)
phase := MonitorUtils.Connect_send_version;
let version_str =
MonitorUtils.VersionPayload.serialize
~tracker
~terminate_monitor_on_version_mismatch
in
let (_ : int) =
Marshal_tools.to_fd_with_preamble
(Unix.descr_of_out_channel oc)
version_str
in
phase := MonitorUtils.Connect_send_newline;
let (_ : int) =
Unix.write
(Unix.descr_of_out_channel oc)
(Bytes.of_string "\n")
0
1
in
let tracker =
Connection_tracker.track tracker ~key:Client_sent_version
in
(* 3. wait for Connection_ok *)
(* timeout/exn -> Server_missing_exn/Monitor_connection_misc_exception *)
phase := MonitorUtils.Connect_receive_connection_ok;
let cstate : connection_state = from_channel_without_buffering ic in
let tracker =
Connection_tracker.track tracker ~key:Client_got_cstate
in
let _ =
match !warn_of_busy_server_timer with
| None -> ()
| Some timer -> Timer.cancel_timer timer
in
(* 4. return Ok *)
match cstate with
| Connection_ok
| Connection_ok_v2 _ ->
finally_close := None;
Ok (ic, oc, tracker)
| Build_id_mismatch ->
wait_on_server_restart ic;
Error (Build_id_mismatched_monitor_will_terminate None)
| Build_id_mismatch_ex mismatch_info ->
wait_on_server_restart ic;
Error
(Build_id_mismatched_monitor_will_terminate (Some mismatch_info))
| Build_id_mismatch_v3 (mismatch_info, mismatch_payload) ->
let monitor_will_terminate =
match
MonitorUtils.MismatchPayload.deserialize mismatch_payload
with
| Error msg ->
Hh_logger.log
"Unparseable response from monitor - %s\n%s"
msg
mismatch_payload;
true
| Ok { MonitorUtils.MismatchPayload.monitor_will_terminate } ->
monitor_will_terminate
in
if monitor_will_terminate then begin
wait_on_server_restart ic;
Error
(Build_id_mismatched_monitor_will_terminate
(Some mismatch_info))
end else
Error (Build_id_mismatched_client_must_terminate mismatch_info))
~on_timeout:(fun _timings ->
Error
(Connect_to_monitor_failure
{
server_exists = server_exists config.lock_file;
failure_phase = !phase;
failure_reason = Connect_timeout;
}))
with
| Unix.Unix_error _ as exn ->
let e = Exception.wrap exn in
Error
(Connect_to_monitor_failure
{
server_exists = server_exists config.lock_file;
failure_phase = !phase;
failure_reason = Connect_exception e;
}))
~finally:(fun () ->
match !finally_close with
| None -> ()
| Some ic ->
Timeout.shutdown_connection ic;
Timeout.close_in_noerr ic)
let connect_and_shut_down ~tracker root =
let open Result.Monad_infix in
let config = hh_monitor_config root in
connect_to_monitor
~tracker
~timeout:3
~terminate_monitor_on_version_mismatch:true
config
>>= fun (ic, oc, tracker) ->
log "send_shutdown" ~tracker;
let (_ : int) =
Marshal_tools.to_fd_with_preamble
(Unix.descr_of_out_channel oc)
(MonitorRpc.SHUT_DOWN tracker)
in
Timeout.with_timeout
~timeout:3
~on_timeout:(fun _timings ->
if server_exists config.lock_file then
Ok MonitorUtils.SHUTDOWN_UNVERIFIED
else
Error
(Connect_to_monitor_failure
{
server_exists = false;
failure_phase = Connect_send_shutdown;
failure_reason = Connect_timeout;
}))
~do_:
begin
fun _ ->
wait_on_server_restart ic;
Ok MonitorUtils.SHUTDOWN_VERIFIED
end
let connect_once
~tracker
~timeout
~terminate_monitor_on_version_mismatch
root
handoff_options =
let open Result.Monad_infix in
let config = hh_monitor_config root in
let t_start = Unix.gettimeofday () in
let result =
let tracker =
Connection_tracker.(track tracker ~key:Client_start_connect ~time:t_start)
in
connect_to_monitor
~tracker
~timeout
~terminate_monitor_on_version_mismatch
config
>>= fun (ic, oc, tracker) ->
let tracker =
Connection_tracker.(track tracker ~key:Client_ready_to_send_handoff)
in
let (_ : int) =
Marshal_tools.to_fd_with_preamble
(Unix.descr_of_out_channel oc)
(MonitorRpc.HANDOFF_TO_SERVER (tracker, handoff_options))
in
let elapsed_t = int_of_float (Unix.gettimeofday () -. t_start) in
let timeout = max (timeout - elapsed_t) 1 in
Timeout.with_timeout
~timeout
~do_:(fun timeout -> consume_prehandoff_messages ~timeout ic oc)
~on_timeout:(fun _ -> Error MonitorUtils.Server_dormant_out_of_retries)
in
(* oops too heavy *)
Result.iter result ~f:(fun _ ->
log ~tracker "CLIENT_CONNECT_ONCE";
HackEventLogger.client_connect_once ~t_start;
());
Result.iter_error result ~f:(fun e ->
let (reason, telemetry) = MonitorUtils.connection_error_to_telemetry e in
log ~tracker "CLIENT_CONNECT_ONCE %s" reason;
HackEventLogger.client_connect_once_failure ~t_start reason telemetry;
());
result |
OCaml Interface | hhvm/hphp/hack/src/monitor/monitorConnection.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val server_exists : string -> bool
val connect_once :
tracker:Connection_tracker.t ->
timeout:int ->
terminate_monitor_on_version_mismatch:bool ->
Path.t ->
MonitorRpc.handoff_options ->
( Timeout.in_channel * out_channel * ServerCommandTypes.server_specific_files,
MonitorUtils.connection_error )
result
val connect_and_shut_down :
tracker:Connection_tracker.t ->
Path.t ->
(MonitorUtils.shutdown_result, MonitorUtils.connection_error) result |
OCaml | hhvm/hphp/hack/src/monitor/monitorMain.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 server monitor is the parent process for a server. It
* listens to a socket for client connections and passes the connections
* to the server and serves the following objectives:
*
* 1) Readily accepts client connections
* 2) Confirms a Build ID match (killing itself and the server quickly
* on mismatch)
* 3) Hands the client connection to the daemon server
* 4) Tracks when the server process crashes or OOMs and echos
* its fate to the next client.
*)
open Hh_prelude.Result.Monad_infix
open Hh_prelude
open ServerProcess
open MonitorUtils
let log s ~tracker =
Hh_logger.log ("[%s] " ^^ s) (Connection_tracker.log_id tracker)
(** If you try to Unix.close the same FD twice, you get EBADF the second time.
Ocaml doesn't have a linear type system, so it's too hard to be crisp about
when we hand off responsibility for closing the FD. Therefore: we call this
method to ensure an FD is closed, and we just silently gobble up the EBADF
if someone else already closed it. *)
let ensure_fd_closed (fd : Unix.file_descr) : unit =
try Unix.close fd with
| Unix.Unix_error (Unix.EBADF, _, _) -> ()
(** This module is to help using Unix "sendmsg" to handoff the client FD
to the server. It's not entirely clear whether it's safe for us in the
monitor to close the FD immediately after calling sendmsg, or whether
we must wait until the server has actually received the FD upon recvmsg.
We got reports from MacOs users that if the monitor closed the FD before
the server had finished recvmsg, then the kernel thinks it was the last open
descriptor for the pipe, and actually closes it; the server subsequently
does recvmsg and reads on the FD and gets an EOF (even though it can write
on the FD and succeed instead of getting EPIPE); the server subsequently
closes its FD and a subsequent "select" by the client blocks forever.
Therefore, instead, the monitor waits to close the FD until after the server has read it.
We detect that the server has read it by having the server write the highest
handoff number it has received to a "server_receipt_to_monitor_file", and the
monitor polls this file to determine which handoff FD can be closed. It might
be that the server receives two FD handoffs in quick succession, and the monitor
only polls the file after the second, so the monitor treats the file as a
"high water mark" and knows that it can close the specified FD plus all earlier ones.
We did this protocol with a file because there aren't alternatives. If we tried
instead to have the server send receipt over the monitor/server pipe, then it
would deadlock if the monitor was also trying to handoff a subsequent FD.
If we tried instead to have the server send receipt over the client/server pipe,
then both monitor and client would be racing to see who receives that receipt first. *)
module Sent_fds_collector = struct
(** [sequence_number] is a monotonically increasing integer to identify which
handoff message has been sent from monitor to server. The first sequence
number is number 1. *)
let sequence_number : int ref = ref 0
let get_and_increment_sequence_number () : int =
sequence_number := !sequence_number + 1;
!sequence_number
type handed_off_fd_to_close = {
tracker: Connection_tracker.t;
fd: Unix.file_descr;
m2s_sequence_number: int;
(** A unique number incremented for each client socket handoff from monitor to server.
Useful to correlate monitor and server logs. *)
}
let handed_off_fds_to_close : handed_off_fd_to_close list ref = ref []
let cleanup_fd ~tracker ~m2s_sequence_number fd =
handed_off_fds_to_close :=
{ tracker; fd; m2s_sequence_number } :: !handed_off_fds_to_close
let collect_fds ~sequence_receipt_high_water_mark =
(* WARNING! Don't use the (slow) HackEventLogger here, in the inner loop non-failure path. *)
(* Note: this code is a filter with a side-effect. The side-effect is to
close FDs that have received their read-receipts. The filter will retain
the FDs that haven't yet received their read-receipts. *)
handed_off_fds_to_close :=
List.filter
!handed_off_fds_to_close
~f:(fun { tracker; m2s_sequence_number; fd } ->
if m2s_sequence_number > sequence_receipt_high_water_mark then
true
else begin
log
"closing client socket from handoff #%d upon receipt of #%d"
~tracker
m2s_sequence_number
sequence_receipt_high_water_mark;
ensure_fd_closed fd;
false
end);
()
(** This must be called in all paths where the server has died, so that the client can
properly see an EOF on its FD. *)
let collect_all_fds () =
collect_fds ~sequence_receipt_high_water_mark:Int.max_value
end
exception Send_fd_failure of int
type env = {
informant: Informant.t;
server: ServerProcess.server_process;
server_start_options: ServerController.server_start_options;
(* How many times have we tried to relaunch it? *)
retries: int;
sql_retries: int;
watchman_retries: int;
max_purgatory_clients: int;
(* Version of this running server, as specified in the config file. *)
current_version: Config_file.version;
(* After sending a Server_not_alive_dormant during Prehandoff,
* clients are put here waiting for a server to come alive, at
* which point they get pushed through the rest of prehandoff and
* then sent to the living server.
*
* String is the server name it wants to connect to. *)
purgatory_clients:
(Connection_tracker.t * MonitorRpc.handoff_options * Unix.file_descr)
Queue.t;
(* Whether to ignore hh version mismatches *)
ignore_hh_version: bool;
}
type t = env * MonitorUtils.monitor_config * Unix.file_descr
type 'a msg_update = ('a, 'a * string) result
(** Use this as the only way to change server.
It closes all outstanding FDs. That's needed so clients know that they can give up. *)
let set_server (env : env msg_update) new_server : env msg_update =
env >>= fun env ->
Sent_fds_collector.collect_all_fds ();
Ok { env with server = new_server }
let msg_to_channel fd msg =
(* This FD will be passed to a server process, so avoid using Ocaml's
* channels which have built-in buffering. Even though we are only writing
* to the FD here, it seems using Ocaml's channels also causes read
* buffering to happen here, so the server process doesn't get what was
* meant for it. *)
Marshal_tools.to_fd_with_preamble fd msg |> ignore
let setup_handler_for_signals handler signals =
List.iter signals ~f:(fun signal ->
Sys_utils.set_signal signal (Sys.Signal_handle handler))
let setup_autokill_server_on_exit process =
try
setup_handler_for_signals
begin
fun _ ->
Hh_logger.log "Got an exit signal. Killing server and exiting.";
ServerController.kill_server ~violently:false process;
Exit.exit Exit_status.Interrupted
end
[Sys.sigint; Sys.sigquit; Sys.sigterm; Sys.sighup]
with
| _ -> Hh_logger.log "Failed to set signal handler"
let sleep_and_check socket =
(* WARNING! Don't use the (slow) HackEventLogger here, in the inner loop non-failure path. *)
let (ready_socket_l, _, _) = Unix.select [socket] [] [] 1.0 in
not (List.is_empty ready_socket_l)
let start_server ~informant_managed options exit_status =
let server_process =
ServerController.start_server
~prior_exit_status:exit_status
~informant_managed
options
in
setup_autokill_server_on_exit server_process;
Alive server_process
let maybe_start_first_server options informant : ServerProcess.server_process =
if Informant.should_start_first_server informant then (
Hh_logger.log "Starting first server";
HackEventLogger.starting_first_server ();
start_server
~informant_managed:(Informant.is_managing informant)
options
None
) else (
Hh_logger.log
("Not starting first server. "
^^ "Starting will be triggered by informant later.");
Not_yet_started
)
let kill_server_with_check_and_wait (server : server_process) : unit =
Sent_fds_collector.collect_all_fds ();
match server with
| Alive server ->
let start_t = Unix.gettimeofday () in
let rec kill_server_with_check_and_wait_impl () =
ServerController.kill_server
~violently:Float.(Unix.gettimeofday () -. start_t >= 4.0)
server;
let success =
ServerController.wait_for_server_exit
~timeout_t:(Unix.gettimeofday () +. 2.0)
server
in
if not success then
kill_server_with_check_and_wait_impl ()
else
let (_ : float) =
Hh_logger.log_duration
"typechecker has exited. Time since first signal: "
start_t
in
()
in
kill_server_with_check_and_wait_impl ()
| _ -> ()
(* Reads current hhconfig contents from disk and returns true if the
* version specified in there matches our currently running version. *)
let is_config_version_matching env =
let filename =
Relative_path.from_root ~suffix:Config_file.file_path_relative_to_repo_root
in
let (_hash, config) =
Config_file.parse_hhconfig (Relative_path.to_absolute filename)
in
let new_version =
Config_file.parse_version (Config_file.Getters.string_opt "version" config)
in
0 = Config_file.compare_versions env.current_version new_version
(* Actually starts a new server. *)
let start_new_server (env : env msg_update) exit_status : env msg_update =
env >>= fun env ->
let informant_managed = Informant.is_managing env.informant in
let new_server =
start_server ~informant_managed env.server_start_options exit_status
in
let env = set_server (Ok env) new_server in
env >>= fun new_env -> Ok { new_env with retries = new_env.retries + 1 }
(* Kill the server (if it's running) and restart it - maybe. Obeying the rules
* of state transitions. See docs on the ServerProcess.server_process ADT for
* state transitions. *)
let kill_and_maybe_restart_server (env : env msg_update) exit_status :
env msg_update =
env >>= fun env ->
Hh_logger.log
"kill_and_maybe_restart_server (env.server=%s)"
(show_server_process env.server);
(* We're going to collect all FDs right here and now. This will be done again below,
in [kill_server_with_check_and_wait], but Informant.reinit might take too long or might throw. *)
Sent_fds_collector.collect_all_fds ();
(* Iff we just restart and keep going, we risk
* Changed_merge_base eventually arriving and restarting the already started server
* for no reason. Re-issuing merge base query here should bring the Monitor and Server
* understanding of current revision to be the same *)
kill_server_with_check_and_wait env.server;
let version_matches = is_config_version_matching env in
if ServerController.is_saved_state_precomputed env.server_start_options then begin
let reason =
"Not restarting server as requested, server was launched using a "
^ "precomputed saved-state. Exiting monitor"
in
Hh_logger.log "%s" reason;
HackEventLogger.refuse_to_restart_server
~reason
~server_state:(ServerProcess.show_server_process env.server)
~version_matches;
Exit.exit Exit_status.Not_restarting_server_with_precomputed_saved_state
end;
match (env.server, version_matches) with
| (Died_config_changed, _) ->
(* Now we can start a new instance safely.
* See diagram on ServerProcess.server_process docs. *)
start_new_server (Ok env) exit_status
| (Not_yet_started, false)
| (Alive _, false)
| (Died_unexpectedly _, false) ->
(* Can't start server instance. State goes to Died_config_changed
* See diagram on ServerProcess.server_process docs. *)
Hh_logger.log
"Avoiding starting a new server because version in config no longer matches.";
set_server (Ok env) Died_config_changed
| (Not_yet_started, true)
| (Alive _, true)
| (Died_unexpectedly _, true) ->
(* Start new server instance because config matches.
* See diagram on ServerProcess.server_process docs. *)
start_new_server (Ok env) exit_status
let read_version_string_then_newline (fd : Unix.file_descr) :
(MonitorUtils.VersionPayload.serialized, string) result =
(* WARNING! Don't use the (slow) HackEventLogger here, in the inner loop non-failure path. *)
let s : string = Marshal_tools.from_fd_with_preamble fd in
let newline_byte = Bytes.create 1 in
let _ = Unix.read fd newline_byte 0 1 in
if String.equal (Bytes.to_string newline_byte) "\n" then
Ok s
else
Error "missing newline after version"
let hand_off_client_connection ~tracker server_fd client_fd =
(* WARNING! Don't use the (slow) HackEventLogger here, in the inner loop non-failure path. *)
let m2s_sequence_number =
Sent_fds_collector.get_and_increment_sequence_number ()
in
let msg = MonitorRpc.{ m2s_tracker = tracker; m2s_sequence_number } in
msg_to_channel server_fd msg;
log
"Handed off tracker to server (client socket handoff #%d)"
~tracker
m2s_sequence_number;
let status = Libancillary.ancil_send_fd server_fd client_fd in
if status = 0 then begin
log
"Handed off client socket to server (handoff #%d)"
~tracker
m2s_sequence_number;
Sent_fds_collector.cleanup_fd ~tracker ~m2s_sequence_number client_fd
end else begin
log
"Failed to handoff client socket to server (handoff #%d)"
~tracker
m2s_sequence_number;
raise (Send_fd_failure status)
end
(** Sends the client connection FD to the server process then closes the FD.
Backpressure: We have a timeout of 30s here to wait for the server to accept
the handoff. That timeout will be exceeded if monitor->server pipe has filled
up from previous requests and the server's current work item is costly. In this
case we'll give up on the handoff, and hh_client will fail with Server_hung_up_should_retry,
and find_hh.sh will retry with exponential backoff.
During the 30s while we're blocked here, if there are lots of other clients trying
to connect to the monitor and the monitor's incoming queue is full, they'll time
out trying to open a connection to the monitor. Their response is to back off,
with exponentially longer timeouts they're willing to wait for the monitor to become
available. In this way the queue of clients is stored in the unix process list.
Why did we pick 30s? It's arbitrary. If we decreased then, if there are lots of clients,
they'll do more work while they needlessly cycle. If we increased up to infinite
then I worry that a failure for other reasons might look like a hang.
This 30s must be comfortably shorter than the 60s delay in ClientConnect.connect, since
if not then by the time we in the monitor timeout we'll find that every single item
in our incoming queue is already stale! *)
let hand_off_client_connection_wrapper ~tracker server_fd client_fd =
(* WARNING! Don't use the (slow) HackEventLogger here, in the inner loop non-failure path. *)
let timeout = 30.0 in
let to_finally_close = ref (Some client_fd) in
Utils.try_finally
~f:(fun () ->
let (_, ready_l, _) = Unix.select [] [server_fd] [] timeout in
if List.is_empty ready_l then
log
~tracker
"Handoff FD timed out (%.1fs): server's current iteration is taking longer than that, and its incoming pipe is full"
timeout
else
try
hand_off_client_connection ~tracker server_fd client_fd;
to_finally_close := None
with
| Unix.Unix_error (Unix.EPIPE, _, _) ->
log
~tracker
"Handoff FD failed: server has closed its end of pipe (EPIPE), maybe due to large rebase or incompatible .hhconfig change or crash"
| exn ->
let e = Exception.wrap exn in
log
~tracker
"Handoff FD failed unexpectedly - %s"
(Exception.to_string e);
HackEventLogger.send_fd_failure e)
~finally:(fun () ->
match !to_finally_close with
| None -> ()
| Some client_fd ->
log
~tracker
"Sending Monitor_failed_to_handoff to client, and closing FD";
msg_to_channel client_fd ServerCommandTypes.Monitor_failed_to_handoff;
ensure_fd_closed client_fd)
(** Send (possibly empty) sequences of messages before handing off to
server. *)
let rec client_prehandoff
~tracker
~is_purgatory_client
(env : env msg_update)
handoff_options
client_fd : env msg_update =
(* WARNING! Don't use the (slow) HackEventLogger here, in the inner loop non-failure path. *)
let module PH = Prehandoff in
env >>= fun env ->
match env.server with
| Alive server ->
let server_fd =
snd
@@ List.find_exn server.out_fds ~f:(fun x ->
String.equal (fst x) handoff_options.MonitorRpc.pipe_name)
in
let t_ready = Unix.gettimeofday () in
let tracker =
Connection_tracker.(track tracker ~key:Monitor_ready ~time:t_ready)
in
(* TODO: Send this to client so it is visible. *)
log
"Got %s request for typechecker. Prior request %.1f seconds ago"
~tracker
handoff_options.MonitorRpc.pipe_name
(t_ready -. !(server.last_request_handoff));
msg_to_channel client_fd (PH.Sentinel server.server_specific_files);
let tracker =
Connection_tracker.(track tracker ~key:Monitor_sent_ack_to_client)
in
hand_off_client_connection_wrapper ~tracker server_fd client_fd;
server.last_request_handoff := Unix.time ();
Ok env
| Died_unexpectedly (status, was_oom) ->
(* Server has died; notify the client *)
msg_to_channel client_fd (PH.Server_died { PH.status; PH.was_oom });
(* Next client to connect starts a new server. *)
Exit.exit Exit_status.No_error
| Died_config_changed ->
if not is_purgatory_client then (
let env = kill_and_maybe_restart_server (Ok env) None in
env >>= fun env ->
(* Assert that the restart succeeded, and then push prehandoff through again. *)
match env.server with
| Alive _ ->
(* Server restarted. We want to re-run prehandoff, which will
* actually do the prehandoff this time. *)
client_prehandoff
~tracker
~is_purgatory_client
(Ok env)
handoff_options
client_fd
| Died_unexpectedly _
| Died_config_changed
| Not_yet_started ->
Hh_logger.log
("Unreachable state. Server should be alive after trying a restart"
^^ " from Died_config_changed state");
failwith
"Failed starting server transitioning off Died_config_changed state"
) else (
msg_to_channel client_fd PH.Server_died_config_change;
Ok env
)
| Not_yet_started ->
let env : env msg_update =
if handoff_options.MonitorRpc.force_dormant_start then (
msg_to_channel
client_fd
(PH.Server_not_alive_dormant
"Warning - starting a server by force-dormant-start option...");
kill_and_maybe_restart_server (Ok env) None
) else (
msg_to_channel
client_fd
(PH.Server_not_alive_dormant
"Server killed by informant. Waiting for next server...");
Ok env
)
in
env >>= fun env ->
if Queue.length env.purgatory_clients >= env.max_purgatory_clients then
let () =
msg_to_channel client_fd PH.Server_dormant_connections_limit_reached
in
Ok env
else
let () =
Queue.enqueue env.purgatory_clients (tracker, handoff_options, client_fd)
in
Ok env
let handle_monitor_rpc (env : env msg_update) client_fd =
(* WARNING! Don't use the (slow) HackEventLogger here, in the inner loop non-failure path. *)
env >>= fun env ->
let cmd : MonitorRpc.command =
Marshal_tools.from_fd_with_preamble client_fd
in
match cmd with
| MonitorRpc.HANDOFF_TO_SERVER (tracker, handoff_options) ->
let tracker =
Connection_tracker.(track tracker ~key:Monitor_received_handoff)
in
client_prehandoff
~tracker
~is_purgatory_client:false
(Ok env)
handoff_options
client_fd
| MonitorRpc.SHUT_DOWN tracker ->
log "Got shutdown RPC. Shutting down." ~tracker;
kill_server_with_check_and_wait env.server;
Exit.exit Exit_status.No_error
let ack_and_handoff_client (env : env msg_update) client_fd : env msg_update =
env >>= fun env ->
(* WARNING! Don't use the (slow) HackEventLogger here, in the inner loop non-failure path. *)
let start_time = Unix.gettimeofday () in
read_version_string_then_newline client_fd
>>= MonitorUtils.VersionPayload.deserialize
|> Result.map_error ~f:(fun _err -> (env, "Malformed Build ID"))
>>= fun {
MonitorUtils.VersionPayload.client_version;
tracker_id;
terminate_monitor_on_version_mismatch;
} ->
Hh_logger.log
"[%s] read_version: start_wait=%s, client_version=%s, monitor_version=%s, monitor_ignore_hh_version=%b, terminate_monitor_on_version_mismatch=%b"
tracker_id
(start_time |> Utils.timestring)
client_version
Build_id.build_revision
env.ignore_hh_version
terminate_monitor_on_version_mismatch;
(* Version is okay if *monitor* was started with --ignore-hh-version, or versions match. *)
let is_version_ok =
env.ignore_hh_version || String.equal client_version Build_id.build_revision
in
if is_version_ok then begin
let connection_state = Connection_ok in
Hh_logger.log
"[%s] sending %s"
tracker_id
(MonitorUtils.show_connection_state connection_state);
msg_to_channel client_fd connection_state;
(* following function returns [env msg_update] monad *)
handle_monitor_rpc (Ok env) client_fd
end else begin
let monitor_will_terminate = terminate_monitor_on_version_mismatch in
let connection_state =
Build_id_mismatch_v3
( MonitorUtils.current_build_info,
MonitorUtils.MismatchPayload.serialize ~monitor_will_terminate )
in
Hh_logger.log
"[%s] sending %s"
tracker_id
(MonitorUtils.show_connection_state connection_state);
(try msg_to_channel client_fd connection_state with
| exn -> Hh_logger.log "while sending, exn: %s" (Exn.to_string exn));
if monitor_will_terminate then begin
kill_server_with_check_and_wait env.server;
Exit.exit Exit_status.Build_id_mismatch
end else begin
Hh_logger.log "Closing client_fd";
(try Unix.close client_fd with
| exn -> Hh_logger.log "while closing, exn: %s" (Exn.to_string exn));
Ok env
end
end
let push_purgatory_clients (env : env msg_update) : env msg_update =
(* We create a queue and transfer all the purgatory clients to it before
* processing to avoid repeatedly retrying the same client even after
* an EBADF. Control flow is easier this way than trying to manage an
* immutable env in the face of exceptions. *)
env >>= fun env ->
let clients = Queue.create () in
Queue.blit_transfer ~src:env.purgatory_clients ~dst:clients ();
let env =
Queue.fold
~f:
begin
fun env_accumulator (tracker, handoff_options, client_fd) ->
try
client_prehandoff
~tracker
~is_purgatory_client:true
env_accumulator
handoff_options
client_fd
with
| Unix.Unix_error (Unix.EPIPE, _, _)
| Unix.Unix_error (Unix.EBADF, _, _) ->
log "Purgatory client disconnected. Dropping." ~tracker;
env_accumulator
(* @nzthomas TODO, is this an error? *)
end
~init:(Ok env)
clients
in
env
let maybe_push_purgatory_clients (env : env msg_update) : env msg_update =
(* WARNING! Don't use the (slow) HackEventLogger here, in the inner loop non-failure path. *)
env >>= fun env ->
match (env.server, Queue.length env.purgatory_clients) with
| (Alive _, 0) -> Ok env
| (Died_config_changed, _) ->
(* These clients are waiting for a server to be started. But this Monitor
* is waiting for a new client to connect (which confirms to us that we
* are running the correct version of the Monitor). So let them know
* that they might want to do something. *)
push_purgatory_clients (Ok env)
| (Alive _, _) -> push_purgatory_clients (Ok env)
| (Not_yet_started, _)
| (Died_unexpectedly _, _) ->
Ok env
(* Kill command from client is handled by server server, so the monitor
* needs to check liveness of the server process to know whether
* to stop itself. *)
let update_status_ (env : env msg_update) monitor_config :
(env * int option * Informant.server_state, env * string) result =
let env =
env >>= fun env ->
match env.server with
| Alive process ->
let (pid, proc_stat) = ServerController.wait_pid process in
(match (pid, proc_stat) with
| (0, _) ->
(* "pid=0" means the pid we waited for (i.e. process) hasn't yet died/stopped *)
Ok env
| (_, Unix.WEXITED 0) ->
(* "pid<>0, WEXITED 0" means the process had a clean exit *)
set_server (Ok env) (Died_unexpectedly (proc_stat, false))
| (_, _) ->
(* this case is any kind of unexpected exit *)
let is_oom =
match proc_stat with
| Unix.WEXITED code
when (code = Exit_status.(exit_code Out_of_shared_memory))
|| code = Exit_status.(exit_code Worker_oomed) ->
true
| _ -> Sys_utils.check_dmesg_for_oom process.pid "hh_server"
in
let (exit_type, exit_code) = Exit_status.unpack proc_stat in
let time_taken = Unix.time () -. process.start_t in
ServerProgress.write "writing crash logs";
let telemetry =
Telemetry.create ()
|> Telemetry.string_ ~key:"unix_exit_type" ~value:exit_type
|> Telemetry.int_ ~key:"unix_exit_code" ~value:exit_code
|> Telemetry.bool_ ~key:"is_oom" ~value:is_oom
in
let (telemetry, exit_status) =
match
Exit_status.get_finale_data
process.server_specific_files
.ServerCommandTypes.server_finale_file
with
| None -> (telemetry, None)
| Some
{
Exit_status.exit_status;
msg;
stack = Utils.Callstack stack;
telemetry = finale_telemetry;
} ->
let telemetry =
telemetry
|> Telemetry.string_
~key:"exit_status"
~value:(Exit_status.show exit_status)
|> Telemetry.string_opt ~key:"msg" ~value:msg
|> Telemetry.string_ ~key:"stack" ~value:stack
|> Telemetry.object_opt ~key:"data" ~value:finale_telemetry
in
(telemetry, Some exit_status)
in
Hh_logger.log "TYPECHECKER_EXIT %s" (Telemetry.to_string telemetry);
HackEventLogger.typechecker_exit
telemetry
time_taken
(monitor_config.server_log_file, monitor_config.monitor_log_file)
~exit_type
~exit_code
~exit_status
~is_oom;
ServerProgress.write
"%s"
~disposition:ServerProgress.DStopped
(Option.value_map
exit_status
~f:Exit_status.show
~default:"server stopped");
set_server (Ok env) (Died_unexpectedly (proc_stat, is_oom)))
| Not_yet_started
| Died_config_changed
| Died_unexpectedly _ ->
Ok env
in
env >>= fun env ->
let (exit_status, server_state) =
match env.server with
| Alive _ -> (None, Informant.Server_alive)
| Died_unexpectedly (Unix.WEXITED c, _) -> (Some c, Informant.Server_dead)
| Not_yet_started -> (None, Informant.Server_not_yet_started)
| Died_unexpectedly ((Unix.WSIGNALED _ | Unix.WSTOPPED _), _)
| Died_config_changed ->
(None, Informant.Server_dead)
in
Ok (env, exit_status, server_state)
let update_status (env : env msg_update) monitor_config : env msg_update =
(* WARNING! Don't use the (slow) HackEventLogger here, in the inner loop non-failure path. *)
update_status_ env monitor_config >>= fun (env, exit_status, server_state) ->
let informant_report = Informant.report env.informant server_state in
let is_watchman_fresh_instance =
match exit_status with
| Some c when c = Exit_status.(exit_code Watchman_fresh_instance) -> true
| _ -> false
in
let is_watchman_failed =
match exit_status with
| Some c when c = Exit_status.(exit_code Watchman_failed) -> true
| _ -> false
in
let is_config_changed =
match exit_status with
| Some c when c = Exit_status.(exit_code Hhconfig_changed) -> true
| _ -> false
in
let is_heap_stale =
match exit_status with
| Some c
when (c = Exit_status.(exit_code File_provider_stale))
|| c = Exit_status.(exit_code Decl_not_found) ->
true
| _ -> false
in
let is_sql_assertion_failure =
match exit_status with
| Some c
when (c = Exit_status.(exit_code Sql_assertion_failure))
|| (c = Exit_status.(exit_code Sql_cantopen))
|| (c = Exit_status.(exit_code Sql_corrupt))
|| c = Exit_status.(exit_code Sql_misuse) ->
true
| _ -> false
in
let is_worker_error =
match exit_status with
| Some c
when (c = Exit_status.(exit_code Worker_not_found_exception))
|| (c = Exit_status.(exit_code Worker_busy))
|| c = Exit_status.(exit_code Worker_failed_to_send_job) ->
true
| _ -> false
in
let is_decl_heap_elems_bug =
match exit_status with
| Some c when c = Exit_status.(exit_code Decl_heap_elems_bug) -> true
| _ -> false
in
let is_big_rebase =
match exit_status with
| Some c when c = Exit_status.(exit_code Big_rebase_detected) -> true
| _ -> false
in
let max_watchman_retries = 3 in
let max_sql_retries = 3 in
let (reason, msg_update) =
match (informant_report, env.server) with
| (Informant.Move_along, Died_config_changed) ->
(* No "reason" here -- we're on an "inner-loop non-failure" path *)
(None, Ok env)
| (Informant.Restart_server, Died_config_changed) ->
let reason =
"Ignoring Informant directed restart - waiting for next client connection to verify server version first"
in
(Some reason, Ok env)
| (Informant.Restart_server, _) ->
let reason = "Informant directed server restart. Restarting server." in
(Some reason, kill_and_maybe_restart_server (Ok env) exit_status)
| (Informant.Move_along, _) ->
if
(is_watchman_failed || is_watchman_fresh_instance)
&& env.watchman_retries < max_watchman_retries
then
let reason =
Printf.sprintf
"Watchman died. Restarting hh_server (attempt: %d)"
(env.watchman_retries + 1)
in
let env = { env with watchman_retries = env.watchman_retries + 1 } in
(Some reason, set_server (Ok env) Not_yet_started)
else if is_decl_heap_elems_bug then
let reason = "hh_server died due to Decl_heap_elems_bug. Restarting" in
(Some reason, set_server (Ok env) Not_yet_started)
else if is_worker_error then
let reason = "hh_server died due to worker error. Restarting" in
(Some reason, set_server (Ok env) Not_yet_started)
else if is_config_changed then
let reason = "hh_server died from hh config change. Restarting" in
(Some reason, set_server (Ok env) Not_yet_started)
else if is_heap_stale then
let reason =
"Several large rebases caused shared heap to be stale. Restarting"
in
(Some reason, set_server (Ok env) Not_yet_started)
else if is_big_rebase then
let reason = "Server exited because of big rebase. Restarting" in
(Some reason, set_server (Ok env) Not_yet_started)
else if is_sql_assertion_failure && env.sql_retries < max_sql_retries then
let reason =
Printf.sprintf
"Sql failed. Restarting hh_server in fresh mode (attempt: %d)"
(env.sql_retries + 1)
in
let env = { env with sql_retries = env.sql_retries + 1 } in
(Some reason, set_server (Ok env) Not_yet_started)
else
(* No reason here, on the inner-loop non-failure path. *)
(None, Ok env)
in
begin
match reason with
| None -> ()
| Some reason ->
Hh_logger.log "MONITOR_UPDATE_STATUS %s" reason;
let (new_server, new_error) =
match msg_update with
| Ok env -> (env.server, None)
| Error (env, s) -> (env.server, Some s)
in
let telemetry =
Telemetry.create ()
|> Telemetry.string_opt
~key:"exit_status"
~value:(Option.map exit_status ~f:Exit_status.exit_code_to_string)
|> Telemetry.string_
~key:"informant_report"
~value:(Informant.show_report informant_report)
|> Telemetry.string_
~key:"server_state"
~value:(Informant.show_server_state server_state)
|> Telemetry.string_
~key:"server"
~value:(ServerProcess.show_server_process env.server)
|> Telemetry.string_
~key:"new_server"
~value:(ServerProcess.show_server_process new_server)
|> Telemetry.string_opt ~key:"new_error" ~value:new_error
in
HackEventLogger.monitor_update_status reason telemetry
end;
msg_update
let rec check_and_run_loop
?(consecutive_throws = 0)
(env : env msg_update)
monitor_config
(socket : Unix.file_descr) : 'a =
let (env, consecutive_throws) =
try (check_and_run_loop_ env monitor_config socket, 0) with
| Unix.Unix_error (Unix.ECHILD, _, _) as exn ->
let e = Exception.wrap exn in
ignore
(Hh_logger.log
"check_and_run_loop_ threw with Unix.ECHILD. Exiting. - %s"
(Exception.get_backtrace_string e));
Exit.exit Exit_status.No_server_running_should_retry
| Watchman.Watchman_restarted ->
Exit.exit Exit_status.Watchman_fresh_instance
| Exit_status.Exit_with _ as exn ->
let e = Exception.wrap exn in
Exception.reraise e
| exn ->
let e = Exception.wrap exn in
if consecutive_throws > 500 then (
Hh_logger.log "Too many consecutive exceptions.";
Hh_logger.log
"Probably an uncaught exception rethrown each retry. Exiting. %s"
(Exception.to_string e);
HackEventLogger.monitor_giving_up_exception e;
Exit.exit (Exit_status.Uncaught_exception e)
);
Hh_logger.log
"check_and_run_loop_ threw with exception: %s"
(Exception.to_string e);
(env, consecutive_throws + 1)
in
let env =
match env with
| Error (e, msg) ->
Hh_logger.log
"Encountered error in check_and_run_loop: %s, starting new loop"
msg;
Ok e
| Ok e -> Ok e
in
check_and_run_loop ~consecutive_throws env monitor_config socket
and check_and_run_loop_
(env : env msg_update) monitor_config (socket : Unix.file_descr) :
env msg_update =
(* WARNING! Don't use the (slow) HackEventLogger here, in the inner loop non-failure path. *)
(* That's because HackEventLogger for the monitor is synchronous and takes 50ms/call. *)
(* But the monitor's non-failure inner loop must handle hundres of clients per second *)
env >>= fun env ->
let lock_file = monitor_config.lock_file in
if not (Lock.grab lock_file) then (
(* e.g. (conjectured) tmpcleaner deletes the .lock file we have a lock on, and another instance of hh_server
starts up and acquires its own lock on a lockfile by the same name; our "Lock.grab" will return false because
we're unable to grab a lock on the file currently under pathname "lock_file".
Or, maybe users just manually deleted the file. *)
Hh_logger.log "Lost lock; terminating.\n%!";
HackEventLogger.lock_stolen lock_file;
Exit.exit Exit_status.Lock_stolen
);
let sequence_receipt_high_water_mark =
match env.server with
| ServerProcess.Alive process_data ->
let pid = process_data.ServerProcess.pid in
MonitorRpc.read_server_receipt_to_monitor_file
~server_receipt_to_monitor_file:
(ServerFiles.server_receipt_to_monitor_file pid)
|> Option.value ~default:0
| _ -> 0
in
let env = maybe_push_purgatory_clients (Ok env) in
(* The first sequence number we send is 1; hence, the default "0" will be a no-op *)
let () = Sent_fds_collector.collect_fds ~sequence_receipt_high_water_mark in
let has_client = sleep_and_check socket in
let env = update_status env monitor_config in
if not has_client then
(* Note: this call merely reads from disk; it doesn't go via the slow HackEventLogger. *)
let () = EventLogger.recheck_disk_files () in
env
else
let (fd, _) =
try Unix.accept socket with
| exn ->
let e = Exception.wrap exn in
HackEventLogger.accepting_on_socket_exception e;
Hh_logger.log
"ACCEPTING_ON_SOCKET_EXCEPTION; closing client FD. %s"
(Exception.to_string e |> Exception.clean_stack);
Exception.reraise e
in
try ack_and_handoff_client env fd with
| Exit_status.Exit_with _ as exn ->
let e = Exception.wrap exn in
Exception.reraise e
| Unix.Unix_error (Unix.EINVAL, _, _) as exn ->
let e = Exception.wrap exn in
Hh_logger.log
"Ack_and_handoff failure; closing client FD: %s"
(Exception.get_ctor_string e);
ensure_fd_closed fd;
raise Exit_status.(Exit_with Socket_error)
| exn ->
let e = Exception.wrap exn in
let msg =
Printf.sprintf
"Ack_and_handoff failure; closing client FD: %s"
(Exception.get_ctor_string e)
in
Hh_logger.log "%s" msg;
ensure_fd_closed fd;
env >>= fun env -> Error (env, msg)
let check_and_run_loop_once (env, monitor_config, socket) =
let env = check_and_run_loop_ (Ok env) monitor_config socket in
match env with
| Ok env -> (env, monitor_config, socket)
| Error (env, msg) ->
Hh_logger.log "%s" msg;
(env, monitor_config, socket)
let start_monitor
~current_version
~waiting_client
~max_purgatory_clients
server_start_options
informant_init_env
monitor_config =
let socket = Socket.init_unix_socket monitor_config.socket_file in
(* If the client started the server, it opened an FD before forking, so it
* can be notified when the monitor socket is ready. The FD number was
* passed in program args. *)
Option.iter waiting_client ~f:(fun fd ->
let oc = Unix.out_channel_of_descr fd in
try
Out_channel.output_string oc (MonitorUtils.ready ^ "\n");
Out_channel.close oc
with
| (Sys_error _ | Unix.Unix_error _) as e ->
Printf.eprintf
"Caught exception while waking client: %s\n%!"
(Exn.to_string e));
(* It is essential that we initiate the Informant before the server if we
* want to give the opportunity for the Informant to truly take
* ownership over the lifetime of the server.
*
* This is because start_server won't actually start a server if it sees
* a hg update sentinel file indicating an hg update is in-progress.
* Starting the informant first ensures that its Watchman watch is started
* before we check for the hgupdate sentinel file - this is required
* for the informant to properly observe an update is complete without
* hitting race conditions. *)
let informant = Informant.init informant_init_env in
let server_process =
maybe_start_first_server server_start_options informant
in
let env =
{
informant;
max_purgatory_clients;
current_version;
purgatory_clients = Queue.create ();
server = server_process;
server_start_options;
retries = 0;
sql_retries = 0;
watchman_retries = 0;
ignore_hh_version = Informant.should_ignore_hh_version informant_init_env;
}
in
(env, monitor_config, socket)
let start_monitoring
~current_version
~waiting_client
~max_purgatory_clients
server_start_options
informant_init_env
monitor_config =
let (env, monitor_config, socket) =
start_monitor
~current_version
~waiting_client
~max_purgatory_clients
server_start_options
informant_init_env
monitor_config
in
check_and_run_loop (Ok env) monitor_config socket |
OCaml Interface | hhvm/hphp/hack/src/monitor/monitorMain.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 t
(** Start a monitor without running the check loop. Useful for testing. *)
val start_monitor :
current_version:Config_file.version ->
waiting_client:Unix.file_descr option ->
max_purgatory_clients:int ->
ServerController.server_start_options ->
Informant.init_env ->
MonitorUtils.monitor_config ->
t
(** Run the check loop once. Useful for testing. *)
val check_and_run_loop_once : t -> t
(** Start the monitor and repeatedly run the check and run loop.
* Does not return. *)
val start_monitoring :
current_version:Config_file.version ->
waiting_client:Unix.file_descr option ->
max_purgatory_clients:int ->
ServerController.server_start_options ->
Informant.init_env ->
MonitorUtils.monitor_config ->
'a |
OCaml | hhvm/hphp/hack/src/monitor/monitorStart.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.
*
*)
(**
* Hack for HipHop: type checker's server monitor code.
*
* This runs hh server in 1 of 3 ways:
1) Runs hh server in-process (check mode)
2) Runs a ServerMonitor in-process which will pass connections to a
daemonized hh server (non-detached mode).
3) Daemonizes a ServerMonitor which will pass connections to a daemonized
hh_server (detached mode).
*)
let () = Random.self_init ()
let make_tmp_dir () =
let tmpdir = Path.make (Tmp.temp_dir GlobalConfig.tmp_dir "files") in
Relative_path.set_path_prefix Relative_path.Tmp tmpdir
(** Main method of the server monitor daemon. The daemon is responsible for
listening to socket requests from hh_client, checking Build ID, and relaying
requests to the typechecker process. *)
let monitor_daemon_main
(options : ServerArgs.options) ~(proc_stack : string list) =
Folly.ensure_folly_init ();
let www_root = ServerArgs.root options in
ServerProgress.set_root www_root;
(* Check mode: --check means we'll start up the server and it will do a typecheck
and then terminate; in the absence of that flag, (1) if a monitor was already running
then we will exit immediately, and avoid side-effects like cycling the logfile;
(2) otherwise we'll start up the server and it will continue to run
and handle requests. *)
(if not (ServerArgs.check_mode options) then
let lock_file = ServerFiles.lock_file www_root in
if not (Lock.grab lock_file) then (
Printf.eprintf "Monitor lock file already exists: %s\n%!" lock_file;
Exit.exit Exit_status.No_error
));
(* Daemon mode (should_detach): --daemon means the caller already spawned
us in a new process, and it's now our responsibility to establish a logfile
and redirect stdout/err to it; in the absence of that flag, we'll just continue
to write to stdout/err as normal. *)
if ServerArgs.should_detach options then begin
let log_link = ServerFiles.monitor_log_link www_root in
(try Sys.rename log_link (log_link ^ ".old") with
| _ -> ());
let log_file_path = Sys_utils.make_link_of_timestamped log_link in
try Sys_utils.redirect_stdout_and_stderr_to_file log_file_path with
| e ->
Printf.eprintf "Can't write to logfile: %s\n%!" (Printexc.to_string e)
end;
Relative_path.set_path_prefix Relative_path.Root www_root;
let () = ServerLoadFlag.set_no_load (ServerArgs.no_load options) in
let init_id = Random_id.short_string () in
let (config, local_config) = ServerConfig.load ~silent:false options in
if not (Sys_utils.enable_telemetry ()) then
EventLogger.init_fake ()
else
HackEventLogger.init_monitor
~from:(ServerArgs.from options)
~custom_columns:(ServerArgs.custom_telemetry_data options)
~hhconfig_version:
(ServerConfig.version config |> Config_file.version_to_string_opt)
~rollout_flags:(ServerLocalConfig.to_rollout_flags local_config)
~rollout_group:local_config.ServerLocalConfig.rollout_group
~proc_stack
(ServerArgs.root options)
init_id
(Unix.gettimeofday ());
Sys_utils.set_signal
Sys.sigpipe
(Sys.Signal_handle (fun i -> Hh_logger.log "SIGPIPE(%d)" i));
(try ignore (Sys_utils.setsid ()) with
| Unix.Unix_error _ -> ());
ignore (make_tmp_dir ());
(match ServerArgs.custom_hhi_path options with
| None -> ignore (Hhi.get_hhi_root ())
| Some path ->
if Disk.file_exists path && Disk.is_directory path then (
Hh_logger.log "Custom hhi directory set to %s." path;
Hhi.set_custom_hhi_root (Path.make path)
) else (
Hh_logger.log "Custom hhi directory %s not found." path;
Exit.exit Exit_status.Input_error
));
(* Now that we've got an exclusive lock and all globals have been initialized: *)
ServerProgress.write "monitor initializing...";
Exit.add_hook_upon_clean_exit (fun _finale_data ->
ServerProgress.try_delete ());
if ServerArgs.check_mode options then (
Hh_logger.log "%s" "Will run once in check mode then exit.";
ServerMain.run_once options config local_config
) else
let current_version = ServerConfig.version config in
let waiting_client = ServerArgs.waiting_client options in
let ServerLocalConfig.Watchman.
{ debug_logging; subscribe = allow_subscriptions; _ } =
local_config.ServerLocalConfig.watchman
in
let informant_options =
{
Informant.root = ServerArgs.root options;
allow_subscriptions;
use_dummy = local_config.ServerLocalConfig.use_dummy_informant;
watchman_debug_logging =
ServerArgs.watchman_debug_logging options || debug_logging;
min_distance_restart =
local_config.ServerLocalConfig.informant_min_distance_restart;
ignore_hh_version = ServerArgs.ignore_hh_version options;
is_saved_state_precomputed =
(match ServerArgs.with_saved_state options with
| Some (ServerArgs.Saved_state_target_info _) -> true
| _ -> false);
}
in
Utils.try_finally
~f:(fun () ->
MonitorMain.start_monitoring
~current_version
~waiting_client
~max_purgatory_clients:
local_config.ServerLocalConfig.max_purgatory_clients
options
informant_options
MonitorUtils.
{
socket_file = ServerFiles.socket_file www_root;
lock_file = ServerFiles.lock_file www_root;
server_log_file = ServerFiles.log_link www_root;
monitor_log_file = ServerFiles.monitor_log_link www_root;
})
~finally:ServerProgress.try_delete
let daemon_entry =
Daemon.register_entry_point
"monitor_daemon_main"
(fun ((options, proc_stack) : ServerArgs.options * string list) (_ic, _oc)
-> monitor_daemon_main options ~proc_stack)
(** Either starts a monitor daemon (which will spawn a typechecker daemon),
or just runs the typechecker if detachment not enabled. *)
let start () =
(* TODO: Catch all exceptions that make it this high, log them, and exit with
* the proper code *)
try
(* This avoids dying if SIGUSR{1,2} is received by accident: *)
Sys_utils.set_signal Sys.sigusr1 Sys.Signal_ignore;
Sys_utils.set_signal Sys.sigusr2 Sys.Signal_ignore;
(* This call might not return: *)
Daemon.check_entry_point ();
(* This allows us to measure cgroups relative to what it was at startup: *)
CgroupProfiler.get_initial_reading () |> CgroupProfiler.use_initial_reading;
(* Yet more initialization: *)
Folly.ensure_folly_init ();
let proc_stack = Proc.get_proc_stack (Unix.getpid ()) in
let options = ServerArgs.parse_options () in
if ServerArgs.should_detach options then begin
let (_ : (unit, unit) Daemon.handle) =
Daemon.spawn
(Daemon.null_fd (), Unix.stdout, Unix.stderr)
daemon_entry
(options, proc_stack)
in
Printf.eprintf "Running in daemon mode\n";
Exit.exit Exit_status.No_error
end else
monitor_daemon_main options ~proc_stack
with
| SharedMem.Out_of_shared_memory -> Exit.exit Exit_status.Out_of_shared_memory |
OCaml Interface | hhvm/hphp/hack/src/monitor/monitorStart.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val start : unit -> unit |
OCaml | hhvm/hphp/hack/src/monitor/monitorUtils.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type monitor_config = {
socket_file: string;
(** The socket file on which the monitor is listening for connections. *)
lock_file: string; (** This lock is held when a monitor is alive. *)
server_log_file: string; (** The path to the server log file *)
monitor_log_file: string; (** The path to the monitor log file *)
}
(* In an Informant-directed restart, Watchman provided a new
* mergebase, a new clock, and a list of files changed w.r.t.
* that mergebase.
*
* A new server instance can "resume" from that new mergebase
* given that it handles the list of files changed w.r.t. that
* new mergebase, and just starts a watchman subscription
* beginning with that clock.
*)
type watchman_mergebase = {
(* Watchman says current repo mergebase is this. *)
mergebase_global_rev: int;
(* ... plus these files changed to represent its current state *)
files_changed: SSet.t; [@printer SSet.pp_large]
(* ...as of this clock *)
watchman_clock: string;
}
[@@deriving show]
let watchman_mergebase_to_string
{ mergebase_global_rev; files_changed; watchman_clock } =
Printf.sprintf
"watchman_mergebase (mergebase_global_rev: %d; files_changed count: %d; watchman_clock: %s)"
mergebase_global_rev
(SSet.cardinal files_changed)
watchman_clock
type build_mismatch_info = {
existing_version: string;
existing_build_commit_time: string;
existing_argv: string list;
existing_launch_time: float;
}
[@@deriving show]
let current_build_info =
{
existing_version = Build_id.build_revision;
existing_build_commit_time = Build_id.build_commit_time_string;
existing_argv = Array.to_list Sys.argv;
existing_launch_time = Unix.gettimeofday ();
}
type connect_failure_reason =
| Connect_timeout
| Connect_exception of Exception.t
[@printer
fun fmt e ->
fprintf fmt "Connect_exception(%s)" (Exception.get_ctor_string e)]
[@@deriving show { with_path = false }]
type connect_failure_phase =
| Connect_open_socket
| Connect_send_version
| Connect_send_newline
| Connect_receive_connection_ok
| Connect_send_shutdown
[@@deriving show { with_path = false }]
type connect_to_monitor_failure = {
server_exists: bool;
(** This reflects the state of the lock file shortly after the failure happened. *)
failure_phase: connect_failure_phase;
failure_reason: connect_failure_reason;
}
[@@deriving show]
type connection_error =
| Connect_to_monitor_failure of connect_to_monitor_failure
| Server_died
| Server_dormant
(** Server dormant, i.e. waiting for a rebase to settle, and monitor's queue
of pending connections in the now-full queue of connections waiting for the next server. *)
| Server_dormant_out_of_retries
| Build_id_mismatched_monitor_will_terminate of build_mismatch_info option
(* hh_client binary is a different version from hh_server binary,
so hh_server will terminate. *)
| Build_id_mismatched_client_must_terminate of build_mismatch_info
(* hh_client binary is a different version and must abandon its connection attempt *)
[@@deriving show { with_path = false }]
(** The telemetry we get from this ends up appearing in our telemetry a HUGE number of times.
I guess [HackEventLogger.client_connect_once_failure] is just called a lot.
We therefore take pains to make this as minimal as we can. *)
let connection_error_to_telemetry (e : connection_error) :
string * Telemetry.t option =
match e with
| Server_died
| Server_dormant
| Server_dormant_out_of_retries
| Build_id_mismatched_monitor_will_terminate _
| Build_id_mismatched_client_must_terminate _ ->
(* these errors come from MonitorConnection.connect_to_monitor [match cstate] *)
(show_connection_error e, None)
| Connect_to_monitor_failure { server_exists; failure_phase; failure_reason }
->
let (reason, stack) =
match failure_reason with
| Connect_timeout ->
(* comes from MonitorConnection.connect_to_monitor [Timeout.open_connection] *)
("Connect_timeout", None)
| Connect_exception e -> begin
(* comes from MonitorConnection.connect_to_monitor and [phase] says what part *)
match Exception.to_exn e with
| Unix.Unix_error (Unix.ECONNREFUSED, "connect", _) ->
(* Generally comes from [Timeout.open_connection] *)
("ECONNREFUSED", None)
| Unix.Unix_error (Unix.ENOENT, "connect", _) ->
(* Generally comes from [Timeout.open_connection] *)
("ENOENT", None)
| Unix.Unix_error (Unix.EMFILE, "pipe", _) ->
(* Usually comes from [Process.exec Exec_command.Pgrep] *)
("EMFILE", None)
| Unix.Unix_error (Unix.ECONNRESET, "read", _) ->
(* Usually from [let cstate : ... = from_channel_without_buffering ic] *)
("ECONNRESET", None)
| _ ->
( Exception.get_ctor_string e,
Some (Exception.get_backtrace_string e |> Exception.clean_stack) )
end
in
let exists =
if server_exists then
"exists"
else
"absent"
in
let reason =
Printf.sprintf
"%s:%s [%s]"
(show_connect_failure_phase failure_phase)
reason
exists
in
let telemetry =
Option.map
~f:(fun value ->
Telemetry.create () |> Telemetry.string_ ~key:"stack" ~value)
stack
in
(reason, telemetry)
(** The first part of the client/monitor handshake is that client sends
a [VersionPayload.serialized] over the socket, followed by a newline byte.
Note that [VersionPayload.serialized] is just an ocaml string, and can
never be anything else, because we have to maintain forwards and backwards
compatibility between different version of hh_client and hh_server. *)
module VersionPayload = struct
type serialized = string
type t = {
client_version: string;
tracker_id: string;
terminate_monitor_on_version_mismatch: bool;
}
let serialize
~(tracker : Connection_tracker.t)
~(terminate_monitor_on_version_mismatch : bool) : serialized =
Hh_json.JSON_Object
[
("client_version", Hh_json.string_ Build_id.build_revision);
("tracker_id", Hh_json.string_ (Connection_tracker.log_id tracker));
( "terminate_monitor_on_version_mismatch",
Hh_json.bool_ terminate_monitor_on_version_mismatch );
]
|> Hh_json.json_to_string
let deserialize (s : serialized) : (t, string) result =
let open Hh_prelude.Result.Monad_infix in
(* Newer clients send version in a json object; older clients sent just a client_version string *)
(if String.is_prefix s ~prefix:"{" then
try Ok (Hh_json.json_of_string s) with
| exn -> Error (Exn.to_string exn)
else
Ok (Hh_json.JSON_Object [("client_version", Hh_json.string_ s)]))
>>= fun json ->
Hh_json_helpers.Jget.string_opt (Some json) "client_version"
|> Result.of_option ~error:"Missing client_version"
>>= fun client_version ->
let tracker_id =
Hh_json_helpers.Jget.string_opt (Some json) "tracker_id"
|> Option.value ~default:"t#?"
in
let terminate_monitor_on_version_mismatch =
Hh_json_helpers.Jget.bool_opt
(Some json)
"terminate_monitor_on_version_mismatch"
|> Option.value ~default:true
in
Ok { client_version; tracker_id; terminate_monitor_on_version_mismatch }
end
(** The second part of the client/monitor handshake is that monitor sends
[connection_state] over the socket. In case of version mismatch it sends
[Build_id_mismatch_v3], which includes a [MismatchPayload.serialized].
Note that this is just an ocaml string, and can never be anything else,
because we have to maintain forwards and backwards compatibility between
different versions of hh_client and hh_server. (However, every version
in existince understands the binary format of Build_id_mismatch_v3...) *)
module MismatchPayload = struct
type serialized = string [@@deriving show]
type t = { monitor_will_terminate: bool }
let serialize ~(monitor_will_terminate : bool) : serialized =
Hh_json.JSON_Object
[("monitor_will_terminate", Hh_json.bool_ monitor_will_terminate)]
|> Hh_json.json_to_string
let deserialize (s : serialized) : (t, string) result =
let open Hh_prelude.Result.Monad_infix in
(try Ok (Hh_json.json_of_string s) with
| exn -> Error (Exn.to_string exn))
>>= fun json ->
let monitor_will_terminate =
Hh_json_helpers.Jget.bool_opt (Some json) "monitor_will_terminate"
|> Option.value ~default:true
in
Ok { monitor_will_terminate }
end
type connection_state =
| Connection_ok
| Build_id_mismatch
(** Build_is_mismatch is never used, but it can't be removed, because
the sequence of constructors here is part of the binary protocol
we want to support between mismatched versions of client_server. *)
| Build_id_mismatch_ex of build_mismatch_info
(** Build_id_mismatch_ex also isn't used. *)
| Build_id_mismatch_v3 of build_mismatch_info * MismatchPayload.serialized
(** Build_id_mismatch_v3 is used! *)
| Connection_ok_v2 of string
(** Connection_ok_v2 isn't used yet, but might be *)
[@@deriving show]
(* Result of a shutdown monitor RPC. *)
type shutdown_result =
(* Request sent and channel hung up, indicating the process has exited. *)
| SHUTDOWN_VERIFIED
(* Request sent, but channel hasn't hung up. *)
| SHUTDOWN_UNVERIFIED
(* Message we send to the --waiting-client *)
let ready = "ready" |
OCaml | hhvm/hphp/hack/src/monitor/prehandoff.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 exit_status = {
status: Unix.process_status;
was_oom: bool;
}
type msg =
(* Last of the prehandoff messages; includes finale_file_name of server. *)
| Sentinel of ServerCommandTypes.server_specific_files
(* The monitor keeps a queue of connections that will need to be passed
* onto the next server instance. This queue has a size limit that has been
* reached. *)
| Server_dormant_connections_limit_reached
(* Monitor is running but has no server - i.e. dormant. Connection has been
* placed on a queue to be sent to the next started server. *)
| Server_not_alive_dormant of string
(* Server process died. Connect another client to start another one. *)
| Server_died of exit_status
(* Server died from a config change, and the Monitor didn't automatically
* start a new one because a version change in the config file. *)
| Server_died_config_change |
OCaml | hhvm/hphp/hack/src/monitor/serverController.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.
*
*)
(** Responsible for starting up a Hack server process. *)
type pipe_type =
| Default
| Priority
| Force_dormant_start_only
let pipe_type_to_string = function
| Default -> "default"
| Priority -> "priority"
| Force_dormant_start_only -> "force_dormant_start_only"
let start_server_daemon
~informant_managed
options
log_link
(daemon_entry : (ServerMain.params, _, _) Daemon.entry) =
let log_fds =
let in_fd = Daemon.null_fd () in
if ServerArgs.should_detach options then (
(try
let old_log_name i = Printf.sprintf "%s.%d.old" log_link i in
let max_n_log_files = 20 in
for i = max_n_log_files - 1 downto 1 do
if Sys.file_exists (old_log_name i) then
Sys.rename (old_log_name i) (old_log_name (i + 1))
done;
let old = log_link ^ ".old" in
if Sys.file_exists old then Sys.rename old (old_log_name 1);
if Sys.file_exists log_link then Sys.rename log_link old
with
| _ -> ());
let log_file = Sys_utils.make_link_of_timestamped log_link in
Hh_logger.log
"About to spawn typechecker daemon. Logs will go to %s\n%!"
(if Sys.win32 then
log_file
else
log_link);
let fd = Daemon.fd_of_path log_file in
(in_fd, fd, fd)
) else (
Hh_logger.log "About to spawn typechecker daemon. Logs will go here.";
(in_fd, Unix.stdout, Unix.stderr)
)
in
let start_t = Unix.time () in
let state = ServerGlobalState.save ~logging_init:(fun () -> ()) in
let monitor_pid = Unix.getpid () in
(* Setting some additional channels between monitor and server *)
let (parent_priority_fd, child_priority_fd) =
Unix.socketpair Unix.PF_UNIX Unix.SOCK_STREAM 0
in
let () = Unix.set_close_on_exec parent_priority_fd in
let () = Unix.clear_close_on_exec child_priority_fd in
let ( parent_force_dormant_start_only_fd,
child_force_dormant_start_only_force_fd ) =
Unix.socketpair Unix.PF_UNIX Unix.SOCK_STREAM 0
in
let () = Unix.set_close_on_exec parent_force_dormant_start_only_fd in
let () = Unix.clear_close_on_exec child_force_dormant_start_only_force_fd in
let { Daemon.pid; Daemon.channels = (ic, oc) } =
Daemon.spawn
~channel_mode:`socket
log_fds
daemon_entry
{
ServerMain.informant_managed;
state;
options;
monitor_pid;
priority_in_fd = child_priority_fd;
force_dormant_start_only_in_fd = child_force_dormant_start_only_force_fd;
}
in
Unix.close child_priority_fd;
Unix.close child_force_dormant_start_only_force_fd;
Hh_logger.log "Just started typechecker server with pid: %d." pid;
(* We'll write an initial progress message to guarantee that the client will
certainly be able to read the progress file as soon as it learns the progress filename.
There's a benign race as to whether our message is written first, or whether the server
started up quickly enough to write its initial message first. It's benign because
either message will communicate the right intent to the user, and in any case the server
will always have further progress updates to write. *)
ServerProgress.write "starting hh_server";
let server =
ServerProcess.
{
pid;
server_specific_files =
{
ServerCommandTypes.server_finale_file =
ServerFiles.server_finale_file pid;
};
in_fd = Daemon.descr_of_in_channel ic;
out_fds =
[
(pipe_type_to_string Default, Daemon.descr_of_out_channel oc);
(pipe_type_to_string Priority, parent_priority_fd);
( pipe_type_to_string Force_dormant_start_only,
parent_force_dormant_start_only_fd );
];
start_t;
last_request_handoff = ref (Unix.time ());
}
in
server
let start_hh_server ~informant_managed options =
let log_link = ServerFiles.log_link (ServerArgs.root options) in
start_server_daemon ~informant_managed options log_link ServerMain.entry
type server_start_options = ServerArgs.options
let start_server ~informant_managed ~prior_exit_status options =
match prior_exit_status with
| Some c
when (c = Exit_status.(exit_code Sql_assertion_failure))
|| (c = Exit_status.(exit_code Sql_cantopen))
|| (c = Exit_status.(exit_code Sql_corrupt))
|| c = Exit_status.(exit_code Sql_misuse) ->
start_hh_server ~informant_managed (ServerArgs.set_no_load options true)
| _ -> start_hh_server ~informant_managed options
let kill_server ~violently process =
if not violently then begin
Hh_logger.log "kill_server: sending SIGUSR2 to %d" process.ServerProcess.pid;
try Unix.kill process.ServerProcess.pid Sys.sigusr2 with
| _ -> ()
end else begin
Hh_logger.log
"Failed to send sigusr2 signal to server process. Trying violently";
try Unix.kill process.ServerProcess.pid Sys.sigkill with
| exn ->
let e = Exception.wrap exn in
Hh_logger.exception_ ~prefix:"Failed to violently kill server process: " e
end
let wait_for_server_exit ~(timeout_t : float) process =
let rec wait_for_server_exit_impl () =
let now_t = Unix.gettimeofday () in
if now_t > timeout_t then
false
else
let exit_status =
Unix.waitpid [Unix.WNOHANG; Unix.WUNTRACED] process.ServerProcess.pid
in
match exit_status with
| (0, _) ->
Unix.sleep 1;
wait_for_server_exit_impl ()
| _ -> true
in
wait_for_server_exit_impl ()
let wait_pid process =
Unix.waitpid [Unix.WNOHANG; Unix.WUNTRACED] process.ServerProcess.pid
let is_saved_state_precomputed = ServerArgs.is_using_precomputed_saved_state |
OCaml Interface | hhvm/hphp/hack/src/monitor/serverController.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 pipe_type =
| Default
| Priority
| Force_dormant_start_only
val pipe_type_to_string : pipe_type -> string
type server_start_options = ServerArgs.options
(** Start the server. Optionally takes in the exit code of the previously
running server that exited. *)
val start_server :
informant_managed:bool ->
prior_exit_status:int option ->
server_start_options ->
ServerProcess.process_data
val kill_server : violently:bool -> ServerProcess.process_data -> unit
val wait_for_server_exit : timeout_t:float -> ServerProcess.process_data -> bool
val wait_pid : ServerProcess.process_data -> int * Unix.process_status
val is_saved_state_precomputed : server_start_options -> bool |
OCaml | hhvm/hphp/hack/src/monitor/serverProcess.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 process_data = {
pid: int; (** Process ID. *)
server_specific_files: ServerCommandTypes.server_specific_files; [@opaque]
start_t: float;
in_fd: Unix.file_descr; [@opaque]
(** Get occasional updates about status/busyness from typechecker here. *)
out_fds: (string * Unix.file_descr) list; [@opaque]
(** Send client's File Descriptors to the typechecker over this. *)
last_request_handoff: float ref;
}
[@@deriving show]
type server_process =
| Not_yet_started
| Alive of process_data
(* When the server crashes, we want to track that it has crashed and report
* that crash info to the next hh_client that connects. We keep that info
* here. *)
| Died_unexpectedly of
(Unix.process_status
[@printer
fun fmt s ->
let (how, code) =
match s with
| Unix.WEXITED c -> ("WEXITED", c)
| Unix.WSIGNALED c -> ("WSIGNALED", c)
| Unix.WSTOPPED c -> ("WSTOPPED", c)
in
fprintf fmt "<%s %d>" how code])
* bool
(*
* The problem we need to solve is this: when the Monitor wants to start
* a new Server instance, it might not be safe to do so because we might
* end up running the a version of the Server not meant for this state of
* the repo (as specified in the .hhconfig file).
*
* Monitor might want to start a Server because the last one died (crashed,
* or exited due to hhconfig change), or the Informant has decided to start
* a new instance on a better saved state. Because the .hhconfig file has
* indicated a version change is occuring and the logic to parse this version
* change and locate the binaries for that version are not inside server
* code, we need to force that logic to be exercised on the user side, and
* only start a new server after we've confirmed that it has been exercised
* (which is confirmed by a new client connecting and succeeding the build_id
* handshake; alternatively, failing that handshake and then this Monitor
* correctly exits).
*
* So, whenever we want to start a new Server, the Monitor must check the
* hhconfig file's version number. If it doesn't match the version at the
* time of this Monitor's startup, we enter this state Died_config_changed.
*
* Only a new client connection after entering this state can transition
* use away from this state.
*
* NB: Monitor could be mid-way handling a new client connection when it
* processes the next Informant decision. In which case, we can't guarantee
* that the client that connected did in fact exercise the version lookup
* logic; so the only safe thing to do is enter the Died_config_changed
* state until the *next* client that connects.
*
* These transitions are centralized in MonitorMain.kill_and_maybe_restart_server
* Don't do them elsewhere or you will screw it up.
*
* State transition looks sort of like:
*
*
* [ Died_config_changed ]
* ^ \
* / \ new client connection
* maybe / \ connection triggers
* restart but / \ maybe_restart which actually
* config not mat/ching \ does start one this time
* / \
* / \
* [ Any server state ]-------------> [ new server instance ]
* restart
* and
* config
* matches
*
*
* Why don't we just exit the Monitor automatically, instead of keeping it
* around with a server in this Died_config_changed state? We want Nuclide
* to know that things are dandy and it should retry connecting without
* the user having to click anything.
*)
| Died_config_changed
[@@deriving show] |
TOML | hhvm/hphp/hack/src/naming/Cargo.toml | # @generated by autocargo
[package]
name = "naming_special_names_rust"
version = "0.0.0"
edition = "2021"
[lib]
path = "naming_special_names.rs"
[dependencies]
hash = { version = "0.0.0", path = "../utils/hash" }
lazy_static = "1.4"
serde = { version = "1.0.176", features = ["derive", "rc"] }
write_bytes = { version = "0.0.0", path = "../utils/write_bytes/write_bytes" } |
hhvm/hphp/hack/src/naming/dune | (library
(name naming_special_names)
(modules naming_special_names)
(libraries collections core_kernel utils_core)
(preprocess
(pps ppx_deriving.std)))
(library
(name naming_error)
(wrapped false)
(modules naming_error name_context)
(libraries
ast
pos
pos_or_decl
error_codes
user_error))
(library
(name nast)
(modules nast)
(libraries annotated_ast naming_special_names user_error errors)
(preprocess
(pps ppx_deriving.std)))
(library
(name naming_attributes)
(modules naming_attributes)
(libraries annotated_ast core_kernel)
(preprocess
(pps ppx_deriving.std)))
(library
(name naming_attributes_params)
(modules naming_attributes_params)
(libraries
annotated_ast
naming_attributes
core_kernel
errors
naming_special_names
nast
nast_eval
pos)
(preprocess
(pps ppx_deriving.std)))
(library
(name naming_ast_print)
(modules naming_ast_print)
(libraries nast pos)
(preprocess
(pps ppx_deriving.std)))
(library
(name nast_eval)
(modules nast_eval)
(libraries annotated_ast errors nast pos)
(preprocess
(pps ppx_deriving.std)))
;
(library
(name naming_types)
(modules naming_types)
(libraries file_info)
(preprocess
(pps ppx_deriving.std)))
(library
(name naming_sqlite)
(modules naming_sqlite)
(libraries
file_info
fileutils
heap_shared_mem
heap_shared_mem_hash
logging
naming_types
relative_path
sqlite3
sqlite_utils
typing_deps)
(preprocess
(pps ppx_deriving.std)))
(library
(name naming_heap)
(modules naming_heap)
(libraries
ast_provider
db_path_provider
file_info
naming_sqlite
naming_types
provider_context
relative_path)
(preprocess
(pps ppx_deriving.std)))
(library
(name naming_table)
(modules naming_table)
(libraries
ast_provider
db_path_provider
file_info
future
global_config
naming_provider
naming_sqlite
relative_path
temp_file)
(preprocess
(pps ppx_deriving.std)))
(library
(name naming_global)
(modules naming_global)
(libraries file_info naming_error naming_provider naming_table)
(preprocess
(pps ppx_deriving.std)))
(library
(name naming_captures)
(modules naming_captures)
(libraries nast naming_error)
(preprocess
(pps ppx_deriving.std)))
(library
(name naming_elaborate_namespaces_endo)
(modules naming_elaborate_namespaces_endo)
(libraries annotated_ast nast parser)
(preprocess
(pps ppx_deriving.std)))
(library
(name elab_ffi)
(modules)
(wrapped false)
(foreign_archives elab_ffi))
(rule
(targets libelab_ffi.a)
(deps
(source_tree %{workspace_root}/hack/src))
(locks /cargo)
(action
(run
%{workspace_root}/hack/scripts/invoke_cargo.sh
elab_ffi
elab_ffi)))
(library
(name naming)
(modules
naming
naming_elab_as_expr
naming_elab_block
naming_elab_call
naming_elab_class_id
naming_elab_class_members
naming_elab_collection
naming_elab_const_expr
naming_elab_defs
naming_elab_dynamic_class_name
naming_elab_enum_class
naming_elab_everything_sdt
naming_elab_func_body
naming_elab_haccess_hint
naming_elab_happly_hint
naming_elab_hkt
naming_elab_import
naming_elab_invariant
naming_elab_lvar
naming_elab_retonly_hint
naming_elab_shape_field_name
naming_elab_soft
naming_elab_this_hint
naming_elab_tuple
naming_elab_user_attributes
naming_elab_wildcard_hint
naming_guard_invalid
naming_phase_env
naming_phase_error
naming_phase_pass
naming_typed_locals
naming_validate_cast_expr
naming_validate_class_req
naming_validate_consistent_construct
naming_validate_dynamic_hint
naming_validate_fun_params
naming_validate_like_hint
naming_validate_module
naming_validate_supportdyn
naming_validate_xhp_name
)
(libraries
ast
ast_provider
common
file_provider
fileutils
full_fidelity
naming_attributes
naming_captures
naming_elaborate_namespaces_endo
naming_error
nast_check_error
naming_table
naming_global
naming_provider
nast
provider_backend
substitution_mutation
typing_deps
typechecker_options
user_error)
(foreign_archives elab_ffi)
(preprocess
(pps ppx_deriving.std))) |
|
Rust | hhvm/hphp/hack/src/naming/elaborate_namespaces_visitor.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.
#![feature(box_patterns)]
use std::sync::Arc;
use core_utils_rust as core_utils;
use hash::HashSet;
use namespaces_rust as namespaces;
use naming_special_names_rust as sn;
use oxidized::aast_visitor::AstParams;
use oxidized::aast_visitor::NodeMut;
use oxidized::aast_visitor::VisitorMut;
use oxidized::ast::*;
use oxidized::namespace_env;
fn is_special_identifier(name: &str) -> bool {
use lazy_static::lazy_static;
lazy_static! {
static ref SPECIAL_IDENTIFIERS: HashSet<&'static str> = vec![
sn::members::M_CLASS,
sn::classes::PARENT,
sn::classes::SELF,
sn::classes::STATIC,
sn::special_idents::THIS,
sn::special_idents::DOLLAR_DOLLAR,
sn::typehints::WILDCARD,
]
.into_iter()
.collect();
}
SPECIAL_IDENTIFIERS.contains(&name)
}
#[derive(Clone)]
struct Env {
// TODO(hrust) I wanted to make namespace and type_params str's references but couldn't
// find a way to specify that the lifetimes of these outlived the node I was taking them from
namespace: std::sync::Arc<namespace_env::Env>,
type_params: HashSet<String>,
}
impl Env {
fn make(namespace: std::sync::Arc<namespace_env::Env>) -> Self {
Self {
namespace,
type_params: HashSet::default(),
}
}
// TODO: While elaboration for codegen and typing is similar, there are currently a
// couple differences between the two and are toggled by this flag (XHP).
// It would be nice to eventually eliminate the discrepancies between the two.
pub fn in_codegen(&self) -> bool {
self.namespace.is_codegen
}
fn extend_tparams(&mut self, tparaml: &[Tparam]) {
for tparam in tparaml {
self.type_params.insert(tparam.name.1.clone());
}
}
fn elaborate_type_name(&self, id: &mut Id) {
let name = &id.1;
if !self.type_params.contains::<str>(name)
&& !is_special_identifier(name)
&& !name.starts_with('$')
{
namespaces::elaborate_id(&self.namespace, namespaces::ElaborateKind::Class, id);
}
}
fn handle_special_calls(&self, call: &mut Expr_) {
if let Expr_::Call(box CallExpr {
func: Expr(_, _, Expr_::Id(id)),
args,
..
}) = call
{
if !self.in_codegen()
&& args.len() == 2
&& id.1 == sn::autoimported_functions::METH_CALLER
{
if let Expr(_, p, Expr_::String(fn_name)) = &args[0].1 {
let fn_name = core_utils::add_ns_bstr(fn_name);
args[0].1 = Expr((), p.clone(), Expr_::String(fn_name.into_owned().into()));
}
}
}
}
fn with_ns(&self, namespace: Arc<namespace_env::Env>) -> Self {
Self {
namespace,
type_params: self.type_params.clone(),
}
}
}
fn contexts_ns() -> Arc<namespace_env::Env> {
Arc::new(namespace_env::Env {
name: Some(sn::coeffects::CONTEXTS.to_owned()),
..namespace_env::Env::empty(
vec![],
// These default values seem obviously wrong, but they're what's
// used in the OCaml visitor at the moment. Since we don't elaborate
// context names in codegen, perhaps these settings don't end up
// being relevant.
oxidized::global_options::GlobalOptions::default().po_codegen,
oxidized::global_options::GlobalOptions::default().po_disable_xhp_element_mangling,
)
})
}
fn unsafe_contexts_ns() -> Arc<namespace_env::Env> {
Arc::new(namespace_env::Env {
name: Some(sn::coeffects::UNSAFE_CONTEXTS.to_owned()),
..namespace_env::Env::empty(
vec![],
// As above, these look wrong, but may be irrelevant.
oxidized::global_options::GlobalOptions::default().po_codegen,
oxidized::global_options::GlobalOptions::default().po_disable_xhp_element_mangling,
)
})
}
fn is_reserved_type_hint(name: &str) -> bool {
let base_name = core_utils::strip_ns(name);
sn::typehints::is_reserved_type_hint(base_name)
}
struct ElaborateNamespacesVisitor {}
impl ElaborateNamespacesVisitor {
fn on_class_ctx_const(&mut self, env: &mut Env, kind: &mut ClassTypeconst) -> Result<(), ()> {
match kind {
ClassTypeconst::TCConcrete(ClassConcreteTypeconst { c_tc_type }) => {
self.on_ctx_hint_ns(&contexts_ns(), env, c_tc_type)
}
ClassTypeconst::TCAbstract(ClassAbstractTypeconst {
as_constraint,
super_constraint,
default,
}) => {
let ctx_ns = contexts_ns();
if let Some(as_constraint) = as_constraint {
self.on_ctx_hint_ns(&ctx_ns, env, as_constraint)?;
}
if let Some(super_constraint) = super_constraint {
self.on_ctx_hint_ns(&ctx_ns, env, super_constraint)?;
}
if let Some(default) = default {
self.on_ctx_hint_ns(&ctx_ns, env, default)?;
}
Ok(())
}
}
}
fn on_contexts_ns(
&mut self,
ctx_ns: &Arc<namespace_env::Env>,
env: &mut Env,
ctxs: &mut Contexts,
) -> Result<(), ()> {
for ctx in &mut ctxs.1 {
self.on_ctx_hint_ns(ctx_ns, env, ctx)?;
}
Ok(())
}
fn on_ctx_hint_ns(
&mut self,
ctx_ns: &Arc<namespace_env::Env>,
env: &mut Env,
h: &mut Context,
) -> Result<(), ()> {
let ctx_env = &mut env.with_ns(Arc::clone(ctx_ns));
fn is_ctx_user_defined(ctx: &str) -> bool {
match ctx.rsplit('\\').next() {
Some(ctx_name) if !ctx_name.is_empty() => {
ctx_name.chars().next().unwrap().is_uppercase()
}
_ => false,
}
}
match h {
Hint(_, box Hint_::Happly(ctx, hl)) if !is_reserved_type_hint(&ctx.1) => {
if is_ctx_user_defined(&ctx.1) {
env.elaborate_type_name(ctx)
} else {
ctx_env.elaborate_type_name(ctx)
};
hl.recurse(env, self.object())?;
}
Hint(_, box Hint_::Hintersection(ctxs)) => {
for ctx in ctxs {
self.on_ctx_hint_ns(ctx_ns, env, ctx)?;
}
}
Hint(_, box Hint_::Haccess(root, _)) => root.recurse(env, self.object())?,
_ => h.recurse(ctx_env, self.object())?,
}
Ok(())
}
}
impl<'ast> VisitorMut<'ast> for ElaborateNamespacesVisitor {
type Params = AstParams<Env, ()>;
fn object(&mut self) -> &mut dyn VisitorMut<'ast, Params = Self::Params> {
self
}
// Namespaces were already precomputed by ElaborateDefs
// The following functions just set the namespace env correctly
fn visit_class_(&mut self, env: &mut Env, cd: &mut Class_) -> Result<(), ()> {
let env = &mut env.clone();
env.namespace = Arc::clone(&cd.namespace);
env.extend_tparams(&cd.tparams);
cd.recurse(env, self.object())
}
fn visit_ctx_refinement(&mut self, env: &mut Env, cr: &mut CtxRefinement) -> Result<(), ()> {
if env.in_codegen() {
return cr.recurse(env, self.object());
}
match cr {
CtxRefinement::CRexact(h) => self.on_ctx_hint_ns(&contexts_ns(), env, h),
CtxRefinement::CRloose(CtxRefinementBounds { lower, upper }) => {
let ctx_ns = contexts_ns();
if let Some(lower) = lower {
self.on_ctx_hint_ns(&ctx_ns, env, lower)?;
}
if let Some(upper) = upper {
self.on_ctx_hint_ns(&ctx_ns, env, upper)?;
}
Ok(())
}
}
}
fn visit_class_typeconst_def(
&mut self,
env: &mut Env,
tc: &mut ClassTypeconstDef,
) -> Result<(), ()> {
if !env.in_codegen() && tc.is_ctx {
self.on_class_ctx_const(env, &mut tc.kind)?;
}
tc.recurse(env, self.object())
}
fn visit_typedef(&mut self, env: &mut Env, td: &mut Typedef) -> Result<(), ()> {
let env = &mut env.clone();
env.namespace = Arc::clone(&td.namespace);
env.extend_tparams(&td.tparams);
if !env.in_codegen() && td.is_ctx {
let ctx_ns = &contexts_ns();
if let Some(as_constraint) = &mut td.as_constraint {
self.on_ctx_hint_ns(ctx_ns, env, as_constraint)?;
}
if let Some(super_constraint) = &mut td.super_constraint {
self.on_ctx_hint_ns(ctx_ns, env, super_constraint)?;
}
self.on_ctx_hint_ns(ctx_ns, env, &mut td.kind)?;
}
td.recurse(env, self.object())
}
fn visit_def(&mut self, env: &mut Env, def: &mut Def) -> Result<(), ()> {
if let Def::SetNamespaceEnv(nsenv) = def {
env.namespace = Arc::clone(nsenv);
}
def.recurse(env, self.object())
}
// Difference between FunDef and Fun_ is that Fun_ is also lambdas
fn visit_fun_def(&mut self, env: &mut Env, fd: &mut FunDef) -> Result<(), ()> {
let env = &mut env.clone();
env.namespace = Arc::clone(&fd.namespace);
env.extend_tparams(&fd.tparams);
fd.recurse(env, self.object())
}
fn visit_fun_(&mut self, env: &mut Env, f: &mut Fun_) -> Result<(), ()> {
if let Some(ctxs) = &mut f.ctxs {
self.on_contexts_ns(&contexts_ns(), env, ctxs)?;
}
if let Some(ctxs) = &mut f.unsafe_ctxs {
self.on_contexts_ns(&unsafe_contexts_ns(), env, ctxs)?;
}
f.recurse(env, self.object())
}
fn visit_method_(&mut self, env: &mut Env, m: &mut Method_) -> Result<(), ()> {
let env = &mut env.clone();
env.extend_tparams(&m.tparams);
if let Some(ctxs) = &mut m.ctxs {
self.on_contexts_ns(&contexts_ns(), env, ctxs)?;
}
if let Some(ctxs) = &mut m.unsafe_ctxs {
self.on_contexts_ns(&unsafe_contexts_ns(), env, ctxs)?;
}
m.recurse(env, self.object())
}
fn visit_tparam(&mut self, env: &mut Env, tparam: &mut Tparam) -> Result<(), ()> {
let env = &mut env.clone();
env.extend_tparams(&tparam.parameters);
tparam.recurse(env, self.object())
}
fn visit_gconst(&mut self, env: &mut Env, gc: &mut Gconst) -> Result<(), ()> {
let env = &mut env.clone();
env.namespace = Arc::clone(&gc.namespace);
gc.recurse(env, self.object())
}
fn visit_file_attribute(&mut self, env: &mut Env, fa: &mut FileAttribute) -> Result<(), ()> {
let env = &mut env.clone();
env.namespace = Arc::clone(&fa.namespace);
fa.recurse(env, self.object())
}
// I don't think we need to visit blocks because we got rid of let bindings :)
fn visit_catch(&mut self, env: &mut Env, catch: &mut Catch) -> Result<(), ()> {
let exception_sid = &mut catch.0;
env.elaborate_type_name(exception_sid);
catch.recurse(env, self.object())
}
// I don't think we need to visit stmts because we got rid of let bindings :)
// Lfun and Efun as Expr_:: nodes so update the env in visit_expr_
// Actually rewrites the names
fn visit_expr_(&mut self, env: &mut Env, e: &mut Expr_) -> Result<(), ()> {
// Sets env for lambdas
match e {
Expr_::Collection(box (id, c_targ_opt, flds)) if !env.in_codegen() => {
namespaces::elaborate_id(&env.namespace, namespaces::ElaborateKind::Class, id);
c_targ_opt.accept(env, self.object())?;
flds.accept(env, self.object())?;
}
Expr_::Call(box CallExpr {
func,
targs,
args,
unpacked_arg,
}) => {
// Recurse first due to borrow order
targs.accept(env, self.object())?;
args.accept(env, self.object())?;
unpacked_arg.accept(env, self.object())?;
if let Some(sid) = func.2.as_id_mut() {
if !sn::special_functions::is_special_function(&sid.1) {
namespaces::elaborate_id(
&env.namespace,
namespaces::ElaborateKind::Fun,
sid,
);
env.handle_special_calls(e);
}
} else {
func.accept(env, self.object())?;
}
}
Expr_::FunctionPointer(box (fpid, targs)) => {
if let Some(sid) = fpid.as_fpid_mut() {
namespaces::elaborate_id(&env.namespace, namespaces::ElaborateKind::Fun, sid);
} else if let Some(cc) = fpid.as_fpclass_const_mut() {
let type_ = cc.0;
if let Some(e) = type_.2.as_ciexpr_mut() {
if let Some(sid) = e.2.as_id_mut() {
env.elaborate_type_name(sid);
} else {
e.accept(env, self.object())?;
}
}
} else {
fpid.accept(env, self.object())?;
}
targs.accept(env, self.object())?;
}
Expr_::ObjGet(box (obj, expr, nullsafe, _)) => {
if let Expr_::Id(..) = expr.2 {
} else {
expr.accept(env, self.object())?;
}
obj.accept(env, self.object())?;
nullsafe.accept(env, self.object())?;
}
Expr_::Id(sid) if !((sid.1 == "NAN" || sid.1 == "INF") && env.in_codegen()) => {
namespaces::elaborate_id(&env.namespace, namespaces::ElaborateKind::Const, sid);
}
Expr_::New(box (class_id, targs, args, unpacked_el, _)) => {
if let Some(e) = class_id.2.as_ciexpr_mut() {
if let Some(sid) = e.2.as_id_mut() {
env.elaborate_type_name(sid);
} else {
e.accept(env, self.object())?;
}
} else {
class_id.accept(env, self.object())?;
}
targs.accept(env, self.object())?;
args.accept(env, self.object())?;
unpacked_el.accept(env, self.object())?;
}
Expr_::ClassConst(box (type_, _)) => {
if let Some(e) = type_.2.as_ciexpr_mut() {
if let Some(sid) = e.2.as_id_mut() {
env.elaborate_type_name(sid);
} else {
e.accept(env, self.object())?;
}
} else {
type_.accept(env, self.object())?;
}
}
Expr_::ClassGet(box (class_id, class_get_expr, _)) => {
if let Some(e) = class_id.2.as_ciexpr_mut() {
if let Some(sid) = e.2.as_id_mut() {
env.elaborate_type_name(sid);
} else {
e.accept(env, self.object())?;
}
} else {
class_id.accept(env, self.object())?;
}
class_get_expr.accept(env, self.object())?;
}
Expr_::Xml(box (xml_id, attributes, el)) => {
/* if XHP element mangling is disabled, namespaces are supported */
if !env.in_codegen() || env.namespace.disable_xhp_element_mangling {
env.elaborate_type_name(xml_id);
}
attributes.recurse(env, self.object())?;
el.recurse(env, self.object())?;
}
Expr_::EnumClassLabel(box (Some(sid), _)) if !env.in_codegen() => {
env.elaborate_type_name(sid);
}
_ => e.recurse(env, self.object())?,
}
Ok(())
}
fn visit_hint_(&mut self, env: &mut Env, hint: &mut Hint_) -> Result<(), ()> {
fn is_xhp_screwup(x: &str) -> bool {
x == "Xhp" || x == ":Xhp" || x == "XHP"
}
match hint {
Hint_::Happly(sid, _) if is_xhp_screwup(&sid.1) => {}
Hint_::Happly(sid, _) if is_reserved_type_hint(&sid.1) && !env.in_codegen() => {}
Hint_::Happly(sid, _) => {
env.elaborate_type_name(sid);
}
_ => {}
}
hint.recurse(env, self.object())
}
fn visit_hint_fun(&mut self, env: &mut Env, hf: &mut HintFun) -> Result<(), ()> {
if let Some(ctxs) = &mut hf.ctxs {
self.on_contexts_ns(&contexts_ns(), env, ctxs)?;
}
hf.recurse(env, self.object())
}
fn visit_shape_field_name(
&mut self,
env: &mut Env,
sfn: &mut ShapeFieldName,
) -> Result<(), ()> {
match sfn {
ShapeFieldName::SFclassConst(id, _) => {
env.elaborate_type_name(id);
}
_ => {}
}
sfn.recurse(env, self.object())
}
fn visit_user_attribute(&mut self, env: &mut Env, ua: &mut UserAttribute) -> Result<(), ()> {
if !sn::user_attributes::is_reserved(&ua.name.1) {
env.elaborate_type_name(&mut ua.name);
}
ua.recurse(env, self.object())
}
fn visit_xhp_child(&mut self, env: &mut Env, child: &mut XhpChild) -> Result<(), ()> {
match child {
XhpChild::ChildName(sid)
if !env.in_codegen()
&& !sn::xhp::is_reserved(&sid.1)
&& !sn::xhp::is_xhp_category(&sid.1) =>
{
env.elaborate_type_name(sid);
}
_ => {}
}
child.recurse(env, self.object())
}
}
pub fn elaborate_program(e: std::sync::Arc<namespace_env::Env>, defs: &mut Program) {
let mut env = Env::make(e);
let mut visitor = ElaborateNamespacesVisitor {};
for def in defs {
visitor.visit_def(&mut env, def).unwrap();
}
}
pub fn elaborate_fun_def(e: std::sync::Arc<namespace_env::Env>, fd: &mut FunDef) {
let mut env = Env::make(e);
let mut visitor = ElaborateNamespacesVisitor {};
visitor.visit_fun_def(&mut env, fd).unwrap();
}
pub fn elaborate_class_(e: std::sync::Arc<namespace_env::Env>, c: &mut Class_) {
let mut env = Env::make(e);
let mut visitor = ElaborateNamespacesVisitor {};
visitor.visit_class_(&mut env, c).unwrap();
}
pub fn elaborate_module_def(e: std::sync::Arc<namespace_env::Env>, m: &mut ModuleDef) {
let mut env = Env::make(e);
let mut visitor = ElaborateNamespacesVisitor {};
visitor.visit_module_def(&mut env, m).unwrap();
}
pub fn elaborate_gconst(e: std::sync::Arc<namespace_env::Env>, cst: &mut Gconst) {
let mut env = Env::make(e);
let mut visitor = ElaborateNamespacesVisitor {};
visitor.visit_gconst(&mut env, cst).unwrap();
}
pub fn elaborate_typedef(e: std::sync::Arc<namespace_env::Env>, td: &mut Typedef) {
let mut env = Env::make(e);
let mut visitor = ElaborateNamespacesVisitor {};
visitor.visit_typedef(&mut env, td).unwrap();
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.