language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
OCaml Interface
hhvm/hphp/hack/src/custom_error/custom_error.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type versioned_patt_error = Error_v1 of Patt_error.t [@@deriving eq, show] [@@boxed] type versioned_error_message = Message_v1 of Error_message.t [@@deriving eq, show] [@@boxed] type t = { name: string; patt: versioned_patt_error; error_message: versioned_error_message; } [@@deriving eq, show]
OCaml
hhvm/hphp/hack/src/custom_error/custom_error_config.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type t = { valid: Custom_error.t list; invalid: Custom_error.t list; } [@@deriving eq, show] [@@boxed] let empty = { valid = []; invalid = [] } let is_valid = function | { invalid = []; _ } -> true | _ -> false external initialize_custom_error_config : string -> (t, string) Result.t = "initialize_custom_error_config" let initialize path = let abs_path = match path with | `Absolute path -> path | `Relative path -> Relative_path.to_absolute path in initialize_custom_error_config abs_path
OCaml Interface
hhvm/hphp/hack/src/custom_error/custom_error_config.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type t = { valid: Custom_error.t list; invalid: Custom_error.t list; } [@@deriving eq, show] [@@boxed] val empty : t val is_valid : t -> bool val initialize : [ `Absolute of string | `Relative of Relative_path.t ] -> (t, string) result
Rust
hhvm/hphp/hack/src/custom_error/custom_error_config_ffi.rs
// Copyright (c) Meta Platforms, Inc. and affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. // Copyright (c) Meta Platforms, Inc. and affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::path::Path; use oxidized::custom_error_config::CustomErrorConfig; ocamlrep_ocamlpool::ocaml_ffi! { fn initialize_custom_error_config(path: String) -> Result<CustomErrorConfig, String> { CustomErrorConfig::from_path(Path::new(&path)).map_err(|e| format!("{}", e)) } }
OCaml
hhvm/hphp/hack/src/custom_error/custom_error_eval.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 Core module Ty = Typing_defs_core exception Invalid_pattern of string * Validation_err.t list exception Illegal_name of string module Value = struct type t = | Ty of (Typing_defs_core.locl_ty[@compare.ignore] [@sexp.opaque]) | Name of ((Pos_or_decl.t[@opaque]) * string) [@@deriving compare, sexp] end module Match = struct module X = struct (* TODO[mjt] - decompose into safe and unsafe match? *) type ('a, 'err) t = | Matched of 'a | No_match | Match_err of 'err let map = `Custom (fun t ~f -> match t with | Matched a -> Matched (f a) | No_match -> No_match | Match_err err -> Match_err err) let map_err t ~f = match t with | Match_err err -> Match_err (f err) | Matched a -> Matched a | No_match -> No_match let bind t ~f = match t with | Matched x -> f x | No_match -> No_match | Match_err err -> Match_err err let return x = Matched x let matched x = Matched x let no_match = No_match let match_err err = Match_err err end include X include Core.Monad.Make2 (X) end module Env = struct type t = Env of Value.t String.Map.t let empty = Env String.Map.empty let add (Env t) ~lbl ~data = Env (Map.add_exn t ~key:lbl ~data) let add_name t ~lbl ~name = add t ~lbl ~data:(Value.Name name) let add_ty t ~lbl ~ty = add t ~lbl ~data:(Value.Ty ty) let get (Env t) lbl = Map.find_exn t lbl end (* -- Helpers --------------------------------------------------------------- *) let match_exists patt ~matches ~scruts ~env = let rec aux = function | [] -> Match.no_match | scrut :: scruts -> (match matches patt scrut ~env with | Match.Matched _ as m -> m | _ -> aux scruts) in aux scruts (* -- Strings --------------------------------------------------------------- *) let matches_patt_string_help t ~scrut = let open Patt_string in let rec aux = function | Exactly str -> String.equal scrut str | Starts_with prefix -> String.is_prefix scrut ~prefix | Ends_with suffix -> String.is_suffix scrut ~suffix | Contains substring -> String.is_substring scrut ~substring | Or ts -> List.exists ~f:aux ts | And ts -> List.for_all ~f:aux ts | Not t -> not @@ aux t in aux t (* Since this pattern can never bind a variable we can't produce a match error. We use this invariant to simply the inner matching function *) let matches_string ?(env = Env.empty) t ~scrut = if matches_patt_string_help t ~scrut then Match.matched env else Match.no_match (* -- Names ----------------------------------------------------------------- *) let split_namespace (_pos, name) = let ls = List.rev @@ List.filter ~f:(fun s -> not @@ String.is_empty s) @@ String.split ~on:'\\' name in match ls with | name :: namespace -> Some (name, namespace) | _ -> None let rec matches_name ?(env = Env.empty) t ~scrut = let open Patt_name in match t with | Wildcard -> Match.matched env | Name { patt_namespace; patt_name } -> (match split_namespace scrut with | Some (name, namespace) -> Match.( matches_string patt_name ~scrut:name ~env >>= fun _ -> matches_namespace patt_namespace ~scrut:namespace ~env) | _ -> raise (Illegal_name (snd scrut))) | As { lbl; patt } -> Match.( matches_name patt ~scrut ~env |> map_err ~f:(fun _ -> assert false) |> map ~f:(Env.add_name ~lbl ~name:scrut)) | Invalid { errs; _ } -> Match.match_err errs and matches_namespace patt_namespace ~scrut ~env = let open Patt_name in match (patt_namespace, scrut) with | (Root, []) -> Match.return env | (Slash { prefix; elt }, next :: rest) -> Match.( matches_string elt ~scrut:next ~env >>= fun _ -> matches_namespace prefix ~scrut:rest ~env) | _ -> Match.no_match (* -- Types ----------------------------------------------------------------- *) let split_fields flds = List.fold ~f:(fun (str_map, cconst_map, int_map) (k, ty) -> match k with | Ty.TSFclass_const ((_, cls_nm), (_, cnst_nm)) -> ( str_map, String.Map.add_exn ~key:(cls_nm ^ "::" ^ cnst_nm) ~data:ty cconst_map, int_map ) | Ty.TSFlit_str (_, nm) -> (String.Map.add_exn ~key:nm ~data:ty str_map, cconst_map, int_map) | Ty.TSFlit_int (_, n) -> (str_map, cconst_map, String.Map.add_exn ~key:n ~data:ty int_map)) ~init:(String.Map.empty, String.Map.empty, String.Map.empty) @@ Ty.TShapeMap.elements flds let matches_locl_ty ?(env = Env.empty) t ~scrut = let open Patt_locl_ty in let rec aux t ty ~env = let ty_pos = Ty.get_pos ty in match (t, Ty.get_node ty) with (* -- Type wildcards ---------------------------------------------------- *) | (Any, _) -> Match.Matched env (* -- Type constructor like types --------------------------------------- *) | (Apply { patt_name; patt_params }, Ty.Tclass (name, _, tys)) -> Match.( matches_name patt_name ~scrut:name ~env >>= fun env -> aux_params patt_params tys ~env) | (Apply { patt_name; patt_params }, Ty.Tnewtype (id, tys, _)) -> Match.( matches_name patt_name ~scrut:(ty_pos, id) ~env >>= fun env -> aux_params patt_params tys ~env) | (Apply { patt_name; patt_params }, Ty.Tvec_or_dict (ty_key, ty_val)) -> Match.( matches_name patt_name ~scrut:(ty_pos, "vec_or_dict") ~env >>= fun env -> aux_params patt_params [ty_key; ty_val] ~env) | (Option t, Ty.Toption ty) -> aux t ty ~env | (Tuple ts, Ty.Ttuple tys) -> aux_tuple ts tys ~env (* -- Primitives & other base types ------------------------------------- *) | (Prim Null, Ty.Tprim Ast_defs.Tnull) | (Prim Void, Ty.Tprim Ast_defs.Tvoid) | (Prim Int, Ty.Tprim Ast_defs.Tint) | (Prim Bool, Ty.Tprim Ast_defs.Tbool) | (Prim Float, Ty.Tprim Ast_defs.Tfloat) | (Prim String, Ty.Tprim Ast_defs.Tstring) | (Prim Resource, Ty.Tprim Ast_defs.Tresource) | (Prim Num, Ty.Tprim Ast_defs.Tnum) | (Prim Arraykey, Ty.Tprim Ast_defs.Tarraykey) | (Prim Noreturn, Ty.Tprim Ast_defs.Tnoreturn) | (Dynamic, Ty.Tdynamic) | (Nonnull, Ty.Tnonnull) -> Match.matched env (* -- Variable binding -------------------------------------------------- *) | (As { lbl; patt }, _) -> Match.(aux patt ty ~env |> map ~f:(Env.add_ty ~lbl ~ty)) (* -- Or patterns ------------------------------------------------------- *) | (Or { patt_fst; patt_snd }, _) -> (match aux patt_fst ty ~env with | Match.Matched _ as m -> m | _ -> aux patt_snd ty ~env) (* -- Shapes ------------------------------------------------------------ *) | (Shape patt_flds, Ty.(Tshape { s_fields = flds; _ })) -> (* Split [TShapeMap.t] into three [String.Map.t]s, eliminating positional information *) let (str_flds, cconst_flds, int_flds) = split_fields flds in aux_shape patt_flds (str_flds, cconst_flds, int_flds) ~env (* -- Mismatches -------------------------------------------------------- *) | ((Apply _ | Option _ | Tuple _ | Prim _ | Dynamic | Nonnull | Shape _), _) -> Match.no_match | (Invalid (errs, _), _) -> Match.match_err errs and aux_shape t (str_flds, cconst_flds, int_flds) ~env = match t with | Fld { patt_fld; patt_rest } -> (match aux_shape_field patt_fld (str_flds, cconst_flds, int_flds) ~env with | Match.Matched (str_flds, cconst_flds, int_flds, env) -> aux_shape patt_rest (str_flds, cconst_flds, int_flds) ~env | Match.No_match -> Match.No_match | Match.Match_err err -> Match.match_err err) (* -- Open matches any remaining shape fields --------------------------- *) | Open -> Match.matched env (* -- Closed matches when we have no remaining shape fields ------------- *) | Closed when Map.is_empty str_flds && Map.is_empty cconst_flds && Map.is_empty int_flds -> Match.matched env | Closed -> Match.no_match and aux_shape_field fld (str_flds, cconst_flds, int_flds) ~env = match fld.lbl with | StrLbl str -> Option.value_map ~default:Match.no_match ~f:(fun Ty.{ sft_optional; sft_ty } -> if Bool.(sft_optional = fld.optional) then match aux fld.patt sft_ty ~env with | Match.Matched env -> Match.matched (Map.remove str_flds str, cconst_flds, int_flds, env) | Match.No_match -> Match.No_match | Match.Match_err err -> Match.Match_err err else Match.no_match) @@ Map.find str_flds str | CConstLbl { cls_nm; cnst_nm } -> let str = cls_nm ^ "::" ^ cnst_nm in Option.value_map ~default:Match.no_match ~f:(fun Ty.{ sft_optional; sft_ty } -> if Bool.(sft_optional = fld.optional) then match aux fld.patt sft_ty ~env with | Match.Matched env -> Match.matched (str_flds, Map.remove cconst_flds str, int_flds, env) | Match.No_match -> Match.No_match | Match.Match_err err -> Match.Match_err err else Match.no_match) @@ Map.find cconst_flds str | IntLbl n -> Option.value_map ~default:Match.no_match ~f:(fun Ty.{ sft_optional; sft_ty } -> if Bool.(sft_optional = fld.optional) then match aux fld.patt sft_ty ~env with | Match.Matched env -> Match.matched (str_flds, cconst_flds, Map.remove int_flds n, env) | Match.No_match -> Match.No_match | Match.Match_err err -> Match.Match_err err else Match.no_match) @@ Map.find int_flds n and aux_params t tys ~env = match (t, tys) with | (Cons { patt_hd; patt_tl }, ty :: tys) -> Match.(aux patt_hd ty ~env >>= fun env -> aux_params patt_tl tys ~env) | (Exists t, _) -> match_exists t ~matches:aux ~scruts:tys ~env | (Nil, []) | (Wildcard, _) -> Match.matched env | (Nil, _) | (Cons _, []) -> Match.no_match and aux_tuple ts tys ~env = match (ts, tys) with | (t :: ts, ty :: tys) -> Match.(aux t ty ~env >>= fun env -> aux_tuple ts tys ~env) | ([], []) -> Match.matched env | _ -> Match.no_match in aux t scrut ~env (* -- Errors ---------------------------------------------------------------- *) let matches_error ?(env = Env.empty) t ~scrut = let open Patt_error in (* -- Top-level typing errors --------------------------------------------- *) let rec aux t err ~env = match (t, err) with | (_, Typing_error.Error.Intersection errs) | (_, Typing_error.Error.Union errs) | (_, Typing_error.Error.Multiple errs) -> match_exists t ~matches:aux ~scruts:errs ~env (* -- Primary errors ---------------------------------------------------- *) | (Primary patt_prim, Typing_error.Error.Primary err_prim) -> aux_primary patt_prim err_prim ~env (* -- Callback application ---------------------------------------------- *) | (Apply { patt_cb; patt_err }, Typing_error.Error.Apply (cb, err)) -> Match.(aux_callback patt_cb cb ~env >>= fun env -> aux patt_err err ~env) (* -- Reasons callback application -------------------------------------- *) | ( Apply_reasons { patt_rsns_cb; patt_secondary }, Typing_error.Error.Apply_reasons (err_rsns_cb, err_secondary) ) -> Match.( aux_reasons_callback patt_rsns_cb err_rsns_cb ~env >>= fun env -> aux_secondary patt_secondary err_secondary ~env) (* -- Or patterns ------------------------------------------------------- *) | (Or { patt_fst; patt_snd }, _) -> (match aux patt_fst err ~env with | Match.Matched _ as m -> m | _ -> aux patt_snd err ~env) (* -- Mismatches -------------------------------------------------------- *) | (Primary _, _) | (Apply _, _) | (Apply_reasons _, _) -> Match.no_match | (Invalid { errs; _ }, _) -> Match.match_err errs (* -- Primary errors ------------------------------------------------------ *) and aux_primary t err_prim ~env = match (t, err_prim) with | (Any_prim, _) -> Match.matched env (* -- Secondary errors ---------------------------------------------------- *) and aux_secondary t err_snd ~env = match (t, err_snd) with | (Of_error patt_err, Typing_error.Secondary.Of_error err) -> aux patt_err err ~env | (Of_error _, _) -> Match.no_match (* We don't expose our internal `constraint_ty` so we handle this here *) | ( Violated_constraint { patt_cstr; patt_ty_sub; patt_ty_sup }, Typing_error.Secondary.Violated_constraint { cstrs; ty_sub; ty_sup; _ } ) -> Match.( match_exists patt_cstr ~matches:aux_param ~scruts:cstrs ~env >>= fun env -> aux_internal_ty patt_ty_sub ty_sub ~env >>= fun env -> aux_internal_ty patt_ty_sup ty_sup ~env) | (Violated_constraint _, _) -> Match.no_match | ( Subtyping_error { patt_ty_sub; patt_ty_sup }, Typing_error.Secondary.Subtyping_error { ty_sub; ty_sup; _ } ) -> Match.( aux_internal_ty patt_ty_sub ty_sub ~env >>= fun env -> aux_internal_ty patt_ty_sup ty_sup ~env) | (Subtyping_error _, _) -> Match.no_match | (Any_snd, _) -> Match.matched env (* -- Primary callbacks --------------------------------------------------- *) and aux_callback t err_callback ~env = match (t, err_callback) with | (Any_callback, _) -> Match.matched env (* -- Secondary / reasons callbacks --------------------------------------- *) and aux_reasons_callback t err_reasons_callback ~env = match (t, err_reasons_callback) with | (Any_reasons_callback, _) -> Match.matched env (* -- Internal types: we don't expose contraint types so handle here ------ *) and aux_internal_ty patt_locl_ty internal_ty ~env = match internal_ty with | Typing_defs_core.LoclType scrut -> matches_locl_ty patt_locl_ty ~scrut ~env | _ -> Match.no_match (* -- Type parameters ----------------------------------------------------- *) and aux_param patt_name (_, (_, scrut)) ~env = matches_string patt_name ~scrut ~env in aux t scrut ~env let eval_error_message Error_message.{ message } ~env = let open Error_message in let f t = match t with | Lit str -> Either.First str | Ty_var var | Name_var var -> Either.Second (Env.get env var) in List.map ~f message let eval_custom_error Custom_error. { patt = Error_v1 patt; error_message = Message_v1 error_message; _ } ~err = match matches_error patt ~scrut:err with | Match.Matched env -> Some (eval_error_message error_message ~env) | _ -> None let eval Custom_error_config.{ valid; _ } ~err = List.filter_map ~f:(eval_custom_error ~err) valid
OCaml Interface
hhvm/hphp/hack/src/custom_error/custom_error_eval.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. * *) exception Invalid_pattern of string * Validation_err.t list module Value : sig type t = | Ty of Typing_defs_core.locl_ty | Name of (Pos_or_decl.t * string) [@@deriving compare, sexp] end val eval : Custom_error_config.t -> err:Typing_error.t -> (string, Value.t) Base.Either.t list list
hhvm/hphp/hack/src/custom_error/dune
(library (name custom_error_types) (wrapped false) (preprocess (pps ppx_deriving.std ppx_compare ppx_sexp_conv)) (modules custom_error custom_error_config error_message patt_binding_ty patt_error patt_locl_ty patt_name patt_string patt_var validation_err ) (libraries core_kernel relative_path ) (foreign_archives custom_error_config_ffi)) (library (name custom_error_config_ffi) (modules) (wrapped false) (foreign_archives custom_error_config_ffi)) (rule (targets libcustom_error_config_ffi.a) (deps (source_tree %{workspace_root}/hack/src)) (locks /cargo) (action (run %{workspace_root}/hack/scripts/invoke_cargo.sh custom_error_config_ffi custom_error_config_ffi))) (library (name custom_error_eval) (wrapped false) (preprocess (pps ppx_compare ppx_sexp_conv)) (modules custom_error_eval) (libraries core_kernel custom_error_types typing_defs_core typing_error))
OCaml
hhvm/hphp/hack/src/custom_error/error_message.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type elem = | Lit of string | Ty_var of Patt_var.t | Name_var of Patt_var.t [@@deriving eq, show] type t = { message: elem list } [@@deriving eq, show]
OCaml Interface
hhvm/hphp/hack/src/custom_error/error_message.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type elem = | Lit of string | Ty_var of Patt_var.t | Name_var of Patt_var.t [@@deriving eq, show] type t = { message: elem list } [@@deriving eq, show]
OCaml
hhvm/hphp/hack/src/custom_error/patt_binding_ty.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. * *) [@@@warning "-66"] type t = | Name | Ty [@@deriving compare, eq, sexp, show]
OCaml Interface
hhvm/hphp/hack/src/custom_error/patt_binding_ty.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type t = | Name | Ty [@@deriving compare, eq, sexp, show]
OCaml
hhvm/hphp/hack/src/custom_error/patt_error.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) [@@@warning "-66"] type t = | Primary of primary | Apply of { patt_cb: callback; patt_err: t; } | Apply_reasons of { patt_rsns_cb: reasons_callback; patt_secondary: secondary; } | Or of { patt_fst: t; patt_snd: t; } | Invalid of { errs: Validation_err.t list; patt: t; } and primary = Any_prim and secondary = | Of_error of t | Violated_constraint of { patt_cstr: Patt_string.t; patt_ty_sub: Patt_locl_ty.t; patt_ty_sup: Patt_locl_ty.t; } | Subtyping_error of { patt_ty_sub: Patt_locl_ty.t; patt_ty_sup: Patt_locl_ty.t; } | Any_snd and callback = Any_callback and reasons_callback = Any_reasons_callback [@@deriving eq, show]
OCaml Interface
hhvm/hphp/hack/src/custom_error/patt_error.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type t = | Primary of primary | Apply of { patt_cb: callback; patt_err: t; } | Apply_reasons of { patt_rsns_cb: reasons_callback; patt_secondary: secondary; } | Or of { patt_fst: t; patt_snd: t; } | Invalid of { errs: Validation_err.t list; patt: t; } and primary = Any_prim and secondary = | Of_error of t | Violated_constraint of { patt_cstr: Patt_string.t; patt_ty_sub: Patt_locl_ty.t; patt_ty_sup: Patt_locl_ty.t; } | Subtyping_error of { patt_ty_sub: Patt_locl_ty.t; patt_ty_sup: Patt_locl_ty.t; } | Any_snd and callback = Any_callback and reasons_callback = Any_reasons_callback [@@deriving eq, show]
OCaml
hhvm/hphp/hack/src/custom_error/patt_locl_ty.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 Core type t = | Apply of { patt_name: Patt_name.t; patt_params: params; } | Prim of prim | Shape of shape_fields | Option of t | Tuple of t list | Dynamic | Nonnull | Any | Or of { patt_fst: t; patt_snd: t; } | As of { lbl: Patt_var.t; patt: t; } | Invalid of Validation_err.t list * t and params = | Nil | Wildcard | Cons of { patt_hd: t; patt_tl: params; } | Exists of t and prim = | Null | Void | Int | Bool | Float | String | Resource | Num | Arraykey | Noreturn and shape_fields = | Fld of { patt_fld: shape_field; patt_rest: shape_fields; } | Open | Closed and shape_field = { lbl: shape_label; optional: bool; patt: t; } and shape_label = | StrLbl of string | IntLbl of string | CConstLbl of { cls_nm: string; cnst_nm: string; } [@@deriving compare, eq, sexp, show]
OCaml Interface
hhvm/hphp/hack/src/custom_error/patt_locl_ty.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. * *) (** Defines pattern matches over a subset of Hack types *) type t = | Apply of { patt_name: Patt_name.t; patt_params: params; } (** Matches type-constructor like types e.g. class, vec_or_dict and newtypes *) | Prim of prim (** Matches Hack primitives *) | Shape of shape_fields (** Matches Hack shapes *) | Option of t (** Matches Hack optional types *) | Tuple of t list (** Matches Hack tuples *) | Dynamic (** Matches dynamic *) | Nonnull (** Matches non-null *) | Any (** Matches any Hack type *) | Or of { patt_fst: t; patt_snd: t; } (** Matches either the first pattern or, if that does not match, the second *) | As of { lbl: Patt_var.t; patt: t; } (** Match the provided pattern and bind the result to the supplied variable name *) | Invalid of Validation_err.t list * t (** Mark invalid patterns *) (** Defines pattern matches over list of Hack types appearing as type parameters *) and params = | Nil (** Matches the empty parameter list *) | Wildcard (** Matches any paramter list *) | Cons of { patt_hd: t; patt_tl: params; } (** Mathes a parameter list where the first element matches [patt_hd] and the remaining parameters match [patt_tl] *) | Exists of t (** Matches a parameter list where at least one Hint matches the supplied pattern *) (** Match Hack primitive types *) and prim = | Null | Void | Int | Bool | Float | String | Resource | Num | Arraykey | Noreturn (** Matches the fields of a Hack shape *) and shape_fields = | Fld of { patt_fld: shape_field; patt_rest: shape_fields; } (** Matches a shape which contains the a field matching the given [shape_field] and matches the remaining [shape_fields] *) | Open (** Matches any shape which contains fields which have not already been matched *) | Closed (** Matches a shape in which all other fields have already been matched *) (** Matches an individual Hack shape field *) and shape_field = { lbl: shape_label; optional: bool; patt: t; } (** Matches a Hack shape label *) and shape_label = | StrLbl of string | IntLbl of string | CConstLbl of { cls_nm: string; cnst_nm: string; } [@@deriving compare, eq, sexp, show]
OCaml
hhvm/hphp/hack/src/custom_error/patt_name.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. * *) [@@@warning "-66"] open Core type t = | As of { lbl: Patt_var.t; patt: t; } | Name of { patt_namespace: namespace; patt_name: Patt_string.t; } | Wildcard | Invalid of { errs: Validation_err.t list; patt: t; } and namespace = | Root | Slash of { prefix: namespace; elt: Patt_string.t; } [@@deriving compare, eq, sexp, show]
OCaml Interface
hhvm/hphp/hack/src/custom_error/patt_name.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type t = | As of { lbl: Patt_var.t; patt: t; } | Name of { patt_namespace: namespace; patt_name: Patt_string.t; } | Wildcard | Invalid of { errs: Validation_err.t list; patt: t; } and namespace = | Root | Slash of { prefix: namespace; elt: Patt_string.t; } [@@deriving compare, eq, sexp, show]
OCaml
hhvm/hphp/hack/src/custom_error/patt_string.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 Core type t = | Exactly of string | Starts_with of string | Ends_with of string | Contains of string | Or of t list | And of t list | Not of t [@@deriving compare, eq, sexp, show]
OCaml Interface
hhvm/hphp/hack/src/custom_error/patt_string.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type t = | Exactly of string | Starts_with of string | Ends_with of string | Contains of string | Or of t list | And of t list | Not of t [@@deriving compare, eq, sexp, show]
OCaml
hhvm/hphp/hack/src/custom_error/patt_var.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 Core type t = string [@@deriving compare, eq, sexp, show]
OCaml Interface
hhvm/hphp/hack/src/custom_error/patt_var.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type t = string [@@deriving compare, eq, sexp, show]
OCaml
hhvm/hphp/hack/src/custom_error/validation_err.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. * *) [@@@warning "-66"] type t = | Mismatch of Patt_binding_ty.t * Patt_binding_ty.t | Shadowed of Patt_var.t | Unbound of Patt_var.t [@@deriving compare, eq, sexp, show]
OCaml Interface
hhvm/hphp/hack/src/custom_error/validation_err.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type t = | Mismatch of Patt_binding_ty.t * Patt_binding_ty.t | Shadowed of Patt_var.t | Unbound of Patt_var.t [@@deriving compare, eq, sexp, show]
TOML
hhvm/hphp/hack/src/custom_error/cargo/custom_error_config_ffi/Cargo.toml
# @generated by autocargo [package] name = "custom_error_config_ffi" version = "0.0.0" edition = "2021" [lib] path = "../../custom_error_config_ffi.rs" test = false doctest = false crate-type = ["lib", "staticlib"] [dependencies] ocamlrep_ocamlpool = { version = "0.1.0", git = "https://github.com/facebook/ocamlrep/", branch = "main" } oxidized = { version = "0.0.0", path = "../../../oxidized" }
OCaml
hhvm/hphp/hack/src/decl/classDiff.ml
(** * Copyright (c) 2019, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type member_change = | Added | Removed | Changed_inheritance (* Modified in a way that affects inheritance *) | Modified (* Modified in a way that does not affect inheritance *) | Private_change (* Added/removed a private member *) [@@deriving eq, show { with_path = false }] (** Order member_change values by corresponding fanout size. *) let ord_member_change = function | Private_change -> 0 | Modified -> 1 | Changed_inheritance -> 2 | Added -> 3 | Removed -> 4 (** Compare member_change values by corresponding fanout size. *) let compare_member_change x y = ord_member_change x - ord_member_change y (* Returns true if the member changed in a way that affects what a descendant might inherit. This is trivially true for Added/Removed. The Changed_inheritance case captures situations where member metadata is used to select which member is used when a member of the same name is inherited from multiple parents. For example, if we have: class A { public function f(): void {} } trait T { public abstract function f(): void; } class B extends A { use T; } Then B inherits the concrete method A::f even though trait methods normally overwrite parent methods in folded methods tables--we use the fact that A::f is concrete and T::f is not to choose which member to inherit in B. Since changes to the abstractness of A::f or T::f can affect what appears in B's member collection, we categorize these changes with Changed_inheritance. We must handle changes which affect descendants in this way differently from changes which do not because of how we record member dependencies in the dependency graph (see Shallow_class_fanout for this handling). Other changes to members are categorized with Modified. In these cases, we need to recheck uses of the member, but this is straightforward to do using the dependency graph. Adding or removing a private member can be handled in the same way as Modified. We need to recheck uses of the member (if any exist), but the presence of a private member does not affect descendants (descendants are not prevented from defining a member of the same name, since each class gets its own "namespace" for private members in the runtime). Changes in positions in members are not considered a change at all by this module, since we re-typecheck all files with errors for every global check (so errors with positions referring to moved members will be recomputed). *) let method_or_property_change_affects_descendants member_change = match member_change with | Added | Removed | Changed_inheritance -> true | Modified | Private_change -> false type constructor_change = member_change option [@@deriving eq, ord] let constructor_change_to_json : constructor_change -> Hh_json.json = Hh_json.opt_ (fun x -> Hh_json.string_ @@ show_member_change x) module MembersChangeCategory = struct type t = { some_added: bool; some_removed: bool; some_changed_inheritance: bool; some_modified: bool; some_private_change: bool; } let no_change = { some_added = false; some_removed = false; some_changed_inheritance = false; some_modified = false; some_private_change = false; } let of_member_change_map (changes : member_change SMap.t) : t option = if SMap.is_empty changes then None else Some (SMap.fold (fun _ change acc -> match change with | Added -> { acc with some_added = true } | Removed -> { acc with some_removed = true } | Changed_inheritance -> { acc with some_changed_inheritance = true } | Modified -> { acc with some_modified = true } | Private_change -> { acc with some_private_change = true }) changes no_change) let to_json { some_added; some_removed; some_changed_inheritance; some_modified; some_private_change; } = Hh_json.JSON_Object [ ("some_added", Hh_json.bool_ some_added); ("some_removed", Hh_json.bool_ some_removed); ("some_changed_inheritance", Hh_json.bool_ some_changed_inheritance); ("some_modified", Hh_json.bool_ some_modified); ("some_private_change", Hh_json.bool_ some_private_change); ] end type member_diff = { consts: member_change SMap.t; typeconsts: member_change SMap.t; props: member_change SMap.t; sprops: member_change SMap.t; methods: member_change SMap.t; smethods: member_change SMap.t; constructor: constructor_change; } [@@deriving eq] module MemberDiffCategory = struct type t = { consts_category: MembersChangeCategory.t option; typeconsts_category: MembersChangeCategory.t option; props_category: MembersChangeCategory.t option; sprops_category: MembersChangeCategory.t option; methods_category: MembersChangeCategory.t option; smethods_category: MembersChangeCategory.t option; constructor_category: constructor_change; } let of_member_diff { consts; typeconsts; props; sprops; methods; smethods; constructor } = { consts_category = MembersChangeCategory.of_member_change_map consts; typeconsts_category = MembersChangeCategory.of_member_change_map typeconsts; props_category = MembersChangeCategory.of_member_change_map props; sprops_category = MembersChangeCategory.of_member_change_map sprops; methods_category = MembersChangeCategory.of_member_change_map methods; smethods_category = MembersChangeCategory.of_member_change_map smethods; constructor_category = constructor; } let to_json { consts_category; typeconsts_category; props_category; sprops_category; methods_category; smethods_category; constructor_category; } = Hh_json.JSON_Object [ ("consts", Hh_json.opt_ MembersChangeCategory.to_json consts_category); ( "typeconsts", Hh_json.opt_ MembersChangeCategory.to_json typeconsts_category ); ("props", Hh_json.opt_ MembersChangeCategory.to_json props_category); ("sprops", Hh_json.opt_ MembersChangeCategory.to_json sprops_category); ("methods", Hh_json.opt_ MembersChangeCategory.to_json methods_category); ( "smethods", Hh_json.opt_ MembersChangeCategory.to_json smethods_category ); ("constructor", constructor_change_to_json constructor_category); ] end let empty_member_diff = { consts = SMap.empty; typeconsts = SMap.empty; props = SMap.empty; sprops = SMap.empty; smethods = SMap.empty; methods = SMap.empty; constructor = None; } let is_empty_member_diff member_diff = member_diff = empty_member_diff (* This is written explicitly instead of derived so that we can omit empty fields of the member_diff record (to make logs easier to read). *) let pp_member_diff fmt member_diff = Format.fprintf fmt "@[<2>{"; let sep = ref false in let pp_smap_field name data = if not (SMap.is_empty data) then ( if !sep then Format.fprintf fmt ";@ " else ( Format.fprintf fmt " "; sep := true ); Format.fprintf fmt "@[%s =@ " name; SMap.pp pp_member_change fmt data; Format.fprintf fmt "@]" ) in let { consts; typeconsts; props; sprops; methods; smethods; constructor } = member_diff in pp_smap_field "consts" consts; pp_smap_field "typeconsts" typeconsts; pp_smap_field "props" props; pp_smap_field "sprops" sprops; pp_smap_field "methods" methods; pp_smap_field "smethods" smethods; begin match constructor with | None -> () | Some member_change -> if !sep then Format.fprintf fmt ";@ " else sep := true; Format.fprintf fmt "@[%s =@ " "constructor"; pp_member_change fmt member_change; Format.fprintf fmt "@]" end; if !sep then Format.fprintf fmt "@ "; Format.fprintf fmt "}@]" let show_member_diff member_diff = Format.asprintf "%a" pp_member_diff member_diff (** The maximum of two constructor changes is the change which has the largest fanout. *) let max_constructor_change left right = if compare_constructor_change left right >= 0 then left else right module ValueChange = struct type 'change t = | Added | Removed | Modified of 'change [@@deriving eq, show { with_path = false }] let to_json change_to_json = function | Added -> Hh_json.string_ "Added" | Removed -> Hh_json.string_ "Removed" | Modified change -> Hh_json.JSON_Object [("Modified", change_to_json change)] let map ~f = function | Added -> Added | Removed -> Removed | Modified x -> Modified (f x) end module NamedItemsListChange = struct type 'change t = { per_name_changes: 'change ValueChange.t SMap.t; order_change: bool; } [@@deriving eq, show { with_path = false }] end type parent_changes = { extends_changes: unit NamedItemsListChange.t NamedItemsListChange.t option; implements_changes: unit NamedItemsListChange.t NamedItemsListChange.t option; req_extends_changes: unit NamedItemsListChange.t NamedItemsListChange.t option; req_implements_changes: unit NamedItemsListChange.t NamedItemsListChange.t option; req_class_changes: unit NamedItemsListChange.t NamedItemsListChange.t option; uses_changes: unit NamedItemsListChange.t NamedItemsListChange.t option; xhp_attr_changes: unit NamedItemsListChange.t NamedItemsListChange.t option; } [@@deriving eq, show { with_path = false }] let classish_kind_to_json kind = Hh_json.string_ @@ Ast_defs.show_classish_kind kind module KindChange = struct type t = { new_kind: Ast_defs.classish_kind } [@@deriving eq, show { with_path = false }] let to_json { new_kind } = Hh_json.JSON_Object [("new_kind", classish_kind_to_json new_kind)] end module BoolChange = struct type t = | Became | No_more [@@deriving eq, show { with_path = false }] let to_json x = Hh_json.string_ @@ show x end module ValueDiff = struct type 'value t = { old_value: 'value; new_value: 'value; } [@@deriving eq, show { with_path = false }] end type enum_type_change = { base_change: Typing_defs.decl_ty ValueDiff.t option; constraint_change: Typing_defs.decl_ty ValueDiff.t ValueChange.t option; includes_change: unit NamedItemsListChange.t NamedItemsListChange.t option; } [@@deriving eq, show { with_path = false }] type class_shell_change = { classish_kind: Ast_defs.classish_kind; parent_changes: parent_changes option; type_parameters_change: unit NamedItemsListChange.t option; kind_change: KindChange.t option; final_change: BoolChange.t option; abstract_change: BoolChange.t option; is_xhp_change: BoolChange.t option; internal_change: BoolChange.t option; has_xhp_keyword_change: BoolChange.t option; support_dynamic_type_change: BoolChange.t option; module_change: unit ValueChange.t option; xhp_enum_values_change: bool; user_attributes_changes: unit NamedItemsListChange.t option; enum_type_change: enum_type_change ValueChange.t option; } [@@deriving eq, show { with_path = false }] module MajorChange = struct type t = | Unknown | Added | Removed | Modified of class_shell_change [@@deriving eq, show { with_path = false }] end type t = | Unchanged | Major_change of MajorChange.t | Minor_change of member_diff [@@deriving eq, show { with_path = false }] let has_changed = function | Unchanged -> false | Major_change _ | Minor_change _ -> true let pretty ~(name : string) (diff : t) : string = let buf = Buffer.create 512 in let fmt = Format.formatter_of_buffer buf in Format.pp_set_margin fmt 120; Format.fprintf fmt "%s @[<2>%s:@ %a@]@?" (String.make 35 ' ') (* indentation hack (width of log timestamp) *) (Utils.strip_ns name) pp diff; let diffstr = Buffer.contents buf in (* indentation hack *) Printf.sprintf " %s" (Caml.String.trim diffstr) module ClassShellChangeCategory = struct module ListChange = struct type t = { some_added: bool; some_removed: bool; some_modified: bool; order_change: bool; } let no_change : t = { some_added = false; some_removed = false; some_modified = false; order_change = false; } let of_list_change_map { NamedItemsListChange.per_name_changes = changes; order_change } = SMap.fold (fun _ change acc -> match change with | ValueChange.Added -> { acc with some_added = true } | ValueChange.Removed -> { acc with some_removed = true } | ValueChange.Modified _ -> { acc with some_modified = true }) changes { no_change with order_change } let to_json { some_added; some_removed; some_modified; order_change } = Hh_json.JSON_Object [ ("some_added", Hh_json.bool_ some_added); ("some_removed", Hh_json.bool_ some_removed); ("some_modified", Hh_json.bool_ some_modified); ("order_change", Hh_json.bool_ order_change); ] end module ParentsChangeCategory = struct type t = { extends_changes_category: ListChange.t option; implements_changes_category: ListChange.t option; req_extends_changes_category: ListChange.t option; req_implements_changes_category: ListChange.t option; req_class_changes_category: ListChange.t option; uses_changes_category: ListChange.t option; xhp_attr_changes_category: ListChange.t option; } let of_parents_change { extends_changes; implements_changes; req_extends_changes; req_implements_changes; req_class_changes; uses_changes; xhp_attr_changes; } = { extends_changes_category = Option.map ListChange.of_list_change_map extends_changes; implements_changes_category = Option.map ListChange.of_list_change_map implements_changes; req_extends_changes_category = Option.map ListChange.of_list_change_map req_extends_changes; req_implements_changes_category = Option.map ListChange.of_list_change_map req_implements_changes; req_class_changes_category = Option.map ListChange.of_list_change_map req_class_changes; uses_changes_category = Option.map ListChange.of_list_change_map uses_changes; xhp_attr_changes_category = Option.map ListChange.of_list_change_map xhp_attr_changes; } let to_json { extends_changes_category; implements_changes_category; req_extends_changes_category; req_implements_changes_category; req_class_changes_category; uses_changes_category; xhp_attr_changes_category; } = Hh_json.JSON_Object [ ( "extends_changes", Hh_json.opt_ ListChange.to_json extends_changes_category ); ( "implements_changes", Hh_json.opt_ ListChange.to_json implements_changes_category ); ( "req_extends_changes", Hh_json.opt_ ListChange.to_json req_extends_changes_category ); ( "req_implements_changes", Hh_json.opt_ ListChange.to_json req_implements_changes_category ); ( "req_class_changes", Hh_json.opt_ ListChange.to_json req_class_changes_category ); ("uses_changes", Hh_json.opt_ ListChange.to_json uses_changes_category); ( "xhp_attr_changes", Hh_json.opt_ ListChange.to_json xhp_attr_changes_category ); ] end let unit_to_json () = Hh_json.JSON_Null module EnumTypeChangeCategory = struct type t = { has_base_change: bool; constraint_change_category: unit ValueChange.t option; includes_change_category: ListChange.t option; } let of_enum_type_change (change : enum_type_change) : t = let { base_change; constraint_change; includes_change } = change in { has_base_change = Option.is_some base_change; constraint_change_category = Option.map (ValueChange.map ~f:(fun _ -> ())) constraint_change; includes_change_category = Option.map ListChange.of_list_change_map includes_change; } let to_json { has_base_change; constraint_change_category; includes_change_category; } = Hh_json.JSON_Object [ ("has_base_change", Hh_json.bool_ has_base_change); ( "constraint_change_category", Hh_json.opt_ (ValueChange.to_json unit_to_json) constraint_change_category ); ( "includes_change_category", Hh_json.opt_ ListChange.to_json includes_change_category ); ] end type t = { classish_kind: Ast_defs.classish_kind; parent_changes_category: ParentsChangeCategory.t option; type_parameters_change_category: ListChange.t option; kind_change_category: KindChange.t option; final_change_category: BoolChange.t option; abstract_change_category: BoolChange.t option; is_xhp_change_category: BoolChange.t option; internal_change_category: BoolChange.t option; has_xhp_keyword_change_category: BoolChange.t option; support_dynamic_type_change_category: BoolChange.t option; module_change_category: unit ValueChange.t option; xhp_enum_values_change_category: bool; user_attributes_changes_category: ListChange.t option; enum_type_change_category: EnumTypeChangeCategory.t ValueChange.t option; } let of_class_shell_change ({ classish_kind; parent_changes; type_parameters_change; kind_change; final_change; abstract_change; is_xhp_change; internal_change; has_xhp_keyword_change; support_dynamic_type_change; module_change; xhp_enum_values_change; user_attributes_changes; enum_type_change; } : class_shell_change) = { classish_kind; parent_changes_category = Option.map ParentsChangeCategory.of_parents_change parent_changes; type_parameters_change_category = Option.map ListChange.of_list_change_map type_parameters_change; kind_change_category = kind_change; final_change_category = final_change; abstract_change_category = abstract_change; is_xhp_change_category = is_xhp_change; internal_change_category = internal_change; has_xhp_keyword_change_category = has_xhp_keyword_change; support_dynamic_type_change_category = support_dynamic_type_change; module_change_category = module_change; xhp_enum_values_change_category = xhp_enum_values_change; user_attributes_changes_category = Option.map ListChange.of_list_change_map user_attributes_changes; enum_type_change_category = Option.map (ValueChange.map ~f:EnumTypeChangeCategory.of_enum_type_change) enum_type_change; } let to_json { classish_kind; parent_changes_category; type_parameters_change_category; kind_change_category; final_change_category; abstract_change_category; is_xhp_change_category; internal_change_category; has_xhp_keyword_change_category; support_dynamic_type_change_category; module_change_category; xhp_enum_values_change_category; user_attributes_changes_category; enum_type_change_category; } = let open Hh_json in JSON_Object [ ("classish_kind", classish_kind_to_json classish_kind); ( "parent_changes", Hh_json.opt_ ParentsChangeCategory.to_json parent_changes_category ); ( "type_parameters_change", Hh_json.opt_ ListChange.to_json type_parameters_change_category ); ("kind_change", Hh_json.opt_ KindChange.to_json kind_change_category); ("final_change", Hh_json.opt_ BoolChange.to_json final_change_category); ( "abstract_change", Hh_json.opt_ BoolChange.to_json abstract_change_category ); ("is_xhp_change", Hh_json.opt_ BoolChange.to_json is_xhp_change_category); ( "internal_change", Hh_json.opt_ BoolChange.to_json internal_change_category ); ( "has_xhp_keyword_change", Hh_json.opt_ BoolChange.to_json has_xhp_keyword_change_category ); ( "support_dynamic_type_change", Hh_json.opt_ BoolChange.to_json support_dynamic_type_change_category ); ( "module_change", Hh_json.opt_ (ValueChange.to_json unit_to_json) module_change_category ); ("xhp_enum_values_change", Hh_json.bool_ xhp_enum_values_change_category); ( "user_attributes_changes", Hh_json.opt_ ListChange.to_json user_attributes_changes_category ); ( "enum_type_change", Hh_json.opt_ (ValueChange.to_json EnumTypeChangeCategory.to_json) enum_type_change_category ); ] end module MajorChangeCategory = struct type t = | Unknown | Added | Removed | Modified of ClassShellChangeCategory.t let of_major_change = function | MajorChange.Unknown -> Unknown | MajorChange.Added -> Added | MajorChange.Removed -> Removed | MajorChange.Modified change -> Modified (ClassShellChangeCategory.of_class_shell_change change) let to_json = function | Unknown -> Hh_json.string_ "Unknown" | Added -> Hh_json.string_ "Added" | Removed -> Hh_json.string_ "Removed" | Modified change -> ClassShellChangeCategory.to_json change end module ChangeCategory = struct type t = | CUnchanged | CMajor_change of MajorChangeCategory.t | CMinor_change of MemberDiffCategory.t let of_change = function | Unchanged -> CUnchanged | Major_change change -> CMajor_change (MajorChangeCategory.of_major_change change) | Minor_change member_diff -> CMinor_change (MemberDiffCategory.of_member_diff member_diff) let to_json = function | CUnchanged -> Hh_json.string_ "Unchanged" | CMajor_change change -> Hh_json.JSON_Object [("Major_change", MajorChangeCategory.to_json change)] | CMinor_change change -> Hh_json.JSON_Object [("Minor_change", MemberDiffCategory.to_json change)] end let to_category_json x = ChangeCategory.to_json @@ ChangeCategory.of_change x
OCaml Interface
hhvm/hphp/hack/src/decl/classDiff.mli
(** * Copyright (c) 2019, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type member_change = | Added | Removed | Changed_inheritance (* Modified in a way that affects inheritance *) | Modified (* Modified in a way that does not affect inheritance *) | Private_change (* Added/removed a private member *) [@@deriving eq, show] type constructor_change = member_change option [@@deriving eq] type member_diff = { consts: member_change SMap.t; typeconsts: member_change SMap.t; props: member_change SMap.t; sprops: member_change SMap.t; methods: member_change SMap.t; smethods: member_change SMap.t; constructor: constructor_change; } [@@deriving eq, show] module ValueChange : sig type 'change t = | Added | Removed | Modified of 'change [@@deriving eq, show] end module NamedItemsListChange : sig type 'change t = { per_name_changes: 'change ValueChange.t SMap.t; order_change: bool; } [@@deriving eq, show] end type parent_changes = { extends_changes: unit NamedItemsListChange.t NamedItemsListChange.t option; implements_changes: unit NamedItemsListChange.t NamedItemsListChange.t option; req_extends_changes: unit NamedItemsListChange.t NamedItemsListChange.t option; req_implements_changes: unit NamedItemsListChange.t NamedItemsListChange.t option; req_class_changes: unit NamedItemsListChange.t NamedItemsListChange.t option; uses_changes: unit NamedItemsListChange.t NamedItemsListChange.t option; xhp_attr_changes: unit NamedItemsListChange.t NamedItemsListChange.t option; } module KindChange : sig type t = { new_kind: Ast_defs.classish_kind } [@@deriving eq, show] end module BoolChange : sig type t = | Became | No_more [@@deriving eq, show] end module ValueDiff : sig type 'value t = { old_value: 'value; new_value: 'value; } [@@deriving eq, show] end type enum_type_change = { base_change: Typing_defs.decl_ty ValueDiff.t option; constraint_change: Typing_defs.decl_ty ValueDiff.t ValueChange.t option; includes_change: unit NamedItemsListChange.t NamedItemsListChange.t option; } [@@deriving eq, show] type class_shell_change = { classish_kind: Ast_defs.classish_kind; parent_changes: parent_changes option; type_parameters_change: unit NamedItemsListChange.t option; kind_change: KindChange.t option; final_change: BoolChange.t option; abstract_change: BoolChange.t option; is_xhp_change: BoolChange.t option; internal_change: BoolChange.t option; has_xhp_keyword_change: BoolChange.t option; support_dynamic_type_change: BoolChange.t option; module_change: unit ValueChange.t option; xhp_enum_values_change: bool; user_attributes_changes: unit NamedItemsListChange.t option; enum_type_change: enum_type_change ValueChange.t option; } [@@deriving eq, show] module MajorChange : sig type t = | Unknown | Added | Removed | Modified of class_shell_change [@@deriving eq, show] end type t = | Unchanged | Major_change of MajorChange.t | Minor_change of member_diff [@@deriving eq, show] val has_changed : t -> bool val pretty : name:string -> t -> string val empty_member_diff : member_diff val is_empty_member_diff : member_diff -> bool (** Wether a change on a method or property affects the descendants. This is the case for added and removed members, but also if e.g. abstractness or visibility has changed. *) val method_or_property_change_affects_descendants : member_change -> bool (** The maximum of two constructor changes is the change which has the largest fanout. *) val max_constructor_change : constructor_change -> constructor_change -> constructor_change val to_category_json : t -> Hh_json.json
OCaml
hhvm/hphp/hack/src/decl/decl.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude let make_env ~(sh : SharedMem.uses) (ctx : Provider_context.t) (fn : Relative_path.t) : unit = match Direct_decl_utils.direct_decl_parse_and_cache ctx fn with | None -> () | Some parsed_file -> List.iter parsed_file.Direct_decl_utils.pfh_decls ~f:(function | (name, Shallow_decl_defs.Class _, _) -> (match Provider_context.get_backend ctx with | Provider_backend.Rust_provider_backend backend -> Rust_provider_backend.Decl.declare_folded_class backend (Naming_provider.rust_backend_ctx_proxy ctx) name | _ -> let (_ : _ option) = Decl_folded_class.class_decl_if_missing ~sh ctx name in ()) | _ -> ())
OCaml Interface
hhvm/hphp/hack/src/decl/decl.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 function works by side effects. It is adding in the Naming_table the * nast produced from the filename passed as a parameter (the SharedMem must * thus have been initialized via SharedMem.init prior to calling this * function). Its performance benefits if the Parser_heap has been previously * populated. It finally adds all the typing information about classes, functions, typedefs, * respectively in the globals in Typing_env.Class, Typing_env.Fun, and * Typing_env.Typedef. *) val make_env : sh:SharedMem.uses -> Provider_context.t -> Relative_path.t -> unit
OCaml
hhvm/hphp/hack/src/decl/decl_class.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 Typing_defs open Decl_defs module Inst = Decl_instantiate module SN = Naming_special_names exception Decl_heap_elems_bug of string (** Raise an exception when the class element can't be found. Note that this exception can be raised in two modes: 1. A Provider_context.t was not available (e.g, Zoncolan execution) and the element was not in the member heaps. A bug in decling or invalidation has occurred, potentially due to files being changed on disk while Hack was decling. No [lazy_member_lookup_error] is available, because we didn't do a lazy member lookup. 2. A Provider_context.t was available (regular Hack execution with eviction), the element was not in the member heap, so we tried falling back to disk. However, the element could not be found in the origin class. This might be due to an inconsistent decl heap (e.g., due to files being changed on disk while Hack was decling) or because the file containing the element was changed while type checking. In this case, we have a [lazy_member_lookup_error] available. *) let raise_decl_heap_elems_bug ~(err : Decl_folded_class.lazy_member_lookup_error option) ~(child_class_name : string) ~(elt_origin : string) ~(member_name : string) = let data = Printf.sprintf "could not find %s::%s (inherited by %s) (%s)" elt_origin member_name child_class_name (Option.map ~f:Decl_folded_class.show_lazy_member_lookup_error err |> Option.value ~default:"no lazy member lookup performed") in Hh_logger.log "Decl_heap_elems_bug: %s\n%s" data (Exception.get_current_callstack_string 99 |> Exception.clean_stack); HackEventLogger.decl_consistency_bug ~data "Decl_heap_elems_bug"; raise (Decl_heap_elems_bug data) let unpack_member_lookup_result (type a) ~child_class_name ~elt_origin ~member_name (res : (a, Decl_folded_class.lazy_member_lookup_error) result option) : a = let res = match res with | None -> Error None | Some res -> Result.map_error ~f:(fun x -> Some x) res in match res with | Ok a -> a | Error err -> raise_decl_heap_elems_bug ~err ~child_class_name ~elt_origin ~member_name let rec apply_substs substs class_context (pos, ty) = match SMap.find_opt class_context substs with | None -> (pos, ty) | Some { sc_subst = subst; sc_class_context = next_class_context; _ } -> apply_substs substs next_class_context (pos, Inst.instantiate subst ty) let element_to_class_elt (pty : (Pos_or_decl.t * decl_ty) lazy_t) { elt_flags = ce_flags; elt_origin = ce_origin; elt_visibility = ce_visibility; elt_deprecated = ce_deprecated; } = let (ce_pos, ce_type) = (lazy (fst @@ Lazy.force pty), lazy (snd @@ Lazy.force pty)) in { ce_visibility; ce_origin; ce_type; ce_deprecated; ce_pos; ce_flags } let fun_elt_to_ty fe = (fe.fe_pos, fe.fe_type) let find_method ctx ~child_class_name x = let (elt_origin, sm_name) = x in let fun_elt = match Decl_store.((get ()).get_method x) with | Some fe -> fe | None -> Option.map ctx ~f: (Decl_folded_class.method_decl_lazy ~sh:SharedMem.Uses ~is_static:false ~elt_origin ~sm_name) |> unpack_member_lookup_result ~child_class_name ~elt_origin ~member_name:sm_name in fun_elt_to_ty fun_elt let find_static_method ctx ~child_class_name x = let (elt_origin, sm_name) = x in let fun_elt = match Decl_store.((get ()).get_static_method x) with | Some fe -> fe | None -> Option.map ctx ~f: (Decl_folded_class.method_decl_lazy ~sh:SharedMem.Uses ~is_static:true ~elt_origin ~sm_name) |> unpack_member_lookup_result ~child_class_name ~elt_origin ~member_name:sm_name in fun_elt_to_ty fun_elt let find_property ctx ~child_class_name x = let (elt_origin, sp_name) = x in let ty = match Decl_store.((get ()).get_prop x) with | Some ty -> ty | None -> Option.map ctx ~f: (Decl_folded_class.prop_decl_lazy ~sh:SharedMem.Uses ~elt_origin ~sp_name) |> unpack_member_lookup_result ~child_class_name ~elt_origin ~member_name:sp_name in (get_pos ty, ty) let find_static_property ctx ~child_class_name x = let (elt_origin, sp_name) = x in let ty = match Decl_store.((get ()).get_static_prop x) with | Some ty -> ty | None -> Option.map ctx ~f: (Decl_folded_class.static_prop_decl_lazy ~sh:SharedMem.Uses ~elt_origin ~sp_name) |> unpack_member_lookup_result ~child_class_name ~elt_origin ~member_name:sp_name in (get_pos ty, ty) let find_constructor ctx ~child_class_name ~elt_origin = match Decl_store.((get ()).get_constructor elt_origin) with | Some fe -> fe | None -> Option.map ctx ~f: (Decl_folded_class.constructor_decl_lazy ~sh:SharedMem.Uses ~elt_origin) |> unpack_member_lookup_result ~child_class_name ~elt_origin ~member_name:SN.Members.__construct let map_element dc_substs find name (elt : element) = let pty = lazy ((elt.elt_origin, name) |> find |> apply_substs dc_substs elt.elt_origin) in element_to_class_elt pty elt let lookup_property_type_lazy (ctx : Provider_context.t option) (dc : Decl_defs.decl_class_type) = map_element dc.dc_substs (find_property ~child_class_name:dc.Decl_defs.dc_name ctx) let lookup_static_property_type_lazy (ctx : Provider_context.t option) (dc : Decl_defs.decl_class_type) = map_element dc.dc_substs (find_static_property ~child_class_name:dc.Decl_defs.dc_name ctx) let lookup_method_type_lazy (ctx : Provider_context.t option) (dc : Decl_defs.decl_class_type) = map_element dc.dc_substs (find_method ctx ~child_class_name:dc.Decl_defs.dc_name) let lookup_static_method_type_lazy (ctx : Provider_context.t option) (dc : Decl_defs.decl_class_type) = map_element dc.dc_substs (find_static_method ctx ~child_class_name:dc.Decl_defs.dc_name) let lookup_constructor_lazy (ctx : Provider_context.t option) ~(child_class_name : string) (dc_substs : Decl_defs.subst_context SMap.t) (dc_construct : Decl_defs.element option * Typing_defs.consistent_kind) : Typing_defs.class_elt option * Typing_defs.consistent_kind = match dc_construct with | (None, consistent) -> (None, consistent) | (Some elt, consistent) -> let pty = lazy (find_constructor ctx ~child_class_name ~elt_origin:elt.elt_origin |> fun_elt_to_ty |> apply_substs dc_substs elt.elt_origin) in let class_elt = element_to_class_elt pty elt in (Some class_elt, consistent)
OCaml Interface
hhvm/hphp/hack/src/decl/decl_class.mli
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) exception Decl_heap_elems_bug of string (** Lookup the type signature of a class property. [Decl_defs.element] only points to where the type signature of an element can be found (i.e. in which class). This function looks up the actual type signature and returns it, together with the original metadata. The type signature is retrieved from the member heaps. If it is not present and a [Provider_context.t] is passed, the member will be extracting from disk. If no [Provider_context.t] is passed or it cannot be found on disk a [Decl_heap_elems_bug] exception is raised. Note that the lookup is lazy. The type signature is wrapped in a lazy value. The lookup will only happen when you try to force the lazy value. (See the definition of [Typing_defs.class_elt].) *) val lookup_property_type_lazy : Provider_context.t option -> Decl_defs.decl_class_type -> string -> Decl_defs.element -> Typing_defs.class_elt (** Lookup the type of a class static property. See [lookup_property_type_lazy] for more information. *) val lookup_static_property_type_lazy : Provider_context.t option -> Decl_defs.decl_class_type -> string -> Decl_defs.element -> Typing_defs.class_elt (** Lookup the type of a class method. See [lookup_property_type_lazy] for more information. *) val lookup_method_type_lazy : Provider_context.t option -> Decl_defs.decl_class_type -> string -> Decl_defs.element -> Typing_defs.class_elt (** Lookup the type of a class static method. See [lookup_property_type_lazy] for more information. *) val lookup_static_method_type_lazy : Provider_context.t option -> Decl_defs.decl_class_type -> string -> Decl_defs.element -> Typing_defs.class_elt (** Lookup the type of a class constructor. See [lookup_property_type_lazy] for more information. *) val lookup_constructor_lazy : Provider_context.t option -> child_class_name:string -> Decl_defs.subst_context SMap.t -> Decl_defs.element option * Typing_defs.consistent_kind -> Typing_defs.class_elt option * Typing_defs.consistent_kind
OCaml
hhvm/hphp/hack/src/decl/decl_class_elements.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 Decl_defs open Decl_heap type t = { props: Props.KeySet.t; sprops: StaticProps.KeySet.t; meths: Methods.KeySet.t; smeths: StaticMethods.KeySet.t; } let from_class { dc_name; dc_props; dc_sprops; dc_methods; dc_smethods; _ } = let filter_inherited_elements (type a) (module EltHeap : SharedMem.Heap with type key = string * string and type KeySet.t = a) elts = SMap.fold begin fun name { elt_origin = cls; _ } set -> if String.equal cls dc_name then EltHeap.KeySet.add (cls, name) set else set end elts EltHeap.KeySet.empty in { props = filter_inherited_elements (module Props) dc_props; sprops = filter_inherited_elements (module StaticProps) dc_sprops; meths = filter_inherited_elements (module Methods) dc_methods; smeths = filter_inherited_elements (module StaticMethods) dc_smethods; } let get_for_classes ~old classes = let get = if old then Decl_heap.Classes.get_old else Decl_heap.Classes.get in List.fold ~f: begin fun acc cls -> match get cls with | None -> acc | Some c -> SMap.add cls (from_class c) acc end classes ~init:SMap.empty let oldify_batch { props; sprops; meths; smeths } = Props.oldify_batch props; StaticProps.oldify_batch sprops; Methods.oldify_batch meths; StaticMethods.oldify_batch smeths let remove_old_batch { props; sprops; meths; smeths } = Props.remove_old_batch props; StaticProps.remove_old_batch sprops; Methods.remove_old_batch meths; StaticMethods.remove_old_batch smeths let remove_batch { props; sprops; meths; smeths } = Props.remove_batch props; StaticProps.remove_batch sprops; Methods.remove_batch meths; StaticMethods.remove_batch smeths let oldify_all class_to_elems = SMap.iter begin fun cls elems -> Constructors.oldify_batch (SSet.singleton cls); oldify_batch elems end class_to_elems let remove_old_all class_to_elems = SMap.iter begin fun cls elems -> Constructors.remove_old_batch (SSet.singleton cls); remove_old_batch elems end class_to_elems let remove_all class_to_elems = SMap.iter begin fun cls elems -> Constructors.remove_batch (SSet.singleton cls); remove_batch elems end class_to_elems
OCaml Interface
hhvm/hphp/hack/src/decl/decl_class_elements.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 = { props: Decl_heap.Props.KeySet.t; sprops: Decl_heap.StaticProps.KeySet.t; meths: Decl_heap.Methods.KeySet.t; smeths: Decl_heap.StaticMethods.KeySet.t; } val get_for_classes : old:bool -> string list -> t SMap.t val oldify_all : t SMap.t -> unit val remove_old_all : t SMap.t -> unit val remove_all : t SMap.t -> unit
OCaml
hhvm/hphp/hack/src/decl/decl_compare.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (*****************************************************************************) (* Module used when we want to figure out what has changed. * 1) The user modifies a file * 2) We compute the type of the file (cf typing_redecl_service.ml) * 3) We compare the old type and the new type of the class (or function) * to see if anything has changed. This is where the code of this module * comes into play. This code compares the old and the new class type * and computes the set of dependencies if something needs to be * either redeclared or checked again. *) (*****************************************************************************) open Hh_prelude open Decl_defs open Typing_deps open Typing_defs (*****************************************************************************) (* Given two classes give back the set of functions or classes that need * to be rechecked *) (*****************************************************************************) module ClassDiff = struct let smap_left s1 s2 = SMap.fold begin fun x ty1 diff -> let ty2 = SMap.find_opt x s2 in match ty2 with | Some ty2 -> if Poly.( = ) ty1 ty2 then diff else SSet.add x diff | None -> SSet.add x diff end s1 SSet.empty let smap s1 s2 = SSet.union (smap_left s1 s2) (smap_left s2 s1) let add_inverted_dep mode build_obj x acc = DepSet.union (Typing_deps.get_ideps mode (build_obj x)) acc let add_inverted_deps mode acc build_obj xset = SSet.fold (add_inverted_dep mode build_obj) xset acc let compare mode cid class1 class2 = let acc = DepSet.make () in let is_unchanged = true in (* compare class constants *) let consts_diff = smap class1.dc_consts class2.dc_consts in let is_unchanged = is_unchanged && SSet.is_empty consts_diff in let acc = add_inverted_deps mode acc (fun x -> Dep.Const (cid, x)) consts_diff in (* compare class members *) let props_diff = smap class1.dc_props class2.dc_props in let is_unchanged = is_unchanged && SSet.is_empty props_diff in let acc = add_inverted_deps mode acc (fun x -> Dep.Prop (cid, x)) props_diff in (* compare class static members *) let sprops_diff = smap class1.dc_sprops class2.dc_sprops in let is_unchanged = is_unchanged && SSet.is_empty sprops_diff in let acc = add_inverted_deps mode acc (fun x -> Dep.SProp (cid, x)) sprops_diff in (* compare class methods *) let methods_diff = smap class1.dc_methods class2.dc_methods in let is_unchanged = is_unchanged && SSet.is_empty methods_diff in let acc = add_inverted_deps mode acc (fun x -> Dep.Method (cid, x)) methods_diff in (* compare class static methods *) let smethods_diff = smap class1.dc_smethods class2.dc_smethods in let is_unchanged = is_unchanged && SSet.is_empty smethods_diff in let acc = add_inverted_deps mode acc (fun x -> Dep.SMethod (cid, x)) smethods_diff in (* compare class constructors *) let ctor_diff = Poly.( <> ) class1.dc_construct class2.dc_construct in let is_unchanged = is_unchanged && not ctor_diff in let ctor_ideps = Typing_deps.get_ideps mode (Dep.Constructor cid) in let acc = if ctor_diff then DepSet.union acc ctor_ideps else acc in (* compare class type constants *) let typeconsts_diff = smap class1.dc_typeconsts class2.dc_typeconsts in let is_unchanged = is_unchanged && SSet.is_empty typeconsts_diff in let acc = add_inverted_deps mode acc (fun x -> Dep.Const (cid, x)) typeconsts_diff in (acc, is_unchanged) end (*****************************************************************************) (* Given two classes give back the set of functions or classes that need * to be rechecked because the type of their member changed *) (*****************************************************************************) module ClassEltDiff = struct open Decl_heap let add_inverted_dep mode build_obj x _ acc = DepSet.union (Typing_deps.get_ideps mode (build_obj x)) acc let add_inverted_deps mode (acc, is_unchanged) build_obj xmap = let is_unchanged = match is_unchanged with | `Unchanged when not @@ SMap.is_empty xmap -> `Changed | x -> x in let acc = SMap.fold (add_inverted_dep mode build_obj) xmap acc in (acc, is_unchanged) let diff_elts (type t) (module EltHeap : SharedMem.Heap with type key = string * string and type value = t) ~cid ~elts1 ~elts2 ~normalize = SMap.merge begin fun name elt1 elt2 -> let key = (cid, name) in let match1 = match elt1 with | Some elt -> String.equal elt.elt_origin cid | _ -> false in let match2 = match elt2 with | Some elt -> String.equal elt.elt_origin cid | _ -> false in if match1 || match2 then match (EltHeap.get_old key, EltHeap.get key) with | (None, _) | (_, None) -> Some () | (Some x1, Some x2) -> let ty1 = normalize x1 in let ty2 = normalize x2 in if Poly.( = ) ty1 ty2 then None else Some () else None end elts1 elts2 let compare_props mode class1 class2 acc = let cid = class1.dc_name in let (elts1, elts2) = (class1.dc_props, class2.dc_props) in let diff = diff_elts (module Props) ~cid ~elts1 ~elts2 ~normalize:Decl_pos_utils.NormalizeSig.ty in add_inverted_deps mode acc (fun x -> Dep.Prop (cid, x)) diff let compare_sprops mode class1 class2 acc = let cid = class1.dc_name in let (elts1, elts2) = (class1.dc_sprops, class2.dc_sprops) in let diff = diff_elts (module StaticProps) ~cid ~elts1 ~elts2 ~normalize:Decl_pos_utils.NormalizeSig.ty in add_inverted_deps mode acc (fun x -> Dep.SProp (cid, x)) diff let compare_meths mode class1 class2 acc = let cid = class1.dc_name in let (elts1, elts2) = (class1.dc_methods, class2.dc_methods) in let diff = diff_elts (module Methods) ~cid ~elts1 ~elts2 ~normalize:Decl_pos_utils.NormalizeSig.fun_elt in add_inverted_deps mode acc (fun x -> Dep.Method (cid, x)) diff let compare_smeths mode class1 class2 acc = let cid = class1.dc_name in let (elts1, elts2) = (class1.dc_smethods, class2.dc_smethods) in let diff = diff_elts (module StaticMethods) ~cid ~elts1 ~elts2 ~normalize:Decl_pos_utils.NormalizeSig.fun_elt in add_inverted_deps mode acc (fun x -> Dep.SMethod (cid, x)) diff let compare_cstrs mode class1 class2 = let cid = class1.dc_name in let match1 = match class1.dc_construct with | (Some elt, _) -> String.equal elt.elt_origin cid | _ -> false in let match2 = match class2.dc_construct with | (Some elt, _) -> String.equal elt.elt_origin cid | _ -> false in if match1 || match2 then match (Constructors.get_old cid, Constructors.get cid) with | (None, _) | (_, None) -> (Typing_deps.get_ideps mode (Dep.Constructor cid), `Changed) | (Some fe1, Some fe2) -> let fe1 = Decl_pos_utils.NormalizeSig.fun_elt fe1 in let fe2 = Decl_pos_utils.NormalizeSig.fun_elt fe2 in if Poly.( = ) fe1 fe2 then (DepSet.make (), `Unchanged) else (Typing_deps.get_ideps mode (Dep.Constructor cid), `Changed) else (DepSet.make (), `Unchanged) let compare mode class1 class2 = compare_cstrs mode class1 class2 |> compare_props mode class1 class2 |> compare_sprops mode class1 class2 |> compare_meths mode class1 class2 |> compare_smeths mode class1 class2 end (*****************************************************************************) (* Determines if there is a "big" difference between two classes * What it really means: most of the time, a change in a class doesn't affect * the users of the class, recomputing the sub-classes is enough. * However, there are some cases, where we really need to re-check all the * use cases of a class. For example: if a class doesn't implement an * interface anymore, all the subtyping is changed, so we have to recheck * all the places where the class was used. *) (*****************************************************************************) let class_big_diff class1 class2 = let class1 = Decl_pos_utils.NormalizeSig.class_type class1 in let class2 = Decl_pos_utils.NormalizeSig.class_type class2 in let ( <> ) = Poly.( <> ) in class1.dc_need_init <> class2.dc_need_init || SSet.compare class1.dc_deferred_init_members class2.dc_deferred_init_members <> 0 || class1.dc_kind <> class2.dc_kind || class1.dc_is_xhp <> class2.dc_is_xhp || class1.dc_has_xhp_keyword <> class2.dc_has_xhp_keyword || class1.dc_const <> class2.dc_const || class1.dc_tparams <> class2.dc_tparams || SMap.compare compare_subst_context class1.dc_substs class2.dc_substs <> 0 || SMap.compare Typing_defs.compare_decl_ty class1.dc_ancestors class2.dc_ancestors <> 0 || List.compare Poly.compare class1.dc_req_ancestors class2.dc_req_ancestors <> 0 || SSet.compare class1.dc_req_ancestors_extends class2.dc_req_ancestors_extends <> 0 || SSet.compare class1.dc_extends class2.dc_extends <> 0 || SSet.compare class1.dc_xhp_attr_deps class2.dc_xhp_attr_deps <> 0 || class1.dc_enum_type <> class2.dc_enum_type || class1.dc_internal <> class2.dc_internal || Option.map ~f:snd class1.dc_module <> Option.map ~f:snd class2.dc_module let get_extend_deps mode cid_hash acc = Typing_deps.get_extend_deps ~mode ~visited:(VisitedSet.make ()) ~source_class:cid_hash ~acc (*****************************************************************************) (* Determine which functions/classes have to be rechecked after comparing * the old and the new type signature of "fid" (function identifier). *) (*****************************************************************************) let get_fun_deps ~ctx ~mode old_funs fid (fanout_acc, old_funs_missing) = match ( SMap.find fid old_funs, match Provider_backend.get () with | Provider_backend.Rust_provider_backend backend -> Rust_provider_backend.Decl.get_fun backend (Naming_provider.rust_backend_ctx_proxy ctx) fid | _ -> Decl_heap.Funs.get fid ) with (* Note that we must include all dependencies even if we get the None, None * case. Due to the fact we can declare types lazily, there may be no * existing declaration in the old Decl_heap that corresponds to a function * `foo` in the AST. Then when the user deletes `foo`, the new Decl_heap * will also lack a definition of `foo`. Now we must recheck all the use * sites of `foo` to make sure there are no dangling references. *) | (None, _) | (_, None) -> let dep = Dep.Fun fid in let fanout_acc = Fanout.add_fanout_of mode dep fanout_acc in (fanout_acc, old_funs_missing + 1) | (Some fe1, Some fe2) -> let fe1 = Decl_pos_utils.NormalizeSig.fun_elt fe1 in let fe2 = Decl_pos_utils.NormalizeSig.fun_elt fe2 in if Poly.( = ) fe1 fe2 then (fanout_acc, old_funs_missing) else let dep = Dep.Fun fid in let fanout_acc = Fanout.add_fanout_of mode dep fanout_acc in (fanout_acc, old_funs_missing) let get_funs_deps ~ctx old_funs funs = let mode = Provider_context.get_deps_mode ctx in SSet.fold (get_fun_deps ~ctx ~mode old_funs) funs (Fanout.empty, 0) (*****************************************************************************) (* Determine which functions/classes have to be rechecked after comparing * the old and the new typedef *) (*****************************************************************************) let get_type_deps ~ctx ~mode old_types tid (fanout_acc, old_types_missing) = match ( SMap.find tid old_types, match Provider_backend.get () with | Provider_backend.Rust_provider_backend backend -> Rust_provider_backend.Decl.get_typedef backend (Naming_provider.rust_backend_ctx_proxy ctx) tid | _ -> Decl_heap.Typedefs.get tid ) with | (None, _) | (_, None) -> let dep = Dep.Type tid in let fanout_acc = Fanout.add_fanout_of mode dep fanout_acc in (fanout_acc, old_types_missing + 1) | (Some tdef1, Some tdef2) -> let tdef1 = Decl_pos_utils.NormalizeSig.typedef tdef1 in let tdef2 = Decl_pos_utils.NormalizeSig.typedef tdef2 in let is_same_signature = Poly.( = ) tdef1 tdef2 in if is_same_signature then (fanout_acc, old_types_missing) else let dep = Dep.Type tid in let fanout_acc = Fanout.add_fanout_of mode dep fanout_acc in (fanout_acc, old_types_missing) let get_types_deps ~ctx old_types types = let mode = Provider_context.get_deps_mode ctx in SSet.fold (get_type_deps ~ctx ~mode old_types) types (Fanout.empty, 0) (*****************************************************************************) (* Determine which top level definitions have to be rechecked if the constant * changed. *) (*****************************************************************************) let get_gconst_deps ~ctx ~mode old_gconsts cst_id (fanout_acc, old_gconsts_missing) = let cst1 = SMap.find cst_id old_gconsts in let cst2 = match Provider_backend.get () with | Provider_backend.Rust_provider_backend backend -> Rust_provider_backend.Decl.get_gconst backend (Naming_provider.rust_backend_ctx_proxy ctx) cst_id | _ -> Decl_heap.GConsts.get cst_id in match (cst1, cst2) with | (None, _) | (_, None) -> let fanout_acc = fanout_acc |> Fanout.add_fanout_of mode (Dep.GConst cst_id) |> Fanout.add_fanout_of mode (Dep.GConstName cst_id) in (fanout_acc, old_gconsts_missing + 1) | (Some cst1, Some cst2) -> let is_same_signature = Poly.( = ) cst1 cst2 in if is_same_signature then (fanout_acc, old_gconsts_missing) else let dep = Dep.GConst cst_id in let fanout_acc = Fanout.add_fanout_of mode dep fanout_acc in (fanout_acc, old_gconsts_missing) let get_gconsts_deps ~ctx old_gconsts gconsts = let mode = Provider_context.get_deps_mode ctx in SSet.fold (get_gconst_deps ~ctx ~mode old_gconsts) gconsts (Fanout.empty, 0) let rule_changed rule1 rule2 = match (rule1, rule2) with | (MRGlobal, MRGlobal) -> false | (MRExact m1, MRExact m2) -> not (String.equal m1 m2) | (MRPrefix p1, MRPrefix p2) -> not (String.equal p1 p2) | _ -> true let rules_changed rules1 rules2 = match (rules1, rules2) with | (None, None) -> false | (_, None) | (None, _) -> true | (Some rules_list1, Some rules_list2) -> (match List.exists2 rules_list1 rules_list2 ~f:rule_changed with | List.Or_unequal_lengths.Ok res -> res | List.Or_unequal_lengths.Unequal_lengths -> true) let get_module_deps ~ctx ~mode old_modules mid (fanout_acc, old_modules_missing) : Fanout.t * int = match ( SMap.find mid old_modules, match Provider_backend.get () with | Provider_backend.Rust_provider_backend backend -> Rust_provider_backend.Decl.get_module backend (Naming_provider.rust_backend_ctx_proxy ctx) mid | _ -> Decl_heap.Modules.get mid ) with | (None, _) | (_, None) -> let dep = Dep.Module mid in let fanout_acc = Fanout.add_fanout_of mode dep fanout_acc in (fanout_acc, old_modules_missing + 1) | (Some module1, Some module2) -> if rules_changed module1.mdt_exports module2.mdt_exports || rules_changed module1.mdt_imports module2.mdt_imports then let dep = Dep.Module mid in let fanout_acc = Fanout.add_fanout_of mode dep fanout_acc in (fanout_acc, old_modules_missing) else (fanout_acc, old_modules_missing) let get_modules_deps ~ctx ~old_modules ~modules = let mode = Provider_context.get_deps_mode ctx in SSet.fold (get_module_deps ~ctx ~mode old_modules) modules (Fanout.empty, 0)
OCaml Interface
hhvm/hphp/hack/src/decl/decl_compare.mli
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Typing_deps open Decl_heap val class_big_diff : Class.t -> Class.t -> bool module ClassDiff : sig val compare : Typing_deps_mode.t -> string -> Class.t -> Class.t -> DepSet.t * bool end module ClassEltDiff : sig val compare : Typing_deps_mode.t -> Class.t -> Class.t -> DepSet.t * [> `Changed | `Unchanged ] end val get_extend_deps : Typing_deps_mode.t -> DepSet.elt -> DepSet.t -> DepSet.t val get_funs_deps : ctx:Provider_context.t -> Funs.value option SMap.t -> SSet.t -> Fanout.t * int val get_types_deps : ctx:Provider_context.t -> Typedef.t option SMap.t -> SSet.t -> Fanout.t * int val get_gconsts_deps : ctx:Provider_context.t -> GConsts.value option SMap.t -> SSet.t -> Fanout.t * int val get_modules_deps : ctx:Provider_context.t -> old_modules:Modules.value option SMap.t -> modules:SSet.t -> Fanout.t * int
OCaml
hhvm/hphp/hack/src/decl/decl_counters.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude let mode = ref HackEventLogger.PerFileProfilingConfig.DeclingOff type decl_kind = | Class | Fun | GConst | Typedef | Module_decl [@@deriving show { with_path = false }] type origin = | Body | TopLevel | Tast | Variance | NastCheck | TastCheck [@@deriving show { with_path = false }] type subdecl_kind = (* Shallow *) | Abstract | Final | Const | Kind | Is_xhp | Name | Module | Internal | IsModuleLevelTrait | Pos | Tparams | Where_constraints | Enum_type | Xhp_enum_values | Xhp_marked_empty | Sealed_whitelist | Docs_url | Decl_errors | Support_dynamic_type (* Lazy *) | Construct | Need_init | Get_ancestor of string [@printer (fun fmt _s -> fprintf fmt "Get_ancestor")] | Has_ancestor of string [@printer (fun fmt _s -> fprintf fmt "Has_ancestor")] | Requires_ancestor of string [@printer (fun fmt _s -> fprintf fmt "Requires_ancestor")] | Extends of string [@printer (fun fmt _s -> fprintf fmt "Extends")] | Is_disposable | Get_const of string [@printer (fun fmt _s -> fprintf fmt "Get_const")] | Has_const of string [@printer (fun fmt _s -> fprintf fmt "Has_const")] | Get_typeconst of string [@printer (fun fmt _s -> fprintf fmt "Get_typeconst")] | Has_typeconst of string [@printer (fun fmt _s -> fprintf fmt "Has_typeconst")] | Get_typeconst_enforceability of string [@printer (fun fmt _s -> fprintf fmt "Get_typeconst_enforceability")] | Get_prop of string [@printer (fun fmt _s -> fprintf fmt "Get_prop")] | Has_prop of string [@printer (fun fmt _s -> fprintf fmt "Has_prop")] | Get_sprop of string [@printer (fun fmt _s -> fprintf fmt "Get_sprop")] | Has_sprop of string [@printer (fun fmt _s -> fprintf fmt "Has_sprop")] | Get_method of string [@printer (fun fmt _s -> fprintf fmt "Get_method")] | Has_method of string [@printer (fun fmt _s -> fprintf fmt "Has_method")] | Get_smethod of string [@printer (fun fmt _s -> fprintf fmt "Get_smethod")] | Has_smethod of string [@printer (fun fmt _s -> fprintf fmt "Has_smethod")] (* Eager *) | Members_fully_known | All_ancestor_req_names | All_extends_ancestors | All_ancestors | All_ancestor_names | All_ancestor_reqs | Consts | Typeconsts | Props | SProps | Methods | SMethods | Overridden_method (* Misc *) | Deferred_init_members [@@deriving show { with_path = false }] type tracing_info = { origin: origin; file: Relative_path.t; } let subdecl_member_name (subdecl_kind : subdecl_kind) : string option = match subdecl_kind with | Get_ancestor s | Has_ancestor s | Requires_ancestor s | Extends s | Get_const s | Has_const s | Get_typeconst s | Has_typeconst s | Get_prop s | Has_prop s | Get_sprop s | Has_sprop s | Get_method s | Has_method s | Get_smethod s | Has_smethod s -> Some s | _ -> None let subdecl_eagerness (subdecl_kind : subdecl_kind) : string = match subdecl_kind with | Abstract | Final | Const | Kind | Is_xhp | Name | Module | Internal | IsModuleLevelTrait | Pos | Tparams | Where_constraints | Enum_type | Xhp_enum_values | Xhp_marked_empty | Sealed_whitelist | Docs_url | Decl_errors | Support_dynamic_type -> "shallow" | Construct | Need_init | Get_ancestor _ | Has_ancestor _ | Requires_ancestor _ | Extends _ | Is_disposable | Get_const _ | Has_const _ | Get_typeconst _ | Has_typeconst _ | Get_typeconst_enforceability _ (* Get_typeconst_enforceability is technically lazy, but much less so than Get_typeconst *) | Get_prop _ | Has_prop _ | Get_sprop _ | Has_sprop _ | Get_method _ | Has_method _ | Get_smethod _ | Has_smethod _ -> "lazy" | Members_fully_known | All_ancestor_req_names | All_extends_ancestors | All_ancestors | All_ancestor_names | All_ancestor_reqs | Consts | Typeconsts | Props | SProps | Methods | SMethods | Overridden_method -> "eager" | Deferred_init_members -> "misc" (** This type provides context that flows from the time someone accessed the top-level Class decl, through to the time that they accessed a subsidiary decl like Get_method. It's used solely in telemetry. The Decl_id would be enough alone to do a JOIN on the telemetry to relate the decl to the subdecl. But for convenience we're also carrying additional information to not even need the join. *) type decl = { decl_id: string; (** a randomly generated ID unique to this particular top-level retrieval, i.e. invocation of get_class / get_fun / ... *) decl_name: string; (** name of the top-level class/fun/... that was retrieved *) decl_origin: origin option; (** a classification of what larger purpose the code was engaged in, at the moment of top-level decl retrieval. The caller of get_class / get_fun / ... will opt into self-describing itself with a suitable origin. As mentioned above, this is used solely for telemetry classification. *) decl_file: Relative_path.t option; (** the file we were typechecking at the moment of top-level decl retrieval. The caller of get_class / get_fun / ... will opt into providing a filename. *) decl_callstack: string option; (** callstack at the moment of top-level decl retrieval. This is optional in case the user opted out of (costly) callstack fetching. *) decl_start_time: float; (** wall-time at the moment of top-level decl retrieval *) } let set_mode (new_mode : HackEventLogger.PerFileProfilingConfig.profile_decling) : unit = mode := new_mode let count_decl ?(tracing_info : tracing_info option) (decl_kind : decl_kind) (decl_name : string) (f : decl option -> 'a) : 'a = match !mode with | HackEventLogger.PerFileProfilingConfig.DeclingOff -> (* CARE! This path must be highly performant. *) f None | HackEventLogger.PerFileProfilingConfig.DeclingTopCounts -> Counters.count Counters.Category.Decling (fun () -> f None) | HackEventLogger.PerFileProfilingConfig.DeclingAllTelemetry { callstacks } -> let start_time = Unix.gettimeofday () in let start_cpu_time = Sys.time () in let decl_id = Random_id.short_string () in let decl_callstack = if callstacks then Some (Exception.get_current_callstack_string 99 |> Exception.clean_stack) else None in let decl = { decl_id; decl_name; decl_callstack; decl_origin = Option.map tracing_info ~f:(fun ti -> ti.origin); decl_file = Option.map tracing_info ~f:(fun ti -> ti.file); decl_start_time = start_time; } in let result = f (Some decl) in HackEventLogger.ProfileDecl.count_decl ~kind:(show_decl_kind decl_kind) ~cpu_duration:(Sys.time () -. start_cpu_time) ~decl_id ~decl_name ~decl_origin:(Option.map decl.decl_origin ~f:show_origin) ~decl_file:decl.decl_file ~decl_callstack ~decl_start_time:start_time ~subdecl_member_name:None ~subdecl_eagerness:None ~subdecl_callstack:None ~subdecl_start_time:None; result let count_subdecl (decl : decl option) (subdecl_kind : subdecl_kind) (f : unit -> 'a) : 'a = match decl with | None -> (* CARE! This path must be highly performant. It's called tens of thousands of times per file. The earlier function count_decl had used "decl=None" to signal that no logging is needed for subdecl accesses, and here we're (cheaply) picking up that fact. *) f () | Some decl -> let start_time = Unix.gettimeofday () in let start_cpu_time = Sys.time () in let subdecl_get_callstack = Option.map decl.decl_callstack ~f:(fun _ -> Exception.get_current_callstack_string 99 |> Exception.clean_stack) in let result = f () in HackEventLogger.ProfileDecl.count_decl ~kind:("Class." ^ show_subdecl_kind subdecl_kind) ~cpu_duration:(Sys.time () -. start_cpu_time) ~decl_id:decl.decl_id ~decl_name:decl.decl_name ~decl_origin:(Option.map decl.decl_origin ~f:show_origin) ~decl_file:decl.decl_file ~decl_callstack:decl.decl_callstack ~decl_start_time:decl.decl_start_time ~subdecl_member_name:(subdecl_member_name subdecl_kind) ~subdecl_eagerness:(Some (subdecl_eagerness subdecl_kind)) ~subdecl_callstack:subdecl_get_callstack ~subdecl_start_time:(Some start_time); result
OCaml Interface
hhvm/hphp/hack/src/decl/decl_counters.mli
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (** This opaque type carries decl_counter-specific context that will be used in telemetry to relate the subdecl accessors like "get member foo of class", back to the original decl accessor "get the class named Bar" which got this specific class in the first place. *) type decl type decl_kind = | Class | Fun | GConst | Typedef | Module_decl (** The idea of [origin] is so that callsites have a way of characterizing what they are, and have this characterization end up in telemetry. That's all. *) type origin = | Body (** block, expr, statement *) | TopLevel (** typing_toplevel stuff, well-formedness *) | Tast (** tast_env *) | Variance (** typing_variance *) | NastCheck (** typing/nast_check *) | TastCheck (** typing/tast_check *) type subdecl_kind = (* Shallow *) | Abstract | Final | Const | Kind | Is_xhp | Name | Module | Internal | IsModuleLevelTrait | Pos | Tparams | Where_constraints | Enum_type | Xhp_enum_values | Xhp_marked_empty | Sealed_whitelist | Docs_url | Decl_errors | Support_dynamic_type (* Lazy *) | Construct | Need_init | Get_ancestor of string | Has_ancestor of string | Requires_ancestor of string | Extends of string | Is_disposable | Get_const of string | Has_const of string | Get_typeconst of string | Has_typeconst of string | Get_typeconst_enforceability of string | Get_prop of string | Has_prop of string | Get_sprop of string | Has_sprop of string | Get_method of string | Has_method of string | Get_smethod of string | Has_smethod of string (* Eager *) | Members_fully_known | All_ancestor_req_names | All_extends_ancestors | All_ancestors | All_ancestor_names | All_ancestor_reqs | Consts | Typeconsts | Props | SProps | Methods | SMethods | Overridden_method (* Misc *) | Deferred_init_members type tracing_info = { origin: origin; file: Relative_path.t; } (** E.g. 'count_decl Class "Foo" (fun d -> <implementation>)'. The idea is that <implementation> is the body of work which fetches the decl of class "foo", and we want to record telemetry about its performance. This function will execute <implementation>, and will internally keep track of things like how long it took and what decl was fetched, and will log the telemetry appropriately. The callback takes a parameter [d]. This is for use of subsidiary decl accessors, e.g. 'count_subdecl d (Get_method "bar") (fun () -> <implementation2>)'. It's so that, when we record telemetry about <implementation2>, we can relate it back to the original count_decl which fetched the class Foo in the first place. [d] is optional; it will be None if e.g. the original call to count_decl established that no telemetry should be collected during this run, and we want to avoid re-establishing this fact during the call to count_subdecl. *) val count_decl : ?tracing_info:tracing_info -> decl_kind -> string -> (decl option -> 'a) -> 'a (** E.g. 'count_subdecl d (Get_method "bar") (fun () -> <implementation2>)'. The idea is that <implementation2> is the body of work which fetches the decl of method 'bar' of some class, and we want to record telemetry about its performance. This function will execution <implementation2> , and will internally keep track of things like how long it took, and will log the telemetry appropriately. *) val count_subdecl : decl option -> subdecl_kind -> (unit -> 'a) -> 'a val set_mode : HackEventLogger.PerFileProfilingConfig.profile_decling -> unit
OCaml
hhvm/hphp/hack/src/decl/decl_defs.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 Typing_defs (** Exception representing not finding a class during decl *) exception Decl_not_found of string let raise_decl_not_found (path : Relative_path.t option) (name : string) : 'a = HackEventLogger.decl_consistency_bug ?path ~data:name "Decl_not_found"; let err_str = Printf.sprintf "%s not found in %s" name (Option.value_map path ~default:"_" ~f:Relative_path.to_absolute) in Hh_logger.log "Decl_not_found: %s\n%s" err_str (Exception.get_current_callstack_string 99 |> Exception.clean_stack); raise (Decl_not_found err_str) (** A substitution context contains all the information necessary for * changing the type of an inherited class element to the class that is * inheriting the class element. It's best illustrated via an example. * * ``` * class A<Ta1, Ta2> { public function test(Ta1 $x, Ta2 $y): void {} } * * class B<Tb> extends A<Tb, int> {} * * class C extends B<string> {} * ``` * * The method `A::test()` has the type (function(Ta1, Ta2): void) in the * context of class A. However in the context of class B, it will have type * (function(Tb, int): void). * The substitution that leads to this change is [Ta1 -> Tb, Ta2 -> int], * which will produce a new type in the context of class B. It's subst_context * would then be: * * ``` * { sc_subst = [Ta1 -> Tb, Ta2 -> int]; * sc_class_context = 'B'; * sc_from_req_extends = false; * } * ``` * * The `sc_from_req_extends` field is set to true if the context was inherited * via a require extends type. This information is relevant when folding * `dc_substs` during inheritance. See Decl_inherit module. *) type subst_context = { sc_subst: decl_ty SMap.t; sc_class_context: string; sc_from_req_extends: bool; } [@@deriving show, ord] type source_type = | Child | Parent | Trait | XHPAttr | Interface | IncludedEnum | ReqImpl | ReqExtends | ReqClass [@@deriving eq, show] type decl_error = | Wrong_extend_kind of { pos: Pos.t; kind: Ast_defs.classish_kind; name: string; parent_pos: Pos_or_decl.t; parent_kind: Ast_defs.classish_kind; parent_name: string; } | Cyclic_class_def of { pos: Pos.t; stack: SSet.t; } [@@deriving show] type decl_class_type = { dc_need_init: bool; dc_abstract: bool; dc_final: bool; dc_const: bool; dc_internal: bool; dc_deferred_init_members: SSet.t; dc_kind: Ast_defs.classish_kind; dc_is_xhp: bool; dc_has_xhp_keyword: bool; dc_module: Ast_defs.id option; dc_is_module_level_trait: bool; dc_name: string; dc_pos: Pos_or_decl.t; dc_tparams: decl_tparam list; dc_where_constraints: decl_where_constraint list; dc_substs: subst_context SMap.t; (** class name to the subst_context that must be applied to that class *) dc_consts: class_const SMap.t; dc_typeconsts: typeconst_type SMap.t; dc_props: element SMap.t; dc_sprops: element SMap.t; dc_methods: element SMap.t; dc_smethods: element SMap.t; dc_construct: element option * consistent_kind; dc_ancestors: decl_ty SMap.t; dc_support_dynamic_type: bool; dc_req_ancestors: requirement list; dc_req_ancestors_extends: SSet.t; dc_req_class_ancestors: requirement list; (** dc_req_class_ancestors gathers all the `require class` * requirements declared in ancestors. Remark that `require class` * requirements are _not_ stored in `dc_req_ancestors` or *`dc_req_ancestors_extends` fields. *) dc_extends: SSet.t; dc_sealed_whitelist: SSet.t option; dc_xhp_attr_deps: SSet.t; dc_xhp_enum_values: Ast_defs.xhp_enum_value list SMap.t; dc_xhp_marked_empty: bool; dc_enum_type: enum_type option; dc_decl_errors: decl_error list; dc_docs_url: string option; } [@@deriving show] and element = { elt_flags: Typing_defs_flags.ClassElt.t; elt_origin: string; elt_visibility: ce_visibility; elt_deprecated: string option; } let get_elt_abstract elt = Typing_defs_flags.ClassElt.is_abstract elt.elt_flags let get_elt_final elt = Typing_defs_flags.ClassElt.is_final elt.elt_flags let get_elt_lsb elt = Typing_defs_flags.ClassElt.has_lsb elt.elt_flags (** Whether a class element comes from a `require extends`. *) let get_elt_synthesized elt = Typing_defs_flags.ClassElt.is_synthesized elt.elt_flags let get_elt_xhp_attr elt = Typing_defs_flags.ClassElt.get_xhp_attr elt.elt_flags let get_elt_needs_init elt = Typing_defs_flags.ClassElt.needs_init elt.elt_flags let set_elt_synthesized elt = { elt with elt_flags = Typing_defs_flags.ClassElt.set_synthesized elt.elt_flags; } let reset_elt_superfluous_override elt = { elt with elt_flags = Typing_defs_flags.ClassElt.reset_superfluous_override elt.elt_flags; }
OCaml
hhvm/hphp/hack/src/decl/decl_enforceability.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 Typing_defs let ( let* ) = Option.Let_syntax.( let* ) let is_typedef ctx x = match Naming_provider.get_type_kind ctx x with | Some Naming_types.TTypedef -> true | _ -> false type enf = (* The type is fully enforced *) | Enforced of decl_ty (* The type is not fully enforced, but is enforced at the given ty, if present *) | Unenforced of decl_ty option type 'a class_or_typedef_result = | ClassResult of 'a | TypedefResult of Typing_defs.typedef_type let get_class_or_typedef ctx x = if is_typedef ctx x then match Typedef_provider.get_typedef ctx x with | None -> None | Some td -> Some (TypedefResult td) else match Shallow_classes_provider.get ctx x with | None -> None | Some cd -> Some (ClassResult cd) let get_typeconst_type ctx c id = let open Shallow_decl_defs in (* Look for id directly defined in the given shallow class. Assume there is only one, since it is an error to have multiple definitions. *) let find_locally c = List.find_map ~f:(fun stc -> if String.equal id (snd stc.stc_name) then Some stc.stc_kind else None) c.sc_typeconsts in let class_type_to_shallow_class cty = match get_node cty with | Tapply ((_, class_name), _) -> Shallow_classes_provider.get ctx class_name | _ -> None in (* Find the first concrete definition of id in the list. If there is none, return the first abstract one, kept in found_abstract *) let rec find_in_list visited found_abstract ctys = match ctys with | [] -> found_abstract | cty :: ctys -> let c = class_type_to_shallow_class cty in (match c with | None -> find_in_list visited found_abstract ctys | Some c -> (match find_in_class visited c with | None -> find_in_list visited found_abstract ctys | Some (TCAbstract _) as new_abstract -> (match found_abstract with | None -> find_in_list visited new_abstract ctys | _ -> find_in_list visited found_abstract ctys) | Some (TCConcrete _ as res) -> Some res)) (* Look for id in c, either locally, or inherited *) and find_in_class visited c = if SSet.mem (snd c.sc_name) visited then None else match find_locally c with | Some tc -> Some tc | None -> find_in_list (SSet.add (snd c.sc_name) visited) None (List.concat [ c.sc_extends; c.sc_implements; c.sc_uses; c.sc_req_extends; c.sc_req_implements; ]) in let* tc = find_in_class SSet.empty c in match tc with | TCAbstract abstract -> abstract.atc_as_constraint | TCConcrete concrete -> Some concrete.tc_type let make_unenforced ty = match ty with | Enforced ty -> Unenforced (Some ty) | Unenforced _ -> ty module VisitedSet = Caml.Set.Make (struct type t = string * string let compare (s1, r1) (s2, r2) = let c1 = String.compare s1 s2 in if c1 = 0 then String.compare r1 r2 else c1 end) module type ContextAccess = sig (** [t] is the type of the context that classes and typedefs can be found in *) type t (** [class_t] is the type that represents a class *) type class_t val get_tcopt : t -> TypecheckerOptions.t val get_class_or_typedef : t -> string -> class_t class_or_typedef_result option val get_typedef : t -> string -> typedef_type option val get_class : t -> string -> class_t option (** [get_typeconst ctx cls name] gets the definition of the type constant [name] from [cls] or ancestor if it exists. *) val get_typeconst_type : t -> class_t -> string -> decl_ty option val get_tparams : class_t -> decl_tparam list val get_name : class_t -> string (** [get_enum_type cls] returns the enumeration type if [cls] is an enum. *) val get_enum_type : class_t -> enum_type option end module type Enforcement = sig type ctx type class_t val get_enforcement : return_from_async:bool -> this_class:class_t option -> ctx -> Typing_defs.decl_ty -> enf val is_enforceable : return_from_async:bool -> this_class:class_t option -> ctx -> Typing_defs.decl_ty -> bool end module Enforce (ContextAccess : ContextAccess) : Enforcement with type ctx = ContextAccess.t and type class_t = ContextAccess.class_t = struct type ctx = ContextAccess.t type class_t = ContextAccess.class_t let add_to_visited visited cd ty = let name = ContextAccess.get_name cd in VisitedSet.add (name, ty) visited let mem_visited visited cd ty = let name = ContextAccess.get_name cd in VisitedSet.mem (name, ty) visited (* Find the class definition that ty represents, by expanding Taccess. Since expanding one Taccess might give us another type containing Taccess, we keep a set of visited type constant definitions and terminate if we reach a cycle. *) let rec get_owner ~this_class visited (ctx : ContextAccess.t) ty = match get_node ty with | Tthis -> this_class | Tapply ((_, name), _) -> ContextAccess.get_class ctx name | Taccess (ty, (_, tcname)) -> let* (visited, cd, ty) = get_owner_and_type ~this_class visited ctx ty tcname in get_owner ~this_class:(Some cd) visited ctx ty | _ -> None (* Lookup tcname in the class that ty represents. *) and get_owner_and_type ~this_class visited (ctx : ContextAccess.t) ty tcname = let* cd = get_owner ~this_class visited ctx ty in if mem_visited visited cd tcname then None else let* ty = ContextAccess.get_typeconst_type ctx cd tcname in Some (add_to_visited visited cd tcname, cd, ty) (* Resolve an access t::T to a type that is not an access *) let resolve_access ~this_class (ctx : ContextAccess.t) ty tcname = (* We need to maintain a visited set because there can be cycles between bounds on type constants *) let rec resolve_access ~this_class visited (ctx : ContextAccess.t) ty tcname = let* (visited, cd, ty) = get_owner_and_type ~this_class visited ctx ty tcname in match get_node ty with | Taccess (sub_ty, (_, tcname)) -> resolve_access ~this_class:(Some cd) visited ctx sub_ty tcname | _ -> Some ty in resolve_access ~this_class VisitedSet.empty ctx ty tcname let get_enforcement ~return_from_async ~this_class (ctx : ContextAccess.t) (ty : decl_ty) : enf = let tcopt = ContextAccess.get_tcopt ctx in let enable_sound_dynamic = TypecheckerOptions.enable_sound_dynamic tcopt in let tc_enforced = TypecheckerOptions.( experimental_feature_enabled tcopt experimental_consider_type_const_enforceable) in let ty_pos = get_pos ty in (* is_dynamic_enforceable controls whether the type dynamic is considered enforceable. It isn't at the top-level of a type, but is as an argument to a reified generic. *) let rec enforcement ~is_dynamic_enforceable (ctx : ContextAccess.t) visited ty = match get_node ty with | Tthis -> Unenforced None (* Look through supportdyn, just as we look through ~ *) | Tapply ((_, name), [ty]) when String.equal name Naming_special_names.Classes.cSupportDyn && enable_sound_dynamic -> enforcement ~is_dynamic_enforceable ctx visited ty | Tapply ((_, name), tyl) -> (* Cyclic type definition error will be produced elsewhere *) if SSet.mem name visited then Unenforced None else begin (* The pessimised definition depends on the class or typedef being referenced, but we aren't adding any dependency edges here. It is therefore critical that we are sure thay are added elsewhere. Currently, that is when we revisit this type in Typing_enforceability when we are typechecking the function/property definition it is part of. *) match ContextAccess.get_class_or_typedef ctx name with | Some (TypedefResult { td_vis = Aast.(CaseType | Transparent); td_type; _ }) -> (* Expand type definition one step and compute its enforcement. * While case types are Tnewtype in the type system, at runtime * they are enforced transparently. TODO(dreeves) Case types * may need to be intersected with their cover types at most. *) enforcement ~is_dynamic_enforceable ctx (SSet.add name visited) td_type | Some (TypedefResult { td_vis = Aast.Opaque; td_pos; td_type; td_as_constraint; td_tparams; _; }) -> let transparent = Relative_path.equal (Pos_or_decl.filename ty_pos) (Pos_or_decl.filename td_pos) in let exp_ty = enforcement ~is_dynamic_enforceable ctx (SSet.add name visited) td_type in if not (Int.equal (List.length td_tparams) (List.length tyl)) then (* If there is an arity error then assume enforced because this is * used to fake a Tany at localization time *) Enforced td_type else if transparent then (* Same as transparent case *) exp_ty else ( (* Similar to enums, newtypes must not be pessimised to their * enforced types, otherwise for `newtype N = int;`, pessimising * `N` to `~N & int` tells the truth, but breaks N's opaqueness. * For `newtype N as O = P;` we want to allow `N` to override `O`, * but it is not safe to just use the constraint to get `~N & O`. * Consider `newtype N as IE = IE;` and `enum IE : int { A = 4; }`. * `N` will only be enforced at `int`, whereas `~N & IE` lies * that the value is definitely a member of `IE`. We could look at * the enforcement of `O`, but it is valid to have newtypes point * to enforced values but be constrained by unenforced ones, e.g. * `newtype N as G<int> = int; newtype G<T> as T = T;`. Looking at * `N`'s constraint's enforcement would take us to just `~N`. This * could not override a non-pessimised `int`, which is a shame * because we know N is an int. * * To compromise, if `newtype N as O = P;` is enforced at `Q`, we * pessimise `N` to `~N & (O | Q)`. This allows the value to flow * into an `O` if `Q` is a subtype of `O`, while making sure we * are intersecting only with something the runtime verifies i.e. * some type at least as large as `Q`. * *) match (exp_ty, td_as_constraint) with | ((Enforced ty | Unenforced (Some ty)), Some cstr) -> Unenforced (Some (Typing_make_type.union (get_reason cstr) [cstr; ty])) | _ -> Unenforced None ) | Some (TypedefResult { td_vis = Aast.OpaqueModule; _ }) -> Unenforced None | Some (ClassResult cls) -> (match ContextAccess.get_enum_type cls with | Some et -> (* for `enum E : int`, pessimising `E` to `~E & int` violates the * opacity of the enum, allowing the value to flow to a position * expecting `int`. We instead weaken our pessimised type to * `~E & arraykey`. For transparent enums `enum F : int as int`, * we pessimise to `~F & int`. *) let intersected_type = Option.value ~default:(Typing_make_type.arraykey (get_reason et.te_base)) et.te_constraint in make_unenforced (enforcement ~is_dynamic_enforceable ctx (SSet.add name visited) intersected_type) | None -> List.Or_unequal_lengths.( (match List.for_all2 tyl (ContextAccess.get_tparams cls) ~f:(fun targ tparam -> match get_node targ with | Tdynamic (* We accept the inner type being dynamic regardless of reification *) | Tlike _ when not enable_sound_dynamic -> true | _ -> (match tparam.tp_reified with | Aast.Erased -> false | Aast.SoftReified -> false | Aast.Reified -> (match enforcement ~is_dynamic_enforceable:true ctx visited targ with | Unenforced _ -> false | Enforced _ -> true))) with | Ok false | Unequal_lengths -> Unenforced None | Ok true -> Enforced ty))) | None -> Unenforced None end | Tgeneric _ -> (* Previously we allowed dynamic ~> T when T is an __Enforceable generic, * that is, when it's valid on the RHS of an `is` or `as` expression. * However, `is` / `as` checks have different behavior than runtime checks * for `tuple`s and `shapes`s; `is` / `as` will shallow-ly check declared * fields but typehint enforcement only checks that we have the right * array type (`varray` for `tuple`, `darray` for `shape`). This means * it's unsound to allow this coercion. * * Additionally, higher kinded generics (i.e., with type arguments) cannot * be enforced at the moment; they are disallowed to have upper bounds. *) Unenforced None | Trefinement _ -> Unenforced None | Taccess (ty, (_, id)) when tc_enforced -> (match resolve_access ~this_class ctx ty id with | None -> Unenforced None | Some ty -> enforcement ~is_dynamic_enforceable ctx visited ty) | Taccess _ -> Unenforced None | Tlike ty when enable_sound_dynamic -> enforcement ~is_dynamic_enforceable ctx visited ty | Tlike _ -> Unenforced None | Tprim Aast.(Tvoid | Tnoreturn) -> Unenforced None | Tprim _ -> Enforced ty | Tany _ -> Enforced ty | Tnonnull -> Enforced ty | Tdynamic -> if (not enable_sound_dynamic) || is_dynamic_enforceable then Enforced ty else Unenforced None | Tfun _ -> Unenforced None | Ttuple _ -> Unenforced None | Tunion [] -> Enforced ty | Tunion _ -> Unenforced None | Tintersection _ -> Unenforced None | Tshape _ -> Unenforced None | Tmixed -> Enforced ty | Twildcard -> Unenforced None (* With no parameters, we enforce varray_or_darray just like array *) | Tvec_or_dict (_, el_ty) -> if is_any el_ty then Enforced ty else Unenforced None | Toption ty -> (match enforcement ~is_dynamic_enforceable ctx visited ty with | Enforced _ -> Enforced ty | Unenforced (Some ety) -> Unenforced (Some (mk (get_reason ty, Toption ety))) | Unenforced None -> Unenforced None) | Tnewtype (name, _, _) -> if SSet.mem name visited then Unenforced None else ( match ContextAccess.get_typedef ctx name with | Some { td_vis = Aast.Opaque; td_type; _ } -> let exp_ty = enforcement ~is_dynamic_enforceable ctx (SSet.add name visited) td_type in make_unenforced exp_ty | Some { td_vis = Aast.OpaqueModule; _ } -> Unenforced None | _ -> failwith "should never happen" ) in if return_from_async then match get_node ty with | Tapply ((_, name), [ty]) when String.equal Naming_special_names.Classes.cAwaitable name -> enforcement ~is_dynamic_enforceable:false ctx SSet.empty ty | _ -> enforcement ~is_dynamic_enforceable:false ctx SSet.empty ty else enforcement ~is_dynamic_enforceable:false ctx SSet.empty ty let is_enforceable ~return_from_async ~this_class (ctx : ContextAccess.t) (ty : decl_ty) = match get_enforcement ~return_from_async ~this_class ctx ty with | Enforced _ -> true | Unenforced _ -> false end module ShallowContextAccess : ContextAccess with type t = Provider_context.t and type class_t = Shallow_decl_defs.shallow_class = struct type t = Provider_context.t type class_t = Shallow_decl_defs.shallow_class let get_tcopt = Provider_context.get_tcopt let get_class_or_typedef = get_class_or_typedef let get_typedef = Typedef_provider.get_typedef let get_class = Shallow_classes_provider.get let get_typeconst_type = get_typeconst_type let get_tparams sc = sc.Shallow_decl_defs.sc_tparams let get_name cd = snd cd.Shallow_decl_defs.sc_name let get_enum_type sc = sc.Shallow_decl_defs.sc_enum_type end module E = Enforce (ShallowContextAccess) include E let make_like_type ~intersect_with ~return_from_async ty = let like_and_intersect r ty = let like_ty = Typing_make_type.like r ty in match intersect_with with | None -> like_ty | Some enf_ty -> Typing_make_type.intersection r [enf_ty; like_ty] in let like_if_not_void ty = match get_node ty with | Tprim Aast.(Tvoid | Tnoreturn) -> ty | _ -> like_and_intersect (get_reason ty) ty in if return_from_async then match get_node ty with | Tapply ((pos, name), [ty]) when String.equal Naming_special_names.Classes.cAwaitable name -> mk ( get_reason ty, Tapply ((pos, name), [like_and_intersect (get_reason ty) ty]) ) | _ -> like_if_not_void ty else like_if_not_void ty let make_supportdyn_type p r ty = mk (r, Tapply ((p, Naming_special_names.Classes.cSupportDyn), [ty])) let supportdyn_mixed p r = make_supportdyn_type p r (mk (r, Tmixed)) let add_supportdyn_constraints p tparams = let r = Reason.Rwitness_from_decl p in List.map tparams ~f:(fun tparam -> if Naming_special_names.Coeffects.is_generated_generic (snd tparam.tp_name) || Typing_defs.Attributes.mem Naming_special_names.UserAttributes.uaNoAutoBound tparam.tp_user_attributes then tparam else { tparam with tp_constraints = (Ast_defs.Constraint_as, supportdyn_mixed p r) :: tparam.tp_constraints; }) let maybe_add_supportdyn_constraints ~this_class ctx p tparams = if Provider_context.implicit_sdt_for_class ctx this_class then add_supportdyn_constraints p tparams else tparams let pessimise_type ~is_xhp_attr ~this_class ctx ty = if (not is_xhp_attr) && is_enforceable ~return_from_async:false ~this_class ctx ty then ty else make_like_type ~intersect_with:None ~return_from_async:false ty let maybe_pessimise_type ~is_xhp_attr ~this_class ctx ty = if Provider_context.implicit_sdt_for_class ctx this_class then pessimise_type ~is_xhp_attr ~this_class ctx ty else ty let update_return_ty ft ty = { ft with ft_ret = { et_type = ty; et_enforced = Unenforced } } type fun_kind = | Function | Abstract_method | Concrete_method (* We do not pessimise parameter types *except* for inout parameters, * which we pessimise regardless of enforcement, because override doesn't * preserve enforcement e.g. `inout int` might beoverridden by `inout C::MyTypeConstant` *) let pessimise_param_type fp = match get_fp_mode fp with | FPnormal -> fp | FPinout -> { fp with fp_type = { et_enforced = Unenforced; et_type = make_like_type ~intersect_with:None ~return_from_async:false fp.fp_type.et_type; }; } (* How we pessimise a function depends on how the type is enforced, where the function is, and the experimental_always_pessimise_return option. The goal is to pessimise non-enforced return types to like types, while also avoiding hierarchy errors. If experimental_always_pessimise_return is set, the all methods should get like-types on their return to avoid hierarchy errors, but top-level functions should only be pessimised when the type is not enforceable. If experimental_always_pessimise_return is not set, we only pessimise the return of non-enforced types. Abstract methods do not have bodies to enforce anything, so we always pessimise their returns. For Concrete methods, if the type is only partially enforced, we pessimise and also intersect with the partially enforced type to avoid hierarchy errors. *) let pessimise_fun_type ~fun_kind ~this_class ~no_auto_likes ctx p ty = match get_node ty with | Tfun ft -> let ft = { ft with ft_tparams = add_supportdyn_constraints p ft.ft_tparams } in if no_auto_likes then mk (get_reason ty, Tfun ft) else let return_from_async = get_ft_async ft in let ret_ty = ft.ft_ret.et_type in let ft = { ft with ft_params = List.map ft.ft_params ~f:pessimise_param_type } in (match ( fun_kind, TypecheckerOptions.( experimental_feature_enabled (Provider_context.get_tcopt ctx) experimental_always_pessimise_return) ) with | (Concrete_method, true) | (Abstract_method, _) -> mk ( get_reason ty, Tfun (update_return_ty ft (make_like_type ~intersect_with:None ~return_from_async ret_ty)) ) | _ -> (match get_enforcement ~return_from_async ~this_class ctx ret_ty with | Enforced _ -> mk (get_reason ty, Tfun ft) | Unenforced enf_ty_opt -> (* For partially enforced type such as enums, we intersect with the * base type for concrete method return types in order to avoid * issues with hierarchies e.g. overriding a method that returns * the base type *) let intersect_with = match fun_kind with | Concrete_method -> enf_ty_opt | _ -> None in mk ( get_reason ty, Tfun (update_return_ty ft (make_like_type ~intersect_with ~return_from_async ret_ty)) ))) | _ -> ty
OCaml Interface
hhvm/hphp/hack/src/decl/decl_enforceability.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type enf = (* The type is fully enforced *) | Enforced of Typing_defs.decl_ty (* The type is not fully enforced, but is enforced at the given ty, if present *) | Unenforced of Typing_defs.decl_ty option type 'a class_or_typedef_result = | ClassResult of 'a | TypedefResult of Typing_defs.typedef_type module type ContextAccess = sig (** [t] is the type of the context that classes and typedefs can be found in *) type t (** [class_t] is the type that represents a class *) type class_t val get_tcopt : t -> TypecheckerOptions.t val get_class_or_typedef : t -> string -> class_t class_or_typedef_result option val get_typedef : t -> string -> Typing_defs.typedef_type option val get_class : t -> string -> class_t option (** [get_typeconst ctx cls name] gets the definition of the type constant [name] from [cls] or ancestor if it exists. *) val get_typeconst_type : t -> class_t -> string -> Typing_defs.decl_ty option val get_tparams : class_t -> Typing_defs.decl_tparam list val get_name : class_t -> string (** [get_enum_type cls] returns the enumeration type if [cls] is an enum. *) val get_enum_type : class_t -> Typing_defs.enum_type option end module type Enforcement = sig type ctx type class_t val get_enforcement : return_from_async:bool -> this_class:class_t option -> ctx -> Typing_defs.decl_ty -> enf val is_enforceable : return_from_async:bool -> this_class:class_t option -> ctx -> Typing_defs.decl_ty -> bool end module Enforce : functor (ContextAccess : ContextAccess) -> Enforcement with type ctx = ContextAccess.t and type class_t = ContextAccess.class_t (** Checks if a type is one that HHVM will enforce as a parameter or return. If the function is async, then the contents of the Awaitable return are enforced. Otherwise they aren't. *) val is_enforceable : return_from_async:bool -> this_class:Shallow_decl_defs.shallow_class option -> Provider_context.t -> Typing_defs.decl_ty -> bool (** If the type is not enforceable, turn it into a like type (~ty) otherwise return the type *) val pessimise_type : is_xhp_attr:bool -> this_class:Shallow_decl_defs.shallow_class option -> Provider_context.t -> Typing_defs.decl_ty -> Typing_defs.decl_ty (** Pessimise the type if in implicit pessimisation mode, otherwise return the type *) val maybe_pessimise_type : is_xhp_attr:bool -> this_class:Shallow_decl_defs.shallow_class option -> Provider_context.t -> Typing_defs.decl_ty -> Typing_defs.decl_ty type fun_kind = | Function | Abstract_method | Concrete_method (** If the return type is not enforceable, turn it into a like type (~ty) otherwise return the original function type. Also add supportdyn<mixed> to the type parameters. *) val pessimise_fun_type : fun_kind:fun_kind -> this_class:Shallow_decl_defs.shallow_class option -> no_auto_likes:bool -> Provider_context.t -> Pos_or_decl.t -> Typing_defs.decl_ty -> Typing_defs.decl_ty (** Add as supportdyn<mixed> constraints to the type parameters *) val add_supportdyn_constraints : Pos_or_decl.t -> Typing_defs.decl_ty Typing_defs_core.tparam list -> Typing_defs.decl_ty Typing_defs_core.tparam list (** Add as supportdyn<mixed> constraints to the type parameters if in implicit pessimisation mode.*) val maybe_add_supportdyn_constraints : this_class:Shallow_decl_defs.shallow_class option -> Provider_context.t -> Pos_or_decl.t -> Typing_defs.decl_ty Typing_defs_core.tparam list -> Typing_defs.decl_ty Typing_defs_core.tparam list val supportdyn_mixed : Pos_or_decl.t -> Typing_defs.Reason.decl_t -> Typing_defs.decl_ty
OCaml
hhvm/hphp/hack/src/decl/decl_enum.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 Aast open Typing_defs module SN = Naming_special_names type t = { base: Typing_defs.decl_ty; (** Underlying type of the enum, e.g. int or string. For subclasses of Enum, this is the type parameter of Enum. For enum classes, this is HH\MemberOf<E, I>. *) type_: Typing_defs.decl_ty; (** Type containing the enum name. For subclasses of Enum, this is also the type parameter of Enum. *) constraint_: Typing_defs.decl_ty option; (** Reflects what's after the [as] keyword in the enum definition. *) interface: Typing_defs.decl_ty option; (** For enum classes, this is the raw interface I, as provided by the user. *) } (** Figures out if a class needs to be treated like an enum. *) let enum_kind name ~is_enum_class enum inner_ty ~get_ancestor = match enum with | None -> (match get_ancestor SN.FB.cEnum with | Some enum -> begin match get_node enum with | Tapply ((_, enum), [ty_exp]) when String.equal enum SN.FB.cEnum -> Some { base = ty_exp; type_ = ty_exp; constraint_ = None; interface = None; } | Tapply ((_, enum_class), _) when String.equal enum_class SN.FB.cEnum -> let ty_exp = (* The fallback if the class does not declare TInner (i.e. it is * abstract) is to use this::TInner *) match inner_ty with | None -> let this = Typing_defs_core.mk (get_reason enum, Tthis) in Typing_defs_core.mk (get_reason enum, Taccess (this, (get_pos enum, SN.FB.tInner))) | Some ty -> ty in Some { base = ty_exp; type_ = ty_exp; constraint_ = None; interface = None; } | _ -> None end | _ -> None) | Some enum -> let reason = get_reason enum.te_base in let pos = Reason.to_pos reason in let enum_type = Typing_defs.mk (reason, Tapply (name, [])) in let (te_base, te_interface) = if is_enum_class then let te_interface = enum.te_base in let te_base = Tapply ((pos, SN.Classes.cMemberOf), [enum_type; enum.te_base]) in (* TODO(T77095784) make a new reason ! *) let te_base = mk (reason, te_base) in (te_base, Some te_interface) else (enum.te_base, None) in Some { base = te_base; type_ = Typing_defs.mk (get_reason enum.te_base, Tapply (name, [])); constraint_ = enum.te_constraint; interface = te_interface; } (** If a class is an Enum, we give all of the constants in the class the type of the Enum. We don't do this for Enum<mixed> and Enum<arraykey>, since that could *lose* type information. *) let rewrite_class name ~is_enum_class enum inner_ty ~get_ancestor consts = match enum_kind name ~is_enum_class enum inner_ty ~get_ancestor with | None -> consts | Some { base = _; type_ = ty; constraint_ = _; interface = te_interface } -> let te_enum_class = Option.is_some te_interface in (match get_node ty with | Tmixed | Tprim Tarraykey -> consts | _ -> (* A special constant called "class" gets added, and we don't * want to rewrite its type. * Also for enum class, the type is set in the lowerer. *) SMap.mapi (fun k c -> if te_enum_class || String.equal k SN.Members.mClass then c else { c with cc_type = ty }) consts)
OCaml Interface
hhvm/hphp/hack/src/decl/decl_enum.mli
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module SN = Naming_special_names type t = { base: Typing_defs.decl_ty; (** Underlying type of the enum, e.g. int or string. For subclasses of Enum, this is the type parameter of Enum. For enum classes, this is HH\MemberOf<E, I>. *) type_: Typing_defs.decl_ty; (** Type containing the enum name. For subclasses of Enum, this is also the type parameter of Enum. *) constraint_: Typing_defs.decl_ty option; (** Reflects what's after the [as] keyword in the enum definition. *) interface: Typing_defs.decl_ty option; (** For enum classes, this is the raw interface I, as provided by the user. *) } (** Figures out if a class needs to be treated like an enum. *) val enum_kind : Typing_defs.pos_id -> is_enum_class:bool -> Typing_defs.enum_type option -> Typing_defs.decl_ty option -> get_ancestor:(string -> Typing_defs.decl_phase Typing_defs.ty option) -> t option (** If a class is an Enum, we give all of the constants in the class the type of the Enum. We don't do this for Enum<mixed> and Enum<arraykey>, since that could *lose* type information. *) val rewrite_class : Typing_defs.pos_id -> is_enum_class:bool -> Typing_defs.enum_type option -> Typing_defs.decl_ty option -> get_ancestor:(string -> Typing_defs.decl_phase Typing_defs.ty option) -> Typing_defs.class_const SMap.t -> Typing_defs.class_const SMap.t
OCaml
hhvm/hphp/hack/src/decl/decl_env.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude type env = { mode: FileInfo.mode; droot: Typing_deps.Dep.dependent Typing_deps.Dep.variant option; droot_member: Typing_pessimisation_deps.dependent_member option; ctx: Provider_context.t; } let root_decl_reference env = env.droot |> Option.map ~f:Typing_deps.Dep.to_decl_reference let make_decl_pos env pos = (* TODO: fail if root_decl_reference returns None *) Pos_or_decl.make_decl_pos_of_option pos (root_decl_reference env) let make_decl_posed env posed = (* TODO: fail if root_decl_reference returns None *) Positioned.make_for_decl_of_option posed (root_decl_reference env) let tcopt env = Provider_context.get_tcopt env.ctx type class_cache = Decl_store.class_entries SMap.t let no_fallback (_ : env) (_ : string) : Decl_defs.decl_class_type option = None let get_class_and_add_dep ~(cache : class_cache) ~(shmem_fallback : bool) ~fallback env x = let res = match SMap.find_opt x cache with | Some c -> Some (fst c) | None when shmem_fallback -> Decl_store.((get ()).get_class x) | None -> None in match res with | Some c -> Some c | None -> fallback env x
OCaml Interface
hhvm/hphp/hack/src/decl/decl_env.mli
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type env = { mode: FileInfo.mode; droot: Typing_deps.Dep.dependent Typing_deps.Dep.variant option; droot_member: Typing_pessimisation_deps.dependent_member option; (** The child/member of [droot] currently under consideration. * Used for fine-grained dependency tracking. *) ctx: Provider_context.t; } val tcopt : env -> TypecheckerOptions.t type class_cache = Decl_store.class_entries SMap.t (** Auxiliary constant fallback function that returns [None]. *) val no_fallback : env -> string -> Decl_defs.decl_class_type option (** Lookup the class from the cache. If [shmem_fallback] and the class is not in the cache, look for the class in the classes heap. If the class is not in the cache, and [shmem_fallback] is false or the class is not in the classes heap, call and return [fallback]. If a class is returned, add a dependency to the class. *) val get_class_and_add_dep : cache:class_cache -> shmem_fallback:bool -> fallback:(env -> string -> Decl_defs.decl_class_type option) -> env -> string -> Decl_defs.decl_class_type option val make_decl_pos : env -> Pos.t -> Pos_or_decl.t val make_decl_posed : env -> Pos.t * 'a -> Pos_or_decl.t * 'a
OCaml
hhvm/hphp/hack/src/decl/decl_export.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 Reordered_argument_collections open Typing_defs module CEKMap = struct include Reordered_argument_map (WrappedMap.Make (Decl_heap.ClassEltKey)) let pp ppd = make_pp (fun fmt (c, m) -> Format.fprintf fmt "(%S, %S)" c m) ppd end type saved_legacy_decls = { classes: Decl_defs.decl_class_type SMap.t; props: decl_ty CEKMap.t; sprops: decl_ty CEKMap.t; meths: fun_elt CEKMap.t; smeths: fun_elt CEKMap.t; cstrs: fun_elt SMap.t; fixmes: Pos.t IMap.t IMap.t Relative_path.Map.t; decl_fixmes: Pos.t IMap.t IMap.t Relative_path.Map.t; } [@@deriving show] let empty_legacy_decls = { classes = SMap.empty; props = CEKMap.empty; sprops = CEKMap.empty; meths = CEKMap.empty; smeths = CEKMap.empty; cstrs = SMap.empty; fixmes = Relative_path.Map.empty; decl_fixmes = Relative_path.Map.empty; } let keys_to_sset smap = SMap.fold smap ~init:SSet.empty ~f:(fun k _ s -> SSet.add s k) let rec collect_legacy_class ?(fail_if_missing = false) (ctx : Provider_context.t) (requested_classes : SSet.t) (cid : string) (decls : saved_legacy_decls) : saved_legacy_decls = let open Decl_defs in if SMap.mem decls.classes cid then decls else let kind = if SSet.mem requested_classes cid then "requested" else "ancestor" in match Decl_heap.Classes.get cid with | None -> if fail_if_missing then failwith @@ "Missing " ^ kind ^ " class " ^ cid ^ " after declaration" else ( try match Naming_provider.get_class_path ctx cid with | None -> raise Exit | Some _filename -> Hh_logger.log "Declaring %s class %s" kind cid; (* NOTE: the following relies on the fact that declaring a class puts * the inheritance hierarchy into the shared memory heaps. When that * invariant no longer holds, the following will no longer work. *) let (_ : _ option) = Errors.run_in_decl_mode (fun () -> Decl_folded_class.class_decl_if_missing ~sh:SharedMem.Uses ctx cid) in collect_legacy_class ctx requested_classes cid decls ~fail_if_missing:true with | Exit | Decl_defs.Decl_not_found _ -> if not @@ SSet.mem requested_classes cid then failwith @@ "Missing legacy ancestor class " ^ cid else ( Hh_logger.log "Missing legacy requested class %s" cid; if Decl_heap.Typedefs.mem cid then Hh_logger.log "(It may have been changed to a typedef)" else Hh_logger.log "(It may have been renamed or deleted)"; decls ) ) | Some data -> let decls = { decls with classes = SMap.add decls.classes ~key:cid ~data } in let collect_elt add mid { elt_origin; _ } decls = if String.equal cid elt_origin then add decls cid mid else decls in let collect_elts elts init f = SMap.fold elts ~init ~f:(collect_elt f) in let decls = collect_elts data.dc_props decls @@ fun decls cid mid -> match Decl_heap.Props.get (cid, mid) with | None -> failwith @@ "Missing property " ^ cid ^ "::" ^ mid | Some x -> { decls with props = CEKMap.add decls.props ~key:(cid, mid) ~data:x } in let decls = collect_elts data.dc_sprops decls @@ fun decls cid mid -> match Decl_heap.StaticProps.get (cid, mid) with | None -> failwith @@ "Missing static property " ^ cid ^ "::" ^ mid | Some x -> { decls with sprops = CEKMap.add decls.sprops ~key:(cid, mid) ~data:x; } in let decls = collect_elts data.dc_methods decls @@ fun decls cid mid -> match Decl_heap.Methods.get (cid, mid) with | None -> failwith @@ "Missing method " ^ cid ^ "::" ^ mid | Some x -> { decls with meths = CEKMap.add decls.meths ~key:(cid, mid) ~data:x } in let decls = collect_elts data.dc_smethods decls @@ fun decls cid mid -> match Decl_heap.StaticMethods.get (cid, mid) with | None -> failwith @@ "Missing static method " ^ cid ^ "::" ^ mid | Some x -> { decls with smeths = CEKMap.add decls.smeths ~key:(cid, mid) ~data:x; } in let decls = fst data.dc_construct |> Option.value_map ~default:decls ~f:(fun { elt_origin; _ } -> if String.( <> ) cid elt_origin then decls else match Decl_heap.Constructors.get cid with | None -> failwith @@ "Missing constructor " ^ cid | Some x -> { decls with cstrs = SMap.add decls.cstrs ~key:cid ~data:x }) in let filename = match Naming_provider.get_class_path ctx cid with | None -> failwith @@ "Could not look up filename for " ^ kind ^ " class " ^ cid | Some f -> f in let decls = if Relative_path.Map.mem decls.fixmes filename || Relative_path.Map.mem decls.decl_fixmes filename then decls else match Fixme_provider.get_hh_fixmes filename with | Some fixmes -> { decls with fixmes = Relative_path.Map.add decls.fixmes ~key:filename ~data:fixmes; } | None -> (match Fixme_provider.get_decl_hh_fixmes filename with | Some fixmes -> { decls with decl_fixmes = Relative_path.Map.add decls.decl_fixmes ~key:filename ~data:fixmes; } | None -> decls) in let ancestors = keys_to_sset data.dc_ancestors |> SSet.union data.dc_xhp_attr_deps |> SSet.union data.dc_req_ancestors_extends in collect_legacy_classes ctx requested_classes decls ancestors and collect_legacy_classes ctx requested_classes decls = SSet.fold ~init:decls ~f:(collect_legacy_class ctx requested_classes) let restore_legacy_decls decls = let { classes; props; sprops; meths; smeths; cstrs; fixmes; decl_fixmes } = decls in SMap.iter classes ~f:Decl_heap.Classes.add; CEKMap.iter props ~f:Decl_heap.Props.add; CEKMap.iter sprops ~f:Decl_heap.StaticProps.add; CEKMap.iter meths ~f:Decl_heap.Methods.add; CEKMap.iter smeths ~f:Decl_heap.StaticMethods.add; SMap.iter cstrs ~f:Decl_heap.Constructors.add; Relative_path.Map.iter fixmes ~f:Fixme_provider.provide_hh_fixmes; Relative_path.Map.iter decl_fixmes ~f:Fixme_provider.provide_decl_hh_fixmes; (* return the number of classes that we restored *) SMap.cardinal classes let collect_legacy_decls ctx classes = collect_legacy_classes ctx classes empty_legacy_decls classes type saved_shallow_decls = { classes: Shallow_decl_defs.shallow_class SMap.t } [@@deriving show] let collect_shallow_decls ctx workers classnames = let classnames = SSet.elements classnames in (* We're only going to fetch the shallow-decls that were explicitly listed; we won't look for ancestors. *) let job (init : 'a SMap.t) (classnames : string list) : 'a SMap.t = List.fold classnames ~init ~f:(fun acc cid -> match Shallow_classes_provider.get ctx cid with | None -> Hh_logger.log "Missing requested shallow class %s" cid; acc | Some data -> SMap.add acc ~key:cid ~data) in (* The 'classnames' came from a SSet, and therefore all elements are unique. So we can safely assume there will be no merge collisions. *) let classes = MultiWorker.call workers ~job ~neutral:SMap.empty ~merge: (SMap.merge ~f:(fun _key a b -> if Option.is_some a then a else b)) ~next:(MultiWorker.next workers classnames) in { classes } let restore_shallow_decls decls = SMap.iter decls.classes ~f:(fun name cls -> Shallow_classes_heap.Classes.add name cls); (* return the number of classes that we restored *) SMap.cardinal decls.classes
OCaml Interface
hhvm/hphp/hack/src/decl/decl_export.mli
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type saved_legacy_decls [@@deriving show] val collect_legacy_decls : Provider_context.t -> SSet.t -> saved_legacy_decls val restore_legacy_decls : saved_legacy_decls -> int type saved_shallow_decls = { classes: Shallow_decl_defs.shallow_class SMap.t } [@@deriving show] val collect_shallow_decls : Provider_context.t -> MultiWorker.worker list option -> SSet.t -> saved_shallow_decls val restore_shallow_decls : saved_shallow_decls -> int
OCaml
hhvm/hphp/hack/src/decl/decl_folded_class.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (*****************************************************************************) (* Module used to declare class types. * For each class we want to build a complete type, that is the type of * the methods defined in the class plus everything that was inherited. *) (*****************************************************************************) open Hh_prelude open Decl_defs open Aast open Shallow_decl_defs open Typing_defs open Typing_deps module Reason = Typing_reason module Inst = Decl_instantiate module Attrs = Typing_defs.Attributes module SN = Naming_special_names type class_entries = Decl_defs.decl_class_type * Decl_store.class_members option type lazy_member_lookup_error = | LMLEShallowClassNotFound | LMLEMemberNotFound [@@deriving show] (*****************************************************************************) (* Checking that the kind of a class is compatible with its parent * For example, a class cannot extend an interface, an interface cannot * extend a trait etc ... *) (*****************************************************************************) let check_extend_kind (parent_pos : Pos_or_decl.t) (parent_kind : Ast_defs.classish_kind) (parent_name : string) (child_pos : Pos_or_decl.t) (child_kind : Ast_defs.classish_kind) (child_name : string) : decl_error option = match (parent_kind, child_kind) with (* What is allowed *) | (Ast_defs.Cclass _, Ast_defs.Cclass _) | (Ast_defs.Ctrait, Ast_defs.Ctrait) | (Ast_defs.Cinterface, Ast_defs.Cinterface) -> None (* enums extend BuiltinEnum under the hood *) | (Ast_defs.Cclass k, (Ast_defs.Cenum | Ast_defs.Cenum_class _)) when Ast_defs.is_abstract k -> None | (Ast_defs.Cenum_class _, Ast_defs.Cenum_class _) -> None | _ -> (* What is disallowed *) Some (Wrong_extend_kind { parent_pos; parent_kind; parent_name; pos = Pos_or_decl.unsafe_to_raw_pos child_pos (* TODO: T87242856 *); kind = child_kind; name = child_name; }) (*****************************************************************************) (* Functions used retrieve everything implemented in parent classes * The return values: * env: the new environment * parents: the name of all the parents and grand parents of the class this * includes traits. * is_complete: true if all the parents live in Hack *) (*****************************************************************************) let member_heaps_enabled (ctx : Provider_context.t) : bool = let tco = Provider_context.get_tcopt ctx in TypecheckerOptions.(populate_member_heaps tco) (** * Adds the traits/classes which are part of a class' hierarchy. * * Traits are tracked separately but merged into the parents list when * typechecking so that the class can access the trait members which are * declared as private/protected. *) let add_grand_parents_or_traits (parent_pos : Pos_or_decl.t) (shallow_class : Shallow_decl_defs.shallow_class) (acc : SSet.t * [ `Extends_pass | `Traits_pass | `Xhp_pass ] * decl_error list) (parent_type : Decl_defs.decl_class_type) : SSet.t * 'a * decl_error list = let (extends, pass, decl_errors) = acc in let class_pos = fst shallow_class.sc_name in let classish_kind = shallow_class.sc_kind in let class_name = snd shallow_class.sc_name in let decl_errors = if phys_equal pass `Extends_pass then match check_extend_kind parent_pos parent_type.dc_kind parent_type.dc_name class_pos classish_kind class_name with | Some err -> err :: decl_errors | None -> decl_errors else decl_errors in (* If we are crawling the xhp attribute deps, we need to merge their xhp deps * as well *) let parent_deps = if phys_equal pass `Xhp_pass then SSet.union parent_type.dc_extends parent_type.dc_xhp_attr_deps else parent_type.dc_extends in let extends' = SSet.union extends parent_deps in (extends', pass, decl_errors) let get_class_parent_or_trait (env : Decl_env.env) (shallow_class : Shallow_decl_defs.shallow_class) (parent_cache : Decl_store.class_entries SMap.t) ((parents, pass, decl_errors) : SSet.t * [ `Extends_pass | `Traits_pass | `Xhp_pass ] * decl_error list) (ty : Typing_defs.decl_phase Typing_defs.ty) : SSet.t * 'a * decl_error list = let (_, (parent_pos, parent), _) = Decl_utils.unwrap_class_type ty in (* If we already had this exact trait, we need to flag trait reuse *) let parents = SSet.add parent parents in let parent_type = Decl_env.get_class_and_add_dep ~cache:parent_cache ~shmem_fallback:false ~fallback:Decl_env.no_fallback env parent in match parent_type with | None -> (parents, pass, decl_errors) | Some parent_type -> let acc = (parents, pass, decl_errors) in add_grand_parents_or_traits parent_pos shallow_class acc parent_type let get_class_parents_and_traits (env : Decl_env.env) (shallow_class : Shallow_decl_defs.shallow_class) parent_cache decl_errors : SSet.t * SSet.t * decl_error list = let parents = SSet.empty in (* extends parents *) let acc = (parents, `Extends_pass, decl_errors) in let (parents, _, decl_errors) = List.fold_left shallow_class.sc_extends ~f:(get_class_parent_or_trait env shallow_class parent_cache) ~init:acc in (* traits *) let acc = (parents, `Traits_pass, decl_errors) in let (parents, _, decl_errors) = List.fold_left shallow_class.sc_uses ~f:(get_class_parent_or_trait env shallow_class parent_cache) ~init:acc in (* XHP classes whose attributes were imported via "attribute :foo;" syntax *) let acc = (SSet.empty, `Xhp_pass, decl_errors) in let (xhp_parents, _, decl_errors) = List.fold_left shallow_class.sc_xhp_attr_uses ~f:(get_class_parent_or_trait env shallow_class parent_cache) ~init:acc in (parents, xhp_parents, decl_errors) type class_env = { ctx: Provider_context.t; stack: SSet.t; } let check_if_cyclic (class_env : class_env) ((pos, cid) : Pos.t * string) : decl_error option = let stack = class_env.stack in let is_cyclic = SSet.mem cid stack in if is_cyclic then Some (Cyclic_class_def { stack; pos }) else None let class_is_abstract (c : Shallow_decl_defs.shallow_class) : bool = match c.sc_kind with | Ast_defs.Cclass k -> Ast_defs.is_abstract k | Ast_defs.Cenum_class k -> Ast_defs.is_abstract k | Ast_defs.Cinterface | Ast_defs.Ctrait | Ast_defs.Cenum -> true let synthesize_const_defaults c = let open Typing_defs in match c.cc_abstract with | CCAbstract true -> { c with cc_abstract = CCConcrete } | _ -> c (* When all type constants have been inherited and declared, this step synthesizes * the defaults of abstract type constants into concrete type constants. *) let synthesize_typeconst_defaults (k : string) (tc : Typing_defs.typeconst_type) ((typeconsts, consts) : Typing_defs.typeconst_type SMap.t * Typing_defs.class_const SMap.t) : Typing_defs.typeconst_type SMap.t * Typing_defs.class_const SMap.t = match tc.ttc_kind with | TCAbstract { atc_default = Some default; _ } -> let concrete = { tc with ttc_kind = TCConcrete { tc_type = default }; ttc_concretized = true; } in let typeconsts = SMap.add k concrete typeconsts in (* OCaml 4.06 has an update method that makes this operation much more ergonomic *) let constant = SMap.find_opt k consts in let consts = Option.value_map constant ~default:consts ~f:(fun c -> SMap.add k { c with cc_abstract = CCConcrete } consts) in (typeconsts, consts) | _ -> (typeconsts, consts) let get_sealed_whitelist (c : Shallow_decl_defs.shallow_class) : SSet.t option = match Attributes.find SN.UserAttributes.uaSealed c.sc_user_attributes with | None -> None | Some { ua_params; _ } -> let cn_params = List.filter_map ~f:(function | Classname cn -> Some cn | _ -> None) ua_params in Some (SSet.of_list cn_params) let get_implements (env : Decl_env.env) parent_cache (ht : Typing_defs.decl_ty) : Typing_defs.decl_ty SMap.t = let (_r, (_p, c), paraml) = Decl_utils.unwrap_class_type ht in let class_ = Decl_env.get_class_and_add_dep ~cache:parent_cache ~shmem_fallback:false ~fallback:Decl_env.no_fallback env c in match class_ with | None -> (* The class lives in PHP land *) SMap.singleton c ht | Some class_ -> let subst = Inst.make_subst class_.dc_tparams paraml in let sub_implements = SMap.map (fun ty -> Inst.instantiate subst ty) class_.dc_ancestors in SMap.add c ht sub_implements let visibility (class_id : string) (module_ : Ast_defs.id option) (visibility : Aast_defs.visibility) : Typing_defs.ce_visibility = match visibility with | Public -> Vpublic | Protected -> Vprotected class_id | Private -> Vprivate class_id | Internal -> (match module_ with | Some m -> Vinternal (snd m) | None -> Vpublic) let build_constructor_fun_elt ~(ctx : Provider_context.t) ~(elt_origin : string) ~(method_ : Shallow_decl_defs.shallow_method) = let pos = fst method_.sm_name in let fe = { fe_module = None; fe_pos = pos; fe_internal = false; fe_deprecated = method_.sm_deprecated; fe_type = method_.sm_type; fe_php_std_lib = false; fe_support_dynamic_type = false; fe_no_auto_dynamic = false; fe_no_auto_likes = false; } in (if member_heaps_enabled ctx then Decl_store.((get ()).add_constructor elt_origin fe)); fe let build_constructor ~(ctx : Provider_context.t) ~(origin_class : Shallow_decl_defs.shallow_class) (method_ : Shallow_decl_defs.shallow_method) : (Decl_defs.element * Typing_defs.fun_elt option) option = let (_, class_name) = origin_class.sc_name in let vis = visibility class_name origin_class.sc_module method_.sm_visibility in let cstr = { elt_flags = make_ce_flags ~xhp_attr:None ~final:(sm_final method_) ~abstract:(sm_abstract method_) ~lateinit:false ~const:false ~lsb:false ~synthesized:false ~superfluous_override:false ~dynamicallycallable:false ~readonly_prop:false ~support_dynamic_type:false ~needs_init:false ~safe_global_variable:false; elt_visibility = vis; elt_origin = class_name; elt_deprecated = method_.sm_deprecated; } in let fe = build_constructor_fun_elt ~ctx ~elt_origin:class_name ~method_ in Some (cstr, Some fe) let constructor_decl_eager ~(sh : SharedMem.uses) ~(ctx : Provider_context.t) ((parent_cstr, pconsist) : (Decl_defs.element * Typing_defs.fun_elt option) option * Typing_defs.consistent_kind) (class_ : Shallow_decl_defs.shallow_class) : (Decl_defs.element * Typing_defs.fun_elt option) option * Typing_defs.consistent_kind = let SharedMem.Uses = sh in (* constructors in children of class_ must be consistent? *) let cconsist = if class_.sc_final then FinalClass else if Attrs.mem SN.UserAttributes.uaConsistentConstruct class_.sc_user_attributes then ConsistentConstruct else Inconsistent in let cstr = match class_.sc_constructor with | None -> parent_cstr | Some method_ -> build_constructor ~ctx ~origin_class:class_ method_ in (cstr, Decl_utils.coalesce_consistent pconsist cconsist) let constructor_decl_lazy ~(sh : SharedMem.uses) (ctx : Provider_context.t) ~(elt_origin : string) : (Typing_defs.fun_elt, lazy_member_lookup_error) result = let SharedMem.Uses = sh in match Shallow_classes_provider.get ctx elt_origin with | None -> Error LMLEShallowClassNotFound | Some class_ -> (match class_.sc_constructor with | None -> Error LMLEMemberNotFound | Some method_ -> Ok (build_constructor_fun_elt ~ctx ~elt_origin ~method_)) let class_const_fold (c : Shallow_decl_defs.shallow_class) (acc : Typing_defs.class_const SMap.t) (scc : Shallow_decl_defs.shallow_class_const) : Typing_defs.class_const SMap.t = let c_name = snd c.sc_name in let cc = { cc_synthesized = false; cc_abstract = scc.scc_abstract; cc_pos = fst scc.scc_name; cc_type = scc.scc_type; cc_origin = c_name; cc_refs = scc.scc_refs; } in let acc = SMap.add (snd scc.scc_name) cc acc in acc (* Every class, interface, and trait implicitly defines a ::class to * allow accessing its fully qualified name as a string *) let class_class_decl (class_id : Typing_defs.pos_id) : Typing_defs.class_const = let (pos, name) = class_id in let reason = Reason.Rclass_class (pos, name) in let classname_ty = mk (reason, Tapply ((pos, SN.Classes.cClassname), [mk (reason, Tthis)])) in { cc_abstract = CCConcrete; cc_pos = pos; cc_synthesized = true; cc_type = classname_ty; cc_origin = name; cc_refs = []; } let build_prop_sprop_ty ~(ctx : Provider_context.t) ~(this_class : shallow_class option) ~(is_static : bool) ~(elt_origin : string) (sp : Shallow_decl_defs.shallow_prop) : Typing_defs.decl_ty = let (_sp_pos, sp_name) = sp.sp_name in let is_xhp_attr = is_some sp.sp_xhp_attr in let no_auto_likes = PropFlags.get_no_auto_likes sp.sp_flags in let ty = if no_auto_likes then sp.sp_type else Decl_enforceability.maybe_pessimise_type ~is_xhp_attr ~this_class ctx sp.sp_type in (if member_heaps_enabled ctx then if is_static then Decl_store.((get ()).add_static_prop (elt_origin, sp_name) ty) else Decl_store.((get ()).add_prop (elt_origin, sp_name) ty)); ty let prop_decl_eager ~(ctx : Provider_context.t) (c : Shallow_decl_defs.shallow_class) (acc : (Decl_defs.element * Typing_defs.decl_ty option) SMap.t) (sp : Shallow_decl_defs.shallow_prop) : (Decl_defs.element * Typing_defs.decl_ty option) SMap.t = let elt_origin = snd c.sc_name in let ty = build_prop_sprop_ty ~ctx ~this_class:(Some c) ~is_static:false ~elt_origin sp in let vis = visibility (snd c.sc_name) c.sc_module sp.sp_visibility in let elt = { elt_flags = make_ce_flags ~xhp_attr:sp.sp_xhp_attr ~final:true ~lsb:false ~synthesized:false ~superfluous_override:false ~const:(sp_const sp) ~lateinit:(sp_lateinit sp) ~abstract:(sp_abstract sp) ~dynamicallycallable:false ~readonly_prop:(sp_readonly sp) ~support_dynamic_type:false ~needs_init:(sp_needs_init sp) ~safe_global_variable:false; elt_visibility = vis; elt_origin; elt_deprecated = None; } in let acc = SMap.add (snd sp.sp_name) (elt, Some ty) acc in acc let prop_decl_lazy ~(sh : SharedMem.uses) (ctx : Provider_context.t) ~(elt_origin : string) ~(sp_name : string) : (Typing_defs.decl_ty, lazy_member_lookup_error) result = let SharedMem.Uses = sh in match Shallow_classes_provider.get ctx elt_origin with | None -> Error LMLEShallowClassNotFound | Some class_ -> (match List.find class_.sc_props ~f:(fun prop -> String.equal (snd prop.sp_name) sp_name) with | None -> Error LMLEMemberNotFound | Some sp -> Ok (build_prop_sprop_ty ~ctx ~this_class:(Some class_) ~is_static:false ~elt_origin sp)) let static_prop_decl_eager ~(ctx : Provider_context.t) (c : Shallow_decl_defs.shallow_class) (acc : (Decl_defs.element * Typing_defs.decl_ty option) SMap.t) (sp : Shallow_decl_defs.shallow_prop) : (Decl_defs.element * Typing_defs.decl_ty option) SMap.t = let elt_origin = snd c.sc_name in let ty = build_prop_sprop_ty ~ctx ~this_class:(Some c) ~is_static:true ~elt_origin sp in let vis = visibility (snd c.sc_name) c.sc_module sp.sp_visibility in let elt = { elt_flags = make_ce_flags ~xhp_attr:sp.sp_xhp_attr ~final:true ~const:(sp_const sp) ~lateinit:(sp_lateinit sp) ~lsb:(sp_lsb sp) ~superfluous_override:false ~abstract:(sp_abstract sp) ~synthesized:false ~dynamicallycallable:false ~readonly_prop:(sp_readonly sp) ~support_dynamic_type:false ~needs_init:false ~safe_global_variable:(sp_safe_global_variable sp); elt_visibility = vis; elt_origin = snd c.sc_name; elt_deprecated = None; } in let acc = SMap.add (snd sp.sp_name) (elt, Some ty) acc in acc let static_prop_decl_lazy ~(sh : SharedMem.uses) (ctx : Provider_context.t) ~(elt_origin : string) ~(sp_name : string) : (Typing_defs.decl_ty, lazy_member_lookup_error) result = let SharedMem.Uses = sh in match Shallow_classes_provider.get ctx elt_origin with | None -> Error LMLEShallowClassNotFound | Some class_ -> (match List.find class_.sc_sprops ~f:(fun prop -> String.equal (snd prop.sp_name) sp_name) with | None -> Error LMLEMemberNotFound | Some sp -> Ok (build_prop_sprop_ty ~ctx ~this_class:(Some class_) ~is_static:true ~elt_origin sp)) (* each concrete type constant T = <sometype> implicitly defines a class constant with the same name which is TypeStructure<sometype> *) let typeconst_structure (c : Shallow_decl_defs.shallow_class) (stc : Shallow_decl_defs.shallow_typeconst) : Typing_defs.class_const = let pos = fst stc.stc_name in let r = Reason.Rwitness_from_decl pos in let tsid = (pos, SN.FB.cTypeStructure) in let ts_ty = mk (r, Tapply (tsid, [mk (r, Taccess (mk (r, Tthis), stc.stc_name))])) in let abstract = match stc.stc_kind with | TCAbstract { atc_default = default; _ } -> CCAbstract (Option.is_some default) | TCConcrete _ -> CCConcrete in { cc_abstract = abstract; cc_pos = pos; cc_synthesized = true; cc_type = ts_ty; cc_origin = snd c.sc_name; cc_refs = []; } let maybe_add_supportdyn_bound ctx p kind = if TypecheckerOptions.everything_sdt (Provider_context.get_tcopt ctx) then match kind with | TCAbstract { atc_as_constraint = None; atc_super_constraint; atc_default } -> TCAbstract { atc_as_constraint = Some (Decl_enforceability.supportdyn_mixed p (Typing_defs.Reason.Rwitness_from_decl p)); atc_super_constraint; atc_default; } | TCAbstract _ | TCConcrete _ -> kind else kind let typeconst_fold (ctx : Provider_context.t) (c : Shallow_decl_defs.shallow_class) (acc : Typing_defs.typeconst_type SMap.t * Typing_defs.class_const SMap.t) (stc : Shallow_decl_defs.shallow_typeconst) : Typing_defs.typeconst_type SMap.t * Typing_defs.class_const SMap.t = let (typeconsts, consts) = acc in match c.sc_kind with | Ast_defs.Cenum -> acc | Ast_defs.Cenum_class _ | Ast_defs.Ctrait | Ast_defs.Cinterface | Ast_defs.Cclass _ -> let name = snd stc.stc_name in let c_name = snd c.sc_name in let ts = typeconst_structure c stc in let consts = SMap.add name ts consts in let ptc_opt = SMap.find_opt name typeconsts in let enforceable = (* Without the positions, this is a simple OR, but this way allows us to * report the position of the <<__Enforceable>> attribute to the user *) if snd stc.stc_enforceable then stc.stc_enforceable else match ptc_opt with | Some ptc -> ptc.ttc_enforceable | None -> (Pos_or_decl.none, false) in let reifiable = if Option.is_some stc.stc_reifiable then stc.stc_reifiable else Option.bind ptc_opt ~f:(fun ptc -> ptc.ttc_reifiable) in let tc = { ttc_synthesized = false; ttc_name = stc.stc_name; ttc_kind = (if stc.stc_is_ctx then stc.stc_kind else maybe_add_supportdyn_bound ctx (fst stc.stc_name) stc.stc_kind); ttc_origin = c_name; ttc_enforceable = enforceable; ttc_reifiable = reifiable; ttc_concretized = false; ttc_is_ctx = stc.stc_is_ctx; } in let typeconsts = SMap.add (snd stc.stc_name) tc typeconsts in (typeconsts, consts) let build_method_fun_elt ~(ctx : Provider_context.t) ~(this_class : shallow_class option) ~(is_static : bool) ~(elt_origin : string) (m : Shallow_decl_defs.shallow_method) : Typing_defs.fun_elt = let (pos, id) = m.sm_name in let support_dynamic_type = sm_support_dynamic_type m in let fe_no_auto_dynamic = Typing_defs.Attributes.mem Naming_special_names.UserAttributes.uaNoAutoDynamic m.Shallow_decl_defs.sm_attributes in let fe_no_auto_likes = Typing_defs.Attributes.mem Naming_special_names.UserAttributes.uaNoAutoLikes m.Shallow_decl_defs.sm_attributes in let fe = { fe_module = None; fe_pos = pos; fe_internal = false; fe_deprecated = None; fe_type = (if (not fe_no_auto_dynamic) && Provider_context.implicit_sdt_for_class ctx this_class then Decl_enforceability.( pessimise_fun_type ~fun_kind: (if MethodFlags.get_abstract m.sm_flags then Abstract_method else Concrete_method) ~this_class ~no_auto_likes:fe_no_auto_likes ctx pos m.sm_type) else m.sm_type); fe_php_std_lib = false; fe_support_dynamic_type = support_dynamic_type; fe_no_auto_dynamic; fe_no_auto_likes; } in (if member_heaps_enabled ctx then if is_static then Decl_store.((get ()).add_static_method (elt_origin, id) fe) else Decl_store.((get ()).add_method (elt_origin, id) fe)); fe let method_decl_eager ~(ctx : Provider_context.t) ~(is_static : bool) (c : Shallow_decl_defs.shallow_class) (acc : (Decl_defs.element * Typing_defs.fun_elt option) SMap.t) (m : Shallow_decl_defs.shallow_method) : (Decl_defs.element * Typing_defs.fun_elt option) SMap.t = (* If method doesn't override anything but has the <<__Override>> attribute, then * set the override flag in ce_flags and let typing emit an appropriate error *) let superfluous_override = sm_override m && not (SMap.mem (snd m.sm_name) acc) in let (_pos, id) = m.sm_name in let vis = match (SMap.find_opt id acc, m.sm_visibility) with | (Some ({ elt_visibility = Vprotected _ as parent_vis; _ }, _), Protected) -> parent_vis | _ -> visibility (snd c.sc_name) c.sc_module m.sm_visibility in let support_dynamic_type = sm_support_dynamic_type m in let elt = { elt_flags = make_ce_flags ~xhp_attr:None ~final:(sm_final m) ~abstract:(sm_abstract m) ~superfluous_override ~synthesized:false ~lsb:false ~const:false ~lateinit:false ~dynamicallycallable:(sm_dynamicallycallable m) ~readonly_prop:false ~support_dynamic_type ~needs_init:false ~safe_global_variable:false; elt_visibility = vis; elt_origin = snd c.sc_name; elt_deprecated = m.sm_deprecated; } in let fe = build_method_fun_elt ~ctx ~this_class:(Some c) ~is_static ~elt_origin:elt.elt_origin m in let acc = SMap.add id (elt, Some fe) acc in acc let method_decl_lazy ~(sh : SharedMem.uses) (ctx : Provider_context.t) ~(is_static : bool) ~(elt_origin : string) ~(sm_name : string) : (Typing_defs.fun_elt, lazy_member_lookup_error) result = let SharedMem.Uses = sh in match Shallow_classes_provider.get ctx elt_origin with | None -> Error LMLEShallowClassNotFound | Some class_ -> let methods = if is_static then class_.sc_static_methods else class_.sc_methods in (match List.find methods ~f:(fun m -> String.equal (snd m.sm_name) sm_name) with | None -> Error LMLEMemberNotFound | Some sm -> Ok (build_method_fun_elt ~this_class:(Some class_) ~ctx ~is_static ~elt_origin sm)) let rec declare_class_and_parents ~(sh : SharedMem.uses) (class_env : class_env) (shallow_class : Shallow_decl_defs.shallow_class) : Decl_store.class_entries = let (_, name) = shallow_class.sc_name in let class_env = { class_env with stack = SSet.add name class_env.stack } in let (class_, member_heaps_values) = let (parents, errors) = class_parents_decl ~sh class_env shallow_class in class_decl ~sh class_env.ctx shallow_class ~parents errors in (class_, Some member_heaps_values) and class_parents_decl ~(sh : SharedMem.uses) (class_env : class_env) (c : Shallow_decl_defs.shallow_class) : Decl_store.class_entries SMap.t * decl_error list = let class_type_decl (parents, errs) class_ty = match get_node class_ty with | Tapply ((pos, class_name), _) -> (match check_if_cyclic class_env (Pos_or_decl.unsafe_to_raw_pos pos, class_name) with | Some err -> (parents, err :: errs) | None -> (match class_decl_if_missing ~sh class_env class_name with | None -> (parents, errs) | Some decls -> (SMap.add class_name decls parents, errs))) | _ -> (parents, errs) in let acc = (SMap.empty, []) in let acc = List.fold c.sc_extends ~f:class_type_decl ~init:acc in let acc = List.fold c.sc_implements ~f:class_type_decl ~init:acc in let acc = List.fold c.sc_uses ~f:class_type_decl ~init:acc in let acc = List.fold c.sc_xhp_attr_uses ~f:class_type_decl ~init:acc in let acc = List.fold c.sc_req_extends ~f:class_type_decl ~init:acc in let acc = List.fold c.sc_req_implements ~f:class_type_decl ~init:acc in let enum_includes = Aast.enum_includes_map ~f:(fun et -> et.te_includes) c.sc_enum_type in let acc = List.fold enum_includes ~f:class_type_decl ~init:acc in acc and class_decl_if_missing ~(sh : SharedMem.uses) (class_env : class_env) (class_name : string) : Decl_store.class_entries option = match Decl_store.((get ()).get_class class_name) with | Some decl -> Some (decl, None) | None -> (match Shallow_classes_provider.get class_env.ctx class_name with | None -> None | Some shallow_class -> let ((class_, _) as result) = declare_class_and_parents ~sh class_env shallow_class in Decl_store.((get ()).add_class class_name class_); Some result) and class_decl ~(sh : SharedMem.uses) (ctx : Provider_context.t) (c : Shallow_decl_defs.shallow_class) ~(parents : Decl_store.class_entries SMap.t) (decl_errors : decl_error list) : Decl_defs.decl_class_type * Decl_store.class_members = let is_abstract = class_is_abstract c in let const = Attrs.mem SN.UserAttributes.uaConst c.sc_user_attributes in (* Support both attribute and keyword for now, until typechecker changes are made *) let internal = c.sc_internal in let (p, cls_name) = c.sc_name in let class_dep = Dep.Type cls_name in let env = { Decl_env.mode = c.sc_mode; droot = Some class_dep; droot_member = None; ctx; } in let inherited = Decl_inherit.make env c ~cache:parents in let props = inherited.Decl_inherit.ih_props in let props = List.fold_left ~f:(prop_decl_eager ~ctx c) ~init:props c.sc_props in let inherited_methods = inherited.Decl_inherit.ih_methods in let methods = List.fold_left ~f:(method_decl_eager ~ctx ~is_static:false c) ~init:inherited_methods c.sc_methods in let consts = inherited.Decl_inherit.ih_consts in let consts = List.fold_left ~f:(class_const_fold c) ~init:consts c.sc_consts in let consts = SMap.add SN.Members.mClass (class_class_decl c.sc_name) consts in let typeconsts = inherited.Decl_inherit.ih_typeconsts in let (typeconsts, consts) = List.fold_left c.sc_typeconsts ~f:(typeconst_fold ctx c) ~init:(typeconsts, consts) in let (typeconsts, consts) = if Ast_defs.is_c_concrete c.sc_kind then let consts = SMap.map synthesize_const_defaults consts in SMap.fold synthesize_typeconst_defaults typeconsts (typeconsts, consts) else (typeconsts, consts) in let sclass_var = static_prop_decl_eager ~ctx c in let inherited_static_props = inherited.Decl_inherit.ih_sprops in let static_props = List.fold_left c.sc_sprops ~f:sclass_var ~init:inherited_static_props in let inherited_static_methods = inherited.Decl_inherit.ih_smethods in let static_methods = List.fold_left c.sc_static_methods ~f:(method_decl_eager ~ctx ~is_static:true c) ~init:inherited_static_methods in let parent_cstr = inherited.Decl_inherit.ih_cstr in let cstr = constructor_decl_eager ~sh ~ctx parent_cstr c in let has_concrete_cstr = match fst cstr with | None -> false | Some (elt, _) when get_elt_abstract elt -> false | _ -> true in let impl = c.sc_extends @ c.sc_implements @ c.sc_uses in let (impl, parents) = match List.find c.sc_methods ~f:(fun sm -> String.equal (snd sm.sm_name) SN.Members.__toString) with | Some { sm_name = (pos, _); _ } when String.( <> ) cls_name SN.Classes.cStringishObject -> (* HHVM implicitly adds StringishObject interface for every class/iface/trait * with a __toString method; "string" also implements this interface *) (* Declare StringishObject and parents if not already declared *) let class_env = { ctx; stack = SSet.empty } in let parents = (* Ensure stringishObject is declared. *) match class_decl_if_missing ~sh class_env SN.Classes.cStringishObject with | None -> parents | Some stringish_cls -> SMap.add SN.Classes.cStringishObject stringish_cls parents in let ty = mk (Reason.Rhint pos, Tapply ((pos, SN.Classes.cStringishObject), [])) in (ty :: impl, parents) | _ -> (impl, parents) in let impl = List.map impl ~f:(get_implements env parents) in let impl = List.fold_right impl ~f:(SMap.fold SMap.add) ~init:SMap.empty in let (extends, xhp_attr_deps, decl_errors) = get_class_parents_and_traits env c parents decl_errors in let (req_ancestors, req_ancestors_extends, req_class_ancestors) = Decl_requirements.get_class_requirements env parents c in let enum = c.sc_enum_type in let enum_inner_ty = SMap.find_opt SN.FB.tInner typeconsts in let is_enum_class = Ast_defs.is_c_enum_class c.sc_kind in let consts = Decl_enum.rewrite_class c.sc_name ~is_enum_class enum Option.( enum_inner_ty >>= fun t -> (* TODO(T88552052) can make logic more explicit now, enum members appear to * only need abstract without default and concrete type consts *) match t.ttc_kind with | TCConcrete { tc_type } -> Some tc_type | TCAbstract { atc_default; _ } -> atc_default) ~get_ancestor:(fun x -> SMap.find_opt x impl) consts in let has_own_cstr = has_concrete_cstr && Option.is_some c.sc_constructor in let deferred_members = let get_class_add_dep decl_env cls = Decl_env.get_class_and_add_dep ~cache:parents ~shmem_fallback:false ~fallback:Decl_env.no_fallback decl_env cls in Decl_init_check.nonprivate_deferred_init_props ~has_own_cstr ~get_class_add_dep env c in let dc_tparams = Decl_enforceability.maybe_add_supportdyn_constraints ~this_class:(Some c) ctx p c.sc_tparams in let sealed_whitelist = get_sealed_whitelist c in let tc = { dc_final = c.sc_final; dc_const = const; dc_internal = internal; dc_abstract = is_abstract; dc_need_init = has_concrete_cstr; dc_deferred_init_members = deferred_members; dc_kind = c.sc_kind; dc_is_xhp = c.sc_is_xhp; dc_has_xhp_keyword = c.sc_has_xhp_keyword; dc_module = c.sc_module; dc_is_module_level_trait = Attributes.mem SN.UserAttributes.uaModuleLevelTrait c.sc_user_attributes; dc_name = snd c.sc_name; dc_pos = fst c.sc_name; dc_tparams; dc_where_constraints = c.sc_where_constraints; dc_substs = inherited.Decl_inherit.ih_substs; dc_consts = consts; dc_typeconsts = typeconsts; dc_props = SMap.map fst props; dc_sprops = SMap.map fst static_props; dc_methods = SMap.map fst methods; dc_smethods = SMap.map fst static_methods; dc_construct = Tuple.T2.map_fst ~f:(Option.map ~f:fst) cstr; dc_ancestors = impl; dc_support_dynamic_type = c.sc_support_dynamic_type; dc_extends = extends; dc_sealed_whitelist = sealed_whitelist; dc_xhp_attr_deps = xhp_attr_deps; dc_xhp_enum_values = c.sc_xhp_enum_values; dc_xhp_marked_empty = c.sc_xhp_marked_empty; dc_req_ancestors = req_ancestors; dc_req_ancestors_extends = req_ancestors_extends; dc_req_class_ancestors = req_class_ancestors; dc_enum_type = enum; dc_decl_errors = decl_errors; dc_docs_url = c.sc_docs_url; } in let filter_snd map = SMap.filter_map (fun _k v -> snd v) map in let member_heaps_values = { Decl_store.m_static_properties = filter_snd static_props; m_properties = filter_snd props; m_static_methods = filter_snd static_methods; m_methods = filter_snd methods; m_constructor = Option.(cstr |> fst >>= snd); } in (tc, member_heaps_values) let class_decl_if_missing ~(sh : SharedMem.uses) (ctx : Provider_context.t) (class_name : string) : Decl_store.class_entries option = match Decl_store.((get ()).get_class class_name) with | Some class_ -> Some (class_, None) | None -> (* Class elements are in memory if and only if the class itself is there. * Exiting before class declaration is ready would break this invariant *) WorkerCancel.with_no_cancellations @@ fun () -> class_decl_if_missing ~sh { ctx; stack = SSet.empty } class_name
OCaml Interface
hhvm/hphp/hack/src/decl/decl_folded_class.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 class_entries = Decl_defs.decl_class_type * Decl_store.class_members option type lazy_member_lookup_error = | LMLEShallowClassNotFound | LMLEMemberNotFound [@@deriving show] (** Check if the class is already in the heap, and if not, declare it, its members and its ancestors and add them to their respective shared heaps. Return what has been added in the multiple heaps, i.e. the class heap entry and the entries in the various member heaps. There is no guarantee that it returns all the member heap entries for that class as some might have already been added previously when decling the ancestors. *) val class_decl_if_missing : sh:SharedMem.uses -> Provider_context.t -> string -> class_entries option val class_decl : sh:SharedMem.uses -> Provider_context.t -> Shallow_decl_defs.shallow_class -> parents:Decl_store.class_entries SMap.t -> Decl_defs.decl_error list -> Decl_defs.decl_class_type * Decl_store.class_members (** Extract the constructor signature from the shallow class. Might return [Error] if the shallow class for [elt_origin] can't be found, or if it has no constructor. *) val constructor_decl_lazy : sh:SharedMem.uses -> Provider_context.t -> elt_origin:string -> (Typing_defs.fun_elt, lazy_member_lookup_error) result (** Extract the property signature from the shallow class. Might return [Error] if the shallow class for [elt_origin] can't be found, or if it has no property with the given name. *) val prop_decl_lazy : sh:SharedMem.uses -> Provider_context.t -> elt_origin:string -> sp_name:string -> (Typing_defs.decl_ty, lazy_member_lookup_error) result (** Extract the static property signature from the shallow class. Might return [Error] if the shallow class for [elt_origin] can't be found, or if it has no static property with the given name. *) val static_prop_decl_lazy : sh:SharedMem.uses -> Provider_context.t -> elt_origin:string -> sp_name:string -> (Typing_defs.decl_ty, lazy_member_lookup_error) result (** Extract the method signature from the shallow class. Might return [Error] if the shallow class for [elt_origin] can't be found, or if it has no method with the given name. *) val method_decl_lazy : sh:SharedMem.uses -> Provider_context.t -> is_static:bool -> elt_origin:string -> sm_name:string -> (Typing_defs.fun_elt, lazy_member_lookup_error) result
OCaml
hhvm/hphp/hack/src/decl/decl_fun_utils.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast open Typing_defs module SN = Naming_special_names let get_classname_or_literal_attribute_param = function | [(_, _, Aast.String s)] -> Some s | [(_, _, Class_const ((_, _, CI (_, s)), (_, name)))] when String.equal name SN.Members.mClass -> Some s | _ -> None let find_policied_attribute user_attributes : ifc_fun_decl = match Naming_attributes.find SN.UserAttributes.uaPolicied user_attributes with | Some { ua_params; _ } -> (match get_classname_or_literal_attribute_param ua_params with | Some s -> FDPolicied (Some s) | None -> FDPolicied None) | None when Naming_attributes.mem SN.UserAttributes.uaInferFlows user_attributes -> FDInferFlows | None -> default_ifc_fun_decl let has_accept_disposable_attribute user_attributes = Naming_attributes.mem SN.UserAttributes.uaAcceptDisposable user_attributes let has_external_attribute user_attributes = Naming_attributes.mem SN.UserAttributes.uaExternal user_attributes let has_can_call_attribute user_attributes = Naming_attributes.mem SN.UserAttributes.uaCanCall user_attributes let has_return_disposable_attribute user_attributes = Naming_attributes.mem SN.UserAttributes.uaReturnDisposable user_attributes let has_memoize_attribute user_attributes = Naming_attributes.mem SN.UserAttributes.uaMemoize user_attributes || Naming_attributes.mem SN.UserAttributes.uaMemoizeLSB user_attributes let hint_to_type_opt env hint = Option.map hint ~f:(Decl_hint.hint env) let hint_to_type ~default env hint = Option.value (hint_to_type_opt env hint) ~default let make_wildcard_ty pos = mk (Reason.Rwitness_from_decl pos, Typing_defs.Twildcard) let make_param_ty env param = let param_pos = Decl_env.make_decl_pos env param.param_pos in let ty = hint_to_type ~default:(make_wildcard_ty param_pos) env (hint_of_type_hint param.param_type_hint) in let ty = match get_node ty with | t when param.param_is_variadic -> (* When checking a call f($a, $b) to a function f(C ...$args), * both $a and $b must be of type C *) mk (Reason.Rvar_param_from_decl param_pos, t) | _ -> ty in let mode = get_param_mode param.param_callconv in { fp_pos = param_pos; fp_name = (* The parser uses ... for variadic parameters that lack a name *) (if String.equal param.param_name "..." then None else Some param.param_name); fp_type = { et_type = ty; et_enforced = Unenforced }; fp_flags = make_fp_flags ~mode ~accept_disposable: (has_accept_disposable_attribute param.param_user_attributes) ~has_default:(Option.is_some param.param_expr) ~ifc_external:(has_external_attribute param.param_user_attributes) ~ifc_can_call:(has_can_call_attribute param.param_user_attributes) ~readonly:(Option.is_some param.param_readonly); } let ret_from_fun_kind ?(is_constructor = false) env (pos : pos) kind hint = let pos = Decl_env.make_decl_pos env pos in let ret_ty () = if is_constructor then mk (Reason.Rwitness_from_decl pos, Tprim Tvoid) else hint_to_type ~default:(make_wildcard_ty pos) env hint in match hint with | None -> (match kind with | Ast_defs.FGenerator -> let r = Reason.Rret_fun_kind_from_decl (pos, kind) in mk ( r, Tapply ((pos, SN.Classes.cGenerator), [ret_ty (); ret_ty (); ret_ty ()]) ) | Ast_defs.FAsyncGenerator -> let r = Reason.Rret_fun_kind_from_decl (pos, kind) in mk ( r, Tapply ( (pos, SN.Classes.cAsyncGenerator), [ret_ty (); ret_ty (); ret_ty ()] ) ) | Ast_defs.FAsync -> let r = Reason.Rret_fun_kind_from_decl (pos, kind) in mk (r, Tapply ((pos, SN.Classes.cAwaitable), [ret_ty ()])) | Ast_defs.FSync -> ret_ty ()) | Some _ -> ret_ty () let type_param = Decl_hint.aast_tparam_to_decl_tparam let where_constraint env (ty1, ck, ty2) = (Decl_hint.hint env ty1, ck, Decl_hint.hint env ty2) (* Functions building the types for the parameters of a function *) (* It's not completely trivial because of optional arguments *) let check_params paraml = (* We wish to give an error on the first non-default parameter after a default parameter. That is: function foo(int $x, ?int $y = null, int $z) is an error on $z. *) (* TODO: This check doesn't need to be done at type checking time; it is entirely syntactic. When we switch over to the FFP, remove this code. *) let rec loop seen_default paraml = match paraml with | [] -> None | param :: rl -> if param.param_is_variadic then None (* Assume that a variadic parameter is the last one we need to check. We've already given a parse error if the variadic parameter is not last. *) else if seen_default && Option.is_none param.param_expr then Some Typing_error.(primary @@ Primary.Previous_default param.param_pos) (* We've seen at least one required parameter, and there's an optional parameter after it. Given an error, and then stop looking for more errors in this parameter list. *) else loop (Option.is_some param.param_expr) rl in loop false paraml let make_params env paraml = List.map paraml ~f:(make_param_ty env)
OCaml Interface
hhvm/hphp/hack/src/decl/decl_fun_utils.mli
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val find_policied_attribute : Nast.user_attribute list -> Typing_defs.ifc_fun_decl val has_return_disposable_attribute : Nast.user_attribute list -> bool val has_memoize_attribute : Nast.user_attribute list -> bool val hint_to_type_opt : Decl_env.env -> Nast.xhp_attr_hint option -> Typing_defs.decl_ty option val make_param_ty : Decl_env.env -> Nast.fun_param -> Typing_defs.decl_ty Typing_defs_core.fun_param val ret_from_fun_kind : ?is_constructor:bool -> Decl_env.env -> Pos.t -> Ast_defs.fun_kind -> Nast.xhp_attr_hint option -> Typing_defs.decl_ty val type_param : Decl_env.env -> Nast.tparam -> Typing_defs.decl_ty Typing_defs_core.tparam val where_constraint : Decl_env.env -> Nast.xhp_attr_hint * 'a * Nast.xhp_attr_hint -> Typing_defs.decl_ty * 'a * Typing_defs.decl_ty val check_params : Nast.fun_param list -> Typing_error.t option val make_params : Decl_env.env -> Nast.fun_param list -> Typing_defs.decl_ty Typing_defs_core.fun_param list
OCaml
hhvm/hphp/hack/src/decl/decl_heap.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 Typing_defs open Decl_defs (* All the following heaps will have a local cache of size 1000 *) module Capacity = struct let capacity = 1000 end (* The following classes are used to make sure we make no typing * mistake when interacting with the database. The database knows * how to associate a string to a string. We need to deserialize * the string and make sure the type is correct. By using these * modules, the places where there could be a typing mistake are * very well isolated. *) (* Module used to represent serialized classes *) module Class = struct type t = decl_class_type let description = "Decl_Class" end (* a function type *) module Fun = struct type t = fun_elt let description = "Decl_Fun" end module Typedef = struct type t = Typing_defs.typedef_type let description = "Decl_Typedef" end module GConst = struct type t = const_decl let description = "Decl_GConst" end module Module = struct type t = Typing_defs.module_def_type let description = "Decl_Module" end module Funs = SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (StringKey) (Fun) (Capacity) module Classes = SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (StringKey) (Class) (Capacity) module Typedefs = SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (StringKey) (Typedef) (Capacity) module GConsts = SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (StringKey) (GConst) (Capacity) module Modules = SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (StringKey) (Module) (Capacity) module Property = struct type t = decl_ty let description = "Decl_Property" end module StaticProperty = struct type t = decl_ty let description = "Decl_StaticProperty" end module Method = struct type t = fun_elt let description = "Decl_Method" end module StaticMethod = struct type t = fun_elt let description = "Decl_StaticMethod" end module Constructor = struct type t = fun_elt let description = "Decl_Constructor" end module ClassEltKey = struct type t = string * string let compare (cls1, elt1) (cls2, elt2) = let r = String.compare cls1 cls2 in if not (Core.Int.equal r 0) then r else String.compare elt1 elt2 let to_string (cls, elt) = cls ^ "::" ^ elt end module Props = SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (ClassEltKey) (Property) (Capacity) module StaticProps = SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (ClassEltKey) (StaticProperty) (Capacity) module Methods = SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (ClassEltKey) (Method) (Capacity) module StaticMethods = SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (ClassEltKey) (StaticMethod) (Capacity) module Constructors = SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (StringKey) (Constructor) (Capacity)
OCaml Interface
hhvm/hphp/hack/src/decl/decl_heap.mli
(* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Typing_defs open Decl_defs module Capacity : sig val capacity : int end module Class : SharedMem.Value with type t = decl_class_type module Fun : SharedMem.Value with type t = fun_elt module Typedef : SharedMem.Value with type t = typedef_type module GConst : SharedMem.Value with type t = const_decl module Module : SharedMem.Value with type t = module_def_type module Property : SharedMem.Value with type t = decl_ty module StaticProperty : SharedMem.Value with type t = decl_ty module Method : SharedMem.Value with type t = fun_elt module StaticMethod : SharedMem.Value with type t = fun_elt module Constructor : SharedMem.Value with type t = fun_elt module ClassEltKey : SharedMem.Key with type t = string * string module Funs : module type of SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (StringKey) (Fun) (Capacity) module Classes : module type of SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (StringKey) (Class) (Capacity) module Typedefs : module type of SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (StringKey) (Typedef) (Capacity) module GConsts : module type of SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (StringKey) (GConst) (Capacity) module Modules : module type of SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (StringKey) (Module) (Capacity) module Props : module type of SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (ClassEltKey) (Property) (Capacity) module StaticProps : module type of SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (ClassEltKey) (StaticProperty) (Capacity) module Methods : module type of SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (ClassEltKey) (Method) (Capacity) module StaticMethods : module type of SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (ClassEltKey) (StaticMethod) (Capacity) module Constructors : module type of SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.Evictable)) (StringKey) (Constructor) (Capacity)
OCaml
hhvm/hphp/hack/src/decl/decl_hint.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. * *) (*****************************************************************************) (* Converts a type hint into a type *) (*****************************************************************************) open Hh_prelude open Aast open Typing_defs module SN = Naming_special_names let make_decl_ty env p ty_ = mk (Typing_reason.Rhint (Decl_env.make_decl_pos env p), ty_) (* Unpacking a hint for typing *) let rec hint env (p, h) = let ty_ = hint_ p env h in make_decl_ty env p ty_ and context_hint env (p, h) = match h with | Hfun_context n -> make_decl_ty env p (Tgeneric (Format.sprintf "T/[ctx %s]" n, [])) | Haccess ((_, (Habstr (n, []) | Hvar n)), ids) -> let name = Format.sprintf "T/[%s::%s]" n (String.concat ~sep:"::" (List.map ~f:snd ids)) in make_decl_ty env p (Tgeneric (name, [])) | _ -> hint env (p, h) and shape_field_info_to_shape_field_type env { sfi_optional; sfi_hint; sfi_name = _ } = { sft_optional = sfi_optional; sft_ty = hint env sfi_hint } and aast_user_attribute_to_decl_user_attribute env { Aast_defs.ua_name; ua_params } = { Typing_defs.ua_name = Decl_env.make_decl_posed env ua_name; ua_params = List.filter_map ua_params ~f:(function | (_, _, Class_const ((_, _, CI (_, cls)), (_, name))) when String.equal name SN.Members.mClass -> Some (Typing_defs_core.Classname cls) | (_, _, Aast.EnumClassLabel (_, s)) -> Some (Typing_defs_core.EnumClassLabel s) | (_, _, Aast.String s) -> Some (Typing_defs_core.String s) | (_, _, Aast.Int i) -> Some (Typing_defs_core.Int i) | _ -> None); } and aast_contexts_to_decl_capability env ctxs default_pos : Aast.pos * decl_ty capability = match ctxs with | Some (pos, hl) -> let dtys = List.map ~f:(context_hint env) hl in (* For coeffect contexts, in general we do not simplify empty or singleton * intersection, we keep them as is, so we don't use Typing_make_type * on purpose. * However the direct decl parser removes the intersection when the * context was a single Hfun_context. Let's do the same here *) let reason = Reason.Rhint (Decl_env.make_decl_pos env pos) in let dty = match dtys with | [dty] -> begin match get_node dty with | Tgeneric _ -> dty | _ -> mk (reason, Tintersection dtys) end | _ -> mk (reason, Tintersection dtys) in (pos, CapTy dty) | None -> (default_pos, CapDefaults (Decl_env.make_decl_pos env default_pos)) and aast_tparam_to_decl_tparam env t = { tp_variance = t.Aast.tp_variance; tp_name = Decl_env.make_decl_posed env t.Aast.tp_name; tp_tparams = List.map ~f:(aast_tparam_to_decl_tparam env) t.Aast.tp_parameters; tp_constraints = List.map ~f:(Tuple.T2.map_snd ~f:(hint env)) t.Aast.tp_constraints; tp_reified = t.Aast.tp_reified; tp_user_attributes = List.map ~f:(aast_user_attribute_to_decl_user_attribute env) t.Aast.tp_user_attributes; } and hint_ p env = function | Hany -> Typing_defs.make_tany () | Herr -> Typing_defs.make_tany () | Hmixed -> Tmixed | Hwildcard -> Twildcard | Hnonnull -> Tnonnull | Hthis -> Tthis | Hdynamic -> Tdynamic | Hnothing -> Tunion [] | Hvec_or_dict (h1, h2) -> let t1 = match h1 with | Some h -> hint env h | None -> mk ( Typing_reason.Rvec_or_dict_key (Decl_env.make_decl_pos env p), Tprim Aast.Tarraykey ) in Tvec_or_dict (t1, hint env h2) | Hprim p -> Tprim p | Habstr (x, argl) -> let argl = List.map argl ~f:(hint env) in Tgeneric (x, argl) | Hoption h -> let h = hint env h in Toption h | Hlike h -> Tlike (hint env h) | Hfun { hf_is_readonly = ro; hf_param_tys = hl; hf_param_info = pil; hf_variadic_ty = vh; hf_ctxs = ctxs; hf_return_ty = h; hf_is_readonly_return = readonly_ret; } -> let make_param ((p, _) as x) param_info = let (readonly, kind) = match param_info with | Some p -> let readonly = match p.hfparam_readonlyness with | Some Ast_defs.Readonly -> true | _ -> false in let param_kind = get_param_mode p.hfparam_kind in (readonly, param_kind) | None -> (false, FPnormal) in { fp_pos = Decl_env.make_decl_pos env p; fp_name = None; fp_type = possibly_enforced_hint env x; fp_flags = make_fp_flags ~mode:kind ~accept_disposable:false ~has_default:false (* Currently do not support external and cancall on parameters of function parameters *) ~ifc_external:false ~ifc_can_call:false ~readonly; } in let readonly_opt ro = match ro with | Some Ast_defs.Readonly -> true | None -> false in let paraml = List.map2_exn hl pil ~f:make_param in let implicit_params = let (_pos, capability) = aast_contexts_to_decl_capability env ctxs p in { capability } in let ret = possibly_enforced_hint env h in let (variadic, paraml) = match vh with | Some t -> (true, paraml @ [make_param t None]) | None -> (false, paraml) in Tfun { ft_tparams = []; ft_where_constraints = []; ft_params = paraml; ft_implicit_params = implicit_params; ft_ret = ret; ft_flags = make_ft_flags Ast_defs.FSync ~return_disposable:false ~returns_readonly:(readonly_opt readonly_ret) ~readonly_this:(readonly_opt ro) ~support_dynamic_type:false ~is_memoized:false ~variadic; (* TODO: handle function parameters with <<CanCall>> *) ft_ifc_decl = default_ifc_fun_decl; (* TODO *) ft_cross_package = None; } | Happly (id, argl) -> let id = Decl_env.make_decl_posed env id in let argl = List.map argl ~f:(hint env) in Tapply (id, argl) | Haccess (root_ty, ids) -> let root_ty = hint_ p env (snd root_ty) in let rec translate res ids = match ids with | [] -> res | id :: ids -> translate (Taccess ( mk (Typing_reason.Rhint (Decl_env.make_decl_pos env p), res), Decl_env.make_decl_posed env id )) ids in translate root_ty ids | Hrefinement (root_ty, members) -> let root_ty = hint env root_ty in let class_ref = (* We do not err on duplicate refinements as the parser will * already have *) List.fold members ~init:{ cr_consts = SMap.empty } ~f:(fun { cr_consts } r -> let (id, rc) = match r with | Rctx ((_, id), CRexact h) -> (id, { rc_bound = TRexact (context_hint env h); rc_is_ctx = true }) | Rctx (((_, id) as _pos), CRloose { cr_lower; cr_upper }) -> let decl_bounds h = Option.map ~f:(context_hint env) h |> Option.to_list in let tr_lower = decl_bounds cr_lower in let tr_upper = decl_bounds cr_upper in ( id, { rc_bound = TRloose { tr_lower; tr_upper }; rc_is_ctx = true } ) | Rtype ((_, id), TRexact h) -> (id, { rc_bound = TRexact (hint env h); rc_is_ctx = false }) | Rtype ((_, id), TRloose { tr_lower; tr_upper }) -> let decl_bounds = List.map ~f:(hint env) in let tr_lower = decl_bounds tr_lower in let tr_upper = decl_bounds tr_upper in ( id, { rc_bound = TRloose { tr_lower; tr_upper }; rc_is_ctx = false } ) in { cr_consts = SMap.add id rc cr_consts }) in Trefinement (root_ty, class_ref) | Htuple hl -> let tyl = List.map hl ~f:(hint env) in Ttuple tyl | Hunion hl -> let tyl = List.map hl ~f:(hint env) in Tunion tyl | Hintersection hl -> let tyl = List.map hl ~f:(hint env) in Tintersection tyl | Hshape { nsi_allows_unknown_fields; nsi_field_map } -> let shape_kind = hint env ( p, if nsi_allows_unknown_fields then Hmixed else Hnothing ) in let fdm = List.fold_left ~f:(fun acc i -> TShapeMap.add (TShapeField.of_ast (Decl_env.make_decl_pos env) i.sfi_name) (shape_field_info_to_shape_field_type env i) acc) ~init:TShapeMap.empty nsi_field_map in Tshape { s_origin = Missing_origin; s_unknown_value = shape_kind; s_fields = fdm; } | Hsoft (p, h_) -> hint_ p env h_ | Hfun_context _ | Hvar _ -> Errors.internal_error p "Unexpected context hint"; Tunion [] and possibly_enforced_hint env h = (* Initially we assume that a type is not enforced at runtime. * We refine this during localization *) { et_enforced = Unenforced; et_type = hint env h }
OCaml Interface
hhvm/hphp/hack/src/decl/decl_hint.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 hint : Decl_env.env -> Aast.hint -> Typing_defs.decl_ty val context_hint : Decl_env.env -> Aast.hint -> Typing_defs.decl_ty val aast_tparam_to_decl_tparam : Decl_env.env -> Nast.tparam -> Typing_defs.decl_ty Typing_defs.tparam val aast_user_attribute_to_decl_user_attribute : Decl_env.env -> Nast.user_attribute -> Typing_defs.user_attribute val aast_contexts_to_decl_capability : Decl_env.env -> Aast.contexts option -> Aast.pos -> Aast.pos * Typing_defs.decl_ty Typing_defs.capability
OCaml
hhvm/hphp/hack/src/decl/decl_inherit.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (*****************************************************************************) (* Module dealing with inheritance. * When we want to declare a new class, we first have to retrieve all the * types that were inherited from their parents. *) (*****************************************************************************) open Hh_prelude open Option.Monad_infix open Decl_defs open Shallow_decl_defs open Typing_defs module Inst = Decl_instantiate (*****************************************************************************) (* This is what we are trying to produce for a given class. *) (*****************************************************************************) type inherited = { ih_substs: subst_context SMap.t; ih_cstr: (Decl_defs.element * fun_elt option) option * consistent_kind; ih_consts: class_const SMap.t; ih_typeconsts: typeconst_type SMap.t; ih_props: (Decl_defs.element * decl_ty option) SMap.t; ih_sprops: (Decl_defs.element * decl_ty option) SMap.t; ih_methods: (Decl_defs.element * fun_elt option) SMap.t; ih_smethods: (Decl_defs.element * fun_elt option) SMap.t; } let empty = { ih_substs = SMap.empty; ih_cstr = (None, Inconsistent); ih_consts = SMap.empty; ih_typeconsts = SMap.empty; ih_props = SMap.empty; ih_sprops = SMap.empty; ih_methods = SMap.empty; ih_smethods = SMap.empty; } (*****************************************************************************) (* Functions used to merge an additional inherited class to the types * we already inherited. *) (*****************************************************************************) module type Member_S = sig type t val is_abstract : t -> bool val is_synthesized : t -> bool val has_lsb : t -> bool val visibility : t -> ce_visibility end module Decl_defs_element : Member_S with type t = Decl_defs.element = struct type t = Decl_defs.element let is_abstract = get_elt_abstract let is_synthesized = get_elt_synthesized let has_lsb = get_elt_lsb let visibility m = m.elt_visibility end module Typing_defs_class_elt : Member_S with type t = Typing_defs.class_elt = struct type t = Typing_defs.class_elt let is_abstract = get_ce_abstract let is_synthesized = get_ce_synthesized let has_lsb = get_ce_lsb let visibility m = m.ce_visibility end module OverridePrecedence : sig (** The override precedence of a member is used to determine if a member overrides previous members from other parents with the same name. *) type t val make : (module Member_S with type t = 'member) -> 'member -> t val ( > ) : t -> t -> bool val is_highest : t -> bool end = struct type t = { is_concrete: bool; is_not_synthesized: bool; } let make (type member) (module Member : Member_S with type t = member) (member : member) = { is_concrete = not @@ Member.is_abstract member; is_not_synthesized = not @@ Member.is_synthesized member; } let bool_to_int b = if b then 1 else 0 let to_int { is_concrete; is_not_synthesized } = (2 * bool_to_int is_concrete) + bool_to_int is_not_synthesized let ( > ) x y = Int.( > ) (to_int x) (to_int y) let is_highest { is_concrete; is_not_synthesized } = is_concrete && is_not_synthesized end (** Reasons to keep the old signature: - We don't want to override a concrete method with an abstract one. - We don't want to override a method that's actually implemented by the programmer with one that's "synthetic", e.g. arising merely from a require-extends declaration in a trait. When these two considerations conflict, we give precedence to abstractness for determining priority of the method. It's possible to implement this boolean logic by just comparing the boolean tuples (is_concrete, is_non_synthesized) of each member, which we do in the OverridePrecedence module. *) let should_keep_old_sig (sig_, _) (old_sig, _) = let precedence = OverridePrecedence.make (module Decl_defs_element) in OverridePrecedence.(precedence old_sig > precedence sig_) let add_method name sig_ methods = match SMap.find_opt name methods with | None -> (* The method didn't exist so far, let's add it *) SMap.add name sig_ methods | Some old_sig -> if should_keep_old_sig sig_ old_sig then methods (* Otherwise, we *are* overwriting a method definition. This is * OK when a naming conflict is parent class vs trait (trait * wins!), but not really OK when the naming conflict is trait vs * trait (we rely on HHVM to catch the error at runtime) *) else let sig_ = Tuple.T2.map_fst sig_ ~f:reset_elt_superfluous_override in SMap.add name sig_ methods let add_methods methods' acc = SMap.fold add_method methods' acc let add_const name const acc = match SMap.find_opt name acc with | None -> SMap.add name const acc | Some existing_const -> (match ( const.cc_synthesized, existing_const.cc_synthesized, const.cc_abstract, existing_const.cc_abstract ) with | (true, false, _, _) -> (* Don't replace a constant with a synthesized constant. This covers the following case: class HasFoo { abstract const int FOO; } trait T { require extends Foo; } class Child extends HasFoo { use T; } In this case, Child still doesn't have a value for the FOO constant. *) acc | (_, _, CCAbstract false, CCAbstract true) | (_, _, CCAbstract _, CCConcrete) -> (* Don't replace a concrete constant with an abstract constant found later in the MRO.*) acc | (_, _, _, _) -> SMap.add name const acc) let add_members members acc = SMap.fold SMap.add members acc let add_typeconst env c name sig_ typeconsts = let fix_synthesized = TypecheckerOptions.enable_strict_const_semantics (Decl_env.tcopt env) > 3 in match SMap.find_opt name typeconsts with | None -> (* The type constant didn't exist so far, let's add it *) SMap.add name sig_ typeconsts | Some old_sig -> let typeconsts = (* Boolean OR for the second element of the tuple. If some typeconst in some ancestor was enforceable, then the child class' typeconst will be enforceable too, even if we didn't take that ancestor typeconst. *) if snd sig_.ttc_enforceable && not (snd old_sig.ttc_enforceable) then SMap.add name { old_sig with ttc_enforceable = sig_.ttc_enforceable } typeconsts else typeconsts in (match ( old_sig.ttc_synthesized, sig_.ttc_synthesized, old_sig.ttc_kind, sig_.ttc_kind ) with | (false, true, _, _) when Ast_defs.is_c_class c.sc_kind && fix_synthesized -> (* Don't replace a type constant with a synthesized type constant. This covers the following case: class A { const type T = int; } trait T { require extends A; } class Child extends A { use T; } Child should not consider T to be synthesized. *) typeconsts (* This covers the following case * * interface I1 { abstract const type T; } * interface I2 { const type T = int; } * * class C implements I1, I2 {} * * Then C::T == I2::T since I2::T is not abstract *) | (_, _, TCConcrete _, TCAbstract _) -> typeconsts (* This covers the following case * * interface I { * abstract const type T as arraykey; * } * * abstract class A { * abstract const type T as arraykey = string; * } * * final class C extends A implements I {} * * C::T must come from A, not I, as A provides the default that will synthesize * into a concrete type constant in C. *) | ( _, _, TCAbstract { atc_default = Some _; _ }, TCAbstract { atc_default = None; _ } ) -> typeconsts | (_, _, _, _) -> (* When a type constant is declared in multiple parents we need to make a * subtle choice of what type we inherit. For example in: * * interface I1 { abstract const type t as Container<int>; } * interface I2 { abstract const type t as KeyedContainer<int, int>; } * abstract class C implements I1, I2 {} * * Depending on the order the interfaces are declared, we may report an error. * Since this could be confusing there is special logic in Typing_extends that * checks for this potentially ambiguous situation and warns the programmer to * explicitly declare T in C. *) let sig_ = (* Boolean OR for the second element of the tuple. If a typeconst we already inherited from some other ancestor was enforceable, then the one we inherit here will be enforceable too. *) if snd old_sig.ttc_enforceable && not (snd sig_.ttc_enforceable) then { sig_ with ttc_enforceable = old_sig.ttc_enforceable } else sig_ in SMap.add name sig_ typeconsts) let add_constructor (cstr, cstr_consist) (acc, acc_consist) = let ce = match (cstr, acc) with | (None, _) -> acc | (Some ce, Some acce) when should_keep_old_sig ce acce -> acc | _ -> cstr in (ce, Decl_utils.coalesce_consistent acc_consist cstr_consist) let add_inherited env c inherited acc = { ih_substs = SMap.merge begin fun _ old_subst_opt new_subst_opt -> match (old_subst_opt, new_subst_opt) with | (None, None) -> None | (Some s, None) | (None, Some s) -> Some s (* If the old subst_context came via require extends, then we want to use * the substitutions from the actual extends instead. e.g., * * class Base<+T> {} * trait MyTrait { require extends Base<mixed>; } * class Child extends Base<int> { use MyTrait; } * * Here the subst_context (MyTrait/[T -> mixed]) should be overridden by * (Child/[T -> int]), because it's the actual extension of class Base. *) | (Some old_subst, Some new_subst) -> if (not new_subst.sc_from_req_extends) || old_subst.sc_from_req_extends then Some new_subst else Some old_subst end acc.ih_substs inherited.ih_substs; ih_cstr = add_constructor inherited.ih_cstr acc.ih_cstr; ih_consts = SMap.fold add_const inherited.ih_consts acc.ih_consts; ih_typeconsts = SMap.fold (add_typeconst env c) inherited.ih_typeconsts acc.ih_typeconsts; ih_props = add_members inherited.ih_props acc.ih_props; ih_sprops = add_members inherited.ih_sprops acc.ih_sprops; ih_methods = add_methods inherited.ih_methods acc.ih_methods; ih_smethods = add_methods inherited.ih_smethods acc.ih_smethods; } (*****************************************************************************) (* Helpers *) (*****************************************************************************) let make_substitution class_type class_parameters = Inst.make_subst class_type.dc_tparams class_parameters let mark_as_synthesized inh = let mark_elt elt = Tuple.T2.map_fst elt ~f:set_elt_synthesized in { ih_substs = SMap.map begin (fun sc -> { sc with sc_from_req_extends = true }) end inh.ih_substs; ih_cstr = (Option.map (fst inh.ih_cstr) ~f:mark_elt, snd inh.ih_cstr); ih_props = SMap.map mark_elt inh.ih_props; ih_sprops = SMap.map mark_elt inh.ih_sprops; ih_methods = SMap.map mark_elt inh.ih_methods; ih_smethods = SMap.map mark_elt inh.ih_smethods; ih_typeconsts = SMap.map (fun const -> { const with ttc_synthesized = true }) inh.ih_typeconsts; ih_consts = SMap.map (fun const -> { const with cc_synthesized = true }) inh.ih_consts; } (*****************************************************************************) (* Code filtering the private members (useful for inheritance) *) (*****************************************************************************) let is_private (type member) (module Member : Member_S with type t = member) (member : member) : bool = match Member.visibility member with | Vprivate _ -> not @@ Member.has_lsb member | Vpublic | Vprotected _ | Vinternal _ -> false let filter_privates class_type = let is_not_private _ elt = not @@ is_private (module Decl_defs_element) elt in { class_type with dc_props = SMap.filter is_not_private class_type.dc_props; dc_sprops = SMap.filter is_not_private class_type.dc_sprops; dc_methods = SMap.filter is_not_private class_type.dc_methods; dc_smethods = SMap.filter is_not_private class_type.dc_smethods; } let chown_private_and_protected owner class_type = let chown elt = match elt.elt_visibility with | Vprivate _ -> { elt with elt_visibility = Vprivate owner } (* Update protected member that's included via a `use` statement, unless * it's synthesized, in which case its owner will be the one specified * in `requires extends` or `requires implements` *) | Vprotected _ when not (get_elt_synthesized elt) -> { elt with elt_visibility = Vprotected owner } | Vpublic | Vprotected _ | Vinternal _ -> elt in { class_type with dc_props = SMap.map chown class_type.dc_props; dc_sprops = SMap.map chown class_type.dc_sprops; dc_methods = SMap.map chown class_type.dc_methods; dc_smethods = SMap.map chown class_type.dc_smethods; } (*****************************************************************************) (* Builds the inherited type when the class lives in Hack *) (*****************************************************************************) let pair_with_heap_entries : type heap_entry. element SMap.t -> heap_entry SMap.t option -> (element * heap_entry option) SMap.t = fun elts heap_entries -> SMap.mapi (fun name elt -> (elt, heap_entries >>= SMap.find_opt name)) elts let inherit_hack_class child parent_name parent argl (parent_members : Decl_store.class_members option) : inherited = let subst = make_substitution parent argl in let parent = match parent.dc_kind with | Ast_defs.Ctrait -> (* Change the private/protected visibility to point to the inheriting class *) chown_private_and_protected (snd child.sc_name) parent | Ast_defs.Cclass _ | Ast_defs.Cinterface -> filter_privates parent | Ast_defs.Cenum | Ast_defs.Cenum_class _ -> parent in let typeconsts = SMap.map (Inst.instantiate_typeconst_type subst) parent.dc_typeconsts in let consts = SMap.map (Inst.instantiate_cc subst) parent.dc_consts in let (cstr, constructor_consistency) = parent.dc_construct in let subst_ctx = { sc_subst = subst; sc_class_context = snd child.sc_name; sc_from_req_extends = false; } in let substs = SMap.add parent_name subst_ctx parent.dc_substs in let result = { ih_substs = substs; ih_cstr = ( Option.map cstr ~f:(fun cstr -> let constructor_heap_value = parent_members >>= fun m -> m.Decl_store.m_constructor in (cstr, constructor_heap_value)), constructor_consistency ); ih_consts = consts; ih_typeconsts = typeconsts; ih_props = pair_with_heap_entries parent.dc_props (parent_members >>| fun m -> m.Decl_store.m_properties); ih_sprops = pair_with_heap_entries parent.dc_sprops (parent_members >>| fun m -> m.Decl_store.m_static_properties); ih_methods = pair_with_heap_entries parent.dc_methods (parent_members >>| fun m -> m.Decl_store.m_methods); ih_smethods = pair_with_heap_entries parent.dc_smethods (parent_members >>| fun m -> m.Decl_store.m_static_methods); } in result (* mostly copy paste of inherit_hack_class *) let inherit_hack_class_constants_only class_type argl _parent_members = let subst = make_substitution class_type argl in let instantiate = SMap.map (Inst.instantiate_cc subst) in let consts = instantiate class_type.dc_consts in let typeconsts = SMap.map (Inst.instantiate_typeconst_type subst) class_type.dc_typeconsts in let result = { empty with ih_consts = consts; ih_typeconsts = typeconsts } in result (* This logic deals with importing XHP attributes from an XHP class via the "attribute :foo;" syntax. *) let inherit_hack_xhp_attrs_only class_type members = (* Filter out properties that are not XHP attributes *) let props = SMap.fold begin fun name prop acc -> if Option.is_some (get_elt_xhp_attr prop) then SMap.add name prop acc else acc end class_type.dc_props SMap.empty in let result = { empty with ih_props = pair_with_heap_entries props (members >>| fun m -> m.Decl_store.m_properties); } in result (*****************************************************************************) (* Include definitions inherited from a class (extends) or a trait (use) * or requires extends *) let from_class c (parents : Decl_store.class_entries SMap.t) parent_ty : inherited = let (_, (_, parent_name), parent_class_params) = Decl_utils.unwrap_class_type parent_ty in match SMap.find_opt parent_name parents with | None -> (* The class lives in PHP, we don't know anything about it *) empty | Some (class_, parent_members) -> (* The class lives in Hack *) inherit_hack_class c parent_name class_ parent_class_params parent_members let from_class_constants_only (parents : Decl_store.class_entries SMap.t) ty = let (_, (_, class_name), class_params) = Decl_utils.unwrap_class_type ty in match SMap.find_opt class_name parents with | None -> (* The class lives in PHP, we don't know anything about it *) empty | Some (class_, parent_members) -> (* The class lives in Hack *) inherit_hack_class_constants_only class_ class_params parent_members let from_class_xhp_attrs_only (parents : Decl_store.class_entries SMap.t) ty = let (_, (_pos, class_name), _class_params) = Decl_utils.unwrap_class_type ty in match SMap.find_opt class_name parents with | None -> (* The class lives in PHP, we don't know anything about it *) empty | Some (class_, parent_members) -> (* The class lives in Hack *) inherit_hack_xhp_attrs_only class_ parent_members let parents_which_provide_members c = (* In an abstract class or a trait, we assume the interfaces * will be implemented in the future, so we take them as * part of the class (as requested by dependency injection implementers) *) match c.sc_kind with | Ast_defs.Cclass k when Ast_defs.is_abstract k -> c.sc_implements @ c.sc_extends | Ast_defs.Ctrait -> c.sc_implements @ c.sc_extends @ c.sc_req_implements | Ast_defs.(Cclass _ | Cinterface | Cenum | Cenum_class _) -> c.sc_extends let from_parent env c (parents : Decl_store.class_entries SMap.t) acc parent = let inherited = from_class c parents parent in add_inherited env c inherited acc let from_requirements env c parents acc reqs = let inherited = from_class c parents reqs in let inherited = mark_as_synthesized inherited in add_inherited env c inherited acc let from_trait env c parents acc uses = let inherited = from_class c parents uses in add_inherited env c inherited acc let from_xhp_attr_use env c (parents : Decl_store.class_entries SMap.t) acc uses = let inherited = from_class_xhp_attrs_only parents uses in add_inherited env c inherited acc let from_interface_constants env c (parents : Decl_store.class_entries SMap.t) acc impls = let inherited = from_class_constants_only parents impls in add_inherited env c inherited acc let has_highest_precedence : (OverridePrecedence.t * 'a) option -> bool = function | Some (precedence, _) -> OverridePrecedence.is_highest precedence | _ -> false let max_precedence (type a) : (OverridePrecedence.t * a) option -> (OverridePrecedence.t * a) option -> (OverridePrecedence.t * a) option = Option.merge ~f:(fun x y -> let (x_precedence, _) = x and (y_precedence, _) = y in if OverridePrecedence.(y_precedence > x_precedence) then y else x) let ( >?? ) (x : (OverridePrecedence.t * 'a) option) (y : (OverridePrecedence.t * 'a) option lazy_t) : (OverridePrecedence.t * 'a) option = if has_highest_precedence x then x else max_precedence x (Lazy.force y) let find_first_with_highest_precedence (l : 'a list) ~(f : 'a -> (OverridePrecedence.t * _) option) : (OverridePrecedence.t * _) option = let rec loop found = function | [] -> found | x :: l -> let x = f x in if has_highest_precedence x then x else loop (max_precedence found x) l in loop None l type parent_kind = | Parent | Requirement | Trait type parent = decl_ty module OrderedParents : sig type t (** This provides the parent traversal order for member folding. This is appropriate for all members except XHP attributes and constants. The order is different for those and these are handled elsewhere. *) val get : shallow_class -> t val fold : t -> init:'acc -> f:(parent_kind -> 'acc -> parent -> 'acc) -> 'acc (** Reverse the ordered parents. *) val rev : t -> t val find_map_first_with_highest_precedence : t -> f:(parent_kind -> parent -> (OverridePrecedence.t * 'res) option) -> (OverridePrecedence.t * 'res) option end = struct type t = (parent_kind * parent list) list let get (c : shallow_class) : t = [ (Parent, parents_which_provide_members c |> List.rev); (Requirement, c.sc_req_class @ c.sc_req_extends); (Trait, c.sc_uses); ] let fold (t : t) ~init ~(f : parent_kind -> 'acc -> parent -> 'acc) = List.fold_left t ~init ~f:(fun acc (parent_kind, parents) -> List.fold_left ~init:acc ~f:(f parent_kind) parents) let rev : t -> t = List.rev_map ~f:(Tuple2.map_snd ~f:List.rev) let find_map_first_with_highest_precedence (type res) (t : t) ~(f : parent_kind -> parent -> (OverridePrecedence.t * res) option) : (OverridePrecedence.t * res) option = List.fold t ~init:None ~f:(fun acc (parent_kind, parents) -> acc >?? lazy (find_first_with_highest_precedence parents ~f:(f parent_kind))) end let make env c ~cache:(parents : Decl_store.class_entries SMap.t) = let acc = empty in let acc = OrderedParents.get c |> OrderedParents.fold ~init:acc ~f:(function | Parent -> from_parent env c parents | Requirement -> from_requirements env c parents | Trait -> from_trait env c parents) in let acc = List.fold_left ~f:(from_xhp_attr_use env c parents) ~init:acc c.sc_xhp_attr_uses in (* todo: what about the same constant defined in different interfaces * we implement? We should forbid and say "constant already defined". * to julien: where is the logic that check for duplicated things? * todo: improve constant handling, see task #2487051 *) let acc = List.fold_left ~f:(from_interface_constants env c parents) ~init:acc c.sc_req_implements in let included_enums = match c.sc_enum_type with | None -> [] | Some enum_type -> enum_type.te_includes in let acc = List.fold_left ~f:(from_interface_constants env c parents) ~init:acc included_enums in List.fold_left ~f:(from_interface_constants env c parents) ~init:acc c.sc_implements let find_overridden_method (cls : shallow_class) ~(get_method : decl_ty -> class_elt option) : class_elt option = let is_not_private m = not @@ is_private (module Typing_defs_class_elt) m in let precedence : class_elt -> OverridePrecedence.t = OverridePrecedence.make (module Typing_defs_class_elt) in let get_method_with_precedence parent_kind ty = match parent_kind with | Trait -> None | Parent | Requirement -> get_method ty |> Option.filter ~f:is_not_private >>| fun method_ -> (precedence method_, method_) in OrderedParents.get cls |> OrderedParents.rev |> OrderedParents.find_map_first_with_highest_precedence ~f:get_method_with_precedence >>| snd
OCaml Interface
hhvm/hphp/hack/src/decl/decl_inherit.mli
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (*****************************************************************************) (* Module dealing with inheritance. * When we want to declare a new class, we first have to retrieve all the * types that where inherited from their parents. *) (*****************************************************************************) open Decl_defs open Typing_defs type inherited = { ih_substs: subst_context SMap.t; ih_cstr: (element * fun_elt option) option * consistent_kind; ih_consts: class_const SMap.t; ih_typeconsts: typeconst_type SMap.t; ih_props: (element * decl_ty option) SMap.t; ih_sprops: (element * decl_ty option) SMap.t; ih_methods: (element * fun_elt option) SMap.t; ih_smethods: (element * fun_elt option) SMap.t; } (** Builds the [inherited] type by fetching any ancestor from the heap. The [cache] parameter is a map of heap entries we might already have at hand which acts as a cache for the shared heap. *) val make : Decl_env.env -> Shallow_decl_defs.shallow_class -> cache:Decl_store.class_entries SMap.t -> inherited (** [find_overridden_method cls ~get_method] finds in the parents of [cls] a method overriden by [cls]. *) val find_overridden_method : Shallow_decl_defs.shallow_class -> get_method:(decl_ty -> class_elt option) -> class_elt option
OCaml
hhvm/hphp/hack/src/decl/decl_init_check.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 Decl_defs open Aast open Shallow_decl_defs open Typing_defs module Attrs = Naming_attributes module SN = Naming_special_names (** Helpers for checking initialization of class properties by looking at decls. *) type get_class_add_dep = Decl_env.env -> string -> Decl_defs.decl_class_type option let parent_init_prop = "parent::" ^ SN.Members.__construct (* If we need to call parent::__construct, we treat it as if it were * a class variable that needs to be initialized. It's a bit hacky * but it works. The idea here is that if the parent needs to be * initialized, we add a phony class variable. *) let add_parent_construct ~(get_class_add_dep : get_class_add_dep) decl_env c props parent_hint = match parent_hint with | (_, Happly ((_, parent), _)) -> (match get_class_add_dep decl_env parent with | Some class_ when class_.dc_need_init -> let (c_constructor, _, _) = split_methods c.c_methods in if Option.is_some c_constructor then SSet.add parent_init_prop props else props | _ -> props) | _ -> props (* As above, but for shallow_class decls rather than class NASTs. *) let add_parent_construct_from_shallow_decl ~get_class_add_dep decl_env sc props parent_ty = match get_node parent_ty with | Tapply ((_, parent), _) -> (match get_class_add_dep decl_env parent with | Some class_ when class_.dc_need_init && Option.is_some sc.sc_constructor -> SSet.add parent_init_prop props | _ -> props) | _ -> props let parent ~(get_class_add_dep : get_class_add_dep) decl_env c acc = if FileInfo.is_hhi c.c_mode then acc else if Ast_defs.is_c_trait c.c_kind then let (req_extends, _req_implements, _req_class) = split_reqs c.c_reqs in List.fold_left req_extends ~init:acc ~f:(add_parent_construct ~get_class_add_dep decl_env c) else match c.c_extends with | [] -> acc | parent_ty :: _ -> add_parent_construct ~get_class_add_dep decl_env c acc parent_ty (* As above, but for shallow_class decls rather than class NASTs. *) let parent_from_shallow_decl ~(get_class_add_dep : get_class_add_dep) decl_env sc acc = if FileInfo.is_hhi sc.sc_mode then acc else if Ast_defs.is_c_trait sc.sc_kind then List.fold_left sc.sc_req_extends ~init:acc ~f:(add_parent_construct_from_shallow_decl ~get_class_add_dep decl_env sc) else match sc.sc_extends with | [] -> acc | parent_ty :: _ -> add_parent_construct_from_shallow_decl ~get_class_add_dep decl_env sc acc parent_ty let is_lateinit cv = Attrs.mem SN.UserAttributes.uaLateInit cv.cv_user_attributes let prop_may_need_init cv = if Option.is_some cv.cv_xhp_attr then false else if is_lateinit cv then false else match snd cv.cv_type with | None | Some (_, Hoption _) | Some (_, Hmixed) -> false | Some _ -> Option.is_none cv.cv_expr (* As above, but for shallow_class decls rather than class NASTs. *) let shallow_prop_may_need_init sp = if Option.is_some sp.sp_xhp_attr then false else if sp_lateinit sp then false else sp_needs_init sp let own_props c props = List.fold_left c.c_vars ~init:props ~f:(fun acc cv -> if prop_may_need_init cv then SSet.add (snd cv.cv_id) acc else acc) let init_not_required_props c props = List.fold_left c.c_vars ~init:props ~f:(fun acc cv -> if prop_may_need_init cv then acc else SSet.add (snd cv.cv_id) acc) let parent_props ~(get_class_add_dep : get_class_add_dep) decl_env c props = List.fold_left c.c_extends ~init:props ~f:(fun acc parent -> match parent with | (_, Happly ((_, parent), _)) -> let tc = get_class_add_dep decl_env parent in (match tc with | None -> acc | Some { dc_deferred_init_members = members; _ } -> SSet.union members acc) | _ -> acc) (* As above, but for shallow_class decls rather than class NASTs. *) let parent_props_from_shallow_decl ~(get_class_add_dep : get_class_add_dep) decl_env sc props = List.fold_left sc.sc_extends ~init:props ~f:(fun acc parent -> match get_node parent with | Tapply ((_, parent), _) -> let tc = get_class_add_dep decl_env parent in (match tc with | None -> acc | Some { dc_deferred_init_members = members; _ } -> SSet.union members acc) | _ -> acc) let trait_props ~(get_class_add_dep : get_class_add_dep) decl_env c props = List.fold_left c.c_uses ~init:props ~f:(fun acc trait_hint -> match trait_hint with | (_, Happly ((_, trait), _)) -> let class_ = get_class_add_dep decl_env trait in (match class_ with | None -> acc | Some { dc_construct = cstr; dc_deferred_init_members = members; _ } -> (* If our current class defines its own constructor, completely ignore * the fact that the trait may have had one defined and merge in all of * its members. * If the curr. class does not have its own constructor, only fold in * the trait members if it would not have had its own constructor when * defining `dc_deferred_init_members`. See logic in `class_` for * Ast_defs.Cclass (Abstract) to see where this deviated for traits. *) (match fst cstr with | None -> SSet.union members acc | Some cstr when String.( <> ) cstr.elt_origin trait || get_elt_abstract cstr -> SSet.union members acc | _ -> let (c_constructor, _, _) = split_methods c.c_methods in if Option.is_some c_constructor then SSet.union members acc else acc)) | _ -> acc) (** return the private init-requiring props of the class from its NAST *) let get_private_deferred_init_props c = List.fold_left c.c_vars ~init:SSet.empty ~f:(fun priv_props cv -> let name = snd cv.cv_id in let visibility = cv.cv_visibility in if prop_may_need_init cv && Aast.(equal_visibility visibility Private) then SSet.add name priv_props else priv_props) (** return all init-requiring props of the class and its ancestors from the given shallow class decl and the ancestors' folded decls. *) let get_nonprivate_deferred_init_props ~(get_class_add_dep : get_class_add_dep) decl_env sc = let props = List.fold_left sc.sc_props ~init:SSet.empty ~f:(fun props sp -> if shallow_prop_may_need_init sp then SSet.add (snd sp.sp_name) props else props) in let props = parent_props_from_shallow_decl ~get_class_add_dep decl_env sc props in let props = parent_from_shallow_decl ~get_class_add_dep decl_env sc props in props let private_deferred_init_props ~has_own_cstr c = match c.c_kind with | Ast_defs.Cclass k when Ast_defs.is_abstract k && not has_own_cstr -> get_private_deferred_init_props c | Ast_defs.Ctrait -> get_private_deferred_init_props c | Ast_defs.(Cclass _ | Cinterface | Cenum | Cenum_class _) -> SSet.empty let nonprivate_deferred_init_props ~has_own_cstr ~(get_class_add_dep : get_class_add_dep) decl_env sc = match sc.sc_kind with | Ast_defs.Cclass k when Ast_defs.is_abstract k && not has_own_cstr -> get_nonprivate_deferred_init_props ~get_class_add_dep decl_env sc | Ast_defs.Ctrait -> get_nonprivate_deferred_init_props ~get_class_add_dep decl_env sc | Ast_defs.(Cclass _ | Cinterface | Cenum | Cenum_class _) -> SSet.empty (** * [parent_initialized_members decl_env c] returns all members initialized in * the parents of [c], s.t. they should not be readable within [c]'s * [__construct] method until _after_ [parent::__construct] has been called. *) let parent_initialized_members ~get_class_add_dep decl_env c = let parent_initialized_members_helper = function | None -> SSet.empty | Some { dc_props; _ } -> dc_props |> SMap.filter (fun _ p -> Decl_defs.get_elt_needs_init p) |> SMap.keys |> SSet.of_list in List.fold_left c.c_extends ~init:SSet.empty ~f:(fun acc parent -> match parent with | (_, Happly ((_, parent), _)) -> get_class_add_dep decl_env parent |> parent_initialized_members_helper |> SSet.union acc | _ -> acc)
OCaml Interface
hhvm/hphp/hack/src/decl/decl_init_check.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 get_class_add_dep = Decl_env.env -> string -> Decl_defs.decl_class_type option val parent_init_prop : string val init_not_required_props : Nast.class_ -> SSet.t -> SSet.t val parent : get_class_add_dep:get_class_add_dep -> Decl_env.env -> Nast.class_ -> SSet.t -> SSet.t val own_props : Nast.class_ -> SSet.t -> SSet.t val parent_props : get_class_add_dep:get_class_add_dep -> Decl_env.env -> Nast.class_ -> SSet.t -> SSet.t val trait_props : get_class_add_dep:get_class_add_dep -> Decl_env.env -> Nast.class_ -> SSet.t -> SSet.t val private_deferred_init_props : has_own_cstr:bool -> Nast.class_ -> SSet.t val nonprivate_deferred_init_props : has_own_cstr:bool -> get_class_add_dep:get_class_add_dep -> Decl_env.env -> Shallow_decl_defs.shallow_class -> SSet.t val parent_initialized_members : get_class_add_dep:get_class_add_dep -> Decl_env.env -> Nast.class_ -> SSet.t
OCaml
hhvm/hphp/hack/src/decl/decl_instantiate.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 Typing_defs module Subst = Decl_subst let make_subst tparams tyl = Subst.make_decl tparams tyl let get_tparams_in_ty_and_acc acc ty = let tparams_visitor = object (this) inherit [SSet.t] Type_visitor.decl_type_visitor method! on_tgeneric acc _ s tyl = List.fold_left tyl ~f:this#on_type ~init:(SSet.add s acc) end in tparams_visitor#on_type acc ty let get_tparams_in_subst subst = SMap.fold (fun _ ty acc -> get_tparams_in_ty_and_acc acc ty) subst SSet.empty (*****************************************************************************) (* Code dealing with instantiation. *) (*****************************************************************************) let rec instantiate subst (ty : decl_ty) = let merge_hk_type orig_r orig_var ty args = let (r, ty_) = deref ty in let res_ty_ = match ty_ with | Tapply (n, existing_args) -> (* We could insist on existing_args = [] here unless we want to support partial application. *) Tapply (n, existing_args @ args) | Tgeneric (n, existing_args) -> (* Same here *) Tgeneric (n, existing_args @ args) | _ -> (* We could insist on args = [] here, everything else is a kinding error *) ty_ in mk (Reason.Rinstantiate (r, orig_var, orig_r), res_ty_) in (* PERF: If subst is empty then instantiation is a no-op. We can save a * significant amount of CPU by avoiding recursively deconstructing the ty * data type. *) if SMap.is_empty subst then ty else match deref ty with | (r, Tgeneric (x, args)) -> let args = List.map args ~f:(instantiate subst) in (match SMap.find_opt x subst with | Some x_ty -> merge_hk_type r x x_ty args | None -> mk (r, Tgeneric (x, args))) | (r, ty) -> let ty = instantiate_ subst ty in mk (r, ty) and instantiate_ subst x = match x with | Tgeneric _ -> assert false (* IMPORTANT: We cannot expand Taccess during instantiation because this can * be called before all type consts have been declared and inherited *) | Taccess (ty, id) -> let ty = instantiate subst ty in Taccess (ty, id) | Trefinement (ty, rs) -> let ty = instantiate subst ty in let rs = Class_refinement.map (instantiate subst) rs in Trefinement (ty, rs) | Tvec_or_dict (ty1, ty2) -> let ty1 = instantiate subst ty1 in let ty2 = instantiate subst ty2 in Tvec_or_dict (ty1, ty2) | (Tthis | Tmixed | Twildcard | Tdynamic | Tnonnull | Tany _ | Tprim _) as x -> x | Ttuple tyl -> let tyl = List.map tyl ~f:(instantiate subst) in Ttuple tyl | Tunion tyl -> let tyl = List.map tyl ~f:(instantiate subst) in Tunion tyl | Tintersection tyl -> let tyl = List.map tyl ~f:(instantiate subst) in Tintersection tyl | Toption ty -> let ty = instantiate subst ty in (* we want to avoid double option: ??T *) (match get_node ty with | Toption _ as ty_node -> ty_node | _ -> Toption ty) | Tlike ty -> Tlike (instantiate subst ty) | Tfun ft -> let tparams = ft.ft_tparams in (* First remove shadowed type parameters from the substitution. * For example, for * class C<T> { public function foo<T>(T $x):void } * class B extends C<int> { } * we do not want to replace T by int in foo's signature. *) let subst = List.fold_left ~f: begin (fun subst t -> SMap.remove (snd t.tp_name) subst) end ~init:subst tparams in (* Now collect up all generic parameters that appear in the target of the substitution *) let target_generics = get_tparams_in_subst subst in (* For generic parameters in the function type, rename them "away" from the parameters * that appear in the target of the substitituion, and extend the substitution with * the renaming. * * For example, consider * class Base<T> { public function cast<TF>(T $x):TF; } * class Derived<TF> extends Base<TF> { } * Now we start with a substitution T:=TF * But when going "under" the generic parameter to the cast method, * we must rename it to avoid capture: T:=TF, TF:=TF#0 * and so we end up with * function cast<TF#0>(TF $x):TF#0 *) let (subst, tparams) = List.fold_map ft.ft_tparams ~init:subst ~f:(fun subst tp -> let (pos, name) = tp.tp_name in if SSet.mem name target_generics then (* Fresh only because we don't support nesting of generic function types *) let fresh_tp_name = name ^ "#0" in let reason = Typing_reason.Rwitness_from_decl pos in ( SMap.add name (mk (reason, Tgeneric (fresh_tp_name, []))) subst, { tp with tp_name = (pos, fresh_tp_name) } ) else (subst, tp)) in let params = List.map ft.ft_params ~f:(fun param -> let ty = instantiate_possibly_enforced_ty subst param.fp_type in { param with fp_type = ty }) in let ret = instantiate_possibly_enforced_ty subst ft.ft_ret in let tparams = List.map tparams ~f:(fun t -> { t with tp_constraints = List.map t.tp_constraints ~f:(fun (ck, ty) -> (ck, instantiate subst ty)); }) in let where_constraints = List.map ft.ft_where_constraints ~f:(fun (ty1, ck, ty2) -> (instantiate subst ty1, ck, instantiate subst ty2)) in Tfun { ft with ft_params = params; ft_ret = ret; ft_tparams = tparams; ft_where_constraints = where_constraints; } | Tapply (x, tyl) -> let tyl = List.map tyl ~f:(instantiate subst) in Tapply (x, tyl) | Tshape { s_origin = _; s_unknown_value = shape_kind; s_fields = fdm } -> let fdm = ShapeFieldMap.map (instantiate subst) fdm in (* TODO(shapes) Should this be changing s_origin? *) Tshape { s_origin = Missing_origin; s_unknown_value = shape_kind; (* TODO(shapes) s_unknown_value should likely be instantiated *) s_fields = fdm; } | Tnewtype (name, tyl, ty) -> let tyl = List.map tyl ~f:(instantiate subst) in let ty = instantiate subst ty in Tnewtype (name, tyl, ty) and instantiate_possibly_enforced_ty subst et = { et_type = instantiate subst et.et_type; et_enforced = et.et_enforced } let instantiate_ce subst ({ ce_type = x; _ } as ce) = { ce with ce_type = lazy (instantiate subst (Lazy.force x)) } let instantiate_cc subst ({ cc_type = x; _ } as cc) = let x = instantiate subst x in { cc with cc_type = x } (* TODO(T88552052) is this necessary? Type consts are not allowed to reference type parameters, which is the substitution which is happening here *) let instantiate_typeconst subst = function | TCAbstract { atc_as_constraint = a; atc_super_constraint = s; atc_default = d } -> TCAbstract { atc_as_constraint = Option.map a ~f:(instantiate subst); atc_super_constraint = Option.map s ~f:(instantiate subst); atc_default = Option.map d ~f:(instantiate subst); } | TCConcrete { tc_type = t } -> TCConcrete { tc_type = instantiate subst t } let instantiate_typeconst_type subst tc = { tc with ttc_kind = instantiate_typeconst subst tc.ttc_kind }
OCaml Interface
hhvm/hphp/hack/src/decl/decl_instantiate.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 make_subst : 'a Typing_defs.tparam list -> Typing_defs.decl_ty list -> Decl_subst.decl_subst val instantiate : Decl_subst.decl_subst -> Typing_defs.decl_ty -> Typing_defs.decl_ty val instantiate_ce : Decl_subst.decl_subst -> Typing_defs.class_elt -> Typing_defs.class_elt val instantiate_cc : Decl_subst.decl_subst -> Typing_defs.class_const -> Typing_defs.class_const val instantiate_typeconst : Decl_subst.decl_subst -> Typing_defs.typeconst -> Typing_defs.typeconst val instantiate_typeconst_type : Decl_subst.decl_subst -> Typing_defs.typeconst_type -> Typing_defs.typeconst_type
OCaml
hhvm/hphp/hack/src/decl/decl_nast.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (*****************************************************************************) (* Module used to convert an AST into a type signature. Historically, all * decls were produced this way. Now, they are produced only by the direct decl * parser. Only lambda type signatures are produced from ASTs here. *) (*****************************************************************************) open Hh_prelude open Aast open Typing_defs module FunUtils = Decl_fun_utils module Reason = Typing_reason module SN = Naming_special_names let lambda_decl_in_env (env : Decl_env.env) (f : Nast.fun_) : Typing_defs.fun_elt = let ifc_decl = FunUtils.find_policied_attribute f.f_user_attributes in let return_disposable = FunUtils.has_return_disposable_attribute f.f_user_attributes in let ft_readonly_this = Option.is_some f.f_readonly_this in let ft_is_memoized = FunUtils.has_memoize_attribute f.f_user_attributes in let params = FunUtils.make_params env f.f_params in let (_pos, capability) = Decl_hint.aast_contexts_to_decl_capability env f.f_ctxs f.f_span in let ret_ty = FunUtils.ret_from_fun_kind env f.f_span f.f_fun_kind (hint_of_type_hint f.f_ret) in let fe_deprecated = Naming_attributes_params.deprecated ~kind:"function" (f.f_span, ";anonymous") f.f_user_attributes in let fe_php_std_lib = Naming_attributes.mem SN.UserAttributes.uaPHPStdLib f.f_user_attributes in let fe_support_dynamic_type = Naming_attributes.mem SN.UserAttributes.uaSupportDynamicType f.f_user_attributes in let fe_pos = Decl_env.make_decl_pos env @@ f.f_span in let fe_type = mk ( Reason.Rwitness_from_decl fe_pos, Tfun { ft_tparams = []; ft_where_constraints = []; ft_params = params; ft_implicit_params = { capability }; ft_ret = { et_type = ret_ty; et_enforced = Unenforced }; ft_flags = make_ft_flags f.f_fun_kind ~return_disposable ~returns_readonly:(Option.is_some f.f_readonly_ret) ~readonly_this:ft_readonly_this ~support_dynamic_type:fe_support_dynamic_type ~is_memoized:ft_is_memoized ~variadic: (List.exists f.f_params ~f:(fun p -> p.param_is_variadic)); (* TODO: handle const attribute *) ft_ifc_decl = ifc_decl; (* Lambdas cannot be cross package *) ft_cross_package = None; } ) in { fe_pos; fe_module = None; fe_internal = false; fe_type; fe_deprecated; fe_php_std_lib; fe_support_dynamic_type; fe_no_auto_dynamic = false; fe_no_auto_likes = false; }
OCaml Interface
hhvm/hphp/hack/src/decl/decl_nast.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. * *) (* TODO(jakebailey): Can/should this be done with the direct decl parser? *) val lambda_decl_in_env : Decl_env.env -> Nast.fun_ -> Typing_defs.fun_elt
OCaml
hhvm/hphp/hack/src/decl/decl_pos_utils.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Decl_defs open Shallow_decl_defs open Typing_defs (*****************************************************************************) (* Functor traversing a type, but applies a user defined function for * positions. Positions in errors (_decl_errors) are not mapped - entire * field is erased instead. This is safe because there exists a completely * different system for tracking and updating positions in errors * (see ServerTypeCheck.get_files_with_stale_errors) *) (*****************************************************************************) module TraversePos (ImplementPos : sig val pos : Pos.t -> Pos.t val pos_or_decl : Pos_or_decl.t -> Pos_or_decl.t end) = struct open Typing_reason let pos = ImplementPos.pos let pos_or_decl = ImplementPos.pos_or_decl let positioned_id : Typing_defs.pos_id -> Typing_defs.pos_id = (fun (p, x) -> (pos_or_decl p, x)) let rec reason : type ph. ph Typing_reason.t_ -> ph Typing_reason.t_ = function | Rnone -> Rnone | Rwitness p -> Rwitness (pos p) | Rwitness_from_decl p -> Rwitness_from_decl (pos_or_decl p) | Ridx (p, r) -> Ridx (pos p, reason r) | Ridx_vector p -> Ridx_vector (pos p) | Ridx_vector_from_decl p -> Ridx_vector_from_decl (pos_or_decl p) | Rforeach p -> Rforeach (pos p) | Rasyncforeach p -> Rasyncforeach (pos p) | Rarith p -> Rarith (pos p) | Rarith_ret p -> Rarith_ret (pos p) | Rcomp p -> Rcomp (pos p) | Rconcat_ret p -> Rconcat_ret (pos p) | Rlogic_ret p -> Rlogic_ret (pos p) | Rbitwise p -> Rbitwise (pos p) | Rbitwise_ret p -> Rbitwise_ret (pos p) | Rno_return p -> Rno_return (pos p) | Rno_return_async p -> Rno_return_async (pos p) | Rret_fun_kind (p, k) -> Rret_fun_kind (pos p, k) | Rret_fun_kind_from_decl (p, k) -> Rret_fun_kind_from_decl (pos_or_decl p, k) | Rhint p -> Rhint (pos_or_decl p) | Rthrow p -> Rthrow (pos p) | Rplaceholder p -> Rplaceholder (pos p) | Rret_div p -> Rret_div (pos p) | Ryield_gen p -> Ryield_gen (pos p) | Ryield_asyncgen p -> Ryield_asyncgen (pos p) | Ryield_asyncnull p -> Ryield_asyncnull (pos p) | Ryield_send p -> Ryield_send (pos p) | Rlost_info (s, r1, Blame (p2, l)) -> Rlost_info (s, reason r1, Blame (pos p2, l)) | Rformat (p1, s, r) -> Rformat (pos p1, s, reason r) | Rclass_class (p, s) -> Rclass_class (pos_or_decl p, s) | Runknown_class p -> Runknown_class (pos p) | Rvar_param p -> Rvar_param (pos p) | Rvar_param_from_decl p -> Rvar_param_from_decl (pos_or_decl p) | Runpack_param (p1, p2, i) -> Runpack_param (pos p1, pos_or_decl p2, i) | Rinout_param p -> Rinout_param (pos_or_decl p) | Rinstantiate (r1, x, r2) -> Rinstantiate (reason r1, x, reason r2) | Rtypeconst (r1, (p, s1), s2, r2) -> Rtypeconst (reason r1, (pos_or_decl p, s1), s2, reason r2) | Rtype_access (r1, ls) -> Rtype_access (reason r1, List.map ls ~f:(fun (r, s) -> (reason r, s))) | Rexpr_dep_type (r, p, n) -> Rexpr_dep_type (reason r, pos_or_decl p, n) | Rnullsafe_op p -> Rnullsafe_op (pos p) | Rtconst_no_cstr id -> Rtconst_no_cstr (positioned_id id) | Rpredicated (p, f) -> Rpredicated (pos p, f) | Ris p -> Ris (pos p) | Ras p -> Ras (pos p) | Requal p -> Requal (pos p) | Rvarray_or_darray_key p -> Rvarray_or_darray_key (pos_or_decl p) | Rvec_or_dict_key p -> Rvec_or_dict_key (pos_or_decl p) | Rusing p -> Rusing (pos p) | Rdynamic_prop p -> Rdynamic_prop (pos p) | Rdynamic_call p -> Rdynamic_call (pos p) | Rdynamic_construct p -> Rdynamic_construct (pos p) | Ridx_dict p -> Ridx_dict (pos p) | Rset_element p -> Rset_element (pos p) | Rmissing_optional_field (p, n) -> Rmissing_optional_field (pos_or_decl p, n) | Runset_field (p, n) -> Runset_field (pos p, n) | Rcontravariant_generic (r1, n) -> Rcontravariant_generic (reason r1, n) | Rinvariant_generic (r1, n) -> Rcontravariant_generic (reason r1, n) | Rregex p -> Rregex (pos p) | Rimplicit_upper_bound (p, s) -> Rimplicit_upper_bound (pos_or_decl p, s) | Rarith_ret_int p -> Rarith_ret_int (pos p) | Rarith_ret_float (p, r, s) -> Rarith_ret_float (pos p, reason r, s) | Rarith_ret_num (p, r, s) -> Rarith_ret_num (pos p, reason r, s) | Rarith_dynamic p -> Rarith_dynamic (pos p) | Rbitwise_dynamic p -> Rbitwise_dynamic (pos p) | Rincdec_dynamic p -> Rincdec_dynamic (pos p) | Rtype_variable p -> Rtype_variable (pos p) | Rtype_variable_error p -> Rtype_variable_error (pos p) | Rtype_variable_generics (p, t, s) -> Rtype_variable_generics (pos p, t, s) | Rglobal_type_variable_generics (p, t, s) -> Rglobal_type_variable_generics (pos_or_decl p, t, s) | Rsolve_fail p -> Rsolve_fail (pos_or_decl p) | Rcstr_on_generics (p, sid) -> Rcstr_on_generics (pos_or_decl p, positioned_id sid) | Rlambda_param (p, r) -> Rlambda_param (pos p, reason r) | Rshape (p, fun_name) -> Rshape (pos p, fun_name) | Rshape_literal p -> Rshape_literal (pos p) | Renforceable p -> Renforceable (pos_or_decl p) | Rdestructure p -> Rdestructure (pos p) | Rkey_value_collection_key p -> Rkey_value_collection_key (pos p) | Rglobal_class_prop p -> Rglobal_class_prop (pos_or_decl p) | Rglobal_fun_param p -> Rglobal_fun_param (pos_or_decl p) | Rglobal_fun_ret p -> Rglobal_fun_ret (pos_or_decl p) | Rsplice p -> Rsplice (pos p) | Ret_boolean p -> Ret_boolean (pos p) | Rdefault_capability p -> Rdefault_capability (pos_or_decl p) | Rconcat_operand p -> Rconcat_operand (pos p) | Rinterp_operand p -> Rinterp_operand (pos p) | Rdynamic_coercion r -> Rdynamic_coercion (reason r) | Rsupport_dynamic_type p -> Rsupport_dynamic_type (pos_or_decl p) | Rdynamic_partial_enforcement (p, cn, r) -> Rdynamic_partial_enforcement (pos_or_decl p, cn, reason r) | Rrigid_tvar_escape (p, v, w, r) -> Rrigid_tvar_escape (pos p, v, w, reason r) | Ropaque_type_from_module (p, m, r) -> Ropaque_type_from_module (pos_or_decl p, m, reason r) | Rmissing_class p -> Rmissing_class (pos p) | Rinvalid -> Rinvalid let rec ty t = let (p, x) = deref t in mk (reason p, ty_ x) and ty_ : decl_phase ty_ -> decl_phase ty_ = function | (Tany _ | Tthis | Tmixed | Twildcard | Tnonnull | Tdynamic) as x -> x | Tvec_or_dict (ty1, ty2) -> Tvec_or_dict (ty ty1, ty ty2) | Tprim _ as x -> x | Tgeneric (name, args) -> Tgeneric (name, List.map args ~f:ty) | Ttuple tyl -> Ttuple (List.map tyl ~f:ty) | Tunion tyl -> Tunion (List.map tyl ~f:ty) | Tintersection tyl -> Tintersection (List.map tyl ~f:ty) | Toption x -> Toption (ty x) | Tlike x -> Tlike (ty x) | Tfun ft -> Tfun (fun_type ft) | Tapply (sid, xl) -> Tapply (positioned_id sid, List.map xl ~f:ty) | Taccess (root_ty, id) -> Taccess (ty root_ty, positioned_id id) | Trefinement (root_ty, rs) -> let rs = Class_refinement.map ty rs in Trefinement (ty root_ty, rs) | Tshape s -> Tshape (shape_type s) | Tnewtype (name, tyl, bound) -> let tyl = List.map tyl ~f:ty in let bound = ty bound in Tnewtype (name, tyl, bound) and ty_opt x = Option.map x ~f:ty and shape_field_name = function | Typing_defs.TSFlit_int (p, s) -> Typing_defs.TSFlit_int (pos_or_decl p, s) | Typing_defs.TSFlit_str (p, s) -> Typing_defs.TSFlit_str (pos_or_decl p, s) | Typing_defs.TSFclass_const (id, s) -> Typing_defs.TSFclass_const (positioned_id id, positioned_id s) and constraint_ x = List.map ~f:(fun (ck, x) -> (ck, ty x)) x and possibly_enforced_ty et = { et with et_type = ty et.et_type } and capability = function | CapTy cap -> CapTy (ty cap) | CapDefaults p -> CapDefaults (pos_or_decl p) and fun_implicit_params implicit = { capability = capability implicit.capability } and fun_type ft = { ft with ft_tparams = List.map ~f:type_param ft.ft_tparams; ft_where_constraints = List.map ft.ft_where_constraints ~f:where_constraint; ft_params = List.map ft.ft_params ~f:fun_param; ft_implicit_params = fun_implicit_params ft.ft_implicit_params; ft_ret = possibly_enforced_ty ft.ft_ret; } and shape_type { s_origin = _; s_unknown_value = shape_kind; s_fields = fdm } = (* TODO(shapes) Should this be changing s_origin? *) { s_origin = Missing_origin; s_unknown_value = shape_kind; (* TODO(shapes) s_unknown_value is missing a call to ty *) s_fields = ShapeFieldMap.map_and_rekey fdm shape_field_name ty; } and fun_elt fe = { fe with fe_type = ty fe.fe_type; fe_pos = pos_or_decl fe.fe_pos } and where_constraint (ty1, c, ty2) = (ty ty1, c, ty ty2) and fun_param param = { param with fp_pos = pos_or_decl param.fp_pos; fp_type = possibly_enforced_ty param.fp_type; } and class_const cc = { cc_synthesized = cc.cc_synthesized; cc_abstract = cc.cc_abstract; cc_pos = pos_or_decl cc.cc_pos; cc_type = ty cc.cc_type; cc_origin = cc.cc_origin; cc_refs = cc.cc_refs; } and typeconst = function | TCAbstract { atc_as_constraint; atc_super_constraint; atc_default } -> TCAbstract { atc_as_constraint = ty_opt atc_as_constraint; atc_super_constraint = ty_opt atc_super_constraint; atc_default = ty_opt atc_default; } | TCConcrete { tc_type } -> TCConcrete { tc_type = ty tc_type } and typeconst_type tc = { ttc_synthesized = tc.ttc_synthesized; ttc_name = positioned_id tc.ttc_name; ttc_kind = typeconst tc.ttc_kind; ttc_origin = tc.ttc_origin; ttc_enforceable = Tuple.T2.map_fst ~f:pos_or_decl tc.ttc_enforceable; ttc_reifiable = Option.map tc.ttc_reifiable ~f:pos_or_decl; ttc_concretized = tc.ttc_concretized; ttc_is_ctx = tc.ttc_is_ctx; } and user_attribute { ua_name; ua_params } = { ua_name = positioned_id ua_name; ua_params } and type_param t = { tp_name = positioned_id t.tp_name; tp_variance = t.tp_variance; tp_reified = t.tp_reified; tp_tparams = List.map ~f:type_param t.tp_tparams; tp_constraints = constraint_ t.tp_constraints; tp_user_attributes = List.map ~f:user_attribute t.tp_user_attributes; } and class_type dc = { dc_final = dc.dc_final; dc_const = dc.dc_const; dc_internal = dc.dc_internal; dc_need_init = dc.dc_need_init; dc_deferred_init_members = dc.dc_deferred_init_members; dc_abstract = dc.dc_abstract; dc_kind = dc.dc_kind; dc_is_xhp = dc.dc_is_xhp; dc_has_xhp_keyword = dc.dc_has_xhp_keyword; dc_module = dc.dc_module; dc_is_module_level_trait = dc.dc_is_module_level_trait; dc_name = dc.dc_name; dc_pos = dc.dc_pos; dc_extends = dc.dc_extends; dc_sealed_whitelist = dc.dc_sealed_whitelist; dc_xhp_attr_deps = dc.dc_xhp_attr_deps; dc_xhp_enum_values = dc.dc_xhp_enum_values; dc_xhp_marked_empty = dc.dc_xhp_marked_empty; dc_req_ancestors = List.map dc.dc_req_ancestors ~f:requirement; dc_req_ancestors_extends = dc.dc_req_ancestors_extends; dc_req_class_ancestors = List.map dc.dc_req_class_ancestors ~f:requirement; dc_tparams = List.map dc.dc_tparams ~f:type_param; dc_where_constraints = List.map dc.dc_where_constraints ~f:where_constraint; dc_substs = SMap.map begin fun ({ sc_subst; _ } as sc) -> { sc with sc_subst = SMap.map ty sc_subst } end dc.dc_substs; dc_consts = SMap.map class_const dc.dc_consts; dc_typeconsts = SMap.map typeconst_type dc.dc_typeconsts; dc_props = dc.dc_props; dc_sprops = dc.dc_sprops; dc_methods = dc.dc_methods; dc_smethods = dc.dc_smethods; dc_construct = dc.dc_construct; dc_ancestors = SMap.map ty dc.dc_ancestors; dc_support_dynamic_type = dc.dc_support_dynamic_type; dc_enum_type = Option.map dc.dc_enum_type ~f:enum_type; dc_decl_errors = []; dc_docs_url = dc.dc_docs_url; } and requirement (p, t) = (pos_or_decl p, ty t) and enum_type te = { te_base = ty te.te_base; te_constraint = ty_opt te.te_constraint; te_includes = List.map te.te_includes ~f:ty; } and typedef tdef = { td_module = tdef.td_module; td_pos = pos_or_decl tdef.td_pos; td_vis = tdef.td_vis; td_tparams = List.map tdef.td_tparams ~f:type_param; td_as_constraint = ty_opt tdef.td_as_constraint; td_super_constraint = ty_opt tdef.td_super_constraint; td_type = ty tdef.td_type; td_is_ctx = tdef.td_is_ctx; td_attributes = List.map tdef.td_attributes ~f:user_attribute; td_internal = tdef.td_internal; td_docs_url = tdef.td_docs_url; } and shallow_class sc = { sc_mode = sc.sc_mode; sc_final = sc.sc_final; sc_abstract = sc.sc_abstract; sc_is_xhp = sc.sc_is_xhp; sc_internal = sc.sc_internal; sc_has_xhp_keyword = sc.sc_has_xhp_keyword; sc_kind = sc.sc_kind; sc_module = sc.sc_module; sc_name = positioned_id sc.sc_name; sc_tparams = List.map sc.sc_tparams ~f:type_param; sc_where_constraints = List.map sc.sc_where_constraints ~f:where_constraint; sc_extends = List.map sc.sc_extends ~f:ty; sc_uses = List.map sc.sc_uses ~f:ty; sc_xhp_attr_uses = List.map sc.sc_xhp_attr_uses ~f:ty; sc_xhp_enum_values = sc.sc_xhp_enum_values; sc_xhp_marked_empty = sc.sc_xhp_marked_empty; sc_req_extends = List.map sc.sc_req_extends ~f:ty; sc_req_implements = List.map sc.sc_req_implements ~f:ty; sc_req_class = List.map sc.sc_req_class ~f:ty; sc_implements = List.map sc.sc_implements ~f:ty; sc_support_dynamic_type = sc.sc_support_dynamic_type; sc_consts = List.map sc.sc_consts ~f:shallow_class_const; sc_typeconsts = List.map sc.sc_typeconsts ~f:shallow_typeconst; sc_props = List.map sc.sc_props ~f:shallow_prop; sc_sprops = List.map sc.sc_sprops ~f:shallow_prop; sc_constructor = Option.map sc.sc_constructor ~f:shallow_method; sc_static_methods = List.map sc.sc_static_methods ~f:shallow_method; sc_methods = List.map sc.sc_methods ~f:shallow_method; sc_user_attributes = List.map sc.sc_user_attributes ~f:user_attribute; sc_enum_type = Option.map sc.sc_enum_type ~f:enum_type; sc_docs_url = sc.sc_docs_url; } and shallow_class_const scc = { scc_abstract = scc.scc_abstract; scc_name = positioned_id scc.scc_name; scc_type = ty scc.scc_type; scc_refs = scc.scc_refs; } and shallow_typeconst stc = { stc_kind = typeconst stc.stc_kind; stc_name = positioned_id stc.stc_name; stc_enforceable = (pos_or_decl (fst stc.stc_enforceable), snd stc.stc_enforceable); stc_reifiable = Option.map stc.stc_reifiable ~f:pos_or_decl; stc_is_ctx = stc.stc_is_ctx; } and shallow_prop sp = { sp_name = positioned_id sp.sp_name; sp_xhp_attr = sp.sp_xhp_attr; sp_type = ty sp.sp_type; sp_visibility = sp.sp_visibility; sp_flags = sp.sp_flags; } and shallow_method sm = { sm_name = positioned_id sm.sm_name; sm_type = ty sm.sm_type; sm_visibility = sm.sm_visibility; sm_deprecated = sm.sm_deprecated; sm_flags = sm.sm_flags; sm_attributes = sm.sm_attributes; } end (*****************************************************************************) (* Returns a signature with all the positions replaced with Pos.none *) (*****************************************************************************) module NormalizeSig = TraversePos (struct let pos _ = Pos.none let pos_or_decl _ = Pos_or_decl.none end)
OCaml Interface
hhvm/hphp/hack/src/decl/decl_pos_utils.mli
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module NormalizeSig : sig val typedef : Typing_defs.typedef_type -> Typing_defs.typedef_type val fun_elt : Typing_defs.fun_elt -> Typing_defs.fun_elt val class_type : Decl_defs.decl_class_type -> Decl_defs.decl_class_type val ty : Typing_defs.decl_ty -> Typing_defs.decl_ty val shallow_class_const : Shallow_decl_defs.shallow_class_const -> Shallow_decl_defs.shallow_class_const val shallow_typeconst : Shallow_decl_defs.shallow_typeconst -> Shallow_decl_defs.shallow_typeconst val shallow_method : Shallow_decl_defs.shallow_method -> Shallow_decl_defs.shallow_method val shallow_prop : Shallow_decl_defs.shallow_prop -> Shallow_decl_defs.shallow_prop val shallow_class : Shallow_decl_defs.shallow_class -> Shallow_decl_defs.shallow_class end
OCaml
hhvm/hphp/hack/src/decl/decl_redecl_service.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. * *) (** On the fly defs-declaration are called when the user modified a file and we are not at initilalization time anymore. Therefore, we have a bit more work to do. We need to calculate what must be re-checked. *) open Hh_prelude open Reordered_argument_collections open Typing_deps type get_classes_in_file = Relative_path.t -> SSet.t type redo_type_decl_result = { fanout: Fanout.t; old_decl_missing_count: int; } let lvl = Hh_logger.Level.Debug let compute_deps_neutral = (Fanout.empty, 0) (** This is the place where we are going to put everything necessary for the redeclaration. We could "pass" the values directly to the workers, but it gives too much work to the master and slows things down, so what we do instead is pass the data through shared memory via OnTheFlyStore. I tried replicating the data to speed things up but it had no effect. *) module OnTheFlyStore = GlobalStorage.Make (struct type t = Naming_table.defs_per_file end) (** Given a set of functions, compare the old and the new decl and deduce what must be rechecked accordingly. *) let compare_funs_and_get_fanout ctx old_funs fanout_acc funs = let (fanout, old_funs_missing) = Decl_compare.get_funs_deps ~ctx old_funs funs in let fanout_acc = Fanout.union fanout fanout_acc in (fanout_acc, old_funs_missing) (** Given a set of typedefs, compare the old and the new decl and deduce what must be rechecked accordingly. *) let compare_types_and_get_fanout ctx old_types fanout_acc types = let (fanout, old_types_missing) = Decl_compare.get_types_deps ~ctx old_types types in let fanout_acc = Fanout.union fanout fanout_acc in (fanout_acc, old_types_missing) (* Given a set of global constants, compare the old and the new decl and deduce what must be rechecked accordingly. *) let compare_gconsts_and_get_fanout ctx old_gconsts fanout_acc gconsts = let (fanout, old_gconsts_missing) = Decl_compare.get_gconsts_deps ~ctx old_gconsts gconsts in let fanout_acc = Fanout.union fanout fanout_acc in (fanout_acc, old_gconsts_missing) (* Given a set of modules, compare the old and the new decl and deduce what must be rechecked accordingly. *) let compare_modules_and_get_fanout ctx old_modules fanout_acc modules = let (fanout, old_modules_missing) = Decl_compare.get_modules_deps ~ctx ~old_modules ~modules in let fanout_acc = Fanout.union fanout fanout_acc in (fanout_acc, old_modules_missing) (*****************************************************************************) (* Redeclares a list of files * And then computes the files that must be redeclared/rechecked by looking * at what changed in the signatures of the classes/functions. *) (*****************************************************************************) (** Compute decls in files. Return errors raised during decling. *) let redeclare_files ctx filel = List.iter filel ~f:(fun fn -> Decl.make_env ~sh:SharedMem.Uses ctx fn) (** Invalidate local caches and compute decls in files. Return errors raised during decling. *) let decl_files ctx filel = SharedMem.invalidate_local_caches (); redeclare_files ctx filel let compare_decls_and_get_fanout ctx defs_per_file (filel : Relative_path.t list) : Fanout.t * int = let defs_in_files = List.map filel ~f:(fun fn -> Relative_path.Map.find defs_per_file fn) in let all_defs = List.fold_left defs_in_files ~f:FileInfo.merge_names ~init:FileInfo.empty_names in let { FileInfo.n_classes = _; n_funs; n_types; n_consts; n_modules } = all_defs in let acc = Fanout.empty in (* Fetching everything at once is faster *) let (old_funs, old_types, old_consts, old_modules) = match Provider_backend.get () with | Provider_backend.Rust_provider_backend be -> let non_class_defs = FileInfo.{ all_defs with n_classes = SSet.empty } in let (_classes, old_funs, old_types, old_consts, old_modules) = Rust_provider_backend.Decl.get_old_defs be non_class_defs in (old_funs, old_types, old_consts, old_modules) | _ -> ( Decl_heap.Funs.get_old_batch n_funs, Decl_heap.Typedefs.get_old_batch n_types, Decl_heap.GConsts.get_old_batch n_consts, Decl_heap.Modules.get_old_batch n_modules ) in let (acc, old_funs_missing) = compare_funs_and_get_fanout ctx old_funs acc n_funs in let (acc, old_types_missing) = compare_types_and_get_fanout ctx old_types acc n_types in let (acc, old_gconsts_missing) = compare_gconsts_and_get_fanout ctx old_consts acc n_consts in let (acc, old_modules_missing) = compare_modules_and_get_fanout ctx old_modules acc n_modules in let old_decl_missing_count = old_funs_missing + old_types_missing + old_gconsts_missing + old_modules_missing in (acc, old_decl_missing_count) (*****************************************************************************) (* Load the environment and then redeclare *) (*****************************************************************************) (** Invalidate local caches and compute decls in files. Return the file count. *) let decl_files_job ctx filel = try (List.length filel, decl_files ctx filel) with | exn -> let e = Exception.wrap exn in Printf.printf "Error: %s\n" (Exception.get_ctor_string e); Out_channel.flush stdout; Exception.reraise e let load_defs_compare_and_get_fanout ctx _acc (filel : Relative_path.t list) : (Fanout.t * int) * int = try let defs_per_file = OnTheFlyStore.load () in let (fanout, old_decl_missing_count) = compare_decls_and_get_fanout ctx defs_per_file filel in ((fanout, List.length filel), old_decl_missing_count) with | exn -> let e = Exception.wrap exn in Printf.printf "Error: %s\n" (Exception.get_ctor_string e); Out_channel.flush stdout; Exception.reraise e (*****************************************************************************) (* Merges the results coming back from the different workers *) (*****************************************************************************) let merge_on_the_fly files_initial_count files_declared_count (count, ()) () = files_declared_count := !files_declared_count + count; ServerProgress.write_percentage ~operation:"declaring" ~done_count:!files_declared_count ~total_count:files_initial_count ~unit:"files" ~extra:None; () let merge_compute_deps files_initial_count files_computed_count ((fanout1, computed_count), old_decl_missing_count1) (fanout2, old_decl_missing_count2) = files_computed_count := !files_computed_count + computed_count; let fanout = Fanout.union fanout1 fanout2 in ServerProgress.write_percentage ~operation:"computing dependencies of" ~done_count:!files_computed_count ~total_count:files_initial_count ~unit:"files" ~extra:None; (fanout, old_decl_missing_count1 + old_decl_missing_count2) (*****************************************************************************) (* The parallel worker *) (*****************************************************************************) (** Invalidate local decl caches and recompute decls in files in parallel. Compare new and old decls and deduce the fanout. Return errors raised during decling, fanout and missing old decl count. *) let parallel_redecl_compare_and_get_fanout (ctx : Provider_context.t) (workers : MultiWorker.worker list option) (bucket_size : int) (defs_per_file : FileInfo.names Relative_path.Map.t) (fnl : Relative_path.t list) : Fanout.t * int = try OnTheFlyStore.store defs_per_file; let files_initial_count = List.length fnl in let files_declared_count = ref 0 in let t = Unix.gettimeofday () in Hh_logger.log ~lvl "Declaring on-the-fly %d files" files_initial_count; ServerProgress.write_percentage ~operation:"declaring" ~done_count:!files_declared_count ~total_count:files_initial_count ~unit:"files" ~extra:None; MultiWorker.call workers ~job:(fun () -> decl_files_job ctx) ~neutral:() ~merge:(merge_on_the_fly files_initial_count files_declared_count) ~next:(MultiWorker.next ~max_size:bucket_size workers fnl); let t = Hh_logger.log_duration ~lvl "Finished declaring on-the-fly" t in Hh_logger.log ~lvl "Computing dependencies of %d files" files_initial_count; let files_computed_count = ref 0 in ServerProgress.write_percentage ~operation:"computing dependencies of" ~done_count:!files_computed_count ~total_count:files_initial_count ~unit:"files" ~extra:None; let (fanout, old_decl_missing_count) = MultiWorker.call workers ~job:(load_defs_compare_and_get_fanout ctx) ~neutral:compute_deps_neutral ~merge:(merge_compute_deps files_initial_count files_computed_count) ~next:(MultiWorker.next ~max_size:bucket_size workers fnl) in let (_t : float) = Hh_logger.log_duration ~lvl "Finished computing dependencies" t in OnTheFlyStore.clear (); (fanout, old_decl_missing_count) with | exn -> let e = Exception.wrap exn in if SharedMem.SMTelemetry.is_heap_overflow () then Exit.exit Exit_status.Redecl_heap_overflow else Exception.reraise e (*****************************************************************************) (* Code invalidating the heap *) (*****************************************************************************) (** Oldify provided defs. This is equivalent to moving a the decls for those defs to some heap of old decls, i.e. they will only be retrievable when querying old values. For classes, it oldifies both shallow and folded classes. *) let[@warning "-21"] oldify_defs (* -21 for dune stubs *) (ctx : Provider_context.t) ({ FileInfo.n_funs; n_classes; n_types; n_consts; n_modules } as names) (elems : Decl_class_elements.t SMap.t) ~(collect_garbage : bool) : unit = match Provider_backend.get () with | Provider_backend.Rust_provider_backend be -> Rust_provider_backend.Decl.oldify_defs be names | _ -> Decl_heap.Funs.oldify_batch n_funs; Decl_class_elements.oldify_all elems; Decl_heap.Classes.oldify_batch n_classes; Shallow_classes_provider.oldify_batch ctx n_classes; Decl_heap.Typedefs.oldify_batch n_types; Decl_heap.GConsts.oldify_batch n_consts; Decl_heap.Modules.oldify_batch n_modules; if collect_garbage then SharedMem.GC.collect `gentle; () (** Remove provided defs from the heap of old decls. For classes, it removes both shallow and folded classes. *) let[@warning "-21"] remove_old_defs (* -21 for dune stubs *) (ctx : Provider_context.t) ({ FileInfo.n_funs; n_classes; n_types; n_consts; n_modules } as names) (elems : Decl_class_elements.t SMap.t) : unit = match Provider_backend.get () with | Provider_backend.Rust_provider_backend be -> Rust_provider_backend.Decl.remove_old_defs be names | _ -> Decl_heap.Funs.remove_old_batch n_funs; Decl_class_elements.remove_old_all elems; Decl_heap.Classes.remove_old_batch n_classes; Shallow_classes_provider.remove_old_batch ctx n_classes; Decl_heap.Typedefs.remove_old_batch n_types; Decl_heap.GConsts.remove_old_batch n_consts; Decl_heap.Modules.remove_old_batch n_modules; SharedMem.GC.collect `gentle; () (** Remove provided defs from the heap of current decls. For classes, it removes both shallow and folded classes. *) let[@warning "-21"] remove_defs (* -21 for dune stubs *) (ctx : Provider_context.t) ({ FileInfo.n_funs; n_classes; n_types; n_consts; n_modules } as names) (elems : Decl_class_elements.t SMap.t) ~(collect_garbage : bool) : unit = match Provider_backend.get () with | Provider_backend.Rust_provider_backend be -> Rust_provider_backend.Decl.remove_defs be names | _ -> Decl_heap.Funs.remove_batch n_funs; Decl_class_elements.remove_all elems; Decl_heap.Classes.remove_batch n_classes; Shallow_classes_provider.remove_batch ctx n_classes; Decl_heap.Typedefs.remove_batch n_types; Decl_heap.GConsts.remove_batch n_consts; Decl_heap.Modules.remove_batch n_modules; if collect_garbage then SharedMem.GC.collect `gentle; () let is_dependent_class_of_any classes (c : string) : bool = if SSet.mem classes c then true else match Decl_heap.Classes.get c with | None -> false (* it might be a dependent class, but we are only doing this * check for the purpose of invalidating things from the heap * - if it's already not there, then we don't care. *) | Some c -> let intersection_nonempty s1 s2 = SSet.exists s1 ~f:(SSet.mem s2) in SMap.exists c.Decl_defs.dc_ancestors ~f:(fun c _ -> SSet.mem classes c) || intersection_nonempty c.Decl_defs.dc_extends classes || intersection_nonempty c.Decl_defs.dc_xhp_attr_deps classes || intersection_nonempty c.Decl_defs.dc_req_ancestors_extends classes let get_maybe_dependent_classes (get_classes : Relative_path.t -> SSet.t) (classes : SSet.t) (files : Relative_path.Set.t) : string list = Relative_path.Set.fold files ~init:classes ~f:(fun x acc -> SSet.union acc @@ get_classes x) |> SSet.elements let get_dependent_classes_files (ctx : Provider_context.t) (classes : SSet.t) : Relative_path.Set.t = let mode = Provider_context.get_deps_mode ctx in let visited = VisitedSet.make () in SSet.fold classes ~init:Typing_deps.(DepSet.make ()) ~f:(fun c acc -> let source_class = Dep.make (Dep.Type c) in Typing_deps.get_extend_deps ~mode ~visited ~source_class ~acc) |> Naming_provider.get_files ctx let filter_dependent_classes (classes : SSet.t) (maybe_dependent_classes : string list) : string list = List.filter maybe_dependent_classes ~f:(is_dependent_class_of_any classes) module ClassSetStore = GlobalStorage.Make (struct type t = SSet.t end) let load_and_filter_dependent_classes (maybe_dependent_classes : string list) : string list * int = let classes = ClassSetStore.load () in ( filter_dependent_classes classes maybe_dependent_classes, List.length maybe_dependent_classes ) let merge_dependent_classes classes_initial_count classes_filtered_count (dependent_classes, filtered) acc = classes_filtered_count := !classes_filtered_count + filtered; ServerProgress.write_percentage ~operation:"filtering" ~done_count:!classes_filtered_count ~total_count:classes_initial_count ~unit:"classes" ~extra:None; dependent_classes @ acc let filter_dependent_classes_parallel (workers : MultiWorker.worker list option) ~(bucket_size : int) (classes : SSet.t) (maybe_dependent_classes : string list) : string list = if List.length maybe_dependent_classes < 10 then filter_dependent_classes classes maybe_dependent_classes else ( ClassSetStore.store classes; let classes_initial_count = List.length maybe_dependent_classes in let classes_filtered_count = ref 0 in let t = Unix.gettimeofday () in Hh_logger.log ~lvl "Filtering %d dependent classes" classes_initial_count; ServerProgress.write_percentage ~operation:"filtering" ~done_count:!classes_filtered_count ~total_count:classes_initial_count ~unit:"classes" ~extra:None; let res = MultiWorker.call workers ~job:(fun _ c -> load_and_filter_dependent_classes c) ~merge: (merge_dependent_classes classes_initial_count classes_filtered_count) ~neutral:[] ~next: (MultiWorker.next ~max_size:bucket_size workers maybe_dependent_classes) in let (_t : float) = Hh_logger.log_duration ~lvl "Finished filtering dependent classes" t in ClassSetStore.clear (); res ) let get_dependent_classes (ctx : Provider_context.t) (workers : MultiWorker.worker list option) ~(bucket_size : int) (get_classes : Relative_path.t -> SSet.t) (classes : SSet.t) : SSet.t = get_dependent_classes_files ctx classes |> get_maybe_dependent_classes get_classes classes |> filter_dependent_classes_parallel workers ~bucket_size classes |> SSet.of_list let merge_elements classes_initial_count classes_processed_count (elements, count) acc = classes_processed_count := !classes_processed_count + count; let acc = SMap.union elements acc in ServerProgress.write_percentage ~operation:"getting members of" ~done_count:!classes_processed_count ~total_count:classes_initial_count ~unit:"classes" ~extra:None; acc (** * Get the [Decl_class_elements.t]s corresponding to the classes contained in * [defs]. *) let get_elems (workers : MultiWorker.worker list option) ~(bucket_size : int) ~(old : bool) (defs : FileInfo.names) : Decl_class_elements.t SMap.t = let classes = SSet.elements defs.FileInfo.n_classes in (* Getting the members of a class requires fetching the class from the heap. * Doing this for too many classes will cause a large amount of allocations * to be performed on the master process triggering the GC and slowing down * redeclaration. Using the workers prevents this from occurring *) let classes_initial_count = List.length classes in let t = Unix.gettimeofday () in Hh_logger.log ~lvl "Getting elements of %d classes" classes_initial_count; let elements = if classes_initial_count < 10 then Decl_class_elements.get_for_classes ~old classes else let classes_processed_count = ref 0 in ServerProgress.write_percentage ~operation:"getting members of" ~done_count:!classes_processed_count ~total_count:classes_initial_count ~unit:"classes" ~extra:None; MultiWorker.call workers ~job:(fun _ c -> (Decl_class_elements.get_for_classes ~old c, List.length c)) ~merge:(merge_elements classes_initial_count classes_processed_count) ~neutral:SMap.empty ~next:(MultiWorker.next ~max_size:bucket_size workers classes) in let (_t : float) = Hh_logger.log_duration ~lvl "Finished getting elements" t in elements let invalidate_folded_classes_for_shallow_fanout ctx workers ~bucket_size ~get_classes_in_file changed_classes = let invalidated = changed_classes |> Typing_deps.add_extend_deps (Provider_context.get_deps_mode ctx) |> Shallow_class_fanout.class_names_from_deps ~ctx ~get_classes_in_file in (match Provider_backend.get () with | Provider_backend.Rust_provider_backend be -> let names = FileInfo.{ empty_names with n_classes = invalidated } in Rust_provider_backend.Decl.remove_old_defs be names; Rust_provider_backend.Decl.remove_defs be names; () | _ -> let get_elems n_classes = get_elems workers ~bucket_size FileInfo.{ empty_names with n_classes } in Decl_class_elements.remove_old_all (get_elems invalidated ~old:true); Decl_class_elements.remove_all (get_elems invalidated ~old:false); Decl_heap.Classes.remove_old_batch invalidated; Decl_heap.Classes.remove_batch invalidated; ()); SharedMem.invalidate_local_caches (); SharedMem.GC.collect `gentle; () (*****************************************************************************) (* The main entry point *) (*****************************************************************************) (** Oldify any defs in [defs] which aren't already in [previously_oldified_defs], then determines which symbols need to be re-typechecked as a result of comparing the current versions of the symbols to their old versions. *) let redo_type_decl (ctx : Provider_context.t) ~during_init (workers : MultiWorker.worker list option) ~(bucket_size : int) (get_classes : Relative_path.t -> SSet.t) ~(previously_oldified_defs : FileInfo.names) ~(defs : FileInfo.names Relative_path.Map.t) : redo_type_decl_result = Hh_logger.log "Decl_redecl_service.redo_type_decl #1"; let all_defs = Relative_path.Map.fold defs ~init:FileInfo.empty_names ~f:(fun _ -> FileInfo.merge_names) in (* Some of the definitions are already in the old heap, left there by a * previous lazy check *) let (oldified_defs, current_defs) = Decl_utils.split_defs all_defs previously_oldified_defs in (* Oldify the remaining defs along with their elements *) let get_elems = get_elems workers ~bucket_size in let current_elems = get_elems current_defs ~old:false in oldify_defs ctx current_defs current_elems ~collect_garbage:true; (* Fetch the already oldified elements too so we can remove them later *) let oldified_elems = get_elems oldified_defs ~old:true in let all_elems = SMap.union current_elems oldified_elems in let fnl = Relative_path.Map.keys defs in Hh_logger.log "Decl_redecl_service.redo_type_decl #2"; let (fanout_acc, old_decl_missing_count) = (* If there aren't enough files, let's do this ourselves ... it's faster! *) if List.length fnl < 10 then let () = decl_files ctx fnl in let (fanout, old_decl_missing_count) = compare_decls_and_get_fanout ctx defs fnl in (fanout, old_decl_missing_count) else parallel_redecl_compare_and_get_fanout ctx workers bucket_size defs fnl in Hh_logger.log "Decl_redecl_service.redo_type_decl #3"; let fanout = let fanout = Shallow_decl_compare.compute_class_fanout ctx ~during_init ~defs fnl in invalidate_folded_classes_for_shallow_fanout ctx workers ~bucket_size ~get_classes_in_file:get_classes fanout.Fanout.changed; Fanout.union fanout fanout_acc in remove_old_defs ctx all_defs all_elems; Hh_logger.log "Finished recomputing type declarations:"; Hh_logger.log " changed: %d" (DepSet.cardinal fanout.Fanout.changed); Hh_logger.log " to_recheck: %d" (DepSet.cardinal fanout.Fanout.to_recheck); { fanout; old_decl_missing_count } (** Mark all provided [defs] as old, as long as they were not previously oldified. *) let oldify_type_decl (ctx : Provider_context.t) ?(collect_garbage = true) (workers : MultiWorker.worker list option) (get_classes : Relative_path.t -> SSet.t) ~(bucket_size : int) ~(defs : FileInfo.names) : unit = let get_elems = get_elems workers ~bucket_size in let current_elems = get_elems defs ~old:false in oldify_defs ctx defs current_elems ~collect_garbage; (* Oldifying/removing classes also affects their elements * (see Decl_class_elements), which might be shared with other classes. We * need to remove all of them too to avoid dangling references *) let all_classes = defs.FileInfo.n_classes in let dependent_classes = get_dependent_classes ctx workers get_classes ~bucket_size all_classes in let dependent_classes = FileInfo. { empty_names with n_classes = SSet.diff dependent_classes all_classes } in remove_defs ctx dependent_classes SMap.empty ~collect_garbage let remove_old_defs (ctx : Provider_context.t) ~(bucket_size : int) (workers : MultiWorker.worker list option) (names : FileInfo.names) : unit = let elems = get_elems workers ~bucket_size names ~old:true in remove_old_defs ctx names elems
OCaml Interface
hhvm/hphp/hack/src/decl/decl_redecl_service.mli
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Reordered_argument_collections type get_classes_in_file = Relative_path.t -> SSet.t type redo_type_decl_result = { fanout: Fanout.t; old_decl_missing_count: int; (** The number of old decls we didn't have when calculating the redecl. *) } (** Oldify any defs in [defs] which aren't already in [previously_oldified_defs], then determines which symbols need to be re-typechecked as a result of comparing the current versions of the symbols to their old versions. *) val redo_type_decl : Provider_context.t -> during_init:bool -> MultiWorker.worker list option -> bucket_size:int -> get_classes_in_file -> previously_oldified_defs:FileInfo.names -> defs:Naming_table.defs_per_file -> redo_type_decl_result (** Mark all provided [defs] as old, as long as they were not previously oldified. All definitions in [previously_oldified_defs] are then removed from the decl heaps. Typically, there are only any [previously_oldified_defs] during two-phase redeclaration. *) val oldify_type_decl : Provider_context.t -> ?collect_garbage:bool -> MultiWorker.worker list option -> get_classes_in_file -> bucket_size:int -> defs:FileInfo.names -> unit (** Remove the given old definitions from the decl heaps. *) val remove_old_defs : Provider_context.t -> bucket_size:int -> MultiWorker.worker list option -> FileInfo.names -> unit (** Exposed for tests only! For a set of classes, return all the declared classes that share their class elements (see Decl_class_elements). Not for general use case since it doesn't use lazy decl and makes sense only in a very particular use case of invalidate_type_decl. *) val get_dependent_classes : Provider_context.t -> MultiWorker.worker list option -> bucket_size:int -> (Relative_path.t -> SSet.t) -> SSet.t -> SSet.t (** Test-only *) val remove_defs : Provider_context.t -> FileInfo.names -> Decl_class_elements.t SMap.t -> collect_garbage:bool -> unit
OCaml
hhvm/hphp/hack/src/decl/decl_requirements.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 Decl_defs open Shallow_decl_defs open Typing_defs module Inst = Decl_instantiate let make_substitution class_type class_parameters = Inst.make_subst class_type.dc_tparams class_parameters (* Accumulate requirements so that we can successfully check the bodies * of trait methods / check that classes satisfy these requirements *) let flatten_parent_class_reqs env class_cache shallow_class (req_ancestors, req_ancestors_extends) parent_ty = let (_, (parent_pos, parent_name), parent_params) = Decl_utils.unwrap_class_type parent_ty in let parent_type = Decl_env.get_class_and_add_dep ~cache:class_cache ~shmem_fallback:false ~fallback:Decl_env.no_fallback env parent_name in match parent_type with | None -> (* The class lives in PHP *) (req_ancestors, req_ancestors_extends) | Some parent_type -> let subst = make_substitution parent_type parent_params in let req_ancestors = List.rev_map_append parent_type.dc_req_ancestors req_ancestors ~f:(fun (_p, ty) -> let ty = Inst.instantiate subst ty in (parent_pos, ty)) in (match shallow_class.sc_kind with | Ast_defs.Cclass _ -> (* not necessary to accumulate req_ancestors_extends for classes -- * it's not used *) (req_ancestors, SSet.empty) | Ast_defs.Ctrait | Ast_defs.Cinterface -> let req_ancestors_extends = SSet.union parent_type.dc_req_ancestors_extends req_ancestors_extends in (req_ancestors, req_ancestors_extends) | Ast_defs.Cenum | Ast_defs.Cenum_class _ -> assert false) let declared_class_req env class_cache (requirements, req_extends) req_ty = let (_, (req_pos, req_name), _) = Decl_utils.unwrap_class_type req_ty in let req_type = Decl_env.get_class_and_add_dep ~cache:class_cache ~shmem_fallback:false ~fallback:Decl_env.no_fallback env req_name in let req_extends = SSet.add req_name req_extends in (* since the req is declared on this class, we should * emphatically *not* substitute: a require extends Foo<T> is * going to be this class's <T> *) let requirements = (req_pos, req_ty) :: requirements in match req_type with | None -> (* The class lives in PHP : error?? *) (requirements, req_extends) | Some parent_type -> (* The parent class lives in Hack *) let req_extends = SSet.union parent_type.dc_extends req_extends in let req_extends = SSet.union parent_type.dc_xhp_attr_deps req_extends in (* the req may be of an interface that has reqs of its own; the * flattened ancestry required by *those* reqs need to be added * in to, e.g., interpret accesses to protected functions inside * traits *) let req_extends = SSet.union parent_type.dc_req_ancestors_extends req_extends in (requirements, req_extends) let declared_class_req_classes required_classes req_ty = let (_, (req_pos, _), _) = Decl_utils.unwrap_class_type req_ty in (req_pos, req_ty) :: required_classes let flatten_parent_class_class_reqs env class_cache req_classes_ancestors parent_ty = let (_, (parent_pos, parent_name), parent_params) = Decl_utils.unwrap_class_type parent_ty in let parent_type = Decl_env.get_class_and_add_dep ~cache:class_cache ~shmem_fallback:false ~fallback:Decl_env.no_fallback env parent_name in match parent_type with | None -> (* The class lives in PHP *) req_classes_ancestors | Some parent_type -> let subst = make_substitution parent_type parent_params in List.rev_map_append parent_type.dc_req_class_ancestors req_classes_ancestors ~f:(fun (_p, ty) -> let ty = Inst.instantiate subst ty in (parent_pos, ty)) (* Cheap hack: we cannot do unification / subtyping in the decl phase because * the type arguments of the types that we are trying to unify may not have * been declared yet. See the test iface_require_circular.php for details. * * However, we don't want a super long req_extends list because of the perf * overhead. And while we can't do proper unification we can dedup types * that are syntactically equivalent. * * A nicer solution might be to add a phase in between type-decl and type-check * that prunes the list via proper subtyping, but that's a little more work * than I'm willing to do now. *) let naive_dedup req_extends = (* maps class names to type params *) let h = String.Table.create () in List.rev_filter_map req_extends ~f:(fun (parent_pos, ty) -> match get_node ty with | Tapply ((_, name), hl) -> let hl = List.map hl ~f:Decl_pos_utils.NormalizeSig.ty in begin try let hl' = String.Table.find_exn h name in if not (List.equal equal_decl_ty hl hl') then raise Exit else None with | Exit | Caml.Not_found | Not_found_s _ -> String.Table.set h ~key:name ~data:hl; Some (parent_pos, ty) end | _ -> Some (parent_pos, ty)) let get_class_requirements env class_cache shallow_class = let req_ancestors_extends = SSet.empty in let acc = ([], req_ancestors_extends) in let acc = List.fold_left ~f:(declared_class_req env class_cache) ~init:acc shallow_class.sc_req_extends in let acc = List.fold_left ~f:(declared_class_req env class_cache) ~init:acc shallow_class.sc_req_implements in let acc = List.fold_left ~f:(flatten_parent_class_reqs env class_cache shallow_class) ~init:acc shallow_class.sc_uses in let acc = List.fold_left ~f:(flatten_parent_class_reqs env class_cache shallow_class) ~init:acc (if Ast_defs.is_c_interface shallow_class.sc_kind then shallow_class.sc_extends else shallow_class.sc_implements) in let (req_extends, req_ancestors_extends) = acc in let req_extends = naive_dedup req_extends in let req_classes = List.fold_left ~f:declared_class_req_classes ~init:[] shallow_class.sc_req_class in let req_classes = List.fold_left ~f:(flatten_parent_class_class_reqs env class_cache) ~init:req_classes shallow_class.sc_uses in let req_classes = naive_dedup req_classes in (req_extends, req_ancestors_extends, req_classes)
OCaml Interface
hhvm/hphp/hack/src/decl/decl_requirements.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 get_class_requirements : Decl_env.env -> Decl_env.class_cache -> Shallow_decl_defs.shallow_class -> Typing_defs.requirement list * SSet.t * Typing_defs.requirement list
OCaml
hhvm/hphp/hack/src/decl/decl_service.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (*****************************************************************************) (* Module declaring the types in parallel *) (*****************************************************************************) open Hh_prelude let category = "decl_service" (*****************************************************************************) (* The job that will be run on the workers *) (*****************************************************************************) let decl_file ctx fn = Hh_logger.debug ~category "Typing decl: %s" (Relative_path.to_absolute fn); Decl.make_env ~sh:SharedMem.Uses ctx fn; Hh_logger.debug ~category "Typing decl OK"; () let decl_files ctx fnl = List.iter fnl ~f:(decl_file ctx) (*****************************************************************************) (* Let's go! That's where the action is *) (*****************************************************************************) let go (ctx : Provider_context.t) (workers : MultiWorker.worker list option) ~bucket_size defs_per_file = let defs_per_file_l = Relative_path.Map.fold defs_per_file ~init:[] ~f:(fun x _ y -> x :: y) in Hh_logger.debug ~category "Declaring the types"; let result = MultiWorker.call workers ~job:(fun () fnl -> decl_files ctx fnl) ~neutral:() ~merge:(fun () () -> ()) ~next:(MultiWorker.next ~max_size:bucket_size workers defs_per_file_l) in result
OCaml Interface
hhvm/hphp/hack/src/decl/decl_service.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. * *) (*****************************************************************************) (* Starts the process *) (*****************************************************************************) val go : Provider_context.t -> MultiWorker.worker list option -> bucket_size:int -> Naming_table.defs_per_file -> unit
OCaml
hhvm/hphp/hack/src/decl/decl_store.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 class_members = { m_properties: Typing_defs.decl_ty SMap.t; m_static_properties: Typing_defs.decl_ty SMap.t; m_methods: Typing_defs.fun_elt SMap.t; m_static_methods: Typing_defs.fun_elt SMap.t; m_constructor: Typing_defs.fun_elt option; } type class_entries = Decl_defs.decl_class_type * class_members option module ClassEltKey = Decl_heap.ClassEltKey type decl_store = { add_class: string -> Decl_defs.decl_class_type -> unit; get_class: string -> Decl_defs.decl_class_type option; add_prop: ClassEltKey.t -> Typing_defs.decl_ty -> unit; get_prop: ClassEltKey.t -> Typing_defs.decl_ty option; add_static_prop: ClassEltKey.t -> Typing_defs.decl_ty -> unit; get_static_prop: ClassEltKey.t -> Typing_defs.decl_ty option; add_method: ClassEltKey.t -> Typing_defs.fun_elt -> unit; get_method: ClassEltKey.t -> Typing_defs.fun_elt option; add_static_method: ClassEltKey.t -> Typing_defs.fun_elt -> unit; get_static_method: ClassEltKey.t -> Typing_defs.fun_elt option; add_constructor: string -> Typing_defs.fun_elt -> unit; get_constructor: string -> Typing_defs.fun_elt option; add_fun: string -> Typing_defs.fun_elt -> unit; get_fun: string -> Typing_defs.fun_elt option; add_typedef: string -> Typing_defs.typedef_type -> unit; get_typedef: string -> Typing_defs.typedef_type option; add_gconst: string -> Typing_defs.const_decl -> unit; get_gconst: string -> Typing_defs.const_decl option; add_module: string -> Typing_defs.module_def_type -> unit; get_module: string -> Typing_defs.module_def_type option; push_local_changes: unit -> unit; pop_local_changes: unit -> unit; } let push_local_changes () : unit = Decl_heap.Funs.LocalChanges.push_stack (); Decl_heap.Constructors.LocalChanges.push_stack (); Decl_heap.Props.LocalChanges.push_stack (); Decl_heap.StaticProps.LocalChanges.push_stack (); Decl_heap.Methods.LocalChanges.push_stack (); Decl_heap.StaticMethods.LocalChanges.push_stack (); Decl_heap.Classes.LocalChanges.push_stack (); Decl_heap.Typedefs.LocalChanges.push_stack (); Decl_heap.GConsts.LocalChanges.push_stack (); Decl_heap.Modules.LocalChanges.push_stack (); () let pop_local_changes () : unit = Decl_heap.Funs.LocalChanges.pop_stack (); Decl_heap.Constructors.LocalChanges.pop_stack (); Decl_heap.Props.LocalChanges.pop_stack (); Decl_heap.StaticProps.LocalChanges.pop_stack (); Decl_heap.Methods.LocalChanges.pop_stack (); Decl_heap.StaticMethods.LocalChanges.pop_stack (); Decl_heap.Classes.LocalChanges.pop_stack (); Decl_heap.Typedefs.LocalChanges.pop_stack (); Decl_heap.GConsts.LocalChanges.pop_stack (); Decl_heap.Modules.LocalChanges.pop_stack (); () let shared_memory_store = { add_prop = Decl_heap.Props.add; get_prop = Decl_heap.Props.get; add_static_prop = Decl_heap.StaticProps.add; get_static_prop = Decl_heap.StaticProps.get; add_method = Decl_heap.Methods.add; get_method = Decl_heap.Methods.get; add_static_method = Decl_heap.StaticMethods.add; get_static_method = Decl_heap.StaticMethods.get; add_constructor = Decl_heap.Constructors.add; get_constructor = Decl_heap.Constructors.get; add_class = Decl_heap.Classes.add; get_class = Decl_heap.Classes.get; add_fun = Decl_heap.Funs.add; get_fun = Decl_heap.Funs.get; add_typedef = Decl_heap.Typedefs.add; get_typedef = Decl_heap.Typedefs.get; add_gconst = Decl_heap.GConsts.add; get_gconst = Decl_heap.GConsts.get; add_module = Decl_heap.Modules.add; get_module = Decl_heap.Modules.get; push_local_changes; pop_local_changes; } let store = ref shared_memory_store let set s = store := s let get () = !store
OCaml Interface
hhvm/hphp/hack/src/decl/decl_store.mli
(* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (* Abstracts over the particular shared memory implementation used for decl information. *) type class_members = { m_properties: Typing_defs.decl_ty SMap.t; m_static_properties: Typing_defs.decl_ty SMap.t; m_methods: Typing_defs.fun_elt SMap.t; m_static_methods: Typing_defs.fun_elt SMap.t; m_constructor: Typing_defs.fun_elt option; } type class_entries = Decl_defs.decl_class_type * class_members option module ClassEltKey : SharedMem.Key with type t = string * string type decl_store = { add_class: string -> Decl_defs.decl_class_type -> unit; get_class: string -> Decl_defs.decl_class_type option; add_prop: ClassEltKey.t -> Typing_defs.decl_ty -> unit; get_prop: ClassEltKey.t -> Typing_defs.decl_ty option; add_static_prop: ClassEltKey.t -> Typing_defs.decl_ty -> unit; get_static_prop: ClassEltKey.t -> Typing_defs.decl_ty option; add_method: ClassEltKey.t -> Typing_defs.fun_elt -> unit; get_method: ClassEltKey.t -> Typing_defs.fun_elt option; add_static_method: ClassEltKey.t -> Typing_defs.fun_elt -> unit; get_static_method: ClassEltKey.t -> Typing_defs.fun_elt option; add_constructor: string -> Typing_defs.fun_elt -> unit; get_constructor: string -> Typing_defs.fun_elt option; add_fun: string -> Typing_defs.fun_elt -> unit; get_fun: string -> Typing_defs.fun_elt option; add_typedef: string -> Typing_defs.typedef_type -> unit; get_typedef: string -> Typing_defs.typedef_type option; add_gconst: string -> Typing_defs.const_decl -> unit; get_gconst: string -> Typing_defs.const_decl option; add_module: string -> Typing_defs.module_def_type -> unit; get_module: string -> Typing_defs.module_def_type option; push_local_changes: unit -> unit; pop_local_changes: unit -> unit; } val get : unit -> decl_store val set : decl_store -> unit val shared_memory_store : decl_store
OCaml
hhvm/hphp/hack/src/decl/decl_subst.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 Typing_defs module Reason = Typing_reason type decl_subst = decl_ty SMap.t (*****************************************************************************) (* Builds a substitution out of a list of type parameters and a list of types. * * Typical use-case: * class Y<T> { ... } * class X extends Y<int> * * To build the type of X, we need to replace all the occurrences of T in Y by * int. The function make_subst, builds the substitution (the map associating * types to a type parameter name), in this case, it would build the map(T => * int). *) (*****************************************************************************) let make_locl tparams tyl = (* We tolerate missing types in silent_mode. When that happens, we bind * all the parameters we can, and bind the remaining ones to "Tany". *) let make_subst_tparam (subst, tyl) t = let (ty, tyl) = match tyl with | [] -> ((Typing_defs.mk (Reason.Rnone, Typing_defs.make_tany ()) : locl_ty), []) | ty :: rl -> (ty, rl) in (SMap.add (snd t.tp_name) ty subst, tyl) in let (subst, _) = List.fold tparams ~init:(SMap.empty, tyl) ~f:make_subst_tparam in subst let make_decl tparams tyl = (* We tolerate missing types in silent_mode. When that happens, we bind * all the parameters we can, and bind the remaining ones to "Tany". *) let make_subst_tparam (subst, tyl) t = let (ty, tyl) = match tyl with | [] -> ((Typing_defs.mk (Reason.Rnone, Typing_defs.make_tany ()) : decl_ty), []) | ty :: rl -> (ty, rl) in (SMap.add (snd t.tp_name) ty subst, tyl) in let (subst, _) = List.fold tparams ~init:(SMap.empty, tyl) ~f:make_subst_tparam in subst
OCaml Interface
hhvm/hphp/hack/src/decl/decl_subst.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 decl_subst = Typing_defs.decl_ty SMap.t val make_locl : 'ty Typing_defs.tparam list -> Typing_defs.locl_ty list -> Typing_defs.locl_ty SMap.t val make_decl : 'ty Typing_defs.tparam list -> Typing_defs.decl_ty list -> decl_subst
OCaml
hhvm/hphp/hack/src/decl/decl_typedef_expand.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 Typing_defs open Utils module MakeType = Typing_make_type type cyclic_td_usage = { td_name: string; decl_pos: Pos_or_decl.t; (** Position of type alias usage that caused the cycle *) } let is_typedef ctx name = match Naming_provider.get_type_kind ctx name with | Some Naming_types.TTypedef -> true | _ -> false (** [expand_and_instantiate visited ctx name ty_argl] returns the full expansion of the type alias named [name] and performs type parameter substitution on the result using [ty_argl]. E.g. if `type A<T> = Vec<B<T>>; type B<T> = Map<int, T>`, [expand_and_instantiate ctx "A" [string]] returns `Vec<Map<int, string>>`. Parameters: - force_expand: expand regardless of typedef visibility (default: false) - visited: set of type alias names. Used to detect cycles. - r: reason to use as part of the returned decl_ty - name: name of type alias to expand - ty_argl: list of type arguments used to substitute the expanded typedef's type parameters *) let rec expand_and_instantiate ?(force_expand = false) visited ctx r name ty_argl : decl_ty * cyclic_td_usage list = let (td_tparams, expanded_type, cycles) = expand_typedef_ ~force_expand visited ctx name in let subst = Decl_instantiate.make_subst td_tparams ty_argl in (Decl_instantiate.instantiate subst (mk (r, expanded_type)), cycles) (** [expand_typedef_ visited ctx name ty_argl] returns the full expansion of the type alias named [name]. E.g. if `type A<T> = Vec<B<T>>; type B<T> = Map<int, T>`, [expand_typedef] on "A" returns `(["T"], Vec<Map<int, T>>)`. Parameters: - force_expand: expand regardless of typedef visibility (default: false) - name: name of type alias to expand - visited: set of type alias names. Used to detect cycles. Returned values: - the list of type parameters for the expanded type alias. Useful to perform substitution. - the full type alias expansion Opaque typedefs are not expanded, regardless of the current file. Detects cycles, but does not raise an error - it just stops expanding instead. *) and expand_typedef_ ?(force_expand = false) visited ctx (name : string) : decl_tparam list * decl_ty_ * cyclic_td_usage list = let td = unsafe_opt @@ Decl_provider.get_typedef ctx name in let { td_pos; td_module = _; td_vis; td_tparams; td_type; td_as_constraint; td_super_constraint = _; td_is_ctx = _; td_attributes = _; td_internal = _; td_docs_url = _; } = td in (* We don't want our visibility logic to depend on the filename of the caller, so the best we can do is determine visibility just based on td_vis. *) let should_expand = (not (SSet.mem name visited)) && (force_expand || match td_vis with | Aast.CaseType | Aast.OpaqueModule | Aast.Opaque -> false | Aast.Transparent -> true) in if should_expand then let visited = SSet.add name visited in let (ty, cycles) = expand_ visited ctx td_type in (td_tparams, get_node ty, cycles) else let tparam_to_tgeneric tparam = mk (Reason.Rhint (fst tparam.tp_name), Tgeneric (snd tparam.tp_name, [])) in let (tyl : decl_ty list) = List.map td_tparams ~f:tparam_to_tgeneric in let cstr = match td_as_constraint with | Some cstr -> cstr | None -> let r_cstr = Reason.Rimplicit_upper_bound (td_pos, "?nonnull") in MakeType.mixed r_cstr in (td_tparams, Tnewtype (name, tyl, cstr), []) (** [expand_ visited ctx ty] traverses the type tree of [ty] and recursively expands all its transparent type alias. E.g. if `type B<Tb> = Map<int, Tb>`, [expand_ visited ctx (Vec<B<Ta>>)] returns `Vec<Map<int, Ta>>`. Parameters: - ty: the type to be recursed into to find all the transparent type aliases and expand them - visited: set of type alias names; used to detect cycles So this is just a decl_ty -> decl_ty mapper where the only interesting case is Tapply. *) and expand_ visited ctx (ty : decl_ty) : decl_ty * cyclic_td_usage list = let (r, ty_) = deref ty in match ty_ with | Tapply ((_pos, name), tyl) -> if is_typedef ctx name then let (tyl, cycles1) = List.unzip @@ List.map tyl ~f:(expand_ visited ctx) in let (ty, cycles2) = expand_and_instantiate visited ctx r name tyl in (ty, List.concat cycles1 @ cycles2) else let (tyl, cycles) = List.unzip @@ List.map tyl ~f:(expand_ visited ctx) in (mk (r, Tapply ((_pos, name), tyl)), List.concat cycles) | Tthis -> failwith "should never happen" | (Tmixed | Twildcard | Tnonnull | Tdynamic | Tprim _ | Tgeneric _ | Tany _) as x -> (mk (r, x), []) | Trefinement (ty, rs) -> let (cycles, rs) = Class_refinement.fold_map (fun cycles1 ty -> let (ty, cycles2) = expand_ visited ctx ty in (cycles1 @ cycles2, ty)) [] rs in (mk (r, Trefinement (ty, rs)), cycles) | Tunion tyl -> let (tyl, cycles) = List.unzip @@ List.map tyl ~f:(expand_ visited ctx) in (mk (r, Tunion tyl), List.concat cycles) | Tintersection tyl -> let (tyl, cycles) = List.unzip @@ List.map tyl ~f:(expand_ visited ctx) in (mk (r, Tintersection tyl), List.concat cycles) | Taccess (ty, id) -> let (ty, cycles) = expand_ visited ctx ty in (mk (r, Taccess (ty, id)), cycles) | Toption ty -> let (ty, cycles) = expand_ visited ctx ty in (match get_node ty with | Toption _ as y -> (mk (r, y), cycles) | _ -> (mk (r, Toption ty), cycles)) | Tlike ty -> let (ty, err) = expand_ visited ctx ty in (mk (r, Tlike ty), err) | Ttuple tyl -> let (tyl, cycles) = List.unzip @@ List.map tyl ~f:(expand_ visited ctx) in (mk (r, Ttuple tyl), List.concat cycles) | Tshape { s_origin = _; s_unknown_value = shape_kind; s_fields = fdm } -> let (cycles, fdm) = ShapeFieldMap.map_env (fun cycles1 ty -> let (ty, cycles2) = expand_ visited ctx ty in (cycles1 @ cycles2, ty)) [] fdm in ( mk ( r, (* TODO(shapes) Should this be resetting the origin? *) Tshape { s_origin = Missing_origin; s_unknown_value = shape_kind; (* TODO(shapes) should call expand_ on s_unknown_value *) s_fields = fdm; } ), cycles ) | Tvec_or_dict (ty1, ty2) -> let (ty1, err1) = expand_ visited ctx ty1 in let (ty2, err2) = expand_ visited ctx ty2 in (mk (r, Tvec_or_dict (ty1, ty2)), err1 @ err2) | Tfun ft -> let tparams = ft.ft_tparams in let (params, cycles1) = List.unzip @@ List.map ft.ft_params ~f:(fun param -> let (ty, cycles) = expand_possibly_enforced_ty visited ctx param.fp_type in ({ param with fp_type = ty }, cycles)) in let (ret, cycles2) = expand_possibly_enforced_ty visited ctx ft.ft_ret in let (tparams, cycles3) = List.unzip @@ List.map tparams ~f:(fun t -> let (constraints, cycles) = List.unzip @@ List.map t.tp_constraints ~f:(fun (ck, ty) -> let (ty, cycles) = expand_ visited ctx ty in ((ck, ty), cycles)) in ({ t with tp_constraints = constraints }, List.concat cycles)) in let (where_constraints, cycles4) = List.unzip @@ List.map ft.ft_where_constraints ~f:(fun (ty1, ck, ty2) -> let (ty1, cycles1) = expand_ visited ctx ty1 in let (ty2, cycles2) = expand_ visited ctx ty2 in ((ty1, ck, ty2), cycles1 @ cycles2)) in ( mk ( r, Tfun { ft with ft_params = params; ft_ret = ret; ft_tparams = tparams; ft_where_constraints = where_constraints; } ), List.concat (cycles1 @ cycles3 @ cycles4) @ cycles2 ) | Tnewtype (name, tyl, ty) -> let (tyl, cycles1) = List.unzip @@ List.map tyl ~f:(expand_ visited ctx) in let (ty, cycles2) = expand_ visited ctx ty in (mk (r, Tnewtype (name, tyl, ty)), List.concat cycles1 @ cycles2) and expand_possibly_enforced_ty visited ctx et : decl_ty possibly_enforced_ty * cyclic_td_usage list = let (ty, cycles) = expand_ visited ctx et.et_type in ({ et_type = ty; et_enforced = et.et_enforced }, cycles) let expand_typedef ?(force_expand = false) ctx r name ty_argl = let visited = SSet.empty in let (ty, _) = expand_and_instantiate ~force_expand visited ctx r name ty_argl in ty let expand_typedef_with_error ?(force_expand = false) ctx r name = let visited = SSet.empty in let (_, expanded_type, cycles) = expand_typedef_ ~force_expand visited ctx name in (mk (r, expanded_type), cycles)
OCaml Interface
hhvm/hphp/hack/src/decl/decl_typedef_expand.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type cyclic_td_usage = { td_name: string; decl_pos: Pos_or_decl.t; (** Position of type alias usage that caused the cycle *) } (** [expand_typedef ctx name ty_argl] returns the full expansion of the type alias named [name]. E.g. if `type A<T> = Vec<B<T>>; type B<T> = Map<int, T>`, [expand_typedef ctx r "A" [string]] returns `Vec<Map<int, string>>`. Parameters: - force_expand: expand regardless of typedef visibility (default: false) - reason: reason to use as part of the returned decl_ty - name: name of type alias to expand - ty_argl: list of type arguments used to substitute the expanded typedef's type parameters All transparent aliases in the expansion are expanded recursively, and type parameter substitution is performed. Opaque typedefs are not expanded, regardless of the current file. Detects cycles, but does not raise an error - it just stops expanding instead. *) val expand_typedef : ?force_expand:bool -> Provider_context.t -> Typing_defs_core.decl_phase Typing_reason.t_ -> string -> Typing_defs.decl_ty list -> Typing_defs.decl_ty (** [expand_typedef ctx name ty_argl] returns the full expansion of the type alias named [name], and the list of cyclic usages in the definition of that typedef. E.g. if `type A<T> = Vec<B<T>>; type B<T> = Map<int, T>`, [expand_typedef ctx r "A"] returns `Vec<Map<int, string>>, []`. Parameters: - force_expand: expand regardless of typedef visibility (default: false) - reason: reason to use as part of the returned decl_ty - name: name of type alias to expand All transparent aliases in the expansion are expanded recursively, and type parameter substitution is performed. Opaque typedefs are not expanded, regardless of the current file. *) val expand_typedef_with_error : ?force_expand:bool -> Provider_context.t -> Typing_defs_core.decl_phase Typing_reason.t_ -> string -> Typing_defs.decl_ty * cyclic_td_usage list
OCaml
hhvm/hphp/hack/src/decl/decl_utils.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Reordered_argument_collections open Aast open Typing_defs module SN = Naming_special_names let unwrap_class_hint = function | (_, Happly ((pos, class_name), type_parameters)) -> ((pos, class_name, type_parameters), None) | (p, Habstr _) -> let err = Typing_error.( primary @@ Primary.Expected_class { suffix = Some (lazy " or interface but got a generic"); pos = p }) in ((Pos.none, "", []), Some err) | (p, _) -> let err = Typing_error.( primary @@ Primary.Expected_class { suffix = Some (lazy " or interface"); pos = p }) in ((Pos.none, "", []), Some err) let unwrap_class_type ty = match deref ty with | (r, Tapply (name, tparaml)) -> (r, name, tparaml) | (r, Tgeneric _) -> let p = Typing_reason.to_pos r in (r, (p, ""), []) | (r, _) -> let p = Typing_reason.to_pos r in (r, (p, ""), []) (** Given sets A and B return a tuple (AnB, A\B), i.e split A into the part that is common with B, and which is unique to A *) let split_sets defs split_if_in_defs = SSet.partition (SSet.mem split_if_in_defs) defs (** Given name sets A and B return a tuple (AnB, A\B), i.e split A into the part that is common with B, and which is unique to A *) let split_defs defs split_if_in_defs = FileInfo.( let (n_funs1, n_funs2) = split_sets defs.n_funs split_if_in_defs.n_funs in let (n_classes1, n_classes2) = split_sets defs.n_classes split_if_in_defs.n_classes in let (n_types1, n_types2) = split_sets defs.n_types split_if_in_defs.n_types in let (n_consts1, n_consts2) = split_sets defs.n_consts split_if_in_defs.n_consts in let (n_modules1, n_modules2) = split_sets defs.n_modules split_if_in_defs.n_modules in let r1 = { n_funs = n_funs1; n_classes = n_classes1; n_types = n_types1; n_consts = n_consts1; n_modules = n_modules1; } in let r2 = { n_funs = n_funs2; n_classes = n_classes2; n_types = n_types2; n_consts = n_consts2; n_modules = n_modules2; } in (r1, r2)) let infer_const expr_ = match expr_ with | Aast.String _ -> Some Tstring | True | False -> Some Tbool | Int _ -> Some Tint | Float _ -> Some Tfloat | Null -> Some Tnull | Unop ((Ast_defs.Uminus | Ast_defs.Uplus), (_, _, Int _)) -> Some Tint | Unop ((Ast_defs.Uminus | Ast_defs.Uplus), (_, _, Float _)) -> Some Tfloat | _ -> (* We can't infer the type of everything here. Notably, if you * define a const in terms of another const, we need an annotation, * since the other const may not have been declared yet. * * Also note that a number of expressions are considered invalid * as constant initializers, even if we can infer their type; see * Naming.check_constant_expr. *) None let coalesce_consistent parent current = (* If the parent's constructor is consistent via <<__ConsistentConstruct>>, then * we want to carry this forward even if the child is final. Example: * * <<__ConsistentConstruct>> * class C { * public static function f(): void { * new static(); * } * } * final class D<reify T> extends C {} * * Even though D's consistency locally comes from the fact that D was * declared as a final class, calling [new static()] via [D::f] will cause * a runtime exception because D has reified generics. *) match parent with | Inconsistent -> current | ConsistentConstruct -> parent (* This case is unreachable in a correct program, because parent would have to be a final class *) | FinalClass -> parent let consistent_construct_kind cls : consistent_kind = Shallow_decl_defs.( if cls.sc_final then FinalClass else let consistent_attr_present = Attributes.mem SN.UserAttributes.uaConsistentConstruct cls.sc_user_attributes in if consistent_attr_present then ConsistentConstruct else Inconsistent)
OCaml
hhvm/hphp/hack/src/decl/direct_decl_parser.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 (* NB: Must keep in sync with Rust type oxidized_by_ref::direct_decl_parser::Decls *) type decls = (string * Shallow_decl_defs.decl) list [@@deriving show] (* NB: Must keep in sync with Rust type oxidized_by_ref::direct_decl_parser::ParsedFile *) type parsed_file = { pf_mode: FileInfo.mode option; pf_file_attributes: Typing_defs.user_attribute list; pf_decls: decls; pf_has_first_pass_parse_errors: bool; } (* NB: Must keep in sync with ToOcamlRep impl of Rust type rust_decl_ffi::OcamlParsedFileWithHashes *) type parsed_file_with_hashes = { pfh_mode: FileInfo.mode option; pfh_hash: Int64.t; pfh_decls: (string * Shallow_decl_defs.decl * Int64.t) list; } external parse_decls : DeclParserOptions.t -> Relative_path.t -> string -> parsed_file = "hh_parse_decls_ffi" external parse_and_hash_decls : DeclParserOptions.t -> bool -> Relative_path.t -> string -> parsed_file_with_hashes = "hh_parse_and_hash_decls_ffi" external decls_hash : decls -> Int64.t = "decls_hash" (* NB: Must be manually kept in sync with Rust function `hackrs_provider_backend::FileInfo::from::<ParsedFileWithHashes>` *) let decls_to_fileinfo fn (parsed_file : parsed_file_with_hashes) = let file_mode = parsed_file.pfh_mode in let hash = Some parsed_file.pfh_hash in List.fold parsed_file.pfh_decls ~init:FileInfo.{ empty_t with hash; file_mode; comments = None } ~f:(fun acc (name, decl, hash) -> let pos p = FileInfo.Full (Pos_or_decl.fill_in_filename fn p) in match decl with | Shallow_decl_defs.Class c -> let info = (pos (fst c.Shallow_decl_defs.sc_name), name, Some hash) in FileInfo.{ acc with classes = info :: acc.classes } | Shallow_decl_defs.Fun f -> let info = (pos f.Typing_defs.fe_pos, name, Some hash) in FileInfo.{ acc with funs = info :: acc.funs } | Shallow_decl_defs.Typedef tf -> let info = (pos tf.Typing_defs.td_pos, name, Some hash) in FileInfo.{ acc with typedefs = info :: acc.typedefs } | Shallow_decl_defs.Const c -> let info = (pos c.Typing_defs.cd_pos, name, Some hash) in FileInfo.{ acc with consts = info :: acc.consts } | Shallow_decl_defs.Module m -> let info = (pos m.Typing_defs.mdt_pos, name, Some hash) in FileInfo.{ acc with modules = info :: acc.modules }) let decls_to_addenda (parsed_file : parsed_file_with_hashes) : SearchTypes.si_addendum list = (* NB: Must be manually kept in sync with Rust function `si_addenum::get_si_addenda` *) List.filter_map parsed_file.pfh_decls ~f:(fun (name, decl, _hash) -> let sia_name = Utils.strip_ns name in let sia_kind = match decl with | Shallow_decl_defs.(Class { sc_kind = Ast_defs.Cclass _; _ }) -> Some SearchTypes.SI_Class | Shallow_decl_defs.(Class { sc_kind = Ast_defs.Cinterface; _ }) -> Some SearchTypes.SI_Interface | Shallow_decl_defs.(Class { sc_kind = Ast_defs.Ctrait; _ }) -> Some SearchTypes.SI_Trait | Shallow_decl_defs.( Class { sc_kind = Ast_defs.(Cenum | Cenum_class _); _ }) -> Some SearchTypes.SI_Enum | Shallow_decl_defs.Fun _ -> Some SearchTypes.SI_Function | Shallow_decl_defs.Typedef _ -> Some SearchTypes.SI_Typedef | Shallow_decl_defs.Const _ -> Some SearchTypes.SI_GlobalConstant | Shallow_decl_defs.Module _ -> None in let (sia_is_abstract, sia_is_final) = match decl with | Shallow_decl_defs.Class c -> (c.Shallow_decl_defs.sc_abstract, c.Shallow_decl_defs.sc_final) | _ -> (false, false) in match sia_kind with | None -> None | Some sia_kind -> Some { SearchTypes.sia_name; sia_kind; sia_is_abstract; sia_is_final })
OCaml Interface
hhvm/hphp/hack/src/decl/direct_decl_parser.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 decls = (string * Shallow_decl_defs.decl) list [@@deriving show] type parsed_file = { pf_mode: FileInfo.mode option; pf_file_attributes: Typing_defs.user_attribute list; pf_decls: decls; pf_has_first_pass_parse_errors: bool; } type parsed_file_with_hashes = { pfh_mode: FileInfo.mode option; pfh_hash: Int64.t; pfh_decls: (string * Shallow_decl_defs.decl * Int64.t) list; } (** NOTE: this doesn't respect deregister_php_lib, and has decls in reverse lexical order. *) val parse_decls : DeclParserOptions.t -> Relative_path.t -> string -> parsed_file (** NOTE: this doesn't respect deregister_php_lib, and has decls in reverse lexical order *) val parse_and_hash_decls : DeclParserOptions.t -> bool -> Relative_path.t -> string -> parsed_file_with_hashes val decls_hash : decls -> Int64.t (** NOTE: this takes input in reverse-lexical-order, and emits FileInfo.t in forward lexical order *) val decls_to_fileinfo : Relative_path.t -> parsed_file_with_hashes -> FileInfo.t val decls_to_addenda : parsed_file_with_hashes -> SearchTypes.si_addendum list
OCaml
hhvm/hphp/hack/src/decl/direct_decl_service.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude let parse (ctx : Provider_context.t) ~(trace : bool) ~(cache_decls : bool) (acc : FileInfo.t Relative_path.Map.t) (fn : Relative_path.t) : FileInfo.t Relative_path.Map.t = if not (FindUtils.path_filter fn) then acc else let start_parse_time = Unix.gettimeofday () in match if cache_decls then Direct_decl_utils.direct_decl_parse_and_cache ctx fn else Direct_decl_utils.direct_decl_parse ctx fn with | None -> acc | Some parsed_file -> let end_parse_time = Unix.gettimeofday () in let fileinfo = Direct_decl_utils.decls_to_fileinfo fn parsed_file in if trace then Hh_logger.log "[%.1fms] %s - %s" ((end_parse_time -. start_parse_time) *. 1000.0) (Relative_path.suffix fn) (FileInfo.to_string fileinfo); Relative_path.Map.add acc ~key:fn ~data:fileinfo let go (ctx : Provider_context.t) ~(trace : bool) ~(cache_decls : bool) ?(worker_call : MultiWorker.call_wrapper = MultiWorker.wrapper) (workers : MultiWorker.worker list option) ~(ide_files : Relative_path.Set.t) ~(get_next : Relative_path.t list MultiWorker.Hh_bucket.next) : FileInfo.t Relative_path.Map.t = let acc = worker_call.MultiWorker.f workers ~job:(fun init -> List.fold ~init ~f:(parse ctx ~trace ~cache_decls)) ~neutral:Relative_path.Map.empty ~merge:Relative_path.Map.union ~next:get_next in Relative_path.Set.fold ide_files ~init:acc ~f:(fun fn acc -> parse ctx ~trace ~cache_decls acc fn)
OCaml Interface
hhvm/hphp/hack/src/decl/direct_decl_service.mli
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val go : Provider_context.t -> trace:bool -> cache_decls:bool -> ?worker_call:MultiWorker.call_wrapper -> MultiWorker.worker list option -> (* IDE files are processed sequentially (in the master process), to match the behavior of the legacy Parsing_service. *) ide_files:Relative_path.Set.t -> (* Buckets the files which will be processed in parallel *) get_next:Relative_path.t list MultiWorker.Hh_bucket.next -> FileInfo.t Relative_path.Map.t
Rust
hhvm/hphp/hack/src/decl/direct_decl_smart_constructors.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. mod direct_decl_smart_constructors_generated; use std::collections::BTreeMap; use std::rc::Rc; use arena_collections::AssocListMut; use arena_collections::List; use arena_collections::MultiSetMut; use bstr::BStr; use bumpalo::collections as bump; use bumpalo::Bump; use flatten_smart_constructors::FlattenSmartConstructors; use hash::HashSet; use hh_autoimport_rust as hh_autoimport; use namespaces::ElaborateKind; use namespaces_rust as namespaces; use naming_special_names_rust as naming_special_names; use oxidized::decl_parser_options::DeclParserOptions; use oxidized_by_ref::aast; use oxidized_by_ref::ast_defs::Abstraction; use oxidized_by_ref::ast_defs::Bop; use oxidized_by_ref::ast_defs::ClassishKind; use oxidized_by_ref::ast_defs::ConstraintKind; use oxidized_by_ref::ast_defs::FunKind; use oxidized_by_ref::ast_defs::Id; use oxidized_by_ref::ast_defs::Id_; use oxidized_by_ref::ast_defs::ShapeFieldName; use oxidized_by_ref::ast_defs::Uop; use oxidized_by_ref::ast_defs::Variance; use oxidized_by_ref::ast_defs::XhpEnumValue; use oxidized_by_ref::direct_decl_parser::Decls; use oxidized_by_ref::file_info::Mode; use oxidized_by_ref::method_flags::MethodFlags; use oxidized_by_ref::namespace_env::Env as NamespaceEnv; use oxidized_by_ref::nast; use oxidized_by_ref::pos::Pos; use oxidized_by_ref::prop_flags::PropFlags; use oxidized_by_ref::relative_path::RelativePath; use oxidized_by_ref::s_map::SMap; use oxidized_by_ref::shallow_decl_defs; use oxidized_by_ref::shallow_decl_defs::Decl; use oxidized_by_ref::shallow_decl_defs::ShallowClassConst; use oxidized_by_ref::shallow_decl_defs::ShallowMethod; use oxidized_by_ref::shallow_decl_defs::ShallowProp; use oxidized_by_ref::shallow_decl_defs::ShallowTypeconst; use oxidized_by_ref::shape_map::ShapeField; use oxidized_by_ref::t_shape_map::TShapeField; use oxidized_by_ref::typing_defs; use oxidized_by_ref::typing_defs::AbstractTypeconst; use oxidized_by_ref::typing_defs::Capability::*; use oxidized_by_ref::typing_defs::ClassConstKind; use oxidized_by_ref::typing_defs::ClassRefinement; use oxidized_by_ref::typing_defs::ConcreteTypeconst; use oxidized_by_ref::typing_defs::ConstDecl; use oxidized_by_ref::typing_defs::Enforcement; use oxidized_by_ref::typing_defs::EnumType; use oxidized_by_ref::typing_defs::FunElt; use oxidized_by_ref::typing_defs::FunImplicitParams; use oxidized_by_ref::typing_defs::FunParam; use oxidized_by_ref::typing_defs::FunParams; use oxidized_by_ref::typing_defs::FunType; use oxidized_by_ref::typing_defs::IfcFunDecl; use oxidized_by_ref::typing_defs::ParamMode; use oxidized_by_ref::typing_defs::PosByteString; use oxidized_by_ref::typing_defs::PosId; use oxidized_by_ref::typing_defs::PosString; use oxidized_by_ref::typing_defs::PossiblyEnforcedTy; use oxidized_by_ref::typing_defs::RefinedConst; use oxidized_by_ref::typing_defs::RefinedConstBound; use oxidized_by_ref::typing_defs::RefinedConstBounds; use oxidized_by_ref::typing_defs::ShapeFieldType; use oxidized_by_ref::typing_defs::ShapeType; use oxidized_by_ref::typing_defs::TaccessType; use oxidized_by_ref::typing_defs::Tparam; use oxidized_by_ref::typing_defs::TshapeFieldName; use oxidized_by_ref::typing_defs::Ty; use oxidized_by_ref::typing_defs::Ty_; use oxidized_by_ref::typing_defs::TypeOrigin; use oxidized_by_ref::typing_defs::Typeconst; use oxidized_by_ref::typing_defs::TypedefType; use oxidized_by_ref::typing_defs::WhereConstraint; use oxidized_by_ref::typing_defs_flags::FunParamFlags; use oxidized_by_ref::typing_defs_flags::FunTypeFlags; use oxidized_by_ref::typing_reason::Reason; use oxidized_by_ref::xhp_attribute; use parser_core_types::compact_token::CompactToken; use parser_core_types::indexed_source_text::IndexedSourceText; use parser_core_types::source_text::SourceText; use parser_core_types::syntax_kind::SyntaxKind; use parser_core_types::token_factory::SimpleTokenFactoryImpl; use parser_core_types::token_kind::TokenKind; type SK = SyntaxKind; type SSet<'a> = arena_collections::SortedSet<'a, &'a str>; #[derive(Clone)] pub struct DirectDeclSmartConstructors<'a, 'o, 't, S: SourceTextAllocator<'t, 'a>> { state: Rc<Impl<'a, 'o, 't, S>>, pub token_factory: SimpleTokenFactoryImpl<CompactToken>, previous_token_kind: TokenKind, } impl<'a, 'o, 't, S: SourceTextAllocator<'t, 'a>> std::ops::Deref for DirectDeclSmartConstructors<'a, 'o, 't, S> { type Target = Impl<'a, 'o, 't, S>; fn deref(&self) -> &Self::Target { &self.state } } #[derive(Clone)] pub struct Impl<'a, 'o, 't, S: SourceTextAllocator<'t, 'a>> { pub source_text: IndexedSourceText<'t>, pub arena: &'a bumpalo::Bump, pub decls: Decls<'a>, pub file_attributes: List<'a, &'a typing_defs::UserAttribute<'a>>, // const_refs will accumulate all scope-resolution-expressions it // encounters while it's "Some" const_refs: Option<HashSet<typing_defs::ClassConstRef<'a>>>, opts: &'o DeclParserOptions, filename: &'a RelativePath<'a>, file_mode: Mode, namespace_builder: Rc<NamespaceBuilder<'a>>, classish_name_builder: Option<ClassishNameBuilder<'a>>, type_parameters: Rc<Vec<SSet<'a>>>, under_no_auto_dynamic: bool, under_no_auto_likes: bool, inside_no_auto_dynamic_class: bool, source_text_allocator: S, module: Option<Id<'a>>, } impl<'a, 'o, 't, S: SourceTextAllocator<'t, 'a>> DirectDeclSmartConstructors<'a, 'o, 't, S> { pub fn new( opts: &'o DeclParserOptions, src: &SourceText<'t>, file_mode: Mode, arena: &'a Bump, source_text_allocator: S, elaborate_xhp_namespaces_for_facts: bool, ) -> Self { let source_text = IndexedSourceText::new(src.clone()); let path = source_text.source_text().file_path(); let prefix = path.prefix(); let path = bump::String::from_str_in(path.path_str(), arena).into_bump_str(); let filename = RelativePath::make(prefix, path); Self { state: Rc::new(Impl { source_text, arena, filename: arena.alloc(filename), file_mode, decls: Decls::empty(), file_attributes: List::empty(), const_refs: None, namespace_builder: Rc::new(NamespaceBuilder::new_in( &opts.auto_namespace_map, opts.disable_xhp_element_mangling, elaborate_xhp_namespaces_for_facts, arena, )), opts, classish_name_builder: None, type_parameters: Rc::new(Vec::new()), source_text_allocator, under_no_auto_dynamic: false, under_no_auto_likes: false, inside_no_auto_dynamic_class: false, module: None, }), token_factory: SimpleTokenFactoryImpl::new(), // EndOfFile is used here as a None value (signifying "beginning of // file") to save space. There is no legitimate circumstance where // we would parse a token and the previous token kind would be // EndOfFile. previous_token_kind: TokenKind::EndOfFile, } } fn qualified_name_from_parts(&self, parts: &'a [Node<'a>], pos: &'a Pos<'a>) -> Id<'a> { // Count the length of the qualified name, so that we can allocate // exactly the right amount of space for it in our arena. let mut len = 0; for part in parts { match part { Node::Name(&(name, _)) => len += name.len(), Node::Token(t) if t.kind() == TokenKind::Backslash => len += 1, Node::ListItem(&(Node::Name(&(name, _)), _backslash)) => len += name.len() + 1, Node::ListItem(&(Node::Token(t), _backslash)) if t.kind() == TokenKind::Namespace => { len += t.width() + 1; } _ => {} } } // If there's no internal trivia, then we can just reference the // qualified name in the original source text instead of copying it. let source_len = pos.end_offset() - pos.start_offset(); if source_len == len { let qualified_name: &'a str = self.str_from_utf8(self.source_text_at_pos(pos)); return Id(pos, qualified_name); } // Allocate `len` bytes and fill them with the fully qualified name. let mut qualified_name = bump::String::with_capacity_in(len, self.arena); for part in parts { match part { Node::Name(&(name, _pos)) => qualified_name.push_str(name), Node::Token(t) if t.kind() == TokenKind::Backslash => qualified_name.push('\\'), &Node::ListItem(&(Node::Name(&(name, _)), _backslash)) => { qualified_name.push_str(name); qualified_name.push_str("\\"); } &Node::ListItem(&(Node::Token(t), _backslash)) if t.kind() == TokenKind::Namespace => { qualified_name.push_str("namespace\\"); } _ => {} } } debug_assert_eq!(len, qualified_name.len()); debug_assert_eq!(len, qualified_name.capacity()); Id(pos, qualified_name.into_bump_str()) } fn module_name_string_from_parts(&self, parts: &'a [Node<'a>], pos: &'a Pos<'a>) -> &'a str { // Count the length of the qualified name, so that we can allocate // exactly the right amount of space for it in our arena. let mut len = 0; for part in parts { match part { Node::Name(&(name, _)) => len += name.len(), Node::ListItem(&(Node::Name(&(name, _)), _dot)) => len += name.len() + 1, _ => {} } } // If there's no internal trivia, then we can just reference the // qualified name in the original source text instead of copying it. let source_len = pos.end_offset() - pos.start_offset(); if source_len == len { return self.str_from_utf8(self.source_text_at_pos(pos)); } // Allocate `len` bytes and fill them with the fully qualified name. let mut qualified_name = bump::String::with_capacity_in(len, self.arena); for part in parts { match part { Node::Name(&(name, _pos)) => qualified_name.push_str(name), &Node::ListItem(&(Node::Name(&(name, _)), _)) => { qualified_name.push_str(name); qualified_name.push_str("."); } _ => {} } } debug_assert_eq!(len, qualified_name.len()); debug_assert_eq!(len, qualified_name.capacity()); qualified_name.into_bump_str() } fn module_reference_from_parts( &self, module_name: &'a str, parts: &'a [Node<'a>], ) -> shallow_decl_defs::ModuleReference<'a> { let mut s = bump::String::new_in(self.arena); for part in parts.iter() { match part { Node::ListItem(&(item, _)) => { if !s.is_empty() { s += "."; } match item { Node::Name(&(n, _)) => { if n == "self" { s += module_name; } else { s += n; } } _ => {} } } Node::Token(t) => match t.kind() { TokenKind::Global => { return shallow_decl_defs::ModuleReference::MRGlobal; } TokenKind::Star => { return shallow_decl_defs::ModuleReference::MRPrefix(s.into_bump_str()); } _ => {} }, Node::Name(&(n, _)) => { if !s.is_empty() { s += "."; } s += n; } _ => {} } } shallow_decl_defs::ModuleReference::MRExact(s.into_bump_str()) } /// If the given node is an identifier, XHP name, or qualified name, /// elaborate it in the current namespace and return Some. To be used for /// the name of a decl in its definition (e.g., "C" in `class C {}` or "f" /// in `function f() {}`). fn elaborate_defined_id(&self, name: Node<'a>) -> Option<Id<'a>> { let id = match name { Node::Name(&(name, pos)) => Id(pos, name), Node::XhpName(&(name, pos)) => Id(pos, name), Node::QualifiedName(&(parts, pos)) => self.qualified_name_from_parts(parts, pos), // This is always an error; e.g. using a reserved word where a name // is expected. Node::Token(t) | Node::IgnoredToken(t) => { let pos = self.token_pos(t); let text = self.str_from_utf8(self.source_text_at_pos(pos)); Id(pos, text) } _ => return None, }; Some(self.namespace_builder.elaborate_defined_id(id)) } /// If the given node is a name (i.e., an identifier or a qualified name), /// return Some. No namespace elaboration is performed. fn expect_name(&self, name: Node<'a>) -> Option<Id<'a>> { // If it's a simple identifier, return it. if let id @ Some(_) = name.as_id() { return id; } match name { Node::QualifiedName(&(parts, pos)) => Some(self.qualified_name_from_parts(parts, pos)), // The IgnoredToken case is always an error; e.g. using a reserved // word where a name is expected. The Token case is not an error if // the token is TokenKind::XHP (which is legal to use as a name), // but an error otherwise (since we expect a Name or QualifiedName // here, and the Name case would have been handled in `as_id` // above). Node::Token(t) | Node::IgnoredToken(t) => { let pos = self.token_pos(t); let text = self.str_from_utf8(self.source_text_at_pos(pos)); Some(Id(pos, text)) } _ => None, } } /// Fully qualify the given identifier as a type name (with consideration /// to `use` statements in scope). fn elaborate_id(&self, id: Id<'a>) -> Id<'a> { let Id(pos, name) = id; Id(pos, self.elaborate_raw_id(name)) } /// Fully qualify the given identifier as a type name (with consideration /// to `use` statements in scope). fn elaborate_raw_id(&self, id: &'a str) -> &'a str { self.namespace_builder .elaborate_raw_id(ElaborateKind::Class, id) } /// Fully qualify the given identifier as a constant name (with /// consideration to `use` statements in scope). fn elaborate_const_id(&self, id: Id<'a>) -> Id<'a> { let Id(pos, name) = id; Id( pos, self.namespace_builder .elaborate_raw_id(ElaborateKind::Const, name), ) } fn start_accumulating_const_refs(&mut self) { let this = Rc::make_mut(&mut self.state); this.const_refs = Some(Default::default()); } fn accumulate_const_ref(&mut self, class_id: &'a aast::ClassId<'_, (), ()>, value_id: &Id<'a>) { let this = Rc::make_mut(&mut self.state); // The decl for a class constant stores a list of all the scope-resolution expressions // it contains. For example "const C=A::X" stores A::X, and "const D=self::Y" stores self::Y. // (This is so we can detect cross-type circularity in constant initializers). // TODO: Hack is the wrong place to detect circularity (because we can never do // it completely soundly, and because it's a cross-body problem). The right place // to do it is in a linter. All this should be removed from here and put into a linter. if let Some(const_refs) = &mut this.const_refs { match class_id.2 { nast::ClassId_::CI(sid) => { const_refs.insert(typing_defs::ClassConstRef( typing_defs::ClassConstFrom::From(sid.1), value_id.1, )); } nast::ClassId_::CIself => { const_refs.insert(typing_defs::ClassConstRef( typing_defs::ClassConstFrom::Self_, value_id.1, )); } nast::ClassId_::CIparent | nast::ClassId_::CIstatic | nast::ClassId_::CIexpr(_) => { // Not allowed } } } } fn stop_accumulating_const_refs(&mut self) -> &'a [typing_defs::ClassConstRef<'a>] { let this = Rc::make_mut(&mut self.state); match this.const_refs.take() { Some(const_refs) => { let mut elements: bump::Vec<'_, typing_defs::ClassConstRef<'_>> = bumpalo::collections::Vec::with_capacity_in(const_refs.len(), self.arena); elements.extend(const_refs.into_iter()); elements.sort_unstable(); elements.into_bump_slice() } None => &[], } } } pub trait SourceTextAllocator<'s, 'd>: Clone { fn alloc(&self, text: &'s str) -> &'d str; } #[derive(Clone)] pub struct NoSourceTextAllocator; impl<'t> SourceTextAllocator<'t, 't> for NoSourceTextAllocator { #[inline] fn alloc(&self, text: &'t str) -> &'t str { text } } #[derive(Clone)] pub struct ArenaSourceTextAllocator<'a>(pub &'a bumpalo::Bump); impl<'t, 'a> SourceTextAllocator<'t, 'a> for ArenaSourceTextAllocator<'a> { #[inline] fn alloc(&self, text: &'t str) -> &'a str { self.0.alloc_str(text) } } fn prefix_slash<'a>(arena: &'a Bump, name: &str) -> &'a str { let mut s = bump::String::with_capacity_in(1 + name.len(), arena); s.push('\\'); s.push_str(name); s.into_bump_str() } fn prefix_colon<'a>(arena: &'a Bump, name: &str) -> &'a str { let mut s = bump::String::with_capacity_in(1 + name.len(), arena); s.push(':'); s.push_str(name); s.into_bump_str() } fn concat<'a>(arena: &'a Bump, str1: &str, str2: &str) -> &'a str { let mut result = bump::String::with_capacity_in(str1.len() + str2.len(), arena); result.push_str(str1); result.push_str(str2); result.into_bump_str() } fn strip_dollar_prefix<'a>(name: &'a str) -> &'a str { name.trim_start_matches('$') } fn is_no_auto_attribute(name: &str) -> bool { name == "__NoAutoDynamic" || name == "__NoAutoLikes" } const TANY_: Ty_<'_> = Ty_::Tany(oxidized_by_ref::tany_sentinel::TanySentinel); const TANY: &Ty<'_> = &Ty(Reason::none(), TANY_); const NO_POS: &Pos<'_> = Pos::none(); fn default_ifc_fun_decl<'a>() -> IfcFunDecl<'a> { IfcFunDecl::FDPolicied(Some("PUBLIC")) } #[derive(Debug)] struct Modifiers { is_static: bool, visibility: aast::Visibility, is_abstract: bool, is_final: bool, is_readonly: bool, } fn read_member_modifiers<'a: 'b, 'b>(modifiers: impl Iterator<Item = &'b Node<'a>>) -> Modifiers { let mut ret = Modifiers { is_static: false, visibility: aast::Visibility::Public, is_abstract: false, is_final: false, is_readonly: false, }; for modifier in modifiers { if let Some(vis) = modifier.as_visibility() { ret.visibility = vis; } match modifier.token_kind() { Some(TokenKind::Static) => ret.is_static = true, Some(TokenKind::Abstract) => ret.is_abstract = true, Some(TokenKind::Final) => ret.is_final = true, Some(TokenKind::Readonly) => ret.is_readonly = true, _ => {} } } ret } #[derive(Clone, Debug)] struct NamespaceBuilder<'a> { arena: &'a Bump, stack: Vec<NamespaceEnv<'a>>, elaborate_xhp_namespaces_for_facts: bool, } impl<'a> NamespaceBuilder<'a> { fn new_in( auto_ns_map: &[(String, String)], disable_xhp_element_mangling: bool, elaborate_xhp_namespaces_for_facts: bool, arena: &'a Bump, ) -> Self { // Copy auto_namespace_map entries into the arena so decls can use them. let auto_ns_map = arena.alloc_slice_fill_iter( auto_ns_map .iter() .map(|(n, v)| (arena.alloc_str(n) as &str, arena.alloc_str(v) as &str)), ); let mut ns_uses = SMap::empty(); for &alias in hh_autoimport::NAMESPACES { ns_uses = ns_uses.add(arena, alias, concat(arena, "HH\\", alias)); } for (alias, ns) in auto_ns_map.iter() { ns_uses = ns_uses.add(arena, alias, ns); } let mut class_uses = SMap::empty(); for &alias in hh_autoimport::TYPES { class_uses = class_uses.add(arena, alias, concat(arena, "HH\\", alias)); } Self { arena, stack: vec![NamespaceEnv { ns_uses, class_uses, fun_uses: SMap::empty(), const_uses: SMap::empty(), name: None, is_codegen: false, disable_xhp_element_mangling, }], elaborate_xhp_namespaces_for_facts, } } fn push_namespace(&mut self, name: Option<&str>) { let current = self.current_namespace(); let nsenv = self.stack.last().unwrap().clone(); // shallow clone if let Some(name) = name { let mut fully_qualified = match current { None => bump::String::with_capacity_in(name.len(), self.arena), Some(current) => { let mut fully_qualified = bump::String::with_capacity_in(current.len() + name.len() + 1, self.arena); fully_qualified.push_str(current); fully_qualified.push('\\'); fully_qualified } }; fully_qualified.push_str(name); self.stack.push(NamespaceEnv { name: Some(fully_qualified.into_bump_str()), ..nsenv }); } else { self.stack.push(NamespaceEnv { name: current, ..nsenv }); } } fn pop_namespace(&mut self) { // We'll never push a namespace for a declaration of items in the global // namespace (e.g., `namespace { ... }`), so only pop if we are in some // namespace other than the global one. if self.stack.len() > 1 { self.stack.pop().unwrap(); } } // push_namespace(Y) + pop_namespace() + push_namespace(X) should be equivalent to // push_namespace(Y) + push_namespace(X) + pop_previous_namespace() fn pop_previous_namespace(&mut self) { if self.stack.len() > 2 { let last = self.stack.pop().unwrap().name.unwrap_or("\\"); let previous = self.stack.pop().unwrap().name.unwrap_or("\\"); assert!(last.starts_with(previous)); let name = &last[previous.len() + 1..last.len()]; self.push_namespace(Some(name)); } } fn current_namespace(&self) -> Option<&'a str> { self.stack.last().and_then(|nsenv| nsenv.name) } fn add_import(&mut self, kind: NamespaceUseKind, name: &'a str, aliased_name: Option<&'a str>) { let stack_top = &mut self .stack .last_mut() .expect("Attempted to get the current import map, but namespace stack was empty"); let aliased_name = aliased_name.unwrap_or_else(|| { name.rsplit_terminator('\\') .next() .expect("Expected at least one entry in import name") }); let name = name.trim_end_matches('\\'); let name = if name.starts_with('\\') { name } else { prefix_slash(self.arena, name) }; match kind { NamespaceUseKind::Type => { stack_top.class_uses = stack_top.class_uses.add(self.arena, aliased_name, name); } NamespaceUseKind::Namespace => { stack_top.ns_uses = stack_top.ns_uses.add(self.arena, aliased_name, name); } NamespaceUseKind::Mixed => { stack_top.class_uses = stack_top.class_uses.add(self.arena, aliased_name, name); stack_top.ns_uses = stack_top.ns_uses.add(self.arena, aliased_name, name); } } } fn elaborate_raw_id(&self, kind: ElaborateKind, name: &'a str) -> &'a str { if name.starts_with('\\') { return name; } let env = self.stack.last().unwrap(); namespaces::elaborate_raw_id_in( self.arena, env, kind, name, self.elaborate_xhp_namespaces_for_facts, ) } fn elaborate_defined_id(&self, id: Id<'a>) -> Id<'a> { let Id(pos, name) = id; let env = self.stack.last().unwrap(); let name = if env.disable_xhp_element_mangling && name.contains(':') { let xhp_name_opt = namespaces::elaborate_xhp_namespace(name); let name = xhp_name_opt.map_or(name, |s| self.arena.alloc_str(&s)); if !name.starts_with('\\') { namespaces::elaborate_into_current_ns_in(self.arena, env, name) } else if self.elaborate_xhp_namespaces_for_facts { // allow :foo:bar to be elaborated into \currentnamespace\foo\bar namespaces::elaborate_into_current_ns_in(self.arena, env, &name[1..]) } else { name } } else { namespaces::elaborate_into_current_ns_in(self.arena, env, name) }; Id(pos, name) } } /// We saw a classish keyword token followed by a Name, so we make it /// available as the name of the containing class declaration. #[derive(Clone, Debug)] struct ClassishNameBuilder<'a> { name: &'a str, pos: &'a Pos<'a>, token_kind: TokenKind, } #[derive(Debug)] pub struct FunParamDecl<'a> { attributes: Node<'a>, visibility: Node<'a>, kind: ParamMode, readonly: bool, hint: Node<'a>, pos: &'a Pos<'a>, name: Option<&'a str>, variadic: bool, initializer: Node<'a>, } #[derive(Debug)] pub struct FunctionHeader<'a> { name: Node<'a>, modifiers: Node<'a>, type_params: Node<'a>, param_list: Node<'a>, capability: Node<'a>, ret_hint: Node<'a>, readonly_return: Node<'a>, where_constraints: Node<'a>, } #[derive(Debug)] pub struct RequireClause<'a> { require_type: Node<'a>, name: Node<'a>, } #[derive(Debug)] pub struct TypeParameterDecl<'a> { name: Node<'a>, reified: aast::ReifyKind, variance: Variance, constraints: &'a [(ConstraintKind, Node<'a>)], tparam_params: &'a [&'a Tparam<'a>], user_attributes: &'a [&'a UserAttributeNode<'a>], } #[derive(Debug)] pub struct ClosureTypeHint<'a> { #[allow(dead_code)] args: Node<'a>, #[allow(dead_code)] ret_hint: Node<'a>, } #[derive(Debug)] pub struct NamespaceUseClause<'a> { kind: NamespaceUseKind, id: Id<'a>, as_: Option<&'a str>, } #[derive(Copy, Clone, Debug)] enum NamespaceUseKind { Type, Namespace, Mixed, } #[derive(Debug)] pub struct ConstructorNode<'a> { method: &'a ShallowMethod<'a>, properties: &'a [ShallowProp<'a>], } #[derive(Debug)] pub struct MethodNode<'a> { method: &'a ShallowMethod<'a>, is_static: bool, } #[derive(Debug)] pub struct PropertyNode<'a> { decls: &'a [ShallowProp<'a>], is_static: bool, } #[derive(Debug)] pub struct XhpClassAttributeDeclarationNode<'a> { xhp_attr_enum_values: &'a [(&'a str, &'a [XhpEnumValue<'a>])], xhp_attr_decls: &'a [ShallowProp<'a>], xhp_attr_uses_decls: &'a [Node<'a>], } #[derive(Debug)] pub struct XhpClassAttributeNode<'a> { name: Id<'a>, tag: Option<xhp_attribute::Tag>, needs_init: bool, nullable: bool, hint: Node<'a>, } #[derive(Debug)] pub struct ShapeFieldNode<'a> { name: &'a ShapeField<'a>, type_: &'a ShapeFieldType<'a>, } #[derive(Copy, Clone, Debug)] enum AttributeParam<'a> { Classname(Id<'a>), EnumClassLabel(&'a Id_<'a>), String(&'a Pos<'a>, &'a BStr), Int(&'a Id_<'a>), } #[derive(Debug)] pub struct UserAttributeNode<'a> { name: Id<'a>, params: &'a [AttributeParam<'a>], /// This is only used for __Deprecated attribute message and CIPP parameters string_literal_param: Option<(&'a Pos<'a>, &'a BStr)>, } mod fixed_width_token { use parser_core_types::token_kind::TokenKind; #[derive(Copy, Clone)] pub struct FixedWidthToken(u64); // { offset: u56, kind: TokenKind } const KIND_BITS: u8 = 8; const KIND_MASK: u64 = u8::MAX as u64; const MAX_OFFSET: u64 = !(KIND_MASK << (64 - KIND_BITS)); impl FixedWidthToken { pub fn new(kind: TokenKind, offset: usize) -> Self { // We don't want to spend bits tracking the width of fixed-width // tokens. Since we don't track width, verify that this token kind // is in fact a fixed-width kind. debug_assert!(kind.fixed_width().is_some()); let offset: u64 = offset.try_into().unwrap(); if offset > MAX_OFFSET { panic!("FixedWidthToken: offset too large: {}", offset); } Self(offset << KIND_BITS | kind as u8 as u64) } pub fn offset(self) -> usize { (self.0 >> KIND_BITS).try_into().unwrap() } pub fn kind(self) -> TokenKind { TokenKind::try_from_u8(self.0 as u8).unwrap() } pub fn width(self) -> usize { self.kind().fixed_width().unwrap().get() } } impl std::fmt::Debug for FixedWidthToken { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fmt.debug_struct("FixedWidthToken") .field("kind", &self.kind()) .field("offset", &self.offset()) .finish() } } } use fixed_width_token::FixedWidthToken; #[derive(Copy, Clone, Debug)] pub enum XhpChildrenKind { Empty, Other, } #[derive(Copy, Clone, Debug)] pub enum Node<'a> { // Nodes which are not useful in constructing a decl are ignored. We keep // track of the SyntaxKind for two reasons. // // One is that the parser needs to know the SyntaxKind of a parsed node in // some circumstances (this information is exposed to the parser via an // implementation of `smart_constructors::NodeType`). An adapter called // WithKind exists to provide a `NodeType` implementation for arbitrary // nodes by pairing each node with a SyntaxKind, but in the direct decl // parser, we want to avoid the extra 8 bytes of overhead on each node. // // The second reason is that debugging is difficult when nodes are silently // ignored, and providing at least the SyntaxKind of an ignored node helps // in tracking down the reason it was ignored. Ignored(SyntaxKind), // For tokens with a fixed width (like `using`), we also keep its offset in // the source text, so that we can reference the text of the token if it's // (erroneously) used as an identifier (e.g., `function using() {}`). IgnoredToken(FixedWidthToken), List(&'a &'a [Node<'a>]), BracketedList(&'a (&'a Pos<'a>, &'a [Node<'a>], &'a Pos<'a>)), Name(&'a (&'a str, &'a Pos<'a>)), XhpName(&'a (&'a str, &'a Pos<'a>)), Variable(&'a (&'a str, &'a Pos<'a>)), QualifiedName(&'a (&'a [Node<'a>], &'a Pos<'a>)), ModuleName(&'a (&'a [Node<'a>], &'a Pos<'a>)), StringLiteral(&'a (&'a BStr, &'a Pos<'a>)), // For shape keys and const expressions. IntLiteral(&'a (&'a str, &'a Pos<'a>)), // For const expressions. FloatingLiteral(&'a (&'a str, &'a Pos<'a>)), // For const expressions. BooleanLiteral(&'a (&'a str, &'a Pos<'a>)), // For const expressions. Ty(&'a Ty<'a>), XhpEnumTy(&'a (Option<&'a Pos<'a>>, &'a Ty<'a>, &'a [XhpEnumValue<'a>])), ListItem(&'a (Node<'a>, Node<'a>)), // For the "X=1" in enums "enum E {X=1}" and enum-classes "enum class C {int X=1}", // and also for consts via make_const_declaration Const(&'a ShallowClassConst<'a>), // Stores (X,1,refs) for "X=1" in top-level "const int X=1" and // class-const "public const int X=1". ConstInitializer(&'a (Node<'a>, Node<'a>, &'a [typing_defs::ClassConstRef<'a>])), FunParam(&'a FunParamDecl<'a>), Attribute(&'a UserAttributeNode<'a>), FunctionHeader(&'a FunctionHeader<'a>), Constructor(&'a ConstructorNode<'a>), Method(&'a MethodNode<'a>), Property(&'a PropertyNode<'a>), EnumUse(&'a Node<'a>), TraitUse(&'a Node<'a>), XhpClassAttributeDeclaration(&'a XhpClassAttributeDeclarationNode<'a>), XhpClassAttribute(&'a XhpClassAttributeNode<'a>), XhpAttributeUse(&'a Node<'a>), XhpChildrenDeclaration(XhpChildrenKind), TypeConstant(&'a ShallowTypeconst<'a>), ContextConstraint(&'a (ConstraintKind, Node<'a>)), RequireClause(&'a RequireClause<'a>), ClassishBody(&'a &'a [Node<'a>]), TypeParameter(&'a TypeParameterDecl<'a>), TypeConstraint(&'a (ConstraintKind, Node<'a>)), ShapeFieldSpecifier(&'a ShapeFieldNode<'a>), NamespaceUseClause(&'a NamespaceUseClause<'a>), Expr(&'a nast::Expr<'a>), TypeParameters(&'a &'a [&'a Tparam<'a>]), WhereConstraint(&'a WhereConstraint<'a>), RefinedConst(&'a (&'a str, RefinedConst<'a>)), EnumClassLabel(&'a str), // Non-ignored, fixed-width tokens (e.g., keywords, operators, braces, etc.). Token(FixedWidthToken), } impl<'a> smart_constructors::NodeType for Node<'a> { type Output = Node<'a>; fn extract(self) -> Self::Output { self } fn is_abstract(&self) -> bool { self.is_token(TokenKind::Abstract) || self.is_ignored_token_with_kind(TokenKind::Abstract) } fn is_name(&self) -> bool { matches!(self, Node::Name(..)) || self.is_ignored_token_with_kind(TokenKind::Name) } fn is_qualified_name(&self) -> bool { matches!(self, Node::QualifiedName(..)) || matches!(self, Node::Ignored(SK::QualifiedName)) } fn is_prefix_unary_expression(&self) -> bool { matches!(self, Node::Expr(aast::Expr(_, _, aast::Expr_::Unop(..)))) || matches!(self, Node::Ignored(SK::PrefixUnaryExpression)) } fn is_scope_resolution_expression(&self) -> bool { matches!( self, Node::Expr(aast::Expr(_, _, aast::Expr_::ClassConst(..))) ) || matches!(self, Node::Ignored(SK::ScopeResolutionExpression)) } fn is_missing(&self) -> bool { matches!(self, Node::Ignored(SK::Missing)) } fn is_variable_expression(&self) -> bool { matches!(self, Node::Ignored(SK::VariableExpression)) } fn is_subscript_expression(&self) -> bool { matches!(self, Node::Ignored(SK::SubscriptExpression)) } fn is_member_selection_expression(&self) -> bool { matches!(self, Node::Ignored(SK::MemberSelectionExpression)) } fn is_object_creation_expression(&self) -> bool { matches!(self, Node::Ignored(SK::ObjectCreationExpression)) } fn is_safe_member_selection_expression(&self) -> bool { matches!(self, Node::Ignored(SK::SafeMemberSelectionExpression)) } fn is_function_call_expression(&self) -> bool { matches!(self, Node::Ignored(SK::FunctionCallExpression)) } fn is_list_expression(&self) -> bool { matches!(self, Node::Ignored(SK::ListExpression)) } } impl<'a> Node<'a> { fn is_token(self, kind: TokenKind) -> bool { self.token_kind() == Some(kind) } fn token_kind(self) -> Option<TokenKind> { match self { Node::Token(token) => Some(token.kind()), _ => None, } } fn is_ignored_token_with_kind(self, kind: TokenKind) -> bool { match self { Node::IgnoredToken(token) => token.kind() == kind, _ => false, } } fn as_slice(self, b: &'a Bump) -> &'a [Self] { match self { Node::List(&items) | Node::BracketedList(&(_, items, _)) => items, n if n.is_ignored() => &[], n => std::slice::from_ref(b.alloc(n)), } } fn iter<'b>(&'b self) -> NodeIterHelper<'a, 'b> where 'a: 'b, { match self { &Node::List(&items) | Node::BracketedList(&(_, items, _)) => { NodeIterHelper::Vec(items.iter()) } n if n.is_ignored() => NodeIterHelper::Empty, n => NodeIterHelper::Single(n), } } // The number of elements which would be yielded by `self.iter()`. // Must return the upper bound returned by NodeIterHelper::size_hint. fn len(&self) -> usize { match self { &Node::List(&items) | Node::BracketedList(&(_, items, _)) => items.len(), n if n.is_ignored() => 0, _ => 1, } } fn as_visibility(&self) -> Option<aast::Visibility> { match self.token_kind() { Some(TokenKind::Private) => Some(aast::Visibility::Private), Some(TokenKind::Protected) => Some(aast::Visibility::Protected), Some(TokenKind::Public) => Some(aast::Visibility::Public), Some(TokenKind::Internal) => Some(aast::Visibility::Internal), _ => None, } } // If this node is a simple unqualified identifier, return its position and text. fn as_id(&self) -> Option<Id<'a>> { match self { Node::Name(&(name, pos)) | Node::XhpName(&(name, pos)) => Some(Id(pos, name)), _ => None, } } // If this node is a Variable token, return its position and text. // As an attempt at error recovery (when the dollar sign is omitted), also // return other unqualified identifiers (i.e., the Name token kind). fn as_variable(&self) -> Option<Id<'a>> { match self { Node::Variable(&(name, pos)) | Node::Name(&(name, pos)) => Some(Id(pos, name)), _ => None, } } fn is_ignored(&self) -> bool { matches!(self, Node::Ignored(..) | Node::IgnoredToken(..)) } fn is_present(&self) -> bool { !self.is_ignored() } fn contains_marker_attribute(&self, name: &str) -> bool { self.iter().any(|node| match node { Node::Attribute(&UserAttributeNode { name: Id(_pos, attr_name), params: [], string_literal_param: None, }) => attr_name == name, _ => false, }) } } #[derive(Debug)] struct Attributes<'a> { deprecated: Option<&'a str>, reifiable: Option<&'a Pos<'a>>, late_init: bool, const_: bool, lsb: bool, memoize: bool, memoizelsb: bool, override_: bool, enforceable: Option<&'a Pos<'a>>, accept_disposable: bool, dynamically_callable: bool, returns_disposable: bool, php_std_lib: bool, ifc_attribute: IfcFunDecl<'a>, external: bool, can_call: bool, soft: bool, support_dynamic_type: bool, no_auto_likes: bool, safe_global_variable: bool, cross_package: Option<&'a str>, } impl<'a, 'o, 't, S: SourceTextAllocator<'t, 'a>> Impl<'a, 'o, 't, S> { fn add_class(&mut self, name: &'a str, decl: &'a shallow_decl_defs::ShallowClass<'a>) { self.under_no_auto_dynamic = false; self.under_no_auto_likes = false; self.inside_no_auto_dynamic_class = false; self.decls.add(name, Decl::Class(decl), self.arena); } fn add_fun(&mut self, name: &'a str, decl: &'a typing_defs::FunElt<'a>) { self.under_no_auto_dynamic = false; self.under_no_auto_likes = false; self.decls.add(name, Decl::Fun(decl), self.arena); } fn add_typedef(&mut self, name: &'a str, decl: &'a typing_defs::TypedefType<'a>) { self.under_no_auto_dynamic = false; self.under_no_auto_likes = false; self.decls.add(name, Decl::Typedef(decl), self.arena); } fn add_const(&mut self, name: &'a str, decl: &'a typing_defs::ConstDecl<'a>) { self.under_no_auto_dynamic = false; self.under_no_auto_likes = false; self.decls.add(name, Decl::Const(decl), self.arena); } fn add_module(&mut self, name: &'a str, decl: &'a typing_defs::ModuleDefType<'a>) { self.under_no_auto_dynamic = false; self.under_no_auto_likes = false; self.decls.add(name, Decl::Module(decl), self.arena) } #[inline(always)] pub fn alloc<T>(&self, val: T) -> &'a T { self.arena.alloc(val) } fn slice<T>(&self, iter: impl Iterator<Item = T>) -> &'a [T] { let mut result = match iter.size_hint().1 { Some(upper_bound) => bump::Vec::with_capacity_in(upper_bound, self.arena), None => bump::Vec::new_in(self.arena), }; for item in iter { result.push(item); } result.into_bump_slice() } fn user_attribute_to_decl( &self, attr: &UserAttributeNode<'a>, ) -> &'a shallow_decl_defs::UserAttribute<'a> { use shallow_decl_defs::UserAttributeParam as UAP; self.alloc(shallow_decl_defs::UserAttribute { name: attr.name.into(), params: self.slice(attr.params.iter().map(|p| match p { AttributeParam::Classname(cls) => UAP::Classname(cls.1), AttributeParam::EnumClassLabel(lbl) => UAP::EnumClassLabel(lbl), AttributeParam::String(_, s) => UAP::String(s), AttributeParam::Int(i) => UAP::Int(i), })), }) } fn get_current_classish_name(&self) -> Option<(&'a str, &'a Pos<'a>)> { let builder = self.classish_name_builder.as_ref()?; Some((builder.name, builder.pos)) } fn in_interface(&self) -> bool { matches!( self.classish_name_builder.as_ref(), Some(ClassishNameBuilder { token_kind: TokenKind::Interface, .. }) ) } fn lexed_name_after_classish_keyword( &mut self, arena: &'a Bump, name: &'a str, pos: &'a Pos<'a>, token_kind: TokenKind, ) { if self.classish_name_builder.is_none() { let name = if name.starts_with(':') { prefix_slash(arena, name) } else { name }; self.classish_name_builder = Some(ClassishNameBuilder { name, pos, token_kind, }); } } } impl<'a, 'o, 't, S: SourceTextAllocator<'t, 'a>> DirectDeclSmartConstructors<'a, 'o, 't, S> { #[inline] fn concat(&self, str1: &str, str2: &str) -> &'a str { concat(self.arena, str1, str2) } fn token_bytes(&self, token: &CompactToken) -> &'t [u8] { self.source_text .source_text() .sub(token.start_offset(), token.width()) } // Check that the slice is valid UTF-8. If it is, return a &str referencing // the same data. Otherwise, copy the slice into our arena using // String::from_utf8_lossy_in, and return a reference to the arena str. fn str_from_utf8(&self, slice: &'t [u8]) -> &'a str { if let Ok(s) = std::str::from_utf8(slice) { self.source_text_allocator.alloc(s) } else { bump::String::from_utf8_lossy_in(slice, self.arena).into_bump_str() } } // Check that the slice is valid UTF-8. If it is, return a &str referencing // the same data. Otherwise, copy the slice into our arena using // String::from_utf8_lossy_in, and return a reference to the arena str. fn str_from_utf8_for_bytes_in_arena(&self, slice: &'a [u8]) -> &'a str { if let Ok(s) = std::str::from_utf8(slice) { s } else { bump::String::from_utf8_lossy_in(slice, self.arena).into_bump_str() } } fn merge( &self, pos1: impl Into<Option<&'a Pos<'a>>>, pos2: impl Into<Option<&'a Pos<'a>>>, ) -> &'a Pos<'a> { match (pos1.into(), pos2.into()) { (None, None) => NO_POS, (Some(pos), None) | (None, Some(pos)) => pos, (Some(pos1), Some(pos2)) => match (pos1.is_none(), pos2.is_none()) { (true, true) => NO_POS, (true, false) => pos2, (false, true) => pos1, (false, false) => Pos::merge_without_checking_filename(self.arena, pos1, pos2), }, } } fn merge_positions(&self, node1: Node<'a>, node2: Node<'a>) -> &'a Pos<'a> { self.merge(self.get_pos(node1), self.get_pos(node2)) } fn pos_from_slice(&self, nodes: &[Node<'a>]) -> &'a Pos<'a> { nodes .iter() .fold(NO_POS, |acc, &node| self.merge(acc, self.get_pos(node))) } fn get_pos(&self, node: Node<'a>) -> &'a Pos<'a> { self.get_pos_opt(node).unwrap_or(NO_POS) } fn get_pos_opt(&self, node: Node<'a>) -> Option<&'a Pos<'a>> { let pos = match node { Node::Name(&(_, pos)) | Node::Variable(&(_, pos)) => pos, Node::Ty(ty) => return ty.get_pos(), Node::XhpName(&(_, pos)) => pos, Node::QualifiedName(&(_, pos)) => pos, Node::ModuleName(&(_, pos)) => pos, Node::IntLiteral(&(_, pos)) | Node::FloatingLiteral(&(_, pos)) | Node::StringLiteral(&(_, pos)) | Node::BooleanLiteral(&(_, pos)) => pos, Node::ListItem(&(fst, snd)) => self.merge_positions(fst, snd), Node::List(items) => self.pos_from_slice(items), Node::BracketedList(&(first_pos, inner_list, second_pos)) => self.merge( first_pos, self.merge(self.pos_from_slice(inner_list), second_pos), ), Node::Expr(&aast::Expr(_, pos, _)) => pos, Node::Token(token) => self.token_pos(token), _ => return None, }; if pos.is_none() { None } else { Some(pos) } } fn token_pos(&self, token: FixedWidthToken) -> &'a Pos<'a> { let start = token.offset(); let end = start + token.width(); let start = self.source_text.offset_to_file_pos_triple(start); let end = self.source_text.offset_to_file_pos_triple(end); Pos::from_lnum_bol_offset(self.arena, self.filename, start, end) } fn node_to_expr(&self, node: Node<'a>) -> Option<&'a nast::Expr<'a>> { let expr_ = match node { Node::Expr(expr) => return Some(expr), Node::IntLiteral(&(s, _)) => aast::Expr_::Int(s), Node::FloatingLiteral(&(s, _)) => aast::Expr_::Float(s), Node::StringLiteral(&(s, _)) => aast::Expr_::String(s), Node::BooleanLiteral((s, _)) => { if s.eq_ignore_ascii_case("true") { aast::Expr_::True } else { aast::Expr_::False } } Node::Token(t) if t.kind() == TokenKind::NullLiteral => aast::Expr_::Null, Node::Name(..) | Node::QualifiedName(..) => { aast::Expr_::Id(self.alloc(self.elaborate_const_id(self.expect_name(node)?))) } _ => return None, }; let pos = self.get_pos(node); Some(self.alloc(aast::Expr((), pos, expr_))) } fn node_to_non_ret_ty(&self, node: Node<'a>) -> Option<&'a Ty<'a>> { self.node_to_ty_(node, false) } fn node_to_ty(&self, node: Node<'a>) -> Option<&'a Ty<'a>> { self.node_to_ty_(node, true) } fn make_supportdyn(&self, pos: &'a Pos<'a>, ty: Ty_<'a>) -> Ty_<'a> { Ty_::Tapply(self.alloc(( (pos, naming_special_names::typehints::HH_SUPPORTDYN), self.alloc([self.alloc(Ty(self.alloc(Reason::witness_from_decl(pos)), ty))]), ))) } fn implicit_sdt(&self) -> bool { self.opts.everything_sdt && !self.under_no_auto_dynamic } fn no_auto_likes(&self) -> bool { self.under_no_auto_likes } fn node_to_ty_(&self, node: Node<'a>, allow_non_ret_ty: bool) -> Option<&'a Ty<'a>> { match node { Node::Ty(Ty(reason, Ty_::Tprim(aast::Tprim::Tvoid))) if !allow_non_ret_ty => { Some(self.alloc(Ty(reason, Ty_::Tprim(self.alloc(aast::Tprim::Tnull))))) } Node::Ty(Ty(reason, Ty_::Tprim(aast::Tprim::Tnoreturn))) if !allow_non_ret_ty => { Some(self.alloc(Ty(reason, Ty_::Tunion(&[])))) } Node::Ty(ty) => Some(ty), Node::Expr(expr) => { fn expr_to_ty<'a>(arena: &'a Bump, expr: &'a nast::Expr<'a>) -> Option<Ty_<'a>> { use aast::Expr_::*; match expr.2 { Null => Some(Ty_::Tprim(arena.alloc(aast::Tprim::Tnull))), This => Some(Ty_::Tthis), True | False => Some(Ty_::Tprim(arena.alloc(aast::Tprim::Tbool))), Int(_) => Some(Ty_::Tprim(arena.alloc(aast::Tprim::Tint))), Float(_) => Some(Ty_::Tprim(arena.alloc(aast::Tprim::Tfloat))), String(_) => Some(Ty_::Tprim(arena.alloc(aast::Tprim::Tstring))), String2(_) => Some(Ty_::Tprim(arena.alloc(aast::Tprim::Tstring))), PrefixedString(_) => Some(Ty_::Tprim(arena.alloc(aast::Tprim::Tstring))), Unop(&(_op, expr)) => expr_to_ty(arena, expr), Hole(&(expr, _, _, _)) => expr_to_ty(arena, expr), ArrayGet(_) | As(_) | Await(_) | Binop(_) | Call(_) | Cast(_) | ClassConst(_) | ClassGet(_) | Clone(_) | Collection(_) | Darray(_) | Dollardollar(_) | Efun(_) | Eif(_) | EnumClassLabel(_) | ETSplice(_) | ExpressionTree(_) | FunctionPointer(_) | Id(_) | Import(_) | Is(_) | KeyValCollection(_) | Lfun(_) | List(_) | Lplaceholder(_) | Lvar(_) | MethodCaller(_) | New(_) | ObjGet(_) | Omitted | Pair(_) | Pipe(_) | ReadonlyExpr(_) | Shape(_) | Tuple(_) | Upcast(_) | ValCollection(_) | Varray(_) | Xml(_) | Yield(_) | Invalid(_) | Package(_) => None, } } Some(self.alloc(Ty( self.alloc(Reason::witness_from_decl(expr.1)), expr_to_ty(self.arena, expr)?, ))) } Node::IntLiteral((_, pos)) => Some(self.alloc(Ty( self.alloc(Reason::witness_from_decl(pos)), Ty_::Tprim(self.alloc(aast::Tprim::Tint)), ))), Node::FloatingLiteral((_, pos)) => Some(self.alloc(Ty( self.alloc(Reason::witness_from_decl(pos)), Ty_::Tprim(self.alloc(aast::Tprim::Tfloat)), ))), Node::StringLiteral((_, pos)) => Some(self.alloc(Ty( self.alloc(Reason::witness_from_decl(pos)), Ty_::Tprim(self.alloc(aast::Tprim::Tstring)), ))), Node::BooleanLiteral((_, pos)) => Some(self.alloc(Ty( self.alloc(Reason::witness_from_decl(pos)), Ty_::Tprim(self.alloc(aast::Tprim::Tbool)), ))), Node::Token(t) if t.kind() == TokenKind::Varray => { let pos = self.token_pos(t); let tany = self.alloc(Ty(self.alloc(Reason::hint(pos)), TANY_)); let ty_ = Ty_::Tapply(self.alloc(( (self.token_pos(t), naming_special_names::collections::VEC), self.alloc([tany]), ))); Some(self.alloc(Ty(self.alloc(Reason::hint(pos)), ty_))) } Node::Token(t) if t.kind() == TokenKind::Darray => { let pos = self.token_pos(t); let tany = self.alloc(Ty(self.alloc(Reason::hint(pos)), TANY_)); let ty_ = Ty_::Tapply(self.alloc(( (self.token_pos(t), naming_special_names::collections::DICT), self.alloc([tany, tany]), ))); Some(self.alloc(Ty(self.alloc(Reason::hint(pos)), ty_))) } Node::Token(t) if t.kind() == TokenKind::This => { Some(self.alloc(Ty(self.alloc(Reason::hint(self.token_pos(t))), Ty_::Tthis))) } Node::Token(t) if t.kind() == TokenKind::NullLiteral => { let pos = self.token_pos(t); Some(self.alloc(Ty( self.alloc(Reason::hint(pos)), Ty_::Tprim(self.alloc(aast::Tprim::Tnull)), ))) } // In coeffects contexts, we get types like `ctx $f` or `$v::C`. // Node::Variable is used for the `$f` and `$v`, so that we don't // incorrectly attempt to elaborate them as names. Node::Variable(&(name, pos)) => Some(self.alloc(Ty( self.alloc(Reason::hint(pos)), Ty_::Tapply(self.alloc(((pos, name), &[][..]))), ))), node => { let Id(pos, name) = self.expect_name(node)?; let reason = self.alloc(Reason::hint(pos)); let ty_ = if self.is_type_param_in_scope(name) { // TODO (T69662957) must fill type args of Tgeneric Ty_::Tgeneric(self.alloc((name, &[]))) } else { match name { "nothing" => Ty_::Tunion(&[]), "nonnull" => { if self.implicit_sdt() { self.make_supportdyn(pos, Ty_::Tnonnull) } else { Ty_::Tnonnull } } "dynamic" => Ty_::Tdynamic, "varray_or_darray" | "vec_or_dict" => { let key_type = self.vec_or_dict_key(pos); let value_type = self.alloc(Ty(self.alloc(Reason::hint(pos)), TANY_)); Ty_::TvecOrDict(self.alloc((key_type, value_type))) } "_" => Ty_::Twildcard, _ => { let name = self.elaborate_raw_id(name); Ty_::Tapply(self.alloc(((pos, name), &[][..]))) } } }; Some(self.alloc(Ty(reason, ty_))) } } } fn partition_bounds_into_lower_and_upper( &self, constraints: Node<'a>, match_constraint: impl Fn(Node<'a>) -> Option<(ConstraintKind, Node<'a>)>, ) -> (bump::Vec<'a, &'a Ty<'a>>, bump::Vec<'a, &'a Ty<'a>>) { let append = |tys: &mut bump::Vec<'_, _>, ty: Option<_>| { if let Some(ty) = ty { tys.push(ty); } }; constraints.iter().fold( (bump::Vec::new_in(self.arena), bump::Vec::new_in(self.arena)), |(mut super_, mut as_), constraint| { if let Some((kind, hint)) = match_constraint(*constraint) { use ConstraintKind::*; match kind { ConstraintAs => append(&mut as_, self.node_to_ty(hint)), ConstraintSuper => append(&mut super_, self.node_to_ty(hint)), _ => (), }; }; (super_, as_) }, ) } fn partition_type_bounds_into_lower_and_upper( &self, constraints: Node<'a>, ) -> (bump::Vec<'a, &'a Ty<'a>>, bump::Vec<'a, &'a Ty<'a>>) { self.partition_bounds_into_lower_and_upper(constraints, |constraint| { if let Node::TypeConstraint(kind_hint) = constraint { Some(*kind_hint) } else { None } }) } fn partition_ctx_bounds_into_lower_and_upper( &self, constraints: Node<'a>, ) -> (bump::Vec<'a, &'a Ty<'a>>, bump::Vec<'a, &'a Ty<'a>>) { self.partition_bounds_into_lower_and_upper(constraints, |constraint| { if let Node::ContextConstraint(kind_hint) = constraint { Some(*kind_hint) } else { None } }) } fn to_attributes(&self, node: Node<'a>) -> Attributes<'a> { let mut attributes = Attributes { deprecated: None, reifiable: None, late_init: false, const_: false, lsb: false, memoize: false, memoizelsb: false, override_: false, enforceable: None, accept_disposable: false, dynamically_callable: false, returns_disposable: false, php_std_lib: false, ifc_attribute: default_ifc_fun_decl(), external: false, can_call: false, soft: false, support_dynamic_type: false, no_auto_likes: false, safe_global_variable: false, cross_package: None, }; let nodes = match node { Node::List(&nodes) | Node::BracketedList(&(_, nodes, _)) => nodes, _ => return attributes, }; let mut ifc_already_policied = false; // Iterate in reverse, to match the behavior of OCaml decl in error conditions. for attribute in nodes.iter().rev() { if let Node::Attribute(attribute) = attribute { match attribute.name.1 { "__Deprecated" => { attributes.deprecated = attribute .string_literal_param .map(|(_, x)| self.str_from_utf8_for_bytes_in_arena(x)); } "__Reifiable" => attributes.reifiable = Some(attribute.name.0), "__LateInit" => { attributes.late_init = true; } "__Const" => { attributes.const_ = true; } "__LSB" => { attributes.lsb = true; } "__Memoize" => { attributes.memoize = true; } "__MemoizeLSB" => { attributes.memoizelsb = true; } "__Override" => { attributes.override_ = true; } "__Enforceable" => { attributes.enforceable = Some(attribute.name.0); } "__AcceptDisposable" => { attributes.accept_disposable = true; } "__DynamicallyCallable" => { attributes.dynamically_callable = true; } "__ReturnDisposable" => { attributes.returns_disposable = true; } "__PHPStdLib" => { attributes.php_std_lib = true; } "__Policied" => { attributes.ifc_attribute = IfcFunDecl::FDPolicied( attribute.params.first().and_then(|a| match a { AttributeParam::Classname(cn) => Some(cn.1), AttributeParam::String(_, s) => { Some(self.str_from_utf8_for_bytes_in_arena(s)) } _ => None, }), ); ifc_already_policied = true; } "__InferFlows" => { if !ifc_already_policied { attributes.ifc_attribute = IfcFunDecl::FDInferFlows; } } "__External" => { attributes.external = true; } "__CanCall" => { attributes.can_call = true; } "__Soft" => { attributes.soft = true; } "__SupportDynamicType" => { attributes.support_dynamic_type = true; } "__NoAutoLikes" => { attributes.no_auto_likes = true; } "__SafeForGlobalAccessCheck" => { attributes.safe_global_variable = true; } "__CrossPackage" => { attributes.cross_package = attribute .string_literal_param .map(|(_, x)| self.str_from_utf8_for_bytes_in_arena(x)); } _ => {} } } } attributes } // Limited version of node_to_ty that matches behavior of Decl_utils.infer_const fn infer_const(&self, name: Node<'a>, node: Node<'a>) -> Option<&'a Ty<'a>> { match node { Node::StringLiteral(_) | Node::BooleanLiteral(_) | Node::IntLiteral(_) | Node::FloatingLiteral(_) | Node::Expr(aast::Expr(_, _, aast::Expr_::Unop(&(Uop::Uminus, _)))) | Node::Expr(aast::Expr(_, _, aast::Expr_::Unop(&(Uop::Uplus, _)))) | Node::Expr(aast::Expr(_, _, aast::Expr_::String(..))) => self.node_to_ty(node), Node::Token(t) if t.kind() == TokenKind::NullLiteral => { let pos = self.token_pos(t); Some(self.alloc(Ty( self.alloc(Reason::witness_from_decl(pos)), Ty_::Tprim(self.alloc(aast::Tprim::Tnull)), ))) } _ => Some(self.tany_with_pos(self.get_pos(name))), } } fn pop_type_params(&mut self, node: Node<'a>) -> &'a [&'a Tparam<'a>] { match node { Node::TypeParameters(tparams) => { let this = Rc::make_mut(&mut self.state); Rc::make_mut(&mut this.type_parameters).pop().unwrap(); tparams } _ => &[], } } fn ret_from_fun_kind(&self, kind: FunKind, type_: &'a Ty<'a>) -> &'a Ty<'a> { let pos = type_.get_pos().unwrap_or(NO_POS); match kind { FunKind::FAsyncGenerator => self.alloc(Ty( self.alloc(Reason::RretFunKindFromDecl(self.alloc((pos, kind)))), Ty_::Tapply(self.alloc(( (pos, naming_special_names::classes::ASYNC_GENERATOR), self.alloc([type_, type_, type_]), ))), )), FunKind::FGenerator => self.alloc(Ty( self.alloc(Reason::RretFunKindFromDecl(self.alloc((pos, kind)))), Ty_::Tapply(self.alloc(( (pos, naming_special_names::classes::GENERATOR), self.alloc([type_, type_, type_]), ))), )), FunKind::FAsync => self.alloc(Ty( self.alloc(Reason::RretFunKindFromDecl(self.alloc((pos, kind)))), Ty_::Tapply(self.alloc(( (pos, naming_special_names::classes::AWAITABLE), self.alloc([type_]), ))), )), _ => type_, } } fn is_type_param_in_scope(&self, name: &str) -> bool { self.type_parameters.iter().any(|tps| tps.contains(name)) } fn as_fun_implicit_params( &self, capability: Node<'a>, default_pos: &'a Pos<'a>, ) -> &'a FunImplicitParams<'a> { /* Note: do not simplify intersections, keep empty / singleton intersections * for coeffect contexts */ let capability = match self.node_to_ty(capability) { Some(ty) => CapTy(ty), None => CapDefaults(default_pos), }; self.alloc(FunImplicitParams { capability }) } fn function_to_ty( &mut self, is_method: bool, attributes: Node<'a>, header: &'a FunctionHeader<'a>, body: Node<'_>, ) -> Option<(PosId<'a>, &'a Ty<'a>, &'a [ShallowProp<'a>])> { let id_opt = match (is_method, header.name) { // If the name is missing, we use the left paren here, just to get a // position to point to. (_, Node::Token(t)) if t.kind() == TokenKind::LeftParen => { let pos = self.token_pos(t); Some(Id(pos, "")) } (true, Node::Token(t)) if t.kind() == TokenKind::Construct => { let pos = self.token_pos(t); Some(Id(pos, naming_special_names::members::__CONSTRUCT)) } (true, _) => self.expect_name(header.name), (false, _) => self.elaborate_defined_id(header.name), }; let id = id_opt.unwrap_or_else(|| Id(self.get_pos(header.name), "")); let attributes = self.to_attributes(attributes); let (params, properties, variadic) = self.as_fun_params(attributes.no_auto_likes, header.param_list)?; let f_pos = self.get_pos(header.name); let implicit_params = self.as_fun_implicit_params(header.capability, f_pos); let type_ = match header.name { Node::Token(t) if t.kind() == TokenKind::Construct => { let pos = self.token_pos(t); self.alloc(Ty( self.alloc(Reason::witness_from_decl(pos)), Ty_::Tprim(self.alloc(aast::Tprim::Tvoid)), )) } _ => self .node_to_ty(header.ret_hint) .unwrap_or_else(|| self.tany_with_pos(f_pos)), }; let async_ = header .modifiers .iter() .any(|n| n.is_token(TokenKind::Async)); let readonly = header .modifiers .iter() .any(|n| n.is_token(TokenKind::Readonly)); let fun_kind = if body.iter().any(|node| node.is_token(TokenKind::Yield)) { if async_ { FunKind::FAsyncGenerator } else { FunKind::FGenerator } } else if async_ { FunKind::FAsync } else { FunKind::FSync }; let type_ = if !header.ret_hint.is_present() { self.ret_from_fun_kind(fun_kind, type_) } else { type_ }; // TODO(hrust) Put this in a helper. Possibly do this for all flags. let mut flags = match fun_kind { FunKind::FSync => FunTypeFlags::empty(), FunKind::FAsync => FunTypeFlags::ASYNC, FunKind::FGenerator => FunTypeFlags::GENERATOR, FunKind::FAsyncGenerator => FunTypeFlags::ASYNC | FunTypeFlags::GENERATOR, }; if attributes.returns_disposable { flags |= FunTypeFlags::RETURN_DISPOSABLE; } if attributes.support_dynamic_type { flags |= FunTypeFlags::SUPPORT_DYNAMIC_TYPE; } if header.readonly_return.is_token(TokenKind::Readonly) { flags |= FunTypeFlags::RETURNS_READONLY; } if attributes.memoize || attributes.memoizelsb { flags |= FunTypeFlags::IS_MEMOIZED; } if readonly { flags |= FunTypeFlags::READONLY_THIS } if variadic { flags |= FunTypeFlags::VARIADIC } let ifc_decl = attributes.ifc_attribute; let cross_package = attributes.cross_package; // Pop the type params stack only after creating all inner types. let tparams = self.pop_type_params(header.type_params); let where_constraints = self.slice(header.where_constraints.iter().filter_map(|&x| match x { Node::WhereConstraint(x) => Some(x), _ => None, })); let (params, tparams, implicit_params, where_constraints) = self.rewrite_effect_polymorphism(params, tparams, implicit_params, where_constraints); let ft = self.alloc(FunType { tparams, where_constraints, params, implicit_params, ret: self.alloc(PossiblyEnforcedTy { enforced: Enforcement::Unenforced, type_, }), flags, ifc_decl, cross_package, }); let ty = self.alloc(Ty( self.alloc(Reason::witness_from_decl(id.0)), Ty_::Tfun(ft), )); Some((id.into(), ty, properties)) } fn as_fun_params( &self, no_auto_likes: bool, list: Node<'a>, ) -> Option<(&'a FunParams<'a>, &'a [ShallowProp<'a>], bool)> { match list { Node::List(nodes) => { let mut params = bump::Vec::with_capacity_in(nodes.len(), self.arena); let mut properties = bump::Vec::new_in(self.arena); let mut ft_variadic = false; for node in nodes.iter() { match node { Node::FunParam(&FunParamDecl { attributes, visibility, kind, readonly, hint, pos, name, variadic, initializer, }) => { let attributes = self.to_attributes(attributes); let type_ = self .node_to_ty(hint) .unwrap_or_else(|| self.tany_with_pos(pos)); if let Some(visibility) = visibility.as_visibility() { let name = name.unwrap_or(""); let name = strip_dollar_prefix(name); let mut flags = PropFlags::empty(); flags.set(PropFlags::CONST, attributes.const_); flags.set(PropFlags::NEEDS_INIT, self.file_mode != Mode::Mhhi); flags.set(PropFlags::PHP_STD_LIB, attributes.php_std_lib); flags.set(PropFlags::READONLY, readonly); // Promoted property either marked <<__NoAutoLikes>> on the parameter or on the constructor flags.set( PropFlags::NO_AUTO_LIKES, attributes.no_auto_likes || no_auto_likes, ); properties.push(ShallowProp { xhp_attr: None, name: (pos, name), type_, visibility, flags, }); } // These are illegal here--they can only be used on // parameters in a function type hint (see // make_closure_type_specifier and unwrap_mutability). // Unwrap them here anyway for better error recovery. let type_ = match type_ { Ty(_, Ty_::Tapply(((_, "\\Mutable"), [t]))) => t, Ty(_, Ty_::Tapply(((_, "\\OwnedMutable"), [t]))) => t, Ty(_, Ty_::Tapply(((_, "\\MaybeMutable"), [t]))) => t, _ => type_, }; let mut flags = FunParamFlags::empty(); if attributes.accept_disposable { flags |= FunParamFlags::ACCEPT_DISPOSABLE } if attributes.external { flags |= FunParamFlags::IFC_EXTERNAL } if attributes.can_call { flags |= FunParamFlags::IFC_CAN_CALL } if readonly { flags |= FunParamFlags::READONLY } match kind { ParamMode::FPinout => { flags |= FunParamFlags::INOUT; } ParamMode::FPnormal => {} }; if initializer.is_present() { flags |= FunParamFlags::HAS_DEFAULT; } if variadic { ft_variadic = true; } let variadic = initializer.is_ignored() && variadic; let type_ = if variadic { self.alloc(Ty( self.alloc(if name.is_some() { Reason::RvarParamFromDecl(pos) } else { Reason::witness_from_decl(pos) }), type_.1, )) } else { type_ }; let param = self.alloc(FunParam { pos, name, type_: self.alloc(PossiblyEnforcedTy { enforced: Enforcement::Unenforced, type_, }), flags, }); params.push(param); } _ => {} } } Some(( params.into_bump_slice(), properties.into_bump_slice(), ft_variadic, )) } n if n.is_ignored() => Some((&[], &[], false)), _ => None, } } fn make_shape_field_name(&self, name: Node<'a>) -> Option<ShapeFieldName<'a>> { Some(match name { Node::StringLiteral(&(s, pos)) => ShapeFieldName::SFlitStr(self.alloc((pos, s))), // TODO: OCaml decl produces SFlitStr here instead of SFlitInt, so // we must also. Looks like int literal keys have become a parse // error--perhaps that's why. Node::IntLiteral(&(s, pos)) => ShapeFieldName::SFlitStr(self.alloc((pos, s.into()))), Node::Expr(aast::Expr( _, _, aast::Expr_::ClassConst(&( aast::ClassId(_, _, aast::ClassId_::CI(&class_name)), const_name, )), )) => ShapeFieldName::SFclassConst(self.alloc((class_name, const_name))), Node::Expr(aast::Expr( _, _, aast::Expr_::ClassConst(&( aast::ClassId(_, pos, aast::ClassId_::CIself), const_name, )), )) => { let (classish_name, _) = self.get_current_classish_name()?; ShapeFieldName::SFclassConst(self.alloc((Id(pos, classish_name), const_name))) } _ => return None, }) } fn make_t_shape_field_name(&self, ShapeField(field): &ShapeField<'a>) -> TShapeField<'a> { TShapeField(match field { ShapeFieldName::SFlitInt(&(pos, x)) => { TshapeFieldName::TSFlitInt(self.alloc(PosString(pos, x))) } ShapeFieldName::SFlitStr(&(pos, x)) => { TshapeFieldName::TSFlitStr(self.alloc(PosByteString(pos, x))) } ShapeFieldName::SFclassConst(&(id, &(pos, x))) => { TshapeFieldName::TSFclassConst(self.alloc((id.into(), PosString(pos, x)))) } }) } fn make_apply( &self, base_ty: PosId<'a>, type_arguments: Node<'a>, pos_to_merge: &'a Pos<'a>, ) -> Node<'a> { let type_arguments = self.slice( type_arguments .iter() .filter_map(|&node| self.node_to_ty(node)), ); let pos = self.merge(base_ty.0, pos_to_merge); // OCaml decl creates a capability with a hint pointing to the entire // type (i.e., pointing to `Rx<(function(): void)>` rather than just // `(function(): void)`), so we extend the hint position similarly here. let extend_capability_pos = |implicit_params: &'a FunImplicitParams<'_>| { let capability = match implicit_params.capability { CapTy(ty) => { let ty = self.alloc(Ty(self.alloc(Reason::hint(pos)), ty.1)); CapTy(ty) } CapDefaults(_) => CapDefaults(pos), }; self.alloc(FunImplicitParams { capability, ..*implicit_params }) }; let ty_ = match (base_ty, type_arguments) { ((_, name), &[&Ty(_, Ty_::Tfun(f))]) if name == "\\Pure" => { Ty_::Tfun(self.alloc(FunType { implicit_params: extend_capability_pos(f.implicit_params), ..*f })) } _ => Ty_::Tapply(self.alloc((base_ty, type_arguments))), }; self.hint_ty(pos, ty_) } fn hint_ty(&self, pos: &'a Pos<'a>, ty_: Ty_<'a>) -> Node<'a> { Node::Ty(self.alloc(Ty(self.alloc(Reason::hint(pos)), ty_))) } fn prim_ty(&self, tprim: aast::Tprim, pos: &'a Pos<'a>) -> Node<'a> { self.hint_ty(pos, Ty_::Tprim(self.alloc(tprim))) } fn tany_with_pos(&self, pos: &'a Pos<'a>) -> &'a Ty<'a> { self.alloc(Ty(self.alloc(Reason::witness_from_decl(pos)), TANY_)) } /// The type used when a `vec_or_dict` typehint is missing its key type argument. fn vec_or_dict_key(&self, pos: &'a Pos<'a>) -> &'a Ty<'a> { self.alloc(Ty( self.alloc(Reason::RvecOrDictKey(pos)), Ty_::Tprim(self.alloc(aast::Tprim::Tarraykey)), )) } fn source_text_at_pos(&self, pos: &'a Pos<'a>) -> &'t [u8] { let start = pos.start_offset(); let end = pos.end_offset(); self.source_text.source_text().sub(start, end - start) } // While we usually can tell whether to allocate a Tapply or Tgeneric based // on our type_parameters stack, *constraints* on type parameters may // reference type parameters which we have not parsed yet. When constructing // a type parameter list, we use this function to rewrite the type of each // constraint, considering the full list of type parameters to be in scope. fn convert_tapply_to_tgeneric(&self, ty: &'a Ty<'a>) -> &'a Ty<'a> { let ty_ = match ty.1 { Ty_::Tapply(&(id, targs)) => { let converted_targs = self.slice( targs .iter() .map(|&targ| self.convert_tapply_to_tgeneric(targ)), ); match self.tapply_should_be_tgeneric(ty.0, id) { Some(name) => Ty_::Tgeneric(self.alloc((name, converted_targs))), None => Ty_::Tapply(self.alloc((id, converted_targs))), } } Ty_::Tlike(ty) => Ty_::Tlike(self.convert_tapply_to_tgeneric(ty)), Ty_::Toption(ty) => Ty_::Toption(self.convert_tapply_to_tgeneric(ty)), Ty_::Tfun(fun_type) => { let convert_param = |param: &'a FunParam<'a>| { self.alloc(FunParam { type_: self.alloc(PossiblyEnforcedTy { enforced: param.type_.enforced, type_: self.convert_tapply_to_tgeneric(param.type_.type_), }), ..*param }) }; let params = self.slice(fun_type.params.iter().copied().map(convert_param)); let implicit_params = fun_type.implicit_params; let ret = self.alloc(PossiblyEnforcedTy { enforced: fun_type.ret.enforced, type_: self.convert_tapply_to_tgeneric(fun_type.ret.type_), }); Ty_::Tfun(self.alloc(FunType { params, implicit_params, ret, ..*fun_type })) } Ty_::Tshape(&ShapeType { origin: _, unknown_value: kind, fields, }) => { let mut converted_fields = AssocListMut::with_capacity_in(fields.len(), self.arena); for (&name, ty) in fields.iter() { converted_fields.insert( name, self.alloc(ShapeFieldType { optional: ty.optional, ty: self.convert_tapply_to_tgeneric(ty.ty), }), ); } let origin = TypeOrigin::MissingOrigin; Ty_::Tshape(self.alloc(ShapeType { origin, unknown_value: kind, fields: converted_fields.into(), })) } Ty_::TvecOrDict(&(tk, tv)) => Ty_::TvecOrDict(self.alloc(( self.convert_tapply_to_tgeneric(tk), self.convert_tapply_to_tgeneric(tv), ))), Ty_::Ttuple(tys) => Ty_::Ttuple( self.slice( tys.iter() .map(|&targ| self.convert_tapply_to_tgeneric(targ)), ), ), Ty_::Tintersection(tys) => Ty_::Tintersection( self.slice(tys.iter().map(|&ty| self.convert_tapply_to_tgeneric(ty))), ), Ty_::Tunion(tys) => { Ty_::Tunion(self.slice(tys.iter().map(|&ty| self.convert_tapply_to_tgeneric(ty)))) } Ty_::Trefinement(&(root_ty, class_ref)) => { let convert_refined_const = |rc: &'a RefinedConst<'a>| { let RefinedConst { bound, is_ctx } = rc; let bound = match bound { RefinedConstBound::TRexact(ty) => { RefinedConstBound::TRexact(self.convert_tapply_to_tgeneric(ty)) } RefinedConstBound::TRloose(bnds) => { let convert_tys = |tys: &'a [&'a Ty<'a>]| { self.slice( tys.iter().map(|&ty| self.convert_tapply_to_tgeneric(ty)), ) }; RefinedConstBound::TRloose(self.alloc(RefinedConstBounds { lower: convert_tys(bnds.lower), upper: convert_tys(bnds.upper), })) } }; RefinedConst { bound, is_ctx: *is_ctx, } }; Ty_::Trefinement( self.alloc(( self.convert_tapply_to_tgeneric(root_ty), ClassRefinement { cr_consts: arena_collections::map::Map::from( self.arena, class_ref .cr_consts .iter() .map(|(id, ctr)| (*id, convert_refined_const(ctr))), ), }, )), ) } Ty_::Taccess(_) | Ty_::Tany(_) | Ty_::Tclass(_) | Ty_::Tdynamic | Ty_::Tgeneric(_) | Ty_::Tmixed | Ty_::Twildcard | Ty_::Tnonnull | Ty_::Tprim(_) | Ty_::Tthis => return ty, Ty_::Tdependent(_) | Ty_::Tneg(_) | Ty_::Tnewtype(_) | Ty_::Tvar(_) | Ty_::TunappliedAlias(_) => panic!("unexpected decl type in constraint"), }; self.alloc(Ty(ty.0, ty_)) } // This is the logic for determining if convert_tapply_to_tgeneric should turn // a Tapply into a Tgeneric fn tapply_should_be_tgeneric(&self, reason: &'a Reason<'a>, id: PosId<'a>) -> Option<&'a str> { match reason.pos() { // If the name contained a namespace delimiter in the original // source text, then it can't have referred to a type parameter // (since type parameters cannot be namespaced). Some(pos) => { if self.source_text_at_pos(pos).contains(&b'\\') { return None; } } None => return None, } // However, the direct decl parser will unconditionally prefix // the name with the current namespace (as it does for any // Tapply). We need to remove it. match id.1.rsplit('\\').next() { Some(name) if self.is_type_param_in_scope(name) => Some(name), _ => None, } } fn rewrite_taccess_reasons(&self, ty: &'a Ty<'a>, r: &'a Reason<'a>) -> &'a Ty<'a> { let ty_ = match ty.1 { Ty_::Taccess(&TaccessType(ty, id)) => { Ty_::Taccess(self.alloc(TaccessType(self.rewrite_taccess_reasons(ty, r), id))) } ty_ => ty_, }; self.alloc(Ty(r, ty_)) } fn namespace_use_kind(use_kind: &Node<'_>) -> Option<NamespaceUseKind> { match use_kind.token_kind() { Some(TokenKind::Const) => None, Some(TokenKind::Function) => None, Some(TokenKind::Type) => Some(NamespaceUseKind::Type), Some(TokenKind::Namespace) => Some(NamespaceUseKind::Namespace), _ if !use_kind.is_present() => Some(NamespaceUseKind::Mixed), _ => None, } } fn has_polymorphic_context(contexts: &[&Ty<'_>]) -> bool { contexts.iter().any(|&ty| match ty.1 { Ty_::Tapply((root, &[])) // Hfun_context in the AST | Ty_::Taccess(TaccessType(Ty(_, Ty_::Tapply((root, &[]))), _)) => root.1.contains('$'), | Ty_::Taccess(TaccessType(t, _)) => Self::taccess_root_is_generic(t), _ => false, }) } fn ctx_generic_for_fun(&self, name: &str) -> &'a str { bumpalo::format!(in self.arena, "T/[ctx {}]", name).into_bump_str() } fn ctx_generic_for_dependent(&self, name: &str, cst: &str) -> &'a str { bumpalo::format!(in self.arena, "T/[{}::{}]", name, cst).into_bump_str() } // Note: the reason for the divergence between this and the lowerer is that // hint Haccess is a flat list, whereas decl ty Taccess is a tree. fn taccess_root_is_generic(ty: &Ty<'_>) -> bool { match ty { Ty(_, Ty_::Tgeneric((_, &[]))) => true, Ty(_, Ty_::Taccess(&TaccessType(t, _))) => Self::taccess_root_is_generic(t), _ => false, } } fn ctx_generic_for_generic_taccess_inner(ty: &Ty<'_>, cst: &str) -> std::string::String { let left = match ty { Ty(_, Ty_::Tgeneric((name, &[]))) => name.to_string(), Ty(_, Ty_::Taccess(&TaccessType(ty, cst))) => { Self::ctx_generic_for_generic_taccess_inner(ty, cst.1) } _ => panic!("Unexpected element in Taccess"), }; format!("{}::{}", left, cst) } fn ctx_generic_for_generic_taccess(&self, ty: &Ty<'_>, cst: &str) -> &'a str { bumpalo::format!( in self.arena, "T/[{}]", Self::ctx_generic_for_generic_taccess_inner(ty, cst) ) .into_bump_str() } // For a polymorphic context with form `ctx $f` (represented here as // `Tapply "$f"`), add a type parameter named `Tctx$f`, and rewrite the // parameter `(function (ts)[_]: t) $f` as `(function (ts)[Tctx$f]: t) $f` fn rewrite_fun_ctx( &self, tparams: &mut bump::Vec<'_, &'a Tparam<'a>>, ty: &Ty<'a>, param_name: &str, ) -> Ty<'a> { match ty.1 { Ty_::Tfun(ft) => { let cap_ty = match ft.implicit_params.capability { CapTy(&Ty(_, Ty_::Tintersection(&[ty]))) | CapTy(ty) => ty, _ => return ty.clone(), }; let pos = match cap_ty.1 { Ty_::Tapply(((pos, "_"), _)) => pos, _ => return ty.clone(), }; let name = self.ctx_generic_for_fun(param_name); let tparam = self.alloc(Tparam { variance: Variance::Invariant, name: (pos, name), tparams: &[], constraints: &[], reified: aast::ReifyKind::Erased, user_attributes: &[], }); tparams.push(tparam); let cap_ty = self.alloc(Ty(cap_ty.0, Ty_::Tgeneric(self.alloc((name, &[]))))); let ft = self.alloc(FunType { implicit_params: self.alloc(FunImplicitParams { capability: CapTy(cap_ty), }), ..*ft }); Ty(ty.0, Ty_::Tfun(ft)) } Ty_::Tlike(t) => Ty( ty.0, Ty_::Tlike(self.alloc(self.rewrite_fun_ctx(tparams, t, param_name))), ), Ty_::Toption(t) => Ty( ty.0, Ty_::Toption(self.alloc(self.rewrite_fun_ctx(tparams, t, param_name))), ), Ty_::Tapply(((p, name), targs)) if *name == naming_special_names::typehints::HH_SUPPORTDYN => { if let Some(t) = targs.first() { Ty( ty.0, Ty_::Tapply(self.alloc(( (p, name), self.alloc([self.alloc(self.rewrite_fun_ctx(tparams, t, param_name))]), ))), ) } else { ty.clone() } } _ => ty.clone(), } } fn rewrite_effect_polymorphism( &self, params: &'a [&'a FunParam<'a>], tparams: &'a [&'a Tparam<'a>], implicit_params: &'a FunImplicitParams<'a>, where_constraints: &'a [&'a WhereConstraint<'a>], ) -> ( &'a [&'a FunParam<'a>], &'a [&'a Tparam<'a>], &'a FunImplicitParams<'a>, &'a [&'a WhereConstraint<'a>], ) { let (cap_reason, context_tys) = match implicit_params.capability { CapTy(&Ty(r, Ty_::Tintersection(tys))) if Self::has_polymorphic_context(tys) => { (r, tys) } CapTy(ty) if Self::has_polymorphic_context(&[ty]) => { (ty.0, std::slice::from_ref(self.alloc(ty))) } _ => return (params, tparams, implicit_params, where_constraints), }; let tp = |name, constraints| { self.alloc(Tparam { variance: Variance::Invariant, name, tparams: &[], constraints, reified: aast::ReifyKind::Erased, user_attributes: &[], }) }; // For a polymorphic context with form `$g::C`, if we have a function // parameter `$g` with type `G` (where `G` is not a type parameter), // - add a type parameter constrained by $g's type: `T/$g as G` // - replace $g's type hint (`G`) with the new type parameter `T/$g` // Then, for each polymorphic context with form `$g::C`, // - add a type parameter `T/[$g::C]` // - add a where constraint `T/[$g::C] = T$g :: C` let rewrite_arg_ctx = |tparams: &mut bump::Vec<'_, &'a Tparam<'a>>, where_constraints: &mut bump::Vec<'_, &'a WhereConstraint<'a>>, ty: &Ty<'a>, param_pos: &'a Pos<'a>, name: &str, context_reason: &'a Reason<'a>, cst: PosId<'a>| -> Ty<'a> { let rewritten_ty = match ty.1 { // If the type hint for this function parameter is a type // parameter introduced in this function declaration, don't add // a new type parameter. Ty_::Tgeneric(&(type_name, _)) if tparams.iter().any(|tp| tp.name.1 == type_name) => { ty.clone() } // Otherwise, if the parameter is `G $g`, create tparam // `T$g as G` and replace $g's type hint _ => { let id = (param_pos, self.concat("T/", name)); tparams.push(tp( id, std::slice::from_ref( self.alloc((ConstraintKind::ConstraintAs, self.alloc(ty.clone()))), ), )); Ty( self.alloc(Reason::hint(param_pos)), Ty_::Tgeneric(self.alloc((id.1, &[]))), ) } }; let ty = self.alloc(Ty(context_reason, rewritten_ty.1)); let right = self.alloc(Ty( context_reason, Ty_::Taccess(self.alloc(TaccessType(ty, cst))), )); let left_id = ( context_reason.pos().unwrap_or(NO_POS), self.ctx_generic_for_dependent(name, cst.1), ); tparams.push(tp(left_id, &[])); let left = self.alloc(Ty( context_reason, Ty_::Tgeneric(self.alloc((left_id.1, &[]))), )); where_constraints.push(self.alloc(WhereConstraint( left, ConstraintKind::ConstraintEq, right, ))); rewritten_ty }; let mut tparams = bump::Vec::from_iter_in(tparams.iter().copied(), self.arena); let mut where_constraints = bump::Vec::from_iter_in(where_constraints.iter().copied(), self.arena); // The divergence here from the lowerer comes from using oxidized_by_ref instead of oxidized let mut ty_by_param: BTreeMap<&str, (Ty<'a>, &'a Pos<'a>)> = params .iter() .filter_map(|param| Some((param.name?, (param.type_.type_.clone(), param.pos)))) .collect(); for context_ty in context_tys { match context_ty.1 { // Hfun_context in the AST. Ty_::Tapply(((_, name), _)) if name.starts_with('$') => { if let Some((param_ty, _)) = ty_by_param.get_mut(name) { *param_ty = self.rewrite_fun_ctx(&mut tparams, param_ty, name); } } Ty_::Taccess(&TaccessType(Ty(_, Ty_::Tapply(((_, name), _))), cst)) => { if let Some((param_ty, param_pos)) = ty_by_param.get_mut(name) { let mut rewrite = |t| { rewrite_arg_ctx( &mut tparams, &mut where_constraints, t, param_pos, name, context_ty.0, cst, ) }; match param_ty.1 { Ty_::Tlike(ref mut ty) => match ty { Ty(r, Ty_::Toption(tinner)) => { *ty = self.alloc(Ty(r, Ty_::Toption(self.alloc(rewrite(tinner))))) } _ => { *ty = self.alloc(rewrite(ty)); } }, Ty_::Toption(ref mut ty) => { *ty = self.alloc(rewrite(ty)); } _ => { *param_ty = rewrite(param_ty); } } } } Ty_::Taccess(&TaccessType(t, cst)) if Self::taccess_root_is_generic(t) => { let left_id = ( context_ty.0.pos().unwrap_or(NO_POS), self.ctx_generic_for_generic_taccess(t, cst.1), ); tparams.push(tp(left_id, &[])); let left = self.alloc(Ty( context_ty.0, Ty_::Tgeneric(self.alloc((left_id.1, &[]))), )); where_constraints.push(self.alloc(WhereConstraint( left, ConstraintKind::ConstraintEq, context_ty, ))); } _ => {} } } let params = self.slice(params.iter().copied().map(|param| match param.name { None => param, Some(name) => match ty_by_param.get(name) { Some((type_, _)) if param.type_.type_ != type_ => self.alloc(FunParam { type_: self.alloc(PossiblyEnforcedTy { type_: self.alloc(type_.clone()), ..*param.type_ }), ..*param }), _ => param, }, })); let context_tys = self.slice(context_tys.iter().copied().map(|ty| { let ty_ = match ty.1 { Ty_::Tapply(((_, name), &[])) if name.starts_with('$') => { Ty_::Tgeneric(self.alloc((self.ctx_generic_for_fun(name), &[]))) } Ty_::Taccess(&TaccessType(Ty(_, Ty_::Tapply(((_, name), &[]))), cst)) if name.starts_with('$') => { let name = self.ctx_generic_for_dependent(name, cst.1); Ty_::Tgeneric(self.alloc((name, &[]))) } Ty_::Taccess(&TaccessType(t, cst)) if Self::taccess_root_is_generic(t) => { let name = self.ctx_generic_for_generic_taccess(t, cst.1); Ty_::Tgeneric(self.alloc((name, &[]))) } _ => return ty, }; self.alloc(Ty(ty.0, ty_)) })); let cap_ty = match context_tys { [ty] => ty, _ => self.alloc(Ty(cap_reason, Ty_::Tintersection(context_tys))), }; let implicit_params = self.alloc(FunImplicitParams { capability: CapTy(cap_ty), }); ( params, tparams.into_bump_slice(), implicit_params, where_constraints.into_bump_slice(), ) } } enum NodeIterHelper<'a, 'b> { Empty, Single(&'b Node<'a>), Vec(std::slice::Iter<'b, Node<'a>>), } impl<'a, 'b> Iterator for NodeIterHelper<'a, 'b> { type Item = &'b Node<'a>; fn next(&mut self) -> Option<Self::Item> { match self { NodeIterHelper::Empty => None, NodeIterHelper::Single(node) => { let node = *node; *self = NodeIterHelper::Empty; Some(node) } NodeIterHelper::Vec(ref mut iter) => iter.next(), } } // Must return the upper bound returned by Node::len. fn size_hint(&self) -> (usize, Option<usize>) { match self { NodeIterHelper::Empty => (0, Some(0)), NodeIterHelper::Single(_) => (1, Some(1)), NodeIterHelper::Vec(iter) => iter.size_hint(), } } } impl<'a, 'b> DoubleEndedIterator for NodeIterHelper<'a, 'b> { fn next_back(&mut self) -> Option<Self::Item> { match self { NodeIterHelper::Empty => None, NodeIterHelper::Single(_) => self.next(), NodeIterHelper::Vec(ref mut iter) => iter.next_back(), } } } impl<'a, 'o, 't, S: SourceTextAllocator<'t, 'a>> FlattenSmartConstructors for DirectDeclSmartConstructors<'a, 'o, 't, S> { // type Output = Node<'a> in direct_decl_smart_constructors_generated.rs fn flatten(&self, kind: SyntaxKind, lst: Vec<Self::Output>) -> Self::Output { let size = lst .iter() .map(|s| match s { Node::List(children) => children.len(), x => { if Self::is_zero(x) { 0 } else { 1 } } }) .sum(); let mut r = bump::Vec::with_capacity_in(size, self.arena); for s in lst.into_iter() { match s { Node::List(children) => r.extend(children.iter().copied()), x => { if !Self::is_zero(&x) { r.push(x) } } } } match r.into_bump_slice() { [] => Node::Ignored(kind), [node] => *node, slice => Node::List(self.alloc(slice)), } } fn zero(kind: SyntaxKind) -> Node<'a> { Node::Ignored(kind) } fn is_zero(s: &Self::Output) -> bool { match s { Node::Token(token) => match token.kind() { TokenKind::Yield | TokenKind::Required | TokenKind::Lateinit => false, _ => true, }, Node::List(inner) => inner.iter().all(Self::is_zero), _ => true, } } fn make_token(&mut self, token: CompactToken) -> Self::Output { let token_text = |this: &Self| this.str_from_utf8(this.token_bytes(&token)); let token_pos = |this: &Self| { let start = this .source_text .offset_to_file_pos_triple(token.start_offset()); let end = this .source_text .offset_to_file_pos_triple(token.end_offset()); Pos::from_lnum_bol_offset(this.arena, this.filename, start, end) }; let kind = token.kind(); let result = match kind { TokenKind::Name | TokenKind::XHPClassName => { let text = token_text(self); let pos = token_pos(self); let name = if kind == TokenKind::XHPClassName { Node::XhpName(self.alloc((text, pos))) } else { Node::Name(self.alloc((text, pos))) }; if self.previous_token_kind == TokenKind::Class || self.previous_token_kind == TokenKind::Trait || self.previous_token_kind == TokenKind::Interface { if let Some(current_class_name) = self.elaborate_defined_id(name) { let previous_token_kind = self.previous_token_kind; let this = Rc::make_mut(&mut self.state); this.lexed_name_after_classish_keyword( this.arena, current_class_name.1, pos, previous_token_kind, ); } } name } TokenKind::Variable => Node::Variable(self.alloc((token_text(self), token_pos(self)))), // There are a few types whose string representations we have to // grab anyway, so just go ahead and treat them as generic names. TokenKind::Vec | TokenKind::Dict | TokenKind::Keyset | TokenKind::Tuple | TokenKind::Classname | TokenKind::SelfToken => Node::Name(self.alloc((token_text(self), token_pos(self)))), TokenKind::XHPElementName => { Node::XhpName(self.alloc((token_text(self), token_pos(self)))) } TokenKind::SingleQuotedStringLiteral => match escaper::unescape_single_in( self.str_from_utf8(escaper::unquote_slice(self.token_bytes(&token))), self.arena, ) { Ok(text) => Node::StringLiteral(self.alloc((text.into(), token_pos(self)))), Err(_) => Node::Ignored(SK::Token(kind)), }, TokenKind::DoubleQuotedStringLiteral => match escaper::unescape_double_in( self.str_from_utf8(escaper::unquote_slice(self.token_bytes(&token))), self.arena, ) { Ok(text) => Node::StringLiteral(self.alloc((text, token_pos(self)))), Err(_) => Node::Ignored(SK::Token(kind)), }, TokenKind::HeredocStringLiteral => match escaper::unescape_heredoc_in( self.str_from_utf8(escaper::unquote_slice(self.token_bytes(&token))), self.arena, ) { Ok(text) if !self.opts.keep_user_attributes => { Node::StringLiteral(self.alloc((text, token_pos(self)))) } _ => Node::Ignored(SK::Token(kind)), }, TokenKind::NowdocStringLiteral => match escaper::unescape_nowdoc_in( self.str_from_utf8(escaper::unquote_slice(self.token_bytes(&token))), self.arena, ) { Ok(text) if !self.opts.keep_user_attributes => { Node::StringLiteral(self.alloc((text.into(), token_pos(self)))) } _ => Node::Ignored(SK::Token(kind)), }, TokenKind::DecimalLiteral | TokenKind::OctalLiteral | TokenKind::HexadecimalLiteral | TokenKind::BinaryLiteral => { Node::IntLiteral(self.alloc((token_text(self), token_pos(self)))) } TokenKind::FloatingLiteral => { Node::FloatingLiteral(self.alloc((token_text(self), token_pos(self)))) } TokenKind::BooleanLiteral => { Node::BooleanLiteral(self.alloc((token_text(self), token_pos(self)))) } TokenKind::String => self.prim_ty(aast::Tprim::Tstring, token_pos(self)), TokenKind::Int => self.prim_ty(aast::Tprim::Tint, token_pos(self)), TokenKind::Float => self.prim_ty(aast::Tprim::Tfloat, token_pos(self)), // "double" and "boolean" are parse errors--they should be written // "float" and "bool". The decl-parser treats the incorrect names as // type names rather than primitives. TokenKind::Double | TokenKind::Boolean => self.hint_ty( token_pos(self), Ty_::Tapply(self.alloc(((token_pos(self), token_text(self)), &[][..]))), ), TokenKind::Num => self.prim_ty(aast::Tprim::Tnum, token_pos(self)), TokenKind::Bool => self.prim_ty(aast::Tprim::Tbool, token_pos(self)), TokenKind::Mixed => { let reason = self.alloc(Reason::hint(token_pos(self))); if self.implicit_sdt() { let ty_ = self.make_supportdyn(token_pos(self), Ty_::Tmixed); Node::Ty(self.alloc(Ty(reason, ty_))) } else { Node::Ty(self.alloc(Ty(reason, Ty_::Tmixed))) } } TokenKind::Void => self.prim_ty(aast::Tprim::Tvoid, token_pos(self)), TokenKind::Arraykey => self.prim_ty(aast::Tprim::Tarraykey, token_pos(self)), TokenKind::Noreturn => self.prim_ty(aast::Tprim::Tnoreturn, token_pos(self)), TokenKind::Resource => self.prim_ty(aast::Tprim::Tresource, token_pos(self)), TokenKind::Class | TokenKind::Interface | TokenKind::Trait => { if self.under_no_auto_dynamic { let this = Rc::make_mut(&mut self.state); this.inside_no_auto_dynamic_class = true; } Node::Token(FixedWidthToken::new(kind, token.start_offset())) } TokenKind::NullLiteral | TokenKind::Darray | TokenKind::Varray | TokenKind::Backslash | TokenKind::Construct | TokenKind::LeftParen | TokenKind::RightParen | TokenKind::LeftBracket | TokenKind::RightBracket | TokenKind::Shape | TokenKind::Question | TokenKind::This | TokenKind::Tilde | TokenKind::Exclamation | TokenKind::Plus | TokenKind::Minus | TokenKind::PlusPlus | TokenKind::MinusMinus | TokenKind::At | TokenKind::Star | TokenKind::Slash | TokenKind::EqualEqual | TokenKind::EqualEqualEqual | TokenKind::StarStar | TokenKind::AmpersandAmpersand | TokenKind::BarBar | TokenKind::LessThan | TokenKind::LessThanEqual | TokenKind::GreaterThan | TokenKind::GreaterThanEqual | TokenKind::Dot | TokenKind::Ampersand | TokenKind::Bar | TokenKind::LessThanLessThan | TokenKind::GreaterThanGreaterThan | TokenKind::Percent | TokenKind::QuestionQuestion | TokenKind::Equal | TokenKind::Abstract | TokenKind::As | TokenKind::Super | TokenKind::Async | TokenKind::DotDotDot | TokenKind::Extends | TokenKind::Final | TokenKind::Implements | TokenKind::Inout | TokenKind::Newctx | TokenKind::Newtype | TokenKind::Type | TokenKind::Yield | TokenKind::Semicolon | TokenKind::Private | TokenKind::Protected | TokenKind::Public | TokenKind::Reify | TokenKind::Static | TokenKind::Lateinit | TokenKind::RightBrace | TokenKind::Enum | TokenKind::Const | TokenKind::Function | TokenKind::Namespace | TokenKind::XHP | TokenKind::Required | TokenKind::Ctx | TokenKind::Readonly | TokenKind::Internal | TokenKind::Global => Node::Token(FixedWidthToken::new(kind, token.start_offset())), _ if kind.fixed_width().is_some() => { Node::IgnoredToken(FixedWidthToken::new(kind, token.start_offset())) } _ => Node::Ignored(SK::Token(kind)), }; self.previous_token_kind = kind; result } fn make_error(&mut self, error: Self::Output) -> Self::Output { // If it's a Token or IgnoredToken, we can use it for error recovery. // For instance, in `function using() {}`, the `using` keyword will be a // token wrapped in an error CST node, since the keyword isn't legal in // that position. error } fn make_missing(&mut self, _: usize) -> Self::Output { Node::Ignored(SK::Missing) } fn make_list(&mut self, mut items: Vec<Self::Output>, _: usize) -> Self::Output { if let Some(&yield_) = items .iter() .flat_map(|node| node.iter()) .find(|node| node.is_token(TokenKind::Yield)) { yield_ } else { items.retain(|node| node.is_present()); if items.is_empty() { Node::Ignored(SK::SyntaxList) } else { let items = self.arena.alloc_slice_fill_iter(items); Node::List(self.alloc(items)) } } } fn make_qualified_name(&mut self, parts: Self::Output) -> Self::Output { let pos = self.get_pos(parts); match parts { Node::List(nodes) => Node::QualifiedName(self.alloc((nodes, pos))), node if node.is_ignored() => Node::Ignored(SK::QualifiedName), node => Node::QualifiedName( self.alloc((bumpalo::vec![in self.arena; node].into_bump_slice(), pos)), ), } } fn make_module_name(&mut self, parts: Self::Output) -> Self::Output { let pos = self.get_pos(parts); match parts { Node::List(nodes) => Node::ModuleName(self.alloc((nodes, pos))), node if node.is_ignored() => Node::Ignored(SK::ModuleName), node => Node::ModuleName( self.alloc((bumpalo::vec![in self.arena; node].into_bump_slice(), pos)), ), } } fn make_simple_type_specifier(&mut self, specifier: Self::Output) -> Self::Output { // Return this explicitly because flatten filters out zero nodes, and // we treat most non-error nodes as zeroes. specifier } fn make_literal_expression(&mut self, expression: Self::Output) -> Self::Output { expression } fn make_simple_initializer( &mut self, equals: Self::Output, expr: Self::Output, ) -> Self::Output { // If the expr is Ignored, bubble up the assignment operator so that we // can tell that *some* initializer was here. Useful for class // properties, where we need to enforce that properties without default // values are initialized in the constructor. if expr.is_ignored() { equals } else { expr } } fn make_anonymous_function( &mut self, _attribute_spec: Self::Output, _async_keyword: Self::Output, _function_keyword: Self::Output, _left_paren: Self::Output, _parameters: Self::Output, _right_paren: Self::Output, _ctx_list: Self::Output, _colon: Self::Output, _readonly_return: Self::Output, _type_: Self::Output, _use_: Self::Output, _body: Self::Output, ) -> Self::Output { // do not allow Yield to bubble up Node::Ignored(SK::AnonymousFunction) } fn make_lambda_expression( &mut self, _attribute_spec: Self::Output, _async_: Self::Output, _signature: Self::Output, _arrow: Self::Output, _body: Self::Output, ) -> Self::Output { // do not allow Yield to bubble up Node::Ignored(SK::LambdaExpression) } fn make_awaitable_creation_expression( &mut self, _attribute_spec: Self::Output, _async_: Self::Output, _compound_statement: Self::Output, ) -> Self::Output { // do not allow Yield to bubble up Node::Ignored(SK::AwaitableCreationExpression) } fn make_element_initializer( &mut self, key: Self::Output, _arrow: Self::Output, value: Self::Output, ) -> Self::Output { Node::ListItem(self.alloc((key, value))) } fn make_prefix_unary_expression( &mut self, op: Self::Output, value: Self::Output, ) -> Self::Output { let pos = self.merge_positions(op, value); let op = match op.token_kind() { Some(TokenKind::Tilde) => Uop::Utild, Some(TokenKind::Exclamation) => Uop::Unot, Some(TokenKind::Plus) => Uop::Uplus, Some(TokenKind::Minus) => Uop::Uminus, Some(TokenKind::PlusPlus) => Uop::Uincr, Some(TokenKind::MinusMinus) => Uop::Udecr, Some(TokenKind::At) => Uop::Usilence, _ => return Node::Ignored(SK::PrefixUnaryExpression), }; let value = match self.node_to_expr(value) { Some(value) => value, None => return Node::Ignored(SK::PrefixUnaryExpression), }; Node::Expr(self.alloc(aast::Expr( (), pos, aast::Expr_::Unop(self.alloc((op, value))), ))) } fn make_postfix_unary_expression( &mut self, value: Self::Output, op: Self::Output, ) -> Self::Output { let pos = self.merge_positions(value, op); let op = match op.token_kind() { Some(TokenKind::PlusPlus) => Uop::Upincr, Some(TokenKind::MinusMinus) => Uop::Updecr, _ => return Node::Ignored(SK::PostfixUnaryExpression), }; let value = match self.node_to_expr(value) { Some(value) => value, None => return Node::Ignored(SK::PostfixUnaryExpression), }; Node::Expr(self.alloc(aast::Expr( (), pos, aast::Expr_::Unop(self.alloc((op, value))), ))) } fn make_binary_expression( &mut self, lhs: Self::Output, op_node: Self::Output, rhs: Self::Output, ) -> Self::Output { let op = match op_node.token_kind() { Some(TokenKind::Plus) => Bop::Plus, Some(TokenKind::Minus) => Bop::Minus, Some(TokenKind::Star) => Bop::Star, Some(TokenKind::Slash) => Bop::Slash, Some(TokenKind::Equal) => Bop::Eq(None), Some(TokenKind::EqualEqual) => Bop::Eqeq, Some(TokenKind::EqualEqualEqual) => Bop::Eqeqeq, Some(TokenKind::StarStar) => Bop::Starstar, Some(TokenKind::AmpersandAmpersand) => Bop::Ampamp, Some(TokenKind::BarBar) => Bop::Barbar, Some(TokenKind::LessThan) => Bop::Lt, Some(TokenKind::LessThanEqual) => Bop::Lte, Some(TokenKind::LessThanLessThan) => Bop::Ltlt, Some(TokenKind::GreaterThan) => Bop::Gt, Some(TokenKind::GreaterThanEqual) => Bop::Gte, Some(TokenKind::GreaterThanGreaterThan) => Bop::Gtgt, Some(TokenKind::Dot) => Bop::Dot, Some(TokenKind::Ampersand) => Bop::Amp, Some(TokenKind::Bar) => Bop::Bar, Some(TokenKind::Percent) => Bop::Percent, Some(TokenKind::QuestionQuestion) => Bop::QuestionQuestion, _ => return Node::Ignored(SK::BinaryExpression), }; match (&op, rhs.is_token(TokenKind::Yield)) { (Bop::Eq(_), true) => return rhs, _ => {} } let pos = self.merge(self.merge_positions(lhs, op_node), self.get_pos(rhs)); let lhs = match self.node_to_expr(lhs) { Some(lhs) => lhs, None => return Node::Ignored(SK::BinaryExpression), }; let rhs = match self.node_to_expr(rhs) { Some(rhs) => rhs, None => return Node::Ignored(SK::BinaryExpression), }; Node::Expr(self.alloc(aast::Expr( (), pos, aast::Expr_::Binop(self.alloc(aast::Binop { bop: op, lhs, rhs })), ))) } fn make_parenthesized_expression( &mut self, _lparen: Self::Output, expr: Self::Output, _rparen: Self::Output, ) -> Self::Output { if self.opts.keep_user_attributes { Node::Ignored(SK::ParenthesizedExpression) } else { expr } } fn make_enum_class_label_expression( &mut self, _class: Self::Output, _hash: Self::Output, label: Self::Output, ) -> Self::Output { // In case we want it later on, _class is either Ignored(Missing) // or a Name node, like label match label { Node::Name((lbl, _)) => Node::EnumClassLabel(lbl), _ => Node::Ignored(SK::EnumClassLabelExpression), } } fn make_list_item(&mut self, item: Self::Output, sep: Self::Output) -> Self::Output { match (item.is_ignored(), sep.is_ignored()) { (true, true) => Node::Ignored(SK::ListItem), (false, true) => item, (true, false) => sep, (false, false) => Node::ListItem(self.alloc((item, sep))), } } fn make_type_arguments( &mut self, less_than: Self::Output, arguments: Self::Output, greater_than: Self::Output, ) -> Self::Output { Node::BracketedList(self.alloc(( self.get_pos(less_than), arguments.as_slice(self.arena), self.get_pos(greater_than), ))) } fn make_generic_type_specifier( &mut self, class_type: Self::Output, type_arguments: Self::Output, ) -> Self::Output { let class_id = match self.expect_name(class_type) { Some(id) => id, None => return Node::Ignored(SK::GenericTypeSpecifier), }; match class_id.1.trim_start_matches('\\') { "varray_or_darray" | "vec_or_dict" => { let id_pos = class_id.0; let pos = self.merge(id_pos, self.get_pos(type_arguments)); let type_arguments = type_arguments.as_slice(self.arena); let ty_ = match type_arguments { [tk, tv] => Ty_::TvecOrDict( self.alloc(( self.node_to_ty(*tk) .unwrap_or_else(|| self.tany_with_pos(id_pos)), self.node_to_ty(*tv) .unwrap_or_else(|| self.tany_with_pos(id_pos)), )), ), [tv] => Ty_::TvecOrDict( self.alloc(( self.vec_or_dict_key(pos), self.node_to_ty(*tv) .unwrap_or_else(|| self.tany_with_pos(id_pos)), )), ), _ => TANY_, }; self.hint_ty(pos, ty_) } _ => { let Id(pos, class_type) = class_id; match class_type.rsplit('\\').next() { Some(name) if self.is_type_param_in_scope(name) => { let pos = self.merge(pos, self.get_pos(type_arguments)); let type_arguments = self.slice( type_arguments .iter() .filter_map(|&node| self.node_to_ty(node)), ); let ty_ = Ty_::Tgeneric(self.alloc((name, type_arguments))); self.hint_ty(pos, ty_) } _ => { let class_type = self.elaborate_raw_id(class_type); self.make_apply( (pos, class_type), type_arguments, self.get_pos(type_arguments), ) } } } } } fn make_alias_declaration( &mut self, attributes: Self::Output, modifiers: Self::Output, module_kw_opt: Self::Output, keyword: Self::Output, name: Self::Output, generic_params: Self::Output, constraint: Self::Output, _equal: Self::Output, aliased_type: Self::Output, _semicolon: Self::Output, ) -> Self::Output { if name.is_ignored() { return Node::Ignored(SK::AliasDeclaration); } let Id(pos, name) = match self.elaborate_defined_id(name) { Some(id) => id, None => return Node::Ignored(SK::AliasDeclaration), }; let ty = match self.node_to_ty(aliased_type) { Some(ty) => ty, None => return Node::Ignored(SK::AliasDeclaration), }; let mut as_constraint = None; let mut super_constraint = None; for c in constraint.iter() { if let Node::TypeConstraint(&(kind, hint)) = c { let ty = self.node_to_ty(hint); match kind { ConstraintKind::ConstraintAs => as_constraint = ty, ConstraintKind::ConstraintSuper => super_constraint = ty, _ => {} } } } // Pop the type params stack only after creating all inner types. let tparams = self.pop_type_params(generic_params); // Parse the user attributes // in facts-mode all attributes are saved, otherwise only __NoAutoDynamic/__NoAutoLikes is let user_attributes = self.slice(attributes.iter().rev().filter_map(|attribute| { if let Node::Attribute(attr) = attribute { if self.opts.keep_user_attributes || is_no_auto_attribute(attr.name.1) { Some(self.user_attribute_to_decl(attr)) } else { None } } else { None } })); let mut docs_url = None; for attribute in attributes.iter() { match attribute { Node::Attribute(attr) => { if attr.name.1 == "__Docs" { if let Some((_, bstr)) = attr.string_literal_param { docs_url = Some(self.str_from_utf8_for_bytes_in_arena(bstr)); } } } _ => {} } } let internal = modifiers .iter() .any(|m| m.as_visibility() == Some(aast::Visibility::Internal)); let is_module_newtype = module_kw_opt.is_ignored_token_with_kind(TokenKind::Module); let typedef = self.alloc(TypedefType { module: self.module, pos, vis: match keyword.token_kind() { Some(TokenKind::Type) => aast::TypedefVisibility::Transparent, Some(TokenKind::Newtype) if is_module_newtype => { aast::TypedefVisibility::OpaqueModule } Some(TokenKind::Newtype) => aast::TypedefVisibility::Opaque, _ => aast::TypedefVisibility::Transparent, }, tparams, as_constraint, super_constraint, type_: ty, is_ctx: false, attributes: user_attributes, internal, docs_url, }); let this = Rc::make_mut(&mut self.state); this.add_typedef(name, typedef); Node::Ignored(SK::AliasDeclaration) } fn make_context_alias_declaration( &mut self, attributes: Self::Output, _keyword: Self::Output, name: Self::Output, generic_params: Self::Output, constraint: Self::Output, _equal: Self::Output, ctx_list: Self::Output, _semicolon: Self::Output, ) -> Self::Output { if name.is_ignored() { return Node::Ignored(SK::ContextAliasDeclaration); } let Id(pos, name) = match self.elaborate_defined_id(name) { Some(id) => id, None => return Node::Ignored(SK::ContextAliasDeclaration), }; let ty = match self.node_to_ty(ctx_list) { Some(ty) => ty, None => self.alloc(Ty( self.alloc(Reason::hint(pos)), Ty_::Tapply(self.alloc(((pos, "\\HH\\Contexts\\defaults"), &[]))), )), }; // lowerer ensures there is only one as constraint let mut as_constraint = None; let mut super_constraint = None; for c in constraint.iter() { if let Node::ContextConstraint(&(kind, hint)) = c { let ty = self.node_to_ty(hint); match kind { ConstraintKind::ConstraintAs => as_constraint = ty, ConstraintKind::ConstraintSuper => super_constraint = ty, _ => {} } } } // Pop the type params stack only after creating all inner types. let tparams = self.pop_type_params(generic_params); let user_attributes = if self.opts.keep_user_attributes { self.slice(attributes.iter().rev().filter_map(|attribute| { if let Node::Attribute(attr) = attribute { Some(self.user_attribute_to_decl(attr)) } else { None } })) } else { &[][..] }; let typedef = self.alloc(TypedefType { module: self.module, pos, vis: aast::TypedefVisibility::Opaque, tparams, as_constraint, super_constraint, type_: ty, is_ctx: true, attributes: user_attributes, internal: false, docs_url: None, }); let this = Rc::make_mut(&mut self.state); this.add_typedef(name, typedef); Node::Ignored(SK::ContextAliasDeclaration) } fn make_case_type_declaration( &mut self, attribute_spec: Self::Output, modifiers: Self::Output, _case_keyword: Self::Output, _type_keyword: Self::Output, name: Self::Output, generic_parameter: Self::Output, _as: Self::Output, bounds: Self::Output, _equal: Self::Output, variants: Self::Output, _semicolon: Self::Output, ) -> Self::Output { if name.is_ignored() { return Node::Ignored(SK::CaseTypeDeclaration); } let Id(pos, name) = match self.elaborate_defined_id(name) { Some(id) => id, None => return Node::Ignored(SK::CaseTypeDeclaration), }; let as_constraint = match bounds.len() { 0 => None, 1 => self.node_to_ty(*bounds.iter().next().unwrap()), _ => { let pos = self.get_pos(bounds); let tys = self.slice(bounds.iter().filter_map(|x| match x { Node::ListItem(&(ty, _commas)) => self.node_to_ty(ty), &x => self.node_to_ty(x), })); Some(self.alloc(Ty(self.alloc(Reason::hint(pos)), Ty_::Tintersection(tys)))) } }; let ty = match variants.len() { 0 => None, 1 => self.node_to_ty(*variants.iter().next().unwrap()), _ => { let pos = self.get_pos(variants); let tys = self.slice(variants.iter().filter_map(|x| self.node_to_ty(*x))); Some(self.alloc(Ty(self.alloc(Reason::hint(pos)), Ty_::Tunion(tys)))) } }; let type_ = match ty { Some(x) => x, None => return Node::Ignored(SK::CaseTypeDeclaration), }; // Pop the type params stack only after creating all inner types. let tparams = self.pop_type_params(generic_parameter); // Parse the user attributes // in facts-mode all attributes are saved, otherwise only __NoAutoDynamic/__NoAutoLikes is let user_attributes = self.slice(attribute_spec.iter().rev().filter_map(|attribute| { if let Node::Attribute(attr) = attribute { if self.opts.keep_user_attributes || is_no_auto_attribute(attr.name.1) { Some(self.user_attribute_to_decl(attr)) } else { None } } else { None } })); let mut docs_url = None; for attribute in attribute_spec.iter() { match attribute { Node::Attribute(attr) => { if attr.name.1 == "__Docs" { if let Some((_, bstr)) = attr.string_literal_param { docs_url = Some(self.str_from_utf8_for_bytes_in_arena(bstr)); } } } _ => {} } } let internal = modifiers .iter() .any(|m| m.as_visibility() == Some(aast::Visibility::Internal)); let typedef = self.alloc(TypedefType { module: self.module, pos, vis: aast::TypedefVisibility::CaseType, tparams, as_constraint, super_constraint: None, type_, is_ctx: false, attributes: user_attributes, internal, docs_url, }); let this = Rc::make_mut(&mut self.state); this.add_typedef(name, typedef); Node::Ignored(SK::CaseTypeDeclaration) } fn make_case_type_variant(&mut self, _bar: Self::Output, type_: Self::Output) -> Self::Output { if type_.is_ignored() { Node::Ignored(SK::CaseTypeVariant) } else { type_ } } fn make_type_constraint(&mut self, kind: Self::Output, value: Self::Output) -> Self::Output { let kind = match kind.token_kind() { Some(TokenKind::As) => ConstraintKind::ConstraintAs, Some(TokenKind::Super) => ConstraintKind::ConstraintSuper, _ => return Node::Ignored(SK::TypeConstraint), }; Node::TypeConstraint(self.alloc((kind, value))) } fn make_context_constraint(&mut self, kind: Self::Output, value: Self::Output) -> Self::Output { let kind = match kind.token_kind() { Some(TokenKind::As) => ConstraintKind::ConstraintAs, Some(TokenKind::Super) => ConstraintKind::ConstraintSuper, _ => return Node::Ignored(SK::ContextConstraint), }; Node::ContextConstraint(self.alloc((kind, value))) } fn make_type_parameter( &mut self, user_attributes: Self::Output, reify: Self::Output, variance: Self::Output, name: Self::Output, tparam_params: Self::Output, constraints: Self::Output, ) -> Self::Output { let user_attributes = match user_attributes { Node::BracketedList((_, attributes, _)) => { self.slice(attributes.iter().filter_map(|x| match x { Node::Attribute(a) => Some(*a), _ => None, })) } _ => &[][..], }; let constraints = self.slice(constraints.iter().filter_map(|node| match node { Node::TypeConstraint(&constraint) => Some(constraint), _ => None, })); // TODO(T70068435) Once we add support for constraints on higher-kinded types // (in particular, constraints on nested type parameters), we need to ensure // that we correctly handle the scoping of nested type parameters. // This includes making sure that the call to convert_type_appl_to_generic // in make_type_parameters handles nested constraints. // For now, we just make sure that the nested type parameters that make_type_parameters // added to the global list of in-scope type parameters are removed immediately: self.pop_type_params(tparam_params); let tparam_params = match tparam_params { Node::TypeParameters(&params) => params, _ => &[], }; Node::TypeParameter(self.alloc(TypeParameterDecl { name, variance: match variance.token_kind() { Some(TokenKind::Minus) => Variance::Contravariant, Some(TokenKind::Plus) => Variance::Covariant, _ => Variance::Invariant, }, reified: if reify.is_token(TokenKind::Reify) { if user_attributes.iter().any(|node| node.name.1 == "__Soft") { aast::ReifyKind::SoftReified } else { aast::ReifyKind::Reified } } else { aast::ReifyKind::Erased }, constraints, tparam_params, user_attributes, })) } fn make_type_parameters( &mut self, _lt: Self::Output, tparams: Self::Output, _gt: Self::Output, ) -> Self::Output { let size = tparams.len(); let mut tparams_with_name = bump::Vec::with_capacity_in(size, self.arena); let mut tparam_names = MultiSetMut::with_capacity_in(size, self.arena); for node in tparams.iter() { match *node { Node::TypeParameter(decl) => { let name = match decl.name.as_id() { Some(name) => name, None => return Node::Ignored(SK::TypeParameters), }; tparam_names.insert(name.1); tparams_with_name.push((decl, name)); } _ => {} } } let this = Rc::make_mut(&mut self.state); Rc::make_mut(&mut this.type_parameters).push(tparam_names.into()); let mut tparams = bump::Vec::with_capacity_in(tparams_with_name.len(), self.arena); for (decl, name) in tparams_with_name.into_iter() { let &TypeParameterDecl { name: _, variance, reified, constraints, tparam_params, user_attributes, } = decl; let constraints = self.slice(constraints.iter().filter_map(|constraint| { let &(kind, ty) = constraint; let ty = self.node_to_ty(ty)?; let ty = self.convert_tapply_to_tgeneric(ty); Some((kind, ty)) })); let user_attributes = self.slice( user_attributes .iter() .rev() .map(|x| self.user_attribute_to_decl(x)), ); tparams.push(self.alloc(Tparam { variance, name: name.into(), constraints, reified, user_attributes, tparams: tparam_params, })); } Node::TypeParameters(self.alloc(tparams.into_bump_slice())) } fn make_parameter_declaration( &mut self, attributes: Self::Output, visibility: Self::Output, inout: Self::Output, readonly: Self::Output, hint: Self::Output, name: Self::Output, initializer: Self::Output, ) -> Self::Output { let (variadic, pos, name) = match name { Node::ListItem(&(ellipsis, id)) => { let Id(pos, name) = match id.as_variable() { Some(id) => id, None => return Node::Ignored(SK::ParameterDeclaration), }; let variadic = ellipsis.is_token(TokenKind::DotDotDot); (variadic, pos, Some(name)) } name => { let Id(pos, name) = match name.as_variable() { Some(id) => id, None => return Node::Ignored(SK::ParameterDeclaration), }; (false, pos, Some(name)) } }; let kind = if inout.is_token(TokenKind::Inout) { ParamMode::FPinout } else { ParamMode::FPnormal }; let is_readonly = readonly.is_token(TokenKind::Readonly); let hint = if self.opts.interpret_soft_types_as_like_types { let attributes = self.to_attributes(attributes); if attributes.soft { match hint { Node::Ty(ty) => self.hint_ty(self.get_pos(hint), Ty_::Tlike(ty)), _ => hint, } } else { hint } } else { hint }; Node::FunParam(self.alloc(FunParamDecl { attributes, visibility, kind, readonly: is_readonly, hint, pos, name, variadic, initializer, })) } fn make_variadic_parameter( &mut self, _: Self::Output, hint: Self::Output, ellipsis: Self::Output, ) -> Self::Output { Node::FunParam( self.alloc(FunParamDecl { attributes: Node::Ignored(SK::Missing), visibility: Node::Ignored(SK::Missing), kind: ParamMode::FPnormal, readonly: false, hint, pos: self .get_pos_opt(hint) .unwrap_or_else(|| self.get_pos(ellipsis)), name: None, variadic: true, initializer: Node::Ignored(SK::Missing), }), ) } fn make_function_declaration( &mut self, attributes: Self::Output, header: Self::Output, body: Self::Output, ) -> Self::Output { let parsed_attributes = self.to_attributes(attributes); match header { Node::FunctionHeader(header) => { let is_method = false; let ((pos, name), type_, _) = match self.function_to_ty(is_method, attributes, header, body) { Some(x) => x, None => return Node::Ignored(SK::FunctionDeclaration), }; let deprecated = parsed_attributes.deprecated.map(|msg| { let mut s = bump::String::new_in(self.arena); s.push_str("The function "); s.push_str(name.trim_start_matches('\\')); s.push_str(" is deprecated: "); s.push_str(msg); s.into_bump_str() }); let internal = header .modifiers .iter() .any(|m| m.as_visibility() == Some(aast::Visibility::Internal)); let fun_elt = self.alloc(FunElt { module: self.module, internal, deprecated, type_, pos, php_std_lib: parsed_attributes.php_std_lib, support_dynamic_type: self.implicit_sdt() || parsed_attributes.support_dynamic_type, no_auto_dynamic: self.under_no_auto_dynamic, no_auto_likes: parsed_attributes.no_auto_likes, }); let this = Rc::make_mut(&mut self.state); this.add_fun(name, fun_elt); Node::Ignored(SK::FunctionDeclaration) } _ => Node::Ignored(SK::FunctionDeclaration), } } fn make_contexts( &mut self, left_bracket: Self::Output, tys: Self::Output, right_bracket: Self::Output, ) -> Self::Output { let tys = self.slice(tys.iter().filter_map(|ty| match ty { Node::ListItem(&(ty, _)) | &ty => { // A wildcard is used for the context of a closure type on a // parameter of a function with a function context (e.g., // `function f((function ()[_]: void) $f)[ctx $f]: void {}`). if let Some(Id(pos, "_")) = self.expect_name(ty) { return Some(self.alloc(Ty( self.alloc(Reason::hint(pos)), Ty_::Tapply(self.alloc(((pos, "_"), &[]))), ))); } let ty = self.node_to_ty(ty)?; match ty.1 { // Only three forms of type can appear here in a valid program: // - function contexts (`ctx $f`) // - value-dependent paths (`$v::C`) // - built-in contexts (`rx`, `cipp_of<EntFoo>`) // The first and last will be represented with `Tapply`, // but function contexts will use a variable name // (containing a `$`). Built-in contexts are always in the // \HH\Contexts namespace, so we rewrite those names here. Ty_::Tapply(&((pos, name), targs)) if !name.starts_with('$') => { // The name will have been elaborated in the current // namespace, but we actually want it to be in the // \HH\Contexts namespace. Grab the last component of // the name, and rewrite it in the correct namespace. // Note that this makes it impossible to express names // in any sub-namespace of \HH\Contexts (e.g., // "Unsafe\\cipp" will be rewritten as // "\\HH\\Contexts\\cipp" rather than // "\\HH\\Contexts\\Unsafe\\cipp"). let name = match name.trim_end_matches('\\').split('\\').next_back() { Some(ctxname) => match ctxname.chars().next() { Some(first_char) if first_char.is_lowercase() => { self.concat("\\HH\\Contexts\\", ctxname) } Some(_) | None => name, }, None => name, }; Some(self.alloc(Ty(ty.0, Ty_::Tapply(self.alloc(((pos, name), targs)))))) } _ => Some(ty), } } })); /* Like in as_fun_implicit_params, we keep the intersection as is: we do not simplify * empty or singleton intersections. */ let pos = self.merge_positions(left_bracket, right_bracket); self.hint_ty(pos, Ty_::Tintersection(tys)) } fn make_function_ctx_type_specifier( &mut self, ctx_keyword: Self::Output, variable: Self::Output, ) -> Self::Output { match variable.as_variable() { Some(Id(pos, name)) => { Node::Variable(self.alloc((name, self.merge(pos, self.get_pos(ctx_keyword))))) } None => Node::Ignored(SK::FunctionCtxTypeSpecifier), } } fn make_function_declaration_header( &mut self, modifiers: Self::Output, _keyword: Self::Output, name: Self::Output, type_params: Self::Output, left_paren: Self::Output, param_list: Self::Output, _right_paren: Self::Output, capability: Self::Output, _colon: Self::Output, readonly_return: Self::Output, ret_hint: Self::Output, where_constraints: Self::Output, ) -> Self::Output { // Use the position of the left paren if the name is missing. // Keep the name if it's an IgnoredToken rather than an Ignored. An // IgnoredToken here should always be an error, but it's better to treat // a keyword as a name than to claim the function has no name at all. let name = if matches!(name, Node::Ignored(..)) { left_paren } else { name }; Node::FunctionHeader(self.alloc(FunctionHeader { name, modifiers, type_params, param_list, capability, ret_hint, readonly_return, where_constraints, })) } fn make_yield_expression( &mut self, keyword: Self::Output, _operand: Self::Output, ) -> Self::Output { assert!(keyword.token_kind() == Some(TokenKind::Yield)); keyword } fn make_const_declaration( &mut self, _attributes: Self::Output, modifiers: Self::Output, const_keyword: Self::Output, hint: Self::Output, decls: Self::Output, semicolon: Self::Output, ) -> Self::Output { match decls { // Class consts. Node::List(consts) if self.classish_name_builder.is_some() => { let ty = self.node_to_ty(hint); Node::List( self.alloc(self.slice(consts.iter().filter_map(|cst| match cst { Node::ConstInitializer(&(name, initializer, refs)) => { let id = name.as_id()?; let modifiers = read_member_modifiers(modifiers.iter()); let abstract_ = if modifiers.is_abstract { ClassConstKind::CCAbstract(!initializer.is_ignored()) } else { ClassConstKind::CCConcrete }; let ty = ty .or_else(|| self.infer_const(name, initializer)) .unwrap_or(TANY); Some(Node::Const(self.alloc( shallow_decl_defs::ShallowClassConst { abstract_, name: id.into(), type_: ty, refs, }, ))) } _ => None, }))), ) } // Global consts. Node::List(consts) => { // This case always returns Node::Ignored, // but has the side effect of calling self.add_const // Note: given "const int X=1,Y=2;", the legacy decl-parser // allows both decls, and it gives them both an identical text-span - // from start of "const" to end of semicolon. This is a bug but // the code here preserves it. let pos = self.merge_positions(const_keyword, semicolon); for cst in consts.iter() { match cst { Node::ConstInitializer(&(name, initializer, _refs)) => { if let Some(Id(id_pos, id)) = self.elaborate_defined_id(name) { let ty = self .node_to_ty(hint) .or_else(|| self.infer_const(name, initializer)) .unwrap_or_else(|| self.tany_with_pos(id_pos)); let this = Rc::make_mut(&mut self.state); this.add_const(id, this.alloc(ConstDecl { pos, type_: ty })); } } _ => {} } } Node::Ignored(SK::ConstDeclaration) } _ => Node::Ignored(SK::ConstDeclaration), } } fn begin_constant_declarator(&mut self) { self.start_accumulating_const_refs(); } fn make_constant_declarator( &mut self, name: Self::Output, initializer: Self::Output, ) -> Self::Output { // The "X=1" part of either a member const "class C {const int X=1;}" or a top-level const "const int X=1;" // Note: the the declarator itself doesn't yet know whether a type was provided by the user; // that's only known in the parent, make_const_declaration let refs = self.stop_accumulating_const_refs(); if name.is_ignored() { Node::Ignored(SK::ConstantDeclarator) } else { Node::ConstInitializer(self.alloc((name, initializer, refs))) } } fn make_namespace_declaration( &mut self, _name: Self::Output, body: Self::Output, ) -> Self::Output { if let Node::Ignored(SK::NamespaceBody) = body { let this = Rc::make_mut(&mut self.state); Rc::make_mut(&mut this.namespace_builder).pop_namespace(); } Node::Ignored(SK::NamespaceDeclaration) } fn make_namespace_declaration_header( &mut self, _keyword: Self::Output, name: Self::Output, ) -> Self::Output { let name = self.expect_name(name).map(|Id(_, name)| name); // if this is header of semicolon-style (one with NamespaceEmptyBody) namespace, we should pop // the previous namespace first, but we don't have the body yet. We'll fix it retroactively in // make_namespace_empty_body let this = Rc::make_mut(&mut self.state); Rc::make_mut(&mut this.namespace_builder).push_namespace(name); Node::Ignored(SK::NamespaceDeclarationHeader) } fn make_namespace_body( &mut self, _left_brace: Self::Output, _declarations: Self::Output, _right_brace: Self::Output, ) -> Self::Output { Node::Ignored(SK::NamespaceBody) } fn make_namespace_empty_body(&mut self, _semicolon: Self::Output) -> Self::Output { let this = Rc::make_mut(&mut self.state); Rc::make_mut(&mut this.namespace_builder).pop_previous_namespace(); Node::Ignored(SK::NamespaceEmptyBody) } fn make_namespace_use_declaration( &mut self, _keyword: Self::Output, namespace_use_kind: Self::Output, clauses: Self::Output, _semicolon: Self::Output, ) -> Self::Output { if let Some(import_kind) = Self::namespace_use_kind(&namespace_use_kind) { for clause in clauses.iter() { if let Node::NamespaceUseClause(nuc) = clause { let this = Rc::make_mut(&mut self.state); Rc::make_mut(&mut this.namespace_builder).add_import( import_kind, nuc.id.1, nuc.as_, ); } } } Node::Ignored(SK::NamespaceUseDeclaration) } fn make_namespace_group_use_declaration( &mut self, _keyword: Self::Output, _kind: Self::Output, prefix: Self::Output, _left_brace: Self::Output, clauses: Self::Output, _right_brace: Self::Output, _semicolon: Self::Output, ) -> Self::Output { let Id(_, prefix) = match self.expect_name(prefix) { Some(id) => id, None => return Node::Ignored(SK::NamespaceGroupUseDeclaration), }; for clause in clauses.iter() { if let Node::NamespaceUseClause(nuc) = clause { let mut id = bump::String::new_in(self.arena); id.push_str(prefix); id.push_str(nuc.id.1); let this = Rc::make_mut(&mut self.state); Rc::make_mut(&mut this.namespace_builder).add_import( nuc.kind, id.into_bump_str(), nuc.as_, ); } } Node::Ignored(SK::NamespaceGroupUseDeclaration) } fn make_namespace_use_clause( &mut self, clause_kind: Self::Output, name: Self::Output, as_: Self::Output, aliased_name: Self::Output, ) -> Self::Output { let id = match self.expect_name(name) { Some(id) => id, None => return Node::Ignored(SK::NamespaceUseClause), }; let as_ = if as_.is_token(TokenKind::As) { match aliased_name.as_id() { Some(name) => Some(name.1), None => return Node::Ignored(SK::NamespaceUseClause), } } else { None }; if let Some(kind) = Self::namespace_use_kind(&clause_kind) { Node::NamespaceUseClause(self.alloc(NamespaceUseClause { kind, id, as_ })) } else { Node::Ignored(SK::NamespaceUseClause) } } fn make_where_clause( &mut self, _: Self::Output, where_constraints: Self::Output, ) -> Self::Output { where_constraints } fn make_where_constraint( &mut self, left_type: Self::Output, operator: Self::Output, right_type: Self::Output, ) -> Self::Output { Node::WhereConstraint(self.alloc(WhereConstraint( self.node_to_ty(left_type).unwrap_or(TANY), match operator.token_kind() { Some(TokenKind::Equal) => ConstraintKind::ConstraintEq, Some(TokenKind::Super) => ConstraintKind::ConstraintSuper, _ => ConstraintKind::ConstraintAs, }, self.node_to_ty(right_type).unwrap_or(TANY), ))) } fn make_classish_declaration( &mut self, attributes: Self::Output, modifiers: Self::Output, xhp_keyword: Self::Output, class_keyword: Self::Output, name: Self::Output, tparams: Self::Output, _extends_keyword: Self::Output, extends: Self::Output, _implements_keyword: Self::Output, implements: Self::Output, where_clause: Self::Output, body: Self::Output, ) -> Self::Output { let raw_name = match self.expect_name(name) { Some(Id(_, name)) => name, None => return Node::Ignored(SK::ClassishDeclaration), }; let Id(pos, name) = match self.elaborate_defined_id(name) { Some(id) => id, None => return Node::Ignored(SK::ClassishDeclaration), }; let is_xhp = raw_name.starts_with(':') || xhp_keyword.is_present(); let mut final_ = false; let mut abstract_ = false; let mut internal = false; for modifier in modifiers.iter() { match modifier.token_kind() { Some(TokenKind::Abstract) => { abstract_ = true; } Some(TokenKind::Final) => final_ = true, Some(TokenKind::Internal) => internal = true, _ => {} } } let class_kind = match class_keyword.token_kind() { Some(TokenKind::Interface) => ClassishKind::Cinterface, Some(TokenKind::Trait) => ClassishKind::Ctrait, _ => ClassishKind::Cclass(if abstract_ { Abstraction::Abstract } else { Abstraction::Concrete }), }; let where_constraints = self.slice(where_clause.iter().filter_map(|&x| match x { Node::WhereConstraint(x) => Some(x), _ => None, })); let body = match body { Node::ClassishBody(body) => body, _ => return Node::Ignored(SK::ClassishDeclaration), }; let mut uses_len = 0; let mut xhp_attr_uses_len = 0; let mut xhp_enum_values = SMap::empty(); let mut xhp_marked_empty = false; let mut req_extends_len = 0; let mut req_implements_len = 0; let mut req_class_len = 0; let mut consts_len = 0; let mut typeconsts_len = 0; let mut props_len = 0; let mut sprops_len = 0; let mut static_methods_len = 0; let mut methods_len = 0; let mut user_attributes_len = 0; for attribute in attributes.iter() { match *attribute { Node::Attribute(..) => user_attributes_len += 1, _ => {} } } for element in body.iter().copied() { match element { Node::TraitUse(names) => uses_len += names.len(), Node::XhpClassAttributeDeclaration(&XhpClassAttributeDeclarationNode { xhp_attr_decls, xhp_attr_uses_decls, xhp_attr_enum_values, }) => { props_len += xhp_attr_decls.len(); xhp_attr_uses_len += xhp_attr_uses_decls.len(); for (name, values) in xhp_attr_enum_values { xhp_enum_values = xhp_enum_values.add(self.arena, name, *values); } } Node::XhpChildrenDeclaration(XhpChildrenKind::Empty) => { xhp_marked_empty = true; } Node::TypeConstant(..) => typeconsts_len += 1, Node::RequireClause(require) => match require.require_type.token_kind() { Some(TokenKind::Extends) => req_extends_len += 1, Some(TokenKind::Implements) => req_implements_len += 1, Some(TokenKind::Class) => req_class_len += 1, _ => {} }, Node::List(consts @ [Node::Const(..), ..]) => consts_len += consts.len(), Node::Property(&PropertyNode { decls, is_static }) => { if is_static { sprops_len += decls.len() } else { props_len += decls.len() } } Node::Constructor(&ConstructorNode { properties, .. }) => { props_len += properties.len() } Node::Method(&MethodNode { is_static, .. }) => { if is_static { static_methods_len += 1 } else { methods_len += 1 } } _ => {} } } let mut constructor = None; let mut uses = bump::Vec::with_capacity_in(uses_len, self.arena); let mut xhp_attr_uses = bump::Vec::with_capacity_in(xhp_attr_uses_len, self.arena); let mut req_extends = bump::Vec::with_capacity_in(req_extends_len, self.arena); let mut req_implements = bump::Vec::with_capacity_in(req_implements_len, self.arena); let mut req_class = bump::Vec::with_capacity_in(req_class_len, self.arena); let mut consts = bump::Vec::with_capacity_in(consts_len, self.arena); let mut typeconsts = bump::Vec::with_capacity_in(typeconsts_len, self.arena); let mut props = bump::Vec::with_capacity_in(props_len, self.arena); let mut sprops = bump::Vec::with_capacity_in(sprops_len, self.arena); let mut static_methods = bump::Vec::with_capacity_in(static_methods_len, self.arena); let mut methods = bump::Vec::with_capacity_in(methods_len, self.arena); let mut user_attributes = bump::Vec::with_capacity_in(user_attributes_len, self.arena); let mut docs_url = None; for attribute in attributes.iter() { match attribute { Node::Attribute(attr) => { if attr.name.1 == "__Docs" { if let Some((_, bstr)) = attr.string_literal_param { docs_url = Some(self.str_from_utf8_for_bytes_in_arena(bstr)); } } user_attributes.push(self.user_attribute_to_decl(attr)); } _ => {} } } // Match ordering of attributes produced by the OCaml decl parser (even // though it's the reverse of the syntactic ordering). user_attributes.reverse(); let class_attributes = self.to_attributes(attributes); // xhp props go after regular props, regardless of their order in file let mut xhp_props = vec![]; for element in body.iter().copied() { match element { Node::TraitUse(names) => { uses.extend(names.iter().filter_map(|&name| self.node_to_ty(name))) } Node::XhpClassAttributeDeclaration(&XhpClassAttributeDeclarationNode { xhp_attr_decls, xhp_attr_uses_decls, .. }) => { xhp_props.extend(xhp_attr_decls); xhp_attr_uses.extend( xhp_attr_uses_decls .iter() .filter_map(|&node| self.node_to_ty(node)), ) } Node::TypeConstant(constant) => typeconsts.push(constant), Node::RequireClause(require) => match require.require_type.token_kind() { Some(TokenKind::Extends) => { req_extends.extend(self.node_to_ty(require.name).iter()) } Some(TokenKind::Implements) => { req_implements.extend(self.node_to_ty(require.name).iter()) } Some(TokenKind::Class) => { req_class.extend(self.node_to_ty(require.name).iter()) } _ => {} }, Node::List(&const_nodes @ [Node::Const(..), ..]) => { for node in const_nodes { if let Node::Const(decl) = *node { consts.push(decl) } } } Node::Property(&PropertyNode { decls, is_static }) => { for property in decls { if is_static { sprops.push(property) } else { props.push(property) } } } Node::Constructor(&ConstructorNode { method, properties }) => { constructor = Some(method); for property in properties { props.push(property) } } Node::Method(&MethodNode { method, is_static }) => { // Annoyingly, the <<__SupportDynamicType>> annotation on a // class implicitly changes the decls of every method inside // it, so we have to reallocate them here. let method = if (self.implicit_sdt() || class_attributes.support_dynamic_type) && !method.flags.contains(MethodFlags::SUPPORT_DYNAMIC_TYPE) { let type_ = match method.type_.1 { Ty_::Tfun(ft) => { let flags = ft.flags | FunTypeFlags::SUPPORT_DYNAMIC_TYPE; let ft = self.alloc(FunType { flags, ..*ft }); self.alloc(Ty(method.type_.0, Ty_::Tfun(ft))) } _ => method.type_, }; let flags = method.flags | MethodFlags::SUPPORT_DYNAMIC_TYPE; self.alloc(ShallowMethod { type_, flags, ..*method }) } else { method }; if is_static { static_methods.push(method); } else { methods.push(method); } } _ => {} // It's not our job to report errors here. } } props.extend(xhp_props.into_iter()); if class_attributes.const_ { for prop in props.iter_mut() { if !prop.flags.contains(PropFlags::CONST) { *prop = self.alloc(ShallowProp { flags: prop.flags | PropFlags::CONST, ..**prop }) } } } let uses = uses.into_bump_slice(); let xhp_attr_uses = xhp_attr_uses.into_bump_slice(); let xhp_enum_values = xhp_enum_values; let req_extends = req_extends.into_bump_slice(); let req_implements = req_implements.into_bump_slice(); let req_class = req_class.into_bump_slice(); let consts = consts.into_bump_slice(); let typeconsts = typeconsts.into_bump_slice(); let props = props.into_bump_slice(); let sprops = sprops.into_bump_slice(); let static_methods = static_methods.into_bump_slice(); let methods = methods.into_bump_slice(); let user_attributes = user_attributes.into_bump_slice(); let extends = self.slice(extends.iter().filter_map(|&node| self.node_to_ty(node))); let implements = self.slice(implements.iter().filter_map(|&node| self.node_to_ty(node))); let support_dynamic_type = self.implicit_sdt() || class_attributes.support_dynamic_type; // Pop the type params stack only after creating all inner types. let tparams = self.pop_type_params(tparams); let module = self.module; let cls = self.alloc(shallow_decl_defs::ShallowClass { mode: self.file_mode, final_, abstract_, is_xhp, has_xhp_keyword: xhp_keyword.is_token(TokenKind::XHP), kind: class_kind, module, internal, name: (pos, name), tparams, where_constraints, extends, uses, xhp_attr_uses, xhp_enum_values, xhp_marked_empty, req_extends, req_implements, req_class, implements, support_dynamic_type, consts, typeconsts, props, sprops, constructor, static_methods, methods, user_attributes, enum_type: None, docs_url, }); let this = Rc::make_mut(&mut self.state); this.add_class(name, cls); this.classish_name_builder = None; Node::Ignored(SK::ClassishDeclaration) } fn make_property_declaration( &mut self, attrs: Self::Output, modifiers: Self::Output, hint: Self::Output, declarators: Self::Output, _semicolon: Self::Output, ) -> Self::Output { let (attrs, modifiers, hint) = (attrs, modifiers, hint); let modifiers = read_member_modifiers(modifiers.iter()); let declarators = self.slice(declarators.iter().filter_map( |declarator| match declarator { Node::ListItem(&(name, initializer)) => { let attributes = self.to_attributes(attrs); let Id(pos, name) = name.as_variable()?; let name = if modifiers.is_static { name } else { strip_dollar_prefix(name) }; let ty = self.node_to_non_ret_ty(hint); let ty = ty.unwrap_or_else(|| self.tany_with_pos(pos)); let ty = if self.opts.interpret_soft_types_as_like_types { if attributes.soft { self.alloc(Ty( self.alloc(Reason::hint(self.get_pos(hint))), Ty_::Tlike(ty), )) } else { ty } } else { ty }; let needs_init = if self.file_mode == Mode::Mhhi { false } else { initializer.is_ignored() }; let mut flags = PropFlags::empty(); flags.set(PropFlags::CONST, attributes.const_); flags.set(PropFlags::LATEINIT, attributes.late_init); flags.set(PropFlags::LSB, attributes.lsb); flags.set(PropFlags::NEEDS_INIT, needs_init); flags.set(PropFlags::ABSTRACT, modifiers.is_abstract); flags.set(PropFlags::READONLY, modifiers.is_readonly); flags.set(PropFlags::PHP_STD_LIB, attributes.php_std_lib); flags.set( PropFlags::SAFE_GLOBAL_VARIABLE, attributes.safe_global_variable, ); flags.set(PropFlags::NO_AUTO_LIKES, attributes.no_auto_likes); Some(ShallowProp { xhp_attr: None, name: (pos, name), type_: ty, visibility: modifiers.visibility, flags, }) } _ => None, }, )); Node::Property(self.alloc(PropertyNode { decls: declarators, is_static: modifiers.is_static, })) } fn make_xhp_children_declaration( &mut self, _keyword: Self::Output, expression: Self::Output, _semicolon: Self::Output, ) -> Self::Output { match expression { Node::IgnoredToken(token) if token.kind() == TokenKind::Empty => { Node::XhpChildrenDeclaration(XhpChildrenKind::Empty) } _ => Node::XhpChildrenDeclaration(XhpChildrenKind::Other), } } fn make_xhp_class_attribute_declaration( &mut self, _keyword: Self::Output, attributes: Self::Output, _semicolon: Self::Output, ) -> Self::Output { let mut xhp_attr_enum_values = bump::Vec::new_in(self.arena); let xhp_attr_decls = self.slice(attributes.iter().filter_map(|node| { let node = match node { Node::XhpClassAttribute(x) => x, _ => return None, }; let Id(pos, name) = node.name; let name = prefix_colon(self.arena, name); let (like, type_, enum_values) = match node.hint { Node::XhpEnumTy((like, ty, values)) => (*like, *ty, Some(values)), _ => ( None, self.node_to_ty(node.hint) .unwrap_or_else(|| self.tany_with_pos(pos)), None, ), }; if let Some(enum_values) = enum_values { xhp_attr_enum_values.push((name, *enum_values)); }; let type_ = if node.nullable && node.tag.is_none() { match type_ { // already nullable Ty(_, Ty_::Toption(_)) | Ty(_, Ty_::Tmixed) => type_, // make nullable _ => self.alloc(Ty( self.alloc(Reason::hint(type_.get_pos()?)), Ty_::Toption(type_), )), } } else { type_ }; let type_ = match like { Some(p) => self.alloc(Ty(self.alloc(Reason::hint(p)), Ty_::Tlike(type_))), None => type_, }; let mut flags = PropFlags::empty(); flags.set(PropFlags::NEEDS_INIT, node.needs_init); Some(ShallowProp { name: (pos, name), visibility: aast::Visibility::Public, type_, xhp_attr: Some(xhp_attribute::XhpAttribute { tag: node.tag, has_default: !node.needs_init, }), flags, }) })); let xhp_attr_uses_decls = self.slice(attributes.iter().filter_map(|x| match x { Node::XhpAttributeUse(&name) => Some(name), _ => None, })); Node::XhpClassAttributeDeclaration(self.alloc(XhpClassAttributeDeclarationNode { xhp_attr_enum_values: xhp_attr_enum_values.into_bump_slice(), xhp_attr_decls, xhp_attr_uses_decls, })) } /// Handle XHP attribute enum declarations. /// /// class :foo implements XHPChild { /// attribute /// enum {'big', 'small'} size; // this line /// } fn make_xhp_enum_type( &mut self, like: Self::Output, enum_keyword: Self::Output, _left_brace: Self::Output, xhp_enum_values: Self::Output, right_brace: Self::Output, ) -> Self::Output { // Infer the type hint from the first value. // TODO: T88207956 consider all the values. let ty = xhp_enum_values .iter() .next() .and_then(|node| self.node_to_ty(*node)) .map(|node_ty| { let pos = self.merge_positions(enum_keyword, right_brace); let ty_ = node_ty.1; self.alloc(Ty(self.alloc(Reason::hint(pos)), ty_)) }); let mut values = bump::Vec::new_in(self.arena); for node in xhp_enum_values.iter() { // XHP enum values may only be string or int literals. match node { Node::IntLiteral(&(s, _)) => { let i = s.parse::<isize>().unwrap_or(0); values.push(XhpEnumValue::XEVInt(i)); } Node::StringLiteral(&(s, _)) => { let owned_str = String::from_utf8_lossy(s); values.push(XhpEnumValue::XEVString(self.arena.alloc_str(&owned_str))); } _ => {} }; } match ty { Some(ty) => { Node::XhpEnumTy(self.alloc((self.get_pos_opt(like), ty, values.into_bump_slice()))) } None => Node::Ignored(SK::XHPEnumType), } } fn make_xhp_class_attribute( &mut self, type_: Self::Output, name: Self::Output, initializer: Self::Output, tag: Self::Output, ) -> Self::Output { let name = match name.as_id() { Some(name) => name, None => return Node::Ignored(SK::XHPClassAttribute), }; Node::XhpClassAttribute(self.alloc(XhpClassAttributeNode { name, hint: type_, needs_init: !initializer.is_present(), tag: match tag.token_kind() { Some(TokenKind::Required) => Some(xhp_attribute::Tag::Required), Some(TokenKind::Lateinit) => Some(xhp_attribute::Tag::LateInit), _ => None, }, nullable: initializer.is_token(TokenKind::NullLiteral) || !initializer.is_present(), })) } fn make_xhp_simple_class_attribute(&mut self, name: Self::Output) -> Self::Output { Node::XhpAttributeUse(self.alloc(name)) } fn make_property_declarator( &mut self, name: Self::Output, initializer: Self::Output, ) -> Self::Output { Node::ListItem(self.alloc((name, initializer))) } fn make_methodish_declaration( &mut self, attrs: Self::Output, header: Self::Output, body: Self::Output, closer: Self::Output, ) -> Self::Output { let header = match header { Node::FunctionHeader(header) => header, _ => return Node::Ignored(SK::MethodishDeclaration), }; // If we don't have a body, use the closing token. A closing token of // '}' indicates a regular function, while a closing token of ';' // indicates an abstract function. let body = if body.is_ignored() { closer } else { body }; let modifiers = read_member_modifiers(header.modifiers.iter()); let is_constructor = header.name.is_token(TokenKind::Construct); let is_method = true; let (id, ty, properties) = match self.function_to_ty(is_method, attrs, header, body) { Some(tuple) => tuple, None => return Node::Ignored(SK::MethodishDeclaration), }; let attributes = self.to_attributes(attrs); let deprecated = attributes.deprecated.map(|msg| { let mut s = bump::String::new_in(self.arena); s.push_str("The method "); s.push_str(id.1); s.push_str(" is deprecated: "); s.push_str(msg); s.into_bump_str() }); let mut flags = MethodFlags::empty(); flags.set( MethodFlags::ABSTRACT, self.in_interface() || modifiers.is_abstract, ); flags.set(MethodFlags::FINAL, modifiers.is_final); flags.set(MethodFlags::OVERRIDE, attributes.override_); flags.set( MethodFlags::DYNAMICALLYCALLABLE, attributes.dynamically_callable, ); flags.set(MethodFlags::PHP_STD_LIB, attributes.php_std_lib); flags.set( MethodFlags::SUPPORT_DYNAMIC_TYPE, !is_constructor && attributes.support_dynamic_type, ); // Parse the user attributes // in facts-mode all attributes are saved, otherwise only __NoAutoDynamic/__NoAutoLikes is let user_attributes = self.slice(attrs.iter().rev().filter_map(|attribute| { if let Node::Attribute(attr) = attribute { if self.opts.keep_user_attributes || is_no_auto_attribute(attr.name.1) { Some(self.user_attribute_to_decl(attr)) } else { None } } else { None } })); let method = self.alloc(ShallowMethod { name: id, type_: ty, visibility: modifiers.visibility, deprecated, flags, attributes: user_attributes, }); if !self.inside_no_auto_dynamic_class { let this = Rc::make_mut(&mut self.state); this.under_no_auto_dynamic = false; this.under_no_auto_likes = false; } if is_constructor { Node::Constructor(self.alloc(ConstructorNode { method, properties })) } else { Node::Method(self.alloc(MethodNode { method, is_static: modifiers.is_static, })) } } fn make_classish_body( &mut self, _left_brace: Self::Output, elements: Self::Output, _right_brace: Self::Output, ) -> Self::Output { Node::ClassishBody(self.alloc(elements.as_slice(self.arena))) } fn make_enum_declaration( &mut self, attributes: Self::Output, modifiers: Self::Output, _keyword: Self::Output, name: Self::Output, _colon: Self::Output, extends: Self::Output, constraint: Self::Output, _left_brace: Self::Output, use_clauses: Self::Output, enumerators: Self::Output, _right_brace: Self::Output, ) -> Self::Output { let id = match self.elaborate_defined_id(name) { Some(id) => id, None => return Node::Ignored(SK::EnumDeclaration), }; let hint = match self.node_to_ty(extends) { Some(ty) => ty, None => return Node::Ignored(SK::EnumDeclaration), }; let extends = match self.node_to_ty(self.make_apply( (self.get_pos(name), "\\HH\\BuiltinEnum"), name, NO_POS, )) { Some(ty) => ty, None => return Node::Ignored(SK::EnumDeclaration), }; let internal = modifiers .iter() .any(|m| m.as_visibility() == Some(aast::Visibility::Internal)); let key = id.1; let consts = self.slice(enumerators.iter().filter_map(|node| match *node { Node::Const(const_) => Some(const_), _ => None, })); let mut user_attributes = bump::Vec::with_capacity_in(attributes.len(), self.arena); let mut docs_url = None; for attribute in attributes.iter() { match attribute { Node::Attribute(attr) => { if attr.name.1 == "__Docs" { if let Some((_, bstr)) = attr.string_literal_param { docs_url = Some(self.str_from_utf8_for_bytes_in_arena(bstr)); } } user_attributes.push(self.user_attribute_to_decl(attr)); } _ => {} } } // Match ordering of attributes produced by the OCaml decl parser (even // though it's the reverse of the syntactic ordering). user_attributes.reverse(); let user_attributes = user_attributes.into_bump_slice(); let constraint = match constraint { Node::TypeConstraint(&(_kind, ty)) => self.node_to_ty(ty), _ => None, }; let mut includes_len = 0; for element in use_clauses.iter() { match element { Node::EnumUse(names) => includes_len += names.len(), _ => {} } } let mut includes = bump::Vec::with_capacity_in(includes_len, self.arena); for element in use_clauses.iter() { match element { Node::EnumUse(names) => { includes.extend(names.iter().filter_map(|&name| self.node_to_ty(name))) } _ => {} } } let includes = includes.into_bump_slice(); let parsed_attributes = self.to_attributes(attributes); let cls = self.alloc(shallow_decl_defs::ShallowClass { mode: self.file_mode, final_: false, abstract_: false, is_xhp: false, has_xhp_keyword: false, kind: ClassishKind::Cenum, module: self.module, internal, name: id.into(), tparams: &[], where_constraints: &[], extends: bumpalo::vec![in self.arena; extends].into_bump_slice(), uses: &[], xhp_attr_uses: &[], xhp_enum_values: SMap::empty(), xhp_marked_empty: false, req_extends: &[], req_implements: &[], req_class: &[], implements: &[], support_dynamic_type: parsed_attributes.support_dynamic_type, consts, typeconsts: &[], props: &[], sprops: &[], constructor: None, static_methods: &[], methods: &[], user_attributes, enum_type: Some(self.alloc(EnumType { base: hint, constraint, includes, })), docs_url, }); let this = Rc::make_mut(&mut self.state); this.add_class(key, cls); this.classish_name_builder = None; Node::Ignored(SK::EnumDeclaration) } fn make_enum_use( &mut self, _keyword: Self::Output, names: Self::Output, _semicolon: Self::Output, ) -> Self::Output { Node::EnumUse(self.alloc(names)) } fn begin_enumerator(&mut self) { self.start_accumulating_const_refs(); } fn make_enumerator( &mut self, name: Self::Output, _equal: Self::Output, value: Self::Output, _semicolon: Self::Output, ) -> Self::Output { let refs = self.stop_accumulating_const_refs(); let id = match self.expect_name(name) { Some(id) => id, None => return Node::Ignored(SyntaxKind::Enumerator), }; Node::Const( self.alloc(ShallowClassConst { abstract_: ClassConstKind::CCConcrete, name: id.into(), type_: self .infer_const(name, value) .unwrap_or_else(|| self.tany_with_pos(id.0)), refs, }), ) } fn make_enum_class_declaration( &mut self, attributes: Self::Output, modifiers: Self::Output, _enum_keyword: Self::Output, _class_keyword: Self::Output, name: Self::Output, _colon: Self::Output, base: Self::Output, _extends_keyword: Self::Output, extends_list: Self::Output, _left_brace: Self::Output, elements: Self::Output, _right_brace: Self::Output, ) -> Self::Output { let name = match self.elaborate_defined_id(name) { Some(name) => name, None => return Node::Ignored(SyntaxKind::EnumClassDeclaration), }; let base_pos = self.get_pos(base); let base = self .node_to_ty(base) .unwrap_or_else(|| self.tany_with_pos(name.0)); let base = if self.opts.everything_sdt { self.alloc(Ty(self.alloc(Reason::hint(base_pos)), Ty_::Tlike(base))) } else { base }; let mut is_abstract = false; let mut is_final = false; for modifier in modifiers.iter() { match modifier.token_kind() { Some(TokenKind::Abstract) => is_abstract = true, Some(TokenKind::Final) => is_final = true, _ => {} } } let class_kind = if is_abstract { ClassishKind::CenumClass(Abstraction::Abstract) } else { ClassishKind::CenumClass(Abstraction::Concrete) }; let builtin_enum_class_ty = { let pos = name.0; let enum_class_ty_ = Ty_::Tapply(self.alloc((name.into(), &[]))); let enum_class_ty = self.alloc(Ty(self.alloc(Reason::hint(pos)), enum_class_ty_)); let elt_ty_ = Ty_::Tapply(self.alloc(( (pos, "\\HH\\MemberOf"), bumpalo::vec![in self.arena; enum_class_ty, base].into_bump_slice(), ))); let elt_ty = self.alloc(Ty(self.alloc(Reason::hint(pos)), elt_ty_)); let builtin_enum_ty_ = if is_abstract { Ty_::Tapply(self.alloc(((pos, "\\HH\\BuiltinAbstractEnumClass"), &[]))) } else { Ty_::Tapply(self.alloc(( (pos, "\\HH\\BuiltinEnumClass"), std::slice::from_ref(self.alloc(elt_ty)), ))) }; self.alloc(Ty(self.alloc(Reason::hint(pos)), builtin_enum_ty_)) }; let consts = self.slice(elements.iter().filter_map(|node| match *node { Node::Const(const_) => Some(const_), _ => None, })); let typeconsts = self.slice(elements.iter().filter_map(|node| match *node { Node::TypeConstant(tconst) => Some(tconst), _ => None, })); let mut extends = bump::Vec::with_capacity_in(extends_list.len() + 1, self.arena); extends.push(builtin_enum_class_ty); extends.extend(extends_list.iter().filter_map(|&n| self.node_to_ty(n))); let extends = extends.into_bump_slice(); let includes = &extends[1..]; let mut user_attributes = bump::Vec::with_capacity_in(attributes.len() + 1, self.arena); let mut docs_url = None; for attribute in attributes.iter() { match attribute { Node::Attribute(attr) => { if attr.name.1 == "__Docs" { if let Some((_, bstr)) = attr.string_literal_param { docs_url = Some(self.str_from_utf8_for_bytes_in_arena(bstr)); } } user_attributes.push(self.user_attribute_to_decl(attr)); } _ => {} } } let internal = modifiers .iter() .any(|m| m.as_visibility() == Some(aast::Visibility::Internal)); user_attributes.push(self.alloc(shallow_decl_defs::UserAttribute { name: (name.0, "__EnumClass"), params: &[], })); // Match ordering of attributes produced by the OCaml decl parser (even // though it's the reverse of the syntactic ordering). user_attributes.reverse(); let user_attributes = user_attributes.into_bump_slice(); let parsed_attributes = self.to_attributes(attributes); let support_dynamic_type = self.implicit_sdt() || parsed_attributes.support_dynamic_type; let cls = self.alloc(shallow_decl_defs::ShallowClass { mode: self.file_mode, final_: is_final, abstract_: is_abstract, is_xhp: false, has_xhp_keyword: false, internal, kind: class_kind, module: self.module, name: name.into(), tparams: &[], where_constraints: &[], extends, uses: &[], xhp_attr_uses: &[], xhp_enum_values: SMap::empty(), xhp_marked_empty: false, req_extends: &[], req_implements: &[], req_class: &[], implements: &[], support_dynamic_type, consts, typeconsts, props: &[], sprops: &[], constructor: None, static_methods: &[], methods: &[], user_attributes, enum_type: Some(self.alloc(EnumType { base, constraint: None, includes, })), docs_url, }); let this = Rc::make_mut(&mut self.state); this.add_class(name.1, cls); this.classish_name_builder = None; Node::Ignored(SyntaxKind::EnumClassDeclaration) } fn begin_enum_class_enumerator(&mut self) { self.start_accumulating_const_refs(); } fn make_enum_class_enumerator( &mut self, modifiers: Self::Output, type_: Self::Output, name: Self::Output, _initializer: Self::Output, _semicolon: Self::Output, ) -> Self::Output { let refs = self.stop_accumulating_const_refs(); let name = match self.expect_name(name) { Some(name) => name, None => return Node::Ignored(SyntaxKind::EnumClassEnumerator), }; let pos = name.0; let has_abstract_keyword = modifiers .iter() .any(|node| node.is_token(TokenKind::Abstract)); let abstract_ = if has_abstract_keyword { /* default values not allowed atm */ ClassConstKind::CCAbstract(false) } else { ClassConstKind::CCConcrete }; let type_pos = self.get_pos(type_); let type_ = self .node_to_ty(type_) .unwrap_or_else(|| self.tany_with_pos(name.0)); let type_ = if self.opts.everything_sdt { self.alloc(Ty(self.alloc(Reason::hint(type_pos)), Ty_::Tlike(type_))) } else { type_ }; let class_name = match self.get_current_classish_name() { Some((name, _)) => name, None => return Node::Ignored(SyntaxKind::EnumClassEnumerator), }; let enum_class_ty_ = Ty_::Tapply(self.alloc(((pos, class_name), &[]))); let enum_class_ty = self.alloc(Ty(self.alloc(Reason::hint(pos)), enum_class_ty_)); let type_ = Ty_::Tapply(self.alloc(( (pos, "\\HH\\MemberOf"), bumpalo::vec![in self.arena; enum_class_ty, type_].into_bump_slice(), ))); let type_ = self.alloc(Ty(self.alloc(Reason::hint(pos)), type_)); Node::Const(self.alloc(ShallowClassConst { abstract_, name: name.into(), type_, refs, })) } fn make_tuple_type_specifier( &mut self, left_paren: Self::Output, tys: Self::Output, right_paren: Self::Output, ) -> Self::Output { // We don't need to include the tys list in this position merging // because by definition it's already contained by the two brackets. let pos = self.merge_positions(left_paren, right_paren); let tys = self.slice(tys.iter().filter_map(|&node| self.node_to_ty(node))); self.hint_ty(pos, Ty_::Ttuple(tys)) } fn make_tuple_type_explicit_specifier( &mut self, keyword: Self::Output, _left_angle: Self::Output, types: Self::Output, right_angle: Self::Output, ) -> Self::Output { let id = (self.get_pos(keyword), "\\tuple"); // This is an error--tuple syntax is (A, B), not tuple<A, B>. // OCaml decl makes a Tapply rather than a Ttuple here. self.make_apply(id, types, self.get_pos(right_angle)) } fn make_intersection_type_specifier( &mut self, left_paren: Self::Output, tys: Self::Output, right_paren: Self::Output, ) -> Self::Output { let pos = self.merge_positions(left_paren, right_paren); let tys = self.slice(tys.iter().filter_map(|x| match x { Node::ListItem(&(ty, _ampersand)) => self.node_to_ty(ty), &x => self.node_to_ty(x), })); self.hint_ty(pos, Ty_::Tintersection(tys)) } fn make_union_type_specifier( &mut self, left_paren: Self::Output, tys: Self::Output, right_paren: Self::Output, ) -> Self::Output { let pos = self.merge_positions(left_paren, right_paren); let tys = self.slice(tys.iter().filter_map(|x| match x { Node::ListItem(&(ty, _bar)) => self.node_to_ty(ty), &x => self.node_to_ty(x), })); self.hint_ty(pos, Ty_::Tunion(tys)) } fn make_shape_type_specifier( &mut self, shape: Self::Output, _lparen: Self::Output, fields: Self::Output, open: Self::Output, rparen: Self::Output, ) -> Self::Output { let fields = fields; let fields_iter = fields.iter(); let mut fields = AssocListMut::new_in(self.arena); for node in fields_iter { if let Node::ShapeFieldSpecifier(&ShapeFieldNode { name, type_ }) = *node { fields.insert(self.make_t_shape_field_name(name), type_) } } let pos = self.get_pos(open); let reason = self.alloc(Reason::hint(pos)); let kind = match open.token_kind() { // Type of unknown fields is mixed, or supportdyn<mixed> under implicit SD Some(TokenKind::DotDotDot) => self.alloc(Ty( reason, if self.implicit_sdt() { self.make_supportdyn(pos, Ty_::Tmixed) } else { Ty_::Tmixed }, )), // Closed shapes are expressed using `nothing` (empty union) as the type of unknown fields _ => self.alloc(Ty(reason, Ty_::Tunion(&[]))), }; let pos = self.merge_positions(shape, rparen); let origin = TypeOrigin::MissingOrigin; self.hint_ty( pos, Ty_::Tshape(self.alloc(ShapeType { origin, unknown_value: kind, fields: fields.into(), })), ) } fn make_classname_type_specifier( &mut self, classname: Self::Output, _lt: Self::Output, targ: Self::Output, _trailing_comma: Self::Output, gt: Self::Output, ) -> Self::Output { let id = match classname.as_id() { Some(id) => id, None => return Node::Ignored(SK::ClassnameTypeSpecifier), }; if gt.is_ignored() { self.prim_ty(aast::Tprim::Tstring, id.0) } else { self.make_apply( (id.0, self.elaborate_raw_id(id.1)), targ, self.merge_positions(classname, gt), ) } } fn make_scope_resolution_expression( &mut self, class_name: Self::Output, _operator: Self::Output, value: Self::Output, ) -> Self::Output { let pos = self.merge_positions(class_name, value); let Id(class_name_pos, class_name_str) = match self.expect_name(class_name) { Some(id) => { if matches!(class_name, Node::XhpName(..)) && self.opts.disable_xhp_element_mangling && self.opts.keep_user_attributes { // for facts, allow xhp class consts to be mangled later // on even when xhp_element_mangling is disabled let mut qualified = bump::String::with_capacity_in(id.1.len() + 1, self.arena); qualified.push_str("\\"); qualified.push_str(id.1); Id(id.0, self.arena.alloc_str(&qualified)) } else { self.elaborate_id(id) } } None => return Node::Ignored(SK::ScopeResolutionExpression), }; let class_id = self.alloc(aast::ClassId( (), class_name_pos, match class_name { Node::Name(("self", _)) => aast::ClassId_::CIself, _ => aast::ClassId_::CI(self.alloc(Id(class_name_pos, class_name_str))), }, )); let value_id = match self.expect_name(value) { Some(id) => id, None => return Node::Ignored(SK::ScopeResolutionExpression), }; self.accumulate_const_ref(class_id, &value_id); Node::Expr(self.alloc(aast::Expr( (), pos, nast::Expr_::ClassConst(self.alloc((class_id, self.alloc((value_id.0, value_id.1))))), ))) } fn make_field_specifier( &mut self, question_token: Self::Output, name: Self::Output, _arrow: Self::Output, type_: Self::Output, ) -> Self::Output { let optional = question_token.is_present(); let ty = match self.node_to_ty(type_) { Some(ty) => ty, None => return Node::Ignored(SK::FieldSpecifier), }; let name = match self.make_shape_field_name(name) { Some(name) => name, None => return Node::Ignored(SK::FieldSpecifier), }; Node::ShapeFieldSpecifier(self.alloc(ShapeFieldNode { name: self.alloc(ShapeField(name)), type_: self.alloc(ShapeFieldType { optional, ty }), })) } fn make_field_initializer( &mut self, key: Self::Output, _arrow: Self::Output, value: Self::Output, ) -> Self::Output { Node::ListItem(self.alloc((key, value))) } fn make_varray_type_specifier( &mut self, varray_keyword: Self::Output, _less_than: Self::Output, tparam: Self::Output, _trailing_comma: Self::Output, greater_than: Self::Output, ) -> Self::Output { let tparam = match self.node_to_ty(tparam) { Some(ty) => ty, None => self.tany_with_pos(self.get_pos(varray_keyword)), }; self.hint_ty( self.merge_positions(varray_keyword, greater_than), Ty_::Tapply(self.alloc(( ( self.get_pos(varray_keyword), naming_special_names::collections::VEC, ), self.alloc([tparam]), ))), ) } fn make_darray_type_specifier( &mut self, darray: Self::Output, _less_than: Self::Output, key_type: Self::Output, _comma: Self::Output, value_type: Self::Output, _trailing_comma: Self::Output, greater_than: Self::Output, ) -> Self::Output { let pos = self.merge_positions(darray, greater_than); let key_type = self.node_to_ty(key_type).unwrap_or(TANY); let value_type = self.node_to_ty(value_type).unwrap_or(TANY); self.hint_ty( pos, Ty_::Tapply(self.alloc(( ( self.get_pos(darray), naming_special_names::collections::DICT, ), self.alloc([key_type, value_type]), ))), ) } fn make_old_attribute_specification( &mut self, ltlt: Self::Output, attrs: Self::Output, gtgt: Self::Output, ) -> Self::Output { if attrs.contains_marker_attribute("__NoAutoDynamic") { let this = Rc::make_mut(&mut self.state); this.under_no_auto_dynamic = true; } if attrs.contains_marker_attribute("__NoAutoLikes") { let this = Rc::make_mut(&mut self.state); this.under_no_auto_likes = true; } match attrs { Node::List(nodes) => { Node::BracketedList(self.alloc((self.get_pos(ltlt), nodes, self.get_pos(gtgt)))) } _ => Node::Ignored(SK::OldAttributeSpecification), } } fn make_constructor_call( &mut self, name: Self::Output, _left_paren: Self::Output, args: Self::Output, _right_paren: Self::Output, ) -> Self::Output { let unqualified_name = match self.expect_name(name) { Some(name) => name, None => return Node::Ignored(SK::ConstructorCall), }; let name = if unqualified_name.1.starts_with("__") { unqualified_name } else { match self.expect_name(name) { Some(name) => self.elaborate_id(name), None => return Node::Ignored(SK::ConstructorCall), } }; let params = self.slice(args.iter().filter_map(|node| match node { Node::Expr(aast::Expr( _, _, aast::Expr_::ClassConst(&( aast::ClassId(_, _, aast::ClassId_::CI(&Id(pos, class_name))), (_, "class"), )), )) => { let name = if class_name.starts_with(':') && self.opts.disable_xhp_element_mangling { // for facts, allow xhp class consts to be mangled later on // even when xhp_element_mangling is disabled let mut qualified = bump::String::with_capacity_in(class_name.len() + 1, self.arena); qualified.push_str("\\"); qualified.push_str(class_name); Id(pos, self.arena.alloc_str(&qualified)) } else { self.elaborate_id(Id(pos, class_name)) }; Some(AttributeParam::Classname(name)) } Node::EnumClassLabel(label) => Some(AttributeParam::EnumClassLabel(label)), Node::Expr(e @ aast::Expr(_, pos, _)) => { // Try to parse a sequence of string concatenations fn fold_string_concat<'a>( expr: &nast::Expr<'a>, acc: &mut bump::Vec<'a, u8>, ) -> bool { match *expr { aast::Expr(_, _, aast::Expr_::String(val)) => { acc.extend_from_slice(val); true } aast::Expr( _, _, aast::Expr_::Binop(&aast::Binop { bop: Bop::Dot, lhs, rhs, }), ) => fold_string_concat(lhs, acc) && fold_string_concat(rhs, acc), _ => false, } } let mut acc = bump::Vec::new_in(self.arena); fold_string_concat(e, &mut acc) .then(|| AttributeParam::String(pos, acc.into_bump_slice().into())) } Node::StringLiteral((slit, pos)) => Some(AttributeParam::String(pos, slit)), Node::IntLiteral((ilit, _)) => Some(AttributeParam::Int(ilit)), _ => None, })); let string_literal_param = params.first().and_then(|p| match *p { AttributeParam::String(pos, s) => Some((pos, s)), _ => None, }); Node::Attribute(self.alloc(UserAttributeNode { name, params, string_literal_param, })) } fn make_trait_use( &mut self, _keyword: Self::Output, names: Self::Output, _semicolon: Self::Output, ) -> Self::Output { Node::TraitUse(self.alloc(names)) } fn make_require_clause( &mut self, _keyword: Self::Output, require_type: Self::Output, name: Self::Output, _semicolon: Self::Output, ) -> Self::Output { Node::RequireClause(self.alloc(RequireClause { require_type, name })) } fn make_nullable_type_specifier( &mut self, question_mark: Self::Output, hint: Self::Output, ) -> Self::Output { let pos = self.merge_positions(question_mark, hint); let ty = match self.node_to_ty(hint) { Some(ty) => ty, None => return Node::Ignored(SK::NullableTypeSpecifier), }; self.hint_ty(pos, Ty_::Toption(ty)) } fn make_like_type_specifier( &mut self, tilde: Self::Output, hint: Self::Output, ) -> Self::Output { let pos = self.merge_positions(tilde, hint); let ty = match self.node_to_ty(hint) { Some(ty) => ty, None => return Node::Ignored(SK::LikeTypeSpecifier), }; self.hint_ty(pos, Ty_::Tlike(ty)) } fn make_closure_type_specifier( &mut self, outer_left_paren: Self::Output, readonly_keyword: Self::Output, _function_keyword: Self::Output, _inner_left_paren: Self::Output, parameter_list: Self::Output, _inner_right_paren: Self::Output, capability: Self::Output, _colon: Self::Output, readonly_ret: Self::Output, return_type: Self::Output, outer_right_paren: Self::Output, ) -> Self::Output { let mut ft_variadic = false; let mut make_param = |fp: &'a FunParamDecl<'a>| -> &'a FunParam<'a> { let mut flags = FunParamFlags::empty(); let pos = self.get_pos(fp.hint); let mut param_type = self.node_to_ty(fp.hint).unwrap_or(TANY); if let ParamMode::FPinout = fp.kind { flags |= FunParamFlags::INOUT; // Pessimise type for inout param_type = if self.implicit_sdt() && !self.no_auto_likes() { self.alloc(Ty(self.alloc(Reason::hint(pos)), Ty_::Tlike(param_type))) } else { param_type } }; if fp.readonly { flags |= FunParamFlags::READONLY; } if fp.variadic { ft_variadic = true; } self.alloc(FunParam { pos, name: None, type_: self.alloc(PossiblyEnforcedTy { enforced: Enforcement::Unenforced, type_: param_type, }), flags, }) }; let params = self.slice(parameter_list.iter().filter_map(|&node| match node { Node::FunParam(fp) => Some(make_param(fp)), _ => None, })); let ret = match self.node_to_ty(return_type) { Some(ty) => ty, None => return Node::Ignored(SK::ClosureTypeSpecifier), }; let pos = self.merge_positions(outer_left_paren, outer_right_paren); let implicit_params = self.as_fun_implicit_params(capability, pos); let mut flags = FunTypeFlags::empty(); if readonly_ret.is_token(TokenKind::Readonly) { flags |= FunTypeFlags::RETURNS_READONLY; } if readonly_keyword.is_token(TokenKind::Readonly) { flags |= FunTypeFlags::READONLY_THIS; } if ft_variadic { flags |= FunTypeFlags::VARIADIC } let pess_return_type = if self.implicit_sdt() && !self.no_auto_likes() { self.alloc(Ty(self.alloc(Reason::hint(pos)), Ty_::Tlike(ret))) } else { ret }; let fty = Ty_::Tfun(self.alloc(FunType { tparams: &[], where_constraints: &[], params, implicit_params, ret: self.alloc(PossiblyEnforcedTy { enforced: Enforcement::Unenforced, type_: pess_return_type, }), flags, ifc_decl: default_ifc_fun_decl(), cross_package: None, })); if self.implicit_sdt() { self.hint_ty(pos, self.make_supportdyn(pos, fty)) } else { self.hint_ty(pos, fty) } } fn make_closure_parameter_type_specifier( &mut self, inout: Self::Output, readonly: Self::Output, hint: Self::Output, ) -> Self::Output { let kind = if inout.is_token(TokenKind::Inout) { ParamMode::FPinout } else { ParamMode::FPnormal }; Node::FunParam(self.alloc(FunParamDecl { attributes: Node::Ignored(SK::Missing), visibility: Node::Ignored(SK::Missing), kind, hint, readonly: readonly.is_token(TokenKind::Readonly), pos: self.get_pos(hint), name: Some(""), variadic: false, initializer: Node::Ignored(SK::Missing), })) } fn make_type_const_declaration( &mut self, attributes: Self::Output, modifiers: Self::Output, _const_keyword: Self::Output, _type_keyword: Self::Output, name: Self::Output, _type_parameters: Self::Output, constraints: Self::Output, _equal: Self::Output, type_: Self::Output, _semicolon: Self::Output, ) -> Self::Output { let attributes = self.to_attributes(attributes); let has_abstract_keyword = modifiers .iter() .any(|node| node.is_token(TokenKind::Abstract)); let reduce_bounds = |mut constraints: bump::Vec<'a, &Ty<'a>>, f: fn(&'a [&Ty<'a>]) -> Ty_<'a>| { if constraints.len() == 1 { constraints.pop().map(|ty| self.alloc(ty.clone())) } else { #[allow(clippy::manual_map)] // map doesn't allow moving out of borrowed constraints match constraints.first() { None => None, // no bounds Some(fst) => Some(self.alloc(Ty(fst.0, f(constraints.into_bump_slice())))), } } }; let type_ = self.node_to_ty(type_); let kind = if has_abstract_keyword { // Abstract type constant in EBNF-like notation: // abstract const type T {as U | super L} [= D]; let (lower, upper) = self.partition_type_bounds_into_lower_and_upper(constraints); Typeconst::TCAbstract(self.alloc(AbstractTypeconst { // `as T1 as T2 as ...` == `as (T1 & T2 & ...)` as_constraint: reduce_bounds(upper, |tys| Ty_::Tintersection(tys)), // `super T1 super T2 super ...` == `super (T1 | T2 | ...)` super_constraint: reduce_bounds(lower, |tys| Ty_::Tunion(tys)), default: type_, })) } else if let Some(tc_type) = type_ { // Concrete type constant: // const type T = Z; Typeconst::TCConcrete(self.alloc(ConcreteTypeconst { tc_type })) } else { // concrete or type constant requires a value return Node::Ignored(SK::TypeConstDeclaration); }; let name = match name.as_id() { Some(name) => name, None => return Node::Ignored(SK::TypeConstDeclaration), }; Node::TypeConstant(self.alloc(ShallowTypeconst { name: name.into(), kind, enforceable: match attributes.enforceable { Some(pos) => (pos, true), None => (NO_POS, false), }, reifiable: attributes.reifiable, is_ctx: false, })) } fn make_context_const_declaration( &mut self, modifiers: Self::Output, _const_keyword: Self::Output, _ctx_keyword: Self::Output, name: Self::Output, _type_parameters: Self::Output, constraints: Self::Output, _equal: Self::Output, ctx_list: Self::Output, _semicolon: Self::Output, ) -> Self::Output { let name = match name.as_id() { Some(name) => name, None => return Node::Ignored(SK::TypeConstDeclaration), }; let has_abstract_keyword = modifiers .iter() .any(|node| node.is_token(TokenKind::Abstract)); let context = self.node_to_ty(ctx_list); // note: lowerer ensures that there's at most 1 constraint of each kind let mut as_constraint = None; let mut super_constraint = None; for c in constraints.iter() { if let Node::ContextConstraint(&(kind, hint)) = c { let ty = self.node_to_ty(hint); match kind { ConstraintKind::ConstraintSuper => super_constraint = ty, ConstraintKind::ConstraintAs => as_constraint = ty, _ => {} } } } let kind = if has_abstract_keyword { Typeconst::TCAbstract(self.alloc(AbstractTypeconst { as_constraint, super_constraint, default: context, })) } else if let Some(tc_type) = context { Typeconst::TCConcrete(self.alloc(ConcreteTypeconst { tc_type })) } else { /* Concrete type const must have a value */ return Node::Ignored(SK::TypeConstDeclaration); }; Node::TypeConstant(self.alloc(ShallowTypeconst { name: name.into(), kind, enforceable: (NO_POS, false), reifiable: None, is_ctx: true, })) } fn make_decorated_expression( &mut self, decorator: Self::Output, expr: Self::Output, ) -> Self::Output { Node::ListItem(self.alloc((decorator, expr))) } fn make_type_constant( &mut self, ty: Self::Output, _coloncolon: Self::Output, constant_name: Self::Output, ) -> Self::Output { let id = match self.expect_name(constant_name) { Some(id) => id, None => return Node::Ignored(SK::TypeConstant), }; let pos = self.merge_positions(ty, constant_name); let ty = match (ty, self.get_current_classish_name()) { (Node::Name(("self", self_pos)), Some((name, class_name_pos))) => { // In classes, we modify the position when rewriting the // `self` keyword to point to the class name. In traits, // we don't (because traits are not types). We indicate // that the position shouldn't be rewritten with the // none Pos. let id_pos = if class_name_pos.is_none() { self_pos } else { class_name_pos }; let reason = self.alloc(Reason::hint(self_pos)); let ty_ = Ty_::Tapply(self.alloc(((id_pos, name), &[][..]))); self.alloc(Ty(reason, ty_)) } _ => match self.node_to_ty(ty) { Some(ty) => ty, None => return Node::Ignored(SK::TypeConstant), }, }; let reason = self.alloc(Reason::hint(pos)); // The reason-rewriting here is only necessary to match the // behavior of OCaml decl (which flattens and then unflattens // Haccess hints, losing some position information). let ty = self.rewrite_taccess_reasons(ty, reason); Node::Ty(self.alloc(Ty( reason, Ty_::Taccess(self.alloc(TaccessType(ty, id.into()))), ))) } fn make_type_in_refinement( &mut self, _type_keyword: Self::Output, type_constant_name: Self::Output, _type_params: Self::Output, constraints: Self::Output, _equal_token: Self::Output, type_specifier: Self::Output, ) -> Self::Output { let Id(_, id) = match self.expect_name(type_constant_name) { Some(id) => id, None => return Node::Ignored(SK::TypeInRefinement), }; let bound = if type_specifier.is_ignored() { // A loose refinement, with bounds let (lower, upper) = self.partition_type_bounds_into_lower_and_upper(constraints); RefinedConstBound::TRloose(self.alloc(RefinedConstBounds { lower: lower.into_bump_slice(), upper: upper.into_bump_slice(), })) } else { // An exact refinement let ty = match self.node_to_ty(type_specifier) { Some(ty) => ty, None => return Node::Ignored(SK::TypeInRefinement), }; RefinedConstBound::TRexact(ty) }; Node::RefinedConst(self.alloc(( id, RefinedConst { bound, is_ctx: false, }, ))) } fn make_ctx_in_refinement( &mut self, _ctx_keyword: Self::Output, ctx_constant_name: Self::Output, _type_params: Self::Output, constraints: Self::Output, _equal_token: Self::Output, ctx_list: Self::Output, ) -> Self::Output { let Id(_, id) = match self.expect_name(ctx_constant_name) { Some(id) => id, None => return Node::Ignored(SK::TypeInRefinement), }; let bound = if ctx_list.is_ignored() { // A loose refinement, with bounds let (lower, upper) = self.partition_ctx_bounds_into_lower_and_upper(constraints); RefinedConstBound::TRloose(self.alloc(RefinedConstBounds { lower: lower.into_bump_slice(), upper: upper.into_bump_slice(), })) } else { // An exact refinement let ty = match self.node_to_ty(ctx_list) { Some(ty) => ty, None => return Node::Ignored(SK::TypeInRefinement), }; RefinedConstBound::TRexact(ty) }; Node::RefinedConst(self.alloc(( id, RefinedConst { bound, is_ctx: true, }, ))) } fn make_type_refinement( &mut self, root_type: Self::Output, _with_keyword: Self::Output, _left_brace: Self::Output, members: Self::Output, right_brace: Self::Output, ) -> Self::Output { let pos = self.merge_positions(root_type, right_brace); let reason = self.alloc(Reason::hint(pos)); let root_type = match self.node_to_ty(root_type) { Some(ty) => ty, None => return Node::Ignored(SK::TypeRefinement), }; let const_members = arena_collections::map::Map::from( self.arena, members.iter().filter_map(|node| match node { Node::ListItem(&(node, _)) | &node => match node { Node::RefinedConst(&(id, ctr)) => Some((id, ctr)), _ => None, }, }), ); let class_ref = ClassRefinement { cr_consts: const_members, }; Node::Ty(self.alloc(Ty( reason, Ty_::Trefinement(self.alloc((root_type, class_ref))), ))) } fn make_soft_type_specifier( &mut self, at_token: Self::Output, hint: Self::Output, ) -> Self::Output { let pos = self.merge_positions(at_token, hint); let hint = match self.node_to_ty(hint) { Some(ty) => ty, None => return Node::Ignored(SK::SoftTypeSpecifier), }; // Use the type of the hint as-is (i.e., throw away the knowledge that // we had a soft type specifier here--the typechecker does not use it). // Replace its Reason with one including the position of the `@` token. self.hint_ty( pos, if self.opts.interpret_soft_types_as_like_types { Ty_::Tlike(hint) } else { hint.1 }, ) } fn make_attribute_specification(&mut self, attributes: Self::Output) -> Self::Output { if attributes.contains_marker_attribute("__NoAutoDynamic") { let this = Rc::make_mut(&mut self.state); this.under_no_auto_dynamic = true; } if attributes.contains_marker_attribute("__NoAutoLikes") { let this = Rc::make_mut(&mut self.state); this.under_no_auto_likes = true; } if self.opts.keep_user_attributes { attributes } else { Node::Ignored(SK::AttributeSpecification) } } fn make_attribute(&mut self, _at: Self::Output, attribute: Self::Output) -> Self::Output { if self.opts.keep_user_attributes { attribute } else { Node::Ignored(SK::Attribute) } } // A type specifier preceded by an attribute list. At the time of writing, // only the <<__Soft>> attribute is permitted here. fn make_attributized_specifier( &mut self, attributes: Self::Output, hint: Self::Output, ) -> Self::Output { match attributes { Node::BracketedList(( ltlt_pos, [ Node::Attribute(UserAttributeNode { name: Id(_, "__Soft"), .. }), ], gtgt_pos, )) => { let attributes_pos = self.merge(*ltlt_pos, *gtgt_pos); let hint_pos = self.get_pos(hint); // Use the type of the hint as-is (i.e., throw away the // knowledge that we had a soft type specifier here--the // typechecker does not use it). Replace its Reason with one // including the position of the attribute list. let hint = match self.node_to_ty(hint) { Some(ty) => ty, None => return Node::Ignored(SK::AttributizedSpecifier), }; self.hint_ty( self.merge(attributes_pos, hint_pos), if self.opts.interpret_soft_types_as_like_types { Ty_::Tlike(hint) } else { hint.1 }, ) } _ => hint, } } fn make_vector_type_specifier( &mut self, vec: Self::Output, _left_angle: Self::Output, hint: Self::Output, _trailing_comma: Self::Output, right_angle: Self::Output, ) -> Self::Output { let id = match self.expect_name(vec) { Some(id) => id, None => return Node::Ignored(SK::VectorTypeSpecifier), }; let id = (id.0, self.elaborate_raw_id(id.1)); self.make_apply(id, hint, self.get_pos(right_angle)) } fn make_dictionary_type_specifier( &mut self, dict: Self::Output, _left_angle: Self::Output, type_arguments: Self::Output, right_angle: Self::Output, ) -> Self::Output { let id = match self.expect_name(dict) { Some(id) => id, None => return Node::Ignored(SK::DictionaryTypeSpecifier), }; let id = (id.0, self.elaborate_raw_id(id.1)); self.make_apply(id, type_arguments, self.get_pos(right_angle)) } fn make_keyset_type_specifier( &mut self, keyset: Self::Output, _left_angle: Self::Output, hint: Self::Output, _trailing_comma: Self::Output, right_angle: Self::Output, ) -> Self::Output { let id = match self.expect_name(keyset) { Some(id) => id, None => return Node::Ignored(SK::KeysetTypeSpecifier), }; let id = (id.0, self.elaborate_raw_id(id.1)); self.make_apply(id, hint, self.get_pos(right_angle)) } fn make_variable_expression(&mut self, _expression: Self::Output) -> Self::Output { Node::Ignored(SK::VariableExpression) } fn make_file_attribute_specification( &mut self, _left_double_angle: Self::Output, _keyword: Self::Output, _colon: Self::Output, attributes: Self::Output, _right_double_angle: Self::Output, ) -> Self::Output { if self.opts.keep_user_attributes { let this = Rc::make_mut(&mut self.state); this.file_attributes = List::empty(); for attr in attributes.iter() { match attr { Node::Attribute(attr) => this .file_attributes .push_front(this.user_attribute_to_decl(attr), this.arena), _ => {} } } } Node::Ignored(SK::FileAttributeSpecification) } fn make_subscript_expression( &mut self, _receiver: Self::Output, _left_bracket: Self::Output, _index: Self::Output, _right_bracket: Self::Output, ) -> Self::Output { Node::Ignored(SK::SubscriptExpression) } fn make_member_selection_expression( &mut self, _object: Self::Output, _operator: Self::Output, _name: Self::Output, ) -> Self::Output { Node::Ignored(SK::MemberSelectionExpression) } fn make_object_creation_expression( &mut self, _new_keyword: Self::Output, _object: Self::Output, ) -> Self::Output { Node::Ignored(SK::ObjectCreationExpression) } fn make_safe_member_selection_expression( &mut self, _object: Self::Output, _operator: Self::Output, _name: Self::Output, ) -> Self::Output { Node::Ignored(SK::SafeMemberSelectionExpression) } fn make_function_call_expression( &mut self, _receiver: Self::Output, _type_args: Self::Output, _left_paren: Self::Output, _argument_list: Self::Output, _right_paren: Self::Output, ) -> Self::Output { Node::Ignored(SK::FunctionCallExpression) } fn make_list_expression( &mut self, _keyword: Self::Output, _left_paren: Self::Output, _members: Self::Output, _right_paren: Self::Output, ) -> Self::Output { Node::Ignored(SK::ListExpression) } fn make_module_declaration( &mut self, _attributes: Self::Output, _new_keyword: Self::Output, _module_keyword: Self::Output, name: Self::Output, _left_brace: Self::Output, exports: Self::Output, imports: Self::Output, _right_brace: Self::Output, ) -> Self::Output { if let Node::ModuleName(&(parts, pos)) = name { let module_name = self.module_name_string_from_parts(parts, pos); let map_references = |references_list| match references_list { Node::List(&references) => Some(self.slice(references.iter().filter_map( |reference| match reference { Node::ModuleName(&(name, _)) => { Some(self.module_reference_from_parts(module_name, name)) } _ => None, }, ))), _ => None, }; let exports = map_references(exports); let imports = map_references(imports); let module = self.alloc(shallow_decl_defs::ModuleDefType { pos, exports, imports, }); let this = Rc::make_mut(&mut self.state); this.add_module(module_name, module); } Node::Ignored(SK::ModuleDeclaration) } fn make_module_exports( &mut self, _exports_keyword: Self::Output, _left_brace: Self::Output, clauses: Self::Output, _right_brace: Self::Output, ) -> Self::Output { match clauses { Node::List(_) => clauses, _ => Node::List(self.alloc(bumpalo::vec![in self.arena;].into_bump_slice())), } } fn make_module_imports( &mut self, _imports_keyword: Self::Output, _left_brace: Self::Output, clauses: Self::Output, _right_brace: Self::Output, ) -> Self::Output { match clauses { Node::List(_) => clauses, _ => Node::List(self.alloc(bumpalo::vec![in self.arena;].into_bump_slice())), } } fn make_module_membership_declaration( &mut self, _module_keyword: Self::Output, name: Self::Output, _semicolon: Self::Output, ) -> Self::Output { match name { Node::ModuleName(&(parts, pos)) => { if self.module.is_none() { let name = self.module_name_string_from_parts(parts, pos); let this = Rc::make_mut(&mut self.state); this.module = Some(Id(pos, name)); } } _ => {} } Node::Ignored(SK::ModuleMembershipDeclaration) } }
Rust
hhvm/hphp/hack/src/decl/direct_decl_smart_constructors_generated.rs
/** * 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. An additional * directory. * ** * * THIS FILE IS @generated; DO NOT EDIT IT * To regenerate this file, run * * buck run //hphp/hack/src:generate_full_fidelity * ** * */ use flatten_smart_constructors::*; use parser_core_types::compact_token::CompactToken; use parser_core_types::token_factory::SimpleTokenFactoryImpl; use smart_constructors::SmartConstructors; use crate::{DirectDeclSmartConstructors, Node, SourceTextAllocator}; impl<'a, 'o, 't, S: SourceTextAllocator<'t, 'a>> SmartConstructors for DirectDeclSmartConstructors<'a, 'o, 't, S> { type State = Self; type Factory = SimpleTokenFactoryImpl<CompactToken>; type Output = Node<'a>; fn state_mut(&mut self) -> &mut Self { self } fn into_state(self) -> Self { self } fn token_factory_mut(&mut self) -> &mut Self::Factory { &mut self.token_factory } fn make_missing(&mut self, offset: usize) -> Self::Output { <Self as FlattenSmartConstructors>::make_missing(self, offset) } fn make_token(&mut self, token: CompactToken) -> Self::Output { <Self as FlattenSmartConstructors>::make_token(self, token) } fn make_list(&mut self, items: Vec<Self::Output>, offset: usize) -> Self::Output { <Self as FlattenSmartConstructors>::make_list(self, items, offset) } fn begin_enumerator(&mut self) { <Self as FlattenSmartConstructors>::begin_enumerator(self) } fn begin_enum_class_enumerator(&mut self) { <Self as FlattenSmartConstructors>::begin_enum_class_enumerator(self) } fn begin_constant_declarator(&mut self) { <Self as FlattenSmartConstructors>::begin_constant_declarator(self) } fn make_end_of_file(&mut self, token: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_end_of_file(self, token) } fn make_script(&mut self, declarations: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_script(self, declarations) } fn make_qualified_name(&mut self, parts: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_qualified_name(self, parts) } fn make_module_name(&mut self, parts: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_module_name(self, parts) } fn make_simple_type_specifier(&mut self, specifier: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_simple_type_specifier(self, specifier) } fn make_literal_expression(&mut self, expression: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_literal_expression(self, expression) } fn make_prefixed_string_expression(&mut self, name: Self::Output, str: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_prefixed_string_expression(self, name, str) } fn make_prefixed_code_expression(&mut self, prefix: Self::Output, left_backtick: Self::Output, body: Self::Output, right_backtick: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_prefixed_code_expression(self, prefix, left_backtick, body, right_backtick) } fn make_variable_expression(&mut self, expression: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_variable_expression(self, expression) } fn make_pipe_variable_expression(&mut self, expression: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_pipe_variable_expression(self, expression) } fn make_file_attribute_specification(&mut self, left_double_angle: Self::Output, keyword: Self::Output, colon: Self::Output, attributes: Self::Output, right_double_angle: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_file_attribute_specification(self, left_double_angle, keyword, colon, attributes, right_double_angle) } fn make_enum_declaration(&mut self, attribute_spec: Self::Output, modifiers: Self::Output, keyword: Self::Output, name: Self::Output, colon: Self::Output, base: Self::Output, type_: Self::Output, left_brace: Self::Output, use_clauses: Self::Output, enumerators: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_enum_declaration(self, attribute_spec, modifiers, keyword, name, colon, base, type_, left_brace, use_clauses, enumerators, right_brace) } fn make_enum_use(&mut self, keyword: Self::Output, names: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_enum_use(self, keyword, names, semicolon) } fn make_enumerator(&mut self, name: Self::Output, equal: Self::Output, value: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_enumerator(self, name, equal, value, semicolon) } fn make_enum_class_declaration(&mut self, attribute_spec: Self::Output, modifiers: Self::Output, enum_keyword: Self::Output, class_keyword: Self::Output, name: Self::Output, colon: Self::Output, base: Self::Output, extends: Self::Output, extends_list: Self::Output, left_brace: Self::Output, elements: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_enum_class_declaration(self, attribute_spec, modifiers, enum_keyword, class_keyword, name, colon, base, extends, extends_list, left_brace, elements, right_brace) } fn make_enum_class_enumerator(&mut self, modifiers: Self::Output, type_: Self::Output, name: Self::Output, initializer: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_enum_class_enumerator(self, modifiers, type_, name, initializer, semicolon) } fn make_alias_declaration(&mut self, attribute_spec: Self::Output, modifiers: Self::Output, module_kw_opt: Self::Output, keyword: Self::Output, name: Self::Output, generic_parameter: Self::Output, constraint: Self::Output, equal: Self::Output, type_: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_alias_declaration(self, attribute_spec, modifiers, module_kw_opt, keyword, name, generic_parameter, constraint, equal, type_, semicolon) } fn make_context_alias_declaration(&mut self, attribute_spec: Self::Output, keyword: Self::Output, name: Self::Output, generic_parameter: Self::Output, as_constraint: Self::Output, equal: Self::Output, context: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_context_alias_declaration(self, attribute_spec, keyword, name, generic_parameter, as_constraint, equal, context, semicolon) } fn make_case_type_declaration(&mut self, attribute_spec: Self::Output, modifiers: Self::Output, case_keyword: Self::Output, type_keyword: Self::Output, name: Self::Output, generic_parameter: Self::Output, as_: Self::Output, bounds: Self::Output, equal: Self::Output, variants: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_case_type_declaration(self, attribute_spec, modifiers, case_keyword, type_keyword, name, generic_parameter, as_, bounds, equal, variants, semicolon) } fn make_case_type_variant(&mut self, bar: Self::Output, type_: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_case_type_variant(self, bar, type_) } fn make_property_declaration(&mut self, attribute_spec: Self::Output, modifiers: Self::Output, type_: Self::Output, declarators: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_property_declaration(self, attribute_spec, modifiers, type_, declarators, semicolon) } fn make_property_declarator(&mut self, name: Self::Output, initializer: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_property_declarator(self, name, initializer) } fn make_namespace_declaration(&mut self, header: Self::Output, body: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_namespace_declaration(self, header, body) } fn make_namespace_declaration_header(&mut self, keyword: Self::Output, name: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_namespace_declaration_header(self, keyword, name) } fn make_namespace_body(&mut self, left_brace: Self::Output, declarations: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_namespace_body(self, left_brace, declarations, right_brace) } fn make_namespace_empty_body(&mut self, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_namespace_empty_body(self, semicolon) } fn make_namespace_use_declaration(&mut self, keyword: Self::Output, kind: Self::Output, clauses: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_namespace_use_declaration(self, keyword, kind, clauses, semicolon) } fn make_namespace_group_use_declaration(&mut self, keyword: Self::Output, kind: Self::Output, prefix: Self::Output, left_brace: Self::Output, clauses: Self::Output, right_brace: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_namespace_group_use_declaration(self, keyword, kind, prefix, left_brace, clauses, right_brace, semicolon) } fn make_namespace_use_clause(&mut self, clause_kind: Self::Output, name: Self::Output, as_: Self::Output, alias: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_namespace_use_clause(self, clause_kind, name, as_, alias) } fn make_function_declaration(&mut self, attribute_spec: Self::Output, declaration_header: Self::Output, body: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_function_declaration(self, attribute_spec, declaration_header, body) } fn make_function_declaration_header(&mut self, modifiers: Self::Output, keyword: Self::Output, name: Self::Output, type_parameter_list: Self::Output, left_paren: Self::Output, parameter_list: Self::Output, right_paren: Self::Output, contexts: Self::Output, colon: Self::Output, readonly_return: Self::Output, type_: Self::Output, where_clause: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_function_declaration_header(self, modifiers, keyword, name, type_parameter_list, left_paren, parameter_list, right_paren, contexts, colon, readonly_return, type_, where_clause) } fn make_contexts(&mut self, left_bracket: Self::Output, types: Self::Output, right_bracket: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_contexts(self, left_bracket, types, right_bracket) } fn make_where_clause(&mut self, keyword: Self::Output, constraints: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_where_clause(self, keyword, constraints) } fn make_where_constraint(&mut self, left_type: Self::Output, operator: Self::Output, right_type: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_where_constraint(self, left_type, operator, right_type) } fn make_methodish_declaration(&mut self, attribute: Self::Output, function_decl_header: Self::Output, function_body: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_methodish_declaration(self, attribute, function_decl_header, function_body, semicolon) } fn make_methodish_trait_resolution(&mut self, attribute: Self::Output, function_decl_header: Self::Output, equal: Self::Output, name: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_methodish_trait_resolution(self, attribute, function_decl_header, equal, name, semicolon) } fn make_classish_declaration(&mut self, attribute: Self::Output, modifiers: Self::Output, xhp: Self::Output, keyword: Self::Output, name: Self::Output, type_parameters: Self::Output, extends_keyword: Self::Output, extends_list: Self::Output, implements_keyword: Self::Output, implements_list: Self::Output, where_clause: Self::Output, body: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_classish_declaration(self, attribute, modifiers, xhp, keyword, name, type_parameters, extends_keyword, extends_list, implements_keyword, implements_list, where_clause, body) } fn make_classish_body(&mut self, left_brace: Self::Output, elements: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_classish_body(self, left_brace, elements, right_brace) } fn make_trait_use(&mut self, keyword: Self::Output, names: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_trait_use(self, keyword, names, semicolon) } fn make_require_clause(&mut self, keyword: Self::Output, kind: Self::Output, name: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_require_clause(self, keyword, kind, name, semicolon) } fn make_const_declaration(&mut self, attribute_spec: Self::Output, modifiers: Self::Output, keyword: Self::Output, type_specifier: Self::Output, declarators: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_const_declaration(self, attribute_spec, modifiers, keyword, type_specifier, declarators, semicolon) } fn make_constant_declarator(&mut self, name: Self::Output, initializer: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_constant_declarator(self, name, initializer) } fn make_type_const_declaration(&mut self, attribute_spec: Self::Output, modifiers: Self::Output, keyword: Self::Output, type_keyword: Self::Output, name: Self::Output, type_parameters: Self::Output, type_constraints: Self::Output, equal: Self::Output, type_specifier: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_type_const_declaration(self, attribute_spec, modifiers, keyword, type_keyword, name, type_parameters, type_constraints, equal, type_specifier, semicolon) } fn make_context_const_declaration(&mut self, modifiers: Self::Output, const_keyword: Self::Output, ctx_keyword: Self::Output, name: Self::Output, type_parameters: Self::Output, constraint: Self::Output, equal: Self::Output, ctx_list: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_context_const_declaration(self, modifiers, const_keyword, ctx_keyword, name, type_parameters, constraint, equal, ctx_list, semicolon) } fn make_decorated_expression(&mut self, decorator: Self::Output, expression: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_decorated_expression(self, decorator, expression) } fn make_parameter_declaration(&mut self, attribute: Self::Output, visibility: Self::Output, call_convention: Self::Output, readonly: Self::Output, type_: Self::Output, name: Self::Output, default_value: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_parameter_declaration(self, attribute, visibility, call_convention, readonly, type_, name, default_value) } fn make_variadic_parameter(&mut self, call_convention: Self::Output, type_: Self::Output, ellipsis: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_variadic_parameter(self, call_convention, type_, ellipsis) } fn make_old_attribute_specification(&mut self, left_double_angle: Self::Output, attributes: Self::Output, right_double_angle: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_old_attribute_specification(self, left_double_angle, attributes, right_double_angle) } fn make_attribute_specification(&mut self, attributes: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_attribute_specification(self, attributes) } fn make_attribute(&mut self, at: Self::Output, attribute_name: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_attribute(self, at, attribute_name) } fn make_inclusion_expression(&mut self, require: Self::Output, filename: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_inclusion_expression(self, require, filename) } fn make_inclusion_directive(&mut self, expression: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_inclusion_directive(self, expression, semicolon) } fn make_compound_statement(&mut self, left_brace: Self::Output, statements: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_compound_statement(self, left_brace, statements, right_brace) } fn make_expression_statement(&mut self, expression: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_expression_statement(self, expression, semicolon) } fn make_markup_section(&mut self, hashbang: Self::Output, suffix: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_markup_section(self, hashbang, suffix) } fn make_markup_suffix(&mut self, less_than_question: Self::Output, name: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_markup_suffix(self, less_than_question, name) } fn make_unset_statement(&mut self, keyword: Self::Output, left_paren: Self::Output, variables: Self::Output, right_paren: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_unset_statement(self, keyword, left_paren, variables, right_paren, semicolon) } fn make_declare_local_statement(&mut self, keyword: Self::Output, variable: Self::Output, colon: Self::Output, type_: Self::Output, initializer: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_declare_local_statement(self, keyword, variable, colon, type_, initializer, semicolon) } fn make_using_statement_block_scoped(&mut self, await_keyword: Self::Output, using_keyword: Self::Output, left_paren: Self::Output, expressions: Self::Output, right_paren: Self::Output, body: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_using_statement_block_scoped(self, await_keyword, using_keyword, left_paren, expressions, right_paren, body) } fn make_using_statement_function_scoped(&mut self, await_keyword: Self::Output, using_keyword: Self::Output, expression: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_using_statement_function_scoped(self, await_keyword, using_keyword, expression, semicolon) } fn make_while_statement(&mut self, keyword: Self::Output, left_paren: Self::Output, condition: Self::Output, right_paren: Self::Output, body: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_while_statement(self, keyword, left_paren, condition, right_paren, body) } fn make_if_statement(&mut self, keyword: Self::Output, left_paren: Self::Output, condition: Self::Output, right_paren: Self::Output, statement: Self::Output, else_clause: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_if_statement(self, keyword, left_paren, condition, right_paren, statement, else_clause) } fn make_else_clause(&mut self, keyword: Self::Output, statement: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_else_clause(self, keyword, statement) } fn make_try_statement(&mut self, keyword: Self::Output, compound_statement: Self::Output, catch_clauses: Self::Output, finally_clause: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_try_statement(self, keyword, compound_statement, catch_clauses, finally_clause) } fn make_catch_clause(&mut self, keyword: Self::Output, left_paren: Self::Output, type_: Self::Output, variable: Self::Output, right_paren: Self::Output, body: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_catch_clause(self, keyword, left_paren, type_, variable, right_paren, body) } fn make_finally_clause(&mut self, keyword: Self::Output, body: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_finally_clause(self, keyword, body) } fn make_do_statement(&mut self, keyword: Self::Output, body: Self::Output, while_keyword: Self::Output, left_paren: Self::Output, condition: Self::Output, right_paren: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_do_statement(self, keyword, body, while_keyword, left_paren, condition, right_paren, semicolon) } fn make_for_statement(&mut self, keyword: Self::Output, left_paren: Self::Output, initializer: Self::Output, first_semicolon: Self::Output, control: Self::Output, second_semicolon: Self::Output, end_of_loop: Self::Output, right_paren: Self::Output, body: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_for_statement(self, keyword, left_paren, initializer, first_semicolon, control, second_semicolon, end_of_loop, right_paren, body) } fn make_foreach_statement(&mut self, keyword: Self::Output, left_paren: Self::Output, collection: Self::Output, await_keyword: Self::Output, as_: Self::Output, key: Self::Output, arrow: Self::Output, value: Self::Output, right_paren: Self::Output, body: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_foreach_statement(self, keyword, left_paren, collection, await_keyword, as_, key, arrow, value, right_paren, body) } fn make_switch_statement(&mut self, keyword: Self::Output, left_paren: Self::Output, expression: Self::Output, right_paren: Self::Output, left_brace: Self::Output, sections: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_switch_statement(self, keyword, left_paren, expression, right_paren, left_brace, sections, right_brace) } fn make_switch_section(&mut self, labels: Self::Output, statements: Self::Output, fallthrough: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_switch_section(self, labels, statements, fallthrough) } fn make_switch_fallthrough(&mut self, keyword: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_switch_fallthrough(self, keyword, semicolon) } fn make_case_label(&mut self, keyword: Self::Output, expression: Self::Output, colon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_case_label(self, keyword, expression, colon) } fn make_default_label(&mut self, keyword: Self::Output, colon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_default_label(self, keyword, colon) } fn make_match_statement(&mut self, keyword: Self::Output, left_paren: Self::Output, expression: Self::Output, right_paren: Self::Output, left_brace: Self::Output, arms: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_match_statement(self, keyword, left_paren, expression, right_paren, left_brace, arms, right_brace) } fn make_match_statement_arm(&mut self, pattern: Self::Output, arrow: Self::Output, body: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_match_statement_arm(self, pattern, arrow, body) } fn make_return_statement(&mut self, keyword: Self::Output, expression: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_return_statement(self, keyword, expression, semicolon) } fn make_yield_break_statement(&mut self, keyword: Self::Output, break_: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_yield_break_statement(self, keyword, break_, semicolon) } fn make_throw_statement(&mut self, keyword: Self::Output, expression: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_throw_statement(self, keyword, expression, semicolon) } fn make_break_statement(&mut self, keyword: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_break_statement(self, keyword, semicolon) } fn make_continue_statement(&mut self, keyword: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_continue_statement(self, keyword, semicolon) } fn make_echo_statement(&mut self, keyword: Self::Output, expressions: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_echo_statement(self, keyword, expressions, semicolon) } fn make_concurrent_statement(&mut self, keyword: Self::Output, statement: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_concurrent_statement(self, keyword, statement) } fn make_simple_initializer(&mut self, equal: Self::Output, value: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_simple_initializer(self, equal, value) } fn make_anonymous_class(&mut self, class_keyword: Self::Output, left_paren: Self::Output, argument_list: Self::Output, right_paren: Self::Output, extends_keyword: Self::Output, extends_list: Self::Output, implements_keyword: Self::Output, implements_list: Self::Output, body: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_anonymous_class(self, class_keyword, left_paren, argument_list, right_paren, extends_keyword, extends_list, implements_keyword, implements_list, body) } fn make_anonymous_function(&mut self, attribute_spec: Self::Output, async_keyword: Self::Output, function_keyword: Self::Output, left_paren: Self::Output, parameters: Self::Output, right_paren: Self::Output, ctx_list: Self::Output, colon: Self::Output, readonly_return: Self::Output, type_: Self::Output, use_: Self::Output, body: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_anonymous_function(self, attribute_spec, async_keyword, function_keyword, left_paren, parameters, right_paren, ctx_list, colon, readonly_return, type_, use_, body) } fn make_anonymous_function_use_clause(&mut self, keyword: Self::Output, left_paren: Self::Output, variables: Self::Output, right_paren: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_anonymous_function_use_clause(self, keyword, left_paren, variables, right_paren) } fn make_variable_pattern(&mut self, variable: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_variable_pattern(self, variable) } fn make_constructor_pattern(&mut self, constructor: Self::Output, left_paren: Self::Output, members: Self::Output, right_paren: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_constructor_pattern(self, constructor, left_paren, members, right_paren) } fn make_refinement_pattern(&mut self, variable: Self::Output, colon: Self::Output, specifier: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_refinement_pattern(self, variable, colon, specifier) } fn make_lambda_expression(&mut self, attribute_spec: Self::Output, async_: Self::Output, signature: Self::Output, arrow: Self::Output, body: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_lambda_expression(self, attribute_spec, async_, signature, arrow, body) } fn make_lambda_signature(&mut self, left_paren: Self::Output, parameters: Self::Output, right_paren: Self::Output, contexts: Self::Output, colon: Self::Output, readonly_return: Self::Output, type_: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_lambda_signature(self, left_paren, parameters, right_paren, contexts, colon, readonly_return, type_) } fn make_cast_expression(&mut self, left_paren: Self::Output, type_: Self::Output, right_paren: Self::Output, operand: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_cast_expression(self, left_paren, type_, right_paren, operand) } fn make_scope_resolution_expression(&mut self, qualifier: Self::Output, operator: Self::Output, name: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_scope_resolution_expression(self, qualifier, operator, name) } fn make_member_selection_expression(&mut self, object: Self::Output, operator: Self::Output, name: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_member_selection_expression(self, object, operator, name) } fn make_safe_member_selection_expression(&mut self, object: Self::Output, operator: Self::Output, name: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_safe_member_selection_expression(self, object, operator, name) } fn make_embedded_member_selection_expression(&mut self, object: Self::Output, operator: Self::Output, name: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_embedded_member_selection_expression(self, object, operator, name) } fn make_yield_expression(&mut self, keyword: Self::Output, operand: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_yield_expression(self, keyword, operand) } fn make_prefix_unary_expression(&mut self, operator: Self::Output, operand: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_prefix_unary_expression(self, operator, operand) } fn make_postfix_unary_expression(&mut self, operand: Self::Output, operator: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_postfix_unary_expression(self, operand, operator) } fn make_binary_expression(&mut self, left_operand: Self::Output, operator: Self::Output, right_operand: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_binary_expression(self, left_operand, operator, right_operand) } fn make_is_expression(&mut self, left_operand: Self::Output, operator: Self::Output, right_operand: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_is_expression(self, left_operand, operator, right_operand) } fn make_as_expression(&mut self, left_operand: Self::Output, operator: Self::Output, right_operand: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_as_expression(self, left_operand, operator, right_operand) } fn make_nullable_as_expression(&mut self, left_operand: Self::Output, operator: Self::Output, right_operand: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_nullable_as_expression(self, left_operand, operator, right_operand) } fn make_upcast_expression(&mut self, left_operand: Self::Output, operator: Self::Output, right_operand: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_upcast_expression(self, left_operand, operator, right_operand) } fn make_conditional_expression(&mut self, test: Self::Output, question: Self::Output, consequence: Self::Output, colon: Self::Output, alternative: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_conditional_expression(self, test, question, consequence, colon, alternative) } fn make_eval_expression(&mut self, keyword: Self::Output, left_paren: Self::Output, argument: Self::Output, right_paren: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_eval_expression(self, keyword, left_paren, argument, right_paren) } fn make_isset_expression(&mut self, keyword: Self::Output, left_paren: Self::Output, argument_list: Self::Output, right_paren: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_isset_expression(self, keyword, left_paren, argument_list, right_paren) } fn make_function_call_expression(&mut self, receiver: Self::Output, type_args: Self::Output, left_paren: Self::Output, argument_list: Self::Output, right_paren: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_function_call_expression(self, receiver, type_args, left_paren, argument_list, right_paren) } fn make_function_pointer_expression(&mut self, receiver: Self::Output, type_args: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_function_pointer_expression(self, receiver, type_args) } fn make_parenthesized_expression(&mut self, left_paren: Self::Output, expression: Self::Output, right_paren: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_parenthesized_expression(self, left_paren, expression, right_paren) } fn make_braced_expression(&mut self, left_brace: Self::Output, expression: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_braced_expression(self, left_brace, expression, right_brace) } fn make_et_splice_expression(&mut self, dollar: Self::Output, left_brace: Self::Output, expression: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_et_splice_expression(self, dollar, left_brace, expression, right_brace) } fn make_embedded_braced_expression(&mut self, left_brace: Self::Output, expression: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_embedded_braced_expression(self, left_brace, expression, right_brace) } fn make_list_expression(&mut self, keyword: Self::Output, left_paren: Self::Output, members: Self::Output, right_paren: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_list_expression(self, keyword, left_paren, members, right_paren) } fn make_collection_literal_expression(&mut self, name: Self::Output, left_brace: Self::Output, initializers: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_collection_literal_expression(self, name, left_brace, initializers, right_brace) } fn make_object_creation_expression(&mut self, new_keyword: Self::Output, object: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_object_creation_expression(self, new_keyword, object) } fn make_constructor_call(&mut self, type_: Self::Output, left_paren: Self::Output, argument_list: Self::Output, right_paren: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_constructor_call(self, type_, left_paren, argument_list, right_paren) } fn make_darray_intrinsic_expression(&mut self, keyword: Self::Output, explicit_type: Self::Output, left_bracket: Self::Output, members: Self::Output, right_bracket: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_darray_intrinsic_expression(self, keyword, explicit_type, left_bracket, members, right_bracket) } fn make_dictionary_intrinsic_expression(&mut self, keyword: Self::Output, explicit_type: Self::Output, left_bracket: Self::Output, members: Self::Output, right_bracket: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_dictionary_intrinsic_expression(self, keyword, explicit_type, left_bracket, members, right_bracket) } fn make_keyset_intrinsic_expression(&mut self, keyword: Self::Output, explicit_type: Self::Output, left_bracket: Self::Output, members: Self::Output, right_bracket: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_keyset_intrinsic_expression(self, keyword, explicit_type, left_bracket, members, right_bracket) } fn make_varray_intrinsic_expression(&mut self, keyword: Self::Output, explicit_type: Self::Output, left_bracket: Self::Output, members: Self::Output, right_bracket: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_varray_intrinsic_expression(self, keyword, explicit_type, left_bracket, members, right_bracket) } fn make_vector_intrinsic_expression(&mut self, keyword: Self::Output, explicit_type: Self::Output, left_bracket: Self::Output, members: Self::Output, right_bracket: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_vector_intrinsic_expression(self, keyword, explicit_type, left_bracket, members, right_bracket) } fn make_element_initializer(&mut self, key: Self::Output, arrow: Self::Output, value: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_element_initializer(self, key, arrow, value) } fn make_subscript_expression(&mut self, receiver: Self::Output, left_bracket: Self::Output, index: Self::Output, right_bracket: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_subscript_expression(self, receiver, left_bracket, index, right_bracket) } fn make_embedded_subscript_expression(&mut self, receiver: Self::Output, left_bracket: Self::Output, index: Self::Output, right_bracket: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_embedded_subscript_expression(self, receiver, left_bracket, index, right_bracket) } fn make_awaitable_creation_expression(&mut self, attribute_spec: Self::Output, async_: Self::Output, compound_statement: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_awaitable_creation_expression(self, attribute_spec, async_, compound_statement) } fn make_xhp_children_declaration(&mut self, keyword: Self::Output, expression: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_xhp_children_declaration(self, keyword, expression, semicolon) } fn make_xhp_children_parenthesized_list(&mut self, left_paren: Self::Output, xhp_children: Self::Output, right_paren: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_xhp_children_parenthesized_list(self, left_paren, xhp_children, right_paren) } fn make_xhp_category_declaration(&mut self, keyword: Self::Output, categories: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_xhp_category_declaration(self, keyword, categories, semicolon) } fn make_xhp_enum_type(&mut self, like: Self::Output, keyword: Self::Output, left_brace: Self::Output, values: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_xhp_enum_type(self, like, keyword, left_brace, values, right_brace) } fn make_xhp_lateinit(&mut self, at: Self::Output, keyword: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_xhp_lateinit(self, at, keyword) } fn make_xhp_required(&mut self, at: Self::Output, keyword: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_xhp_required(self, at, keyword) } fn make_xhp_class_attribute_declaration(&mut self, keyword: Self::Output, attributes: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_xhp_class_attribute_declaration(self, keyword, attributes, semicolon) } fn make_xhp_class_attribute(&mut self, type_: Self::Output, name: Self::Output, initializer: Self::Output, required: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_xhp_class_attribute(self, type_, name, initializer, required) } fn make_xhp_simple_class_attribute(&mut self, type_: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_xhp_simple_class_attribute(self, type_) } fn make_xhp_simple_attribute(&mut self, name: Self::Output, equal: Self::Output, expression: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_xhp_simple_attribute(self, name, equal, expression) } fn make_xhp_spread_attribute(&mut self, left_brace: Self::Output, spread_operator: Self::Output, expression: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_xhp_spread_attribute(self, left_brace, spread_operator, expression, right_brace) } fn make_xhp_open(&mut self, left_angle: Self::Output, name: Self::Output, attributes: Self::Output, right_angle: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_xhp_open(self, left_angle, name, attributes, right_angle) } fn make_xhp_expression(&mut self, open: Self::Output, body: Self::Output, close: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_xhp_expression(self, open, body, close) } fn make_xhp_close(&mut self, left_angle: Self::Output, name: Self::Output, right_angle: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_xhp_close(self, left_angle, name, right_angle) } fn make_type_constant(&mut self, left_type: Self::Output, separator: Self::Output, right_type: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_type_constant(self, left_type, separator, right_type) } fn make_vector_type_specifier(&mut self, keyword: Self::Output, left_angle: Self::Output, type_: Self::Output, trailing_comma: Self::Output, right_angle: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_vector_type_specifier(self, keyword, left_angle, type_, trailing_comma, right_angle) } fn make_keyset_type_specifier(&mut self, keyword: Self::Output, left_angle: Self::Output, type_: Self::Output, trailing_comma: Self::Output, right_angle: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_keyset_type_specifier(self, keyword, left_angle, type_, trailing_comma, right_angle) } fn make_tuple_type_explicit_specifier(&mut self, keyword: Self::Output, left_angle: Self::Output, types: Self::Output, right_angle: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_tuple_type_explicit_specifier(self, keyword, left_angle, types, right_angle) } fn make_varray_type_specifier(&mut self, keyword: Self::Output, left_angle: Self::Output, type_: Self::Output, trailing_comma: Self::Output, right_angle: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_varray_type_specifier(self, keyword, left_angle, type_, trailing_comma, right_angle) } fn make_function_ctx_type_specifier(&mut self, keyword: Self::Output, variable: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_function_ctx_type_specifier(self, keyword, variable) } fn make_type_parameter(&mut self, attribute_spec: Self::Output, reified: Self::Output, variance: Self::Output, name: Self::Output, param_params: Self::Output, constraints: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_type_parameter(self, attribute_spec, reified, variance, name, param_params, constraints) } fn make_type_constraint(&mut self, keyword: Self::Output, type_: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_type_constraint(self, keyword, type_) } fn make_context_constraint(&mut self, keyword: Self::Output, ctx_list: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_context_constraint(self, keyword, ctx_list) } fn make_darray_type_specifier(&mut self, keyword: Self::Output, left_angle: Self::Output, key: Self::Output, comma: Self::Output, value: Self::Output, trailing_comma: Self::Output, right_angle: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_darray_type_specifier(self, keyword, left_angle, key, comma, value, trailing_comma, right_angle) } fn make_dictionary_type_specifier(&mut self, keyword: Self::Output, left_angle: Self::Output, members: Self::Output, right_angle: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_dictionary_type_specifier(self, keyword, left_angle, members, right_angle) } fn make_closure_type_specifier(&mut self, outer_left_paren: Self::Output, readonly_keyword: Self::Output, function_keyword: Self::Output, inner_left_paren: Self::Output, parameter_list: Self::Output, inner_right_paren: Self::Output, contexts: Self::Output, colon: Self::Output, readonly_return: Self::Output, return_type: Self::Output, outer_right_paren: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_closure_type_specifier(self, outer_left_paren, readonly_keyword, function_keyword, inner_left_paren, parameter_list, inner_right_paren, contexts, colon, readonly_return, return_type, outer_right_paren) } fn make_closure_parameter_type_specifier(&mut self, call_convention: Self::Output, readonly: Self::Output, type_: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_closure_parameter_type_specifier(self, call_convention, readonly, type_) } fn make_type_refinement(&mut self, type_: Self::Output, keyword: Self::Output, left_brace: Self::Output, members: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_type_refinement(self, type_, keyword, left_brace, members, right_brace) } fn make_type_in_refinement(&mut self, keyword: Self::Output, name: Self::Output, type_parameters: Self::Output, constraints: Self::Output, equal: Self::Output, type_: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_type_in_refinement(self, keyword, name, type_parameters, constraints, equal, type_) } fn make_ctx_in_refinement(&mut self, keyword: Self::Output, name: Self::Output, type_parameters: Self::Output, constraints: Self::Output, equal: Self::Output, ctx_list: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_ctx_in_refinement(self, keyword, name, type_parameters, constraints, equal, ctx_list) } fn make_classname_type_specifier(&mut self, keyword: Self::Output, left_angle: Self::Output, type_: Self::Output, trailing_comma: Self::Output, right_angle: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_classname_type_specifier(self, keyword, left_angle, type_, trailing_comma, right_angle) } fn make_field_specifier(&mut self, question: Self::Output, name: Self::Output, arrow: Self::Output, type_: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_field_specifier(self, question, name, arrow, type_) } fn make_field_initializer(&mut self, name: Self::Output, arrow: Self::Output, value: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_field_initializer(self, name, arrow, value) } fn make_shape_type_specifier(&mut self, keyword: Self::Output, left_paren: Self::Output, fields: Self::Output, ellipsis: Self::Output, right_paren: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_shape_type_specifier(self, keyword, left_paren, fields, ellipsis, right_paren) } fn make_shape_expression(&mut self, keyword: Self::Output, left_paren: Self::Output, fields: Self::Output, right_paren: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_shape_expression(self, keyword, left_paren, fields, right_paren) } fn make_tuple_expression(&mut self, keyword: Self::Output, left_paren: Self::Output, items: Self::Output, right_paren: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_tuple_expression(self, keyword, left_paren, items, right_paren) } fn make_generic_type_specifier(&mut self, class_type: Self::Output, argument_list: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_generic_type_specifier(self, class_type, argument_list) } fn make_nullable_type_specifier(&mut self, question: Self::Output, type_: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_nullable_type_specifier(self, question, type_) } fn make_like_type_specifier(&mut self, tilde: Self::Output, type_: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_like_type_specifier(self, tilde, type_) } fn make_soft_type_specifier(&mut self, at: Self::Output, type_: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_soft_type_specifier(self, at, type_) } fn make_attributized_specifier(&mut self, attribute_spec: Self::Output, type_: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_attributized_specifier(self, attribute_spec, type_) } fn make_reified_type_argument(&mut self, reified: Self::Output, type_: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_reified_type_argument(self, reified, type_) } fn make_type_arguments(&mut self, left_angle: Self::Output, types: Self::Output, right_angle: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_type_arguments(self, left_angle, types, right_angle) } fn make_type_parameters(&mut self, left_angle: Self::Output, parameters: Self::Output, right_angle: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_type_parameters(self, left_angle, parameters, right_angle) } fn make_tuple_type_specifier(&mut self, left_paren: Self::Output, types: Self::Output, right_paren: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_tuple_type_specifier(self, left_paren, types, right_paren) } fn make_union_type_specifier(&mut self, left_paren: Self::Output, types: Self::Output, right_paren: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_union_type_specifier(self, left_paren, types, right_paren) } fn make_intersection_type_specifier(&mut self, left_paren: Self::Output, types: Self::Output, right_paren: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_intersection_type_specifier(self, left_paren, types, right_paren) } fn make_error(&mut self, error: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_error(self, error) } fn make_list_item(&mut self, item: Self::Output, separator: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_list_item(self, item, separator) } fn make_enum_class_label_expression(&mut self, qualifier: Self::Output, hash: Self::Output, expression: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_enum_class_label_expression(self, qualifier, hash, expression) } fn make_module_declaration(&mut self, attribute_spec: Self::Output, new_keyword: Self::Output, module_keyword: Self::Output, name: Self::Output, left_brace: Self::Output, exports: Self::Output, imports: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_module_declaration(self, attribute_spec, new_keyword, module_keyword, name, left_brace, exports, imports, right_brace) } fn make_module_exports(&mut self, exports_keyword: Self::Output, left_brace: Self::Output, exports: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_module_exports(self, exports_keyword, left_brace, exports, right_brace) } fn make_module_imports(&mut self, imports_keyword: Self::Output, left_brace: Self::Output, imports: Self::Output, right_brace: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_module_imports(self, imports_keyword, left_brace, imports, right_brace) } fn make_module_membership_declaration(&mut self, module_keyword: Self::Output, name: Self::Output, semicolon: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_module_membership_declaration(self, module_keyword, name, semicolon) } fn make_package_expression(&mut self, keyword: Self::Output, name: Self::Output) -> Self::Output { <Self as FlattenSmartConstructors>::make_package_expression(self, keyword, name) } }
hhvm/hphp/hack/src/decl/dune
; FFI OCaml to Rust (../../target/*/librust_decl_ffi.a) ; contains "external" function definition in .ml and ; the symbol is provided by the ocaml-rs Rust package via caml! macro (data_only_dirs cargo rust_decl_ffi direct_decl_smart_constructors) ; so dune doesn't look at rust stuff (library (name rust_decl_ffi) (modules) (wrapped false) (foreign_archives rust_decl_ffi)) (rule (targets librust_decl_ffi.a) (deps (source_tree %{workspace_root}/hack/src)) (locks /cargo) (action (run %{workspace_root}/hack/scripts/invoke_cargo.sh rust_decl_ffi rust_decl_ffi))) (library (name classDiff) (modules classDiff) (libraries decl_defs typing_defs) (preprocess (pps ppx_deriving.std))) (library (name decl) (modules decl) (libraries classDiff ast_provider decl_class decl_class_elements decl_env decl_fun_utils decl_folded_class decl_hint decl_nast decl_pos_utils decl_store full_fidelity naming naming_heap procs_procs shallow_class_diff shallow_classes_provider shallow_decl_defs typing_defs) (preprocess (pps ppx_deriving.std))) (library (name decl_nast) (modules decl_nast) (libraries decl_env decl_fun_utils decl_hint decl_init_check decl_pos_utils decl_reference decl_utils full_fidelity naming naming_attributes naming_attributes_params typing_defs) (preprocess (pps ppx_deriving.std))) (library (name decl_folded_class) (wrapped false) (modules decl_folded_class decl_inherit decl_requirements) (libraries ast_provider decl_class_elements decl_defs decl_enforceability decl_enum decl_env decl_fun_utils decl_init_check decl_instantiate decl_pos_utils decl_store decl_utils naming procs_procs shallow_classes_provider shallow_decl_defs typing_defs typing_pessimisation_deps) (preprocess (pps ppx_deriving.std))) (library (name direct_decl_parser) (modules direct_decl_parser) (libraries decl_parser_options shallow_decl_defs pos_or_decl typing_defs rust_decl_ffi search_utils) (preprocess (pps ppx_deriving.std))) (library (name decl_class) (modules decl_class) (libraries decl_defs decl_folded_class decl_instantiate decl_store decl_subst typing_defs) (preprocess (pps ppx_deriving.std))) (library (name decl_class_elements) (modules decl_class_elements) (libraries decl_defs decl_heap typing_defs) (preprocess (pps ppx_deriving.std))) (library (name decl_compare) (modules decl_compare) (libraries decl_defs decl_heap decl_pos_utils fanout naming_provider provider_context rust_provider_backend_stubs typechecker_options typing_defs typing_deps) (preprocess (pps ppx_deriving.std))) (library (name decl_defs) (modules decl_defs) (libraries pos_or_decl typing_defs utils_core) (preprocess (pps ppx_deriving.std))) (library (name decl_enforceability) (modules decl_enforceability) (libraries decl_env shallow_classes_provider typedef_provider naming_provider)) (library (name decl_enum) (modules decl_enum) (libraries decl_defs typing_defs) (preprocess (pps ppx_deriving.std))) (library (name decl_env) (modules decl_env) (libraries decl_defs decl_store provider_context typing_defs typing_pessimisation_deps typing_deps) (preprocess (pps ppx_deriving.std))) (library (name decl_export) (modules decl_export) (libraries decl decl_defs decl_store naming naming_heap utils_core) (preprocess (pps ppx_deriving.std))) (library (name decl_fun_utils) (modules decl_fun_utils) (libraries decl_defs decl_env decl_hint typing_defs ) (preprocess (pps ppx_deriving.std))) (library (name decl_heap) (modules decl_heap) (libraries decl_defs heap_shared_mem typing_defs) (preprocess (pps ppx_deriving.std))) (library (name decl_store) (modules decl_store) (libraries decl_defs decl_heap typing_defs) (preprocess (pps ppx_deriving.std))) (library (name decl_hint) (modules decl_hint) (libraries decl_defs decl_env typing_defs) (preprocess (pps ppx_deriving.std))) (library (name decl_init_check) (modules decl_init_check) (libraries decl_defs decl_env shallow_decl_defs typing_defs) (preprocess (pps ppx_deriving.std))) (library (name decl_instantiate) (modules decl_instantiate) (libraries decl_defs decl_subst shallow_decl_defs typing_defs) (preprocess (pps ppx_deriving.std))) (library (name decl_typedef_expand) (modules decl_typedef_expand) (libraries decl_subst decl_provider provider_context typing_defs) (preprocess (pps ppx_deriving.std))) (library (name decl_pos_utils) (modules decl_pos_utils) (libraries decl_defs shallow_decl_defs typing_defs) (preprocess (pps ppx_deriving.std))) (library (name decl_service) (modules decl_service) (libraries decl procs_procs utils_core) (preprocess (pps ppx_deriving.std))) (library (name decl_redecl_service) (modules decl_redecl_service) (libraries decl decl_class_elements decl_compare heap_global_storage naming procs_procs remote_old_decl_client rust_provider_backend_stubs server_progress shallow_decl_compare typing_deps utils_core utils_exit) (preprocess (pps ppx_deriving.std))) (library (name decl_subst) (modules decl_subst) (libraries decl_defs typing_defs) (preprocess (pps ppx_deriving.std))) (library (name decl_utils) (modules decl_utils) (libraries decl_defs naming_attributes naming_attributes_params shallow_decl_defs typing_defs typing_error ) (preprocess (pps ppx_deriving.std))) (library (name remote_old_decl_client) (modules remote_old_decl_client) (libraries db_path_provider file_info future naming_sqlite process process_types provider_context shallow_decl_defs sys_username sys_utils temp_file typing_defs remote_old_decls_ffi utils_config_file utils_core utils_www_root) (preprocess (pps ppx_deriving.std))) (library (name shallow_class_diff) (modules shallow_class_diff) (libraries classDiff decl_defs decl_pos_utils decl_utils package_info shallow_decl_defs typing_defs) (preprocess (pps ppx_deriving.std))) (library (name fanout) (modules fanout) (libraries typing_deps)) (library (name shallow_class_fanout) (modules shallow_class_fanout) (libraries classDiff decl_defs fanout naming_provider shallow_decl_defs typing_defs) (preprocess (pps ppx_deriving.std))) (library (name shallow_classes_heap) (modules shallow_classes_heap) (libraries decl_defs decl_utils heap_shared_mem naming naming_heap shallow_decl_defs typing_defs) (preprocess (pps ppx_deriving.std))) (library (name shallow_decl_compare) (modules shallow_decl_compare) (libraries classDiff decl_defs package_info shallow_class_diff shallow_class_fanout shallow_classes_provider shallow_decl_defs typing_defs) (preprocess (pps ppx_deriving.std))) (library (name shallow_decl_defs) (modules shallow_decl_defs) (libraries decl_defs typing_defs) (preprocess (pps ppx_deriving.std))) (library (name decl_counters) (modules decl_counters) (libraries counters logging utils_core relative_path) (preprocess (pps ppx_deriving.std))) (library (name direct_decl_service) (modules direct_decl_service) (libraries direct_decl_utils direct_decl_parser shallow_decl_defs file_info relative_path typing_defs provider_context utils_find procs_procs) (preprocess (pps ppx_deriving.std)))
OCaml
hhvm/hphp/hack/src/decl/fanout.ml
(** * Copyright (c) 2019, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module Dep = Typing_deps.Dep module DepSet = Typing_deps.DepSet type t = { changed: DepSet.t; to_recheck: DepSet.t; } let empty = { changed = DepSet.make (); to_recheck = DepSet.make () } let union { changed = changed1; to_recheck = to_recheck1 } { changed = changed2; to_recheck = to_recheck2 } = { changed = DepSet.union changed1 changed2; to_recheck = DepSet.union to_recheck1 to_recheck2; } let add_fanout_of mode dep { changed; to_recheck } = { changed = DepSet.add changed (Dep.make dep); to_recheck = DepSet.union (Typing_deps.get_ideps mode dep) to_recheck; }
OCaml Interface
hhvm/hphp/hack/src/decl/fanout.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. * *) (** Represents the "fanout" of a change, representing the cached information we must invalidate and the files we must re-typecheck if we want to produce a correct list of all errors in the repository which reflects those changes. *) type t = { changed: Typing_deps.DepSet.t; (** The subset of classes in changed files whose decls changed (excluding classes whose decls experienced a positions-only change). *) to_recheck: Typing_deps.DepSet.t; (** This set represents the dependents of the declarations which were changed. In order to detect all errors which may have resulted from the changes, we must re-typecheck all files containing these dependents. Because DepSet.t is lossy--it is only a set of symbol hashes--we cannot precisely reproduce the set of symbols which need rechecking. Instead, Typing_deps maintains a mapping from symbol hash to filename (exposed via Typing_deps.get_files). *) } val empty : t val union : t -> t -> t val add_fanout_of : Typing_deps_mode.t -> Typing_deps.Dep.dependency Typing_deps.Dep.variant -> t -> t
OCaml
hhvm/hphp/hack/src/decl/remote_old_decl_client.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 for getting old decls remotely. *) (*****************************************************************************) open Hh_prelude module Utils = struct let get_hh_version () = (* TODO: the following is a bug! *) let repo = Wwwroot.interpret_command_line_root_parameter [] in let hhconfig_path = Path.to_string (Path.concat repo Config_file.file_path_relative_to_repo_root) in let version = if Disk.file_exists hhconfig_path then let (_, config) = Config_file.parse_hhconfig hhconfig_path in Config_file.Getters.string_opt "version" config else None in match version with | None -> Hh_version.version | Some version -> let version = "v" ^ String_utils.lstrip version "^" in version let get_dev_build_version () = if String.is_empty Build_id.build_revision then Sys_username.get_logged_in_username () |> Option.value ~default:"anonymous" else Build_id.build_revision let make_manifold_path ~version = Printf.sprintf "hack_decl_prefetching/tree/prefetch/%s/shallow_decls" version let manifold_path_exists ~path = let cmd = Printf.sprintf "manifold exists %s" path in let code = Sys.command cmd in Int.equal code 0 let get_version () = if Build_id.is_dev_build then let version = get_dev_build_version () in let path = make_manifold_path ~version in if manifold_path_exists ~path then version else get_hh_version () else get_hh_version () let db_path_of_ctx ~(ctx : Provider_context.t) : Naming_sqlite.db_path option = ctx |> Provider_context.get_backend |> Db_path_provider.get_naming_db_path let name_to_decl_hash_opt ~(name : string) ~(db_path : Naming_sqlite.db_path) = let dep = Typing_deps.(Dep.make (Dep.Type name)) in let decl_hash = Naming_sqlite.get_decl_hash_by_64bit_dep db_path dep in decl_hash end module FetchAsync = struct (** The input record that gets passed from the main process to the daemon process *) type input = { hhconfig_version: string; destination_path: string; no_limit: bool; decl_hashes: string list; } (** The main entry point of the daemon process that fetches the remote old decl blobs and writes them to a file. *) let fetch { hhconfig_version; destination_path; no_limit; decl_hashes } : unit = begin match Remote_old_decls_ffi.get_decls hhconfig_version no_limit decl_hashes with | Ok decl_hashes_and_blobs -> let chan = Stdlib.open_out_bin destination_path in Marshal.to_channel chan decl_hashes_and_blobs []; Stdlib.close_out chan | Error msg -> Hh_logger.log "Error fetching remote decls: %s" msg end; (* The intention here is to force the daemon process to exit with an failed exit code so that the main process can detect the condition and log the outcome. *) assert (Disk.file_exists destination_path) (** The daemon entry registration - used by the main process *) let fetch_entry = Process.register_entry_point "remote_old_decls_fetch_async_entry" fetch end let fetch_async ~hhconfig_version ~destination_path ~no_limit decl_hashes = Hh_logger.log "Fetching %d remote old decls to %s" (List.length decl_hashes) destination_path; let open FetchAsync in FutureProcess.make (Process.run_entry Process_types.Default fetch_entry { hhconfig_version; destination_path; no_limit; decl_hashes }) (fun _output -> Hh_logger.log "Finished fetching remote old decls") let fetch_old_decls ~(ctx : Provider_context.t) (names : string list) : Shallow_decl_defs.shallow_class option SMap.t = let db_path_opt = Utils.db_path_of_ctx ~ctx in match db_path_opt with | None -> SMap.empty | Some db_path -> let decl_hashes = List.filter_map ~f:(fun name -> Utils.name_to_decl_hash_opt ~name ~db_path) names in (match decl_hashes with | [] -> SMap.empty | _ -> let hhconfig_version = Utils.get_version () in let start_t = Unix.gettimeofday () in let no_limit = TypecheckerOptions.remote_old_decls_no_limit (Provider_context.get_tcopt ctx) in let tmp_dir = Tempfile.mkdtemp ~skip_mocking:false in let destination_path = Path.(to_string @@ concat tmp_dir "decl_blobs") in let decl_fetch_future = fetch_async ~hhconfig_version ~destination_path ~no_limit decl_hashes in (match Future.get ~timeout:120 decl_fetch_future with | Error e -> Hh_logger.log "Failed to fetch decls from remote decl store: %s" (Future.error_to_string e); SMap.empty | Ok () -> let chan = Stdlib.open_in_bin destination_path in let decl_hashes_and_blobs : (string * string) list = Marshal.from_channel chan in let decl_blobs = List.map ~f:(fun (_decl_hash, blob) -> blob) decl_hashes_and_blobs in Stdlib.close_in chan; let decls = List.fold ~init:SMap.empty ~f:(fun acc blob -> let contents : Shallow_decl_defs.decl SMap.t = Marshal.from_string blob 0 in SMap.fold (fun name decl acc -> match decl with | Shallow_decl_defs.Class cls -> SMap.add name (Some cls) acc | _ -> acc) contents acc) decl_blobs in let telemetry = Telemetry.create () |> Telemetry.int_ ~key:"to_fetch" ~value:(List.length names) |> Telemetry.int_ ~key:"fetched" ~value:(SMap.cardinal decls) in Hh_logger.log "Fetched %d/%d decls remotely" (SMap.cardinal decls) (List.length names); HackEventLogger.remote_old_decl_end telemetry start_t; decls))
OCaml Interface
hhvm/hphp/hack/src/decl/remote_old_decl_client.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 fetch_old_decls : ctx:Provider_context.t -> string list -> Shallow_decl_defs.shallow_class option SMap.t module Utils : sig val get_dev_build_version : unit -> string val make_manifold_path : version:string -> string val name_to_decl_hash_opt : name:string -> db_path:Naming_sqlite.db_path -> string option val db_path_of_ctx : ctx:Provider_context.t -> Naming_sqlite.db_path option end
OCaml
hhvm/hphp/hack/src/decl/shallow_classes_heap.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 Shallow_decl_defs module Capacity = struct let capacity = 1000 end module Class = struct type t = shallow_class let description = "Decl_ShallowClass" end module Classes = SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.NonEvictable)) (StringKey) (Class) (Capacity)
OCaml Interface
hhvm/hphp/hack/src/decl/shallow_classes_heap.mli
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (** [Shallow_classes_heap] provides a cache of shallow class declarations. *) open Shallow_decl_defs module Capacity : sig val capacity : int end module Class : SharedMem.Value with type t = shallow_class module Classes : module type of SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.NonEvictable)) (StringKey) (Class) (Capacity)
OCaml
hhvm/hphp/hack/src/decl/shallow_class_diff.ml
(** * Copyright (c) 2019, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open ClassDiff open Reordered_argument_collections open Shallow_decl_defs module SN = Naming_special_names module Parents = struct type t = { extends: Typing_defs.decl_ty list; implements: Typing_defs.decl_ty list; req_extends: Typing_defs.decl_ty list; req_implements: Typing_defs.decl_ty list; req_class: Typing_defs.decl_ty list; uses: Typing_defs.decl_ty list; xhp_attr_uses: Typing_defs.decl_ty list; } [@@deriving eq] let of_shallow_class c = let { sc_extends; sc_implements; sc_req_extends; sc_req_implements; sc_uses; sc_req_class; sc_xhp_attr_uses; sc_mode = _; sc_final = _; sc_abstract = _; sc_is_xhp = _; sc_internal = _; sc_has_xhp_keyword = _; sc_kind = _; sc_module = _; sc_name = _; sc_tparams = _; sc_where_constraints = _; sc_xhp_enum_values = _; sc_xhp_marked_empty = _; sc_support_dynamic_type = _; sc_consts = _; sc_typeconsts = _; sc_props = _; sc_sprops = _; sc_constructor = _; sc_static_methods = _; sc_methods = _; sc_user_attributes = _; sc_enum_type = _; sc_docs_url = _; } = c in { extends = sc_extends; implements = sc_implements; req_extends = sc_req_extends; req_implements = sc_req_implements; req_class = sc_req_class; uses = sc_uses; xhp_attr_uses = sc_xhp_attr_uses; } end let merge_member_lists (get_name : 'member -> string) (l1 : 'member list) (l2 : 'member list) : ('member option * 'member option) SMap.t = (* When a member of a given name is declared multiple times, keep the first (as Decl_inheritance does). *) let map = List.fold l1 ~init:SMap.empty ~f:(fun map x -> let name = get_name x in if SMap.mem map name then map else SMap.add map ~key:name ~data:(Some x, None)) in List.fold l2 ~init:map ~f:(fun map y -> let name = get_name y in match SMap.find_opt map name with | Some (x, None) -> SMap.add map ~key:name ~data:(x, Some y) | None -> SMap.add map ~key:name ~data:(None, Some y) | Some (_, Some _) -> map) module type Member_S = sig type t val diff : t -> t -> member_change option val is_private : t -> bool val is_internal : t -> bool (** Whether adding this member implies that the constructor and the constructor of all descendants should be considered modified. This is the case for example for required XHP attributes. *) val constructor_is_changed_inheritance_when_added : t -> bool (** Whether modifying this member implies that the constructor and the constructor of all descendants should be considered modified. This is the case for example for required XHP attributes. *) val constructor_is_changed_inheritance_when_modified : old:t -> new_:t -> bool end (** Returns the diff of two member lists, plus a diff on the constructor if the member changes impact the constructor. *) let diff_members (type member) (members_left_right : (member option * member option) SMap.t) (module Member : Member_S with type t = member) (classish_kind : Ast_defs.classish_kind) (module_changed : bool) : member_change SMap.t * constructor_change = (* If both members are internal and the module changed, we have to treat it as a Modified change*) let check_module_change_internal m1 m2 diff = match diff with | None when module_changed && Member.is_internal m1 && Member.is_internal m2 -> Some Modified | None | Some _ -> diff in SMap.fold members_left_right ~init:(SMap.empty, None) ~f:(fun name old_and_new (diff, constructor_change) -> match old_and_new with | (None, None) -> failwith "merge_member_lists added (None, None)" | (Some member, None) | (None, Some member) when (not Ast_defs.(is_c_trait classish_kind)) && Member.is_private member -> (SMap.add diff ~key:name ~data:Private_change, constructor_change) | (Some _, None) -> (SMap.add diff ~key:name ~data:Removed, constructor_change) | (None, Some m) -> let constructor_change = max_constructor_change constructor_change (if Member.constructor_is_changed_inheritance_when_added m then Some Changed_inheritance else None) in (SMap.add diff ~key:name ~data:Added, constructor_change) | (Some old_member, Some new_member) -> let member_changes = Member.diff old_member new_member |> check_module_change_internal old_member new_member |> Option.value_map ~default:diff ~f:(fun ch -> SMap.add diff ~key:name ~data:ch) in let constructor_change = max_constructor_change constructor_change (if Member.constructor_is_changed_inheritance_when_modified ~old:old_member ~new_:new_member then Some Changed_inheritance else None) in (member_changes, constructor_change)) module ClassConst : Member_S with type t = shallow_class_const = struct type t = shallow_class_const let diff (c1 : shallow_class_const) c2 : member_change option = let c1 = Decl_pos_utils.NormalizeSig.shallow_class_const c1 in let c2 = Decl_pos_utils.NormalizeSig.shallow_class_const c2 in if equal_shallow_class_const c1 c2 then None else if not (Typing_defs.equal_class_const_kind c1.scc_abstract c2.scc_abstract) then Some Changed_inheritance else Some Modified let is_private _ = false let is_internal _ = false let constructor_is_changed_inheritance_when_added _ = false let constructor_is_changed_inheritance_when_modified ~old:_ ~new_:_ = false end module TypeConst : Member_S with type t = shallow_typeconst = struct type t = shallow_typeconst let diff tc1 tc2 : member_change option = let tc1 = Decl_pos_utils.NormalizeSig.shallow_typeconst tc1 in let tc2 = Decl_pos_utils.NormalizeSig.shallow_typeconst tc2 in if equal_shallow_typeconst tc1 tc2 then None else let open Typing_defs in match (tc1.stc_kind, tc2.stc_kind) with | (TCAbstract _, TCAbstract _) | (TCConcrete _, TCConcrete _) -> Some Modified | (_, (TCAbstract _ | TCConcrete _)) -> Some Changed_inheritance let is_private _ = false let is_internal _ = false let constructor_is_changed_inheritance_when_added _ = false let constructor_is_changed_inheritance_when_modified ~old:_ ~new_:_ = false end module Prop : Member_S with type t = shallow_prop = struct type t = shallow_prop let diff p1 p2 : member_change option = let p1 = Decl_pos_utils.NormalizeSig.shallow_prop p1 in let p2 = Decl_pos_utils.NormalizeSig.shallow_prop p2 in if equal_shallow_prop p1 p2 then None else if (not (Aast.equal_visibility p1.sp_visibility p2.sp_visibility)) || Bool.( <> ) (sp_abstract p1) (sp_abstract p2) then Some Changed_inheritance else Some Modified let is_private p : bool = Aast_defs.equal_visibility p.sp_visibility Aast_defs.Private let is_internal p : bool = Aast_defs.equal_visibility p.sp_visibility Aast_defs.Internal let constructor_is_changed_inheritance_when_added p = Xhp_attribute.opt_is_required p.sp_xhp_attr let constructor_is_changed_inheritance_when_modified ~old ~new_ = Xhp_attribute.opt_is_required new_.sp_xhp_attr && (not @@ Xhp_attribute.opt_is_required old.sp_xhp_attr) end module Method : Member_S with type t = shallow_method = struct type t = shallow_method let diff m1 m2 : member_change option = let m1 = Decl_pos_utils.NormalizeSig.shallow_method m1 in let m2 = Decl_pos_utils.NormalizeSig.shallow_method m2 in if equal_shallow_method m1 m2 then None else if (not (Aast.equal_visibility m1.sm_visibility m2.sm_visibility)) || Bool.( <> ) (sm_abstract m1) (sm_abstract m2) then Some Changed_inheritance else Some Modified let is_private m : bool = Aast_defs.equal_visibility m.sm_visibility Aast_defs.Private let is_internal m : bool = Aast_defs.equal_visibility m.sm_visibility Aast_defs.Internal let constructor_is_changed_inheritance_when_added _ = false let constructor_is_changed_inheritance_when_modified ~old:_ ~new_:_ = false end let diff_constructor old_cls new_cls old_cstr new_cstr : member_change option = let consistent1 = Decl_utils.consistent_construct_kind old_cls in let consistent2 = Decl_utils.consistent_construct_kind new_cls in if not (Typing_defs.equal_consistent_kind consistent1 consistent2) then Some Changed_inheritance else match (old_cstr, new_cstr) with | (None, None) -> None | (Some _, None) -> Some Removed | (None, Some _) -> Some Added | (Some old_method, Some new_method) -> Method.diff old_method new_method let diff_class_members (c1 : shallow_class) (c2 : shallow_class) : ClassDiff.member_diff = let diff = ClassDiff.empty_member_diff in let kind = c2.sc_kind in let module_changed = match (c1.sc_module, c2.sc_module) with | (Some (_, m1), Some (_, m2)) when String.equal m1 m2 -> false | (None, None) -> false | _ -> true in let diff = let get_name x = snd x.scc_name in let consts = merge_member_lists get_name c1.sc_consts c2.sc_consts in let (consts, constructor_change) = diff_members consts (module ClassConst : Member_S with type t = shallow_class_const) kind module_changed in { diff with consts; constructor = max_constructor_change diff.constructor constructor_change; } in let diff = let get_name x = snd x.stc_name in let typeconsts = merge_member_lists get_name c1.sc_typeconsts c2.sc_typeconsts in let (typeconsts, constructor_change) = diff_members typeconsts (module TypeConst : Member_S with type t = shallow_typeconst) kind module_changed in { diff with typeconsts; constructor = max_constructor_change diff.constructor constructor_change; } in let diff = let get_name x = snd x.sp_name in let props = merge_member_lists get_name c1.sc_props c2.sc_props in let (props, constructor_change) = diff_members props (module Prop : Member_S with type t = shallow_prop) kind module_changed in { diff with props; constructor = max_constructor_change diff.constructor constructor_change; } in let diff = let get_name x = snd x.sp_name in let sprops = merge_member_lists get_name c1.sc_sprops c2.sc_sprops in let (sprops, constructor_change) = diff_members sprops (module Prop : Member_S with type t = shallow_prop) kind module_changed in { diff with sprops; constructor = max_constructor_change diff.constructor constructor_change; } in let diff = let get_name x = snd x.sm_name in let methods = merge_member_lists get_name c1.sc_methods c2.sc_methods in let (methods, constructor_change) = diff_members methods (module Method : Member_S with type t = shallow_method) kind module_changed in { diff with methods; constructor = max_constructor_change diff.constructor constructor_change; } in let diff = let get_name x = snd x.sm_name in let smethods = merge_member_lists get_name c1.sc_static_methods c2.sc_static_methods in let (smethods, constructor_change) = diff_members smethods (module Method : Member_S with type t = shallow_method) kind module_changed in { diff with smethods; constructor = max_constructor_change diff.constructor constructor_change; } in let diff = let constructor = diff_constructor c1 c2 c1.sc_constructor c2.sc_constructor in { diff with constructor = max_constructor_change diff.constructor constructor; } in diff (** Return true if the two classes would (shallowly) produce the same member resolution order (the output of the Decl_linearize module). NB: It is critical for the correctness of incremental typechecking that every bit of information used by Decl_linearize is checked here! *) let mro_inputs_equal (c1 : shallow_class) (c2 : shallow_class) : bool = let is_to_string m = String.equal (snd m.sm_name) SN.Members.__toString in Typing_defs.equal_pos_id c1.sc_name c2.sc_name && Ast_defs.equal_classish_kind c1.sc_kind c2.sc_kind && Option.equal equal_shallow_method (List.find c1.sc_methods ~f:is_to_string) (List.find c2.sc_methods ~f:is_to_string) && List.equal Poly.( = ) c1.sc_tparams c2.sc_tparams && List.equal Poly.( = ) c1.sc_extends c2.sc_extends && List.equal Poly.( = ) c1.sc_implements c2.sc_implements && List.equal Poly.( = ) c1.sc_uses c2.sc_uses && List.equal Poly.( = ) c1.sc_req_extends c2.sc_req_extends && List.equal Poly.( = ) c1.sc_req_implements c2.sc_req_implements && List.equal Poly.( = ) c1.sc_xhp_attr_uses c2.sc_xhp_attr_uses (* The ConsistentConstruct attribute is propagated down the inheritance hierarchy, so we can model it with Changed_inheritance on the constructor. To do so, though, we need to remove the attribute while normalizing classes (so that we don't consider it a Major_change). *) let remove_consistent_construct_attribute sc = { sc with sc_user_attributes = List.filter sc.sc_user_attributes ~f:(fun ua -> not (String.equal (snd ua.Typing_defs.ua_name) SN.UserAttributes.uaConsistentConstruct)); } (* Normalize module if the class is public *) let remove_modules_if_public sc = if sc.sc_internal then sc else { sc with sc_module = None } let remove_members_except_to_string sc = { sc with sc_constructor = None; sc_consts = []; sc_typeconsts = []; sc_props = []; sc_sprops = []; sc_static_methods = []; sc_methods = List.filter sc.sc_methods ~f:(fun m -> String.equal (snd m.sm_name) SN.Members.__toString); } (* To normalize classes for comparison, we: - Remove the ConsistentConstruct attribute - Remove module if class itself is public - Remove all members (except for the toString method, which results in the implicit inclusion of the Stringish interface), - Replace all positions with Pos.none We consider any difference between normalized classes to be a "Major change". This means only that we have not implemented some means of computing a fanout for that change which is smaller than what would be added by Shallow_class_fanout.add_maximum_fanout (e.g., since we DO have fine-grained dependency tracking for uses of members, and can handle them in a more intelligent way, we remove them during major-change-detection). There are certainly opportunities for us to be cleverer about some kinds of changes, but any kind of cleverness in reducing fanout must be implemented with great care. *) let normalize sc ~same_package = let id sc = sc in sc |> remove_consistent_construct_attribute |> remove_members_except_to_string |> Decl_pos_utils.NormalizeSig.shallow_class |> if same_package then remove_modules_if_public else id let type_name ty = let (_, (_, name), tparams) = Decl_utils.unwrap_class_type ty in (name, tparams) let diff_value_lists values1 values2 ~equal ~get_name_value ~diff = if List.equal equal values1 values2 then None else Some (let values1 = List.map ~f:get_name_value values1 in let values2 = List.map ~f:get_name_value values2 in { NamedItemsListChange.order_change = not @@ List.equal String.equal (List.map ~f:fst values1) (List.map ~f:fst values2); per_name_changes = SMap.merge (SMap.of_list values1) (SMap.of_list values2) ~f:(fun _ value1 value2 -> match (value1, value2) with | (None, None) -> None | (None, Some _) -> Some ValueChange.Added | (Some _, None) -> Some ValueChange.Removed | (Some value1, Some value2) -> let open Option.Monad_infix in diff value1 value2 >>| fun change -> ValueChange.Modified change); }) let diff_of_equal equal x y = if equal x y then None else Some () let diff_type_lists = diff_value_lists ~equal:Typing_defs.ty_equal ~get_name_value:type_name ~diff: (diff_value_lists ~equal:Typing_defs.ty_equal ~get_name_value:type_name ~diff:(diff_of_equal Typing_defs.tyl_equal)) let diff_parents (c1 : Parents.t) (c2 : Parents.t) : parent_changes option = if Parents.equal c1 c2 then None else Some { extends_changes = diff_type_lists c1.Parents.extends c2.Parents.extends; implements_changes = diff_type_lists c1.Parents.implements c2.Parents.implements; req_extends_changes = diff_type_lists c1.Parents.req_extends c2.Parents.req_extends; req_implements_changes = diff_type_lists c1.Parents.req_implements c2.Parents.req_implements; req_class_changes = diff_type_lists c1.Parents.req_class c2.Parents.req_class; uses_changes = diff_type_lists c1.Parents.uses c2.Parents.uses; xhp_attr_changes = diff_type_lists c1.Parents.xhp_attr_uses c2.Parents.xhp_attr_uses; } let diff_kinds kind1 kind2 = if Ast_defs.equal_classish_kind kind1 kind2 then None else Some { KindChange.new_kind = kind2 } let diff_bools b1 b2 = match (b1, b2) with | (true, true) | (false, false) -> None | (false, true) -> Some BoolChange.Became | (true, false) -> Some BoolChange.No_more let diff_options option1 option2 ~diff = match (option1, option2) with | (None, None) -> None | (None, Some _) -> Some ValueChange.Added | (Some _, None) -> Some ValueChange.Removed | (Some value1, Some value2) -> (match diff value1 value2 with | None -> None | Some diff -> Some (ValueChange.Modified diff)) let diff_modules = diff_options ~diff:(diff_of_equal Ast_defs.equal_id) let diff (type value) ~(equal : value -> value -> bool) (old_value : value) (new_value : value) : value ValueDiff.t option = if equal old_value new_value then None else Some { ValueDiff.old_value; new_value } let diff_types = diff ~equal:Typing_defs.ty_equal let diff_enum_types (enum_type1 : Typing_defs.enum_type) (enum_type2 : Typing_defs.enum_type) : enum_type_change option = if Typing_defs.equal_enum_type enum_type1 enum_type2 then None else Option.some @@ let { Typing_defs.te_base = base1; te_constraint = constraint1; te_includes = includes1; } = enum_type1 in let { Typing_defs.te_base = base2; te_constraint = constraint2; te_includes = includes2; } = enum_type2 in { base_change = diff_types base1 base2; constraint_change = diff_options ~diff:diff_types constraint1 constraint2; includes_change = diff_type_lists includes1 includes2; } let diff_enum_type_options = diff_options ~diff:diff_enum_types let user_attribute_name_value { Typing_defs.ua_name = (_, name); ua_params } = (name, ua_params) let equal_user_attr_params = [%derive.eq: Typing_defs.user_attribute_param list] let diff_class_shells (c1 : shallow_class) (c2 : shallow_class) : class_shell_change = { classish_kind = c1.sc_kind; parent_changes = diff_parents (Parents.of_shallow_class c1) (Parents.of_shallow_class c2); type_parameters_change = diff_value_lists c2.sc_tparams c1.sc_tparams ~equal:Typing_defs.equal_decl_tparam ~get_name_value:(fun tparam -> (snd tparam.Typing_defs.tp_name, tparam)) ~diff:(diff_of_equal Typing_defs.equal_decl_tparam); kind_change = diff_kinds c1.sc_kind c2.sc_kind; final_change = diff_bools c1.sc_final c2.sc_final; abstract_change = diff_bools c1.sc_abstract c2.sc_abstract; is_xhp_change = diff_bools c1.sc_is_xhp c2.sc_is_xhp; internal_change = diff_bools c1.sc_internal c2.sc_internal; has_xhp_keyword_change = diff_bools c1.sc_has_xhp_keyword c2.sc_has_xhp_keyword; support_dynamic_type_change = diff_bools c1.sc_support_dynamic_type c2.sc_support_dynamic_type; module_change = diff_modules c1.sc_module c2.sc_module; xhp_enum_values_change = not @@ equal_xhp_enum_values c1.sc_xhp_enum_values c2.sc_xhp_enum_values; user_attributes_changes = diff_value_lists c1.sc_user_attributes c2.sc_user_attributes ~equal:Typing_defs.equal_user_attribute ~get_name_value:user_attribute_name_value ~diff:(diff_of_equal equal_user_attr_params); enum_type_change = diff_enum_type_options c1.sc_enum_type c2.sc_enum_type; } let same_package (info : PackageInfo.t) (c1 : shallow_class) (c2 : shallow_class) : bool = let get_package_for_module info sc_module = match sc_module with | Some (_, name) -> PackageInfo.get_package_for_module info name | None -> None in let p1 = get_package_for_module info c1.sc_module in let p2 = get_package_for_module info c2.sc_module in Option.equal Package.equal p1 p2 let diff_class (info : PackageInfo.t) (c1 : shallow_class) (c2 : shallow_class) : ClassDiff.t = let same_package = same_package info c1 c2 in let class_shell1 = normalize c1 ~same_package and class_shell2 = normalize c2 ~same_package in if not (equal_shallow_class class_shell1 class_shell2) then Major_change (MajorChange.Modified (diff_class_shells class_shell1 class_shell2)) else let mro_inputs_equal = mro_inputs_equal c1 c2 in let member_diff = diff_class_members c1 c2 in if mro_inputs_equal && ClassDiff.is_empty_member_diff member_diff then Unchanged else Minor_change member_diff
OCaml Interface
hhvm/hphp/hack/src/decl/shallow_class_diff.mli
(** * Copyright (c) 2019, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Shallow_decl_defs val diff_class : PackageInfo.t -> shallow_class -> shallow_class -> ClassDiff.t
OCaml
hhvm/hphp/hack/src/decl/shallow_class_fanout.ml
(** * Copyright (c) 2019, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open ClassDiff open Reordered_argument_collections open Typing_deps let class_names_from_deps ~ctx ~get_classes_in_file deps = let filenames = Naming_provider.get_files ctx deps in Relative_path.Set.fold filenames ~init:SSet.empty ~f:(fun file acc -> SSet.fold (get_classes_in_file file) ~init:acc ~f:(fun cid acc -> if DepSet.mem deps Dep.(make (Type cid)) then SSet.add acc cid else acc)) let include_fanout_of_dep (mode : Mode.t) (dep : Dep.t) (deps : DepSet.t) : DepSet.t = let fanout = Typing_deps.get_ideps_from_hash mode dep in DepSet.union fanout deps let get_minor_change_fanout ~(ctx : Provider_context.t) (class_dep : Dep.t) (member_diff : ClassDiff.member_diff) : DepSet.t = let mode = Provider_context.get_deps_mode ctx in let changed = DepSet.singleton class_dep in let acc = DepSet.singleton class_dep in let { consts; typeconsts; props; sprops; methods; smethods; constructor } = member_diff in let changed_and_descendants = lazy (Typing_deps.add_extend_deps mode changed) in (* Recheck any file with a dependency on the provided member in the changed class and in each of its descendants, even if the member was overridden in a subclass. This deals with the case where adding, removing, or changing the abstract-ness of a member causes some subclass which inherits a member of that name from multiple parents to resolve the conflict in a different way than it did previously. *) let recheck_descendants_and_their_member_dependents (acc : DepSet.t) member : DepSet.t = let changed_and_descendants = Lazy.force changed_and_descendants in DepSet.fold changed_and_descendants ~init:acc ~f:(fun dep acc -> DepSet.add acc dep |> include_fanout_of_dep mode (Typing_deps.Dep.make_member_dep_from_type_dep dep member)) in let add_member_fanout ~is_const (member : Dep.Member.t) (change : member_change) (acc : DepSet.t) = (* Consts and typeconsts have their types copied into descendant classes in folded decl (rather than being stored in a separate heap as methods and properties are). As a result, when using a const, we register a dependency only upon the class type at the use site. In contrast, if we use a method or property B::f which was inherited from A, we register a dependency both upon B::f and A::f, which is what allows us to avoid the more expensive use of recheck_descendants_and_their_member_dependents here. Since we don't register a dependency upon the const at its class of origin in this way, we must always take the more expensive path for consts. *) if is_const || ClassDiff.method_or_property_change_affects_descendants change then recheck_descendants_and_their_member_dependents acc member else include_fanout_of_dep mode (Dep.make_member_dep_from_type_dep class_dep member) acc in let add_member_fanouts ~is_const changes make_member acc = SMap.fold changes ~init:acc ~f:(fun name -> add_member_fanout ~is_const (make_member name)) in let acc = SMap.fold consts ~init:acc ~f:(fun name change acc -> let acc = (* If a const has been added or removed in an enum type, we must recheck all switch statements which need to have a case for each variant (exhaustive switch statements add an AllMembers dependency). We don't bother to test whether the class is an enum type because non-enum classes will have no AllMembers dependents anyway. *) match change with | Added | Removed -> recheck_descendants_and_their_member_dependents acc Dep.Member.all | _ -> acc in add_member_fanout ~is_const:true (Dep.Member.const name) change acc) in let acc = acc |> add_member_fanouts ~is_const:true typeconsts Dep.Member.const |> add_member_fanouts ~is_const:false props Dep.Member.prop |> add_member_fanouts ~is_const:false sprops Dep.Member.sprop |> add_member_fanouts ~is_const:false methods Dep.Member.method_ |> add_member_fanouts ~is_const:false smethods Dep.Member.smethod in let acc = Option.value_map constructor ~default:acc ~f:(fun change -> add_member_fanout ~is_const:false Dep.Member.constructor change acc) in acc let get_maximum_fanout (ctx : Provider_context.t) (class_dep : Dep.t) : DepSet.t = let mode = Provider_context.get_deps_mode ctx in Typing_deps.add_all_deps mode @@ DepSet.singleton class_dep let get_fanout ~(ctx : Provider_context.t) (class_name, diff) : DepSet.t = let class_dep = Dep.make (Dep.Type class_name) in match diff with | Unchanged -> DepSet.make () | Major_change _major_change -> get_maximum_fanout ctx class_dep | Minor_change minor_change -> get_minor_change_fanout ~ctx class_dep minor_change let direct_references_cardinal mode class_name : int = Typing_deps.get_ideps mode (Dep.Type class_name) |> DepSet.cardinal let descendants_cardinal mode class_name : int = (Typing_deps.add_extend_deps mode (DepSet.singleton @@ Dep.make @@ Dep.Type class_name) |> DepSet.cardinal) - 1 let children_cardinal mode class_name : int = Typing_deps.get_ideps mode (Dep.Extends class_name) |> DepSet.cardinal module Log : sig val log_class_fanout : Provider_context.t -> string * ClassDiff.t -> DepSet.t -> unit val log_fanout : Provider_context.t -> 'a list -> DepSet.t -> max_class_fanout_cardinal:int -> unit end = struct let do_log ctx ~fanout_cardinal = TypecheckerOptions.log_fanout ~fanout_cardinal @@ Provider_context.get_tcopt ctx let log_class_fanout ctx ((class_name : string), (diff : ClassDiff.t)) (fanout : DepSet.t) : unit = let fanout_cardinal = DepSet.cardinal fanout in if do_log ~fanout_cardinal ctx then let mode = Provider_context.get_deps_mode ctx in HackEventLogger.Fanouts.log_class ~class_name ~class_diff:(ClassDiff.show diff) ~fanout_cardinal ~class_diff_category:(ClassDiff.to_category_json diff) ~direct_references_cardinal:(direct_references_cardinal mode class_name) ~descendants_cardinal:(descendants_cardinal mode class_name) ~children_cardinal:(children_cardinal mode class_name) let log_fanout ctx (changes : _ list) (fanout : DepSet.t) ~max_class_fanout_cardinal : unit = let fanout_cardinal = DepSet.cardinal fanout in if do_log ~fanout_cardinal ctx then HackEventLogger.Fanouts.log ~changes_cardinal:(List.length changes) ~max_class_fanout_cardinal ~fanout_cardinal end let add_fanout ~ctx ((fanout_acc, max_class_fanout_cardinal) : DepSet.t * int) diff : DepSet.t * int = let fanout = get_fanout ~ctx diff in Log.log_class_fanout ctx diff fanout; let fanout_acc = DepSet.union fanout_acc fanout in let max_class_fanout_cardinal = Int.max max_class_fanout_cardinal (DepSet.cardinal fanout) in (fanout_acc, max_class_fanout_cardinal) let fanout_of_changes ~(ctx : Provider_context.t) (changes : (string * ClassDiff.t) list) : Fanout.t = let changed_deps = List.filter_map changes ~f:(fun (name, diff) -> Option.some_if (ClassDiff.has_changed diff) (Dep.make @@ Dep.Type name)) |> DepSet.of_list in let (to_recheck, max_class_fanout_cardinal) = List.fold changes ~init:(DepSet.make (), 0) ~f:(add_fanout ~ctx) in Log.log_fanout ctx changes to_recheck ~max_class_fanout_cardinal; { Fanout.changed = changed_deps; to_recheck }
OCaml Interface
hhvm/hphp/hack/src/decl/shallow_class_fanout.mli
(** * Copyright (c) 2019, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val fanout_of_changes : ctx:Provider_context.t -> (string * ClassDiff.t) list -> Fanout.t val class_names_from_deps : ctx:Provider_context.t -> get_classes_in_file:(Relative_path.t -> SSet.t) -> Typing_deps.DepSet.t -> SSet.t
OCaml
hhvm/hphp/hack/src/decl/shallow_decl_compare.ml
(** * Copyright (c) 2019, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open ClassDiff open Reordered_argument_collections open Shallow_decl_defs let diff_class_in_changed_file (package_info : PackageInfo.t) (old_classes : shallow_class option SMap.t) (new_classes : shallow_class option SMap.t) (class_name : string) : ClassDiff.t = let old_class_opt = SMap.find old_classes class_name in let new_class_opt = SMap.find new_classes class_name in match (old_class_opt, new_class_opt) with | (Some old_class, Some new_class) -> Shallow_class_diff.diff_class package_info old_class new_class | (None, None) -> Major_change MajorChange.Unknown | (None, Some _) -> Major_change MajorChange.Added | (Some _, None) -> Major_change MajorChange.Removed let compute_class_diffs (ctx : Provider_context.t) ~during_init ~(defs : FileInfo.names Relative_path.Map.t) : (string * ClassDiff.t) list = let all_defs = Relative_path.Map.fold defs ~init:FileInfo.empty_names ~f:(fun _ -> FileInfo.merge_names) in let possibly_changed_classes = all_defs.FileInfo.n_classes in let old_classes = Shallow_classes_provider.get_old_batch ctx ~during_init possibly_changed_classes in let new_classes = Shallow_classes_provider.get_batch ctx possibly_changed_classes in let package_info = Provider_context.get_package_info ctx in SSet.fold possibly_changed_classes ~init:[] ~f:(fun cid acc -> let diff = diff_class_in_changed_file package_info old_classes new_classes cid in Hh_logger.log "%s" (ClassDiff.pretty ~name:cid diff); if ClassDiff.equal diff Unchanged then acc else (cid, diff) :: acc) let compute_class_fanout (ctx : Provider_context.t) ~during_init ~(defs : FileInfo.names Relative_path.Map.t) (changed_files : Relative_path.t list) : Fanout.t = let file_count = List.length changed_files in Hh_logger.log "Detecting changes to classes in %d files:" file_count; let changes = compute_class_diffs ctx ~during_init ~defs in let change_count = List.length changes in if List.is_empty changes then Hh_logger.log "No class changes detected" else Hh_logger.log "Computing fanout from %d changed classes" change_count; Shallow_class_fanout.fanout_of_changes ~ctx changes
OCaml Interface
hhvm/hphp/hack/src/decl/shallow_decl_compare.mli
(** * Copyright (c) 2019, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (** Compare classes in files and deduce fanout. *) val compute_class_fanout : Provider_context.t -> during_init:bool -> defs:FileInfo.names Relative_path.Map.t -> Relative_path.t list -> Fanout.t
OCaml
hhvm/hphp/hack/src/decl/shallow_decl_defs.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 Typing_defs (* Is this bit set in the flags? *) let is_set bit flags = not (Int.equal 0 (Int.bit_and bit flags)) (* Set a single bit to a boolean value *) let set_bit bit value flags = if value then Int.bit_or bit flags else Int.bit_and (Int.bit_not bit) flags module PropFlags = struct type t = int [@@deriving eq] let empty = 0 let abstract_bit = 1 lsl 0 let const_bit = 1 lsl 1 let lateinit_bit = 1 lsl 2 let lsb_bit = 1 lsl 3 let needs_init_bit = 1 lsl 4 let php_std_lib_bit = 1 lsl 5 let readonly_bit = 1 lsl 6 let safe_global_variable_bit = 1 lsl 7 let no_auto_likes_bit = 1 lsl 8 let get_abstract = is_set abstract_bit let get_const = is_set const_bit let get_lateinit = is_set lateinit_bit let get_lsb = is_set lsb_bit let get_needs_init = is_set needs_init_bit let get_php_std_lib = is_set php_std_lib_bit let get_readonly = is_set readonly_bit let get_safe_global_variable = is_set safe_global_variable_bit let get_no_auto_likes = is_set no_auto_likes_bit let set_abstract = set_bit abstract_bit let set_const = set_bit const_bit let set_lateinit = set_bit lateinit_bit let set_lsb = set_bit lsb_bit let set_needs_init = set_bit needs_init_bit let set_php_std_lib = set_bit php_std_lib_bit let set_readonly = set_bit readonly_bit let set_safe_global_variable = set_bit safe_global_variable_bit let set_no_auto_likes = set_bit no_auto_likes_bit let make ~abstract ~const ~lateinit ~lsb ~needs_init ~php_std_lib ~readonly ~safe_global_variable ~no_auto_likes = empty |> set_abstract abstract |> set_const const |> set_lateinit lateinit |> set_lsb lsb |> set_needs_init needs_init |> set_php_std_lib php_std_lib |> set_readonly readonly |> set_safe_global_variable safe_global_variable |> set_no_auto_likes no_auto_likes let pp fmt t = if t = empty then Format.pp_print_string fmt "(empty)" else ( Format.fprintf fmt "@[<2>"; let sep = ref false in let print s = if !sep then Format.fprintf fmt " |@ "; Format.pp_print_string fmt s; sep := true in if get_abstract t then print "abstract"; if get_const t then print "const"; if get_lateinit t then print "lateinit"; if get_lsb t then print "lsb"; if get_needs_init t then print "needs_init"; if get_php_std_lib t then print "php_std_lib"; if get_readonly t then print "readonly"; if get_safe_global_variable t then print "safe_global_variable"; if get_no_auto_likes t then print "no_auto_likes"; Format.fprintf fmt "@,@]" ) let show = Format.asprintf "%a" pp end [@@ocamlformat "disable"] module MethodFlags = struct type t = int [@@deriving eq] let empty = 0 let abstract_bit = 1 lsl 0 let final_bit = 1 lsl 1 let override_bit = 1 lsl 2 let dynamicallycallable_bit = 1 lsl 3 let php_std_lib_bit = 1 lsl 4 let support_dynamic_type_bit = 1 lsl 5 let get_abstract = is_set abstract_bit let get_final = is_set final_bit let get_override = is_set override_bit let get_dynamicallycallable = is_set dynamicallycallable_bit let get_php_std_lib = is_set php_std_lib_bit let get_support_dynamic_type = is_set support_dynamic_type_bit let set_abstract = set_bit abstract_bit let set_final = set_bit final_bit let set_override = set_bit override_bit let set_dynamicallycallable = set_bit dynamicallycallable_bit let set_php_std_lib = set_bit php_std_lib_bit let set_support_dynamic_type = set_bit support_dynamic_type_bit let make ~abstract ~final ~override ~dynamicallycallable ~php_std_lib ~support_dynamic_type = empty |> set_abstract abstract |> set_final final |> set_override override |> set_dynamicallycallable dynamicallycallable |> set_php_std_lib php_std_lib |> set_support_dynamic_type support_dynamic_type let pp fmt t = if t = empty then Format.pp_print_string fmt "(empty)" else ( Format.fprintf fmt "@[<2>"; let sep = ref false in let print s = if !sep then Format.fprintf fmt " |@ "; Format.pp_print_string fmt s; sep := true in if get_abstract t then print "abstract"; if get_final t then print "final"; if get_override t then print "override"; if get_dynamicallycallable t then print "dynamicallycallable"; if get_php_std_lib t then print "php_std_lib"; if get_support_dynamic_type t then print "support_dynamic_type"; Format.fprintf fmt "@,@]" ) let show = Format.asprintf "%a" pp end [@@ocamlformat "disable"] type shallow_class_const = { scc_abstract: Typing_defs.class_const_kind; scc_name: Typing_defs.pos_id; scc_type: decl_ty; (** This field is used for two different meanings in two different places... enum class A:arraykey {int X="a";} -- here X.scc_type=\HH\MemberOf<A,int> enum B:int as arraykey {X="a"; Y=1; Z=B::X;} -- here X.scc_type=string, Y.scc_type=int, Z.scc_type=TAny In the later case, the scc_type is just a simple syntactic attempt to retrieve the type from the initializer. *) scc_refs: Typing_defs.class_const_ref list; (** This is a list of all scope-resolution operators "A::B" that are mentioned in the const initializer, for members of regular-enums and enum-class-enums to detect circularity of initializers. We don't yet have a similar mechanism for top-level const initializers. *) } [@@deriving eq, show] type shallow_typeconst = { stc_name: Typing_defs.pos_id; stc_kind: Typing_defs.typeconst; stc_enforceable: Pos_or_decl.t * bool; stc_reifiable: Pos_or_decl.t option; stc_is_ctx: bool; } [@@deriving eq, show] type shallow_prop = { sp_name: Typing_defs.pos_id; sp_xhp_attr: xhp_attr option; sp_type: decl_ty; sp_visibility: Ast_defs.visibility; sp_flags: PropFlags.t; } [@@deriving eq, show] type shallow_method = { sm_name: Typing_defs.pos_id; sm_type: decl_ty; sm_visibility: Ast_defs.visibility; sm_deprecated: string option; sm_flags: MethodFlags.t; sm_attributes: user_attribute list; } [@@deriving eq, show] type xhp_enum_values = Ast_defs.xhp_enum_value list SMap.t [@@deriving eq, show] type shallow_class = { sc_mode: FileInfo.mode; sc_final: bool; sc_abstract: bool; sc_is_xhp: bool; sc_internal: bool; sc_has_xhp_keyword: bool; sc_kind: Ast_defs.classish_kind; sc_module: Ast_defs.id option; sc_name: Typing_defs.pos_id; sc_tparams: decl_tparam list; sc_where_constraints: decl_where_constraint list; sc_extends: decl_ty list; sc_uses: decl_ty list; sc_xhp_attr_uses: decl_ty list; sc_xhp_enum_values: Ast_defs.xhp_enum_value list SMap.t; sc_xhp_marked_empty: bool; sc_req_extends: decl_ty list; sc_req_implements: decl_ty list; sc_req_class: decl_ty list; sc_implements: decl_ty list; sc_support_dynamic_type: bool; sc_consts: shallow_class_const list; sc_typeconsts: shallow_typeconst list; sc_props: shallow_prop list; sc_sprops: shallow_prop list; sc_constructor: shallow_method option; sc_static_methods: shallow_method list; sc_methods: shallow_method list; sc_user_attributes: user_attribute list; sc_enum_type: enum_type option; sc_docs_url: string option; } [@@deriving eq, show] let sp_abstract sp = PropFlags.get_abstract sp.sp_flags let sp_const sp = PropFlags.get_const sp.sp_flags let sp_lateinit sp = PropFlags.get_lateinit sp.sp_flags let sp_lsb sp = PropFlags.get_lsb sp.sp_flags let sp_needs_init sp = PropFlags.get_needs_init sp.sp_flags let sp_php_std_lib sp = PropFlags.get_php_std_lib sp.sp_flags let sp_readonly sp = PropFlags.get_readonly sp.sp_flags let sp_safe_global_variable sp = PropFlags.get_safe_global_variable sp.sp_flags let sm_abstract sm = MethodFlags.get_abstract sm.sm_flags let sm_final sm = MethodFlags.get_final sm.sm_flags let sm_override sm = MethodFlags.get_override sm.sm_flags let sm_dynamicallycallable sm = MethodFlags.get_dynamicallycallable sm.sm_flags let sm_php_std_lib sm = MethodFlags.get_php_std_lib sm.sm_flags let sm_support_dynamic_type sm = MethodFlags.get_support_dynamic_type sm.sm_flags type fun_decl = fun_elt [@@deriving show] type class_decl = shallow_class [@@deriving show] type typedef_decl = typedef_type [@@deriving show] type const_decl = Typing_defs.const_decl [@@deriving show] type module_decl = Typing_defs.module_def_type [@@deriving show] type decl = | Class of class_decl | Fun of fun_decl | Typedef of typedef_decl | Const of const_decl | Module of module_decl [@@deriving show] let to_class_decl_opt = function | Class decl -> Some decl | _ -> None let to_fun_decl_opt = function | Fun decl -> Some decl | _ -> None let to_typedef_decl_opt = function | Typedef decl -> Some decl | _ -> None let to_const_decl_opt = function | Const decl -> Some decl | _ -> None let to_module_decl_opt = function | Module decl -> Some decl | _ -> None
OCaml Interface
hhvm/hphp/hack/src/decl/shallow_decl_defs.mli
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Typing_defs module PropFlags : sig type t [@@deriving eq, show] val empty : t val get_abstract : t -> bool val get_const : t -> bool val get_lateinit : t -> bool val get_lsb : t -> bool val get_needs_init : t -> bool val get_php_std_lib : t -> bool val get_readonly : t -> bool val get_safe_global_variable: t -> bool val get_no_auto_likes : t -> bool val set_abstract : bool -> t -> t val set_const : bool -> t -> t val set_lateinit : bool -> t -> t val set_lsb : bool -> t -> t val set_needs_init : bool -> t -> t val set_php_std_lib : bool -> t -> t val set_readonly : bool -> t -> t val set_safe_global_variable: bool -> t -> t val set_no_auto_likes : bool -> t -> t val make : abstract:bool -> const:bool -> lateinit:bool -> lsb:bool -> needs_init:bool -> php_std_lib:bool -> readonly: bool -> safe_global_variable: bool -> no_auto_likes: bool -> t end [@@ocamlformat "disable"] module MethodFlags : sig type t [@@deriving eq, show] val empty : t val get_abstract : t -> bool val get_final : t -> bool val get_override : t -> bool val get_dynamicallycallable : t -> bool val get_php_std_lib : t -> bool val get_support_dynamic_type : t -> bool val set_abstract : bool -> t -> t val set_final : bool -> t -> t val set_override : bool -> t -> t val set_dynamicallycallable : bool -> t -> t val set_php_std_lib : bool -> t -> t val set_support_dynamic_type : bool -> t -> t val make : abstract:bool -> final:bool -> override:bool -> dynamicallycallable:bool -> php_std_lib:bool -> support_dynamic_type:bool -> t end [@@ocamlformat "disable"] type shallow_class_const = { scc_abstract: Typing_defs.class_const_kind; scc_name: Typing_defs.pos_id; scc_type: decl_ty; scc_refs: Typing_defs.class_const_ref list; } [@@deriving eq, show] type shallow_typeconst = { stc_name: Typing_defs.pos_id; stc_kind: Typing_defs.typeconst; stc_enforceable: Pos_or_decl.t * bool; stc_reifiable: Pos_or_decl.t option; stc_is_ctx: bool; } [@@deriving eq, show] type shallow_prop = { sp_name: Typing_defs.pos_id; sp_xhp_attr: xhp_attr option; sp_type: decl_ty; sp_visibility: Ast_defs.visibility; sp_flags: PropFlags.t; } [@@deriving eq, show] type shallow_method = { sm_name: Typing_defs.pos_id; sm_type: decl_ty; sm_visibility: Ast_defs.visibility; sm_deprecated: string option; sm_flags: MethodFlags.t; sm_attributes: user_attribute list; } [@@deriving eq, show] type xhp_enum_values = Ast_defs.xhp_enum_value list SMap.t [@@deriving eq, show] type shallow_class = { sc_mode: FileInfo.mode; sc_final: bool; sc_abstract: bool; sc_is_xhp: bool; sc_internal: bool; sc_has_xhp_keyword: bool; sc_kind: Ast_defs.classish_kind; sc_module: Ast_defs.id option; sc_name: Typing_defs.pos_id; sc_tparams: decl_tparam list; sc_where_constraints: decl_where_constraint list; sc_extends: decl_ty list; sc_uses: decl_ty list; sc_xhp_attr_uses: decl_ty list; sc_xhp_enum_values: xhp_enum_values; sc_xhp_marked_empty: bool; sc_req_extends: decl_ty list; sc_req_implements: decl_ty list; sc_req_class: decl_ty list; sc_implements: decl_ty list; sc_support_dynamic_type: bool; sc_consts: shallow_class_const list; sc_typeconsts: shallow_typeconst list; sc_props: shallow_prop list; sc_sprops: shallow_prop list; sc_constructor: shallow_method option; sc_static_methods: shallow_method list; sc_methods: shallow_method list; sc_user_attributes: user_attribute list; sc_enum_type: enum_type option; sc_docs_url: string option; } [@@deriving eq, show] val sp_abstract : shallow_prop -> bool val sp_const : shallow_prop -> bool val sp_lateinit : shallow_prop -> bool val sp_lsb : shallow_prop -> bool val sp_needs_init : shallow_prop -> bool val sp_php_std_lib : shallow_prop -> bool val sp_readonly : shallow_prop -> bool val sp_safe_global_variable : shallow_prop -> bool val sm_abstract : shallow_method -> bool val sm_final : shallow_method -> bool val sm_override : shallow_method -> bool val sm_dynamicallycallable : shallow_method -> bool val sm_php_std_lib : shallow_method -> bool val sm_support_dynamic_type : shallow_method -> bool type fun_decl = fun_elt [@@deriving show] type class_decl = shallow_class [@@deriving show] type typedef_decl = typedef_type [@@deriving show] type const_decl = Typing_defs.const_decl [@@deriving show] type module_decl = Typing_defs.module_def_type [@@deriving show] type decl = | Class of class_decl | Fun of fun_decl | Typedef of typedef_decl | Const of const_decl | Module of module_decl [@@deriving show] val to_class_decl_opt : decl -> class_decl option val to_fun_decl_opt : decl -> fun_decl option val to_typedef_decl_opt : decl -> typedef_decl option val to_const_decl_opt : decl -> const_decl option val to_module_decl_opt : decl -> module_decl option
TOML
hhvm/hphp/hack/src/decl/cargo/rust_decl_ffi/Cargo.toml
# @generated by autocargo [package] name = "rust_decl_ffi" version = "0.0.0" edition = "2021" [lib] path = "../../rust_decl_ffi/rust_decl_ffi.rs" test = false doctest = false crate-type = ["lib", "staticlib"] [dependencies] ast_and_decl_parser = { version = "0.0.0", path = "../../../parser/cargo/ast_and_decl_parser" } bumpalo = { version = "3.11.1", features = ["collections"] } direct_decl_parser = { version = "0.0.0", path = "../../../parser/api/cargo/direct_decl_parser" } hh_hash = { version = "0.0.0", path = "../../../utils/hh_hash" } ocamlrep = { version = "0.1.0", git = "https://github.com/facebook/ocamlrep/", branch = "main" } ocamlrep_caml_builtins = { version = "0.1.0", git = "https://github.com/facebook/ocamlrep/", branch = "main" } ocamlrep_ocamlpool = { version = "0.1.0", git = "https://github.com/facebook/ocamlrep/", branch = "main" } oxidized = { version = "0.0.0", path = "../../../oxidized" } oxidized_by_ref = { version = "0.0.0", path = "../../../oxidized_by_ref" } parser_core_types = { version = "0.0.0", path = "../../../parser/cargo/core_types" } relative_path = { version = "0.0.0", path = "../../../utils/rust/relative_path" }
TOML
hhvm/hphp/hack/src/decl/direct_decl_smart_constructors/Cargo.toml
# @generated by autocargo [package] name = "direct_decl_smart_constructors" version = "0.0.0" edition = "2021" [lib] path = "../direct_decl_smart_constructors.rs" test = false doctest = false [dependencies] arena_collections = { version = "0.0.0", path = "../../arena_collections" } bstr = { version = "1.4.0", features = ["serde", "std", "unicode"] } bumpalo = { version = "3.11.1", features = ["collections"] } escaper = { version = "0.0.0", path = "../../utils/escaper" } flatten_smart_constructors = { version = "0.0.0", path = "../../parser/cargo/flatten_smart_constructors" } hash = { version = "0.0.0", path = "../../utils/hash" } hh_autoimport_rust = { version = "0.0.0", path = "../../parser/cargo/hh_autoimport" } namespaces_rust = { version = "0.0.0", path = "../../parser/cargo/namespaces" } naming_special_names_rust = { version = "0.0.0", path = "../../naming" } oxidized = { version = "0.0.0", path = "../../oxidized" } oxidized_by_ref = { version = "0.0.0", path = "../../oxidized_by_ref" } parser_core_types = { version = "0.0.0", path = "../../parser/cargo/core_types" } smart_constructors = { version = "0.0.0", path = "../../parser/cargo/smart_constructors" }
hhvm/hphp/hack/src/decl/pos/dune
(library (name pos_or_decl) (wrapped false) (libraries decl_reference pos) (preprocess (pps ppx_deriving.std ppx_hash)))