language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
OCaml Interface
hhvm/hphp/hack/src/typing/nast_check/prop_modifier_prohibited_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. * *) val handler : Nast_visitor.handler_base
OCaml
hhvm/hphp/hack/src/typing/nast_check/read_from_append_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Aast open Nast_check_env let handler = object inherit Nast_visitor.handler_base method! at_expr env (_, _, e) = match e with | Array_get ((_, p, _), None) when not env.array_append_allowed -> Errors.add_error Nast_check_error.(to_user_error @@ Reading_from_append p) | _ -> () end
OCaml
hhvm/hphp/hack/src/typing/nast_check/shape_name_check.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast module ShapeSet = Ast_defs.ShapeSet let get_pos name = match name with | Ast_defs.SFlit_int (pos, _) | Ast_defs.SFlit_str (pos, _) | Ast_defs.SFclass_const (_, (pos, _)) -> pos let error_if_duplicate_names fdl = let _ = List.fold_left fdl ~init:ShapeSet.empty ~f:(fun seen (name, _) -> if ShapeSet.mem name seen then Errors.add_error Naming_error.( to_user_error @@ Field_name_already_bound (get_pos name)); ShapeSet.add name seen) in () let handler = object inherit Nast_visitor.handler_base method! at_expr _ expr = match expr with | (_, _, Shape fdl) -> error_if_duplicate_names fdl | _ -> () end
OCaml Interface
hhvm/hphp/hack/src/typing/nast_check/shape_name_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. * *) val handler : Nast_visitor.handler_base
OCaml
hhvm/hphp/hack/src/typing/nast_check/type_structure_leak_check.ml
(* * Copyright (c) 2022, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast let visitor = object (_this) inherit [_] Nast_visitor.iter_with_state as super method! on_expr (env, ancestor) ((_, _p, expr) as e) = let ancestor = match expr with | Is (_, _h) -> Some "an is-expression" | As (_, _h, _) -> Some "an as-expression" | _ -> ancestor in super#on_expr (env, ancestor) e method! on_hint (env, ancestor) ((pos, h_) as h) = match h_ with | Hrefinement _ -> (match ancestor with | Some kind -> Errors.add_error Nast_check_error.( to_user_error @@ Refinement_in_typestruct { pos; kind }) | None -> ()) | _ -> super#on_hint (env, ancestor) h end let handler = object inherit Nast_visitor.handler_base method! at_expr env = visitor#on_expr (env, None) method! at_class_ env class_ = List.iter class_.c_typeconsts ~f:(fun tc -> match tc.c_tconst_kind with | TCAbstract { c_atc_default = Some hint; _ } | TCConcrete { c_tc_type = hint; _ } -> let ancestor = Some (if tc.c_tconst_is_ctx then "a context constant" else "a type constant") in visitor#on_hint (env, ancestor) hint | _ -> ()) method! at_typedef env td = visitor#on_hint (env, Some "a type alias") td.t_kind end
OCaml
hhvm/hphp/hack/src/typing/nast_check/unbound_name_check.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (** * Checks to determine whether names referenced in a file are defined globally. * * NOTE: Unlike other nast checks, this one depends on and also * modifies global naming table state. We would rather have this done in typing * but currently there are multiple scenarios when the typechecker * does not comprehensively check expressions. We are then left with * an unrecorded dependency. This should be fixed on some more basic level. *) open Hh_prelude type env = { droot: Typing_deps.Dep.dependent Typing_deps.Dep.variant; ctx: Provider_context.t; type_params: Aast.reify_kind SMap.t; (* Need some context to differentiate global consts and other Id's *) seen_names: Pos.t SMap.t; (* Contexts where typedefs are valid typenames *) class_id_allow_typedef: bool; hint_allow_typedef: bool; hint_context: Name_context.t; } let handle_unbound_name env (pos, name) kind = (* We've already errored in naming if we get *Unknown* class *) if String.equal name Naming_special_names.Classes.cUnknown then () else begin Errors.add_error Naming_error.(to_user_error @@ Unbound_name { pos; name; kind }); (* In addition to reporting errors, we also add to the global dependency table *) let dep = let open Name_context in match kind with | FunctionNamespace -> Typing_deps.Dep.Fun name | TypeNamespace -> Typing_deps.Dep.Type name | ConstantNamespace -> Typing_deps.Dep.GConst name | TraitContext -> Typing_deps.Dep.Type name | ClassContext -> Typing_deps.Dep.Type name | ModuleNamespace -> Typing_deps.Dep.Module name | PackageNamespace -> failwith "impossible match case" (* TODO (T148526825) *) in Typing_deps.add_idep (Provider_context.get_deps_mode env.ctx) env.droot dep end let has_canon_name env get_name get_pos (pos, name) = match get_name env.ctx name with | None -> false | Some suggest_name -> begin match get_pos env.ctx suggest_name with | None -> false | Some suggest_pos -> Errors.add_error Naming_error.( to_user_error @@ Did_you_mean { pos; name; suggest_pos; suggest_name }); true end let check_fun_name env ((_, name) as id) = if Naming_special_names.SpecialFunctions.is_special_function name then () else if Naming_provider.fun_exists env.ctx name then () else if has_canon_name env Naming_provider.get_fun_canon_name Naming_global.GEnv.fun_pos id then () else handle_unbound_name env id Name_context.FunctionNamespace let check_const_name env ((_, name) as id) = if Naming_provider.const_exists env.ctx name then () else handle_unbound_name env id Name_context.ConstantNamespace let check_module_name env ((_, name) as id) = if Naming_provider.module_exists env.ctx name then () else handle_unbound_name env id Name_context.ModuleNamespace let check_module_if_present env id_opt = Option.iter id_opt ~f:(check_module_name env) let check_package_name env (pos, name) = if PackageInfo.package_exists (Provider_context.get_package_info env.ctx) name then () else Errors.add_error Naming_error.( to_user_error @@ Unbound_name { pos; name; kind = Name_context.PackageNamespace }) let check_type_name ?(kind = Name_context.TypeNamespace) env ((pos, name) as id) ~allow_typedef ~allow_generics = if String.equal name Naming_special_names.Classes.cHH_BuiltinEnum then () else match SMap.find_opt name env.type_params with | Some reified -> (* TODO: These throw typing errors instead of naming errors *) if not allow_generics then Errors.add_error Nast_check_error.(to_user_error @@ Generics_not_allowed pos); begin match reified with | Aast.Erased -> Errors.add_error Nast_check_error.( to_user_error @@ Generic_at_runtime { pos; prefix = "Erased" }) | Aast.SoftReified -> Errors.add_error Nast_check_error.( to_user_error @@ Generic_at_runtime { pos; prefix = "Soft reified" }) | Aast.Reified -> () end | None -> begin match Naming_provider.get_type_kind env.ctx name with | Some Naming_types.TTypedef when not allow_typedef -> let def_pos = Naming_provider.get_type_pos env.ctx name |> Option.value_exn in let (decl_pos, _) = Naming_global.GEnv.get_type_full_pos env.ctx (def_pos, name) in Errors.add_error Naming_error.( to_user_error @@ Unexpected_typedef { pos; decl_pos; expected_kind = kind }) | Some _ -> () | None -> if has_canon_name env Naming_provider.get_type_canon_name Naming_global.GEnv.type_pos id then () else handle_unbound_name env id kind end let check_type_hint ?(kind = Name_context.TypeNamespace) env ((_, name) as id) ~allow_typedef ~allow_generics = if String.equal name Naming_special_names.Typehints.wildcard then () else check_type_name ~kind env id ~allow_typedef ~allow_generics let extend_type_params init paraml = List.fold_right ~init ~f:(fun { Aast.tp_name = (_, name); tp_reified; _ } acc -> SMap.add name tp_reified acc) paraml let handler ctx = object inherit [env] Stateful_aast_visitor.default_nast_visitor_with_state (* The following are all setting the environments / context correctly *) method initial_state = { droot = Typing_deps.Dep.Fun ""; ctx; type_params = SMap.empty; seen_names = SMap.empty; class_id_allow_typedef = false; hint_allow_typedef = true; hint_context = Name_context.TypeNamespace; } method! at_class_ env c = let new_env = { env with droot = Typing_deps.Dep.Type (snd c.Aast.c_name); type_params = extend_type_params SMap.empty c.Aast.c_tparams; } in check_module_if_present new_env c.Aast.c_module; new_env method! at_typedef env td = let new_env = { env with droot = Typing_deps.Dep.Type (snd td.Aast.t_name); type_params = extend_type_params SMap.empty td.Aast.t_tparams; } in check_module_if_present new_env td.Aast.t_module; new_env method! at_fun_def env fd = let new_env = { env with droot = Typing_deps.Dep.Fun (snd fd.Aast.fd_name); type_params = extend_type_params env.type_params fd.Aast.fd_tparams; } in check_module_if_present new_env fd.Aast.fd_module; new_env method! at_gconst env gconst = let new_env = { env with droot = Typing_deps.Dep.GConst (snd gconst.Aast.cst_name) } in new_env method! at_method_ env m = { env with type_params = extend_type_params env.type_params m.Aast.m_tparams; } method! at_targ env _ = { env with hint_allow_typedef = true } method! at_class_hint env _ = { env with hint_context = Name_context.ClassContext; hint_allow_typedef = false; } method! at_trait_hint env _ = { env with hint_context = Name_context.TraitContext; hint_allow_typedef = false; } method! at_xhp_attr_hint env _ = { env with hint_allow_typedef = false } (* Below are the methods where we check for unbound names *) method! at_expr env (_, _, e) = match e with | Aast.FunctionPointer (Aast.FP_id ((p, name) as id), _) | Aast.(Call { func = (_, _, Aast.Id ((p, name) as id)); _ }) -> let () = check_fun_name env id in { env with seen_names = SMap.add name p env.seen_names } | Aast.Id ((p, name) as id) -> let () = match SMap.find_opt name env.seen_names with | None -> check_const_name env id | Some pos when not @@ Pos.equal p pos -> check_const_name env id | _ -> () in env | Aast.Method_caller (id, _) | Aast.Xml (id, _, _) -> let () = check_type_name env ~allow_typedef:false ~allow_generics:false ~kind:Name_context.ClassContext id in env | Aast.Class_const ((_, _, Aast.CI _), (_, s)) when String.equal s "class" -> { env with class_id_allow_typedef = true } | Aast.Obj_get (_, (_, _, Aast.Id (p, name)), _, _) -> { env with seen_names = SMap.add name p env.seen_names } | Aast.EnumClassLabel (Some cname, _) -> let allow_typedef = (* we might reconsider this ? *) false in let () = check_type_name env ~allow_typedef ~allow_generics:false ~kind:Name_context.ClassContext cname in env | Aast.Package pkg -> let () = check_package_name env pkg in env | _ -> env method! at_shape_field_name env sfn = let () = match sfn with | Ast_defs.SFclass_const (id, _) -> check_type_name env ~allow_typedef:false ~allow_generics:false ~kind:Name_context.ClassContext id | _ -> () in env method! at_user_attribute env { Aast.ua_name; Aast.ua_params; _ } = let () = if not @@ Naming_special_names.UserAttributes.is_reserved (snd ua_name) then check_type_name env ~allow_typedef:false ~allow_generics:false ~kind:Name_context.ClassContext ua_name in let () = if String.equal (snd ua_name) Naming_special_names.UserAttributes.uaCrossPackage then List.iter ~f:(function | (_, pos, Aast.String pkg_name) -> check_package_name env (pos, pkg_name) | _ -> ()) ua_params in env method! at_class_id env (_, _, ci) = match ci with | Aast.CI id -> let () = check_type_name env ~allow_typedef:env.class_id_allow_typedef ~allow_generics:true ~kind:Name_context.ClassContext id in env | _ -> env method! at_catch env (id, _, _) = let () = check_type_name env ~allow_typedef:false ~allow_generics:false ~kind:Name_context.ClassContext id in env method! at_hint env h = match snd h with | Aast.Happly (id, _) -> let () = check_type_hint env ~allow_typedef:env.hint_allow_typedef ~allow_generics:false ~kind:env.hint_context id in (* Intentionally set allow_typedef to true for a hint's type parameters * * because there are no runtime restrictions *) { env with hint_allow_typedef = true } | _ -> env end
OCaml Interface
hhvm/hphp/hack/src/typing/nast_check/unbound_name_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 env val handler : Provider_context.t -> env Stateful_aast_visitor.default_nast_visitor_with_state
OCaml
hhvm/hphp/hack/src/typing/nast_check/well_formed_internal_trait.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast module SN = Naming_special_names let handler = object inherit Nast_visitor.handler_base method! at_class_ env c = if Option.is_some env.Nast_check_env.module_ then match c.c_kind with | Ast_defs.Ctrait when not c.c_internal -> let trait_pos = fst c.c_name in let check visibility pos member = if Aast.equal_visibility Aast.Internal (visibility member) then Errors.add_error Nast_check_error.( to_user_error @@ Internal_member_inside_public_trait { member_pos = pos member; trait_pos }) in List.iter c.c_methods ~f:(check (fun meth -> meth.m_visibility) (fun meth -> meth.m_span)); List.iter c.c_vars ~f:(check (fun cv -> cv.cv_visibility) (fun cv -> cv.cv_span)) | Ast_defs.Ctrait | Ast_defs.Cclass _ | Ast_defs.Cinterface | Ast_defs.Cenum | Ast_defs.Cenum_class _ -> () end
hhvm/hphp/hack/src/typing/service/dune
(library (name tast_hashes) (wrapped false) (modules tast_hashes) (libraries collections provider_context relative_path typing_ast) (preprocess (pps ppx_yojson_conv))) (library (name type_counter) (wrapped false) (modules type_counter) (libraries collections provider_context relative_path typing_ast tast_env) (preprocess (pps ppx_deriving.std ppx_yojson_conv))) (library (name map_reduce_ffi) (wrapped false) (modules map_reduce_ffi) (libraries tast_hashes type_counter) (preprocess (pps ppx_yojson_conv))) (library (name map_reduce) (wrapped false) (modules map_reduce) (libraries provider_context collections map_reduce_ffi relative_path tast_hashes typing_ast) (preprocess (pps ppx_deriving.std))) (library (name typing_service_types) (wrapped false) (modules typing_service_types) (libraries biglist core_kernel errors hg map_reduce relative_path typechecker_options typing_deps) (preprocess (pps ppx_deriving.std)))
OCaml
hhvm/hphp/hack/src/typing/service/map_reduce.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude module type MapReducer = sig type t val is_enabled : TypecheckerOptions.t -> bool val map : Provider_context.t -> Relative_path.t -> Tast.by_names -> t val reduce : t -> t -> t val finalize : progress:(string -> unit) -> init_id:string -> recheck_id:string option -> t -> unit end [@@@warning "-32"] (* for ppxs *) (* An enumeration of all supported map reducers. If you want to add a map-reducer, add a variant here and let the compiler guide you. *) type map_reducer = | TastHashes | TypeCounter [@@deriving eq, ord, show, enum] [@@@warning "+32"] (** Link each map-reducer to the type of its data. *) type _ map_reducer_type = | TypeForTastHashes : Tast_hashes.t map_reducer_type | TypeForTypeCounter : Type_counter.t map_reducer_type (** Existential wrapper around the type for a map-reducer. *) type any_map_reducer_type = | TypeForAny : 'a map_reducer_type -> any_map_reducer_type (** A mapping from a supported map-reducer to a witness of its type. Needs an entry when adding a map-reducer. *) let type_for : map_reducer -> any_map_reducer_type = function | TastHashes -> TypeForAny TypeForTastHashes | TypeCounter -> TypeForAny TypeForTypeCounter (** A mapping from a map-reducer type to a compatible implementation operating on data for that type. Needs an entry when adding a map-reducer. *) let implementation_for (type t) (mr : t map_reducer_type) : (module MapReducer with type t = t) = match mr with | TypeForTastHashes -> (module Tast_hashes) | TypeForTypeCounter -> (module Type_counter) module MRMap = WrappedMap.Make (struct type t = map_reducer let compare = compare_map_reducer end) (** Existential wrapper around any map-reducer with a value of its intermediate data type attached. *) type map_reducer_result = | MapReducerResult : ('a map_reducer_type * 'a) -> map_reducer_result (** Witness that two values are of the same type. * Needs an entry when adding a map-reducer. *) let refine_map_reducer_result (type a b) (x : a map_reducer_type) (xv : a) (y : b map_reducer_type) (yv : b) : (a * a) option = match (x, y) with | (TypeForTastHashes, TypeForTastHashes) -> Some (xv, yv) | (TypeForTastHashes, _) -> None | (TypeForTypeCounter, TypeForTypeCounter) -> Some (xv, yv) | (TypeForTypeCounter, _) -> None let all_of_map_reducer : map_reducer list = List.init (max_map_reducer - min_map_reducer + 1) ~f:(fun i -> map_reducer_of_enum (i + min_map_reducer) |> Option.value_exn) (** A list of all reducers with a function that can tell you whether they are enabled. Evaluated at module initialization time, because we don't want to do the resolution from map-reducer to function everytime. *) let all_map_reducers : ((TypecheckerOptions.t -> bool) * map_reducer) list = List.map all_of_map_reducer ~f:(fun mr -> match type_for mr with | TypeForAny typed_mr -> let (module MR) = implementation_for typed_mr in (MR.is_enabled, mr)) type t = map_reducer_result MRMap.t let empty = MRMap.empty let map ctx path tasts = let tcopt = Provider_context.get_tcopt ctx in let results = List.filter_map all_map_reducers ~f:(fun (is_enabled, mr) -> if is_enabled tcopt then match type_for mr with | TypeForAny typed_mr -> let (module MR) = implementation_for typed_mr in Some (mr, MapReducerResult (typed_mr, MR.map ctx path tasts)) else None) in MRMap.of_list results let reduce xs ys = let combine (_mr : map_reducer) (x : map_reducer_result) (y : map_reducer_result) = match (x, y) with | (MapReducerResult (typed_x, x_value), MapReducerResult (typed_y, y_value)) -> let (x, y) = refine_map_reducer_result typed_x x_value typed_y y_value |> Option.value_exn ~message:"impossible, they have to be the same type" in let (module MR) = implementation_for typed_x in let z = MR.reduce x y in Some (MapReducerResult (typed_x, z)) in (* This is lightning fast when we don't have any map-reducers enabled which is the common case. *) MRMap.union ~combine xs ys let finalize ~progress ~init_id ~recheck_id xs = let do_ _key x = match x with | MapReducerResult (typed_x, x_value) -> let (module MR) = implementation_for typed_x in MR.finalize ~progress ~init_id ~recheck_id x_value in MRMap.iter do_ xs let to_ffi xs = let f _key v s = let open Map_reduce_ffi in match v with | MapReducerResult (TypeForTastHashes, tast_hashes) -> { s with tast_hashes = Some tast_hashes } | MapReducerResult (TypeForTypeCounter, type_counter) -> { s with type_counter = Some type_counter } in MRMap.fold f xs Map_reduce_ffi.empty let of_ffi s = let Map_reduce_ffi.{ tast_hashes; type_counter } = s in let elems = List.filter_map ~f:Fn.id [ Option.map tast_hashes ~f:(fun tast_hashes -> (TastHashes, MapReducerResult (TypeForTastHashes, tast_hashes))); Option.map type_counter ~f:(fun type_counter -> (TypeCounter, MapReducerResult (TypeForTypeCounter, type_counter))); ] in MRMap.of_list elems
OCaml Interface
hhvm/hphp/hack/src/typing/service/map_reduce.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. * *) (** A map-reducer maps a TAST into intermediate data, and then reduces a bunch of intermediate data to a single value. *) module type MapReducer = sig (** Type of the intermediate and reduced data. *) type t (** A function that takes type checker options and returns whether the map-reducer is enabled *) val is_enabled : TypecheckerOptions.t -> bool (** A map function that takes in a TAST and produces the intermediate data. Note that we don't make guarantees about the uniqueness of the file path. *) val map : Provider_context.t -> Relative_path.t -> Tast.by_names -> t (** Reduce two intermediate data elements. *) val reduce : t -> t -> t (** Consume the final result of the full map-reduce analysis. *) val finalize : progress:(string -> unit) -> init_id:string -> recheck_id:string option -> t -> unit end (** The result of an analysis. *) type t (** The empty analysis. *) val empty : t (** Take in a TAST and analyze it. *) val map : Provider_context.t -> Relative_path.t -> Tast.by_names -> t (** Reduce two analysis into one. *) val reduce : t -> t -> t (** Consume the final result of the full map-reduce analysis. *) val finalize : progress:(string -> unit) -> init_id:string -> recheck_id:string option -> t -> unit (** Convert the results of an anlysis to an FFI friendly data structure *) val to_ffi : t -> Map_reduce_ffi.t (** Read in the results of an analysis from an FFI friendly data structure *) val of_ffi : Map_reduce_ffi.t -> t
OCaml
hhvm/hphp/hack/src/typing/service/map_reduce_ffi.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"] (* yojson *) (** Auxiliary type used for communicating map-reduce data across FFI boundaries. *) type t = { tast_hashes: Tast_hashes.t option; [@yojson.option] type_counter: Type_counter.t option; [@yojson.option] } [@@deriving yojson_of] let empty = { tast_hashes = None; type_counter = None }
OCaml
hhvm/hphp/hack/src/typing/service/tast_hashes.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude type hash = Hash.hash_value let yojson_of_hash = yojson_of_int type by_names = { fun_tast_hashes: hash SMap.t; [@yojson_drop_if SMap.is_empty] class_tast_hashes: hash SMap.t; [@yojson_drop_if SMap.is_empty] typedef_tast_hashes: hash SMap.t; [@yojson_drop_if SMap.is_empty] gconst_tast_hashes: hash SMap.t; [@yojson_drop_if SMap.is_empty] module_tast_hashes: hash SMap.t; [@yojson_drop_if SMap.is_empty] } [@@deriving yojson_of] type t = by_names Relative_path.Map.t [@@deriving yojson_of] let hash_tasts { Tast.fun_tasts; class_tasts; typedef_tasts; gconst_tasts; module_tasts } : by_names = { fun_tast_hashes = SMap.map Tast.hash_def_with_dynamic fun_tasts; class_tast_hashes = SMap.map Tast.hash_def_with_dynamic class_tasts; typedef_tast_hashes = SMap.map Tast.hash_def typedef_tasts; gconst_tast_hashes = SMap.map Tast.hash_def gconst_tasts; module_tast_hashes = SMap.map Tast.hash_def module_tasts; } let union_by_names x y = { fun_tast_hashes = SMap.union x.fun_tast_hashes y.fun_tast_hashes; class_tast_hashes = SMap.union x.class_tast_hashes y.class_tast_hashes; typedef_tast_hashes = SMap.union x.typedef_tast_hashes y.typedef_tast_hashes; gconst_tast_hashes = SMap.union x.gconst_tast_hashes y.gconst_tast_hashes; module_tast_hashes = SMap.union x.module_tast_hashes y.module_tast_hashes; } let error_while_hashing { Tast.fun_tasts; class_tasts; typedef_tasts; gconst_tasts; module_tasts } : by_names = let minus_one _ = -1 in { fun_tast_hashes = SMap.map minus_one fun_tasts; class_tast_hashes = SMap.map minus_one class_tasts; typedef_tast_hashes = SMap.map minus_one typedef_tasts; gconst_tast_hashes = SMap.map minus_one gconst_tasts; module_tast_hashes = SMap.map minus_one module_tasts; } let empty = Relative_path.Map.empty let union m1 m2 = Relative_path.Map.union m1 m2 let add m ~key ~data = match data with | None -> m | Some data -> Relative_path.Map.add m ~key ~data let is_enabled tcopt = TypecheckerOptions.dump_tast_hashes tcopt let map _ctx path tasts = let data = hash_tasts tasts in add empty ~key:path ~data:(Some data) let reduce xs ys = Relative_path.Map.union ~combine:(fun _key x y -> Some (union_by_names x y)) xs ys let finalize ~progress ~init_id ~recheck_id tast_hashes = progress "Converting TAST hashes to JSON"; let tast_hashes_json = yojson_of_t tast_hashes in progress "Writing TAST hashes to disk"; let tast_dir = Tmp.make_dir_in_tmp ~description_what_for:"tast_hashes" ~root:None in let tast_hashes_file = Filename.concat tast_dir (Printf.sprintf "initId%s_recheckId%s.json" init_id (Option.value recheck_id ~default:"None")) in Out_channel.with_file tast_hashes_file ~f:(fun out -> Yojson.Safe.pretty_to_channel out tast_hashes_json)
OCaml Interface
hhvm/hphp/hack/src/typing/service/tast_hashes.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 by_names type t [@@deriving yojson_of] val hash_tasts : Tast.by_names -> by_names (** Return a by_names structure with all hash values equal to -1 *) val error_while_hashing : Tast.by_names -> by_names val empty : t val union : t -> t -> t val add : t -> key:Relative_path.t -> data:by_names option -> t val is_enabled : TypecheckerOptions.t -> bool val map : Provider_context.t -> Relative_path.t -> Tast.by_names -> t val reduce : t -> t -> t val finalize : progress:(string -> unit) -> init_id:string -> recheck_id:string option -> t -> unit
OCaml
hhvm/hphp/hack/src/typing/service/type_counter.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude type entity = | Class of string | Function of string [@@deriving ord, yojson_of] type pos = Pos.t [@@deriving ord] let yojson_of_pos pos = let filename = Pos.to_relative_string pos |> Pos.filename in let line = Pos.line pos in yojson_of_string @@ Format.sprintf "%s:%d" filename line type entity_pos = pos * entity [@@deriving ord, yojson_of] type logged_type = | Like | NonLike | Mixed | SupportdynOfMixed | Dynamic | Tany [@@deriving ord, yojson_of] type category = | Expression | Obj_get_receiver | Class_get_receiver | Class_const_receiver | Property | Parameter | Return [@@deriving ord, yojson_of] let dynamic = Typing_make_type.dynamic Typing_reason.Rnone let mixed = Typing_make_type.mixed Typing_reason.Rnone let supportdyn_of_mixed = Typing_make_type.supportdyn_mixed Typing_reason.Rnone let is_exactly env ty ty' = Tast_env.is_sub_type env ty ty' && Tast_env.is_sub_type env ty' ty let is_like_type env ty = let is_sub_type = Tast_env.is_sub_type env in is_sub_type dynamic ty && not (is_sub_type mixed ty || is_sub_type supportdyn_of_mixed ty) let is_tany = Typing_defs.is_any let locl_ty_of_hint (ty, _) = ty module Counter : sig type t val zero : t val is_zero : t -> bool val plus : t -> t -> t val unit : Tast_env.t -> Typing_defs.locl_ty -> t val unpack : t -> (logged_type * int) list end = struct module Key = struct type t = logged_type [@@deriving ord] end open WrappedMap.Make (Key) type nonrec t = int t let zero = empty let is_zero = is_empty let plus = merge (fun _ c_opt c_opt' -> match (c_opt, c_opt') with | (Some c, Some c') -> Some (c + c') | (None, Some c) | (Some c, None) -> Some c | (None, None) -> None) let inc key = update key @@ function | None -> Some 1 | Some c -> Some (c + 1) let unit env ty = empty |> begin if is_like_type env ty then inc Like else inc NonLike end |> begin if is_exactly env ty mixed then inc Mixed else Fn.id end |> begin if is_exactly env ty supportdyn_of_mixed then inc SupportdynOfMixed else Fn.id end |> begin if is_exactly env ty dynamic then inc Dynamic else Fn.id end |> begin if is_tany ty then inc Tany else Fn.id end let unpack = elements end module Categories : sig module Key : sig type t = category end type t val zero : t val plus : t -> t -> t val singleton : Key.t -> Counter.t -> t val unpack : t -> (category * logged_type * int) list end = struct module Key = struct type t = category [@@deriving ord] end open WrappedMap.Make (Key) type nonrec t = Counter.t t let zero = empty let plus = merge (fun _ c_opt c_opt' -> match (c_opt, c_opt') with | (Some c, Some c') -> Some (Counter.plus c c') | (None, Some c) | (Some c, None) -> Some c | (None, None) -> None) let singleton k c = if Counter.is_zero c then empty else singleton k c let unpack : t -> (category * logged_type * int) list = fun x -> map Counter.unpack x |> elements |> List.map ~f:(fun (cg, cnts) -> List.map cnts ~f:(fun (t, c) -> (cg, t, c))) |> List.concat end let callable_decl_counter env params ret = let parameter = List.fold params ~init:Counter.zero ~f:(fun acc param -> let ty = locl_ty_of_hint param.Aast.param_type_hint in Counter.plus acc (Counter.unit env ty)) |> Categories.singleton Parameter in let return = let ty = locl_ty_of_hint ret in Counter.unit env ty |> Categories.singleton Return in Categories.(plus parameter return) let partition_types = object inherit [_] Tast_visitor.reduce as super method zero = Categories.zero method plus = Categories.plus method! on_expr env ((ty, _, e_) as e) = let open Categories in Counter.unit env ty |> Categories.singleton Expression |> plus begin match e_ with | Aast.Obj_get ((receiver_ty, _, _), _, _, _) -> Counter.unit env receiver_ty |> singleton Obj_get_receiver | Aast.Class_get ((receiver_ty, _, _), _, _) -> Counter.unit env receiver_ty |> singleton Class_get_receiver | Aast.Class_const ((receiver_ty, _, _), _) -> Counter.unit env receiver_ty |> singleton Class_const_receiver | _ -> zero end |> plus (super#on_expr env e) method! on_method_ env m = let declaration = callable_decl_counter env m.Aast.m_params m.Aast.m_ret in let expression = super#on_method_ env m in Categories.plus declaration expression method! on_fun_ env f = let declaration = callable_decl_counter env f.Aast.f_params f.Aast.f_ret in let expression = super#on_fun_ env f in Categories.plus declaration expression method! on_class_ env c = let property = List.fold c.Aast.c_vars ~init:Counter.zero ~f:(fun acc prop -> let ty = locl_ty_of_hint prop.Aast.cv_type in Counter.plus acc (Counter.unit env ty)) |> Categories.singleton Property in let method_ = super#on_class_ env c in Categories.plus property method_ end type count = { entity_pos: entity_pos; (** The position of the entity for which this count holds *) counted_type: logged_type; (** The type that this count is for *) category: category; (** Program construct that produces this type *) value: int; (** The actual count *) } [@@deriving yojson_of] let count ctx program = let reducer = object inherit [count list] Tast_visitor.reduce method zero = [] method plus = ( @ ) method! on_fun_def env f = let categories = partition_types#on_fun_def env f in let data = Categories.unpack categories in List.map data ~f:(fun (category, counted_type, value) -> { entity_pos = (fst f.Aast.fd_name, Function (snd f.Aast.fd_name)); counted_type; category; value; }) method! on_class_ env c = let categories = partition_types#on_class_ env c in let data = Categories.unpack categories in List.map data ~f:(fun (category, counted_type, value) -> { entity_pos = (fst c.Aast.c_name, Class (snd c.Aast.c_name)); counted_type; category; value; }) end in reducer#go ctx program type summary = { num_like_types: int; num_non_like_types: int; num_mixed: int; num_supportdyn_of_mixed: int; num_dynamic: int; num_tany: int; } [@@deriving yojson_of] type t = summary Relative_path.Map.t [@@deriving yojson_of] let empty_summary = { num_like_types = 0; num_non_like_types = 0; num_mixed = 0; num_supportdyn_of_mixed = 0; num_dynamic = 0; num_tany = 0; } let summary_of_count (cnt : count) = let { counted_type; value; entity_pos = _; category = _ } = cnt in match counted_type with | Like -> { empty_summary with num_like_types = value } | NonLike -> { empty_summary with num_non_like_types = value } | Mixed -> { empty_summary with num_mixed = value } | SupportdynOfMixed -> { empty_summary with num_supportdyn_of_mixed = value } | Dynamic -> { empty_summary with num_dynamic = value } | Tany -> { empty_summary with num_tany = value } let plus_summary s t = let { num_like_types; num_non_like_types; num_mixed; num_supportdyn_of_mixed; num_dynamic; num_tany; } = s in { num_like_types = num_like_types + t.num_like_types; num_non_like_types = num_non_like_types + t.num_non_like_types; num_mixed = num_mixed + t.num_mixed; num_supportdyn_of_mixed = num_supportdyn_of_mixed + t.num_supportdyn_of_mixed; num_dynamic = num_dynamic + t.num_dynamic; num_tany = num_tany + t.num_tany; } let summary_of_counts (cnts : count list) = List.fold cnts ~init:Relative_path.Map.empty ~f:(fun m c -> let fn = Pos.filename (fst c.entity_pos) in let c = summary_of_count c in Relative_path.Map.update fn (fun x -> Some (plus_summary (Option.value x ~default:empty_summary) c)) m) let is_enabled tcopt = TypecheckerOptions.log_levels tcopt |> SMap.find_opt "type_counter" |> Option.map ~f:(fun level -> level = 1) |> Option.value ~default:false let map (ctx : Provider_context.t) (_path : Relative_path.t) (tasts : Tast.by_names) : t = Tast.tasts_as_list tasts |> List.map ~f:(fun t -> t.Tast_with_dynamic.under_normal_assumptions) |> count ctx |> summary_of_counts let reduce = Relative_path.Map.union ~combine:(fun _key x y -> Some (plus_summary x y)) let finalize ~progress:_ ~init_id:_ ~recheck_id:_ _counts = ()
OCaml Interface
hhvm/hphp/hack/src/typing/service/type_counter.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 entity = | Class of string | Function of string [@@deriving ord] type entity_pos = Pos.t * entity [@@deriving ord] type logged_type = | Like | NonLike | Mixed | SupportdynOfMixed | Dynamic | Tany [@@deriving ord] type category = | Expression | Obj_get_receiver | Class_get_receiver | Class_const_receiver | Property | Parameter | Return [@@deriving ord] type count = { entity_pos: entity_pos; (** The position of the entity for which this count holds *) counted_type: logged_type; (** The type that this count is for *) category: category; (** Program construct that produces this type *) value: int; (** The actual count *) } [@@deriving yojson_of] (** Summary for one file, only counting like types. **) type summary = { num_like_types: int; num_non_like_types: int; num_mixed: int; num_supportdyn_of_mixed: int; num_dynamic: int; num_tany: int; } [@@deriving yojson_of] type t = summary Relative_path.Map.t [@@deriving yojson_of] val is_enabled : TypecheckerOptions.t -> bool val map : Provider_context.t -> Relative_path.t -> Tast.by_names -> t val reduce : t -> t -> t val finalize : progress:(string -> unit) -> init_id:string -> recheck_id:string option -> t -> unit
OCaml
hhvm/hphp/hack/src/typing/service/typing_service_types.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude type check_file_workitem = { path: Relative_path.t; was_already_deferred: bool; } [@@deriving show] type workitem = | Check of check_file_workitem | Declare of (Relative_path.t * string) [@@deriving show] module TypingProgress : sig type t type progress_outcome = { deferred_workitems: workitem list; continue: bool; } val init : workitem list -> t val of_completed : workitem list -> t val remaining : t -> workitem list val completed : t -> workitem list val deferred : t -> workitem list val progress_through : init:'acc -> t -> (workitem -> 'acc -> progress_outcome * 'acc) -> t * 'acc end = struct (** This type is used for both input and output of typechecker jobs. INPUT: [remaining] is the list of files that this job is expected to process, and [completed], [deferred] are empty. OUTPUT: all the files that were processed by the job are placed in [completed] or [deferred]; if the job had to stop early, then [remaining] are the leftover files that the job failed to process. *) type t = { remaining: workitem list; completed: workitem list; deferred: workitem list; } type progress_outcome = { deferred_workitems: workitem list; continue: bool; } let init remaining = { remaining; completed = []; deferred = [] } let of_completed completed = { remaining = []; completed; deferred = [] } let remaining t = t.remaining let completed t = t.completed let deferred t = t.deferred let advance ({ remaining; completed; deferred } : t) (acc : 'acc) (f : workitem -> 'acc -> progress_outcome * 'acc) : (t * 'acc * bool) option = match remaining with | [] -> None | x :: remaining -> let ({ deferred_workitems; continue }, acc) = f x acc in let progress = { remaining; completed = x :: completed; deferred = deferred_workitems @ deferred; } in Some (progress, acc, continue) let progress_through ~(init : 'acc) (progress : t) (f : workitem -> 'acc -> progress_outcome * 'acc) : t * 'acc = let rec go (progress : t) (acc : 'acc) = match advance progress acc f with | None -> (progress, acc) | Some (progress, acc, continue) -> if continue then go progress acc else (progress, acc) in go progress init end (** This type is used for both input and output of typechecker jobs. It is also used to accumulate the results of all typechecker jobs. JOB-INPUT: all the fields are empty JOB-OUTPUT: process_files will merge what it discovered into the typing_result output by each job. ACCUMULATE: we start with all fields empty, and then merge in the output of each job as it's done. *) type typing_result = { errors: Errors.t; map_reduce_data: Map_reduce.t; dep_edges: Typing_deps.dep_edges; profiling_info: Telemetry.t; (** Instrumentation about how the workers behaved, e.g. how many decls were computed or how much cpu-time it took. This info is merged by adding together the sub-fields, so as to aggregate information from multiple workers. *) } let make_typing_result () = { errors = Errors.empty; map_reduce_data = Map_reduce.empty; dep_edges = Typing_deps.dep_edges_make (); profiling_info = Telemetry.create (); } let accumulate_job_output (produced_by_job : typing_result) (accumulated_so_far : typing_result) : typing_result = { errors = Errors.merge produced_by_job.errors accumulated_so_far.errors; map_reduce_data = Map_reduce.reduce produced_by_job.map_reduce_data accumulated_so_far.map_reduce_data; dep_edges = Typing_deps.merge_dep_edges produced_by_job.dep_edges accumulated_so_far.dep_edges; profiling_info = Telemetry.add produced_by_job.profiling_info accumulated_so_far.profiling_info; } type progress_kind = Progress type job_progress = { kind: progress_kind; progress: TypingProgress.t; } type check_info = { init_id: string; check_reason: string; log_errors: bool; recheck_id: string option; use_max_typechecker_worker_memory_for_decl_deferral: bool; per_file_profiling: HackEventLogger.PerFileProfilingConfig.t; memtrace_dir: string option; } type workitems_to_process = workitem BigList.t type workitems_in_progress = workitem list
OCaml
hhvm/hphp/hack/src/typing/tast_check/abstract_class_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Aast open Hh_prelude module Env = Tast_env module Cls = Decl_provider.Class module SN = Naming_special_names let check_expr env (_, pos, e) = match e with | Class_const ((_, _, CIparent), (_, construct)) when String.equal construct SN.Members.__construct -> let tenv = Env.tast_env_as_typing_env env in (match Typing_env.get_parent_class tenv with | Some parent_class when Ast_defs.is_c_abstract (Cls.kind parent_class) && Option.is_none (fst (Cls.construct parent_class)) -> Typing_error_utils.add_typing_error ~env:(Env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Parent_abstract_call { meth_name = construct; pos; decl_pos = Cls.pos parent_class }) | _ -> ()) | _ -> () let check_method_body m = let named_body = m.m_body in if m.m_abstract && not (List.is_empty named_body.fb_ast) then Errors.add_error Nast_check_error.(to_user_error @@ Abstract_with_body (fst m.m_name)) let check_class _ c = if Ast_defs.is_c_abstract c.c_kind && c.c_final then ( let err m = Errors.add_error Nast_check_error.( to_user_error @@ Nonstatic_method_in_abstract_final_class (fst m.m_name)) in let (c_constructor, _, c_methods) = split_methods c.c_methods in List.iter c_methods ~f:err; Option.iter c_constructor ~f:err; let (_, c_instance_vars) = split_vars c.c_vars in c_instance_vars |> List.filter ~f:(fun var -> Option.is_none var.cv_xhp_attr) |> List.iter ~f:(fun var -> Errors.add_error Nast_check_error.( to_user_error @@ Instance_property_in_abstract_final_class (fst var.cv_id))) ) let handler = object inherit Tast_visitor.handler_base method! at_expr env e = check_expr env e method! at_method_ _ m = check_method_body m method! at_class_ env c = check_class env c end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/abstract_class_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/callconv_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast open Typing_defs module Env = Tast_env module SN = Naming_special_names let check_types env (_, p, te) = let rec check_types_helper = function | Lvar _ -> () | Array_get ((ty1, _, te1), Some _) -> let rec iter ty1 = let (_, ety1) = Env.expand_type env ty1 in match get_node ety1 with | Tany _ -> true | Tvec_or_dict _ | Ttuple _ | Tshape _ | Tdynamic -> true | Tclass ((_, cn), _, _) when String.equal cn SN.Collections.cDict || String.equal cn SN.Collections.cKeyset || String.equal cn SN.Collections.cVec -> true | Tunion tyl -> List.for_all ~f:iter tyl | Tintersection tyl -> List.exists ~f:iter tyl | Tgeneric _ | Tnewtype _ | Tdependent _ -> let (_, tyl) = Env.get_concrete_supertypes ~abstract_enum:true env ety1 in List.exists ~f:iter tyl | _ -> false in if iter ty1 then check_types_helper te1 else let ty_str = lazy (Env.print_error_ty env ty1) in let reasons = Lazy.map ty_str ~f:(fun ty_str -> Reason.to_string ("This is " ^ ty_str) (get_reason ty1)) in Typing_error_utils.add_typing_error ~env:(Env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Inout_argument_bad_type { pos = p; reasons }) (* Other invalid expressions are caught in Nast_check. *) | _ -> () in check_types_helper te let handler = object inherit Tast_visitor.handler_base method! at_expr env = function | (_, _, Call { args; _ }) -> List.iter ~f:(function | (Ast_defs.Pnormal, _) -> () | (Ast_defs.Pinout _, e) -> check_types env e) args | _ -> () end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/callconv_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/class_const_origin_check.ml
(* * Copyright (c) 2021, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast open Typing_defs module Env = Tast_env module StringPair = struct type t = string * string [@@deriving ord, eq] end module SPSet = Caml.Set.Make (StringPair) (* Check that a constant does not depend on itself when initialized. * The cycle can span multiple classes. We're using the decl info * that tells us what are the constants *directly* used to initialize * `class_name::constant_name` to build a transitive set and check for cycles. * * Note that some constant are using `self` instead of the current class * name, so we always carry the class where refs come from to be able * to perform the correct naming resolution. *) let find_cycle env class_name constant_name = let get_origin_and_refs class_name constant_name = let open Option in let cls = Env.get_class env class_name in cls >>= fun cls -> Env.get_const env cls constant_name >>| fun class_const -> (class_const.cc_origin, class_const.cc_refs) in let target = (class_name, constant_name) in (* Todo is a list of pairs: a class name and class constant references * for constants within this class. It is used to resolve `self` correctly. *) let rec spot_target visited todo = match todo with | [] -> false | (current_class, refs) :: todo -> (* Normalize refs *) let refs = List.map ~f:(function | (Typing_defs.Self, name) -> (current_class, name) | (Typing_defs.From class_name, name) -> (* Do deal with inherited constants we need to check the * origin of constants from the decls. *) let origin = let open Option in let cls = Env.get_class env class_name in cls >>= fun cls -> Env.get_const env cls name >>| fun class_const -> class_const.cc_origin in let origin = Option.value ~default:class_name origin in (origin, name)) refs in let (spotted, visited, todo) = List.fold ~init:(false, visited, todo) ~f:(fun (spotted, visited, todo) (c_name, name) -> let spotted = spotted || StringPair.equal target (c_name, name) in if spotted then (spotted, visited, todo) else if SPSet.mem (c_name, name) visited then (spotted, visited, todo) else let visited = SPSet.add (c_name, name) visited in let todo = match get_origin_and_refs c_name name with | None -> todo | Some (origin, refs) -> (origin, refs) :: todo in (spotted, visited, todo)) refs in spotted || spot_target visited todo in let empty = SPSet.empty in let init = get_origin_and_refs class_name constant_name in let init = Option.value ~default:(class_name, []) init in spot_target empty [init] let handler = object inherit Tast_visitor.handler_base method! at_class_ env c = let c_name = snd c.c_name in let c_consts = c.c_consts in let cls = Env.get_class env c_name in match cls with | None -> () | Some cls -> List.iter c_consts ~f:(fun cc -> let cc_name = snd cc.cc_id in let cc = Env.get_const env cls cc_name in match cc with | None -> () | Some cc -> (* This class constant may be inherited from an ancestor class, in which * case we don't want to fire the error in this file. *) Option.iter (Tast_env.fill_in_pos_filename_if_in_current_decl env cc.cc_pos) ~f:(fun cc_pos -> if find_cycle env c_name cc_name then Typing_error_utils.add_typing_error ~env:(Env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Cyclic_class_constant { pos = cc_pos; class_name = c_name; const_name = cc_name; }))) end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/class_const_origin_check.mli
(* * Copyright (c) 2021, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler_base
OCaml
hhvm/hphp/hack/src/typing/tast_check/class_inherited_member_case_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Aast open Base open Typing_defs module Env = Tast_env module Cls = Decl_provider.Class let error_inherited_base env member_type base_name parent_name base_elt parent_elt : unit = Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Inherited_class_member_with_different_case { member_type; name = base_name; name_prev = parent_name; pos = Lazy.force base_elt.ce_pos |> Pos_or_decl.unsafe_to_raw_pos; child_class = base_elt.ce_origin; prev_class = parent_elt.ce_origin; prev_class_pos = Lazy.force parent_elt.ce_pos; }) let check_inheritance_case env (member_type : string) (class_id : Aast.sid) ((name, elt) : string * class_elt) (acc : (string * class_elt) SMap.t) : (string * class_elt) SMap.t = let (p, cls_name) = class_id in let canonical_name = String.lowercase name in (match SMap.find_opt canonical_name acc with | Some (prev_name, prev_elt) when not (String.equal name prev_name) -> (match (elt.ce_origin, prev_elt.ce_origin) with (* If they are from the same class, there's already a parsing error *) | (a, b) when String.equal a b -> () (* new is the current class *) | (base_cls, _) when String.equal cls_name base_cls -> error_inherited_base env member_type name prev_name elt prev_elt (* prev is the current class *) | (_, base_cls) when String.equal cls_name base_cls -> error_inherited_base env member_type prev_name name prev_elt elt (* Otherwise, this class inherited two methods that differ only by case *) | (class1, class2) -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Multiple_inherited_class_member_with_different_case { member_type; name1 = name; name2 = prev_name; class1_name = class1; class2_name = class2; child_class_name = cls_name; pos = p; class1_pos = Lazy.force elt.ce_pos; class2_pos = Lazy.force prev_elt.ce_pos; })) | _ -> ()); SMap.add canonical_name (name, elt) acc let check_inheritance_cases env (member_type : string) (name : Aast.sid) (class_elts : (string * class_elt) list) = (* We keep a map of canonical names for each class element and iterate through the list. If we ever see two members with the same canonical name, we raise an error. *) let (_ : (string * class_elt) SMap.t) = List.fold_right ~f:(check_inheritance_case env member_type name) ~init:SMap.empty class_elts in () let handler = object inherit Tast_visitor.handler_base method! at_class_ env c = (* Check if any methods, including inherited ones, interfere via canonical name *) let (_, cls_name) = c.c_name in let result = Env.get_class env cls_name in match result with | None -> () | Some cls -> let methods = Cls.methods cls in let smethods = Cls.smethods cls in let all_methods = methods @ smethods in (* All methods are treated the same when it comes to inheritance *) (* Member type may be useful for properties, constants, etc later *) check_inheritance_cases (Env.tast_env_as_typing_env env) "method" c.c_name all_methods end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/class_inherited_member_case_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/class_parent_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Aast open Base module Env = Tast_env module Cls = Decl_provider.Class let check_is_class env ~require_class_check (p, h) = match h with | Aast.Happly ((_, name), _) -> begin match Env.get_class env name with | None -> () | Some cls -> let kind = Cls.kind cls in let name = Cls.name cls in if Ast_defs.is_c_class kind then ( if Cls.final cls && not require_class_check then Errors.add_error Nast_check_error.( to_user_error @@ Requires_final_class { pos = p; name }) ) else Errors.add_error Nast_check_error.( to_user_error @@ Requires_non_class { pos = p; name; kind = Ast_defs.string_of_classish_kind kind }) end | Aast.Habstr (name, _) -> Errors.add_error Nast_check_error.( to_user_error @@ Requires_non_class { pos = p; name; kind = "a generic" }) | _ -> Errors.add_error Nast_check_error.( to_user_error @@ Requires_non_class { pos = p; name = "This"; kind = "an invalid type hint" }) let check_is_interface (env, error_verb) (p, h) = match h with | Aast.Happly ((_, name), _) -> begin match Env.get_class env name with | None -> () | Some cls when Ast_defs.is_c_interface (Cls.kind cls) -> () | Some cls -> Errors.add_error Nast_check_error.( to_user_error @@ Non_interface { pos = p; name = Cls.name cls; verb = error_verb }) end | Aast.Habstr _ -> Errors.add_error Nast_check_error.( to_user_error @@ Non_interface { pos = p; name = "generic"; verb = error_verb }) | _ -> Errors.add_error Nast_check_error.( to_user_error @@ Non_interface { pos = p; name = "invalid type hint"; verb = error_verb }) let check_is_trait env (p, h) = match h with | Aast.Happly ((_, name), _) -> let type_info = Env.get_class env name in begin match type_info with | None -> () | Some cls when Ast_defs.is_c_trait (Cls.kind cls) -> () | Some cls -> let name = Cls.name cls in let kind = Cls.kind cls in Errors.add_error Nast_check_error.( to_user_error @@ Uses_non_trait { pos = p; name; kind = Ast_defs.string_of_classish_kind kind }) end | _ -> failwith "assertion failure: trait isn't an Happly" let hint_happly_to_string h = match h with | Aast.Happly ((_, name), _) -> Some name | _ -> None let duplicated_used_traits env c = let traits = Hashtbl.create (module String) in List.iter ~f:(fun (p, h) -> match hint_happly_to_string h with | Some s -> Hashtbl.add_multi traits ~key:s ~data:p | None -> ()) c.c_uses; Hashtbl.iteri ~f:(fun ~key ~data -> if List.length data > 1 then let (pos, class_name) = c.c_name in Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Trait_reuse_inside_class { class_name; pos; trait_name = key; occurrences = List.rev_map data ~f:Pos_or_decl.of_raw_pos; })) traits let handler = object inherit Tast_visitor.handler_base method! at_class_ env c = let (req_extends, req_implements, req_class) = split_reqs c.c_reqs in List.iter c.c_uses ~f:(check_is_trait env); duplicated_used_traits (Env.tast_env_as_typing_env env) c; List.iter req_extends ~f:(check_is_class ~require_class_check:false env); List.iter c.c_implements ~f:(check_is_interface (env, Nast_check_error.Vimplement)); List.iter req_implements ~f:(check_is_interface (env, Nast_check_error.Vreq_implement)); List.iter req_class ~f:(check_is_class ~require_class_check:true env) end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/class_parent_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/const_write_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Aast open Hh_prelude open Typing_defs module Env = Tast_env module SN = Naming_special_names (* Requires id to be a property *) let check_static_const_prop tenv class_ (pos, id) = let scprop = Typing_env.get_static_member false tenv class_ id in Option.iter scprop ~f:(fun ce -> if get_ce_const ce then Typing_error_utils.add_typing_error ~env:tenv Typing_error.(primary @@ Primary.Mutating_const_property pos)) (* Requires id to be a property *) let check_const_prop env tenv class_ (pos, id) cty = let cprop = Typing_env.get_member false tenv class_ id in Option.iter cprop ~f:(fun ce -> if get_ce_const ce then if not (Env.get_inside_constructor env && (* expensive call behind short circuiting && *) Tast_env.is_sub_type env (Env.get_self_ty_exn env) cty) then Typing_error_utils.add_typing_error ~env:tenv Typing_error.(primary @@ Primary.Mutating_const_property pos)) let check_prop env c pid cty_opt = let class_ = Env.get_class env c in (* Check we're in the LHS of an assignment, so we don't get confused by $foo->bar(), which is an Obj_get but not a property. *) if Typing_defs.(equal_val_kind (Env.get_val_kind env) Lval) then Option.iter class_ ~f:(fun class_ -> match cty_opt with | Some cty -> check_const_prop env (Env.tast_env_as_typing_env env) class_ pid cty | None -> check_static_const_prop (Env.tast_env_as_typing_env env) class_ pid) let rec check_expr env ((_, _, e) : Tast.expr) = match e with | Class_get ((cty, _, _), CGstring pid, _) -> let (env, cty) = Env.expand_type env cty in begin match get_node cty with | Tclass ((_, c), _, _) -> check_prop env c pid None | Tdependent (_, bound) -> begin match get_node bound with | Tclass ((_, c), _, _) -> check_prop env c pid None | _ -> () end | Tgeneric (name, targs) -> let upper_bounds = Env.get_upper_bounds env name targs in let check_class bound = match get_node bound with | Tclass ((_, c), _, _) -> check_prop env c pid None | _ -> () in Typing_set.iter check_class upper_bounds | _ -> () end | Obj_get ((cty, _, _), (_, _, Id id), _, _) -> let (env, cty) = Env.expand_type env cty in let rec check_const_cty seen cty = (* we track already seen types to avoid infinite recursion when dealing with Tgeneric arguments *) if Typing_set.mem cty seen then seen else let seen = Typing_set.add cty seen in match get_node cty with | Tunion ty_list | Tintersection ty_list -> List.fold ty_list ~init:seen ~f:check_const_cty | Tclass ((_, c), _, _) -> check_prop env c id (Some cty); seen | Tnewtype (_, _, bound) | Tdependent (_, bound) -> check_const_cty seen bound | Tgeneric (name, targs) -> let upper_bounds = Env.get_upper_bounds env name targs in let check_class cty seen = check_const_cty seen cty in Typing_set.fold check_class upper_bounds seen | _ -> seen in ignore (check_const_cty Typing_set.empty cty) | Call { func = (_, _, Id (_, f)); args; unpacked_arg = None; _ } when String.equal f SN.PseudoFunctions.unset -> let rec check_unset_exp e = match e with | (_, _, Array_get (e, Some _)) -> check_unset_exp e | _ -> check_expr (Env.set_val_kind env Typing_defs.Lval) e in List.iter args ~f:(fun (_, e) -> check_unset_exp e) | _ -> () let handler = object inherit Tast_visitor.handler_base method! at_expr env e = check_expr env e end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/const_write_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/discarded_awaitable_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast open Typing_defs module Env = Tast_env module MakeType = Typing_make_type module SN = Naming_special_names let is_awaitable env ty = let mixed = MakeType.mixed Typing_reason.none in let awaitable_of_mixed = MakeType.awaitable Typing_reason.none mixed in Tast_env.can_subtype env ty awaitable_of_mixed let can_be_null env ty = let null = MakeType.null Typing_reason.none in Tast_env.can_subtype env null ty let rec enforce_not_awaitable env p ty = let (_, ety) = Tast_env.expand_type env ty in match get_node ety with | Tunion tyl | Tintersection tyl -> List.iter tyl ~f:(enforce_not_awaitable env p) | Tclass ((_, awaitable), _, _) when String.equal awaitable SN.Classes.cAwaitable -> Typing_error_utils.add_typing_error ~env:(Env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Discarded_awaitable { pos = p; decl_pos = get_pos ety }) | Toption ty' -> if TypecheckerOptions.disallow_discarded_nullable_awaitables (Env.get_tcopt env) then enforce_not_awaitable env p ty' else () | Tany _ | Tnonnull | Tvec_or_dict _ | Tprim _ | Tvar _ | Tfun _ | Tgeneric _ | Tnewtype _ | Tdependent _ | Tclass _ | Ttuple _ | Tshape _ | Tdynamic | Taccess _ | Tneg _ -> () | Tunapplied_alias _ -> Typing_defs.error_Tunapplied_alias_in_illegal_context () type ctx = { (* Is a supertype of ?Awaitable<t> allowed in a given * context? * * E.g.: If true, ?Awaitable<t> is disallowed, but Awaitable<t> is allowed. *) nullable_awaitable_disallowed: bool; (* Is a non-nullable supertype of Awaitable<t> disallowed in a given * context? * * E.g.: If true, Awaitable<t> is disallowed, but ?Awaitable<t> and any * union containing Awaitable<t> and an nullable type are allowed. *) non_nullable_awaitable_disallowed: bool; } let allow_awaitable = { nullable_awaitable_disallowed = false; non_nullable_awaitable_disallowed = false; } let disallow_awaitable = { nullable_awaitable_disallowed = true; non_nullable_awaitable_disallowed = true; } let disallow_due_to_cast ctx env = if TypecheckerOptions.disallow_discarded_nullable_awaitables (Env.get_tcopt env) then { nullable_awaitable_disallowed = true; non_nullable_awaitable_disallowed = true; } else { ctx with non_nullable_awaitable_disallowed = true } let disallow_due_to_cast_with_explicit_nullcheck = { nullable_awaitable_disallowed = false; non_nullable_awaitable_disallowed = true; } let disallow_due_to_cast_with_explicit_nullcheck_and_return_nonnull ctx = { nullable_awaitable_disallowed = ctx.nullable_awaitable_disallowed && ctx.non_nullable_awaitable_disallowed; non_nullable_awaitable_disallowed = true; } let visitor = object (this) inherit [_] Tast_visitor.iter_with_state as super method! on_expr (env, ctx) ((ty, p, e) as te) = match e with | Unop (Ast_defs.Unot, e) | Binop { bop = Ast_defs.Eqeqeq; lhs = e; rhs = (_, _, Null) } | Binop { bop = Ast_defs.Eqeqeq; lhs = (_, _, Null); rhs = e } | Binop { bop = Ast_defs.Diff2; lhs = e; rhs = (_, _, Null) } | Binop { bop = Ast_defs.Diff2; lhs = (_, _, Null); rhs = e } -> this#on_expr (env, disallow_due_to_cast_with_explicit_nullcheck) e | Binop { bop = Ast_defs.(Eqeq | Eqeqeq | Diff | Diff2 | Barbar | Ampamp); lhs; rhs; } -> this#on_expr (env, disallow_due_to_cast ctx env) lhs; this#on_expr (env, disallow_due_to_cast ctx env) rhs | Binop { bop = Ast_defs.QuestionQuestion; lhs; rhs } -> this#on_expr ( env, disallow_due_to_cast_with_explicit_nullcheck_and_return_nonnull ctx ) lhs; this#on_expr (env, ctx) rhs | Eif (e1, e2, e3) -> this#on_expr (env, disallow_due_to_cast ctx env) e1; Option.iter e2 ~f:(this#on_expr (env, ctx)); this#on_expr (env, ctx) e3 | Cast (hint, e) -> this#on_hint (env, ctx) hint; this#on_expr (env, disallow_awaitable) e | Is (e, (_, Hnonnull)) | Is (e, (_, Hprim Tnull)) -> this#on_expr (env, disallow_due_to_cast_with_explicit_nullcheck) e | Is (e, hint) | As (e, hint, _) -> let hint_ty = Env.hint_to_ty env hint in let (env, hint_ty) = Env.localize_no_subst env ~ignore_errors:true hint_ty in let ctx' = if is_awaitable env hint_ty then allow_awaitable else disallow_due_to_cast ctx env in this#on_expr (env, ctx') e | _ -> if ctx.nullable_awaitable_disallowed || ctx.non_nullable_awaitable_disallowed then if if can_be_null env ty then ctx.nullable_awaitable_disallowed else ctx.non_nullable_awaitable_disallowed then enforce_not_awaitable env p ty; super#on_expr (env, allow_awaitable) te method! on_stmt (env, ctx) stmt = match snd stmt with | Expr ((_, _, Binop { bop = Ast_defs.Eq _; _ }) as e) -> this#on_expr (env, allow_awaitable) e | Expr e -> this#on_expr (env, disallow_awaitable) e | If (e, b1, b2) -> this#on_expr (env, disallow_due_to_cast ctx env) e; this#on_block (env, ctx) b1; this#on_block (env, ctx) b2 | Do (b, e) -> this#on_block (env, ctx) b; this#on_expr (env, disallow_due_to_cast ctx env) e | While (e, b) -> this#on_expr (env, disallow_due_to_cast ctx env) e; this#on_block (env, ctx) b | For (e1, e2, e3, b) -> List.iter e1 ~f:(this#on_expr (env, ctx)); Option.iter e2 ~f:(this#on_expr (env, disallow_due_to_cast ctx env)); List.iter e3 ~f:(this#on_expr (env, ctx)); this#on_block (env, ctx) b | Switch (e, casel, dfl) -> this#on_expr (env, disallow_awaitable) e; List.iter casel ~f:(this#on_case (env, ctx)); Option.iter dfl ~f:(this#on_default_case (env, ctx)) | _ -> super#on_stmt (env, allow_awaitable) stmt method! on_block (env, _) block = super#on_block (env, allow_awaitable) block end let handler = object inherit Tast_visitor.handler_base method! at_fun_def env = visitor#on_fun_def (env, allow_awaitable) method! at_method_ env = visitor#on_method_ (env, allow_awaitable) end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/discarded_awaitable_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
hhvm/hphp/hack/src/typing/tast_check/dune
(library (name tast_check) (wrapped false) (libraries ast tany_logger core_kernel ifc_lib nast shape_analysis shape_analysis_scuba sdt_analysis remove_dead_unsafe_casts tast_env typing_deps typing_pessimisation_deps utils_core) (preprocess (pps ppx_deriving.std)))
OCaml
hhvm/hphp/hack/src/typing/tast_check/enforceable_hint_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) [@@@warning "-33"] open Hh_prelude [@@@warning "+33"] open Aast let handler = object inherit Tast_visitor.handler_base method! at_expr env (_, _, e) = let validate hint op = let tenv = Tast_env.tast_env_as_typing_env env in Typing_enforceable_hint.validate_hint tenv hint (fun pos reasons -> Typing_error_utils.add_typing_error ~env:tenv Typing_error.( primary @@ Primary.Invalid_is_as_expression_hint { op; pos; reasons })) in match e with | Is (_, hint) -> validate hint `is | As (_, hint, _) -> validate hint `as_ | _ -> () end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/enforceable_hint_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/enum_check.ml
(* * Copyright (c) 2021, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast open Typing_defs module Env = Tast_env module Cls = Decl_provider.Class let get_name dty = match get_node dty with | Tapply ((_, name), []) -> Some name | _ -> None (* Check that the base type of an enum or (enum class) is not an alias * to the enum being defined: * * enum Foo : Foo {} * enum Bar0 : Bar1 {} * enum Bar1 : Bar0 {} * * Such code would make HHVM fatal. * * Note that we have a similar check for enum/class constants themselves in * Cyclic_class_constant but it doesn't take into account the empty enums. *) let find_cycle env class_name = (* Note w.r.t. Cyclic_class_constant: * Since `self` is not allowed (parsing error) in this position, we just * keep track of the hints we see. *) let rec spot_target seen current = let open Option in let enum_def = Env.get_enum env current in let enum_info = enum_def >>= Cls.enum_type in let te_base = enum_info >>= fun info -> get_name info.te_base in match te_base with | None -> None | Some base -> if SSet.mem base seen then Some seen else spot_target (SSet.add base seen) base in spot_target SSet.empty class_name let handler = object inherit Tast_visitor.handler_base method! at_class_ env c = let (pos, c_name) = c.c_name in match find_cycle env c_name with | Some stack -> Typing_error_utils.add_typing_error ~env:(Env.tast_env_as_typing_env env) Typing_error.(primary @@ Primary.Cyclic_class_def { pos; stack }) | None -> () end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/enum_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/expression_tree_check.ml
(* * Copyright (c) 2021, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast let handler = object inherit Tast_visitor.handler_base method! at_expr env (_, pos, e) = match e with | ExpressionTree et -> let tcopt = Tast_env.get_tcopt env in (* Unstable features file attribute ignores all restrictions *) if TypecheckerOptions.expression_trees_enabled tcopt then () else (* Otherwise, only allow those visitors in hhconfig *) let allowed_expression_tree_visitors = TypecheckerOptions.allowed_expression_tree_visitors tcopt in let (_pos, hint) = et.et_hint in let err_opt = match hint with | Happly ((_, id), _) when List.exists allowed_expression_tree_visitors ~f:(fun s -> String.equal s id) -> None | _ -> Some Typing_error.( expr_tree @@ Primary.Expr_tree.Experimental_expression_trees pos) in let tenv = Tast_env.tast_env_as_typing_env env in Option.iter err_opt ~f:(Typing_error_utils.add_typing_error ~env:tenv) | _ -> () end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/expression_tree_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/global_access_check.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * This global access checker raises an error when: * - a global variable is written: * - a global variable is directly written (e.g. (Foo::$bar)->prop = 1;) * - a global variable is written via references (e.g. $a = Foo::$bar; $a->prop = 1;) * - a global variable is passed to a function call, in which it may be written. * - or a global variable is read. * * Notice that the return value of a memoized function (if it is mutable) * is treated as a global variable as well. * * By default, this checker is turned off. * To turn on this checker, use the argument --enable-global-access-check. * * A trick to run this checker on a specific list of files is to * use "--config enable_type_check_filter_files=true" togehter with above arguments, * which runs typechecker only on files listed in ~/.hack_type_check_files_filter. *) open Hh_prelude open Aast module MakeType = Typing_make_type module Reason = Typing_reason module Cls = Decl_provider.Class module Hashtbl = Stdlib.Hashtbl module Option = Stdlib.Option module GlobalAccessCheck = Error_codes.GlobalAccessCheck module SN = Naming_special_names (* Recognize common patterns for global access (only writes for now). *) type global_access_pattern = | Singleton (* Write to a global variable whose value is null *) | Caching (* Write to a global collection when the element is null or does not exist *) | CounterIncrement (* Increase a global variable by 1 or -1 *) | WriteEmptyOrNull (* Assign null or empty string to a global variable *) | WriteLiteral (* Assign a literal to a global variable *) | WriteGlobalToGlobal (* Assign a global variable to another one *) | WriteNonSensitive (* Write non-sensitive data to a global variable *) | SuperGlobalWrite (* Global write via super global functions *) | SuperGlobalRead (* Global read via super global functions *) | NoPattern (* No pattern above is recognized *) [@@deriving ord, show { with_path = false }] module GlobalAccessPatternSet = Caml.Set.Make (struct type t = global_access_pattern let compare = compare_global_access_pattern end) (* Raise a global access error if the corresponding write/read mode is enabled. *) let raise_global_access_error pos fun_name data_type global_set patterns error_code = let error_message = match error_code with | GlobalAccessCheck.DefiniteGlobalWrite -> "definitely written." | GlobalAccessCheck.PossibleGlobalWriteViaReference -> "possibly written via reference." | GlobalAccessCheck.PossibleGlobalWriteViaFunctionCall -> "possibly written via function call." | GlobalAccessCheck.DefiniteGlobalRead -> "definitely read." in let global_vars_str = String.concat ~sep:";" (SSet.elements global_set) in let print_pattern p = match p with | NoPattern -> None | _ as p -> Some (show_global_access_pattern p) in let patterns_str = String.concat ~sep:"," (Caml.List.filter_map print_pattern (GlobalAccessPatternSet.elements patterns)) in let message = "[" ^ fun_name ^ "]{" ^ global_vars_str ^ "}(" ^ data_type ^ ")" ^ (if String.length patterns_str > 0 then "<" ^ patterns_str ^ ">" else "") ^ " A global variable is " ^ error_message in Errors.global_access_error error_code pos message (* Various types of data sources for a local variable. *) type data_source = | GlobalReference of string (* A reference to a mutable global var *) | GlobalValue of string (* The value of a immutable global var *) | NullOrEmpty (* null or empty string *) | Literal (* Boolean, integer, floating-point, or string literals *) | NonSensitive (* E.g. timer, site var *) | Unknown (* Other sources that have not been identified yet *) [@@deriving ord, show] module DataSourceSet = Caml.Set.Make (struct type t = data_source let compare = compare_data_source end) (* Given the data sources of written data (i.e. RHS of assignment), return the recognized patterns. Specially, if there is unknown data sources, no pattern is recognized. *) let get_patterns_from_written_data_srcs srcs = let is_unknown s = match s with | Unknown -> true | _ -> false in if not (DataSourceSet.exists is_unknown srcs) then let add_src_to_patterns s acc = let p = match s with | GlobalReference _ | GlobalValue _ -> WriteGlobalToGlobal | NullOrEmpty -> WriteEmptyOrNull | Literal -> WriteLiteral | NonSensitive -> WriteNonSensitive | Unknown -> NoPattern in GlobalAccessPatternSet.add p acc in DataSourceSet.fold add_src_to_patterns srcs GlobalAccessPatternSet.empty else GlobalAccessPatternSet.empty (* The set of safe/non-sensitive functions or classes *) let safe_func_ids = SSet.of_list ["\\microtime"; "\\FlibSL\\PHP\\microtime"] let safe_class_ids = SSet.of_list ["\\Time"] (* The set of functions whose return value's data sources are the union of the data sources of all its parameters. *) let src_from_para_func_ids = SSet.of_list [ "\\FlibSL\\Dict\\merge"; "\\HH\\Lib\\Dict\\merge"; "\\FlibSL\\Keyset\\union"; "\\HH\\Lib\\Keyset\\union"; ] (* Functions whose return value is from only its first parameter. *) let src_from_first_para_func_ids = SSet.of_list ["\\HH\\idx"; "\\FlibSL\\Dict\\filter_keys"; "\\HH\\Lib\\Dict\\filter_keys"] (* Functions that check if its first parameter is not null. *) let check_non_null_func_ids = SSet.of_list ["\\FlibSL\\C\\contains_key"; "\\HH\\Lib\\C\\contains_key"] (* The type to represent the super global classes under www/flib/core/superglobals. *) type super_global_class_detail = { (* global_variable is None if the corresponding super global variable is not fixed, but is given as the parameter of get/set methods, e.g. in GlobalVARIABLES. *) global_variable: string option; global_write_methods: SSet.t; global_read_methods: SSet.t; } (* Map from super global class names to the corresponding details. *) let super_global_class_map : super_global_class_detail SMap.t = SMap.of_list [ ( "\\GlobalCOOKIE", { global_variable = Some "$_COOKIE"; global_write_methods = SSet.of_list [ "redactCookieSuperglobal"; "overrideCookieSuperglobalForEmulation"; "setForCookieMonsterInternalTest"; ]; global_read_methods = SSet.of_list [ "getInitialKeys"; "getCopy_COOKIE_MONSTER_INTERNAL_ONLY"; "getCopyForEmulation"; ]; } ); ( "\\GlobalENV", { global_variable = Some "$_ENV"; global_write_methods = SSet.of_list ["set_ENV_DO_NOT_USE"; "set"]; global_read_methods = SSet.of_list ["getCopy_DO_NOT_USE"; "get"; "getReadonly"; "idx"; "idxReadonly"]; } ); ( "\\GlobalFILES", { global_variable = Some "$_FILES"; global_write_methods = SSet.of_list ["set_FILES_DO_NOT_USE"; "set"]; global_read_methods = SSet.of_list ["getCopy_DO_NOT_USE"; "get"; "getReadonly"; "idx"]; } ); ( "\\GlobalGET", { global_variable = Some "$_GET"; global_write_methods = SSet.of_list ["set_GET_DO_NOT_USE"; "set"]; global_read_methods = SSet.of_list ["getCopy_DO_NOT_USE"; "get"; "getReadonly"; "idx"; "idxReadonly"]; } ); ( "\\GlobalPOST", { global_variable = Some "$_POST"; global_write_methods = SSet.of_list ["set_POST_DO_NOT_USE"; "set"]; global_read_methods = SSet.of_list ["getCopy_DO_NOT_USE"; "get"; "getReadonly"; "idx"; "idxReadonly"]; } ); ( "\\GlobalREQUEST", { global_variable = Some "$_REQUEST"; global_write_methods = SSet.of_list [ "set_REQUEST_DO_NOT_USE"; "set"; "redactCookiesFromRequestSuperglobal"; ]; global_read_methods = SSet.of_list ["getCopy_DO_NOT_USE"; "get"; "getReadonly"; "idx"]; } ); ( "\\GlobalSERVER", { global_variable = Some "$_SERVER"; global_write_methods = SSet.of_list ["set_SERVER_DO_NOT_USE"; "set"]; global_read_methods = SSet.of_list [ "getCopy_DO_NOT_USE"; "getDocumentRoot"; "getPHPRoot"; "getPHPSelf"; "getRequestTime"; "getParentRequestTime"; "getRequestTimeFloat"; "getParentRequestTimeFloat"; "getScriptName"; "getServerAddress"; "getArgv"; "getArgc"; "getHTTPAuthorization"; "getHTTPHost"; "getHTTPReferer_DO_NOT_USE"; "getHTTPUserAgent"; "getRequestMethod"; "getSecFetchDest"; "getSecFetchMode"; "getSecFetchSite"; "getSecFetchUser"; "getXFBLSD"; "getTFBENV"; "getRequestURIString"; "getRequestURI_UNSAFE_TO_LOG"; "getServerName"; "getUserName"; "getLocalCanaryID"; "getInterestingIniKeys"; "idx"; "idxReadonly"; "get"; "getReadonly"; "idxString_UNSAFE"; "idxArgv"; ]; } ); (* GlobalSESSION is not implemented and hence omitted. *) ( "\\GlobalVARIABLES", { (* The global variable is not fixed but given as the methods's parameter. *) global_variable = None; global_write_methods = SSet.of_list ["set"]; global_read_methods = SSet.of_list ["idxReadonly"; "idx"; "get"; "getReadonly"]; } ); ] (* Given an expression, check if it's a call of static method from some super global class. If so, raise the global read/write error, and return true; otherwise, return false. *) let check_super_global_method expr env external_fun_name = match expr with | Call { func = ( func_ty, pos, Class_const ((_, _, CI (_, class_name)), (_, method_name)) ); args; _; } -> (* Check if the class is a super global class *) (match SMap.find_opt class_name super_global_class_map with | Some class_detail -> (* Check if the method is write or read or not recognized. *) let error_code_pattern_opt = if SSet.mem method_name class_detail.global_write_methods then Some (GlobalAccessCheck.DefiniteGlobalWrite, SuperGlobalWrite) else if SSet.mem method_name class_detail.global_read_methods then Some (GlobalAccessCheck.DefiniteGlobalRead, SuperGlobalRead) else None in if Option.is_some error_code_pattern_opt then ( let func_ty_str = Tast_env.print_ty env func_ty in let (error_code, pattern) = Option.get error_code_pattern_opt in let default_global_var_name = "$_" in let global_var_name = match class_detail.global_variable with | Some var_name -> var_name | None -> (* If the super global class does not have fixed global var name, then the 1st parameter of those get/set methods is assumed to be the global var; and if it's a string literal, we simply use it, otherwise we don't know and use default name. *) (match args with | (_, (_, _, para_expr)) :: _ -> (match para_expr with | String s -> "$" ^ s | _ -> default_global_var_name) | [] -> default_global_var_name) in raise_global_access_error pos external_fun_name ("superglobal " ^ func_ty_str) (SSet.singleton global_var_name) (GlobalAccessPatternSet.singleton pattern) error_code; true ) else false | _ -> false) | _ -> false (* The context maintains: (1) A hash table from local variables to the corresponding data sources. For any local variable, if its data sources contain GlobalReference(s), then it is potentially a reference to global variable. Notice that a local variable may refers to multiple global variables, for example: "if (condition) { $a = Foo::$bar; } else { $a = memoized_func(); }" after the above code, $a has a reference to either Foo::$bar or memoized_func, thus var_data_src_tbl is like {"a" => {GlobalReference of "Foo::$bar", GlobalReference of "\memoized_func"}}. (2) A set of global variables whose values are null, which can be used to identify singletons. For example, consider the following program: "if (Foo::$bar is null) { Foo::$bar = new Bar(); }" inside the true branch, null_global_var_set is {"Foo::$bar"}, and the assignment to Foo::$bar shall be identified as a singleton. *) type ctx = { var_data_src_tbl: (string, DataSourceSet.t) Hashtbl.t ref; null_global_var_set: SSet.t ref; } let current_ctx = { var_data_src_tbl = ref (Hashtbl.create 0); null_global_var_set = ref SSet.empty; } (* Add the key (a variable name) and the value (a set of data srcs) to the table. *) let add_var_data_srcs_to_tbl tbl var srcs = let pre_data_src_set = if Hashtbl.mem tbl var then Hashtbl.find tbl var else DataSourceSet.empty in Hashtbl.replace tbl var (DataSourceSet.union pre_data_src_set srcs) let replace_var_data_srcs_in_tbl tbl var srcs = Hashtbl.replace tbl var srcs (* Given two hash tables of type (string, DataSourceSet.t) Hashtbl.t, merge the second table into the first one. *) let merge_var_data_srcs_tbls tbl1 tbl2 = Hashtbl.iter (add_var_data_srcs_to_tbl tbl1) tbl2 (* For a hash table whose value is DataSourceSet, get its total cardinal. *) let get_tbl_total_cardinal tbl = Hashtbl.fold (fun _ v cur_cardinal -> cur_cardinal + DataSourceSet.cardinal v) tbl 0 let rec grab_class_elts_from_ty ~static ?(seen = SSet.empty) env ty prop_id = let open Typing_defs in (* Given a list of types, find recurse on the first type that has the property and return the result *) let find_first_in_list ~seen tyl = List.find_map ~f:(fun ty -> match grab_class_elts_from_ty ~static ~seen env ty prop_id with | [] -> None | tyl -> Some tyl) tyl in match get_node ty with | Tclass (id, _exact, _args) -> let provider_ctx = Tast_env.get_ctx env in let class_decl = Decl_provider.get_class provider_ctx (snd id) in (match class_decl with | Some class_decl -> let prop = if static then Cls.get_sprop class_decl (snd prop_id) else Cls.get_prop class_decl (snd prop_id) in Option.to_list prop | None -> []) (* Accessing a property off of an intersection type should involve exactly one kind of readonlyness, since for the intersection type to exist, the property must be related by some subtyping relationship anyways, and property readonlyness is invariant. Thus we just grab the first one from the list where the prop exists. *) | Tintersection [] -> [] | Tintersection tyl -> find_first_in_list ~seen tyl |> Option.value ~default:[] (* A union type is more interesting, where we must return all possible cases and be conservative in our use case. *) | Tunion tyl -> List.concat_map ~f:(fun ty -> grab_class_elts_from_ty ~static ~seen env ty prop_id) tyl (* Generic types can be treated similarly to an intersection type where we find the first prop that works from the upper bounds *) | Tgeneric (name, tyargs) -> (* Avoid circular generics with a set *) if SSet.mem name seen then [] else let new_seen = SSet.add name seen in let upper_bounds = Tast_env.get_upper_bounds env name tyargs in find_first_in_list ~seen:new_seen (Typing_set.elements upper_bounds) |> Option.value ~default:[] | Tdependent (_, ty) -> (* Dependent types have an upper bound that's a class or generic *) grab_class_elts_from_ty ~static ~seen env ty prop_id | Toption ty -> (* If it's nullable, take the *) grab_class_elts_from_ty ~static ~seen env ty prop_id | _ -> [] (* Return a list of possible static prop elts given a class_get expression *) let get_static_prop_elts env class_id get = let (ty, _, _) = class_id in match get with | CGstring prop_id -> grab_class_elts_from_ty ~static:true env ty prop_id (* An expression is dynamic, so there's no way to tell the type generally *) | CGexpr _ -> [] (* Check if an expression is directly from a static variable or not, e.g. it returns true for Foo::$bar or (Foo::$bar)->prop. *) let rec is_expr_static env (_, _, te) = match te with | Class_get (class_id, expr, Is_prop) -> (* Ignore static variables annotated with <<__SafeForGlobalAccessCheck>> *) let class_elts = get_static_prop_elts env class_id expr in not (List.exists class_elts ~f:Typing_defs.get_ce_safe_global_variable) | Obj_get (e, _, _, Is_prop) -> is_expr_static env e | Array_get (e, _) -> is_expr_static env e | _ -> false (* Print out global variables, e.g. Foo::$bar => "Foo::$bar", self::$bar => "Foo::$bar", static::$bar => "this::$bar", memoized_func => "\memoized_func", $baz->memoized_method => "Baz->memoized_method", Baz::memoized_method => "Baz::memoized_method", $this->memoized_method => "this->memoized_method". Notice that this does not handle arbitrary expressions. *) let rec print_global_expr env expr = match expr with | Call { func = (_, _, caller_expr); _ } -> (* For function/method calls, we print the caller expression, which could be Id (e.g. memoized_func()) or Obj_get (e.g. $baz->memoized_method()). *) print_global_expr env caller_expr | Class_get ((c_ty, _, _), expr, _) -> (* For static properties, we concatenate the class type (instead of class_id_, which could be self, parent, static) and the property name. *) let class_ty_str = Tast_env.print_ty env c_ty in (match expr with | CGstring (_, expr_str) -> class_ty_str ^ "::" ^ expr_str | CGexpr _ -> class_ty_str ^ "::Unknown") | Class_const ((c_ty, _, _), (_, const_str)) -> (* For static method calls, we concatenate the class type and the method name. *) Tast_env.print_ty env c_ty ^ "::" ^ const_str | Id (_, name) -> name | Obj_get (obj, m, _, _) -> (* For Obj_get (e.g. $baz->memoized_method()), we concatenate the class type and the method id. *) let class_ty_str = Tast_env.print_ty env (Tast.get_type obj) in let (_, _, m_id) = m in (* For the case $obj?->method(), the question mark is removed from the class type, since we are not interested in the case where $obj is null. *) let remove_question_mark_prefix str = if String.is_prefix ~prefix:"?" str then String.sub str ~pos:1 ~len:(String.length str - 1) else str in remove_question_mark_prefix class_ty_str ^ "->" ^ print_global_expr env m_id | _ -> "Unknown" (* Given a function call of type Aast.expr_, if it's memoized, return its function name, otherwise return None. *) let check_func_is_memoized func_expr env = let open Typing_defs in let rec find_fty ty = match get_node ty with | Tnewtype (name, _, ty) when String.equal name SN.Classes.cSupportDyn -> find_fty ty | Tfun fty -> Some fty | _ -> None in let (func_ty, _, te) = func_expr in match find_fty func_ty with | Some fty when get_ft_is_memoized fty -> Some (print_global_expr env te) | _ -> None (* Check if type is a collection. *) let is_value_collection_ty env ty = let mixed = MakeType.mixed Reason.none in let env = Tast_env.tast_env_as_typing_env env in let hackarray = MakeType.any_array Reason.none mixed mixed in (* Subtype against an empty open shape (shape(...)) *) let shape = MakeType.open_shape Reason.none Typing_defs.TShapeMap.empty in Typing_utils.is_sub_type env ty hackarray || Typing_utils.is_sub_type env ty shape (* Check if the variable type does NOT has a reference to any object: if so, then it is OK to write to this variable. Copied from is_safe_mut_ty in readonly_check.ml. To do: check if any change is needed for the global write checker. *) let rec has_no_object_ref_ty env (seen : SSet.t) ty = let open Typing_defs_core in let (env, ty) = Tast_env.expand_type env ty in let tenv = Tast_env.tast_env_as_typing_env env in let ty = Typing_utils.strip_dynamic tenv ty in match get_node ty with (* Allow all primitive types *) | Tprim _ -> true (* Open shapes can technically have objects in them, but as long as the current fields don't have objects in them we will allow you to call the function. Note that the function fails at runtime if any shape fields are objects. *) | Tshape { s_fields = fields; _ } -> TShapeMap.for_all (fun _k v -> has_no_object_ref_ty env seen v.sft_ty) fields (* If it's a Tclass it's an array type by is_value_collection *) | Tintersection tyl -> List.exists tyl ~f:(fun l -> has_no_object_ref_ty env seen l) (* Only error if there isn't a type that it could be that's primitive *) | Tunion tyl -> List.exists tyl ~f:(fun l -> has_no_object_ref_ty env seen l) | Ttuple tyl -> List.for_all tyl ~f:(fun l -> has_no_object_ref_ty env seen l) | Tdependent (_, upper) -> (* check upper bounds *) has_no_object_ref_ty env seen upper | Tclass ((_, id), _, tyl) when is_value_collection_ty env ty || String.equal id "\\HH\\Awaitable" -> List.for_all tyl ~f:(fun l -> has_no_object_ref_ty env seen l) | Tgeneric (name, tyargs) -> (* Avoid circular generics with a set *) if SSet.mem name seen then false else let new_seen = SSet.add name seen in let upper_bounds = Tast_env.get_upper_bounds env name tyargs in Typing_set.exists (fun l -> has_no_object_ref_ty env new_seen l) upper_bounds | _ -> (* Otherwise, check if there's any primitive type it could be *) let env = Tast_env.tast_env_as_typing_env env in let primitive_types = [ MakeType.bool Reason.none; MakeType.int Reason.none; MakeType.arraykey Reason.none; MakeType.string Reason.none; MakeType.float Reason.none; MakeType.num Reason.none; (* Keysets only contain arraykeys so if they're readonly its safe to remove *) MakeType.keyset Reason.none (MakeType.arraykey Reason.none); (* We don't put null here because we want to exclude ?Foo. as_mut(null) itself is allowed by the Tprim above*) ] in (* Make sure that a primitive *could* be this type by intersecting all primitives and subtyping. *) let union = MakeType.union Reason.none primitive_types in not (Typing_subtype.is_type_disjoint env ty union) (* Get all possible data sources for the given expression. *) let rec get_data_srcs_from_expr env ctx (tp, _, te) = let is_immutable_ty = has_no_object_ref_ty env SSet.empty tp in let convert_ref_to_val srcs = DataSourceSet.map (fun src -> match src with | GlobalReference s -> GlobalValue s | _ as s -> s) srcs in (* For a collection (Varray, ValCollection and List) that uses a list of expressions (e.g. vec[$a, $b] uses the list [$a; $b]), the function get_data_srcs_of_expr_list gets the data source for each expression in the list and do the union; specially, if the list is empty (e.g. vec[]), the data source is NullOrEmpty. *) let get_data_srcs_of_expr_list list = if List.length list = 0 then DataSourceSet.singleton NullOrEmpty else List.fold list ~init:DataSourceSet.empty ~f:(fun cur_src_set e -> DataSourceSet.union cur_src_set (get_data_srcs_from_expr env ctx e)) in (* For a collection (Darray, Shape and KeyValCollection) that uses a list of expression pairs (e.g. dict[0 => $a, 1 => $b] uses the list [(0, $a); (1, $b)]), the function get_data_srcs_of_pair_expr_list gets the data source for the 2nd expression in each pair and do the union; specially, return NullOrEmpty if the list is empty (e.g. dict[]). *) let get_data_srcs_of_pair_expr_list list = if List.length list = 0 then DataSourceSet.singleton NullOrEmpty else List.fold list ~init:DataSourceSet.empty ~f:(fun cur_src_set (_, e) -> DataSourceSet.union cur_src_set (get_data_srcs_from_expr env ctx e)) in match te with | Class_get (class_id, expr, Is_prop) -> (* Static variables annotated with <<__SafeForGlobalAccessCheck>> are treated as non-sensitive. *) let class_elts = get_static_prop_elts env class_id expr in if List.exists class_elts ~f:Typing_defs.get_ce_safe_global_variable then DataSourceSet.singleton NonSensitive else let expr_str = print_global_expr env te in if is_immutable_ty then DataSourceSet.singleton (GlobalValue expr_str) else DataSourceSet.singleton (GlobalReference expr_str) | Lvar (_, id) -> if Hashtbl.mem !(ctx.var_data_src_tbl) (Local_id.to_string id) then Hashtbl.find !(ctx.var_data_src_tbl) (Local_id.to_string id) else DataSourceSet.singleton Unknown | Call { func = (_, _, func_expr) as caller; args; _ } -> (match check_func_is_memoized caller env with | Some func_name -> (* If the called function is memoized, then its return is global. *) if is_immutable_ty then DataSourceSet.singleton (GlobalValue func_name) else DataSourceSet.singleton (GlobalReference func_name) | None -> (* Otherwise, the function call is treated as a black boxes, except for some special function (i.e. idx), the data source of its return is assumed to be the same as its first parameter. *) (match func_expr with | Id (_, func_id) when SSet.mem func_id src_from_first_para_func_ids -> (match args with | (_, para_expr) :: _ -> get_data_srcs_from_expr env ctx para_expr | [] -> DataSourceSet.singleton Unknown) | Id (_, func_id) -> if SSet.mem func_id safe_func_ids then DataSourceSet.singleton NonSensitive else if SSet.mem func_id src_from_para_func_ids then List.fold args ~init:DataSourceSet.empty ~f:(fun cur_src_set (_, para_expr) -> DataSourceSet.union cur_src_set (get_data_srcs_from_expr env ctx para_expr)) else DataSourceSet.singleton Unknown | Class_const ((_, _, CI (_, class_name)), _) -> (* A static method call is safe if the class name is in "safe_class_ids", or it starts with "SV_" (i.e. it's a site var). *) let is_class_safe = SSet.mem class_name safe_class_ids || Caml.String.starts_with ~prefix:"\\SV_" class_name in if is_class_safe then DataSourceSet.singleton NonSensitive else DataSourceSet.singleton Unknown | _ -> DataSourceSet.singleton Unknown)) | Darray (_, tpl) -> get_data_srcs_of_pair_expr_list tpl | Varray (_, el) -> get_data_srcs_of_expr_list el | Shape tpl -> get_data_srcs_of_pair_expr_list tpl | ValCollection (_, _, el) -> get_data_srcs_of_expr_list el | KeyValCollection (_, _, fl) -> get_data_srcs_of_pair_expr_list fl | Null -> DataSourceSet.singleton NullOrEmpty | Clone e -> get_data_srcs_from_expr env ctx e | Array_get (e, _) -> get_data_srcs_from_expr env ctx e | Obj_get (obj_expr, _, _, Is_prop) -> let obj_data_srcs = get_data_srcs_from_expr env ctx obj_expr in if is_immutable_ty then convert_ref_to_val obj_data_srcs else obj_data_srcs | Class_const _ -> DataSourceSet.singleton NonSensitive | Await e -> get_data_srcs_from_expr env ctx e | ReadonlyExpr e -> get_data_srcs_from_expr env ctx e | Tuple el | List el -> get_data_srcs_of_expr_list el | Cast (_, e) -> get_data_srcs_from_expr env ctx e | Unop (_, e) -> get_data_srcs_from_expr env ctx e | Binop { lhs; rhs; _ } -> DataSourceSet.union (get_data_srcs_from_expr env ctx lhs) (get_data_srcs_from_expr env ctx rhs) | Pipe (_, _, e) -> get_data_srcs_from_expr env ctx e | Eif (_, e1, e2) -> DataSourceSet.union (match e1 with | Some e -> get_data_srcs_from_expr env ctx e | None -> DataSourceSet.empty) (get_data_srcs_from_expr env ctx e2) | As (e, _, _) -> get_data_srcs_from_expr env ctx e | Upcast (e, _) -> get_data_srcs_from_expr env ctx e | Pair (_, e1, e2) -> DataSourceSet.union (get_data_srcs_from_expr env ctx e1) (get_data_srcs_from_expr env ctx e2) | True | False | Int _ | Float _ | String _ | String2 _ | PrefixedString _ | ExpressionTree _ -> DataSourceSet.singleton Literal | This | Omitted | Id _ | Dollardollar _ | Obj_get (_, _, _, Is_method) | Class_get (_, _, Is_method) | FunctionPointer _ | Yield _ | Is _ | New _ | Efun _ | Lfun _ | Xml _ | Import _ | Collection _ | Lplaceholder _ | Method_caller _ | ET_Splice _ | EnumClassLabel _ | Hole _ | Invalid _ | Package _ -> DataSourceSet.singleton Unknown (* Get the global variable names from the given expression's data sources. By default, include_immutable is true, and we return both GlobalReference and GlobalValue; otherwise, we return only GlobalReference. If no such global variable exists, None is returned. *) let get_global_vars_from_expr ?(include_immutable = true) env ctx expr = let is_src_global src = match src with | GlobalReference _ -> true | GlobalValue _ -> include_immutable | _ -> false in let print_src src = match src with | GlobalReference str | GlobalValue str -> str | _ as s -> show_data_source s in let data_srcs = get_data_srcs_from_expr env ctx expr in let global_srcs = DataSourceSet.filter is_src_global data_srcs in if DataSourceSet.is_empty global_srcs then None else Some (DataSourceSet.fold (fun src s -> SSet.add (print_src src) s) global_srcs SSet.empty) (* Given an expression that appears on LHS of an assignment, this method gets the set of variables whose value may be assigned. *) let rec get_vars_in_expr vars (_, _, te) = match te with | Lvar (_, id) -> vars := SSet.add (Local_id.to_string id) !vars | Obj_get (e, _, _, Is_prop) -> get_vars_in_expr vars e | Array_get (e, _) -> get_vars_in_expr vars e | ReadonlyExpr e -> get_vars_in_expr vars e | List el -> List.iter el ~f:(get_vars_in_expr vars) | _ -> () (* Suppose te is on LHS of an assignment, check if we can write to global variables by accessing either directly static variables or an object's properties. *) let rec has_global_write_access (_, _, te) = match te with | Class_get (_, _, Is_prop) | Obj_get (_, _, _, Is_prop) -> true | List el -> List.exists el ~f:has_global_write_access | Lvar _ | ReadonlyExpr _ | Array_get _ | _ -> false let visitor = object (self) inherit [_] Tast_visitor.iter_with_state as super method! on_method_ (env, (ctx, fun_name)) m = Hashtbl.clear !(ctx.var_data_src_tbl); ctx.null_global_var_set := SSet.empty; super#on_method_ (env, (ctx, fun_name)) m method! on_fun_def (env, (ctx, fun_name)) f = Hashtbl.clear !(ctx.var_data_src_tbl); ctx.null_global_var_set := SSet.empty; super#on_fun_def (env, (ctx, fun_name)) f method! on_fun_ (env, (ctx, fun_name)) f = let var_data_src_tbl_cpy = Hashtbl.copy !(ctx.var_data_src_tbl) in let null_global_var_set_cpy = !(ctx.null_global_var_set) in super#on_fun_ (env, (ctx, fun_name)) f; ctx.var_data_src_tbl := var_data_src_tbl_cpy; ctx.null_global_var_set := null_global_var_set_cpy method! on_stmt_ (env, (ctx, fun_name)) s = match s with | If (((_, _, cond) as c), b1, b2) -> (* Make a copy of null_global_var_set, and reset afterwards. *) let null_global_var_set_cpy = !(ctx.null_global_var_set) in let ctx_else_branch = { var_data_src_tbl = ref (Hashtbl.copy !(ctx.var_data_src_tbl)); null_global_var_set = ref !(ctx.null_global_var_set); } in (* From the condition, we get the expression whose value is null in one brach (true represents the if branch, while false represents the else branch). *) let nullable_expr_in_cond_opt = match cond with (* For the condition of format "expr is null", "expr === null" or "expr == null", return expr and true (i.e. if branch). *) | Is (cond_expr, (_, Hprim Tnull)) | Binop { bop = Ast_defs.(Eqeqeq | Eqeq); lhs = cond_expr; rhs = (_, _, Null); } -> Some (cond_expr, true) (* For the condition of format "!C\contains_key(expr, $key)" where expr shall be a dictionary, return expr and true (i.e. if branch). *) | Unop ( Ast_defs.Unot, (_, _, Call { func = (_, _, Id (_, func_id)); args; _ }) ) when SSet.mem func_id check_non_null_func_ids -> (match args with | [] -> None | (_, para_expr) :: _ -> Some (para_expr, true)) (* For the condition of format "expr is nonnull", "expr !== null" or "expr != null", return expr and false (i.e. else branch). *) | Is (cond_expr, (_, Hnonnull)) | Binop { bop = Ast_defs.(Diff | Diff2); lhs = cond_expr; rhs = (_, _, Null); } -> Some (cond_expr, false) (* For the condition of format "C\contains_key(expr, $key)" where expr shall be a dictionary, return expr and false (i.e. else branch). *) | Call { func = (_, _, Id (_, func_id)); args; _ } when SSet.mem func_id check_non_null_func_ids -> (match args with | [] -> None | (_, para_expr) :: _ -> Some (para_expr, false)) | _ -> None in let () = match nullable_expr_in_cond_opt with | None -> () | Some (nullable_expr, if_branch) -> let nullable_global_vars_opt = get_global_vars_from_expr env ctx nullable_expr in (* Add nullable global variables to null_global_var_set of the right branch. *) (match (nullable_global_vars_opt, if_branch) with | (None, _) -> () | (Some vars, true) -> ctx.null_global_var_set := SSet.union !(ctx.null_global_var_set) vars | (Some vars, false) -> ctx_else_branch.null_global_var_set := SSet.union !(ctx_else_branch.null_global_var_set) vars) in (* Check the condition expression and report global reads/writes if any. For example, a global read is reported if a global varialbe is directly used; a global write is reported if a global variable is passed to a function call (which is very likely to happen) or it is directly mutated inside the condition (which is uncommon but possible). *) super#on_expr (env, (ctx, fun_name)) c; (* Check two branches separately, then merge the table of global variables and reset the set of nullable variables. *) super#on_block (env, (ctx, fun_name)) b1; super#on_block (env, (ctx_else_branch, fun_name)) b2; merge_var_data_srcs_tbls !(ctx.var_data_src_tbl) !(ctx_else_branch.var_data_src_tbl); ctx.null_global_var_set := null_global_var_set_cpy | Do (b, _) | While (_, b) | For (_, _, _, b) | Foreach (_, _, b) -> super#on_stmt_ (env, (ctx, fun_name)) s; (* Iterate the block and update the set of global varialbes until no new global variable is found *) let ctx_cpy = { var_data_src_tbl = ref (Hashtbl.copy !(ctx.var_data_src_tbl)); null_global_var_set = ref !(ctx.null_global_var_set); } in let ctx_len = ref (get_tbl_total_cardinal !(ctx.var_data_src_tbl)) in let has_context_change = ref true in (* Continue the loop until no more data sources are found. *) while !has_context_change do super#on_block (env, (ctx_cpy, fun_name)) b; merge_var_data_srcs_tbls !(ctx.var_data_src_tbl) !(ctx_cpy.var_data_src_tbl); let new_ctx_tbl_cardinal = get_tbl_total_cardinal !(ctx.var_data_src_tbl) in if new_ctx_tbl_cardinal <> !ctx_len then ctx_len := new_ctx_tbl_cardinal else has_context_change := false done | Return r -> (match r with | Some ((ty, p, _) as e) -> (match get_global_vars_from_expr ~include_immutable:false env ctx e with | Some global_set -> raise_global_access_error p fun_name (Tast_env.print_ty env ty) global_set (GlobalAccessPatternSet.singleton NoPattern) GlobalAccessCheck.PossibleGlobalWriteViaFunctionCall | None -> ()) | None -> ()); super#on_stmt_ (env, (ctx, fun_name)) s | _ -> super#on_stmt_ (env, (ctx, fun_name)) s method! on_expr (env, (ctx, fun_name)) ((ty, p, e) as te) = match e with (* For the case where the expression is directly a static variable or a memoized function, and we report a global read. Notice that if the expression is on the LHS of an assignment, we will not run on_expr on it, hence no global reads would be reported; similarly, for the unary operation like "Foo::$prop++", we don't report a global read. *) | Class_get (class_id, expr, Is_prop) -> (* Ignore static variables annotated with <<__SafeForGlobalAccessCheck>> *) let class_elts = get_static_prop_elts env class_id expr in let is_annotated_safe = List.exists class_elts ~f:Typing_defs.get_ce_safe_global_variable in if not is_annotated_safe then let expr_str = print_global_expr env e in let ty_str = Tast_env.print_ty env ty in raise_global_access_error p fun_name ty_str (SSet.singleton expr_str) (GlobalAccessPatternSet.singleton NoPattern) GlobalAccessCheck.DefiniteGlobalRead | Call { func = (func_ty, _, _) as func_expr; args; _ } -> (* First check if the called functions is from super globals. *) let is_super_global_call = check_super_global_method e env fun_name in (if not is_super_global_call then (* If not super global, then check if the function is memoized. *) let func_ty_str = Tast_env.print_ty env func_ty in match check_func_is_memoized func_expr env with | Some memoized_func_name -> raise_global_access_error p fun_name func_ty_str (SSet.singleton memoized_func_name) (GlobalAccessPatternSet.singleton NoPattern) GlobalAccessCheck.DefiniteGlobalRead | None -> ()); (* Lastly, check if a global variable is used as the parameter. *) List.iter args ~f:(fun (pk, ((ty, pos, _) as expr)) -> let e_global_opt = match pk with | Ast_defs.Pinout _ -> get_global_vars_from_expr env ctx expr | Ast_defs.Pnormal -> get_global_vars_from_expr ~include_immutable:false env ctx expr in if Option.is_some e_global_opt then raise_global_access_error pos fun_name (Tast_env.print_ty env ty) (Option.get e_global_opt) (GlobalAccessPatternSet.singleton NoPattern) GlobalAccessCheck.PossibleGlobalWriteViaFunctionCall); super#on_expr (env, (ctx, fun_name)) te | Binop { bop = Ast_defs.Eq bop_opt; lhs; rhs } -> let () = self#on_expr (env, (ctx, fun_name)) rhs in let re_ty = Tast_env.print_ty env (Tast.get_type rhs) in let le_global_opt = get_global_vars_from_expr env ctx lhs in (* When write to a global variable whose value is null or does not exist: if the written variable is in a collection (e.g. $global[$key] = $val), then it's asumed to be caching; otherwise, it's a singleton. *) let singleton_or_caching = match lhs with | (_, _, Array_get _) -> Caching | _ -> Singleton in let le_pattern = match (le_global_opt, bop_opt) with | (None, _) -> NoPattern | (Some _, Some Ast_defs.QuestionQuestion) -> singleton_or_caching | (Some le_global, _) -> if SSet.exists (fun v -> SSet.mem v !(ctx.null_global_var_set)) le_global then singleton_or_caching else NoPattern in let re_data_srcs = get_data_srcs_from_expr env ctx rhs in let re_patterns = get_patterns_from_written_data_srcs re_data_srcs in (* Distinguish directly writing to static variables from writing to a variable that has references to static variables. *) (if is_expr_static env lhs && Option.is_some le_global_opt then raise_global_access_error p fun_name re_ty (Option.get le_global_opt) (GlobalAccessPatternSet.add le_pattern re_patterns) GlobalAccessCheck.DefiniteGlobalWrite else let vars_in_le = ref SSet.empty in let () = get_vars_in_expr vars_in_le lhs in if has_global_write_access lhs then ( if Option.is_some le_global_opt then raise_global_access_error p fun_name re_ty (Option.get le_global_opt) (GlobalAccessPatternSet.add le_pattern re_patterns) GlobalAccessCheck.PossibleGlobalWriteViaReference; SSet.iter (fun v -> add_var_data_srcs_to_tbl !(ctx.var_data_src_tbl) v re_data_srcs) !vars_in_le ) else SSet.iter (fun v -> replace_var_data_srcs_in_tbl !(ctx.var_data_src_tbl) v re_data_srcs) !vars_in_le); super#on_expr (env, (ctx, fun_name)) rhs (* add_var_refs_to_tbl !(ctx.global_var_refs_tbl) !vars_in_le *) | Unop (op, e) -> let e_global_opt = get_global_vars_from_expr env ctx e in if Option.is_some e_global_opt then let e_global = Option.get e_global_opt in let e_ty = Tast_env.print_ty env (Tast.get_type e) in (match op with | Ast_defs.Uincr | Ast_defs.Udecr | Ast_defs.Upincr | Ast_defs.Updecr -> (* Distinguish directly writing to static variables from writing to a variable that has references to static variables. *) if is_expr_static env e then raise_global_access_error p fun_name e_ty e_global (GlobalAccessPatternSet.singleton CounterIncrement) GlobalAccessCheck.DefiniteGlobalWrite else if has_global_write_access e then raise_global_access_error p fun_name e_ty e_global (GlobalAccessPatternSet.singleton CounterIncrement) GlobalAccessCheck.PossibleGlobalWriteViaReference | _ -> super#on_expr (env, (ctx, fun_name)) e) | New (_, _, el, _, _) -> List.iter el ~f:(fun ((ty, pos, _) as expr) -> let e_global_opt = get_global_vars_from_expr ~include_immutable:false env ctx expr in if Option.is_some e_global_opt then raise_global_access_error pos fun_name (Tast_env.print_ty env ty) (Option.get e_global_opt) (GlobalAccessPatternSet.singleton NoPattern) GlobalAccessCheck.PossibleGlobalWriteViaFunctionCall); super#on_expr (env, (ctx, fun_name)) te | _ -> super#on_expr (env, (ctx, fun_name)) te end let handler = object inherit Tast_visitor.handler_base method! at_method_ env m = let class_name = Tast_env.get_self_id env in let (_, method_name) = m.m_name in let full_name = match class_name with | Some s -> s ^ "::" ^ method_name | _ -> method_name in (* Class name starts with '\' or ';' *) let full_name = String.sub full_name ~pos:1 ~len:(String.length full_name - 1) in visitor#on_method_ (env, (current_ctx, full_name)) m method! at_fun_def env f = let (_, function_name) = f.fd_name in (* Function name starts with '\'*) let function_name = String.sub function_name ~pos:1 ~len:(String.length function_name - 1) in visitor#on_fun_def (env, (current_ctx, function_name)) f end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/global_access_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/ifc_tast_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Ifc_types open Aast open Base let options : options = { opt_mode = Ifc_types.Mcheck; (* TODO: support non default security lattices *) opt_security_lattice = FlowSet.empty; } let catch_ifc_internal_errors pos f = try Timeout.with_timeout ~timeout:5 ~do_:(fun _ -> f ()) ~on_timeout:(fun _ -> Hh_logger.log "Timed out running IFC analysis on %s" (Relative_path.suffix (Pos.filename pos))) with (* Solver exceptions*) | IFCError _ (* Failwith exceptions *) | Failure _ | _ -> () let decl_env : decl_env = { de_class = SMap.empty } let check_errors_from_callable_result result = match result with | Some r -> let results = Ifc.get_solver_result [r] in let simplified_results = SMap.map Ifc.simplify results in SMap.iter (Ifc.check_valid_flow options) simplified_results | None -> () (* Run IFC on a single method, catching exceptions *) let handle_method (class_name : string) (ctx : Provider_context.t) ({ m_name = (_, name); m_annotation = saved_env; m_params = params; m_body = body; m_ret = (return, _); m_span = pos; m_static = is_static; _; } : Tast.method_) : unit = catch_ifc_internal_errors pos (fun () -> Ifc.analyse_callable ~opts:options ~class_name ~pos ~decl_env ~is_static ~saved_env ~ctx name params body return |> check_errors_from_callable_result) (* Run IFC on a single toplevel function, catching exceptions *) let handle_fun (ctx : Provider_context.t) (fd : Tast.fun_def) = let (_, name) = fd.fd_name in let { f_annotation = saved_env; f_params = params; f_body = body; f_ret = (return, _); f_span = pos; _; } = fd.fd_fun in catch_ifc_internal_errors pos (fun () -> Ifc.analyse_callable ~opts:options ~pos ~decl_env ~is_static:false ~saved_env ~ctx name params body return |> check_errors_from_callable_result) let ifc_enabled_on_file tcopt file = let ifc_enabled_paths = TypecheckerOptions.ifc_enabled tcopt in let path = "/" ^ Relative_path.suffix file in List.exists ifc_enabled_paths ~f:(fun prefix -> String.is_prefix path ~prefix) let should_run_ifc tcopt file = match ( ifc_enabled_on_file tcopt file, TypecheckerOptions.experimental_feature_enabled tcopt TypecheckerOptions.experimental_infer_flows ) with | (true, false) -> true (* If inferflows is allowed, IFC tast check won't work properly since there can be global inference. We're in IFC mode anyways, so don't run it here. *) | (true, true) -> false | _ -> false let handler = object inherit Tast_visitor.handler_base method! at_class_ env c = if should_run_ifc (Tast_env.get_tcopt env) (Tast_env.get_file env) then let ctx : Provider_context.t = Tast_env.get_ctx env in let (_, classname) = c.c_name in let methods = c.c_methods in List.iter ~f:(handle_method classname ctx) methods method! at_fun_def env f = if should_run_ifc (Tast_env.get_tcopt env) (Tast_env.get_file env) then let ctx : Provider_context.t = Tast_env.get_ctx env in handle_fun ctx f end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/ifc_tast_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/instantiability_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast module SN = Naming_special_names module Cls = Decl_provider.Class (* This TAST check raises an error when an abstract final class or a trait appears outside of classname<_>. *) let rec validate_classname env (pos, hint) = match hint with | Aast.Happly _ | Aast.Hthis | Aast.Hany | Aast.Herr | Aast.Hmixed | Aast.Hwildcard | Aast.Hnonnull | Aast.Habstr _ | Aast.Haccess _ | Aast.Hdynamic | Aast.Hsoft _ | Aast.Hlike _ | Aast.Hnothing -> () | Aast.Hrefinement (h, _) -> validate_classname env h | Aast.Htuple _ | Aast.Hunion _ | Aast.Hintersection _ | Aast.Hvec_or_dict _ | Aast.Hprim _ | Aast.Hoption _ | Aast.Hfun _ | Aast.Hshape _ | Aast.Hfun_context _ | Aast.Hvar _ -> Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.Invalid_classname pos) let rec check_hint env (pos, hint) = match hint with | Aast.Happly ((_, class_id), tal) -> begin match Tast_env.get_class_or_typedef env class_id with | Some (Tast_env.ClassResult cls) when let kind = Cls.kind cls in let tc_name = Cls.name cls in (Ast_defs.is_c_trait kind || (Ast_defs.is_c_abstract kind && Cls.final cls)) && String.( <> ) tc_name SN.Collections.cDict && String.( <> ) tc_name SN.Collections.cKeyset && String.( <> ) tc_name SN.Collections.cVec -> let tc_pos = Cls.pos cls in let tc_name = Cls.name cls in let err = Typing_error.( primary @@ Primary.Uninstantiable_class { pos; class_name = tc_name; decl_pos = tc_pos; reason_ty_opt = None; }) in Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) err | _ -> () end; if String.equal class_id SN.Classes.cClassname then Option.iter (List.hd tal) ~f:(validate_classname (Tast_env.tast_env_as_typing_env env)) else List.iter tal ~f:(check_hint env) | Aast.Hrefinement (h, members) -> let check_bounds (lower, upper) = List.iter lower ~f:(check_hint env); List.iter upper ~f:(check_hint env) in let check_member = function | Aast.Rtype (_, ref) -> (match ref with | Aast.TRexact h -> check_hint env h | Aast.TRloose { Aast.tr_lower; tr_upper } -> check_bounds (tr_lower, tr_upper)) | Aast.Rctx (_, ref) -> (match ref with | Aast.CRexact h -> check_hint env h | Aast.CRloose { Aast.cr_lower; cr_upper } -> check_bounds (Option.to_list cr_lower, Option.to_list cr_upper)) in List.iter members ~f:check_member; check_hint env h | Aast.Hshape hm -> check_shape env hm | Aast.Haccess (h, ids) -> check_access env h ids | Aast.Hvec_or_dict (hopt1, h2) -> Option.iter hopt1 ~f:(check_hint env); check_hint env h2 | Aast.Hoption h | Aast.Hlike h | Aast.Hsoft h -> check_hint env h | Aast.Habstr _ | Aast.Hprim _ | Aast.Hany | Aast.Herr | Aast.Hdynamic | Aast.Hnonnull | Aast.Hmixed | Aast.Hwildcard | Aast.Hthis | Aast.Hnothing | Aast.Hfun_context _ | Aast.Hvar _ -> () | Aast.Hfun Aast. { hf_is_readonly = _; hf_param_tys = hl; hf_param_info = _; (* TODO: shouldn't we be checking this hint as well? *) hf_variadic_ty = _; hf_ctxs = _; hf_return_ty = h; hf_is_readonly_return = _; } -> List.iter hl ~f:(check_hint env); check_hint env h | Aast.Htuple hl | Aast.Hunion hl | Aast.Hintersection hl -> List.iter hl ~f:(check_hint env) and check_shape env Aast.{ nsi_allows_unknown_fields = _; nsi_field_map } = List.iter ~f:(fun v -> check_hint env v.Aast.sfi_hint) nsi_field_map (* Need to skip the root of the Haccess element *) and check_access env h _ = match h with | (_, Aast.Happly (_, hl)) -> List.iter hl ~f:(check_hint env) | _ -> check_hint env h let check_tparams env tparams = List.iter tparams ~f:(fun t -> List.iter t.tp_constraints ~f:(fun (_ck, h) -> check_hint env h)) let check_param env param = Option.iter (hint_of_type_hint param.param_type_hint) ~f:(check_hint env) let handler = object inherit Tast_visitor.handler_base method! at_typedef env t = check_hint env t.t_kind; Option.iter t.t_as_constraint ~f:(check_hint env); Option.iter t.t_super_constraint ~f:(check_hint env) method! at_class_ env c = let check_class_vars cvar = Option.iter (hint_of_type_hint cvar.cv_type) ~f:(check_hint env) in List.iter c.c_vars ~f:check_class_vars; check_tparams env c.c_tparams method! at_fun_def env fd = check_tparams env fd.fd_tparams method! at_fun_ env f = List.iter f.f_params ~f:(check_param env); Option.iter (hint_of_type_hint f.f_ret) ~f:(check_hint env) method! at_method_ env m = check_tparams env m.m_tparams; List.iter m.m_params ~f:(check_param env); Option.iter (hint_of_type_hint m.m_ret) ~f:(check_hint env) method! at_hint env (_, h) = match h with | Aast.Hshape hm -> check_shape env hm | _ -> () method! at_gconst env cst = Option.iter cst.cst_type ~f:(check_hint env) method! at_expr env (_, _, e) = match e with | Is (_, h) -> check_hint env h | As (_, h, _) -> check_hint env h | _ -> () end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/instantiability_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/invalid_index_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast open Typing_defs module Env = Tast_env module TCO = TypecheckerOptions module MakeType = Typing_make_type module SN = Naming_special_names open String.Replace_polymorphic_compare let should_enforce env = TCO.disallow_invalid_arraykey (Env.get_tcopt env) let equiv_ak_inter_dyn env ty_expect = let r = get_reason ty_expect in let ak_dyn = MakeType.intersection r [MakeType.arraykey r; MakeType.dynamic r] in Env.can_subtype env ty_expect ak_dyn && Env.can_subtype env ak_dyn ty_expect (* For new-inference, types of keys in collection types may not be resolved * until TAST check time. For this reason, we replicate some of the checks that * are applied in Typing_array_access.array_get here. Specifically, those * checks that involve the key type from a dictionary-like container, checked * against the type of the index expression. For example, * the container might have a type dict<k,t> and the index expression might * have a type k'. We want k' <: k. *) let rec array_get ~array_pos ~expr_pos ~index_pos env array_ty index_ty = let type_index ?(is_covariant_index = false) env ty_have ty_expect reason = let t_env = Env.tast_env_as_typing_env env in let got_error = if Typing_env_types.( TypecheckerOptions.enable_sound_dynamic t_env.genv.tcopt) then let (_env, ty_err_opt) = Typing_coercion.coerce_type ~coerce_for_op:true index_pos reason t_env ty_have (MakeType.enforced ty_expect) Typing_error.Callback.index_type_mismatch in Option.is_some ty_err_opt else Option.is_none (Typing_coercion.try_coerce ~coerce:None t_env ty_have (MakeType.enforced ty_expect)) in if not got_error then Ok () else if (Env.can_subtype env ty_have (MakeType.dynamic (get_reason ty_have)) (* Terrible heuristic to agree with legacy: if we inferred `nothing` for * the key type of the array, just let it pass *) || Env.can_subtype env ty_expect (MakeType.nothing (get_reason ty_expect)) ) (* If the key is not even an arraykey, we've already produced an error *) || (not (Env.can_subtype env ty_have (MakeType.arraykey Reason.Rnone))) && should_enforce env (* Keytype of arraykey&dynamic happens when you assign a dynamic into a dict, but the above coercion doesn't work. *) || equiv_ak_inter_dyn env ty_expect then Ok () else let reasons_opt = Some (lazy (let (_, ty_have) = Env.expand_type env ty_have in let (_, ty_expect) = Env.expand_type env ty_expect in let ty_expect_str = Env.print_error_ty env ty_expect in let ty_have_str = Env.print_error_ty env ty_have in Typing_reason.to_string ("This is " ^ ty_expect_str) (get_reason ty_expect) @ Typing_reason.to_string ("It is incompatible with " ^ ty_have_str) (get_reason ty_have))) in Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Index_type_mismatch { pos = expr_pos; msg_opt = Some (Reason.string_of_ureason reason); reasons_opt; is_covariant_container = is_covariant_index; }); Error () in let (_, ety) = Env.expand_type env array_ty in match get_node ety with | Tunion tyl -> List.iter tyl ~f:(fun ty -> array_get ~array_pos ~expr_pos ~index_pos env ty index_ty) | Tclass ((_, cn), _, key_ty :: _) when cn = SN.Collections.cDict || cn = SN.Collections.cKeyset -> (* dict and keyset are both covariant in their key types so it is only required that the index be a subtype of the upper bound on that param, i.e., arraykey Here, we first check that we do not have a type error; if we do not, we then check that the indexing expression is a subtype of the key type and raise a distinct error. This allows us to retain the older behavior (which raised an index_type_mismatch error) whilst allowing us to discern between it and errors which can be addressed with `UNSAFE_CAST` *) let arraykey_ty = MakeType.arraykey (Reason.Ridx_dict array_pos) in let array_key_res = type_index env index_ty arraykey_ty (Reason.index_class cn) in (match array_key_res with | Error _ -> (* We have raised the more general error *) () | Ok _ -> (* The index expression _is_ a subtype of arraykey, now check it is a subtype of the given key_ty *) let (_ : (unit, unit) result) = type_index ~is_covariant_index:true env index_ty key_ty (Reason.index_class cn) in ()) | Tclass ((_, cn), _, key_ty :: _) when cn = SN.Collections.cMap || cn = SN.Collections.cConstMap || cn = SN.Collections.cImmMap || cn = SN.Collections.cKeyedContainer || cn = SN.Collections.cAnyArray -> let (_ : (unit, unit) result) = type_index env index_ty key_ty (Reason.index_class cn) in () | Toption array_ty -> array_get ~array_pos ~expr_pos ~index_pos env array_ty index_ty | Tnonnull | Tprim _ | Tfun _ | Tvar _ | Tclass _ | Ttuple _ | Tshape _ | Tdynamic | Tany _ | Tnewtype _ | Tdependent _ | _ -> () let index_visitor = object (this) inherit [_] Tast_visitor.iter_with_state as super (* Distinguish between lvalue and rvalue array indexing. * Suppose $x : dict<string,int> * We want to check rvalue e.g. $y = $x[3], or $z[$x[3]] = 5 * But not lvalue e.g. $x[3] = 5 or list ($x[3], $w) = e; *) method! on_expr (env, is_lvalue) ((_, p, expr) as e) = match expr with | Array_get (((ty1, p1, _) as e1), Some ((ty2, p2, _) as e2)) -> if not is_lvalue then array_get ~array_pos:p1 ~expr_pos:p ~index_pos:p2 env ty1 ty2; this#on_expr (env, false) e1; this#on_expr (env, false) e2 | Binop { bop = Ast_defs.Eq _; lhs; rhs } -> this#on_expr (env, true) lhs; this#on_expr (env, false) rhs | List el -> List.iter ~f:(this#on_expr (env, is_lvalue)) el | _ -> super#on_expr (env, is_lvalue) e end let handler = object inherit Tast_visitor.handler_base method! at_fun_def env = index_visitor#on_fun_def (env, false) method! at_method_ env = index_visitor#on_method_ (env, false) end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/invalid_index_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/like_type_logger.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude module JSON = Hh_json let dynamic = Typing_make_type.dynamic Typing_reason.Rnone let mixed = Typing_make_type.mixed Typing_reason.Rnone let supportdyn_of_mixed = Typing_make_type.supportdyn_mixed Typing_reason.Rnone let is_exactly env ty ty' = Tast_env.is_sub_type env ty ty' && Tast_env.is_sub_type env ty' ty let is_like_type env ty = let is_sub_type = Tast_env.is_sub_type env in is_sub_type dynamic ty && not (is_sub_type mixed ty || is_sub_type supportdyn_of_mixed ty) let should_log env = not @@ Tast_env.is_hhi env let like_type_log_level_of env = Tast_env.get_tcopt env |> TypecheckerOptions.log_levels |> SMap.find_opt "like_type" |> Option.value ~default:0 let locl_ty_of_hint (ty, _) = ty module Counter : sig type t val zero : t val is_zero : t -> bool val plus : t -> t -> t val unit : Tast_env.t -> Typing_defs.locl_ty -> t val json_of : t -> JSON.json end = struct module Key = struct type t = | Like | NonLike | Mixed | SupportdynOfMixed | Dynamic [@@deriving show { with_path = false }, ord] end open WrappedMap.Make (Key) type nonrec t = int t let zero = empty let is_zero = is_empty let plus = merge (fun _ c_opt c_opt' -> match (c_opt, c_opt') with | (Some c, Some c') -> Some (c + c') | (None, Some c) | (Some c, None) -> Some c | (None, None) -> None) let inc key = update key @@ function | None -> Some 1 | Some c -> Some (c + 1) let unit env ty = empty |> begin if is_like_type env ty then inc Key.Like else inc Key.NonLike end |> begin if is_exactly env ty mixed then inc Key.Mixed else Fn.id end |> begin if is_exactly env ty supportdyn_of_mixed then inc Key.SupportdynOfMixed else Fn.id end |> begin if is_exactly env ty dynamic then inc Key.Dynamic else Fn.id end let json_of ctr = JSON.JSON_Object (bindings ctr |> List.map ~f:(fun (k, v) -> (Key.show k, JSON.int_ v))) end module Categories : sig module Key : sig type t = | Expression | Obj_get_receiver | Class_get_receiver | Class_const_receiver | Property | Parameter | Return end type t val zero : t val plus : t -> t -> t val singleton : Key.t -> Counter.t -> t val json_of : t -> JSON.json end = struct module Key = struct type t = | Expression | Obj_get_receiver | Class_get_receiver | Class_const_receiver | Property | Parameter | Return [@@deriving show { with_path = false }, ord] end open WrappedMap.Make (Key) type nonrec t = Counter.t t let zero = empty let plus = merge (fun _ c_opt c_opt' -> match (c_opt, c_opt') with | (Some c, Some c') -> Some (Counter.plus c c') | (None, Some c) | (Some c, None) -> Some c | (None, None) -> None) let singleton k c = if Counter.is_zero c then empty else singleton k c let json_of ctr = JSON.JSON_Object (bindings ctr |> List.map ~f:(fun (k, v) -> (Key.show k, Counter.json_of v))) end module Log = struct type t = { pos: Pos.t; categories: Categories.t; } let json_of l = let pos_str = let pos = l.pos in let filename = Pos.to_relative_string pos |> Pos.filename in let line = Pos.line pos in Format.sprintf "%s:%d" filename line in JSON.JSON_Object [ ("pos", JSON.string_ pos_str); ("categories", Categories.json_of l.categories); ] let to_string ?(pretty = false) l = Format.sprintf "[Like_type_logger] %s" (json_of l |> JSON.json_to_string ~pretty) end let callable_decl_counter env params ret = let parameter = List.fold params ~init:Counter.zero ~f:(fun acc param -> let ty = locl_ty_of_hint param.Aast.param_type_hint in Counter.plus acc (Counter.unit env ty)) |> Categories.singleton Categories.Key.Parameter in let return = let ty = locl_ty_of_hint ret in Counter.unit env ty |> Categories.singleton Categories.Key.Return in Categories.(plus parameter return) let partition_types = object inherit [_] Tast_visitor.reduce as super method zero = Categories.zero method plus = Categories.plus method! on_expr env ((ty, _, e_) as e) = let open Categories in Counter.unit env ty |> Categories.singleton Categories.Key.Expression |> plus begin match e_ with | Aast.Obj_get ((receiver_ty, _, _), _, _, _) -> Counter.unit env receiver_ty |> singleton Key.Obj_get_receiver | Aast.Class_get ((receiver_ty, _, _), _, _) -> Counter.unit env receiver_ty |> singleton Key.Class_get_receiver | Aast.Class_const ((receiver_ty, _, _), _) -> Counter.unit env receiver_ty |> singleton Key.Class_const_receiver | _ -> zero end |> plus (super#on_expr env e) method! on_method_ env m = let declaration = callable_decl_counter env m.Aast.m_params m.Aast.m_ret in let expression = super#on_method_ env m in Categories.plus declaration expression method! on_fun_ env f = let declaration = callable_decl_counter env f.Aast.f_params f.Aast.f_ret in let expression = super#on_fun_ env f in Categories.plus declaration expression method! on_class_ env c = let property = List.fold c.Aast.c_vars ~init:Counter.zero ~f:(fun acc prop -> let ty = locl_ty_of_hint prop.Aast.cv_type in Counter.plus acc (Counter.unit env ty)) |> Categories.singleton Categories.Key.Property in let method_ = super#on_class_ env c in Categories.plus property method_ end let log_type_partition env log = if like_type_log_level_of env > 1 then Hh_logger.log "%s" (Log.to_string log) else begin (* We don't use the logger when the log level is 1 so that we can write .exp style tests *) Format.sprintf "%s\n" (Log.to_string ~pretty:true log) |> Out_channel.output_string !Typing_log.out_channel; Out_channel.flush !Typing_log.out_channel end let create_handler _ctx = object inherit Tast_visitor.handler_base method! at_fun_ env f = if should_log env then let categories = partition_types#on_fun_ env f in log_type_partition env Log.{ pos = f.Aast.f_span; categories } method! at_class_ env c = if should_log env then let categories = partition_types#on_class_ env c in log_type_partition env Log.{ pos = c.Aast.c_span; categories } end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/like_type_logger.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. * *) (** Tast visitor to count like types across different entities. *) val create_handler : Provider_context.t -> Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/method_type_param_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast let check_tparams env tps = let check_tparam tp = match tp.tp_variance with | Ast_defs.Invariant -> () | _ -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.(primary @@ Primary.Method_variance (fst tp.tp_name)) in List.iter tps ~f:check_tparam let handler = object inherit Tast_visitor.handler_base method! at_method_ env m = check_tparams env m.m_tparams method! at_fun_def env fd = check_tparams env fd.fd_tparams end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/method_type_param_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/meth_caller_check.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast open Typing_defs (* meth_caller does not support methods with inout parameters *) let check_parameters env = let get_illegal_parameter ftype = List.find ~f:(fun ft_param -> match get_fp_mode ft_param with | FPnormal -> false | _ -> true) ftype.ft_params in let rec check pos ft = match get_node ft with | Tfun ftype -> begin match get_illegal_parameter ftype with | Some fparam -> let convention = match get_fp_mode fparam with | FPinout -> "`inout`" | FPnormal -> "normal" in Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Invalid_meth_caller_calling_convention { pos; decl_pos = fparam.fp_pos; convention }) | None -> () end | Tnewtype (name, [ty], _) when String.equal Naming_special_names.Classes.cSupportDyn name -> check pos ty | _ -> () in check let check_readonly_return env pos ft = match get_node ft with | Tfun ftype -> if Flags.get_ft_returns_readonly ftype then let (_, expanded_ty) = Tast_env.expand_type env ft in let r = get_reason expanded_ty in let rpos = Typing_reason.to_pos r in Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Invalid_meth_caller_readonly_return { pos; decl_pos = rpos }) | _ -> () let strip_supportdyn ty = match get_node ty with | Tnewtype (name, [ty], _) when String.equal name Naming_special_names.Classes.cSupportDyn -> ty | _ -> ty let handler = object inherit Tast_visitor.handler_base method! at_expr env e = match e with | (ft, pos, Method_caller _) -> let ft = strip_supportdyn ft in check_parameters (Tast_env.tast_env_as_typing_env env) pos ft; check_readonly_return env pos ft | _ -> () end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/meth_caller_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/obj_get_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Aast open Typing_defs module MakeType = Typing_make_type let handler = object inherit Tast_visitor.handler_base method! at_expr env = function | (_, _, Obj_get (_, (_, p, This), _, _)) -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Nonsense_member_selection { pos = p; kind = "$this" }) | (_, _, Obj_get (_, (_, p, Lplaceholder _), _, _)) -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Nonsense_member_selection { pos = p; kind = "$_" }) | (_, _, Obj_get ((ty, _, _), _, _, _)) when Tast_env.is_sub_type_for_union env ty (MakeType.dynamic Reason.none) || Tast_env.is_sub_type_for_union env ty (mk (Reason.none, Typing_defs.make_tany ())) -> (* TODO akenn: do we need to detect error tyvar too? *) () | (_, _, Obj_get (_, (_, pos, Lvar (lvar_pos, lvar_lid)), _, _)) -> let lvar_name = Local_id.get_name lvar_lid in Errors.add_error Naming_error.( to_user_error @@ Lvar_in_obj_get { pos; lvar_pos; lvar_name }) | _ -> () end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/obj_get_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/pseudofunctions_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Aast module SN = Naming_special_names let disallow_isset_inout_args_check env p = function | Call { func = (_, _, Id (_, pseudo_func)); args; _ } when String.equal pseudo_func SN.PseudoFunctions.isset && List.exists (function | (Ast_defs.Pinout _, _) -> true | (Ast_defs.Pnormal, _) -> false) args -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.(primary @@ Primary.Isset_inout_arg p) | _ -> () let well_formed_isset_argument_check env p = function | Call { func = (_, _, Id (_, pseudo_func)); args = [(_, (_, _, arg))]; _ } -> begin match arg with | Lvar _ (* isset($var->thing) but not isset($foo->$bar) *) | Obj_get (_, (_, _, Id _), _, Is_prop) (* isset($var::thing) but not isset($foo::$bar) *) | Class_get (_, CGexpr (_, _, Id _), _) when String.equal pseudo_func SN.PseudoFunctions.isset -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.(primary @@ Primary.Isset_in_strict p) | _ -> () end | _ -> () let handler = object inherit Tast_visitor.handler_base method! at_expr env (_, p, x) = disallow_isset_inout_args_check env p x; well_formed_isset_argument_check env p x end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/pseudofunctions_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/readonly_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast module Cls = Decl_provider.Class module SN = Naming_special_names module MakeType = Typing_make_type module Reason = Typing_reason (* Create a synthetic function type out of two fun_ty that has the correct readonlyness by being conservative *) let union_fty_readonly (fty1 : Typing_defs.locl_ty Typing_defs.fun_type) (fty2 : Typing_defs.locl_ty Typing_defs.fun_type) : Typing_defs.locl_ty Typing_defs.fun_type = let open Typing_defs in let union_fp_readonly fp1 fp2 = match (get_fp_readonly fp1, get_fp_readonly fp2) with | (true, _) -> fp2 (* Must both be readonly to be readonly *) | (false, _) -> fp1 in (* Not readonly *) (* Must both be readonly to be considered a readonly call *) let fty_readonly_this = get_ft_readonly_this fty1 && get_ft_readonly_this fty2 in (* If either are readonly, consider readonly return *) let fty_returns_readonly = get_ft_returns_readonly fty1 || get_ft_returns_readonly fty2 in let fty = set_ft_readonly_this fty1 fty_readonly_this in let fty = set_ft_returns_readonly fty fty_returns_readonly in let fps = List.map2 fty1.ft_params fty2.ft_params ~f:union_fp_readonly in (* If lenghts unequal we have other problems and errors, just return the first one *) let fps = match fps with | List.Or_unequal_lengths.Unequal_lengths -> fty1.ft_params | List.Or_unequal_lengths.Ok fp -> fp in { fty with Typing_defs.ft_params = fps } let rec get_fty ty = let open Typing_defs in match get_node ty with | Tnewtype (name, _, ty2) when String.equal name SN.Classes.cSupportDyn -> get_fty ty2 | Tfun fty -> Some fty | Tunion tyl -> (* Filter out dynamic types *) let ftys = List.filter_map tyl ~f:get_fty in (* Because Typing_union already aggressively simplifies function unions to a single function type, there should be a single function type here 99% of the time. *) (match ftys with (* Not calling a function, ignore *) | [] -> None (* In the rare case where union did not simplify, use readonly union to merge all fty's together with a union into a single function type, and return it. *) | fty1 :: rest -> let result = List.fold ~init:fty1 ~f:union_fty_readonly rest in Some result) | _ -> None type rty = | Readonly | Mut [@deriving show] (* Returns true if rty_sub is a subtype of rty_sup. TODO: Later, we'll have to consider the regular type as well, for example we could allow readonly int as equivalent to an int for devX purposes. This would require TIC to handle correctly, though. *) let subtype_rty rty_sub rty_sup = match (rty_sub, rty_sup) with | (Readonly, Mut) -> false | _ -> true let param_to_rty param = if Typing_defs.get_fp_readonly param then Readonly else Mut let rec grab_class_elts_from_ty ~static ?(seen = SSet.empty) env ty prop_id = let open Typing_defs in (* Given a list of types, find recurse on the first type that has the property and return the result *) let find_first_in_list ~seen tyl = List.find_map ~f:(fun ty -> match grab_class_elts_from_ty ~static ~seen env ty prop_id with | [] -> None | tyl -> Some tyl) tyl in match get_node ty with | Tclass (id, _exact, _args) -> let provider_ctx = Tast_env.get_ctx env in let class_decl = Decl_provider.get_class provider_ctx (snd id) in (match class_decl with | Some class_decl -> let prop = if static then Cls.get_sprop class_decl (snd prop_id) else Cls.get_prop class_decl (snd prop_id) in Option.to_list prop | None -> []) (* Accessing a property off of an intersection type should involve exactly one kind of readonlyness, since for the intersection type to exist, the property must be related by some subtyping relationship anyways, and property readonlyness is invariant. Thus we just grab the first one from the list where the prop exists. *) | Tintersection [] -> [] | Tintersection tyl -> find_first_in_list ~seen tyl |> Option.value ~default:[] (* A union type is more interesting, where we must return all possible cases and be conservative in our use case. *) | Tunion tyl -> List.concat_map ~f:(fun ty -> grab_class_elts_from_ty ~static ~seen env ty prop_id) tyl (* Generic types can be treated similarly to an intersection type where we find the first prop that works from the upper bounds *) | Tgeneric (name, tyargs) -> (* Avoid circular generics with a set *) if SSet.mem name seen then [] else let new_seen = SSet.add name seen in let upper_bounds = Tast_env.get_upper_bounds env name tyargs in find_first_in_list ~seen:new_seen (Typing_set.elements upper_bounds) |> Option.value ~default:[] | Tdependent (_, ty) -> (* Dependent types have an upper bound that's a class or generic *) grab_class_elts_from_ty ~static ~seen env ty prop_id | Toption ty -> (* If it's nullable, take the *) grab_class_elts_from_ty ~static ~seen env ty prop_id | _ -> [] (* Return a list of possible static prop elts given a class_get expression *) let get_static_prop_elts env class_id get = let (ty, _, _) = class_id in match get with | CGstring prop_id -> grab_class_elts_from_ty ~static:true env ty prop_id (* An expression is dynamic, so there's no way to tell the type generally *) | CGexpr _ -> [] (* Return a list of possible prop elts given an obj get expression *) let get_prop_elts env obj get = let (env, ty) = Tast_env.expand_type env (Tast.get_type obj) in match get with | (_, _, Id prop_id) -> grab_class_elts_from_ty ~static:false env ty prop_id (* TODO: Handle more complex cases *) | _ -> [] let rec ty_expr env ((_, _, expr_) : Tast.expr) : rty = match expr_ with | ReadonlyExpr _ -> Readonly (* Obj_get, array_get, and class_get are here for better error messages when used as lval *) | Obj_get (e1, e2, _, Is_prop) -> (match ty_expr env e1 with | Readonly -> Readonly | Mut -> (* In the mut case, we need to check if the property is marked readonly *) let prop_elts = get_prop_elts env e1 e2 in let readonly_prop = List.find ~f:Typing_defs.get_ce_readonly_prop prop_elts in Option.value_map readonly_prop ~default:Mut ~f:(fun _ -> Readonly)) | Class_get (class_id, expr, Is_prop) -> (* If any of the static props could be readonly, treat the expression as readonly *) let class_elts = get_static_prop_elts env class_id expr in (* Note that the empty list case (when the prop doesn't exist) returns Mut *) if List.exists class_elts ~f:Typing_defs.get_ce_readonly_prop then Readonly else Mut | Array_get (array, _) -> ty_expr env array | _ -> Mut let is_value_collection_ty env ty = let mixed = MakeType.mixed Reason.none in let env = Tast_env.tast_env_as_typing_env env in let ty = Typing_utils.strip_dynamic env ty in let hackarray = MakeType.any_array Reason.none mixed mixed in (* Subtype against an empty open shape (shape(...)) *) let shape = MakeType.open_shape Reason.none Typing_defs.TShapeMap.empty in Typing_utils.is_sub_type env ty hackarray || Typing_utils.is_sub_type env ty shape (* Check if type is safe to convert from readonly to mut TODO(readonly): Update to include more complex types. *) let rec is_safe_mut_ty env (seen : SSet.t) ty = let open Typing_defs_core in let (env, ty) = Tast_env.expand_type env ty in match get_node ty with (* Allow all primitive types *) | Tprim _ -> true (* Open shapes can technically have objects in them, but as long as the current fields don't have objects in them we will allow you to call the function. Note that the function fails at runtime if any shape fields are objects. *) | Tshape { s_fields = fields; _ } -> TShapeMap.for_all (fun _k v -> is_safe_mut_ty env seen v.sft_ty) fields (* If it's a Tclass it's an array type by is_value_collection *) | Tintersection tyl -> List.exists tyl ~f:(fun l -> is_safe_mut_ty env seen l) (* Only error if there isn't a type that it could be that's primitive *) | Tunion tyl -> List.exists tyl ~f:(fun l -> is_safe_mut_ty env seen l) | Ttuple tyl -> List.for_all tyl ~f:(fun l -> is_safe_mut_ty env seen l) | Tdependent (_, upper) -> (* check upper bounds *) is_safe_mut_ty env seen upper | Tclass (_, _, tyl) when is_value_collection_ty env ty -> List.for_all tyl ~f:(fun l -> is_safe_mut_ty env seen l) | Tgeneric (name, tyargs) -> (* Avoid circular generics with a set *) if SSet.mem name seen then false else let new_seen = SSet.add name seen in let upper_bounds = Tast_env.get_upper_bounds env name tyargs in Typing_set.exists (fun l -> is_safe_mut_ty env new_seen l) upper_bounds | _ -> (* Otherwise, check if there's any primitive type it could be *) let env = Tast_env.tast_env_as_typing_env env in let primitive_types = [ MakeType.bool Reason.none; MakeType.int Reason.none; MakeType.arraykey Reason.none; MakeType.string Reason.none; MakeType.float Reason.none; MakeType.num Reason.none; (* Keysets only contain arraykeys so if they're readonly its safe to remove *) MakeType.keyset Reason.none (MakeType.arraykey Reason.none); (* We don't put null here because we want to exclude ?Foo. as_mut(null) itself is allowed by the Tprim above*) ] in (* Make sure that a primitive *could* be this type by intersecting all primitives and subtyping. *) let union = MakeType.union Reason.none primitive_types in not (Typing_subtype.is_type_disjoint env ty union) (* Check that function calls which return readonly are wrapped in readonly *) let rec check_readonly_return_call env pos caller_ty is_readonly = if is_readonly then () else let open Typing_defs in match get_node caller_ty with | Tunion tyl -> List.iter tyl ~f:(fun ty -> check_readonly_return_call env pos ty is_readonly) | _ -> (match get_fty caller_ty with | Some fty when get_ft_returns_readonly fty -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( readonly @@ Primary.Readonly.Explicit_readonly_cast { pos; kind = `fn_call; decl_pos = Typing_defs.get_pos caller_ty; }) | _ -> ()) let check_readonly_property env obj get obj_ro = let open Typing_defs in let prop_elts = get_prop_elts env obj get in (* If there's any property in the list of possible properties that could be readonly, it must be explicitly cast to readonly *) let readonly_prop = List.find ~f:get_ce_readonly_prop prop_elts in match (readonly_prop, obj_ro) with | (Some elt, Mut) -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( readonly @@ Primary.Readonly.Explicit_readonly_cast { pos = Tast.get_position get; kind = `property; decl_pos = Lazy.force elt.ce_pos; }) | _ -> () let check_static_readonly_property pos env (class_ : Tast.class_id) get obj_ro = let prop_elts = get_static_prop_elts env class_ get in (* If there's any property in the list of possible properties that could be readonly, it must be explicitly cast to readonly *) let readonly_prop = List.find ~f:Typing_defs.get_ce_readonly_prop prop_elts in match (readonly_prop, obj_ro) with | (Some elt, Mut) when Typing_defs.get_ce_readonly_prop elt -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( readonly @@ Primary.Readonly.Explicit_readonly_cast { pos; kind = `static_property; decl_pos = Lazy.force elt.Typing_defs.ce_pos; }) | _ -> () let is_method_caller (caller : Tast.expr) = match caller with | (_, _, ReadonlyExpr (_, _, Obj_get (_, _, _, Is_method))) | (_, _, Obj_get (_, _, _, Is_method)) -> true | _ -> false let is_special_builtin = function (* none of these functions require readonly checks, and can take in readonly values safely *) | "HH\\dict" | "HH\\varray" | "HH\\darray" | "HH\\vec" | "HH\\keyset" | "hphp_array_idx" -> true | _ -> false let rec assign env lval rval = (* Check that we're assigning a readonly value to a readonly property *) let check_ro_prop_assignment prop_elts = let mutable_prop = List.find ~f:(fun r -> not (Typing_defs.get_ce_readonly_prop r)) prop_elts in match mutable_prop with | Some elt when not (Typing_defs.get_ce_readonly_prop elt) -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( readonly @@ Primary.Readonly.Readonly_mismatch { pos = Tast.get_position lval; what = `prop_assign; pos_sub = Tast.get_position rval |> Pos_or_decl.of_raw_pos; pos_super = Lazy.force elt.Typing_defs.ce_pos; }) | _ -> () in match lval with (* List assignment *) | (_, _, List exprs) -> List.iter exprs ~f:(fun lval -> assign env lval rval) | (_, _, Array_get (array, _)) -> begin match (ty_expr env array, ty_expr env rval) with | (Readonly, _) when is_value_collection_ty env (Tast.get_type array) -> (* In the case of (expr)[0] = rvalue, where expr is a value collection like vec, we need to check assignment recursively because ($x->prop)[0] is only valid if $x is mutable and prop is readonly. *) (match array with | (_, _, Array_get _) | (_, _, Obj_get _) -> assign env array rval | _ -> ()) | (Mut, Readonly) -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( readonly @@ Primary.Readonly.Readonly_mismatch { pos = Tast.get_position lval; what = `collection_mod; pos_sub = Tast.get_position rval |> Pos_or_decl.of_raw_pos; pos_super = Tast.get_position array |> Pos_or_decl.of_raw_pos; }) | (Readonly, _) -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( readonly @@ Primary.Readonly.Readonly_modified { pos = Tast.get_position array; reason_opt = None }) | (Mut, Mut) -> () end | (_, _, Class_get (id, expr, Is_prop)) -> (match ty_expr env rval with | Readonly -> let prop_elts = get_static_prop_elts env id expr in check_ro_prop_assignment prop_elts | _ -> ()) | (_, _, Obj_get (obj, get, _, Is_prop)) -> (* Here to check for nested property accesses that are accessing readonly values *) begin match ty_expr env obj with | Readonly -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( readonly @@ Primary.Readonly.Readonly_modified { pos = Tast.get_position obj; reason_opt = None }) | Mut -> () end; (match ty_expr env rval with | Readonly -> let prop_elts = get_prop_elts env obj get in (* If there's a mutable prop, then there's a chance we're assigning to one *) check_ro_prop_assignment prop_elts | _ -> ()) (* TODO: make this exhaustive *) | _ -> () (* Method call invocation *) let method_call env caller = let open Typing_defs in match caller with (* Readonly call checks *) | (ty, _, ReadonlyExpr (_, _, Obj_get (e1, _, _, Is_method))) -> (match get_fty ty with | Some fty when not (get_ft_readonly_this fty) -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( readonly @@ Primary.Readonly.Readonly_method_call { pos = Tast.get_position e1; decl_pos = get_pos ty }) | _ -> ()) | _ -> () let check_special_function env caller args = match (caller, args) with | ((_, _, Id (pos, x)), [(_, arg)]) when String.equal (Utils.strip_ns x) (Utils.strip_ns SN.Readonly.as_mut) -> let arg_ty = Tast.get_type arg in if not (is_safe_mut_ty env SSet.empty arg_ty) then Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.(readonly @@ Primary.Readonly.Readonly_invalid_as_mut pos) else () | _ -> () (* Checks related to calling a function or method is_readonly is true when the call is allowed to return readonly *) let call ~is_readonly ~method_call (env : Tast_env.t) (pos : Pos.t) (caller_ty : Tast.ty) (caller_rty : rty) (args : (Ast_defs.param_kind * Tast.expr) list) (unpacked_arg : Tast.expr option) = let open Typing_defs in let (env, caller_ty) = Tast_env.expand_type env caller_ty in let check_readonly_closure caller_ty caller_rty = match (get_fty caller_ty, caller_rty) with | (Some fty, Readonly) when (not (get_ft_readonly_this fty)) && not method_call -> (* Get the position of why this function is its current type (usually a typehint) *) let reason = get_reason caller_ty in let f_pos = Reason.to_pos (get_reason caller_ty) in let suggestion = match reason with (* If we got this function from a typehint, we suggest marking the function (readonly function) *) | Typing_reason.Rhint _ -> let new_flags = Typing_defs_flags.(set_bit ft_flags_readonly_this true fty.ft_flags) in let readonly_fty = Tfun { fty with ft_flags = new_flags } in let suggested_fty = mk (reason, readonly_fty) in let suggested_fty_str = Tast_env.print_ty env suggested_fty in "annotate this typehint as a " ^ suggested_fty_str (* Otherwise, it's likely from a Rwitness, but we suggest declaring it as readonly *) | _ -> "declaring this as a `readonly` function" in Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( readonly @@ Primary.Readonly.Readonly_closure_call { pos; decl_pos = f_pos; suggestion }) | _ -> () in (* Checks a single arg against a parameter *) let check_arg env param (_, arg) = let param_rty = param_to_rty param in let arg_rty = ty_expr env arg in if not (subtype_rty arg_rty param_rty) then Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( readonly @@ Primary.Readonly.Readonly_mismatch { pos = Tast.get_position arg; what = (match arg_rty with | Readonly -> `arg_readonly | Mut -> `arg_mut); pos_sub = Tast.get_position arg |> Pos_or_decl.of_raw_pos; pos_super = param.fp_pos; }) in (* Check that readonly arguments match their parameters *) let check_args env caller_ty args unpacked_arg = match get_fty caller_ty with | Some fty -> let rec check args params = match (args, params) with (* Remaining args should be checked against variadic *) | (x1 :: args1, [x2]) when get_ft_variadic fty -> check_arg env x2 x1; check args1 [x2] | (x1 :: args1, x2 :: params2) -> check_arg env x2 x1; check args1 params2 | ([], _) -> (* If args are empty, it's either a type error already or a default arg that's not filled in either way, no need to check readonlyness *) () | (_x1 :: _args1, []) -> (* Too many args and no variadic: there was a type error somewhere*) () in let unpacked_rty = unpacked_arg |> Option.map ~f:(fun e -> (Ast_defs.Pnormal, e)) |> Option.to_list in let args = args @ unpacked_rty in check args fty.ft_params | None -> () in check_readonly_closure caller_ty caller_rty; check_readonly_return_call env pos caller_ty is_readonly; check_args env caller_ty args unpacked_arg let caller_is_special_builtin caller = match caller with | (_, _, Id (_, name)) when is_special_builtin (Utils.strip_ns name) -> true | _ -> false let check = object (self) inherit Tast_visitor.iter as super method! on_expr env e = match e with | (_, _, Binop { bop = Ast_defs.Eq _; lhs; rhs }) -> assign env lhs rhs; self#on_expr env rhs | ( _, _, ReadonlyExpr (_, _, Call ({ func; args; unpacked_arg; _ } as call_expr)) ) -> let default () = (* Skip the recursive step into ReadonlyExpr to avoid erroring *) self#on_Call env call_expr in if caller_is_special_builtin func then default () else call ~is_readonly:true ~method_call:(is_method_caller func) env (Tast.get_position func) (Tast.get_type func) (ty_expr env func) args unpacked_arg; check_special_function env func args; method_call env func; default () (* Non readonly calls *) | (_, _, Call { func; args; unpacked_arg; _ }) -> if caller_is_special_builtin func then super#on_expr env e else call env ~is_readonly:false ~method_call:(is_method_caller func) (Tast.get_position func) (Tast.get_type func) (ty_expr env func) args unpacked_arg; check_special_function env func args; method_call env func; super#on_expr env e | (_, _, ReadonlyExpr (_, _, Obj_get (obj, get, nullable, is_prop_call))) -> (* Skip the recursive step into ReadonlyExpr to avoid erroring *) self#on_Obj_get env obj get nullable is_prop_call | (_, _, ReadonlyExpr (_, _, Class_get (class_, get, x))) -> (* Skip the recursive step into ReadonlyExpr to avoid erroring *) self#on_Class_get env class_ get x | (_, _, Obj_get (obj, get, _nullable, Is_prop)) -> check_readonly_property env obj get Mut; super#on_expr env e | (_, pos, Class_get (class_, get, Is_prop)) -> check_static_readonly_property pos env class_ get Mut; super#on_expr env e | (_, pos, New (_, _, args, unpacked_arg, constructor_fty)) -> (* Constructors never return readonly, so that specific check is irrelevant *) call ~is_readonly:false ~method_call:false env pos constructor_fty Mut (List.map ~f:(fun e -> (Ast_defs.Pnormal, e)) args) unpacked_arg; super#on_expr env e | (_, _, Obj_get _) | (_, _, Class_get _) | (_, _, This) | (_, _, ValCollection (_, _, _)) | (_, _, KeyValCollection (_, _, _)) | (_, _, Lvar _) | (_, _, Clone _) | (_, _, Array_get (_, _)) | (_, _, Yield _) | (_, _, Await _) | (_, _, Tuple _) | (_, _, List _) | (_, _, Cast (_, _)) | (_, _, Unop (_, _)) | (_, _, Pipe (_, _, _)) | (_, _, Eif (_, _, _)) | (_, _, Is (_, _)) | (_, _, As (_, _, _)) | (_, _, Upcast (_, _)) | (_, _, Import (_, _)) | (_, _, Lplaceholder _) | (_, _, Pair (_, _, _)) | (_, _, ReadonlyExpr _) | (_, _, Binop _) | (_, _, ExpressionTree _) | (_, _, Xml _) | (_, _, Efun _) (* Neither this nor any of the *_id expressions call the function *) | (_, _, Method_caller (_, _)) | (_, _, FunctionPointer _) | (_, _, Lfun _) | (_, _, Null) | (_, _, True) | (_, _, False) | (_, _, Omitted) | (_, _, Id _) | (_, _, Shape _) | (_, _, EnumClassLabel _) | (_, _, ET_Splice _) | (_, _, Darray _) | (_, _, Varray _) | (_, _, Int _) | (_, _, Dollardollar _) | (_, _, String _) | (_, _, String2 _) | (_, _, Collection (_, _, _)) | (_, _, Class_const _) | (_, _, Float _) | (_, _, PrefixedString _) | (_, _, Hole _) | (_, _, Package _) -> super#on_expr env e (* Stop at invalid marker *) | (_, _, Invalid _) -> () end let handler = object inherit Tast_visitor.handler_base (* Ref updated before every function def *) val fun_has_readonly = ref false method! at_method_ env m = let env = Tast_env.restore_method_env env m in if Tast_env.fun_has_readonly env then ( fun_has_readonly := true; check#on_method_ env m ) else ( fun_has_readonly := false; () ) method! at_fun_def env f = let env = Tast_env.restore_fun_env env f.fd_fun in if Tast_env.fun_has_readonly env then ( fun_has_readonly := true; check#on_fun_def env f ) else ( fun_has_readonly := false; () ) (* The following error checks are ones that need to run even if readonly analysis is not enabled by the file attribute. *) method! at_Call env { func; _ } = (* this check is already handled by the readonly analysis, which handles cases when there's a readonly keyword *) if !fun_has_readonly then () else let caller_pos = Tast.get_position func in let caller_ty = Tast.get_type func in let (_, caller_ty) = Tast_env.expand_type env caller_ty in check_readonly_return_call env caller_pos caller_ty false method! at_expr env e = (* this check is already handled by the readonly analysis, which handles cases when there's a readonly keyword *) let check = if !fun_has_readonly then fun _e -> () else fun e -> let val_kind = Tast_env.get_val_kind env in match (e, val_kind) with | ((_, _, Binop { bop = Ast_defs.Eq _; lhs; rhs }), _) -> (* Check property assignments to make sure they're safe *) assign env lhs rhs (* Assume obj is mutable here since you can't have a readonly thing without readonly keyword/analysis *) (* Only check this for rvalues, not lvalues *) | ((_, _, Obj_get (obj, get, _, Is_prop)), Typing_defs.Other) -> check_readonly_property env obj get Mut | ((_, pos, Class_get (class_id, get, Is_prop)), Typing_defs.Other) -> check_static_readonly_property pos env class_id get Mut | _ -> () in match e with | (_, _, Aast.Invalid _) -> () | _ -> check e end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/readonly_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/redundant_generics_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast open Typing_defs module Cls = Decl_provider.Class module SN = Naming_special_names let ft_redundant_generics env tparams ty = let tracked = List.fold_left tparams ~f:(fun tracked t -> SSet.add (snd t.tp_name) tracked) ~init:SSet.empty in let (positive, negative) = Typing_variance.get_positive_negative_generics ~tracked ~is_mutable:false (Tast_env.tast_env_as_typing_env env) (SMap.empty, SMap.empty) ty in List.iter tparams ~f:(fun t -> let (pos, name) = t.tp_name in (* It's only redundant if it's erased and inferred *) if equal_reify_kind t.tp_reified Erased && not (Attributes.mem SN.UserAttributes.uaExplicit t.tp_user_attributes) then let super_bounds = List.filter ~f:(fun (ck, _) -> Ast_defs.(equal_constraint_kind ck Constraint_super)) t.tp_constraints in let as_bounds = List.filter ~f:(fun (ck, _) -> Ast_defs.(equal_constraint_kind ck Constraint_as)) t.tp_constraints in match (SMap.find_opt name positive, SMap.find_opt name negative) with | (Some _, Some _) -> () | (Some _positions, None) -> let bounds_message = if List.is_empty as_bounds then "" else " with useless `as` bound" in (* If there is more than one `super` bound, we can't replace, * because we don't support explicit union types *) begin match super_bounds with | [] -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Redundant_covariant { pos = Pos_or_decl.unsafe_to_raw_pos pos; msg = bounds_message; suggest = "nothing"; }) | [(_, t)] -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Redundant_covariant { pos = Pos_or_decl.unsafe_to_raw_pos pos; msg = bounds_message; suggest = Tast_env.print_decl_ty env t; }) | _ -> () end | (None, Some _positions) -> () | (None, None) -> ()) let check_redundant_generics_class_method env (_method_name, method_) = match method_.ce_type with | (lazy (ty as ft)) -> begin match get_node ty with | Tfun { ft_tparams; _ } -> ft_redundant_generics env ft_tparams ft | _ -> assert false end let check_redundant_generics_fun env ft = ft_redundant_generics env ft.ft_tparams (mk (Reason.Rnone, Tfun ft)) let check_redundant_generics_class env class_name class_type = Cls.methods class_type |> ListLabels.filter ~f:(fun (_, meth) -> String.equal meth.ce_origin class_name) |> List.iter ~f:(check_redundant_generics_class_method env); Cls.smethods class_type |> List.filter ~f:(fun (_, meth) -> String.equal meth.ce_origin class_name) |> List.iter ~f:(check_redundant_generics_class_method env) let get_tracing_info env = { Decl_counters.origin = Decl_counters.TastCheck; file = Tast_env.get_file env; } let create_handler ctx = let handler = object inherit Tast_visitor.handler_base method! at_fun_def env fd = if not (Tast_env.is_hhi env) then match Decl_provider.get_fun ~tracing_info:(get_tracing_info env) ctx (snd fd.fd_name) with | Some { fe_type; _ } -> begin match get_node fe_type with | Tfun ft -> check_redundant_generics_fun env ft | _ -> () end | _ -> () method! at_class_ env c = if not (Tast_env.is_hhi env) then let cid = snd c.c_name in match Decl_provider.get_class ~tracing_info:(get_tracing_info env) ctx cid with | None -> () | Some cls -> check_redundant_generics_class env (snd c.c_name) cls end in if TypecheckerOptions.check_redundant_generics (Provider_context.get_tcopt ctx) then Some handler else None
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/redundant_generics_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val create_handler : Provider_context.t -> Tast_visitor.handler option
OCaml
hhvm/hphp/hack/src/typing/tast_check/reified_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast open Typing_defs open Typing_reified_check (* validator *) module Env = Tast_env module SN = Naming_special_names module UA = SN.UserAttributes module Cls = Decl_provider.Class module Nast = Aast let is_reified tparam = not (equal_reify_kind tparam.tp_reified Erased) let tparams_has_reified tparams = List.exists tparams ~f:is_reified let valid_newable_hint env (tp_pos, tp_name) (pos, hint) = let err_opt = let open Typing_error.Primary in match hint with | Aast.Happly ((p, h), _) -> begin match Env.get_class_or_typedef env h with | Some (Env.ClassResult cls) -> if not Ast_defs.(is_c_normal (Cls.kind cls)) then Some (Invalid_newable_type_argument { tp_pos; tp_name; pos = p }) else None | _ -> (* This case should never happen *) Some (Invalid_newable_type_argument { tp_pos; tp_name; pos = p }) end | Aast.Habstr (name, []) -> if not @@ Env.get_newable env name then Some (Invalid_newable_type_argument { tp_pos; tp_name; pos }) else None | _ -> Some (Invalid_newable_type_argument { tp_pos; tp_name; pos }) in Option.iter err_opt ~f:(fun err -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) @@ Typing_error.primary err) let verify_has_consistent_bound env (tparam : Tast.tparam) = let upper_bounds = (* a newable type parameter cannot be higher-kinded/require arguments *) Typing_set.elements (Env.get_upper_bounds env (snd tparam.tp_name) []) in let bound_classes = List.filter_map upper_bounds ~f:(fun ty -> match get_node ty with | Tclass ((_, class_id), _, _) -> Env.get_class env class_id | _ -> None) in let valid_classes = List.filter bound_classes ~f:Cls.valid_newable_class in if Int.( <> ) 1 (List.length valid_classes) then let constraints = List.map ~f:Cls.name valid_classes in let (pos, tp_name) = tparam.tp_name in Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Invalid_newable_typaram_constraints { pos; tp_name; constraints }) (* When passing targs to a reified position, they must either be concrete types * or reified type parameters. This prevents the case of * * class C<reify Tc> {} * function f<Tf>(): C<Tf> {} * * where Tf does not exist at runtime. *) let verify_targ_valid env reification tparam targ = (* There is some subtlety here. If a type *parameter* is declared reified, * even if it is soft, we require that the argument be concrete or reified, not soft * reified or erased *) (if is_reified tparam then match tparam.tp_reified with | Nast.Reified | Nast.SoftReified -> let (decl_pos, param_name) = tparam.tp_name in let emit_error pos arg_info = Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Invalid_reified_arg { pos; param_name; decl_pos; arg_info }) in validator#validate_hint (Tast_env.tast_env_as_typing_env env) (snd targ) ~reification emit_error | Nast.Erased -> ()); if Attributes.mem UA.uaEnforceable tparam.tp_user_attributes then Typing_enforceable_hint.validate_hint (Tast_env.tast_env_as_typing_env env) (snd targ) (fun pos ty_info -> let (tp_pos, tp_name) = tparam.tp_name in Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Invalid_enforceable_type { kind = `param; pos; ty_info; tp_pos; tp_name })); if Attributes.mem UA.uaNewable tparam.tp_user_attributes then valid_newable_hint env tparam.tp_name (snd targ) let verify_call_targs env expr_pos decl_pos tparams targs = (if tparams_has_reified tparams then let tparams_length = List.length tparams in let targs_length = List.length targs in if Int.( <> ) tparams_length targs_length then if Int.( = ) targs_length 0 then Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Require_args_reify { decl_pos; pos = expr_pos }) else (* mismatches with targs_length > 0 are not specific to reification and handled elsewhere *) ()); let all_wildcards = List.for_all ~f:(fun (_, h) -> Aast_defs.is_wildcard_hint h) targs in if all_wildcards && tparams_has_reified tparams then Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Require_args_reify { decl_pos; pos = expr_pos }) else (* Unequal_lengths case handled elsewhere *) List.iter2 tparams targs ~f:(verify_targ_valid env Type_validator.Resolved) |> ignore let rec get_ft_tparams fun_ty = match get_node fun_ty with | Tnewtype (name, _, ty1) when String.equal name SN.Classes.cSupportDyn -> get_ft_tparams ty1 | Tfun ({ ft_tparams; _ } as fun_ty) -> Some (ft_tparams, fun_ty) | _ -> None let handler = object inherit Tast_visitor.handler_base method! at_expr env x = (* only considering functions where one or more params are reified *) match x with | (_, call_pos, Class_get ((_, _, CI (_, t)), _, _)) -> if equal_reify_kind (Env.get_reified env t) Reified then Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.(primary @@ Primary.Class_get_reified call_pos) | (fun_ty, pos, Method_caller _) -> (match get_ft_tparams fun_ty with | Some (ft_tparams, _) -> if tparams_has_reified ft_tparams then Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.(primary @@ Primary.Reified_function_reference pos) | None -> ()) | ( _, pos, FunctionPointer (FP_class_const ((ty, _, CI (_, class_id)), _), _) ) when Env.is_in_expr_tree env -> let (_env, ty) = Env.expand_type env ty in begin match get_node ty with (* If we get Tgeneric here, the underlying type was reified *) | Tgeneric (ci, _) when String.equal ci class_id -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( expr_tree @@ Primary.Expr_tree.Reified_static_method_in_expr_tree pos) | _ -> () end | (fun_ty, pos, FunctionPointer (_, targs)) -> begin match get_ft_tparams fun_ty with | Some (ft_tparams, _) -> verify_call_targs env pos (get_pos fun_ty) ft_tparams targs | None -> () end | (_, pos, Call { func = (fun_ty, _, _); targs; _ }) -> let (env, efun_ty) = Env.expand_type env fun_ty in (match get_ft_tparams efun_ty with | Some (ft_tparams, ty) when not @@ get_ft_is_function_pointer ty -> verify_call_targs env pos (get_pos efun_ty) ft_tparams targs | _ -> ()) | (_, pos, New ((ty, _, CI (_, class_id)), targs, _, _, _)) -> let (env, ty) = Env.expand_type env ty in (match get_node ty with | Tgeneric (ci, _tyargs) when String.equal ci class_id -> (* ignoring type arguments here: If we get a Tgeneric here, the underlying type parameter must have been newable and reified, neither of which his allowed for higher-kinded type-parameters *) if not (Env.get_newable env ci) then Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.New_without_newable { pos; name = ci }) (* No need to report a separate error here if targs is non-empty: If targs is not empty then there are two cases: - ci is indeed higher-kinded, in which case it is not allowed to be newable (yielding an error above) - ci is not higher-kinded. Typing_phase.localize_targs_* is called on the the type arguments, reporting the arity mismatch *) | _ -> (match Env.get_class env class_id with | Some cls -> let tparams = Cls.tparams cls in let class_pos = Cls.pos cls in verify_call_targs env pos class_pos tparams targs | None -> ())) | ( _, pos, New ((_, _, ((CIstatic | CIself | CIparent) as cid)), _, _, _, _) ) -> Option.( let t = Env.get_self_id env >>= Env.get_class env >>| Cls.tparams >>| tparams_has_reified in Option.iter t ~f:(fun has_reified -> if has_reified then let (class_kind, suggested_class_name) = match cid with | CIstatic -> ("static", None) | CIself -> ("self", Env.get_self_id env) | CIparent -> ("parent", Env.get_parent_id env) | _ -> failwith "Unexpected match" in Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.New_class_reified { pos; class_kind; suggested_class_name }))) | (_, pos, New ((ty, _, _), targs, _, _, _)) -> let (env, ty) = Env.expand_type env ty in begin match get_node ty with | Tclass ((_, cid), _, _) -> begin match Env.get_class env cid with | Some cls -> let tparams = Cls.tparams cls in let class_pos = Cls.pos cls in verify_call_targs env pos class_pos tparams targs | _ -> () end | _ -> () end | _ -> () method! at_hint env = function | (_pos, Aast.Happly ((_, class_id), hints)) -> let tc = Env.get_class_or_typedef env class_id in begin match tc with | Some (Env.ClassResult tc) -> let tparams = Cls.tparams tc in ignore (List.iter2 tparams hints ~f:(fun tp hint -> verify_targ_valid env Type_validator.Unresolved tp ((), hint))) | _ -> () end | _ -> () method! at_tparam env tparam = (* Can't use Attributes.mem here because of a conflict between Nast.user_attributes and Tast.user_attributes *) if List.exists tparam.tp_user_attributes ~f:(fun { ua_name; _ } -> String.equal UA.uaNewable (snd ua_name)) then verify_has_consistent_bound env tparam method! at_class_ env { c_name = (pos, name); _ } = match Env.get_class env name with | Some cls -> begin match Cls.construct cls with | (_, Typing_defs.ConsistentConstruct) -> if List.exists ~f:(fun t -> not (equal_reify_kind t.tp_reified Erased)) (Cls.tparams cls) then Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.(primary @@ Primary.Consistent_construct_reified pos) | _ -> () end | None -> () end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/reified_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/rvalue_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast open Typing_defs module Env = Tast_env module Reason = Typing_reason let check_valid_rvalue pos env ty = let rec iter_over_types env tyl = match tyl with | [] -> env | ty :: tyl -> let (env, ety) = Env.expand_type env ty in (match deref ety with | (r, Tprim Tnoreturn) -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( wellformedness @@ Primary.Wellformedness.Noreturn_usage { pos; reason = lazy (Reason.to_string "A `noreturn` function always throws or exits." r); }); env | (r, Tprim Tvoid) -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( wellformedness @@ Primary.Wellformedness.Void_usage { pos; reason = lazy (Reason.to_string "A `void` function doesn't return a value." r); }); env | (_, Tunion tyl2) -> iter_over_types env (tyl2 @ tyl) | (_, _) -> iter_over_types env tyl) in ignore (iter_over_types env [ty]) let visitor = object (this) inherit [_] Aast.iter as super val non_returning_allowed = ref true method allow_non_returning f = let is_non_returning_allowed = !non_returning_allowed in non_returning_allowed := true; f (); non_returning_allowed := is_non_returning_allowed method disallow_non_returning f = let is_non_returning_allowed = !non_returning_allowed in non_returning_allowed := false; f (); non_returning_allowed := is_non_returning_allowed method! on_expr env ((ty, p, e) as te) = match e with | Binop { bop = Ast_defs.Eq None; lhs; rhs } -> this#allow_non_returning (fun () -> this#on_expr env lhs); this#disallow_non_returning (fun () -> this#on_expr env rhs) | Eif (e1, e2, e3) -> this#disallow_non_returning (fun () -> this#on_expr env e1); Option.iter e2 ~f:(this#on_expr env); this#on_expr env e3 | Pipe (_, e1, e2) -> this#disallow_non_returning (fun () -> this#on_expr env e1); this#on_expr env e2 | List el -> List.iter el ~f:(this#on_expr env) | ReadonlyExpr r -> (* ReadonlyExprs can be immediately surrounding a void thing, but the thing inside the expression should be checked for void *) this#disallow_non_returning (fun () -> super#on_expr env r) | ExpressionTree { et_hint; et_splices; et_function_pointers; et_virtualized_expr; et_runtime_expr; et_dollardollar_pos = _; } -> this#on_hint env et_hint; this#on_block env et_splices; this#on_block env et_function_pointers; (* Allow calls to void functions at the top level: Code`void_func()` but not in subexpressions: Code`() ==> { $x = void_func(); }` *) super#on_expr env et_virtualized_expr; this#on_expr env et_runtime_expr | _ -> if not !non_returning_allowed then check_valid_rvalue p env ty; this#disallow_non_returning (fun () -> super#on_expr env te) method! on_stmt env stmt = match snd stmt with | Expr e -> this#allow_non_returning (fun () -> this#on_expr env e) | Return (Some (_, _, Hole (e, _, _, _))) | Return (Some e) -> this#allow_non_returning (fun () -> this#on_expr env e) | For (e1, e2, e3, b) -> this#allow_non_returning (fun () -> List.iter ~f:(this#on_expr env) e1); this#disallow_non_returning (fun () -> Option.iter ~f:(this#on_expr env) e2); this#allow_non_returning (fun () -> List.iter ~f:(this#on_expr env) e3); this#on_block env b | Foreach (e1, e2, b) -> this#disallow_non_returning (fun () -> this#on_expr env e1); this#allow_non_returning (fun () -> this#on_as_expr env e2); this#on_block env b | Awaitall _ -> this#allow_non_returning (fun () -> super#on_stmt env stmt) | _ -> this#disallow_non_returning (fun () -> super#on_stmt env stmt) method! on_block env block = this#allow_non_returning (fun () -> super#on_block env block) end let handler = object inherit Tast_visitor.handler_base method! at_stmt = visitor#on_stmt end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/rvalue_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/sdt_analysis_logger.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) let create_handler ctx = let worker_id = !Typing_deps.worker_id |> Option.value ~default:0 in let db_dir = Sdt_analysis.default_db_dir in Sdt_analysis.create_handler ~db_dir ~worker_id ctx
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/sdt_analysis_logger.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. * *) (** collects __SupportDynamicType information *) val create_handler : Provider_context.t -> Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/shape_analysis_logger.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 Shape_analysis_types module A = Aast module SA = Shape_analysis module SAC = Shape_analysis_codemod let constraints_dir = "/tmp/shape_analysis_constraints" let constraints_dir_created = ref false type logger_mode = | LogLocally | LogScuba | LogCodemod of { atomic: bool; (** 'atomic' is described in D40008464. TODO(T138659101) remove option. *) } | LogConstraints of { mode: mode } let mode_of_logger_mode = function | LogConstraints { mode } -> mode | LogCodemod { atomic = _ } -> Local | LogLocally | LogScuba -> Local let parse_logger_mode_exn typing_env = let level_int = Typing_env.get_tcopt typing_env |> TypecheckerOptions.log_levels |> SMap.find_opt "shape_analysis" in match Option.value_exn level_int with | 1 -> LogLocally | 2 -> LogScuba | 3 -> LogCodemod { atomic = false } | 4 -> LogCodemod { atomic = true } | 5 -> LogConstraints { mode = Local } | 6 -> LogConstraints { mode = Global } | n -> failwith @@ Printf.sprintf "Unrecognized logger mode %d" n let channel_opt = ref None let get_channel () = match !channel_opt with | None -> let worker_id = Option.value ~default:0 !Typing_deps.worker_id in let filename = Format.asprintf "/tmp/shape-like-dict-codemod-%d.json" worker_id in let channel = Caml.Out_channel.(open_gen [Open_wronly; Open_creat] 0o644 filename) in channel_opt := Some channel; channel | Some channel -> channel let log_events_locally typing_env : log list -> unit = let log_result id error_count result : unit = Format.sprintf "[RESULT] %s: (# of errors: %d) %s\n" id error_count (SA.show_shape_result typing_env result) |> Out_channel.output_string !Typing_log.out_channel; Out_channel.flush !Typing_log.out_channel in let log_results id result : unit = List.iter ~f:(log_result id result.error_count) result.results in let log_error id error_message = Format.sprintf "[FAILURE] %s: %s\n" id (Error.show error_message) |> Out_channel.output_string !Typing_log.out_channel; Out_channel.flush !Typing_log.out_channel in List.iter ~f:(fun result -> Either.iter ~first:(log_results result.location) ~second:(log_error result.location) result.result) let log_events_as_codemod typing_env : log list -> unit = let log_success { results; error_count } = let channel = get_channel () in let len = Out_channel.length channel in let result_json = SAC.group_of_results typing_env results ~error_count in let result_str = if Int64.(len = of_int 0) then Format.asprintf "[\n%a\n]" Hh_json.pp_json result_json else begin Out_channel.seek channel Int64.(len - of_int 2); Format.asprintf ",\n%a\n]" Hh_json.pp_json result_json end in Out_channel.output_string channel result_str; Out_channel.flush channel in List.iter ~f:(fun result -> Either.iter ~first:log_success ~second:Fn.ignore result.result) let log_events tast_env = let typing_env = Tast_env.tast_env_as_typing_env tast_env in match parse_logger_mode_exn typing_env with | LogLocally -> log_events_locally typing_env | LogScuba -> Shape_analysis_scuba.log_events_remotely typing_env | LogCodemod _ -> log_events_as_codemod typing_env | LogConstraints _ -> ignore let compute_results source_file tast_env id params return body = let strip_decorations { constraint_; _ } = constraint_ in let typing_env = Tast_env.tast_env_as_typing_env tast_env in let logger_mode = parse_logger_mode_exn typing_env in let mode = mode_of_logger_mode logger_mode in try let (decorated_constraints, errors) = SA.callable mode id tast_env params ~return body in match logger_mode with | LogConstraints { mode = _ } -> let () = if not !constraints_dir_created then begin Sys_utils.mkdir_p constraints_dir; constraints_dir_created := true end; let constraints = SA.any_constraints_of_decorated_constraints decorated_constraints in let worker = Option.value ~default:0 !Typing_deps.worker_id in Shape_analysis_files.write_constraints ~constraints_dir ~worker ConstraintEntry. { source_file; id; constraints; error_count = List.length errors } in [] | LogLocally | LogScuba | LogCodemod _ -> let error_count = List.length errors in let successes = fst decorated_constraints |> DecoratedConstraintSet.elements |> List.map ~f:strip_decorations |> SA.simplify typing_env |> List.filter ~f:SA.is_shape_like_dict in let successes = match logger_mode with | LogCodemod { atomic = true } -> if List.is_empty successes then [] else [ { location = id; result = Either.First { results = successes; error_count }; }; ] | _ -> List.map ~f:(fun success -> { location = id; result = Either.First { results = [success]; error_count }; }) successes in let failures = List.map ~f:(fun err -> { location = id; result = Either.Second err }) errors in successes @ failures with | SA.Shape_analysis_exn error_message -> (* Logging failures is expensive because there are so many of them right now, to see all the shape results in a timely manner, simply don't log failure events. *) [{ location = id; result = Either.Second error_message }] let should_not_skip tast_env = let typing_env = Tast_env.tast_env_as_typing_env tast_env in not @@ Typing_env.is_hhi typing_env let create_handler _ctx = object inherit Tast_visitor.handler_base method! at_class_ tast_env A.{ c_methods; c_name = (_, class_name); _ } = let collect_method_events A.{ m_body; m_name = (_, method_name); m_params; m_ret; _ } = let id = class_name ^ "::" ^ method_name in let source_file = Tast_env.get_file tast_env in compute_results source_file tast_env id m_params m_ret m_body in if should_not_skip tast_env then List.concat_map ~f:collect_method_events c_methods |> log_events tast_env method! at_fun_def tast_env fd = let (_, id) = fd.A.fd_name in let A.{ f_body; f_params; f_ret; _ } = fd.A.fd_fun in let source_file = Tast_env.get_file tast_env in if should_not_skip tast_env then compute_results source_file tast_env id f_params f_ret f_body |> log_events tast_env end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/shape_analysis_logger.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val create_handler : Provider_context.t -> Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/shape_field_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast open Typing_defs module SN = Naming_special_names (* Returns the status `DoesExists, `DoesNotExist or `Unknown along with * a boolean to track if the shape was optional or not. *) let shapes_key_exists env shape field_name = let check pos shape_kind fields = match TShapeMap.find_opt field_name fields with | None -> if is_nothing shape_kind then `DoesNotExist (pos, `Undefined) else `Unknown | Some { sft_optional; sft_ty } -> if not sft_optional then `DoesExist (get_pos sft_ty) else let nothing = Typing_make_type.nothing Reason.Rnone in if Tast_env.is_sub_type env sft_ty nothing then `DoesNotExist ( get_pos shape, `Nothing (lazy (Reason.to_string "It is nothing" (get_reason sft_ty))) ) else `Unknown in let tenv = Tast_env.tast_env_as_typing_env env in let shape = Typing_utils.strip_dynamic tenv shape in let (_, _, shape) = Typing_utils.strip_supportdyn tenv shape in let (_, shape) = Tast_env.expand_type env shape in match get_node shape with | Tshape { s_origin = _; s_unknown_value = shape_kind; s_fields = fields } -> (check (get_pos shape) shape_kind fields, false) | Toption maybe_shape -> let (_, shape) = Tast_env.expand_type env maybe_shape in (match get_node shape with | Tshape { s_origin = _; s_unknown_value = shape_kind; s_fields = fields } -> (check (get_pos shape) shape_kind fields, true) | _ -> (`Unknown, true)) | _ -> (`Unknown, false) let trivial_shapes_key_exists_check pos1 env (shape, _, _) field_name = let (status, optional) = shapes_key_exists env shape (TSFlit_str field_name) in (* Shapes::keyExists only supports non optional shapes, so an error * would already have been raised. *) if not optional then match status with | `DoesExist decl_pos -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( shape @@ Primary.Shape.Shapes_key_exists_always_true { pos = pos1; field_name = snd field_name; decl_pos }) | `DoesNotExist (decl_pos, reason) -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( shape @@ Primary.Shape.Shapes_key_exists_always_false { pos = pos1; field_name = snd field_name; decl_pos; reason }) | `Unknown -> () let shapes_method_access_with_non_existent_field pos1 env method_name (shape, _, _) field_name = let (status, optional_shape) = shapes_key_exists env shape (TSFlit_str field_name) in match (status, optional_shape) with | (`DoesExist _, false) -> Lint.shape_idx_access_required_field pos1 (snd field_name) | (`DoesNotExist (decl_pos, reason), _) -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( shape @@ Primary.Shape.Shapes_method_access_with_non_existent_field { pos = pos1; field_name = snd field_name; decl_pos; method_name; reason; }) | (`DoesExist _, true) | (`Unknown, _) -> () let shape_access_with_non_existent_field pos1 env (shape, _, _) field_name = let (status, optional) = shapes_key_exists env shape (TSFlit_str field_name) in match (status, optional) with | (`DoesNotExist (decl_pos, reason), _) -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( shape @@ Primary.Shape.Shapes_access_with_non_existent_field { pos = pos1; field_name = snd field_name; decl_pos; reason }) | (`DoesExist _, _) | (`Unknown, _) -> () let handler = object inherit Tast_visitor.handler_base method! at_expr env = function | ( _, p, Call { func = ( _, _, Class_const ((_, _, CI (_, class_name)), (_, method_name)) ); args = [(_, shape); (_, (_, pos, String field_name))]; unpacked_arg = None; _; } ) when String.equal class_name SN.Shapes.cShapes && String.equal method_name SN.Shapes.keyExists -> trivial_shapes_key_exists_check p env shape (Pos_or_decl.of_raw_pos pos, field_name) | ( _, _, Call { func = ( _, _, Class_const ((_, _, CI (_, class_name)), (_, method_name)) ); args = [(_, shape); (_, (_, pos, String field_name)); _]; unpacked_arg = None; _; } ) | ( _, _, Call { func = ( _, _, Class_const ((_, _, CI (_, class_name)), (_, method_name)) ); args = [(_, shape); (_, (_, pos, String field_name))]; unpacked_arg = None; _; } ) when String.equal class_name SN.Shapes.cShapes && (String.equal method_name SN.Shapes.idx || String.equal method_name SN.Shapes.at) -> shapes_method_access_with_non_existent_field pos env method_name shape (Pos_or_decl.of_raw_pos pos, field_name) | ( _, p, Binop { bop = Ast_defs.QuestionQuestion; lhs = (_, _, Array_get (shape, Some (_, pos, String field_name))); _; } ) -> shape_access_with_non_existent_field p env shape (Pos_or_decl.of_raw_pos pos, field_name) | _ -> () end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/shape_field_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/static_memoized_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast module SN = Naming_special_names let attribute_exists x1 attrs = List.exists attrs ~f:(fun { ua_name; _ } -> String.equal x1 (snd ua_name)) let static_memoized_check m = if attribute_exists SN.UserAttributes.uaMemoize m.m_user_attributes then Errors.add_error Nast_check_error.( to_user_error @@ Static_memoized_function (fst m.m_name)) let unnecessary_memoize_lsb c m = let attr = SN.UserAttributes.uaMemoizeLSB in match Naming_attributes.mem_pos attr m.m_user_attributes with | None -> () | Some pos -> let (class_pos, class_name) = c.c_name in let suggestion = Some (sprintf "Try using the attribute `%s` instead" SN.UserAttributes.uaMemoize) in Errors.add_error Naming_error.( to_user_error @@ Unnecessary_attribute { pos; attr; class_pos; class_name; suggestion }) let handler = object inherit Tast_visitor.handler_base method! at_class_ env c = let disallow_static_memoized = TypecheckerOptions.experimental_feature_enabled (Tast_env.get_tcopt env) TypecheckerOptions.experimental_disallow_static_memoized in let (constructor, static_methods, _) = split_methods c.c_methods in if disallow_static_memoized && not c.c_final then ( List.iter static_methods ~f:static_memoized_check; Option.iter constructor ~f:static_memoized_check ); if c.c_final then List.iter static_methods ~f:(unnecessary_memoize_lsb c) end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/static_memoized_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/static_method_generics_check.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast let static_method_check env reified_params m = let visitor = object (this) inherit [_] Aast.iter as super method! on_hint env (pos, h) = match h with | Aast.Habstr (t, args) -> if SSet.mem t reified_params then Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Static_meth_with_class_reified_generic { pos = m.m_span; generic_pos = pos }); List.iter args ~f:(this#on_hint env) | _ -> super#on_hint env (pos, h) end in List.iter m.m_params ~f:(visitor#on_fun_param env); visitor#on_type_hint env m.m_ret let handler = object inherit Tast_visitor.handler_base method! at_class_ env c = let (_, static_methods, _) = split_methods c.c_methods in if not (Pos.filename c.c_span |> Relative_path.prefix |> Relative_path.is_hhi) then let reified_params = List.filter_map c.c_tparams ~f:(function tp -> if not (equal_reify_kind tp.tp_reified Erased) then Some (snd tp.tp_name) else None) |> SSet.of_list in List.iter static_methods ~f:(static_method_check env reified_params) end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/static_method_generics_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/string_cast_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast open Typing_defs module Env = Tast_env module SN = Naming_special_names (** Produce an error on (string) casts of objects. Currently it is allowed in HHVM to cast an object if it is Stringish (i.e., has a __toString() method), but all (string) casts of objects will be banned in the future. Eventually, __toString/(string) casts of objects will be removed from HHVM entirely. *) let check__toString m = let (pos, name) = m.m_name in if String.equal name SN.Members.__toString then ( if (not (Aast.equal_visibility m.m_visibility Public)) || m.m_static then Errors.add_error Nast_check_error.(to_user_error @@ ToString_visibility pos); match hint_of_type_hint m.m_ret with | Some (_, Hprim Tstring) | Some (_, Hlike (_, Hprim Tstring)) -> () | Some (p, _) -> Errors.add_error Nast_check_error.(to_user_error @@ ToString_returns_string p) | None -> () ) let rec is_stringish env ty = let (env, ety) = Env.expand_type env ty in match get_node ety with | Toption ty' -> is_stringish env ty' | Tunion tyl -> List.for_all ~f:(is_stringish env) tyl | Tintersection tyl -> List.exists ~f:(is_stringish env) tyl | Tgeneric _ | Tnewtype _ | Tdependent _ -> let (env, tyl) = Env.get_concrete_supertypes ~abstract_enum:true env ty in List.for_all ~f:(is_stringish env) tyl | Tclass (x, _, _) -> Option.is_none (Env.get_class env (snd x)) (* TODO akenn: error tyvar? *) | Tany _ | Tdynamic | Tnonnull | Tprim _ | Tneg _ -> true | Tvec_or_dict _ | Tvar _ | Ttuple _ | Tfun _ | Tshape _ | Taccess _ -> false | Tunapplied_alias _ -> Typing_defs.error_Tunapplied_alias_in_illegal_context () let handler = object inherit Tast_visitor.handler_base method! at_expr env (_, p, expr) = match expr with | Cast ((_, Hprim Tstring), te) -> let (ty, _, _) = te in if not (is_stringish env ty) then Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.String_cast { pos = p; ty_name = lazy (Env.print_ty env ty) }) | _ -> () method! at_method_ _ m = check__toString m end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/string_cast_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/switch_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast open Typing_defs open Utils module Env = Tast_env module Cls = Decl_provider.Class module SN = Naming_special_names module MakeType = Typing_make_type module Reason = Typing_reason type kind = | Enum | EnumClass | EnumClassLabel let is_arraykey env ty = Env.is_sub_type env ty (MakeType.arraykey Reason.Rnone) let is_dynamic env ty = Env.is_sub_type env ty (MakeType.dynamic Reason.Rnone) let is_enum env ty = let (env, ty) = Env.expand_type env ty in match Typing_defs.get_node ty with | Tnewtype (name, _, _) -> Env.is_enum env name | _ -> false let is_like_enum env ty = let (env, ty) = Env.expand_type env ty in match Typing_defs.get_node ty with | Typing_defs.Tunion [ty; dynamic_ty] when is_dynamic env dynamic_ty -> is_enum env ty | Typing_defs.Tunion [dynamic_ty; ty] when is_dynamic env dynamic_ty -> is_enum env ty | _ -> false let get_constant env tc kind (seen, has_default) case = let (kind, is_enum_class_label) = match kind with | Enum -> ("enum ", false) | EnumClass -> ("enum class ", false) | EnumClassLabel -> ("enum class ", true) in let check_case pos cls const = (* wish:T109260699 *) if String.( <> ) cls (Cls.name tc) then ( Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( enum @@ Primary.Enum.Enum_switch_wrong_class { pos; kind; expected = strip_ns (Cls.name tc); actual = strip_ns cls; }); (seen, has_default) ) else match SMap.find_opt const seen with | None -> (SMap.add const pos seen, has_default) | Some old_pos -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( enum @@ Primary.Enum.Enum_switch_redundant { const_name = const; first_pos = old_pos; pos }); (seen, has_default) in match case with | Default _ -> (seen, true) | Case ((_, pos, Class_const ((_, _, CI (_, cls)), (_, const))), _) when not is_enum_class_label -> check_case pos cls const | Case ((_, pos, EnumClassLabel (Some (_, cls), const)), _) -> check_case pos cls const | Case ((_, pos, _), _) -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.(enum @@ Primary.Enum.Enum_switch_not_const pos); (seen, has_default) let check_enum_exhaustiveness env pos tc kind (caselist, dfl) coming_from_unresolved = let str_kind = match kind with | Enum -> "Enum" | EnumClass | EnumClassLabel -> "Enum class" in (* If this check comes from an enum inside a Tunion, then don't punish for having an extra default case *) let (seen, has_default) = let state = (SMap.empty, false) in let state = List.fold_left ~f:(fun state c -> get_constant env tc kind state (Aast.Case c)) ~init:state caselist in let state = Option.fold ~f:(fun state c -> get_constant env tc kind state (Aast.Default c)) ~init:state dfl in state in let rec first_n_unhandled n acc = function | _ when n < 1 -> List.rev acc | [] -> List.rev acc | (id, _) :: rest -> if String.equal id SN.Members.mClass || SMap.mem id seen then first_n_unhandled n acc rest else first_n_unhandled (n - 1) (id :: acc) rest in let unhandled = first_n_unhandled 10 [] @@ Cls.consts tc in let all_cases_handled = List.is_empty unhandled in let enum_err_opt = let open Typing_error in match (all_cases_handled, has_default, coming_from_unresolved) with | (false, false, _) -> Some (Primary.Enum.Enum_switch_nonexhaustive { pos; kind = str_kind; missing = unhandled; decl_pos = Cls.pos tc }) | (true, true, false) -> Some (Primary.Enum.Enum_switch_redundant_default { pos; kind = str_kind; decl_pos = Cls.pos tc }) | _ -> None in Option.iter enum_err_opt ~f:(fun err -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) @@ Typing_error.enum err) (* Small reminder: * - enums are localized to `Tnewtype (name, _, _)` where name is the name of * the enum. This can be checked using `Env.is_enum` * - enum classes are not inhabited by design. The type of elements is * HH\MemberOf<name, _> were name is the name of the enum class. This * is localized as Tnewtype("HH\MemberOf", [enum; interface]) where * enum is localized as Tclass(name, _, _) where Env.is_enum_class name is * true. *) (* Wrapper to share the logic that detects if a type is an enum or an enum * class, or something else. *) let apply_if_enum_or_enum_class env ~(default : 'a) ~(f : kind -> Env.env -> string -> 'a) name args = let check_ec kind = function | [enum; _interface] -> begin match get_node enum with | Tclass ((_, cid), _, _) when Env.is_enum_class env cid -> f kind env cid | _ -> default end | _ -> default in if Env.is_enum env name then f Enum env name else if String.equal name SN.Classes.cMemberOf then check_ec EnumClass args else if String.equal name SN.Classes.cEnumClassLabel then check_ec EnumClassLabel args else default let rec check_exhaustiveness_ env pos ty caselist enum_coming_from_unresolved ~outcomes = (* Right now we only do exhaustiveness checking for enums. *) (* This function has a built in hack where if Tunion has an enum inside then it tells the enum exhaustiveness checker to not punish for extra default *) let (env, ty) = Env.expand_type env ty in let check kind env id ~outcomes = let dep = Typing_deps.Dep.AllMembers id in let decl_env = Env.get_decl_env env in Option.iter decl_env.Decl_env.droot ~f:(fun root -> Typing_deps.add_idep (Env.get_deps_mode env) root dep); if TypecheckerOptions.record_fine_grained_dependencies @@ Env.get_tcopt env then Typing_pessimisation_deps.try_add_fine_dep (Env.get_deps_mode env) decl_env.Decl_env.droot decl_env.Decl_env.droot_member dep; let tc = unsafe_opt @@ Env.get_enum env id in check_enum_exhaustiveness env pos tc kind caselist enum_coming_from_unresolved; (`Enum_checked :: outcomes, env) in match get_node ty with | Tunion tyl -> let new_enum = enum_coming_from_unresolved || List.length tyl > 1 && List.exists tyl ~f:(fun cur_ty -> let (_, cur_ty) = Env.expand_type env cur_ty in match get_node cur_ty with | Tnewtype (name, args, _) -> apply_if_enum_or_enum_class env ~default:false ~f:(fun _ _ _ -> true) name args | _ -> false) in List.fold_left tyl ~init:(outcomes, env) ~f:(fun (outcomes, env) ty -> check_exhaustiveness_ env pos ty caselist new_enum ~outcomes) | Tintersection [arraykey; like_ty] when is_arraykey env arraykey && is_like_enum env like_ty -> check_exhaustiveness_ env pos like_ty caselist enum_coming_from_unresolved ~outcomes | Tintersection tyl -> fst @@ Typing_utils.run_on_intersection (outcomes, env) tyl ~f:(fun (outcomes, env) ty -> ( check_exhaustiveness_ env pos ty caselist enum_coming_from_unresolved ~outcomes, () )) | Tnewtype (name, args, _) -> apply_if_enum_or_enum_class env ~default:(outcomes, env) ~f:(check ~outcomes) name args | Tany _ | Tnonnull | Tvec_or_dict _ | Tclass _ | Toption _ | Tprim _ | Tvar _ | Tfun _ | Tgeneric _ | Tdependent _ | Ttuple _ | Tshape _ | Taccess _ | Tneg _ | Tdynamic -> if Option.is_none (snd caselist) then (`Silently_ends ty :: outcomes, env) else (`Dyn_with_default :: outcomes, env) | Tunapplied_alias _ -> Typing_defs.error_Tunapplied_alias_in_illegal_context () type outcomes = { silently_ends: Tast.ty list; dyn_with_default: int; enum_checked: int; } let count_outcomes = let f ({ silently_ends; dyn_with_default; enum_checked } as outcomes : outcomes) = function | `Silently_ends ty -> { outcomes with silently_ends = ty :: silently_ends } | `Dyn_with_default -> { outcomes with dyn_with_default = dyn_with_default + 1 } | `Enum_checked -> { outcomes with enum_checked = enum_checked + 1 } in List.fold_left ~f ~init:{ silently_ends = []; dyn_with_default = 0; enum_checked = 0 } let rec get_kind_and_args json = let open Option.Let_syntax in let* kind = Hh_json.get_field_opt (Hh_json.Access.get_string "kind") json in match kind with | "primitive" -> let* name = Hh_json.get_field_opt (Hh_json.Access.get_string "name") json in Some ("prim_" ^ name) | "nullable" -> let* args = Hh_json.get_field_opt (Hh_json.Access.get_array "args") json in let* hd = List.hd args in let* recurse = get_kind_and_args hd in Some ("nullable_" ^ recurse) | _ -> Some kind let to_json_array env silently_ends = silently_ends |> List.filter_map ~f:(fun ty -> ty |> Env.ty_to_json env ~show_like_ty:true |> get_kind_and_args) |> List.dedup_and_sort ~compare:String.compare |> Hh_json.array_ Hh_json.string_ let outcomes_to_fields env ({ silently_ends; dyn_with_default; enum_checked } : outcomes) = let silently_ends = ("silently_ends", to_json_array env silently_ends) in let dyn_with_default = ("dyn_with_default", Hh_json.int_ dyn_with_default) in let enum_checked = ("enum_checked", Hh_json.int_ enum_checked) in [silently_ends; dyn_with_default; enum_checked] let log_exhaustivity_check env pos default_label outcomes ty_json = let add_fields json ~fields = match json with | Hh_json.JSON_Object old -> Hh_json.JSON_Object (old @ fields) | _ -> Hh_json.JSON_Object (("warning_expected_object", json) :: fields) in let has_default = ("has_default", Option.is_some default_label |> Hh_json.bool_) in let switch_pos = ("switch_pos", Pos.(pos |> to_absolute |> json)) in let fields = has_default :: switch_pos :: (outcomes_to_fields env @@ count_outcomes outcomes) in ty_json |> add_fields ~fields |> Hh_json.json_to_string |> Hh_logger.log "[hh_tco_log_exhaustivity_check] %s" let check_exhaustiveness env pos ty ((_, dfl) as caselist) = let (outcomes, env) = check_exhaustiveness_ env pos ty caselist false ~outcomes:[] in let tcopt = env |> Env.get_decl_env |> Decl_env.tcopt in if TypecheckerOptions.tco_log_exhaustivity_check tcopt then Env.ty_to_json env ~show_like_ty:true ty |> log_exhaustivity_check env pos dfl outcomes let handler = object inherit Tast_visitor.handler_base method! at_stmt env x = match snd x with | Switch ((scrutinee_ty, scrutinee_pos, _), casel, dfl) -> check_exhaustiveness env scrutinee_pos scrutinee_ty (casel, dfl) | _ -> () end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/switch_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/tast_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) [@@@warning "-33"] open Hh_prelude [@@@warning "+33"] (* Handlers that are enabled through 'log_levels' configuration. *) let logger_handlers ctx = let tco = Provider_context.get_tcopt ctx in let log_levels = TypecheckerOptions.log_levels tco in let add_handler handlers (key, handler) = match SMap.find_opt key log_levels with | Some level when level > 0 -> handler ctx :: handlers | _ -> handlers in let key_handler_pairs = [ ("tany", Tany_logger.create_handler); ("like_type", Like_type_logger.create_handler); ("shape_analysis", Shape_analysis_logger.create_handler); ("sdt_analysis", Sdt_analysis_logger.create_handler); ] in List.fold ~init:[] ~f:add_handler key_handler_pairs let visitor ctx = (* Handlers that are not TAST checks to produce errors, but are used for telemetry that processes TASTs. *) let irregular_handlers = logger_handlers ctx in let tcopt = Provider_context.get_tcopt ctx in let hierarchy_check handler = if TypecheckerOptions.skip_hierarchy_checks tcopt then None else Some handler in let handlers = irregular_handlers @ List.filter_map ~f:Fn.id [ Xhp_required_check.create_handler ctx; Redundant_generics_check.create_handler ctx; Some Shape_field_check.handler; Some String_cast_check.handler; Some Tautology_check.handler; Some Enforceable_hint_check.handler; Some Const_write_check.handler; Some Switch_check.handler; Some Void_return_check.handler; Some Rvalue_check.handler; Some Callconv_check.handler; Some Xhp_check.handler; Some Discarded_awaitable_check.handler; Some Invalid_index_check.handler; Some Pseudofunctions_check.handler; Some Reified_check.handler; Some Instantiability_check.handler; Some Static_memoized_check.handler; Some Abstract_class_check.handler; hierarchy_check Class_parent_check.handler; Some Method_type_param_check.handler; Some Obj_get_check.handler; Some This_hint_check.handler; Some Unresolved_type_variable_check.handler; Some Type_const_check.handler; Some Static_method_generics_check.handler; hierarchy_check Class_inherited_member_case_check.handler; Some Ifc_tast_check.handler; Some Readonly_check.handler; Some Meth_caller_check.handler; Some Expression_tree_check.handler; hierarchy_check Class_const_origin_check.handler; (if TypecheckerOptions.global_access_check_enabled tcopt then Some Global_access_check.handler else None); hierarchy_check Enum_check.handler; (if TypecheckerOptions.populate_dead_unsafe_cast_heap tcopt then Some Remove_dead_unsafe_casts.patch_location_collection_handler else None); ] in let handlers = if TypecheckerOptions.skip_tast_checks (Provider_context.get_tcopt ctx) then [] else handlers in Tast_visitor.iter_with handlers let program ctx = (visitor ctx)#go ctx let def ctx = (visitor ctx)#go_def ctx
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/tast_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val program : Provider_context.t -> Tast.program -> unit val def : Provider_context.t -> Tast.def -> unit
OCaml
hhvm/hphp/hack/src/typing/tast_check/tautology_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) [@@@warning "-33"] open Hh_prelude [@@@warning "+33"] open Ast_defs open Aast open Tast let handler = object inherit Tast_visitor.handler_base method! at_expr env = function | (_, p, Binop { bop = (Eqeqeq | Diff2) as bop; lhs; rhs }) -> Tast_env.assert_nontrivial p bop env (get_type lhs) (get_type rhs) | _ -> () end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/tautology_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/this_hint_check.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. * *) let handler = object inherit Tast_visitor.handler_base method! at_hint env (pos, hint) = let report_error_if_outside_class env = match Tast_env.get_self_id env with | Some _ -> () | None -> Errors.add_error Naming_error.(to_user_error @@ This_hint_outside_class pos) in match hint with | Aast.Hthis -> report_error_if_outside_class env | _ -> () end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/this_hint_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/type_const_check.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 Aast open Typing_defs module Cls = Decl_provider.Class open Typing_const_reifiable let handler = object inherit Tast_visitor.handler_base method! at_class_typeconst_def env { c_tconst_name = (_, name); _ } = Option.( let cls_opt = Tast_env.get_self_id env >>= Tast_env.get_class env in match cls_opt with | None -> () | Some cls -> begin match Cls.get_typeconst cls name with | None -> () | Some tc -> begin match tc.ttc_kind with | TCAbstract { atc_default = Some ty; _ } | TCConcrete { tc_type = ty } -> let (tp_pos, enforceable) = Option.value_exn (Cls.get_typeconst_enforceability cls name) in if enforceable then Typing_enforceable_hint.validate_type (Tast_env.tast_env_as_typing_env env) (fst tc.ttc_name |> Pos_or_decl.unsafe_to_raw_pos) ty (fun pos ty_info -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Invalid_enforceable_type { pos; ty_info; kind = `constant; tp_pos; tp_name = name; })) | _ -> () end; if String.equal tc.ttc_origin (Cls.name cls) then Option.iter tc.ttc_reifiable ~f:(check_reifiable (Tast_env.tast_env_as_typing_env env) tc) end) end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/type_const_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/type_serialization_identity_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Typing_defs (* Replace unserialized information from the type with dummy information. For example, we don't currently serialize the arity of function types, so update the input type to set it to a default arity value. *) let rec strip_ty ty = let (reason, ty) = deref ty in let strip_tyl tyl = List.map tyl ~f:strip_ty in let strip_possibly_enforced_ty et = { et with et_type = strip_ty et.et_type } in let ty = match ty with | Tany _ | Tnonnull | Tdynamic -> ty | Tprim _ -> ty | Tvar _ -> ty | Tgeneric (name, args) -> Tgeneric (name, strip_tyl args) | Tvec_or_dict (ty1, ty2) -> Tvec_or_dict (strip_ty ty1, strip_ty ty2) | Ttuple tyl -> Ttuple (strip_tyl tyl) | Toption ty -> Toption (strip_ty ty) | Tnewtype (name, tparams, ty) -> Tnewtype (name, strip_tyl tparams, strip_ty ty) | Tdependent (dep, ty) -> Tdependent (dep, strip_ty ty) | Tunion tyl -> Tunion (strip_tyl tyl) | Tintersection tyl -> Tintersection (strip_tyl tyl) | Tclass (sid, exact, tyl) -> Tclass (sid, exact, strip_tyl tyl) | Tfun { ft_params; ft_implicit_params = { capability }; ft_ret; _ } -> let strip_param ({ fp_type; _ } as fp) = let fp_type = strip_possibly_enforced_ty fp_type in { fp_type; fp_flags = Typing_defs.make_fp_flags ~mode:(get_fp_mode fp) ~accept_disposable:false ~has_default:false ~ifc_external:false ~ifc_can_call:false ~readonly:false; (* Dummy values: these aren't currently serialized. *) fp_pos = Pos_or_decl.none; fp_name = None; } in let ft_params = List.map ft_params ~f:strip_param in let ft_implicit_params = { capability = (match capability with | CapTy cap -> CapTy (strip_ty cap) | CapDefaults p -> CapDefaults p); } in let ft_ret = strip_possibly_enforced_ty ft_ret in Tfun { ft_params; ft_implicit_params; ft_ret; (* Dummy values: these aren't currently serialized. *) ft_tparams = []; ft_where_constraints = []; ft_flags = 0; ft_ifc_decl = default_ifc_fun_decl; ft_cross_package = None; } | Tshape { s_origin = _; s_unknown_value = shape_kind; s_fields = shape_fields } -> let strip_field { sft_optional; sft_ty } = let sft_ty = strip_ty sft_ty in { sft_optional; sft_ty } in let shape_fields = TShapeMap.map strip_field shape_fields in Tshape { s_origin = Missing_origin; s_unknown_value = shape_kind; (* TODO(shapes) strip_ty s_unknown_value *) s_fields = shape_fields; } | Taccess _ -> ty | Tunapplied_alias _ -> Typing_defs.error_Tunapplied_alias_in_illegal_context () | Tneg _ -> ty in mk (reason, ty) (* * Check that type deserialization works correctly by examining every type of * every expression and serializing and deserializing it, and confirming that * it's the same type afterward. * * This is not useful work to run as a part of the typechecker, only when * checking the type serialization/deserialization logic. For this reason, this * TAST check is not enabled by default. *) let handler = object inherit Tast_visitor.handler_base method! at_expr env (ty, p, _) = try let ty = Tast_expand.expand_ty env ~pos:p ty in let serialized_ty = Tast_env.ty_to_json env ty in let deserialized_ty = Tast_env.json_to_locl_ty (Tast_env.get_ctx env) serialized_ty in match deserialized_ty with | Ok deserialized_ty -> let ty = strip_ty ty in let deserialized_ty = strip_ty deserialized_ty in if not (ty_equal ty deserialized_ty) then Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Unserializable_type { pos = p; message = Printf.sprintf "unequal types: %s vs %s (%s vs %s)" (Tast_env.print_ty env ty) (Tast_env.print_ty env deserialized_ty) (Tast_env.ty_to_json env ty |> Hh_json.json_to_string) (Tast_env.ty_to_json env deserialized_ty |> Hh_json.json_to_string); }) | Error (Not_supported _) -> () | Error (Wrong_phase message) -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Unserializable_type { pos = p; message = Printf.sprintf "type %s (%s) was not in the locl phase: %s" message (Tast_env.print_ty env ty) (Tast_env.ty_to_json env ty |> Hh_json.json_to_string); }) | Error (Deserialization_error message) -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Unserializable_type { pos = p; message = Printf.sprintf "type %s (%s) could not be deserialized to a locl type: %s" message (Tast_env.print_ty env ty) (Tast_env.ty_to_json env ty |> Hh_json.json_to_string); }) with | e -> Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Unserializable_type { pos = p; message = Printf.sprintf "exception: %s" (Exn.to_string e); }) end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/type_serialization_identity_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/unresolved_type_variable_check.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. * *) let handler = object inherit Tast_visitor.handler_base method! at_expr env (ty, p, _) = if TypecheckerOptions.disallow_unresolved_type_variables (Tast_env.get_tcopt env) then ignore (Tast_expand.expand_ty ~pos:p env ty) end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/unresolved_type_variable_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/void_return_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Aast open Hh_prelude (* This check enforces 3 properties related to return statements and functions' return types: Property 1: A function annotated with return type void must not contain a return statement with a value. Property 2: A function containing a return statement without a value (or returning implicitly) can only be annotated with a return type if that return type is void (or <Awaitable<void>, for async functions). Property 3: A function must not mix return statements with and without a value, even if such a function could be given a sufficiently general type. *) type state = { fun_def_pos: Pos.t; (** Position of the currently active function *) return_type: (Pos.t * Aast.hint_) option; (** Return type that the active function is annotated with. None if no annotation present. *) prev_no_value_return: Pos.t option option; (** Some if the active function can return without a value. If we only know that the function implicitly returns somewhere, the position is empty If we have seen an explicit return;, we store the location here *) prev_value_return: Pos.t option; (** Some if we have seen a return foo; in the active function. In that case we store the location here. *) active: bool; (** Indicates whether the state has already been used to traverse a function. *) } let initial_dummy_state = { return_type = None; prev_no_value_return = None; prev_value_return = None; fun_def_pos = Pos.none; active = false; } let validate_state fun_span fun_kind env s = (* FIXME: Move as two functions to Ast_defs? *) let (is_generator, is_async) = let open Ast_defs in match fun_kind with | FGenerator -> (true, false) | FAsyncGenerator -> (true, true) | FSync -> (false, false) | FAsync -> (false, true) in let ret_type_hint_locl_opt = Option.map s.return_type ~f:(fun ty_hint -> Tast_env.hint_to_ty env ty_hint |> Tast_env.localize_no_subst env ~ignore_errors:true |> snd) in let annotated_with_ret_any = Option.value_map ret_type_hint_locl_opt ~default:false ~f:Typing_defs.is_any in let is_bad_supertype sub sup = let sup = if TypecheckerOptions.enable_sound_dynamic (Tast_env.get_tcopt env) then Typing_defs.( map_ty sup ~f:(function | Tclass (cid, ex, [ty]) when String.equal (snd cid) Naming_special_names.Classes.cAwaitable -> let tenv = Tast_env.tast_env_as_typing_env env in Tclass (cid, ex, [Typing_utils.strip_dynamic tenv ty]) | x -> x)) else sup in (* returns false if sup is TAny, which implements the special behavior for functions annotated with variations of TAny *) Tast_env.is_sub_type env sub sup && not (Tast_env.is_sub_type env sup sub) in let check_ret_type ret_type_hint_locl = (* Fixme: Should we use more precise logic to determine the expected return type hint by factoring it into a function in Typing_return? *) let void = Typing_make_type.void Typing_reason.Rnone in let aw_void = Typing_make_type.awaitable Typing_reason.Rnone void in let is_void_super_ty = is_bad_supertype void ret_type_hint_locl in let is_awaitable_void_super_ty = is_bad_supertype aw_void ret_type_hint_locl in if is_void_super_ty || is_awaitable_void_super_ty then let hint_loc = match s.return_type with | None -> fun_span | Some (hint_loc, _) -> hint_loc in ( false, lazy (Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( wellformedness @@ Primary.Wellformedness .Non_void_annotation_on_return_void_function { is_async; hint_pos = hint_loc })) ) else (true, lazy ()) in (* Property 2 There are several exceptions: - We do not complain if the function is annotated with Tany or Awaitable<Tany> (e.g., using one of its aliases in using one of its aliases in HH_FIXME) - We only actually report an error if the return type hint of the function is a proper supertype of void (other than Tany, see first exception). Otherwise you get a normal type error already anyway. *) let (property_2_ok, raise_error_2) = match (s.prev_no_value_return, ret_type_hint_locl_opt, is_generator) with | (Some _, Some ret_type_hint_locl, false) -> check_ret_type ret_type_hint_locl | _ -> (true, lazy ()) in (* Property 3: Again, there are several exceptions: - If the function is async, it is allowed to have a (implicit or explicit) no-value return and also a "return foo;", where the type of foo is void-typed (e.g., a call to a void-returning function or an wait of an Awaitable<void>). - If the function is annotated with return type TAny (e.g., using one of its aliases in HH_FIXME), we do not complain. - return await foo. *) let (property_3_ok, raise_error_3) = (* We must accommodate the slightly inconsistent rule that "return await foo;" is allowed in an async function of type Awaitable<void> if foo's type is Awaitable<void>. The test below currently lets the following corner case slip through: An async lambda without a return type annotation can combine returning with and without a value if we can otherwise type the lambda with an sufficiently general type like Awaitable<mixed> *) match ( s.prev_no_value_return, s.prev_value_return, is_async, annotated_with_ret_any ) with | (Some without_value_pos_opt, Some with_value_pos, false, false) -> let fun_pos = s.fun_def_pos in ( false, lazy (Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( wellformedness @@ Primary.Wellformedness.Returns_with_and_without_value { pos = fun_pos; with_value_pos; without_value_pos_opt })) ) | _ -> (true, lazy ()) in (* Don't report violations of property 2 if prop 3 is also violated *) match (property_2_ok, property_3_ok) with | (_, false) -> Lazy.force raise_error_3 | (false, _) -> Lazy.force raise_error_2 | _ -> () let visitor = object (this) inherit [_] Aast.iter as super (** The state is only ever updated when entering a new function/method/lambda body Additionally, the prev_return_form part of the state may be updated by on_return_form while traversing a function body when we see a return statement. *) val state = ref initial_dummy_state method traverse_fun_body fun_span new_return_type new_fun_pos fun_kind has_implicit_return env traversal = let initial_no_value_return = if has_implicit_return then (* There is an implicit return but we don't know where *) Some None else None in if !state.active then (* We are in a function/method already. We do not descend into the nested function/method at this point. The handler (defined below) will always traverse any nested functions/methods. Thus, if we traversed the nested function/method here, the handler would *also* traverse it later and we would report the same errors multiple times *) () else let new_state = { return_type = new_return_type; prev_no_value_return = initial_no_value_return; prev_value_return = None; fun_def_pos = new_fun_pos; active = true; } in state := new_state; traversal (); validate_state fun_span fun_kind env !state method reset = state := initial_dummy_state method update_seen_return_stmts with_value return_pos = if with_value then state := { !state with prev_value_return = Some return_pos } else state := { !state with prev_no_value_return = Some (Some return_pos) } method! on_expr_ env expr_ = match expr_ with | Aast.Invalid _ -> () | _ -> super#on_expr_ env expr_ method! on_fun_ env fun_ = let decl_env = Tast_env.get_decl_env env in let has_impl_ret = Tast_env.fun_has_implicit_return env in if not (FileInfo.(equal_mode decl_env.Decl_env.mode Mhhi) || Typing_native.is_native_fun ~env:(Tast_env.tast_env_as_typing_env env) fun_) then this#traverse_fun_body fun_.f_span (hint_of_type_hint fun_.f_ret) fun_.f_span fun_.f_fun_kind has_impl_ret env (fun () -> super#on_fun_ env fun_) method! on_method_ env method_ = let has_impl_ret = Tast_env.fun_has_implicit_return env in let decl_env = Tast_env.get_decl_env env in if not (method_.m_abstract || FileInfo.(equal_mode decl_env.Decl_env.mode Mhhi) || Typing_native.is_native_meth ~env:(Tast_env.tast_env_as_typing_env env) method_) then this#traverse_fun_body method_.m_span (hint_of_type_hint method_.m_ret) (fst method_.m_name) method_.m_fun_kind has_impl_ret env (fun () -> super#on_method_ env method_) method! on_stmt env st = (* Always call super to make sure the expressions in return statements are traversed *) super#on_stmt env st; match st with | (return_pos, Return (Some _)) -> this#update_seen_return_stmts true return_pos; begin match !state.return_type with | Some (pos2, Hprim Tvoid) -> (* Property 1 *) Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( primary @@ Primary.Return_in_void { pos = return_pos; decl_pos = pos2 }) | _ -> () end | (return_pos, Return None) -> this#update_seen_return_stmts false return_pos | _ -> () method! on_expr env e = match e with | (_, _, Aast.Invalid _) -> () | _ -> super#on_expr env e end let handler = object inherit Tast_visitor.handler_base method! at_method_ env x = let env = Tast_env.restore_method_env env x in visitor#reset; visitor#on_method_ env x method! at_fun_ env x = let env = Tast_env.restore_fun_env env x in visitor#reset; visitor#on_fun_ env x end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/void_return_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/xhp_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast open Typing_defs module Env = Tast_env let check_xhp_children env pos ty = let (is_xhp_child, subty_err_opt) = Env.is_xhp_child env pos ty in let tenv = Tast_env.tast_env_as_typing_env env in Option.iter subty_err_opt ~f:(Typing_error_utils.add_typing_error ~env:tenv); if not is_xhp_child then let ty_str = lazy (Env.print_error_ty ~ignore_dynamic:true env ty) in let ty_reason_msg = Lazy.map ty_str ~f:(fun ty_str -> Reason.to_string ("This is " ^ ty_str) (get_reason ty)) in Typing_error_utils.add_typing_error ~env:tenv Typing_error.(xhp @@ Primary.Xhp.Illegal_xhp_child { pos; ty_reason_msg }) let handler = object inherit Tast_visitor.handler_base method! at_expr env = function | (_, _, Xml (_, _, tel)) -> List.iter tel ~f:(fun (ty, pos, _) -> check_xhp_children env pos ty) | _ -> () method! at_xhp_child env child = match child with | ChildName (p, name) when (not @@ Naming_special_names.XHP.is_reserved name) && (not @@ Naming_special_names.XHP.is_xhp_category name) -> begin match Env.get_class env name with | Some _ -> () | None -> Errors.add_error Naming_error.( to_user_error @@ Unbound_name { pos = p; name; kind = Name_context.ClassContext }) end | _ -> () end
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/xhp_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val handler : Tast_visitor.handler
OCaml
hhvm/hphp/hack/src/typing/tast_check/xhp_required_check.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast open Typing_defs open Utils module Cls = Decl_provider.Class module Env = Tast_env let collect_attrs_from_ty_sid ?(include_optional = false) env add bag sid = match Env.get_class env sid with | None -> bag | Some c -> let should_collect ce = match Typing_defs.get_ce_xhp_attr ce with | Some { Xhp_attribute.xa_has_default; xa_tag = None; _ } when include_optional -> xa_has_default | Some { Xhp_attribute.xa_tag = Some Xhp_attribute.Required; _ } -> true | _ -> false in let required_attrs = List.filter (Cls.props c) ~f:(compose should_collect snd) in List.fold required_attrs ~init:bag ~f:(fun s (n, elt) -> add (n, elt.ce_origin) s) let rec collect_attrs_from_ty env set ty = let (_, ty) = Env.expand_type env ty in let tenv = Tast_env.tast_env_as_typing_env env in let ty = Typing_utils.strip_dynamic tenv ty in match get_node ty with | Tunion tys -> (* Filter out dynamic, as we conservatively assume that anything dynamic * has the appropriate required attrs *) let tys = List.filter tys ~f:(fun ty -> not (Typing_utils.is_dynamic tenv ty)) in begin match tys with | [] -> set | ty :: tys -> let collect = collect_attrs_from_ty env SSet.empty in List.fold (List.map tys ~f:collect) ~init:(collect ty) ~f:SSet.inter end | Tclass ((_, sid), _, _) -> collect_attrs_from_ty_sid ~include_optional:true env (compose SSet.add fst) set sid | _ -> set let collect_attrs env attrs = let collect_attr set attr = match attr with | Xhp_simple { xs_name = (_, n); _ } -> SSet.add (":" ^ n) set | Xhp_spread (ty, _, _) -> collect_attrs_from_ty env set ty in List.fold attrs ~init:SSet.empty ~f:collect_attr let check_attrs pos env sid attrs = let collect_with_ty = collect_attrs_from_ty_sid env (fun (n, c) -> SMap.add n c) in let required_attrs = collect_with_ty SMap.empty sid in let supplied_attrs = collect_attrs env attrs in let missing_attrs = SSet.fold SMap.remove supplied_attrs required_attrs in if SMap.is_empty missing_attrs then () else SMap.iter (fun attr origin_sid -> let attr_name = Utils.strip_xhp_ns attr in let ty_reason_msg = lazy (match Env.get_class env origin_sid with | None -> [] | Some ty -> let pos = match Cls.get_prop ty attr with | Some attr_decl -> Lazy.force attr_decl.ce_pos | None -> Cls.pos ty in Reason.to_string ("The attribute `" ^ attr_name ^ "` is declared here.") (Reason.Rwitness_from_decl pos)) in Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.( xhp @@ Primary.Xhp.Missing_xhp_required_attr { pos; attr = attr_name; ty_reason_msg })) missing_attrs let create_handler ctx = let handler = object inherit Tast_visitor.handler_base method! at_expr env = function | (_, pos, Xml ((_, sid), attrs, _)) -> check_attrs pos env sid attrs | _ -> () end in if TypecheckerOptions.check_xhp_attribute (Provider_context.get_tcopt ctx) then Some handler else None
OCaml Interface
hhvm/hphp/hack/src/typing/tast_check/xhp_required_check.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val create_handler : Provider_context.t -> Tast_visitor.handler option
hhvm/hphp/hack/src/typing/tast_check/tany_logger/dune
(library (name tany_logger) (modules tany_logger tany_logger_file) (wrapped false) (libraries ast tany_logger_common core_kernel tast_env utils_core) (preprocess (pps ppx_deriving.std))) (library (name tany_logger_common) (wrapped false) (modules tany_logger_types tany_logger_common) (libraries ast core_kernel tast_env utils_core) (preprocess (pps ppx_deriving.std)))
OCaml
hhvm/hphp/hack/src/typing/tast_check/tany_logger/tany_logger.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Tany_logger_types open Tany_logger_file (* A bad type is a Tany *) let log_info env (infos : info list) : unit = List.iter ~f:(log_info_to_file env) infos let _extract_bad_type_indicator ty = let finder = object inherit [bool] Type_visitor.locl_type_visitor method! on_tany _ _ = true end in finder#on_type false ty let mk_common_info ~context_id pos = let path = Pos.filename pos |> Relative_path.suffix in let is_generated = String.is_substring ~substring:"generated" path in let is_test = String.is_substring ~substring:"test" path in { context_id; is_generated; is_test; pos } let mk_ret_decl_info_internal ~context_id env ty = let pos = Typing_defs.get_pos ty |> Pos_or_decl.fill_in_filename (Tast_env.get_file env) in let common_info = mk_common_info ~context_id pos in let position = Return in let context = Declaration { position } in { common_info; context } let mk_ret_decl_info ~context_id env ((ty, _hint) : Typing_defs.locl_ty Aast.type_hint) = let bad_type = Typing_defs.is_any ty in if bad_type then let ret_decl_info = mk_ret_decl_info_internal ~context_id env ty in Some ret_decl_info else None let mk_param_decl_info_internal ~context_id ~is_variadic pos callconv = let common_info = mk_common_info ~context_id pos in let is_inout = match callconv with | Ast_defs.Pinout _ -> true | Ast_defs.Pnormal -> false in let position = Parameter { is_inout; is_variadic } in let context = Declaration { position } in { common_info; context } let mk_param_decl_info ~context_id Aast. { param_pos; param_callconv; param_type_hint = (ty, _); param_is_variadic; _; } = let bad_type = Typing_defs.is_any ty in if bad_type then let param_decl_info = mk_param_decl_info_internal ~context_id ~is_variadic:param_is_variadic param_pos param_callconv in Some param_decl_info else None let mk_callable_decl_infos ~context_id env params ret = let param_infos = List.map ~f:(mk_param_decl_info ~context_id) params in List.filter_opt @@ (mk_ret_decl_info ~context_id env ret :: param_infos) let mk_expr_info_internal ~context_id pos ty exp = let common_info = mk_common_info ~context_id pos in let producer_id = function | Aast.Id (_, id) -> Some id | Aast.Class_const ((_, _, Aast.CI (_, class_id)), (_, id)) -> Some (class_id ^ "::" ^ id) | _ -> None in let exp_info = match exp with | Aast.(Call { func = (_, _, receiver); _ }) -> let producer = match producer_id receiver with | Some id -> Some id | None -> Some "-" in let declaration_usage = false in { producer; declaration_usage } | Aast.Id _ | Aast.Class_const _ -> let producer = None in let declaration_usage = match Typing_defs.get_node ty with | Typing_defs.Tfun _ -> true | _ -> false in { producer; declaration_usage } | _ -> let producer = None in let declaration_usage = false in { producer; declaration_usage } in let context = Expression exp_info in { common_info; context } let mk_expr_info ~context_id (ty, pos, exp) = let bad_type = Typing_defs.is_any ty in if bad_type then let expr_info = mk_expr_info_internal ~context_id pos ty exp in Some expr_info else None (** Reduction to collect all Tany/Terr information below methods and functions.*) let collect_infos_methods_functions context_id = object inherit [_] Tast_visitor.reduce as super method zero = [] method plus = ( @ ) method! on_method_ env (Aast.{ m_params; m_ret; _ } as m) = let infos = mk_callable_decl_infos ~context_id env m_params m_ret in infos @ super#on_method_ env m method! on_fun_ env (Aast.{ f_params; f_ret; _ } as f) = let infos = mk_callable_decl_infos ~context_id env f_params f_ret in infos @ super#on_fun_ env f method! on_expr env exp = let infos = match mk_expr_info ~context_id exp with | Some info -> [info] | None -> [] in infos @ super#on_expr env exp end (** Reduction to collect all Tany/Terr information. It calls the reudction for functions and methods with the context information attached. *) let collect_infos = object inherit [_] Tast_visitor.reduce method zero = [] method plus = ( @ ) method! on_fun_def env (Aast.{ fd_name; _ } as fd) = let context_id = Function (snd fd_name) in (collect_infos_methods_functions context_id)#on_fun_def env fd method! on_method_ env (Aast.{ m_name; _ } as m) = let context_id = match Tast_env.get_self_id env with | Some c_name -> Method (c_name, snd m_name) | None -> failwith "method does not have an enclosing class" in (collect_infos_methods_functions context_id)#on_method_ env m end let create_handler _ctx = object inherit Tast_visitor.handler_base method! at_fun_def env f = let infos = collect_infos#on_fun_def env f in log_info env infos method! at_class_ env c = let infos = collect_infos#on_class_ env c in log_info env infos end
OCaml
hhvm/hphp/hack/src/typing/tast_check/tany_logger/tany_logger_common.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Tany_logger_types let should_log log_level log_mask = log_level land log_mask_to_enum log_mask > 0 let string_of_pos pos = let path = Pos.filename pos |> Relative_path.suffix in let filename = match String.rsplit2 ~on:'/' path with | Some (_, filename) -> filename | None -> path in let (line, col) = Pos.line_column pos in Printf.sprintf "%s:%d:%d" filename line (col + 1) let string_of_context_id = function | Function fx_name -> fx_name | Method (class_name, method_name) -> class_name ^ "::" ^ method_name
OCaml
hhvm/hphp/hack/src/typing/tast_check/tany_logger/tany_logger_file.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Tany_logger_types open Tany_logger_common (** Flattens the structure information about Tanys and writes it out to the logging channel. *) let log_info_to_file_internal level (info : info) : unit = let tag tag rest = Format.sprintf "%s[%s]" rest tag in let iftag tag cond rest = if cond then Format.sprintf "%s[%s]" rest tag else rest in let keyedtag tag value rest = Format.sprintf "%s[%s:%s]" rest tag value in let opttag tag opt rest = Option.value_map ~default:rest ~f:(fun value -> keyedtag tag value rest) opt in let exp_info_tags exp_info rest = rest |> iftag "decl_use" exp_info.declaration_usage |> opttag "producer" exp_info.producer in let param_info_tags param_info rest = rest |> iftag "inout" param_info.is_inout |> iftag "variadic" param_info.is_variadic in let position_tags position rest = match position with | Parameter param_info -> rest |> tag "param" |> param_info_tags param_info | Return -> tag "return" rest in let decl_info_tags decl_info rest = rest |> position_tags decl_info.position in let context_tags context rest = match context with | Expression exp_info -> rest |> tag "exp" |> exp_info_tags exp_info | Declaration decl_info -> rest |> tag "decl" |> decl_info_tags decl_info in let common_info_tags common_info rest = rest |> tag "Tany" |> iftag "generated" common_info.is_generated |> iftag "test" common_info.is_test |> keyedtag "context" (string_of_context_id common_info.context_id) |> keyedtag "position" (string_of_pos common_info.pos) in "" |> common_info_tags info.common_info |> context_tags info.context |> fun output -> if level > 1 then Hh_logger.log "%s" output else ( Format.sprintf "%s\n" output |> Out_channel.output_string !Typing_log.out_channel; Out_channel.flush !Typing_log.out_channel ) let log_info_to_file env (info : info) : unit = let log_level_opt = Tast_env.tast_env_as_typing_env env |> Typing_env.get_tcopt |> TypecheckerOptions.log_levels |> SMap.find_opt "tany" in match log_level_opt with | Some level when should_log level File -> log_info_to_file_internal level info | _ -> ()