language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
OCaml Interface | hhvm/hphp/hack/src/typing/typing_classes_heap.mli | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Typing_defs
(* This entire file is "private". Its sole consumer is Decl_provider.ml. *)
type class_t
val make_eager_class_decl : Decl_defs.decl_class_type -> class_t
val get :
Provider_context.t ->
string ->
(Provider_context.t ->
string ->
Decl_defs.decl_class_type * Decl_store.class_members option) ->
class_t option
module Api : sig
(** This type "t" is what all APIs operate upon. It includes
a "decl option". This provides context about how the specified
class_t was fetched in the first place. It's used solely for telemetry,
so that telemetry about APIs can be easily correlated with telemetry
to the original call to the [get] which fetched the class_t in the
first place.
It also references the provider context that was used to query the class_t,
as it might be needed when querying its members when the shallow decl where it
was defines is evicted. For Zoncolan, this Provider_context.t is not
available, as Zoncolan doesn't support eviction. *)
type t =
(Decl_counters.decl option[@opaque])
* class_t
* (Provider_context.t[@opaque]) option
[@@deriving show]
val need_init : t -> bool
val abstract : t -> bool
val final : t -> bool
val const : t -> bool
val deferred_init_members : t -> SSet.t
val kind : t -> Ast_defs.classish_kind
val is_xhp : t -> bool
val name : t -> string
val get_docs_url : t -> string option
val get_module : t -> string option
val internal : t -> bool
val is_module_level_trait : t -> bool
val pos : t -> Pos_or_decl.t
val tparams : t -> decl_tparam list
val where_constraints : t -> decl_where_constraint list
val all_where_constraints_on_this : t -> decl_where_constraint list
val upper_bounds_on_this : t -> decl_ty list
val upper_bounds_on_this_from_constraints : t -> decl_ty list
val has_upper_bounds_on_this_from_constraints : t -> bool
val lower_bounds_on_this : t -> decl_ty list
val lower_bounds_on_this_from_constraints : t -> decl_ty list
val has_lower_bounds_on_this_from_constraints : t -> bool
val construct : t -> class_elt option * consistent_kind
val enum_type : t -> enum_type option
val xhp_enum_values : t -> Ast_defs.xhp_enum_value list SMap.t
val xhp_marked_empty : t -> bool
val sealed_whitelist : t -> SSet.t option
val decl_errors : t -> Decl_defs.decl_error list
val get_ancestor : t -> string -> decl_ty option
val has_ancestor : t -> string -> bool
val requires_ancestor : t -> string -> bool
val get_support_dynamic_type : t -> bool
val all_ancestors : t -> (string * decl_ty) list
val all_ancestor_names : t -> string list
(** All the require extends and require implements requirements
* These requirements impose a strict subtype constraint
*)
val all_ancestor_reqs : t -> requirement list
val all_ancestor_req_names : t -> string list
(** All the require class requirements
* These requirements impose an equality constraint and are not
* included in all_ancestor_reqs or all_ancestor_req_names
*)
val all_ancestor_req_class_requirements : t -> requirement list
val get_const : t -> string -> class_const option
val get_typeconst : t -> string -> typeconst_type option
val get_prop : t -> string -> class_elt option
val get_sprop : t -> string -> class_elt option
val get_method : t -> string -> class_elt option
val get_smethod : t -> string -> class_elt option
val get_any_method : is_static:bool -> t -> string -> class_elt option
val has_const : t -> string -> bool
val has_typeconst : t -> string -> bool
val has_prop : t -> string -> bool
val has_sprop : t -> string -> bool
val has_method : t -> string -> bool
val has_smethod : t -> string -> bool
val consts : t -> (string * class_const) list
val typeconsts : t -> (string * typeconst_type) list
val props : t -> (string * class_elt) list
val sprops : t -> (string * class_elt) list
val methods : t -> (string * class_elt) list
val smethods : t -> (string * class_elt) list
(** Return the enforceability of the typeconst with the given name. A
typeconst is enforceable if it was declared with the <<__Enforceable>>
attribute, or if it overrides some ancestor typeconst with that attribute.
Only enforceable typeconsts may be used in [is] or [as] expressions. The
overriding behavior makes this expensive to compute in shallow decl, which
is why this separate accessor is provided (rather than making this
information available in the [ttc_enforceable] field, whose semantics
differ between legacy and shallow decl due to the perf cost in shallow). *)
val get_typeconst_enforceability :
t -> string -> (Pos_or_decl.t * bool) option
val valid_newable_class : t -> bool
val overridden_method :
t ->
method_name:string ->
is_static:bool ->
get_class:(Provider_context.t -> string -> t option) ->
class_elt option
end
val get_class_with_cache :
Provider_context.t ->
string ->
Provider_backend.Decl_cache.t ->
(Provider_context.t -> string -> Decl_defs.decl_class_type * 'a) ->
class_t option |
OCaml | hhvm/hphp/hack/src/typing/typing_class_types.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type inherited_members = {
consts: Typing_defs.class_const Lazy_string_table.t;
typeconsts: Typing_defs.typeconst_type Lazy_string_table.t;
props: Typing_defs.class_elt Lazy_string_table.t;
sprops: Typing_defs.class_elt Lazy_string_table.t;
methods: Typing_defs.class_elt Lazy_string_table.t;
smethods: Typing_defs.class_elt Lazy_string_table.t;
all_inherited_methods: Typing_defs.class_elt list Lazy_string_table.t;
all_inherited_smethods: Typing_defs.class_elt list Lazy_string_table.t;
typeconst_enforceability: (Pos_or_decl.t * bool) Lazy_string_table.t;
construct:
(Typing_defs.class_elt option * Typing_defs_core.consistent_kind) Lazy.t;
}
type eager_members = {
props: Typing_defs.class_elt String.Table.t;
static_props: Typing_defs.class_elt String.Table.t;
methods: Typing_defs.class_elt String.Table.t;
static_methods: Typing_defs.class_elt String.Table.t;
construct:
(Typing_defs.class_elt option * Typing_defs_core.consistent_kind) option ref;
}
(** class_t:
This type is an abstraction layer over the way folded decls are stored, and
provides a view of classes which includes all inherited members and their types.
This view is constructed by merging a single heap entry for the folded class
with many entries for the types of each of its members (those member entries are
looked up lazily, as needed). *)
type class_t = Decl_defs.decl_class_type * (eager_members[@opaque])
[@@deriving show] |
OCaml | hhvm/hphp/hack/src/typing/typing_coeffects.ml | (*
* Copyright (c) 2020, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
open Common
open Typing_defs
open Typing_env_types
module Env = Typing_env
module Phase = Typing_phase
module MakeType = Typing_make_type
module SN = Naming_special_names
let capability_id = Local_id.make_unscoped SN.Coeffects.capability
let local_capability_id = Local_id.make_unscoped SN.Coeffects.local_capability
let register_capabilities env (cap_ty : locl_ty) (unsafe_cap_ty : locl_ty) =
let cap_pos = Typing_defs.get_pos cap_ty in
(* Represents the capability for local operations inside a function body, excluding calls. *)
let env =
Env.set_local
~is_defined:true
~bound_ty:None
env
local_capability_id
cap_ty
(Pos_or_decl.unsafe_to_raw_pos cap_pos)
in
let (env, ty) =
Typing_intersection.intersect
env
~r:(Reason.Rhint cap_pos)
cap_ty
unsafe_cap_ty
in
(* The implicit argument for ft_implicit_params.capability *)
( Env.set_local
~is_defined:true
~bound_ty:None
env
capability_id
ty
(Pos_or_decl.unsafe_to_raw_pos cap_pos),
ty )
let get_type capability =
match capability with
| CapTy cap -> cap
| CapDefaults p -> MakeType.default_capability p
let rec validate_capability env pos ty =
match get_node ty with
| Tintersection tys -> List.iter ~f:(validate_capability env pos) tys
| Tapply ((_, n), _) when String.is_prefix ~prefix:SN.Coeffects.contexts n ->
()
| Tapply ((_, n), _) ->
(match Env.get_class_or_typedef env n with
| None -> () (* unbound name error *)
| Some (Env.TypedefResult { Typing_defs.td_is_ctx = true; _ }) -> ()
| _ ->
Errors.add_error
Nast_check_error.(
to_user_error
@@ Illegal_context
{ pos; name = Typing_print.full_decl (Env.get_tcopt env) ty }))
| Tgeneric (name, []) when SN.Coeffects.is_generated_generic name -> ()
| Taccess (root, (_p, c)) ->
let ((env, ty_err_opt), root) =
Phase.localize_no_subst env ~ignore_errors:false root
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
let (env, candidates) =
Typing_utils.get_concrete_supertypes ~abstract_enum:false env root
in
let check_ctx_const t =
match get_node t with
| Tclass ((_, name), _, _) ->
(match Env.get_class env name with
| Some cls ->
(match Env.get_typeconst env cls c with
| Some tc ->
if not tc.Typing_defs.ttc_is_ctx then
Errors.add_error
Nast_check_error.(
to_user_error
@@ Illegal_context
{
pos;
name = Typing_print.full_decl (Env.get_tcopt env) ty;
})
| None -> () (* typeconst not found *))
| None -> () (* unbound name error *))
| _ -> ()
in
List.iter ~f:check_ctx_const candidates
| _ ->
Errors.add_error
Nast_check_error.(
to_user_error
@@ Illegal_context
{ pos; name = Typing_print.full_decl (Env.get_tcopt env) ty })
let pretty env ty =
lazy
(let (env, ty) = Typing_intersection.simplify_intersections env ty in
Typing_print.coeffects env ty)
let is_generated_generic =
String.is_prefix ~prefix:SN.Coeffects.generated_generic_prefix
let type_capability env ctxs unsafe_ctxs default_pos =
(* No need to repeat the following check (saves time) for unsafe_ctx
because it's synthetic and well-kinded by construction *)
Option.iter ctxs ~f:(fun (_pos, hl) ->
List.iter
hl
~f:
(Typing_kinding.Simple.check_well_kinded_context_hint
~in_signature:false
env));
let cc = Decl_hint.aast_contexts_to_decl_capability in
let (decl_pos, cap) = cc env.decl_env ctxs default_pos in
let ((env, ty_err_opt1), cap_ty) =
match cap with
| CapTy ty ->
if TypecheckerOptions.strict_contexts (Env.get_tcopt env) then
validate_capability env decl_pos ty;
Phase.localize_no_subst env ~ignore_errors:false ty
| CapDefaults p -> ((env, None), MakeType.default_capability p)
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt1;
let ((env, ty_err_opt2), unsafe_cap_ty) =
match snd @@ cc env.decl_env unsafe_ctxs default_pos with
| CapTy ty -> Phase.localize_no_subst env ~ignore_errors:false ty
| CapDefaults p -> ((env, None), MakeType.default_capability_unsafe p)
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt2;
(env, cap_ty, unsafe_cap_ty)
(* Checking this with List.exists will be a single op in the vast majority of cases (empty) *)
let get_ctx_vars ctxs =
Option.value_map
~f:(fun (_, cs) ->
List.filter_map cs ~f:(function
| (_, Haccess ((_, Hvar n), _)) -> Some n
| _ -> None))
~default:[]
ctxs |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_coeffects.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 capability_id : Local_id.t
val local_capability_id : Local_id.t
val register_capabilities :
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty
val get_type : Typing_defs.locl_ty Typing_defs.capability -> Typing_defs.locl_ty
val validate_capability :
Typing_env_types.env -> Pos.t -> Typing_defs.decl_ty -> unit
val pretty : Typing_env_types.env -> Typing_defs.locl_ty -> string Lazy.t
val is_generated_generic : string -> bool
val type_capability :
Typing_env_types.env ->
Aast.contexts option ->
Aast.contexts option ->
Pos.t ->
Typing_env_types.env * Typing_defs.locl_ty * Typing_defs.locl_ty
val get_ctx_vars : Aast.contexts option -> string list |
OCaml | hhvm/hphp/hack/src/typing/typing_coercion.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
open Typing_env_types
(*
* These are the main coercion functions. Roughly, coercion should be used over
* subtyping in places where a particular type that could be dynamic is
* required, like parameters and returns.
*
* The old dynamic uses the following ideas:
*
* There are only a few coercion (~>) rules, documented in hphp/hack/doc/type_system/hack_typing.ott.
*
* 1. |- t ~> dynamic
* (you can coerce t to dynamic)
* 2. t is enforceable |- dynamic ~> t
* (coercion from dynamic to enforceable types is permitted)
* 3. T1 ~> T and T2 ~> T |- T1|T2 ~> T
* (coercion from a union is valid if coercion from each element is valid)
* 4. t1 <: t2 |- t1 ~> t2
* (you can coerce t1 to any of its supertypes)
*
* This boils down to running the normal sub_type procedure whenever possible,
* and catching the remaining cases. The normal sub_type procedure is important
* for resolving/inferring various types (e.g. array's union types), as well as
* useful to the user for error messages. In the cases where we do not want to
* sub_type, it suffices to do nothing.
*
*
* The experimental sound dynamic (--enable-sound-dynamic-type) works
* differently because dynamic is part of the sub-typing relation.
*
*)
(* does coercion, including subtyping *)
let coerce_type_impl
~coerce_for_op
~coerce
env
ty_have
ty_expect
(on_error : Typing_error.Reasons_callback.t option) =
let is_expected_enforced = equal_enforcement ty_expect.et_enforced Enforced in
if TypecheckerOptions.enable_sound_dynamic env.genv.tcopt then
if coerce_for_op && is_expected_enforced then
(* If the coercion is for a built-in operation, then we want to allow it to apply to
dynamic *)
let tunion =
Typing_make_type.locl_like
(Reason.Rdynamic_coercion (get_reason ty_expect.et_type))
ty_expect.et_type
in
Typing_utils.sub_type ~coerce:None env ty_have tunion on_error
else
let (env, ety_expect) = Typing_env.expand_type env ty_expect.et_type in
match get_node ety_expect with
| Tdynamic ->
Typing_utils.sub_type
~coerce:(Some Typing_logic.CoerceToDynamic)
env
ty_have
ty_expect.et_type
on_error
| _ ->
Typing_utils.sub_type ~coerce env ty_have ty_expect.et_type on_error
else
let (env, ety_expect) = Typing_env.expand_type env ty_expect.et_type in
let (env, ety_have) = Typing_env.expand_type env ty_have in
match (get_node ety_have, get_node ety_expect) with
| (_, Tdynamic) -> (env, None)
| (Tdynamic, _) when is_expected_enforced -> (env, None)
| _ when is_expected_enforced ->
Typing_utils.sub_type_with_dynamic_as_bottom
env
ty_have
ty_expect.et_type
on_error
| _ -> Typing_utils.sub_type env ty_have ty_expect.et_type on_error
let coerce_type
?(coerce_for_op = false)
?(coerce = None)
p
ur
env
ty_have
ty_expect
(on_error : Typing_error.Callback.t) =
Typing_log.(
log_with_level env "typing" ~level:2 (fun () ->
log_types
(Pos_or_decl.of_raw_pos p)
env
[
Log_head
( "Typing_coercion.coerce_type ",
[
Log_type ("ty_expect", ty_expect.et_type);
Log_type ("ty_have", ty_have);
] );
]));
coerce_type_impl ~coerce_for_op ~coerce env ty_have ty_expect
@@ Some
(Typing_error.Reasons_callback.with_claim
on_error
~claim:(lazy (p, Reason.string_of_ureason ur)))
let coerce_type_like_strip
p ur env ty_have ty_expect (on_error : Typing_error.Callback.t) =
let (env1, ty_err_opt) =
coerce_type_impl
~coerce_for_op:false
~coerce:None
env
ty_have
{ et_type = ty_expect; et_enforced = Unenforced }
@@ Some
(Typing_error.Reasons_callback.with_claim
on_error
~claim:(lazy (p, Reason.string_of_ureason ur)))
in
match ty_err_opt with
| None -> (env1, None, false, ty_have)
| Some _ ->
let (env2, fresh_ty) = Typing_env.fresh_type env p in
let (env2, like_ty) =
Typing_utils.union
env2
fresh_ty
(Typing_make_type.dynamic (get_reason fresh_ty))
in
let cb = Typing_error.Reasons_callback.unify_error_at p in
let (env2, impossible_error) =
Typing_utils.sub_type env2 fresh_ty ty_expect (Some cb)
in
(* Enforce the invariant - this call should never give us an error *)
if Option.is_some impossible_error then
Errors.internal_error p "Subtype of fresh type variable";
let (env2, ty_err_opt_like) =
coerce_type
p
Reason.URnone
env2
ty_have
{ et_type = like_ty; et_enforced = Unenforced }
Typing_error.Callback.unify_error
in
(match ty_err_opt_like with
| None -> (env2, None, true, fresh_ty)
| Some _ ->
Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env:env1);
let ty_mismatch =
Option.map ty_err_opt ~f:Fn.(const (ty_have, ty_expect))
in
(env1, ty_mismatch, false, ty_have))
(* does coercion if possible, returning Some env with resultant coercion constraints
* otherwise suppresses errors from attempted coercion and returns None *)
let try_coerce ?(coerce = None) env ty_have ty_expect =
let pos =
get_pos ty_have
|> Typing_env.fill_in_pos_filename_if_in_current_decl env
|> Option.value ~default:Pos.none
in
let res =
coerce_type_impl ~coerce ~coerce_for_op:false env ty_have ty_expect
@@ Some (Typing_error.Reasons_callback.unify_error_at pos)
in
match res with
| (env, None) -> Some env
| _ -> None |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_coercion.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 coerce_type :
?coerce_for_op:bool ->
?coerce:Typing_logic.coercion_direction option ->
Pos.t ->
Typing_defs.Reason.ureason ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_defs.locl_ty Typing_defs.possibly_enforced_ty ->
Typing_error.Callback.t ->
Typing_env_types.env * Typing_error.t option
val coerce_type_like_strip :
Pos.t ->
Typing_defs.Reason.ureason ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_defs.locl_ty ->
Typing_error.Callback.t ->
Typing_env_types.env
* (Typing_defs.locl_ty * Typing_defs.locl_ty) option
* bool
* Typing_defs.locl_ty
val try_coerce :
?coerce:Typing_logic.coercion_direction option ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_defs.locl_ty Typing_defs.possibly_enforced_ty ->
Typing_env_types.env option |
OCaml | hhvm/hphp/hack/src/typing/typing_const_reifiable.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 Typing_defs
let check_reifiable env tc attr_pos =
let check_impl kind ty =
let emit_err pos ty_info =
Typing_error_utils.add_typing_error
~env
Typing_error.(
primary @@ Primary.Reifiable_attr { pos; ty_info; attr_pos; kind })
in
Typing_reified_check.validator#validate_type
env
(fst tc.ttc_name |> Pos_or_decl.unsafe_to_raw_pos)
ty
~reification:Type_validator.Unresolved
emit_err
in
match tc.ttc_kind with
| TCConcrete { tc_type } -> check_impl `ty tc_type
| TCAbstract { atc_as_constraint; atc_super_constraint; atc_default } ->
Option.iter ~f:(check_impl `ty) atc_default;
Option.iter ~f:(check_impl `cnstr) atc_as_constraint;
Option.iter ~f:(check_impl `cnstr) atc_super_constraint |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_const_reifiable.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 check_reifiable :
Typing_env_types.env -> Typing_defs.typeconst_type -> Pos_or_decl.t -> unit |
OCaml | hhvm/hphp/hack/src/typing/typing_continuations.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
include Typing_cont_key
module Map = struct
let show _ = "<WrappedMap.Make(Continuations)>"
let pp _ _ = Printf.printf "%s\n" "<WrappedMap.Make(Continuations)>"
include WrappedMap.Make (Typing_cont_key)
end |
OCaml | hhvm/hphp/hack/src/typing/typing_cont_key.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type t =
| Next
| Continue
| Break
| Catch
| Do
| Exit
| Fallthrough
| Finally
[@@deriving eq, ord, show]
let all = [Next; Continue; Break; Catch; Do; Exit; Fallthrough; Finally]
let to_string = function
| Next -> "Next"
| Continue -> "Continue"
| Break -> "Break"
| Catch -> "Catch"
| Do -> "Do"
| Exit -> "Exit"
| Fallthrough -> "Fallthrough"
| Finally -> "Finally" |
OCaml | hhvm/hphp/hack/src/typing/typing_debug.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Typing_env_types
open Typing_inference_env.Size
module Env = Typing_env
let local_env_size env =
match Env.next_cont_opt env with
| None -> 0
| Some Typing_per_cont_env.{ local_types; _ } ->
Local_id.Map.fold
(fun _ local size ->
size + ty_size env.inference_env local.Typing_local_types.ty)
local_types
0
let env_size env = local_env_size env + inference_env_size env.inference_env
let log_env_if_too_big pos env =
if
Env.get_tcopt env |> TypecheckerOptions.timeout > 0
&& List.length !(env.big_envs) < 1
&& env_size env >= 1000
then
env.big_envs := (pos, env) :: !(env.big_envs) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_debug.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 log_env_if_too_big : Pos.t -> Typing_env_types.env -> unit |
OCaml | hhvm/hphp/hack/src/typing/typing_defs.ml | (*
* Copyrighd (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Typing_defs_flags
include Typing_defs_core
(** Origin of Class Constant References:
In order to be able to detect cycle definitions like
class C {
const int A = D::A;
}
class D {
const int A = C::A;
}
we need to remember which constants were used during initialization.
Currently the syntax of constants allows direct references to another class
like D::A, or self references using self::A.
class_const_from encodes the origin (class vs self).
*)
type class_const_from =
| Self
| From of string
[@@deriving eq, show]
(** Class Constant References:
In order to be able to detect cycle definitions like
class C {
const int A = D::A;
}
class D {
const int A = C::A;
}
we need to remember which constants were used during initialization.
Currently the syntax of constants allows direct references to another class
like D::A, or self references using self::A.
*)
type class_const_ref = class_const_from * string [@@deriving eq, show]
module CCR = struct
type t = class_const_ref [@@deriving show]
(* We're deriving the compare function by hand to sync it with the rust code.
* In the decl parser I need to sort these class_const_from in the same
* way. I used `cargo expand` to see how Cargo generated they Ord/PartialOrd
* functions.
*)
let compare_class_const_from ccf0 ccf1 =
match (ccf0, ccf1) with
| (Self, Self) -> 0
| (From lhs, From rhs) -> String.compare lhs rhs
| (Self, From _) -> -1
| (From _, Self) -> 1
let compare (ccf0, s0) (ccf1, s1) =
match compare_class_const_from ccf0 ccf1 with
| 0 -> String.compare s0 s1
| x -> x
end
module CCRSet = struct
include Caml.Set.Make (CCR)
type t_as_list = CCR.t list [@@deriving show]
let pp fmt set = pp_t_as_list fmt (elements set)
let show set = show_t_as_list (elements set)
end
type const_decl = {
cd_pos: Pos_or_decl.t;
cd_type: decl_ty;
}
[@@deriving show]
type class_elt = {
ce_visibility: ce_visibility;
ce_type: decl_ty Lazy.t;
ce_origin: string; (** identifies the class from which this elt originates *)
ce_deprecated: string option;
ce_pos: Pos_or_decl.t Lazy.t; (** pos of the type of the elt *)
ce_flags: Typing_defs_flags.ClassElt.t;
}
[@@deriving show]
type fun_elt = {
fe_deprecated: string option;
fe_module: Ast_defs.id option;
fe_internal: bool; (** Top-level functions have limited visibilities *)
fe_type: decl_ty;
fe_pos: Pos_or_decl.t;
(* TODO: ideally these should be packed flags *)
fe_php_std_lib: bool;
fe_support_dynamic_type: bool;
fe_no_auto_dynamic: bool;
fe_no_auto_likes: bool;
}
[@@deriving show]
(* TODO(T71787342) This is temporary. It is necessary because legacy decl
* uses Typing_defs types to represent folded inherited members. This will
* be removed when shallow decl ships as this information is only necessary
* there. *)
type class_const_kind =
| CCAbstract of bool (* has default *)
| CCConcrete
[@@deriving eq, show]
type class_const = {
cc_synthesized: bool;
cc_abstract: class_const_kind;
cc_pos: Pos_or_decl.t;
cc_type: decl_ty;
cc_origin: string;
(** identifies the class from which this const originates *)
cc_refs: class_const_ref list;
(** references to the constants used in the initializer *)
}
[@@deriving show]
type module_reference =
| MRGlobal
| MRPrefix of string
| MRExact of string
[@@deriving show]
type module_def_type = {
mdt_pos: Pos_or_decl.t;
mdt_exports: module_reference list option;
mdt_imports: module_reference list option;
}
[@@deriving show]
(** The position is that of the hint in the `use` / `implements` AST node
* that causes a class to have this requirement applied to it. E.g.
*
* ```
* class Foo {}
*
* interface Bar {
* require extends Foo; <- position of the decl_phase ty
* }
*
* class Baz extends Foo implements Bar { <- position of the `implements`
* }
* ```
*)
type requirement = Pos_or_decl.t * decl_ty
and abstract_typeconst = {
atc_as_constraint: decl_ty option;
atc_super_constraint: decl_ty option;
atc_default: decl_ty option;
}
and concrete_typeconst = { tc_type: decl_ty }
and partially_abstract_typeconst = {
patc_constraint: decl_ty;
patc_type: decl_ty;
}
and typeconst =
| TCAbstract of abstract_typeconst
| TCConcrete of concrete_typeconst
and typeconst_type = {
ttc_synthesized: bool;
ttc_name: pos_id;
ttc_kind: typeconst;
ttc_origin: string;
ttc_enforceable: Pos_or_decl.t * bool;
(** If the typeconst had the <<__Enforceable>> attribute on its
declaration, this will be [(position_of_declaration, true)].
In legacy decl, the second element of the tuple will also be true if
the typeconst overrides some parent typeconst which had the
<<__Enforceable>> attribute. In that case, the position will point to
the declaration of the parent typeconst.
In shallow decl, this is not the case--there is no overriding behavior
modeled here, and the second element will only be true when the
declaration of this typeconst had the attribute.
When the second element of the tuple is false, the position will be
[Pos_or_decl.none].
To manage the difference between legacy and shallow decl, use
[Typing_classes_heap.Api.get_typeconst_enforceability] rather than
accessing this field directly. *)
ttc_reifiable: Pos_or_decl.t option;
ttc_concretized: bool;
ttc_is_ctx: bool;
}
and enum_type = {
te_base: decl_ty;
te_constraint: decl_ty option;
te_includes: decl_ty list;
}
[@@deriving show]
type typedef_type = {
td_module: Ast_defs.id option;
td_pos: Pos_or_decl.t;
td_vis: Ast_defs.typedef_visibility;
td_tparams: decl_tparam list;
td_as_constraint: decl_ty option;
td_super_constraint: decl_ty option;
td_type: decl_ty;
td_is_ctx: bool;
td_attributes: user_attribute list;
td_internal: bool;
td_docs_url: string option;
}
[@@deriving show]
type phase_ty =
| DeclTy of decl_ty
| LoclTy of locl_ty
type deserialization_error =
| Wrong_phase of string
(** The type was valid, but some component thereof was a decl_ty when we
expected a locl_phase ty, or vice versa. *)
| Not_supported of string
(** The specific type or some component thereof is not one that we support
deserializing, usually because not enough information was serialized to be
able to deserialize it again. *)
| Deserialization_error of string
(** The input JSON was invalid for some reason. *)
[@@deriving show]
module Type_expansions : sig
(** A list of the type defs and type access we have expanded thus far. Used
to prevent entering into a cycle when expanding these types. *)
type t
val empty : t
(** If we are expanding the RHS of a type definition, [report_cycle] contains
the position and id of the LHS. This way, if the RHS expands at some point
to the LHS id, we are able to report a cycle. *)
val empty_w_cycle_report : report_cycle:(Pos.t * string) option -> t
(** Returns:
- [None] if there was no cycle
- [Some None] if there was a cycle which did not involve the first
type expansion, i.e. error reporting should be done elsewhere
- [Some (Some pos)] if there was a cycle involving the first type
expansion in which case an error should be reported at [pos]. *)
val add_and_check_cycles :
t -> Pos_or_decl.t * string -> t * Pos.t option option
val ids : t -> string list
val positions : t -> Pos_or_decl.t list
(** Returns true if there was an attempt to add a cycle to the expansion list. *)
val cyclic_expansion : t -> bool
end = struct
type t = {
report_cycle: (Pos.t * string) option;
(** If we are expanding the RHS of a type definition, [report_cycle] contains
the position and id of the LHS. This way, if the RHS expands at some point
to the LHS id, we are able to report a cycle. *)
expansions: (Pos_or_decl.t * string) list;
(** A list of the type defs and type access we have expanded thus far. Used
to prevent entering into a cycle when expanding these types. *)
cyclic_expansion: bool ref;
}
let empty_w_cycle_report ~report_cycle =
{ report_cycle; expansions = []; cyclic_expansion = ref false }
let empty = empty_w_cycle_report ~report_cycle:None
let add ({ expansions; _ } as exps) exp =
{ exps with expansions = exp :: expansions }
let has_expanded { report_cycle; expansions; _ } x =
match report_cycle with
| Some (p, x') when String.equal x x' -> Some (Some p)
| Some _
| None ->
List.find_map expansions ~f:(function
| (_, x') when String.equal x x' -> Some None
| _ -> None)
let add_and_check_cycles exps (p, id) =
let has_cycle = has_expanded exps id in
if Option.is_some has_cycle then exps.cyclic_expansion := true;
let exps = add exps (p, id) in
(exps, has_cycle)
let as_list { report_cycle; expansions; _ } =
(report_cycle
|> Option.map ~f:(Tuple2.map_fst ~f:Pos_or_decl.of_raw_pos)
|> Option.to_list)
@ List.rev expansions
let ids exps = as_list exps |> List.map ~f:snd
let positions exps = as_list exps |> List.map ~f:fst
let cyclic_expansion exps = !(exps.cyclic_expansion)
end
(** How should we treat the wildcard character _ when localizing?
* 1. Generate a fresh type variable, e.g. in type argument to constructor or function,
* or in a lambda parameter or return type.
* Example: foo<shape('a' => _)>($myshape);
* Example: ($v : vec<_>) ==> $v[0]
* 2. As a placeholder in a formal higher-kinded type parameter
* Example: function test<T1, T2<_>>() // T2 is HK and takes a type to a type
* 3. Generate a fresh generic (aka Skolem variable), e.g. in `is` or `as` test
* Example: if ($x is Vector<_>) { // $x has type Vector<T#1> }
* 4. Reject, when in a type argument to a generic parameter marked <<__Explicit>>
* Example: makeVec<_>(3) where function makeVec<<<__Explicit>> T>(T $_): void
* 5. Reject, because the type must be explicit.
* 6. (Specially for case type checking). Replace any type argument by a fresh generic.
*)
type wildcard_action =
| Wildcard_fresh_tyvar
| Wildcard_fresh_generic
| Wildcard_higher_kinded_placeholder
| Wildcard_require_explicit of decl_tparam
| Wildcard_illegal
| Wildcard_fresh_generic_type_argument
(** Tracks information about how a type was expanded *)
type expand_env = {
type_expansions: Type_expansions.t;
expand_visible_newtype: bool;
(** Allow to expand visible `newtype`, i.e. opaque types defined in the current file.
True by default. *)
substs: locl_ty SMap.t;
this_ty: locl_ty;
(** The type that is substituted for `this` in signatures. It should be
* set to an expression dependent type if appropriate
*)
on_error: Typing_error.Reasons_callback.t option;
wildcard_action: wildcard_action;
}
let empty_expand_env =
{
type_expansions = Type_expansions.empty;
expand_visible_newtype = true;
substs = SMap.empty;
this_ty =
mk (Reason.none, Tgeneric (Naming_special_names.Typehints.this, []));
on_error = None;
wildcard_action = Wildcard_fresh_tyvar;
}
let empty_expand_env_with_on_error on_error =
{ empty_expand_env with on_error = Some on_error }
let add_type_expansion_check_cycles env exp =
let (type_expansions, has_cycle) =
Type_expansions.add_and_check_cycles env.type_expansions exp
in
let env = { env with type_expansions } in
(env, has_cycle)
let cyclic_expansion env = Type_expansions.cyclic_expansion env.type_expansions
let get_var t =
match get_node t with
| Tvar v -> Some v
| _ -> None
let get_class_type t =
match get_node t with
| Tclass (id, exact, tyl) -> Some (id, exact, tyl)
| _ -> None
let get_var_i t =
match t with
| LoclType t -> get_var t
| ConstraintType _ -> None
let is_tyvar t = Option.is_some (get_var t)
let is_tyvar_i t = Option.is_some (get_var_i t)
let is_var_v t v =
match get_node t with
| Tvar v' when Ident.equal v v' -> true
| _ -> false
let is_generic t =
match get_node t with
| Tgeneric _ -> true
| _ -> false
let is_dynamic t =
match get_node t with
| Tdynamic -> true
| _ -> false
let is_nothing t =
match get_node t with
| Tunion [] -> true
| _ -> false
let is_wildcard t =
match get_node t with
| Twildcard -> true
| _ -> false
let is_nonnull t =
match get_node t with
| Tnonnull -> true
| _ -> false
let is_fun t =
match get_node t with
| Tfun _ -> true
| _ -> false
let is_any t =
match get_node t with
| Tany _ -> true
| _ -> false
let is_generic_equal_to n t =
(* TODO(T69551141) handle type arguments *)
match get_node t with
| Tgeneric (n', _tyargs) when String.equal n n' -> true
| _ -> false
let is_prim p t =
match get_node t with
| Tprim p' when Aast.equal_tprim p p' -> true
| _ -> false
let is_union t =
match get_node t with
| Tunion _ -> true
| _ -> false
let is_neg t =
match get_node t with
| Tneg _ -> true
| _ -> false
let is_constraint_type_union t =
match deref_constraint_type t with
| (_, TCunion _) -> true
| _ -> false
let is_has_member t =
match deref_constraint_type t with
| (_, Thas_member _) -> true
| _ -> false
let show_phase_ty _ = "<phase_ty>"
let pp_phase_ty _ _ = Printf.printf "%s\n" "<phase_ty>"
let is_locl_type = function
| LoclType _ -> true
| _ -> false
let reason = function
| LoclType t -> get_reason t
| ConstraintType t -> fst (deref_constraint_type t)
let is_constraint_type = function
| ConstraintType _ -> true
| LoclType _ -> false
let is_union_or_inter_type (ty : locl_ty) =
(* do not expand type here! *)
match get_node ty with
| Toption _
| Tunion _
| Tintersection _ ->
true
| Tnonnull
| Tneg _
| Tdynamic
| Tany _
| Tprim _
| Tfun _
| Ttuple _
| Tshape _
| Tvar _
| Tnewtype _
| Tdependent _
| Tgeneric _
| Tclass _
| Tunapplied_alias _
| Tvec_or_dict _
| Taccess _ ->
false
module InternalType = struct
let get_var t =
match t with
| LoclType t -> get_var t
| ConstraintType _ -> None
let is_var_v t ~v =
match t with
| LoclType t -> is_var_v t v
| ConstraintType _ -> false
let is_not_var_v t ~v = not @@ is_var_v t ~v
end
(* The identifier for this *)
let this = Local_id.make_scoped "$this"
(* This should be the ONLY way that Tany is constructed anywhere in the
* codebase. *)
let make_tany () = Tany TanySentinel.value
let arity_min ft : int =
let a = List.count ~f:(fun fp -> not (get_fp_has_default fp)) ft.ft_params in
if get_ft_variadic ft then
a - 1
else
a
let get_param_mode callconv =
match callconv with
| Ast_defs.Pinout _ -> FPinout
| Ast_defs.Pnormal -> FPnormal
module DependentKind = struct
let to_string = function
| DTexpr i ->
let display_id = Reason.get_expr_display_id i in
"<expr#" ^ string_of_int display_id ^ ">"
let is_generic_dep_ty s =
String.is_substring ~substring:"::" s
|| String.equal s Naming_special_names.Typehints.this
end
let rec is_denotable ty =
match get_node ty with
| Tunion [] (* Possible encodings of nothing *)
| Tintersection [] (* Possible encodings of mixed *)
| Tnonnull
| Tdynamic
| Tprim _
| Tnewtype _ ->
true
| Tunion [ty; ty'] -> begin
match (get_node ty, get_node ty') with
| (Tprim Aast.(Tfloat | Tstring), Tprim Aast.Tint)
| (Tprim Aast.Tint, Tprim Aast.(Tfloat | Tstring)) ->
true
| _ -> false
end
| Tclass (_, _, ts)
| Ttuple ts ->
List.for_all ~f:is_denotable ts
| Tvec_or_dict (tk, tv) -> is_denotable tk && is_denotable tv
| Taccess (ty, _) -> is_denotable ty
| Tshape { s_origin = _; s_unknown_value = unknown_field_type; s_fields = sm }
->
TShapeMap.for_all (fun _ { sft_ty; _ } -> is_denotable sft_ty) sm
&& unknown_field_type_is_denotable unknown_field_type
| Tfun { ft_params; ft_ret; _ } ->
is_denotable ft_ret.et_type
&& List.for_all ft_params ~f:(fun { fp_type; _ } ->
is_denotable fp_type.et_type)
| Toption ty -> is_denotable ty
| Tgeneric (nm, _) ->
not
(DependentKind.is_generic_dep_ty nm
|| String.is_substring ~substring:"#" nm)
| Tunion _
| Tintersection _
| Tneg _
| Tany _
| Tvar _
| Tdependent _
| Tunapplied_alias _ ->
false
and unknown_field_type_is_denotable ty =
match get_node ty with
| Tunion [] -> true
| Tintersection [] -> true
| Toption ty -> begin
match get_node ty with
| Tnonnull -> true
| _ -> false
end
| _ -> false
let same_type_origin orig1 orig2 =
match orig1 with
| Missing_origin -> false
| _ -> equal_type_origin orig1 orig2
module ShapeFieldMap = struct
include TShapeMap
let map_and_rekey shape_map key_f value_f =
let f_over_shape_field_type ({ sft_ty; _ } as shape_field_type) =
{ shape_field_type with sft_ty = value_f sft_ty }
in
TShapeMap.map_and_rekey shape_map key_f f_over_shape_field_type
let map_env f env shape_map =
let f_over_shape_field_type env _key ({ sft_ty; _ } as shape_field_type) =
let (env, sft_ty) = f env sft_ty in
(env, { shape_field_type with sft_ty })
in
TShapeMap.map_env f_over_shape_field_type env shape_map
let map_env_ty_err_opt f env shape_map ~combine_ty_errs =
let f_over_shape_field_type env _key ({ sft_ty; _ } as shape_field_type) =
let (env, sft_ty) = f env sft_ty in
(env, { shape_field_type with sft_ty })
in
TShapeMap.map_env_ty_err_opt
f_over_shape_field_type
env
shape_map
~combine_ty_errs
let map f shape_map = map_and_rekey shape_map (fun x -> x) f
let iter f shape_map =
let f_over_shape_field_type shape_map_key { sft_ty; _ } =
f shape_map_key sft_ty
in
TShapeMap.iter f_over_shape_field_type shape_map
let iter_values f = iter (fun _ -> f)
end
module ShapeFieldList = struct
include Common.List
let map_env env xs ~f =
let f_over_shape_field_type env ({ sft_ty; _ } as shape_field_type) =
let (env, sft_ty) = f env sft_ty in
(env, { shape_field_type with sft_ty })
in
Common.List.map_env env xs ~f:f_over_shape_field_type
end
(*****************************************************************************)
(* Suggest mode *)
(*****************************************************************************)
(* Set to true when we are trying to infer the missing type hints. *)
let is_suggest_mode = ref false
(* Ordinal value for type constructor *)
let ty_con_ordinal_ : type a. a ty_ -> int = function
(* only decl constructors *)
| Tthis -> 100
| Tapply _ -> 101
| Tmixed -> 102
| Tlike _ -> 103
| Trefinement _ -> 104
| Twildcard -> 105
(* exist in both phases *)
| Tany _ -> 0
| Toption t -> begin
match get_node t with
| Tnonnull -> 1
| _ -> 4
end
| Tnonnull -> 2
| Tdynamic -> 3
| Tprim _ -> 5
| Tfun _ -> 6
| Ttuple _ -> 7
| Tshape _ -> 8
| Tvar _ -> 9
| Tgeneric _ -> 11
| Tunion _ -> 13
| Tintersection _ -> 14
| Taccess _ -> 24
| Tvec_or_dict _ -> 25
(* only locl constructors *)
| Tunapplied_alias _ -> 200
| Tnewtype _ -> 201
| Tdependent _ -> 202
| Tclass _ -> 204
| Tneg _ -> 205
let compare_neg_type neg1 neg2 =
match (neg1, neg2) with
| (Neg_prim tp1, Neg_prim tp2) -> Aast.compare_tprim tp1 tp2
| (Neg_class c1, Neg_class c2) -> String.compare (snd c1) (snd c2)
| (Neg_prim _, Neg_class _) -> -1
| (Neg_class _, Neg_prim _) -> 1
(* Compare two types syntactically, ignoring reason information and other
* small differences that do not affect type inference behaviour. This
* comparison function can be used to construct tree-based sets of types,
* or to compare two types for "exact" equality.
* Note that this function does *not* expand type variables, or type
* aliases.
* But if ty_compare ty1 ty2 = 0, then the types must not be distinguishable
* by any typing rules.
*)
let rec ty__compare : type a. ?normalize_lists:bool -> a ty_ -> a ty_ -> int =
fun ?(normalize_lists = false) ty_1 ty_2 ->
let rec ty__compare : type a. a ty_ -> a ty_ -> int =
fun ty_1 ty_2 ->
match (ty_1, ty_2) with
(* Only in Declared Phase *)
| (Tthis, Tthis) -> 0
| (Tapply (id1, tyl1), Tapply (id2, tyl2)) -> begin
match String.compare (snd id1) (snd id2) with
| 0 -> tyl_compare ~sort:normalize_lists ~normalize_lists tyl1 tyl2
| n -> n
end
| (Trefinement (ty1, r1), Trefinement (ty2, r2)) -> begin
match ty_compare ty1 ty2 with
| 0 -> class_refinement_compare r1 r2
| n -> n
end
| (Tmixed, Tmixed) -> 0
| (Twildcard, Twildcard) -> 0
| (Tlike ty1, Tlike ty2) -> ty_compare ty1 ty2
| ((Tthis | Tapply _ | Tmixed | Twildcard | Tlike _), _)
| (_, (Tthis | Tapply _ | Tmixed | Twildcard | Tlike _)) ->
ty_con_ordinal_ ty_1 - ty_con_ordinal_ ty_2
(* Both or in Localized Phase *)
| (Tprim ty1, Tprim ty2) -> Aast_defs.compare_tprim ty1 ty2
| (Toption ty, Toption ty2) -> ty_compare ty ty2
| (Tvec_or_dict (tk, tv), Tvec_or_dict (tk2, tv2)) -> begin
match ty_compare tk tk2 with
| 0 -> ty_compare tv tv2
| n -> n
end
| (Tfun fty, Tfun fty2) -> tfun_compare fty fty2
| (Tunion tyl1, Tunion tyl2)
| (Tintersection tyl1, Tintersection tyl2)
| (Ttuple tyl1, Ttuple tyl2) ->
tyl_compare ~sort:normalize_lists ~normalize_lists tyl1 tyl2
| (Tgeneric (n1, args1), Tgeneric (n2, args2)) -> begin
match String.compare n1 n2 with
| 0 -> tyl_compare ~sort:false ~normalize_lists args1 args2
| n -> n
end
| (Tnewtype (id, tyl, cstr1), Tnewtype (id2, tyl2, cstr2)) -> begin
match String.compare id id2 with
| 0 ->
(match tyl_compare ~sort:false tyl tyl2 with
| 0 -> ty_compare cstr1 cstr2
| n -> n)
| n -> n
end
| (Tdependent (d1, cstr1), Tdependent (d2, cstr2)) -> begin
match compare_dependent_type d1 d2 with
| 0 -> ty_compare cstr1 cstr2
| n -> n
end
(* An instance of a class or interface, ty list are the arguments *)
| (Tclass (id, exact, tyl), Tclass (id2, exact2, tyl2)) -> begin
match String.compare (snd id) (snd id2) with
| 0 -> begin
match tyl_compare ~sort:false tyl tyl2 with
| 0 -> exact_compare exact exact2
| n -> n
end
| n -> n
end
| (Tshape s1, Tshape s2) -> shape_type_compare s1 s2
| (Tvar v1, Tvar v2) -> compare v1 v2
| (Tunapplied_alias n1, Tunapplied_alias n2) -> String.compare n1 n2
| (Taccess (ty1, id1), Taccess (ty2, id2)) -> begin
match ty_compare ty1 ty2 with
| 0 -> String.compare (snd id1) (snd id2)
| n -> n
end
| (Tneg neg1, Tneg neg2) -> compare_neg_type neg1 neg2
| (Tnonnull, Tnonnull) -> 0
| (Tdynamic, Tdynamic) -> 0
| ( ( Tprim _ | Toption _ | Tvec_or_dict _ | Tfun _ | Tintersection _
| Tunion _ | Ttuple _ | Tgeneric _ | Tnewtype _ | Tdependent _
| Tclass _ | Tshape _ | Tvar _ | Tunapplied_alias _ | Tnonnull
| Tdynamic | Taccess _ | Tany _ | Tneg _ | Trefinement _ ),
_ ) ->
ty_con_ordinal_ ty_1 - ty_con_ordinal_ ty_2
and shape_field_type_compare :
type a. a shape_field_type -> a shape_field_type -> int =
fun sft1 sft2 ->
let { sft_ty = ty1; sft_optional = optional1 } = sft1 in
let { sft_ty = ty2; sft_optional = optional2 } = sft2 in
match ty_compare ty1 ty2 with
| 0 -> Bool.compare optional1 optional2
| n -> n
and shape_type_compare : type a. a shape_type -> a shape_type -> int =
fun s1 s2 ->
let {
s_origin = shape_origin1;
s_unknown_value = unknown_fields_type1;
s_fields = fields1;
} =
s1
in
let {
s_origin = shape_origin2;
s_unknown_value = unknown_fields_type2;
s_fields = fields2;
} =
s2
in
if same_type_origin shape_origin1 shape_origin2 then
0
else begin
match ty_compare unknown_fields_type1 unknown_fields_type2 with
| 0 ->
List.compare
(fun (k1, v1) (k2, v2) ->
match TShapeField.compare k1 k2 with
| 0 -> shape_field_type_compare v1 v2
| n -> n)
(TShapeMap.elements fields1)
(TShapeMap.elements fields2)
| n -> n
end
and user_attribute_param_compare p1 p2 =
let dest_user_attribute_param p =
match p with
| Classname s -> (0, s)
| EnumClassLabel s -> (1, s)
| String s -> (2, s)
| Int i -> (3, i)
in
let (id1, s1) = dest_user_attribute_param p1 in
let (id2, s2) = dest_user_attribute_param p2 in
match Int.compare id1 id2 with
| 0 -> String.compare s1 s2
| n -> n
and user_attribute_compare ua1 ua2 =
let { ua_name = name1; ua_params = params1 } = ua1 in
let { ua_name = name2; ua_params = params2 } = ua2 in
match String.compare (snd name1) (snd name2) with
| 0 -> List.compare user_attribute_param_compare params1 params2
| n -> n
and user_attributes_compare ual1 ual2 =
List.compare user_attribute_compare ual1 ual2
and tparam_compare : type a. a ty tparam -> a ty tparam -> int =
fun tp1 tp2 ->
let {
(* Type parameters on functions are always marked invariant *)
tp_variance = _;
tp_name = name1;
tp_tparams = tparams1;
tp_constraints = constraints1;
tp_reified = reified1;
tp_user_attributes = user_attributes1;
} =
tp1
in
let {
tp_variance = _;
tp_name = name2;
tp_tparams = tparams2;
tp_constraints = constraints2;
tp_reified = reified2;
tp_user_attributes = user_attributes2;
} =
tp2
in
match String.compare (snd name1) (snd name2) with
| 0 -> begin
match tparams_compare tparams1 tparams2 with
| 0 -> begin
match constraints_compare constraints1 constraints2 with
| 0 -> begin
match user_attributes_compare user_attributes1 user_attributes2 with
| 0 -> Aast_defs.compare_reify_kind reified1 reified2
| n -> n
end
| n -> n
end
| n -> n
end
| n -> n
and tparams_compare : type a. a ty tparam list -> a ty tparam list -> int =
(fun tpl1 tpl2 -> List.compare tparam_compare tpl1 tpl2)
and constraints_compare :
type a.
(Ast_defs.constraint_kind * a ty) list ->
(Ast_defs.constraint_kind * a ty) list ->
int =
(fun cl1 cl2 -> List.compare constraint_compare cl1 cl2)
and constraint_compare :
type a.
Ast_defs.constraint_kind * a ty -> Ast_defs.constraint_kind * a ty -> int
=
fun (ck1, ty1) (ck2, ty2) ->
match Ast_defs.compare_constraint_kind ck1 ck2 with
| 0 -> ty_compare ty1 ty2
| n -> n
and where_constraint_compare :
type a b.
a ty * Ast_defs.constraint_kind * b ty ->
a ty * Ast_defs.constraint_kind * b ty ->
int =
fun (ty1a, ck1, ty1b) (ty2a, ck2, ty2b) ->
match Ast_defs.compare_constraint_kind ck1 ck2 with
| 0 -> begin
match ty_compare ty1a ty2a with
| 0 -> ty_compare ty1b ty2b
| n -> n
end
| n -> n
and where_constraints_compare :
type a b.
(a ty * Ast_defs.constraint_kind * b ty) list ->
(a ty * Ast_defs.constraint_kind * b ty) list ->
int =
(fun cl1 cl2 -> List.compare where_constraint_compare cl1 cl2)
(* We match every field rather than using field selection syntax. This guards against future additions to function type elements *)
and tfun_compare : type a. a ty fun_type -> a ty fun_type -> int =
fun fty1 fty2 ->
let {
ft_ret = ret1;
ft_params = params1;
ft_flags = flags1;
ft_implicit_params = implicit_params1;
ft_ifc_decl = ifc_decl1;
ft_tparams = tparams1;
ft_where_constraints = where_constraints1;
ft_cross_package = cross_package1;
} =
fty1
in
let {
ft_ret = ret2;
ft_params = params2;
ft_flags = flags2;
ft_implicit_params = implicit_params2;
ft_ifc_decl = ifc_decl2;
ft_tparams = tparams2;
ft_where_constraints = where_constraints2;
ft_cross_package = cross_package2;
} =
fty2
in
match possibly_enforced_ty_compare ret1 ret2 with
| 0 -> begin
match ft_params_compare params1 params2 with
| 0 -> begin
match tparams_compare tparams1 tparams2 with
| 0 -> begin
match
where_constraints_compare where_constraints1 where_constraints2
with
| 0 -> begin
match Int.compare flags1 flags2 with
| 0 ->
let { capability = capability1 } = implicit_params1 in
let { capability = capability2 } = implicit_params2 in
begin
match capability_compare capability1 capability2 with
| 0 -> begin
match compare_ifc_fun_decl ifc_decl1 ifc_decl2 with
| 0 ->
compare_cross_package_decl cross_package1 cross_package2
| n -> n
end
| n -> n
end
| n -> n
end
| n -> n
end
| n -> n
end
| n -> n
end
| n -> n
and capability_compare : type a. a ty capability -> a ty capability -> int =
fun cap1 cap2 ->
match (cap1, cap2) with
| (CapDefaults _, CapDefaults _) -> 0
| (CapDefaults _, CapTy _) -> -1
| (CapTy _, CapDefaults _) -> 1
| (CapTy ty1, CapTy ty2) -> ty_compare ty1 ty2
and ty_compare : type a. a ty -> a ty -> int =
(fun ty1 ty2 -> ty__compare (get_node ty1) (get_node ty2))
in
ty__compare ty_1 ty_2
and ty_compare : type a. ?normalize_lists:bool -> a ty -> a ty -> int =
fun ?(normalize_lists = false) ty1 ty2 ->
ty__compare ~normalize_lists (get_node ty1) (get_node ty2)
and tyl_compare :
type a. sort:bool -> ?normalize_lists:bool -> a ty list -> a ty list -> int
=
fun ~sort ?(normalize_lists = false) tyl1 tyl2 ->
let (tyl1, tyl2) =
if sort then
(List.sort ~compare:ty_compare tyl1, List.sort ~compare:ty_compare tyl2)
else
(tyl1, tyl2)
in
List.compare (ty_compare ~normalize_lists) tyl1 tyl2
and possibly_enforced_ty_compare :
type a.
?normalize_lists:bool ->
a ty possibly_enforced_ty ->
a ty possibly_enforced_ty ->
int =
fun ?(normalize_lists = false) ety1 ety2 ->
match ty_compare ~normalize_lists ety1.et_type ety2.et_type with
| 0 -> compare_enforcement ety1.et_enforced ety2.et_enforced
| n -> n
and ft_param_compare :
type a. ?normalize_lists:bool -> a ty fun_param -> a ty fun_param -> int =
fun ?(normalize_lists = false) param1 param2 ->
match
possibly_enforced_ty_compare ~normalize_lists param1.fp_type param2.fp_type
with
| 0 -> Int.compare param1.fp_flags param2.fp_flags
| n -> n
and ft_params_compare :
type a.
?normalize_lists:bool -> a ty fun_param list -> a ty fun_param list -> int =
fun ?(normalize_lists = false) params1 params2 ->
List.compare (ft_param_compare ~normalize_lists) params1 params2
and refined_const_compare : type a. a refined_const -> a refined_const -> int =
fun a b ->
(* Note: `rc_is_ctx` is not used for typing inference, so we can safely ignore it *)
match (a.rc_bound, b.rc_bound) with
| (TRexact _, TRloose _) -> -1
| (TRloose _, TRexact _) -> 1
| (TRloose b1, TRloose b2) -> begin
match tyl_compare ~sort:true b1.tr_lower b2.tr_lower with
| 0 -> tyl_compare ~sort:true b1.tr_upper b2.tr_upper
| n -> n
end
| (TRexact ty1, TRexact ty2) -> ty_compare ty1 ty2
and class_refinement_compare :
type a. a class_refinement -> a class_refinement -> int =
fun { cr_consts = rcs1 } { cr_consts = rcs2 } ->
SMap.compare refined_const_compare rcs1 rcs2
and exact_compare e1 e2 =
match (e1, e2) with
| (Exact, Exact) -> 0
| (Nonexact _, Exact) -> 1
| (Exact, Nonexact _) -> -1
| (Nonexact r1, Nonexact r2) -> class_refinement_compare r1 r2
(* Dedicated functions with more easily discoverable names *)
let compare_locl_ty : ?normalize_lists:bool -> locl_ty -> locl_ty -> int =
ty_compare
let compare_decl_ty : ?normalize_lists:bool -> decl_ty -> decl_ty -> int =
ty_compare
let tyl_equal tyl1 tyl2 = Int.equal 0 @@ tyl_compare ~sort:false tyl1 tyl2
let compare_exact = exact_compare
let equal_exact e1 e2 = Int.equal 0 (compare_exact e1 e2)
let class_id_con_ordinal cid =
match cid with
| Aast.CIparent -> 0
| Aast.CIself -> 1
| Aast.CIstatic -> 2
| Aast.CIexpr _ -> 3
| Aast.CI _ -> 4
let class_id_compare cid1 cid2 =
match (cid1, cid2) with
| (Aast.CIexpr _e1, Aast.CIexpr _e2) -> 0
| (Aast.CI (_, id1), Aast.CI (_, id2)) -> String.compare id1 id2
| _ -> class_id_con_ordinal cid2 - class_id_con_ordinal cid1
let class_id_equal cid1 cid2 = Int.equal (class_id_compare cid1 cid2) 0
let has_member_compare ~normalize_lists hm1 hm2 =
let ty_compare = ty_compare ~normalize_lists in
let {
hm_name = (_, m1);
hm_type = ty1;
hm_class_id = cid1;
hm_explicit_targs = targs1;
} =
hm1
in
let {
hm_name = (_, m2);
hm_type = ty2;
hm_class_id = cid2;
hm_explicit_targs = targs2;
} =
hm2
in
let targ_compare (_, (_, hint1)) (_, (_, hint2)) =
Aast_defs.compare_hint_ hint1 hint2
in
match String.compare m1 m2 with
| 0 ->
(match ty_compare ty1 ty2 with
| 0 ->
(match class_id_compare cid1 cid2 with
| 0 -> Option.compare (List.compare targ_compare) targs1 targs2
| comp -> comp)
| comp -> comp)
| comp -> comp
let can_index_compare ~normalize_lists ci1 ci2 =
match ty_compare ~normalize_lists ci1.ci_key ci2.ci_key with
| 0 ->
(match ty_compare ~normalize_lists ci1.ci_val ci2.ci_val with
| 0 -> Option.compare compare_tshape_field_name ci1.ci_shape ci2.ci_shape
| comp -> comp)
| comp -> comp
let can_traverse_compare ~normalize_lists ct1 ct2 =
match Option.compare (ty_compare ~normalize_lists) ct1.ct_key ct2.ct_key with
| 0 ->
(match ty_compare ~normalize_lists ct1.ct_val ct2.ct_val with
| 0 -> Bool.compare ct1.ct_is_await ct2.ct_is_await
| comp -> comp)
| comp -> comp
let destructure_compare ~normalize_lists d1 d2 =
let {
d_required = tyl1;
d_optional = tyl_opt1;
d_variadic = ty_opt1;
d_kind = e1;
} =
d1
in
let {
d_required = tyl2;
d_optional = tyl_opt2;
d_variadic = ty_opt2;
d_kind = e2;
} =
d2
in
match tyl_compare ~normalize_lists ~sort:false tyl1 tyl2 with
| 0 ->
(match tyl_compare ~normalize_lists ~sort:false tyl_opt1 tyl_opt2 with
| 0 ->
(match Option.compare ty_compare ty_opt1 ty_opt2 with
| 0 -> compare_destructure_kind e1 e2
| comp -> comp)
| comp -> comp)
| comp -> comp
let constraint_ty_con_ordinal cty =
match cty with
| Thas_member _ -> 0
| Tdestructure _ -> 1
| TCunion _ -> 2
| TCintersection _ -> 3
| Tcan_index _ -> 4
| Tcan_traverse _ -> 5
| Thas_type_member _ -> 6
let rec constraint_ty_compare ?(normalize_lists = false) ty1 ty2 =
let (_, ty1) = deref_constraint_type ty1 in
let (_, ty2) = deref_constraint_type ty2 in
match (ty1, ty2) with
| (Thas_member hm1, Thas_member hm2) ->
has_member_compare ~normalize_lists hm1 hm2
| (Thas_type_member htm1, Thas_type_member htm2) ->
let { htm_id = id1; htm_lower = lower1; htm_upper = upper1 } = htm1
and { htm_id = id2; htm_lower = lower2; htm_upper = upper2 } = htm2 in
(match String.compare id1 id2 with
| 0 ->
(match ty_compare lower1 lower2 with
| 0 -> ty_compare upper1 upper2
| comp -> comp)
| comp -> comp)
| (Tcan_index ci1, Tcan_index ci2) ->
can_index_compare ~normalize_lists ci1 ci2
| (Tcan_traverse ct1, Tcan_traverse ct2) ->
can_traverse_compare ~normalize_lists ct1 ct2
| (Tdestructure d1, Tdestructure d2) ->
destructure_compare ~normalize_lists d1 d2
| (TCunion (lty1, cty1), TCunion (lty2, cty2))
| (TCintersection (lty1, cty1), TCintersection (lty2, cty2)) ->
let comp1 = ty_compare ~normalize_lists lty1 lty2 in
if not @@ Int.equal comp1 0 then
comp1
else
constraint_ty_compare ~normalize_lists cty1 cty2
| ( _,
( Thas_member _ | Tcan_index _ | Tcan_traverse _ | Tdestructure _
| TCunion _ | TCintersection _ | Thas_type_member _ ) ) ->
constraint_ty_con_ordinal ty2 - constraint_ty_con_ordinal ty1
let constraint_ty_equal ?(normalize_lists = false) ty1 ty2 =
Int.equal (constraint_ty_compare ~normalize_lists ty1 ty2) 0
let ty_equal ?(normalize_lists = false) ty1 ty2 =
phys_equal (get_node ty1) (get_node ty2)
|| Int.equal 0 (ty_compare ~normalize_lists ty1 ty2)
let equal_internal_type ty1 ty2 =
match (ty1, ty2) with
| (LoclType ty1, LoclType ty2) -> ty_equal ~normalize_lists:true ty1 ty2
| (ConstraintType ty1, ConstraintType ty2) ->
constraint_ty_equal ~normalize_lists:true ty1 ty2
| (_, (LoclType _ | ConstraintType _)) -> false
let equal_locl_ty : locl_ty -> locl_ty -> bool =
(fun ty1 ty2 -> ty_equal ty1 ty2)
let equal_locl_ty_ : locl_ty_ -> locl_ty_ -> bool =
(fun ty_1 ty_2 -> Int.equal 0 (ty__compare ty_1 ty_2))
let is_type_no_return : locl_ty_ -> bool = equal_locl_ty_ (Tprim Aast.Tnoreturn)
let equal_decl_ty_ : decl_ty_ -> decl_ty_ -> bool =
(fun ty1 ty2 -> Int.equal 0 (ty__compare ty1 ty2))
let equal_decl_ty ty1 ty2 = equal_decl_ty_ (get_node ty1) (get_node ty2)
let equal_shape_field_type sft1 sft2 =
equal_decl_ty sft1.sft_ty sft2.sft_ty
&& Bool.equal sft1.sft_optional sft2.sft_optional
let non_public_ifc ifc =
match ifc with
| FDPolicied (Some "PUBLIC") -> false
| _ -> true
let equal_decl_tyl tyl1 tyl2 = List.equal equal_decl_ty tyl1 tyl2
let equal_decl_possibly_enforced_ty ety1 ety2 =
equal_decl_ty ety1.et_type ety2.et_type
&& equal_enforcement ety1.et_enforced ety2.et_enforced
let equal_decl_fun_param param1 param2 =
equal_decl_possibly_enforced_ty param1.fp_type param2.fp_type
&& Int.equal param1.fp_flags param2.fp_flags
let equal_decl_ft_params params1 params2 =
List.equal equal_decl_fun_param params1 params2
let equal_decl_ft_implicit_params :
decl_ty fun_implicit_params -> decl_ty fun_implicit_params -> bool =
fun { capability = cap1 } { capability = cap2 } ->
(* TODO(coeffects): could rework this so that implicit defaults and explicit
* [defaults] are considered equal *)
match (cap1, cap2) with
| (CapDefaults p1, CapDefaults p2) -> Pos_or_decl.equal p1 p2
| (CapTy c1, CapTy c2) -> equal_decl_ty c1 c2
| (CapDefaults _, CapTy _)
| (CapTy _, CapDefaults _) ->
false
let equal_decl_fun_type fty1 fty2 =
equal_decl_possibly_enforced_ty fty1.ft_ret fty2.ft_ret
&& equal_decl_ft_params fty1.ft_params fty2.ft_params
&& equal_decl_ft_implicit_params
fty1.ft_implicit_params
fty2.ft_implicit_params
&& Int.equal fty1.ft_flags fty2.ft_flags
let equal_abstract_typeconst at1 at2 =
Option.equal equal_decl_ty at1.atc_as_constraint at2.atc_as_constraint
&& Option.equal
equal_decl_ty
at1.atc_super_constraint
at2.atc_super_constraint
&& Option.equal equal_decl_ty at1.atc_default at2.atc_default
let equal_concrete_typeconst ct1 ct2 = equal_decl_ty ct1.tc_type ct2.tc_type
let equal_typeconst t1 t2 =
match (t1, t2) with
| (TCAbstract at1, TCAbstract at2) -> equal_abstract_typeconst at1 at2
| (TCConcrete ct1, TCConcrete ct2) -> equal_concrete_typeconst ct1 ct2
| _ -> false
let equal_enum_type et1 et2 =
equal_decl_ty et1.te_base et2.te_base
&& Option.equal equal_decl_ty et1.te_constraint et2.te_constraint
let equal_decl_where_constraint c1 c2 =
let (tya1, ck1, tyb1) = c1 in
let (tya2, ck2, tyb2) = c2 in
equal_decl_ty tya1 tya2
&& Ast_defs.equal_constraint_kind ck1 ck2
&& equal_decl_ty tyb1 tyb2
let equal_decl_tparam tp1 tp2 =
Ast_defs.equal_variance tp1.tp_variance tp2.tp_variance
&& equal_pos_id tp1.tp_name tp2.tp_name
&& List.equal
(Tuple.T2.equal ~eq1:Ast_defs.equal_constraint_kind ~eq2:equal_decl_ty)
tp1.tp_constraints
tp2.tp_constraints
&& Aast.equal_reify_kind tp1.tp_reified tp2.tp_reified
&& List.equal
equal_user_attribute
tp1.tp_user_attributes
tp2.tp_user_attributes
let equal_typedef_type tt1 tt2 =
Pos_or_decl.equal tt1.td_pos tt2.td_pos
&& Aast.equal_typedef_visibility tt1.td_vis tt2.td_vis
&& List.equal equal_decl_tparam tt1.td_tparams tt2.td_tparams
&& Option.equal equal_decl_ty tt1.td_as_constraint tt2.td_as_constraint
&& Option.equal equal_decl_ty tt1.td_super_constraint tt2.td_super_constraint
&& equal_decl_ty tt1.td_type tt2.td_type
let equal_fun_elt fe1 fe2 =
Option.equal String.equal fe1.fe_deprecated fe2.fe_deprecated
&& equal_decl_ty fe1.fe_type fe2.fe_type
&& Pos_or_decl.equal fe1.fe_pos fe2.fe_pos
let equal_const_decl cd1 cd2 =
Pos_or_decl.equal cd1.cd_pos cd2.cd_pos
&& equal_decl_ty cd1.cd_type cd2.cd_type
let get_ce_abstract ce = ClassElt.is_abstract ce.ce_flags
let get_ce_final ce = ClassElt.is_final ce.ce_flags
let get_ce_superfluous_override ce =
ClassElt.has_superfluous_override ce.ce_flags
let get_ce_lsb ce = ClassElt.has_lsb ce.ce_flags
let get_ce_synthesized ce = ClassElt.is_synthesized ce.ce_flags
let get_ce_const ce = ClassElt.is_const ce.ce_flags
let get_ce_lateinit ce = ClassElt.has_lateinit ce.ce_flags
let get_ce_readonly_prop ce = ClassElt.is_readonly_prop ce.ce_flags
let get_ce_dynamicallycallable ce = ClassElt.is_dynamicallycallable ce.ce_flags
let get_ce_support_dynamic_type ce = ClassElt.supports_dynamic_type ce.ce_flags
let get_ce_xhp_attr ce = Typing_defs_flags.ClassElt.get_xhp_attr ce.ce_flags
let get_ce_safe_global_variable ce =
ClassElt.is_safe_global_variable ce.ce_flags
let make_ce_flags = Typing_defs_flags.ClassElt.make
(** Return true if the element is private and not marked with the __LSB
attribute. Private elements are not inherited by child classes and are
namespaced to the containing class--if B extends A, then A may define a
method A::foo and B may define a method B::foo, and they both will exist in
the hierarchy and be callable at runtime (which method is invoked depends on
the caller).
The __LSB attribute can be applied to properties only. LSB properties are
(effectively) implicitly cloned into every subclass. This means that in the
typechecker, we want to avoid filtering them out in subclasses, so we treat
them as non-private here. *)
let class_elt_is_private_not_lsb (elt : class_elt) : bool =
match elt.ce_visibility with
| Vprivate _ -> not (get_ce_lsb elt)
| Vprotected _
| Vpublic
| Vinternal _ ->
false
let class_elt_is_private_or_protected_not_lsb elt =
match elt.ce_visibility with
| Vprivate _
| Vprotected _
when get_ce_lsb elt ->
false
| Vprivate _
| Vprotected _ ->
true
| Vpublic
| Vinternal _ ->
false
(** Tunapplied_alias is a locl phase constructor that always stands for a higher-kinded type.
We use this function in cases where Tunapplied_alias appears in a context where we expect
a fully applied type, rather than a type constructor. Seeing Tunapplied_alias in such a context
always indicates a kinding error, which means that during localization, we should have
created Terr rather than Tunapplied_alias. Hence, this is an *internal* error, because
something went wrong during localization. Kind mismatches in code are reported to users
elsewhere. *)
let error_Tunapplied_alias_in_illegal_context () =
failwith "Found Tunapplied_alias in a context where it must not occur"
let is_typeconst_type_abstract tc =
match tc.ttc_kind with
| TCConcrete _ -> false
| TCAbstract _ -> true
module Attributes = struct
let mem x xs =
List.exists xs ~f:(fun { ua_name; _ } -> String.equal x (snd ua_name))
let find x xs =
List.find xs ~f:(fun { ua_name; _ } -> String.equal x (snd ua_name))
end |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_defs.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.
*
*)
(* "include" typing_defs_core.mli *)
include module type of struct
include Typing_defs_core
end
type class_const_from =
| Self
| From of string
[@@deriving eq, show]
type class_const_ref = class_const_from * string [@@deriving eq, show]
module CCR : sig
type t = class_const_ref [@@deriving show]
val compare_class_const_from : class_const_from -> class_const_from -> int
val compare : class_const_from * string -> class_const_from * string -> int
end
module CCRSet : sig
include module type of struct
include Caml.Set.Make (CCR)
end
type t_as_list = CCR.t list [@@deriving show]
val pp :
Ppx_deriving_runtime.Format.formatter -> t -> Ppx_deriving_runtime.unit
val show : t -> Ppx_deriving_runtime.string
end
type const_decl = {
cd_pos: Pos_or_decl.t;
cd_type: decl_ty;
}
[@@deriving show]
type class_elt = {
ce_visibility: ce_visibility;
ce_type: decl_ty Hh_prelude.Lazy.t;
ce_origin: string;
ce_deprecated: string option;
ce_pos: Pos_or_decl.t Hh_prelude.Lazy.t;
ce_flags: Typing_defs_flags.ClassElt.t;
}
[@@deriving show]
type fun_elt = {
fe_deprecated: string option;
fe_module: Ast_defs.id option;
fe_internal: bool;
fe_type: decl_ty;
fe_pos: Pos_or_decl.t;
fe_php_std_lib: bool;
fe_support_dynamic_type: bool;
fe_no_auto_dynamic: bool;
fe_no_auto_likes: bool;
}
[@@deriving show]
type class_const_kind =
| CCAbstract of bool (* has default *)
| CCConcrete
[@@deriving eq, show]
type class_const = {
cc_synthesized: bool;
cc_abstract: class_const_kind;
cc_pos: Pos_or_decl.t;
cc_type: decl_ty;
cc_origin: string;
cc_refs: class_const_ref list;
}
[@@deriving show]
type module_reference =
| MRGlobal
| MRPrefix of string
| MRExact of string
[@@deriving show]
type module_def_type = {
mdt_pos: Pos_or_decl.t;
mdt_exports: module_reference list option;
mdt_imports: module_reference list option;
}
[@@deriving show]
type requirement = Pos_or_decl.t * decl_ty
and abstract_typeconst = {
atc_as_constraint: decl_ty option;
atc_super_constraint: decl_ty option;
atc_default: decl_ty option;
}
and concrete_typeconst = { tc_type: decl_ty }
and partially_abstract_typeconst = {
patc_constraint: decl_ty;
patc_type: decl_ty;
}
and typeconst =
| TCAbstract of abstract_typeconst
| TCConcrete of concrete_typeconst
and typeconst_type = {
ttc_synthesized: bool;
ttc_name: pos_id;
ttc_kind: typeconst;
ttc_origin: string;
ttc_enforceable: Pos_or_decl.t * bool;
ttc_reifiable: Pos_or_decl.t option;
ttc_concretized: bool;
ttc_is_ctx: bool;
}
and enum_type = {
te_base: decl_ty;
te_constraint: decl_ty option;
te_includes: decl_ty list;
}
[@@deriving show]
type typedef_type = {
td_module: Ast_defs.id option;
td_pos: Pos_or_decl.t;
td_vis: Aast.typedef_visibility;
td_tparams: decl_tparam list;
td_as_constraint: decl_ty option;
td_super_constraint: decl_ty option;
td_type: decl_ty;
td_is_ctx: bool;
td_attributes: user_attribute list;
td_internal: bool;
td_docs_url: string option;
}
[@@deriving show]
type phase_ty =
| DeclTy of decl_ty
| LoclTy of locl_ty
type deserialization_error =
| Wrong_phase of string
| Not_supported of string
| Deserialization_error of string
[@@deriving show]
module Type_expansions : sig
(** A list of the type defs and type access we have expanded thus far. Used
to prevent entering into a cycle when expanding these types. *)
type t
val empty : t
(** If we are expanding the RHS of a type definition, [report_cycle] contains
the position and id of the LHS. This way, if the RHS expands at some point
to the LHS id, we are able to report a cycle. *)
val empty_w_cycle_report : report_cycle:(Pos.t * string) option -> t
val ids : t -> string list
val positions : t -> Pos_or_decl.t list
end
(** How should we treat the wildcard character _ when localizing?
* 1. Generate a fresh type variable, e.g. in type argument to constructor or function,
* or in a lambda parameter or return type.
* Example: foo<shape('a' => _)>($myshape);
* Example: ($v : vec<_>) ==> $v[0]
* 2. As a placeholder in a formal higher-kinded type parameter
* Example: function test<T1, T2<_>>() // T2 is HK and takes a type to a type
* 3. Generate a fresh generic (aka Skolem variable), e.g. in `is` or `as` test
* Example: if ($x is Vector<_>) { // $x has type Vector<T#1> }
* 4. Reject, when in a type argument to a generic parameter marked <<__Explicit>>
* Example: makeVec<_>(3) where function makeVec<<<__Explicit>> T>(T $_): void
* 5. Reject, because the type must be explicit.
* 6. (Specially for case type checking). Replace any type argument by a fresh generic.
*)
type wildcard_action =
| Wildcard_fresh_tyvar
| Wildcard_fresh_generic
| Wildcard_higher_kinded_placeholder
| Wildcard_require_explicit of decl_tparam
| Wildcard_illegal
| Wildcard_fresh_generic_type_argument
(** Tracks information about how a type was expanded *)
type expand_env = {
type_expansions: Type_expansions.t;
expand_visible_newtype: bool;
(** Allow to expand visible `newtype`, i.e. opaque types defined in the current file.
True by default. *)
substs: locl_ty SMap.t;
this_ty: locl_ty;
on_error: Typing_error.Reasons_callback.t option;
wildcard_action: wildcard_action;
}
val empty_expand_env : expand_env
val empty_expand_env_with_on_error :
Typing_error.Reasons_callback.t -> expand_env
(** Returns:
- [None] if there was no cycle
- [Some None] if there was a cycle which did not involve the first
type expansion, i.e. error reporting should be done elsewhere
- [Some (Some pos)] if there was a cycle involving the first type
expansion in which case an error should be reported at [pos]. *)
val add_type_expansion_check_cycles :
expand_env -> Pos_or_decl.t * string -> expand_env * Pos.t option option
(** Returns whether there was an attempt at expanding a cyclic type. *)
val cyclic_expansion : expand_env -> bool
val get_var : locl_phase ty -> Ident.t option
val get_class_type : locl_phase ty -> (pos_id * exact * locl_ty list) option
val get_var_i : internal_type -> Ident.t option
val is_tyvar : locl_phase ty -> bool
val is_tyvar_i : internal_type -> bool
val is_var_v : locl_phase ty -> Ident.t -> bool
val is_generic : 'a ty -> bool
val is_dynamic : 'a ty -> bool
val is_nonnull : 'a ty -> bool
val is_nothing : 'a ty -> bool
val is_wildcard : decl_phase ty -> bool
val is_fun : 'a ty -> bool
val is_any : 'a ty -> bool
val is_generic_equal_to : string -> 'a ty -> bool
val is_prim : Aast.tprim -> 'a ty -> bool
val is_union : 'a ty -> bool
val is_neg : locl_ty -> bool
val is_constraint_type_union : constraint_type -> bool
val is_has_member : constraint_type -> bool
(** Can the type be written down in a Hack program?
- [false] result is sound but potentially incomplete;
- [true] result is complete but potentially unsound. *)
val is_denotable : locl_ty -> bool
val show_phase_ty : 'a -> string
val pp_phase_ty : 'a -> 'b -> Base.unit
val is_locl_type : internal_type -> bool
val reason : internal_type -> locl_phase Reason.t_
val is_constraint_type : internal_type -> bool
(** Whether the given type is a union, intersection or option. *)
val is_union_or_inter_type : locl_ty -> bool
module InternalType : sig
val get_var : internal_type -> Ident.t option
val is_var_v : internal_type -> v:Ident.t -> bool
val is_not_var_v : internal_type -> v:Ident.t -> bool
end
val this : Local_id.t
val make_tany : unit -> 'a ty_
val arity_min : 'a fun_type -> int
val get_param_mode : Ast_defs.param_kind -> param_mode
module DependentKind : sig
val to_string : dependent_type -> string
val is_generic_dep_ty : string -> bool
end
(** Returns [true] if both origins are available and identical.
If this function returns [true], the two types that have
the origins provided must be identical. *)
val same_type_origin : type_origin -> type_origin -> bool
module ShapeFieldMap : sig
include module type of struct
include TShapeMap
end
val map_and_rekey :
'a shape_field_type TShapeMap.t ->
(TShapeMap.key -> TShapeMap.key) ->
('a ty -> 'b ty) ->
'b shape_field_type TShapeMap.t
val map_env :
('a -> 'b ty -> 'a * 'c ty) ->
'a ->
'b shape_field_type TShapeMap.t ->
'a * 'c shape_field_type TShapeMap.t
val map_env_ty_err_opt :
('a -> 'b ty -> ('a * 'e option) * 'c ty) ->
'a ->
'b shape_field_type TShapeMap.t ->
combine_ty_errs:('e list -> 'f) ->
('a * 'f) * 'c shape_field_type TShapeMap.t
val map :
('a ty -> 'b ty) ->
'a shape_field_type TShapeMap.t ->
'b shape_field_type TShapeMap.t
val iter :
(TShapeMap.key -> 'a ty -> unit) -> 'a shape_field_type TShapeMap.t -> unit
val iter_values : ('a ty -> unit) -> 'a shape_field_type TShapeMap.t -> unit
end
module ShapeFieldList : sig
include module type of struct
include Common.List
end
val map_env :
'a ->
'b shape_field_type list ->
f:('a -> 'b ty -> 'a * 'c ty) ->
'a * 'c shape_field_type Common.List.t
end
val is_suggest_mode : bool Hh_prelude.ref
val possibly_enforced_ty_compare :
?normalize_lists:bool ->
'a ty possibly_enforced_ty ->
'a ty possibly_enforced_ty ->
Ppx_deriving_runtime.int
val ft_param_compare :
?normalize_lists:bool -> 'a ty fun_param -> 'a ty fun_param -> int
val ft_params_compare :
?normalize_lists:bool ->
'a ty fun_param list ->
'a ty fun_param list ->
Ppx_deriving_runtime.int
val compare_locl_ty : ?normalize_lists:bool -> locl_ty -> locl_ty -> int
val compare_decl_ty : ?normalize_lists:bool -> decl_ty -> decl_ty -> int
val tyl_equal : 'a ty list -> 'a ty list -> bool
val class_id_con_ordinal : ('a, 'b) Aast.class_id_ -> int
val class_id_compare : ('a, 'b) Aast.class_id_ -> ('c, 'd) Aast.class_id_ -> int
val class_id_equal : ('a, 'b) Aast.class_id_ -> ('c, 'd) Aast.class_id_ -> bool
val has_member_compare :
normalize_lists:bool -> has_member -> has_member -> Ppx_deriving_runtime.int
val can_index_compare :
normalize_lists:bool -> can_index -> can_index -> Ppx_deriving_runtime.int
val destructure_compare :
normalize_lists:bool -> destructure -> destructure -> Ppx_deriving_runtime.int
val constraint_ty_con_ordinal : constraint_type_ -> int
val constraint_ty_compare :
?normalize_lists:bool ->
constraint_type ->
constraint_type ->
Ppx_deriving_runtime.int
val constraint_ty_equal :
?normalize_lists:bool -> constraint_type -> constraint_type -> bool
val ty_equal : ?normalize_lists:bool -> 'a ty -> 'a ty -> bool
val compare_exact : exact -> exact -> int
val equal_exact : exact -> exact -> bool
val equal_internal_type : internal_type -> internal_type -> bool
val equal_locl_ty : locl_ty -> locl_ty -> bool
val equal_locl_ty_ : locl_ty_ -> locl_ty_ -> bool
val is_type_no_return : locl_ty_ -> bool
val equal_decl_ty_ :
decl_phase ty_ -> decl_phase ty_ -> Ppx_deriving_runtime.bool
val equal_decl_ty : decl_phase ty -> decl_phase ty -> Ppx_deriving_runtime.bool
val equal_shape_field_type :
decl_phase shape_field_type -> decl_phase shape_field_type -> bool
val equal_decl_fun_type :
decl_phase ty fun_type -> decl_phase ty fun_type -> bool
val non_public_ifc : ifc_fun_decl -> bool
val equal_decl_tyl :
decl_phase ty Hh_prelude.List.t -> decl_phase ty Hh_prelude.List.t -> bool
val equal_decl_possibly_enforced_ty :
decl_phase ty possibly_enforced_ty ->
decl_phase ty possibly_enforced_ty ->
bool
val equal_decl_fun_param :
decl_phase ty fun_param -> decl_phase ty fun_param -> bool
val equal_decl_ft_params :
decl_phase ty fun_params -> decl_phase ty fun_params -> bool
val equal_decl_ft_implicit_params :
decl_ty fun_implicit_params -> decl_ty fun_implicit_params -> bool
val equal_typeconst : typeconst -> typeconst -> bool
val equal_enum_type : enum_type -> enum_type -> bool
val equal_decl_where_constraint :
decl_phase ty * Ast_defs.constraint_kind * decl_phase ty ->
decl_phase ty * Ast_defs.constraint_kind * decl_phase ty ->
bool
val equal_decl_tparam : decl_phase ty tparam -> decl_phase ty tparam -> bool
val equal_typedef_type : typedef_type -> typedef_type -> bool
val equal_fun_elt : fun_elt -> fun_elt -> bool
val equal_const_decl : const_decl -> const_decl -> bool
val get_ce_abstract : class_elt -> bool
val get_ce_final : class_elt -> bool
val get_ce_superfluous_override : class_elt -> bool
val get_ce_lsb : class_elt -> bool
(** Whether a class element comes from a `require extends`. *)
val get_ce_synthesized : class_elt -> bool
val get_ce_const : class_elt -> bool
val get_ce_lateinit : class_elt -> bool
val get_ce_readonly_prop : class_elt -> bool
val get_ce_dynamicallycallable : class_elt -> bool
val get_ce_support_dynamic_type : class_elt -> bool
val get_ce_xhp_attr : class_elt -> xhp_attr option
val get_ce_safe_global_variable : class_elt -> bool
val make_ce_flags :
xhp_attr:xhp_attr option ->
abstract:bool ->
final:bool ->
superfluous_override:bool ->
lsb:bool ->
synthesized:bool ->
const:bool ->
lateinit:bool ->
dynamicallycallable:bool ->
readonly_prop:bool ->
support_dynamic_type:bool ->
needs_init:bool ->
safe_global_variable:bool ->
Typing_defs_flags.ClassElt.t
val class_elt_is_private_not_lsb : class_elt -> bool
val class_elt_is_private_or_protected_not_lsb : class_elt -> bool
val error_Tunapplied_alias_in_illegal_context : unit -> 'a
val is_typeconst_type_abstract : typeconst_type -> bool
module Attributes : sig
val mem : string -> user_attribute Hh_prelude.List.t -> bool
val find : string -> user_attribute Hh_prelude.List.t -> user_attribute option
end |
OCaml | hhvm/hphp/hack/src/typing/typing_defs_core.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module Reason = Typing_reason
type pos_id = Reason.pos_id [@@deriving eq, hash, ord, show]
type ce_visibility =
| Vpublic
| Vprivate of string
| Vprotected of string
(* When we construct `Vinternal`, we are guaranteed to be inside a module *)
| Vinternal of string
[@@deriving eq, ord, show]
(* Represents <<__Policied()>> or <<__InferFlows>> attribute *)
type ifc_fun_decl =
| FDPolicied of string option
| FDInferFlows
[@@deriving eq, hash, ord]
type cross_package_decl = string option [@@deriving eq, hash, ord]
(* The default policy is the public one. PUBLIC is a keyword, so no need to prevent class collisions *)
let default_ifc_fun_decl = FDPolicied (Some "PUBLIC")
(* All the possible types, reason is a trace of why a type
was inferred in a certain way.
Types exists in two phases. Phase one is 'decl', meaning it is a type that
was declared in user code. Phase two is 'locl', meaning it is a type that is
inferred via local inference.
*)
(* create private types to represent the different type phases *)
type decl_phase = Reason.decl_phase [@@deriving eq, hash, show]
type locl_phase = Reason.locl_phase [@@deriving eq, hash, show]
type val_kind =
| Lval
| LvalSubexpr
| Other
[@@deriving eq]
type fun_tparams_kind =
| FTKtparams
(** If ft_tparams is empty, the containing fun_type is a concrete function type.
Otherwise, it is a generic function and ft_tparams specifies its type parameters. *)
| FTKinstantiated_targs
(** The containing fun_type is a concrete function type which is an
instantiation of a generic function with at least one reified type
parameter. This means that the function requires explicit type arguments
at every invocation, and ft_tparams specifies the type arguments with
which the generic function was instantiated, as well as whether each
explicit type argument must be reified. *)
[@@deriving eq]
type type_origin =
| Missing_origin
| From_alias of string
[@@deriving eq, hash, ord, show]
type pos_string = Pos_or_decl.t * string [@@deriving eq, hash, ord, show]
(* Trick the Rust generators to use a BStr, the same way it does for Ast_defs.shape_field_name. *)
type t_byte_string = string [@@deriving eq, hash, ord, show]
type pos_byte_string = Pos_or_decl.t * t_byte_string
[@@deriving eq, hash, ord, show]
type tshape_field_name =
| TSFlit_int of pos_string
| TSFlit_str of pos_byte_string
| TSFclass_const of pos_id * pos_string
[@@deriving eq, hash, ord, show]
module TShapeField = struct
type t = tshape_field_name [@@deriving hash]
let pos : t -> Pos_or_decl.t = function
| TSFlit_int (p, _)
| TSFlit_str (p, _) ->
p
| TSFclass_const ((cls_pos, _), (mem_pos, _)) ->
Pos_or_decl.btw cls_pos mem_pos
let name = function
| TSFlit_int (_, s)
| TSFlit_str (_, s) ->
s
| TSFclass_const ((_, s1), (_, s2)) -> s1 ^ "::" ^ s2
let of_ast : (Pos.t -> Pos_or_decl.t) -> Ast_defs.shape_field_name -> t =
fun convert_pos -> function
| Ast_defs.SFlit_int (p, s) -> TSFlit_int (convert_pos p, s)
| Ast_defs.SFlit_str (p, s) -> TSFlit_str (convert_pos p, s)
| Ast_defs.SFclass_const ((pcls, cls), (pconst, const)) ->
TSFclass_const ((convert_pos pcls, cls), (convert_pos pconst, const))
(* We include span information in shape_field_name to improve error
* messages, but we don't want it being used in the comparison, so
* we have to write our own compare. *)
let compare x y =
match (x, y) with
| (TSFlit_int (_, s1), TSFlit_int (_, s2)) -> String.compare s1 s2
| (TSFlit_str (_, s1), TSFlit_str (_, s2)) -> String.compare s1 s2
| (TSFclass_const ((_, s1), (_, s1')), TSFclass_const ((_, s2), (_, s2')))
->
Core.Tuple.T2.compare
~cmp1:String.compare
~cmp2:String.compare
(s1, s1')
(s2, s2')
| (TSFlit_int _, _) -> -1
| (TSFlit_str _, TSFlit_int _) -> 1
| (TSFlit_str _, _) -> -1
| (TSFclass_const _, _) -> 1
let equal x y = Core.Int.equal 0 (compare x y)
end
module TShapeMap = struct
include WrappedMap.Make (TShapeField)
let map_and_rekey m f1 f2 =
fold (fun k v acc -> add (f1 k) (f2 v) acc) m empty
let pp
(pp_val : Format.formatter -> 'a -> unit)
(fmt : Format.formatter)
(map : 'a t) : unit =
make_pp pp_tshape_field_name pp_val fmt map
let hash_fold_t x = make_hash_fold_t TShapeField.hash_fold_t x
end
module TShapeSet = Caml.Set.Make (TShapeField)
type param_mode =
| FPnormal
| FPinout
[@@deriving eq, show]
type xhp_attr = Xhp_attribute.t [@@deriving eq, show]
(** Denotes the categories of requirements we apply to constructor overrides.
*
* In the default case, we use Inconsistent. If a class has <<__ConsistentConstruct>>,
* or if it inherits a class that has <<__ConsistentConstruct>>, we use inherited.
* If we have a new final class that doesn't extend from <<__ConsistentConstruct>>,
* then we use Final. Only classes that are Inconsistent or Final can have reified
* generics. *)
type consistent_kind =
| Inconsistent
| ConsistentConstruct
| FinalClass
[@@deriving eq, show]
type dependent_type =
(* A reference to some expression. For example:
*
* $x->foo()
*
* The expression $x would have a reference Ident.t
* The expression $x->foo() would have a different one
*)
| DTexpr of Ident.t
[@@deriving eq, hash, ord, show]
type user_attribute_param =
| Classname of string
| EnumClassLabel of string
| String of t_byte_string
| Int of string
[@@deriving eq, hash, show]
type user_attribute = {
ua_name: pos_id;
ua_params: user_attribute_param list;
}
[@@deriving eq, hash, show]
type 'ty tparam = {
tp_variance: Ast_defs.variance;
tp_name: pos_id;
tp_tparams: 'ty tparam list;
tp_constraints: (Ast_defs.constraint_kind * 'ty) list;
tp_reified: Ast_defs.reify_kind;
tp_user_attributes: user_attribute list;
}
[@@deriving eq, hash, show]
type 'ty where_constraint = 'ty * Ast_defs.constraint_kind * 'ty
[@@deriving eq, hash, show]
type enforcement =
| Unenforced
| Enforced
[@@deriving eq, hash, show, ord]
(* This is to avoid a compile error with ppx_hash "Unbound value _hash_fold_phase". *)
let _hash_fold_phase hsv _ = hsv
type 'phase ty = 'phase Reason.t_ * 'phase ty_
and decl_ty = decl_phase ty
and locl_ty = locl_phase ty
and neg_type =
| Neg_prim of Ast_defs.tprim
| Neg_class of pos_id
(** A shape may specify whether or not fields are required. For example, consider
* this typedef:
*
* ```
* type ShapeWithOptionalField = shape(?'a' => ?int);
* ```
*
* With this definition, the field 'a' may be unprovided in a shape. In this
* case, the field 'a' would have sf_optional set to true.
*)
and 'phase shape_field_type = {
sft_optional: bool;
sft_ty: 'phase ty;
}
and _ ty_ =
(*========== Following Types Exist Only in the Declared Phase ==========*)
| Tthis : decl_phase ty_ (** The late static bound type of a class *)
| Tapply : pos_id * decl_ty list -> decl_phase ty_
(** Either an object type or a type alias, ty list are the arguments *)
| Trefinement : decl_ty * decl_phase class_refinement -> decl_phase ty_
(** 'With' refinements of the form `_ with { type T as int; type TC = C; }`. *)
| Tmixed : decl_phase ty_
(** "Any" is the type of a variable with a missing annotation, and "mixed" is
* the type of a variable annotated as "mixed". THESE TWO ARE VERY DIFFERENT!
* Any unifies with anything, i.e., it is both a supertype and subtype of any
* other type. You can do literally anything to it; it's the "trust me" type.
* Mixed, on the other hand, is only a supertype of everything. You need to do
* a case analysis to figure out what it is (i.e., its elimination form).
*
* Here's an example to demonstrate:
*
* ```
* function f($x): int {
* return $x + 1;
* }
* ```
*
* In that example, $x has type Tany. This unifies with anything, so adding
* one to it is allowed, and returning that as int is allowed.
*
* In contrast, if $x were annotated as mixed, adding one to that would be
* a type error -- mixed is not a subtype of int, and you must be a subtype
* of int to take part in addition. (The converse is true though -- int is a
* subtype of mixed.) A case analysis would need to be done on $x, via
* is_int or similar.
*
* mixed exists only in the decl_phase phase because it is desugared into ?nonnull
* during the localization phase.
*)
| Twildcard : decl_phase ty_
(** Various intepretations, depending on context.
* inferred type e.g. (vec<_> $x) ==> $x[0]
* placeholder in refinement e.g. $x as Vector<_>
* placeholder for higher-kinded formal type parameter e.g. foo<T1<_>>(T1<int> $_)
*)
| Tlike : decl_ty -> decl_phase ty_
(*========== Following Types Exist in Both Phases ==========*)
| Tany : TanySentinel.t -> 'phase ty_
| Tnonnull
| Tdynamic
(** A dynamic type is a special type which sometimes behaves as if it were a
* top type; roughly speaking, where a specific value of a particular type is
* expected and that type is dynamic, anything can be given. We call this
* behaviour "coercion", in that the types "coerce" to dynamic. In other ways it
* behaves like a bottom type; it can be used in any sort of binary expression
* or even have object methods called from it. However, it is in fact neither.
*
* it captures dynamicism within function scope.
* See tests in typecheck/dynamic/ for more examples.
*)
| Toption : 'phase ty -> 'phase ty_
(** Nullable, called "option" in the ML parlance. *)
| Tprim : Ast_defs.tprim -> 'phase ty_
(** All the primitive types: int, string, void, etc. *)
| Tfun : 'phase ty fun_type -> 'phase ty_
(** A wrapper around fun_type, which contains the full type information for a
* function, method, lambda, etc. *)
| Ttuple : 'phase ty list -> 'phase ty_
(** Tuple, with ordered list of the types of the elements of the tuple. *)
| Tshape : 'phase shape_type -> 'phase ty_
| Tgeneric : string * 'phase ty list -> 'phase ty_
(** The type of a generic parameter. The constraints on a generic parameter
* are accessed through the lenv.tpenv component of the environment, which
* is set up when checking the body of a function or method. See uses of
* Typing_phase.add_generic_parameters_and_constraints. The list denotes
* type arguments.
*)
| Tunion : 'phase ty list -> 'phase ty_
(** Union type.
* The values that are members of this type are the union of the values
* that are members of the components of the union.
* Some examples (writing | for binary union)
* Tunion [] is the "nothing" type, with no values
* Tunion [int;float] is the same as num
* Tunion [null;t] is the same as Toption t
*)
| Tintersection : 'phase ty list -> 'phase ty_
| Tvec_or_dict : 'phase ty * 'phase ty -> 'phase ty_
(** Tvec_or_dict (ty1, ty2) => "vec_or_dict<ty1, ty2>" *)
| Taccess : 'phase taccess_type -> 'phase ty_
(** Name of class, name of type const, remaining names of type consts *)
| Tnewtype : string * 'phase ty list * 'phase ty -> 'phase ty_
(** The type of an opaque type or enum. Outside their defining files or
* when they represent enums, they are "opaque", which means that they
* only unify with themselves. Within a file, uses of newtypes are
* expanded to their definitions (unless the newtype is an enum).
*
* However, it is possible to have a constraint that allows us to relax
* opaqueness. For example:
*
* newtype MyType as int = ...
*
* or
*
* enum MyType: int as int { ... }
*
* Outside of the file where the type was defined, this translates to:
*
* Tnewtype ((pos, "MyType"), [], Tprim Tint)
*
* which means that MyType is abstract, but is a subtype of int as well.
* When the constraint is omitted, the third parameter is set to mixed.
*
* The second parameter is the list of type arguments to the type.
*)
(*========== Below Are Types That Cannot Be Declared In User Code ==========*)
| Tvar : Ident.t -> locl_phase ty_
| Tunapplied_alias : string -> locl_phase ty_
(** This represents a type alias that lacks necessary type arguments. Given
type Foo<T1,T2> = ...
Tunappliedalias "Foo" stands for usages of plain Foo, without supplying
further type arguments. In particular, Tunappliedalias always stands for
a higher-kinded type. It is never used for an alias like
type Foo2 = ...
that simply doesn't require type arguments. *)
| Tdependent : dependent_type * locl_ty -> locl_phase ty_
(** see dependent_type *)
| Tclass : pos_id * exact * locl_ty list -> locl_phase ty_
(** An instance of a class or interface, ty list are the arguments
* If exact=Exact, then this represents instances of *exactly* this class
* If exact=Nonexact, this also includes subclasses
*)
| Tneg : neg_type -> locl_phase ty_
(** The negation of the type in neg_type *)
and 'phase taccess_type = 'phase ty * pos_id
and exact =
| Exact
| Nonexact of locl_phase class_refinement
and 'phase class_refinement = { cr_consts: 'phase refined_const SMap.t }
and 'phase refined_const = {
rc_bound: 'phase refined_const_bound;
rc_is_ctx: bool;
}
and 'phase refined_const_bound =
| TRexact : 'phase ty -> 'phase refined_const_bound
| TRloose : 'phase refined_const_bounds -> 'phase refined_const_bound
and 'phase refined_const_bounds = {
tr_lower: 'phase ty list;
tr_upper: 'phase ty list;
}
(** Whether all fields of this shape are known, types of each of the
* known arms.
*)
and 'phase shape_type = {
s_origin: type_origin;
s_unknown_value: 'phase ty;
s_fields: 'phase shape_field_type TShapeMap.t;
}
and 'ty capability =
| CapDefaults of Pos_or_decl.t
| CapTy of 'ty
(** Companion to fun_params type, intended to consolidate checking of
* implicit params for functions. *)
and 'ty fun_implicit_params = { capability: 'ty capability }
(** The type of a function AND a method. *)
and 'ty fun_type = {
ft_tparams: 'ty tparam list;
ft_where_constraints: 'ty where_constraint list;
ft_params: 'ty fun_params;
ft_implicit_params: 'ty fun_implicit_params;
ft_ret: 'ty possibly_enforced_ty;
(** Carries through the sync/async information from the aast *)
ft_flags: Typing_defs_flags.fun_type_flags;
ft_ifc_decl: ifc_fun_decl;
ft_cross_package: cross_package_decl;
}
and 'ty possibly_enforced_ty = {
et_enforced: enforcement;
(** True if consumer of this type enforces it at runtime *)
et_type: 'ty;
}
and 'ty fun_param = {
fp_pos: Pos_or_decl.t;
fp_name: string option;
fp_type: 'ty possibly_enforced_ty;
fp_flags: Typing_defs_flags.fun_param_flags;
}
and 'ty fun_params = 'ty fun_param list [@@deriving hash]
let nonexact = Nonexact { cr_consts = SMap.empty }
let is_nonexact = function
| Nonexact _ -> true
| Exact -> false
let refined_const_kind_str : type a. a refined_const -> string =
fun { rc_is_ctx; _ } ->
if rc_is_ctx then
"ctx"
else
"type"
module Flags = struct
open Typing_defs_flags
let get_ft_return_disposable ft =
is_set ft.ft_flags ft_flags_return_disposable
let get_ft_returns_readonly ft = is_set ft.ft_flags ft_flags_returns_readonly
let get_ft_readonly_this ft = is_set ft.ft_flags ft_flags_readonly_this
let get_ft_async ft = is_set ft.ft_flags ft_flags_async
let get_ft_generator ft = is_set ft.ft_flags ft_flags_generator
let get_ft_support_dynamic_type ft =
is_set ft.ft_flags ft_flags_support_dynamic_type
(* This flag is set true only if the exact method has the memoized attribute. *)
let get_ft_is_memoized ft = is_set ft.ft_flags ft_flags_is_memoized
let get_ft_ftk ft =
if is_set ft.ft_flags ft_flags_instantiated_targs then
FTKinstantiated_targs
else
FTKtparams
let set_ft_ftk ft ftk =
{
ft with
ft_flags =
set_bit
ft_flags_instantiated_targs
(match ftk with
| FTKinstantiated_targs -> true
| FTKtparams -> false)
ft.ft_flags;
}
let set_ft_is_function_pointer ft is_fp =
{
ft with
ft_flags = set_bit ft_flags_is_function_pointer is_fp ft.ft_flags;
}
let set_ft_readonly_this ft readonly_this =
{
ft with
ft_flags = set_bit ft_flags_readonly_this readonly_this ft.ft_flags;
}
let set_ft_returns_readonly ft readonly_return =
{
ft with
ft_flags = set_bit ft_flags_returns_readonly readonly_return ft.ft_flags;
}
let get_ft_is_function_pointer ft =
is_set ft.ft_flags ft_flags_is_function_pointer
let get_ft_variadic ft = is_set ft.ft_flags ft_flags_variadic
let get_ft_fun_kind ft =
match (get_ft_async ft, get_ft_generator ft) with
| (false, false) -> Ast_defs.FSync
| (true, false) -> Ast_defs.FAsync
| (false, true) -> Ast_defs.FGenerator
| (true, true) -> Ast_defs.FAsyncGenerator
let get_fp_ifc_external fp = is_set fp.fp_flags fp_flags_ifc_external
let get_fp_ifc_can_call fp = is_set fp.fp_flags fp_flags_ifc_can_call
let get_fp_readonly fp = is_set fp.fp_flags fp_flags_readonly
let fun_kind_to_flags kind =
match kind with
| Ast_defs.FSync -> 0
| Ast_defs.FAsync -> ft_flags_async
| Ast_defs.FGenerator -> ft_flags_generator
| Ast_defs.FAsyncGenerator -> Int.bit_or ft_flags_async ft_flags_generator
let make_ft_flags
kind
~return_disposable
~returns_readonly
~readonly_this
~support_dynamic_type
~is_memoized
~variadic =
let flags = fun_kind_to_flags kind in
let flags = set_bit ft_flags_return_disposable return_disposable flags in
let flags = set_bit ft_flags_returns_readonly returns_readonly flags in
let flags = set_bit ft_flags_readonly_this readonly_this flags in
let flags =
set_bit ft_flags_support_dynamic_type support_dynamic_type flags
in
let flags = set_bit ft_flags_is_memoized is_memoized flags in
let flags = set_bit ft_flags_variadic variadic flags in
flags
let mode_to_flags mode =
match mode with
| FPnormal -> 0x0
| FPinout -> fp_flags_inout
let make_fp_flags
~mode
~accept_disposable
~has_default
~ifc_external
~ifc_can_call
~readonly =
let flags = mode_to_flags mode in
let flags = set_bit fp_flags_accept_disposable accept_disposable flags in
let flags = set_bit fp_flags_has_default has_default flags in
let flags = set_bit fp_flags_ifc_external ifc_external flags in
let flags = set_bit fp_flags_ifc_can_call ifc_can_call flags in
let flags = set_bit fp_flags_readonly readonly flags in
flags
let get_fp_accept_disposable fp =
is_set fp.fp_flags fp_flags_accept_disposable
let get_fp_has_default fp = is_set fp.fp_flags fp_flags_has_default
let get_fp_mode fp =
if is_set fp.fp_flags fp_flags_inout then
FPinout
else
FPnormal
end
include Flags
module Pp = struct
let rec pp_ty : type a. Format.formatter -> a ty -> unit =
fun fmt t ->
let (a0, a1) = t in
Format.fprintf fmt "(@[";
Reason.pp fmt a0;
Format.fprintf fmt ",@ ";
pp_ty_ fmt a1;
Format.fprintf fmt "@])"
and pp_neg_type : Format.formatter -> neg_type -> unit =
fun fmt neg_ty ->
match neg_ty with
| Neg_prim tp ->
Format.fprintf fmt "(@[<2>Neg_prim@ ";
Aast.pp_tprim fmt tp;
Format.fprintf fmt "@])"
| Neg_class c ->
Format.fprintf fmt "(@[<2>Neg_class ";
pp_pos_id fmt c;
Format.fprintf fmt "@])"
and pp_ty_ : type a. Format.formatter -> a ty_ -> unit =
fun fmt ty ->
match ty with
| Tany _ -> Format.pp_print_string fmt "Tany"
| Tthis -> Format.pp_print_string fmt "Tthis"
| Tmixed -> Format.pp_print_string fmt "Tmixed"
| Twildcard -> Format.pp_print_string fmt "Twildcard"
| Tdynamic -> Format.pp_print_string fmt "Tdynamic"
| Tnonnull -> Format.pp_print_string fmt "Tnonnull"
| Tapply (a0, a1) ->
Format.fprintf fmt "(@[<2>Tapply (@,";
let () = pp_pos_id fmt a0 in
Format.fprintf fmt ",@ ";
pp_list pp_ty fmt a1;
Format.fprintf fmt "@,))@]"
| Trefinement (a0, a1) ->
Format.fprintf fmt "(@[<2>Trefinement (@,";
pp_ty fmt a0;
Format.fprintf fmt ",@ ";
pp_class_refinement fmt a1;
Format.fprintf fmt "@,))@]"
| Tgeneric (a0, a1) ->
Format.fprintf fmt "(@[<2>Tgeneric (@,";
Format.fprintf fmt "%S" a0;
Format.fprintf fmt ",@ ";
pp_list pp_ty fmt a1;
Format.fprintf fmt "@,)@])"
| Tunapplied_alias a0 ->
Format.fprintf fmt "(@[<2>Tunappliedalias@ ";
Format.fprintf fmt "%S" a0;
Format.fprintf fmt "@])"
| Taccess a0 ->
Format.fprintf fmt "(@[<2>Taccess@ ";
pp_taccess_type fmt a0;
Format.fprintf fmt "@])"
| Tvec_or_dict (a0, a1) ->
Format.fprintf fmt "(@[<2>Tvec_or_dict@ ";
pp_ty fmt a0;
Format.fprintf fmt ",@ ";
pp_ty fmt a1;
Format.fprintf fmt "@])"
| Toption a0 ->
Format.fprintf fmt "(@[<2>Toption@ ";
pp_ty fmt a0;
Format.fprintf fmt "@])"
| Tlike a0 ->
Format.fprintf fmt "(@[<2>Tlike@ ";
pp_ty fmt a0;
Format.fprintf fmt "@])"
| Tprim a0 ->
Format.fprintf fmt "(@[<2>Tprim@ ";
Aast.pp_tprim fmt a0;
Format.fprintf fmt "@])"
| Tfun a0 ->
Format.fprintf fmt "(@[<2>Tfun@ ";
pp_fun_type fmt a0;
Format.fprintf fmt "@])"
| Ttuple a0 ->
Format.fprintf fmt "(@[<2>Ttuple@ ";
pp_list pp_ty fmt a0;
Format.fprintf fmt "@])"
| Tshape a0 ->
Format.fprintf fmt "(@[<2>Tshape@ ";
pp_shape_type fmt a0;
Format.fprintf fmt "@])"
| Tvar a0 ->
Format.fprintf fmt "(@[<2>Tvar@ ";
Ident.pp fmt a0;
Format.fprintf fmt "@])"
| Tnewtype (a0, a1, a2) ->
Format.fprintf fmt "(@[<2>Tnewtype (@,";
Format.fprintf fmt "%S" a0;
Format.fprintf fmt ",@ ";
pp_list pp_ty fmt a1;
Format.fprintf fmt ",@ ";
pp_ty fmt a2;
Format.fprintf fmt "@,))@]"
| Tdependent (a0, a1) ->
Format.fprintf fmt "(@[<2>Tdependent@ ";
pp_dependent_type fmt a0;
Format.fprintf fmt ",@ ";
pp_ty fmt a1;
Format.fprintf fmt "@])"
| Tunion tyl ->
Format.fprintf fmt "(@[<2>Tunion@ ";
pp_list pp_ty fmt tyl;
Format.fprintf fmt "@])"
| Tintersection tyl ->
Format.fprintf fmt "(@[<2>Tintersection@ ";
pp_list pp_ty fmt tyl;
Format.fprintf fmt "@])"
| Tclass (a0, a2, a1) ->
Format.fprintf fmt "(@[<2>Tclass (@,";
pp_pos_id fmt a0;
Format.fprintf fmt ",@ ";
pp_exact fmt a2;
Format.fprintf fmt ",@ ";
pp_list pp_ty fmt a1;
Format.fprintf fmt "@,))@]"
| Tneg a0 ->
Format.fprintf fmt "(@[<2>Tneg@ ";
pp_neg_type fmt a0;
Format.fprintf fmt "@])"
and pp_list :
type a.
(Format.formatter -> a -> unit) -> Format.formatter -> a list -> unit =
fun pp_elem fmt l ->
Format.fprintf fmt "@[<2>[";
ignore
(List.fold_left
~f:(fun sep x ->
if sep then Format.fprintf fmt ";@ ";
pp_elem fmt x;
true)
~init:false
l);
Format.fprintf fmt "@,]@]"
and pp_refined_const : type a. Format.formatter -> a refined_const -> unit =
fun fmt { rc_bound; rc_is_ctx } ->
Format.fprintf fmt "@[<2>{";
Format.fprintf fmt "rc_bound = ";
(match rc_bound with
| TRexact exact ->
Format.fprintf fmt "TRexact ";
pp_ty fmt exact
| TRloose { tr_lower = lower; tr_upper = upper } ->
Format.fprintf fmt "TRloose @[<2>{";
Format.pp_print_string fmt "tr_lower = ";
pp_list pp_ty fmt lower;
Format.fprintf fmt ";@ ";
Format.pp_print_string fmt "tr_upper = ";
pp_list pp_ty fmt upper);
Format.fprintf fmt ";@ ";
Format.fprintf fmt "rc_is_ctx = %B" rc_is_ctx;
Format.fprintf fmt "}@]"
and pp_class_refinement :
type a. Format.formatter -> a class_refinement -> unit =
fun fmt { cr_consts } ->
Format.fprintf fmt "@[<2>{";
Format.fprintf fmt "cr_consts = ";
SMap.pp pp_refined_const fmt cr_consts;
Format.fprintf fmt ";@ ";
Format.fprintf fmt "}@]"
and pp_exact fmt e =
match e with
| Exact -> Format.pp_print_string fmt "Exact"
| Nonexact cr ->
Format.pp_print_string fmt "Nonexact ";
pp_class_refinement fmt cr
and pp_taccess_type : type a. Format.formatter -> a taccess_type -> unit =
fun fmt (a0, a1) ->
Format.fprintf fmt "(@[";
pp_ty fmt a0;
Format.fprintf fmt ",@ ";
Format.fprintf fmt "@[<2>[";
pp_pos_id fmt a1;
Format.fprintf fmt "@,]@]";
Format.fprintf fmt "@])"
and pp_possibly_enforced_ty :
type a. Format.formatter -> a ty possibly_enforced_ty -> unit =
fun fmt x ->
Format.fprintf fmt "@[<2>{ ";
Format.fprintf fmt "@[%s =@ " "et_enforced";
Format.fprintf fmt "%a" pp_enforcement x.et_enforced;
Format.fprintf fmt "@]";
Format.fprintf fmt ";@ ";
Format.fprintf fmt "@[%s =@ " "et_type";
pp_ty fmt x.et_type;
Format.fprintf fmt "@]";
Format.fprintf fmt "@ }@]"
and pp_capability : type a. Format.formatter -> a ty capability -> unit =
fun fmt -> function
| CapTy ty ->
Format.pp_print_string fmt "(CapTy ";
pp_ty fmt ty;
Format.pp_print_string fmt ")"
| CapDefaults pos ->
Format.pp_print_string fmt "(CapDefaults ";
Pos_or_decl.pp fmt pos;
Format.pp_print_string fmt ")"
and pp_fun_implicit_params :
type a. Format.formatter -> a ty fun_implicit_params -> unit =
fun fmt x ->
Format.fprintf fmt "@[<2>{ ";
Format.fprintf fmt "@[%s =@ " "capability";
pp_capability fmt x.capability;
Format.fprintf fmt "@]";
Format.fprintf fmt "@ }@]"
and pp_shape_field_type :
type a. Format.formatter -> a shape_field_type -> unit =
fun fmt x ->
Format.fprintf fmt "@[<2>{ ";
Format.fprintf fmt "@[%s =@ " "sft_optional";
Format.fprintf fmt "%B" x.sft_optional;
Format.fprintf fmt "@]";
Format.fprintf fmt ";@ ";
Format.fprintf fmt "@[%s =@ " "sft_ty";
pp_ty fmt x.sft_ty;
Format.fprintf fmt "@]";
Format.fprintf fmt "@ }@]"
and pp_ifc_fun_decl : Format.formatter -> ifc_fun_decl -> unit =
fun fmt r ->
match r with
| FDInferFlows -> Format.pp_print_string fmt "FDInferFlows"
| FDPolicied None -> Format.pp_print_string fmt "FDPolicied {}"
| FDPolicied (Some s) ->
Format.pp_print_string fmt "FDPolicied {";
Format.pp_print_string fmt s;
Format.pp_print_string fmt "}"
and pp_cross_package_decl : Format.formatter -> cross_package_decl -> unit =
fun fmt r ->
match r with
| Some s ->
Format.pp_print_string fmt "CrossPackage(";
Format.pp_print_string fmt s;
Format.pp_print_string fmt ")"
| None -> Format.pp_print_string fmt "None"
and pp_shape_type : type a. Format.formatter -> a shape_type -> unit =
fun fmt x ->
Format.fprintf fmt "@[<2>{ ";
Format.fprintf fmt "@[%s =@ " "s_origin";
pp_type_origin fmt x.s_origin;
Format.fprintf fmt "@]";
Format.fprintf fmt ";@ ";
Format.fprintf fmt "@[%s =@ " "s_fields";
TShapeMap.pp pp_shape_field_type fmt x.s_fields;
Format.fprintf fmt "@]";
Format.fprintf fmt ";@ ";
Format.fprintf fmt "@[%s =@ " "s_unknown_value";
pp_ty fmt x.s_unknown_value;
Format.fprintf fmt "@]";
Format.fprintf fmt "@ }@]"
and pp_fun_type : type a. Format.formatter -> a ty fun_type -> unit =
fun fmt x ->
Format.fprintf fmt "@[<2>{ ";
Format.fprintf fmt "@[%s =@ " "ft_tparams";
pp_list pp_tparam_ fmt x.ft_tparams;
Format.fprintf fmt "@]";
Format.fprintf fmt ";@ ";
Format.fprintf fmt "@[%s =@ " "ft_where_constraints";
pp_list pp_where_constraint_ fmt x.ft_where_constraints;
Format.fprintf fmt "@]";
Format.fprintf fmt ";@ ";
Format.fprintf fmt "@[%s =@ " "ft_params";
pp_list pp_fun_param fmt x.ft_params;
Format.fprintf fmt "@]";
Format.fprintf fmt ";@ ";
Format.fprintf fmt "@[%s =@ " "ft_implicit_params";
pp_fun_implicit_params fmt x.ft_implicit_params;
Format.fprintf fmt "@]";
Format.fprintf fmt ";@ ";
Format.fprintf fmt "@[%s =@ " "ft_ret";
pp_possibly_enforced_ty fmt x.ft_ret;
Format.fprintf fmt "@]";
Format.fprintf fmt ";@ ";
let pp_ft_flags fmt ft =
Format.fprintf fmt "@[<2>(%s@ " "make_ft_flags";
Format.fprintf fmt "@[";
Format.fprintf fmt "%s" (Ast_defs.show_fun_kind (get_ft_fun_kind ft));
Format.fprintf fmt "@]";
Format.fprintf fmt "@ ";
Format.fprintf fmt "@[~%s:" "return_disposable";
Format.fprintf fmt "%B" (get_ft_return_disposable ft);
Format.fprintf fmt "@]";
Format.fprintf fmt "@ ";
Format.fprintf fmt "@[~%s:" "returns_readonly";
Format.fprintf fmt "%B" (get_ft_returns_readonly ft);
Format.fprintf fmt "@]";
Format.fprintf fmt "@ ";
Format.fprintf fmt "@[~%s:" "support_dynamic_type";
Format.fprintf fmt "%B" (get_ft_support_dynamic_type ft);
Format.fprintf fmt "@]";
Format.fprintf fmt "@ ";
Format.fprintf fmt "@[~%s:" "readonly_this";
Format.fprintf fmt "%B" (get_ft_readonly_this ft);
Format.fprintf fmt "@]";
Format.fprintf fmt "@ ";
Format.fprintf fmt "@[~%s:" "is_memoized";
Format.fprintf fmt "%B" (get_ft_is_memoized ft);
Format.fprintf fmt "@]";
Format.fprintf fmt "@ ";
Format.fprintf fmt "@[~%s:" "variadic";
Format.fprintf fmt "%B" (get_ft_variadic ft);
Format.fprintf fmt "@]";
Format.fprintf fmt ")@]"
in
Format.fprintf fmt "@[%s =@ " "ft_flags";
pp_ft_flags fmt x;
Format.fprintf fmt "@]";
Format.fprintf fmt ";@ ";
Format.fprintf fmt "@[%s =@ " "ft_ifc_decl";
pp_ifc_fun_decl fmt x.ft_ifc_decl;
Format.fprintf fmt "@]";
Format.fprintf fmt ";@ ";
Format.fprintf fmt "@[%s =@ " "ft_cross_package";
pp_cross_package_decl fmt x.ft_cross_package;
Format.fprintf fmt "@]";
Format.fprintf fmt "@ }@]"
and pp_where_constraint_ :
type a. Format.formatter -> a ty where_constraint -> unit =
(fun fmt whcstr -> pp_where_constraint pp_ty fmt whcstr)
and pp_fun_param : type a. Format.formatter -> a ty fun_param -> unit =
let pp_fp_flags fmt fp =
Format.fprintf fmt "@[<2>(%s@ " "make_fp_flags";
Format.fprintf fmt "@[~%s:" "accept_disposable";
Format.fprintf fmt "%B" (get_fp_accept_disposable fp);
Format.fprintf fmt "@]";
Format.fprintf fmt "@ ";
Format.fprintf fmt "@[~%s:" "has_default";
Format.fprintf fmt "%B" (get_fp_has_default fp);
Format.fprintf fmt "@]";
Format.fprintf fmt "@ ";
Format.fprintf fmt "@[~%s:" "mode";
Format.fprintf fmt "%s" (show_param_mode (get_fp_mode fp));
Format.fprintf fmt "@]";
Format.fprintf fmt "@ ";
Format.fprintf fmt "@[~%s:" "ifc_external";
Format.fprintf fmt "%B" (get_fp_ifc_external fp);
Format.fprintf fmt "@]";
Format.fprintf fmt "@ ";
Format.fprintf fmt "@[~%s:" "ifc_can_call";
Format.fprintf fmt "%B" (get_fp_ifc_can_call fp);
Format.fprintf fmt "@]";
Format.fprintf fmt "@ ";
Format.fprintf fmt "@[~%s:" "readonly";
Format.fprintf fmt "%B" (get_fp_readonly fp);
Format.fprintf fmt "@]";
Format.fprintf fmt ")@]"
in
fun fmt x ->
Format.fprintf fmt "@[<2>{ ";
Format.fprintf fmt "@[%s =@ " "fp_pos";
Pos_or_decl.pp fmt x.fp_pos;
Format.fprintf fmt "@]";
Format.fprintf fmt ";@ ";
Format.fprintf fmt "@[%s =@ " "fp_name";
(match x.fp_name with
| None -> Format.pp_print_string fmt "None"
| Some x ->
Format.pp_print_string fmt "(Some ";
Format.fprintf fmt "%S" x;
Format.pp_print_string fmt ")");
Format.fprintf fmt "@]";
Format.fprintf fmt ";@ ";
Format.fprintf fmt "@[%s =@ " "fp_type";
pp_possibly_enforced_ty fmt x.fp_type;
Format.fprintf fmt "@]";
Format.fprintf fmt ";@ ";
Format.fprintf fmt "@[%s =@ " "fp_flags";
pp_fp_flags fmt x;
Format.fprintf fmt "@]";
Format.fprintf fmt ";@ ";
Format.fprintf fmt "@ }@]"
and pp_tparam_ : type a. Format.formatter -> a ty tparam -> unit =
(fun fmt tparam -> pp_tparam pp_ty fmt tparam)
let pp_possibly_enforced_ty :
type a.
(Format.formatter -> a ty -> unit) ->
Format.formatter ->
a ty possibly_enforced_ty ->
unit =
(fun _ fmt x -> pp_possibly_enforced_ty fmt x)
let pp_decl_ty : Format.formatter -> decl_ty -> unit =
(fun fmt ty -> pp_ty fmt ty)
let pp_locl_ty : Format.formatter -> locl_ty -> unit =
(fun fmt ty -> pp_ty fmt ty)
let show_ty : type a. a ty -> string = (fun x -> Format.asprintf "%a" pp_ty x)
let show_decl_ty x = show_ty x
let show_locl_ty x = show_ty x
end
include Pp
type decl_ty_ = decl_phase ty_
type locl_ty_ = locl_phase ty_
type decl_tparam = decl_ty tparam [@@deriving show]
type locl_tparam = locl_ty tparam
type decl_where_constraint = decl_ty where_constraint [@@deriving show]
type locl_where_constraint = locl_ty where_constraint
type decl_fun_type = decl_ty fun_type
type locl_fun_type = locl_ty fun_type
type decl_possibly_enforced_ty = decl_ty possibly_enforced_ty
type locl_possibly_enforced_ty = locl_ty possibly_enforced_ty [@@deriving show]
type decl_fun_param = decl_ty fun_param
type locl_fun_param = locl_ty fun_param
type decl_fun_params = decl_ty fun_params
type locl_fun_params = locl_ty fun_params
type decl_class_refinement = decl_phase class_refinement
type locl_class_refinement = locl_phase class_refinement
type decl_refined_const = decl_phase refined_const
type locl_refined_const = locl_phase refined_const
type destructure_kind =
| ListDestructure
| SplatUnpack
[@@deriving eq, ord, show]
type destructure = {
d_required: locl_ty list;
(** This represents the standard parameters of a function or the fields in a list
* destructuring assignment. Example:
*
* function take(bool $b, float $f = 3.14, arraykey ...$aks): void {}
* function f((bool, float, int, string) $tup): void {
* take(...$tup);
* }
*
* corresponds to the subtyping assertion
*
* (bool, float, int, string) <: splat([#1], [opt#2], ...#3)
*)
d_optional: locl_ty list;
(** Represents the optional parameters in a function, only used for splats *)
d_variadic: locl_ty option;
(** Represents a function's variadic parameter, also only used for splats *)
d_kind: destructure_kind;
(** list() destructuring allows for partial matches on lists, even when the operation
* might throw i.e. list($a) = vec[]; *)
}
[@@deriving show]
type has_member = {
hm_name: Nast.sid;
hm_type: locl_ty;
hm_class_id: Nast.class_id_; [@opaque]
(** This is required to check ambiguous object access, where sometimes
HHVM would access the private member of a parent class instead of the
one from the current class. *)
hm_explicit_targs: Nast.targ list option; [@opaque]
(* - For a "has-property" constraint, this is `None`
* - For a "has-method" constraint, this is `Some targs`, where targs
* is the list of explicit type arguments provided to the method call.
* Note that this list can be empty (i.e. `Some []`) in the case of a
* method not taking type arguments, or when we leave them implicit
*
* We need to know if this is a "has-property" or "has-method" to pass
* the correct `is_method` parameter to `Typing_object_get.obj_get`.
*)
}
[@@deriving show]
type can_index = {
ci_key: locl_ty;
ci_shape: tshape_field_name option;
ci_val: locl_ty;
ci_expr_pos: Pos.t;
ci_index_pos: Pos.t;
}
[@@deriving show]
type can_traverse = {
ct_key: locl_ty option;
ct_val: locl_ty;
ct_is_await: bool;
ct_reason: Reason.t;
}
[@@deriving show]
type has_type_member = {
htm_id: string;
htm_lower: locl_ty;
htm_upper: locl_ty;
}
[@@deriving show]
type constraint_type_ =
| Thas_member of has_member
| Thas_type_member of has_type_member
| Tcan_index of can_index
| Tcan_traverse of can_traverse
| Tdestructure of destructure
(** The type of container destructuring via list() or splat `...` *)
| TCunion of locl_ty * constraint_type
| TCintersection of locl_ty * constraint_type
and constraint_type = Reason.t * constraint_type_ [@@deriving show]
type internal_type =
| LoclType of locl_ty
| ConstraintType of constraint_type
[@@deriving show]
(* [@@deriving ord] doesn't support GADT. If we want to get
* rid of this one, we will have to write it *)
let compare_decl_ty : decl_ty -> decl_ty -> int = Stdlib.compare
(* Constructor and deconstructor functions for types and constraint types.
* Abstracting these lets us change the implementation, e.g. hash cons
*)
let mk p = p
let deref p = p
let get_reason (r, _) = r
let get_node (_, n) = n
let map_reason (r, ty) ~(f : _ Reason.t_ -> _ Reason.t_) = (f r, ty)
let map_ty : type ph. ph ty -> f:(ph ty_ -> ph ty_) -> ph ty =
(fun (r, ty) ~(f : _ ty_ -> _ ty_) -> (r, f ty))
let with_reason ty r = map_reason ty ~f:(fun _r -> r)
let get_pos t = Reason.to_pos (get_reason t)
let mk_constraint_type p = p
let deref_constraint_type p = p
let get_reason_i : internal_type -> Reason.t = function
| LoclType lty -> get_reason lty
| ConstraintType (r, _) -> r
(** Hack keyword for this visibility *)
let string_of_visibility : ce_visibility -> string = function
| Vpublic -> "public"
| Vprivate _ -> "private"
| Vprotected _ -> "protected"
| Vinternal _ -> "internal" |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_defs_core.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module Reason = Typing_reason
type pos_id = Reason.pos_id [@@deriving eq, ord, show]
type ce_visibility =
| Vpublic
| Vprivate of string
| Vprotected of string
(* When we construct `Vinternal`, we are guaranteed to be inside a module *)
| Vinternal of string
[@@deriving eq, ord, show]
type cross_package_decl = string option [@@deriving eq, ord]
(* Represents <<Policied()>> or <<InferFlows>> attribute *)
type ifc_fun_decl =
| FDPolicied of string option
| FDInferFlows
[@@deriving eq, ord]
val default_ifc_fun_decl : ifc_fun_decl
(* All the possible types, reason is a trace of why a type
was inferred in a certain way.
Types exists in two phases. Phase one is 'decl', meaning it is a type that
was declared in user code. Phase two is 'locl', meaning it is a type that is
inferred via local inference.
*)
(* create private types to represent the different type phases *)
type decl_phase = Typing_reason.decl_phase [@@deriving eq, show]
type locl_phase = Typing_reason.locl_phase [@@deriving eq, show]
type val_kind =
| Lval
| LvalSubexpr
| Other
[@@deriving eq]
type fun_tparams_kind =
| FTKtparams
(** If ft_tparams is empty, the containing fun_type is a concrete function type.
Otherwise, it is a generic function and ft_tparams specifies its type parameters. *)
| FTKinstantiated_targs
(** The containing fun_type is a concrete function type which is an
instantiation of a generic function with at least one reified type
parameter. This means that the function requires explicit type arguments
at every invocation, and ft_tparams specifies the type arguments with
which the generic function was instantiated, as well as whether each
explicit type argument must be reified. *)
[@@deriving eq]
(** The origin of a type is a succinct key that is unique to the
type containing it. Consequently, two types with the same
origin are necessarily identical. Any change to a type with
origin needs to come with a *reset* of its origin. For example,
all type mappers have to reset origins to [Missing_origin]. *)
type type_origin =
| Missing_origin
(** When we do not have any origin for the type. It is always
correct to use [Missing_origin]; so when in doubt, use it. *)
| From_alias of string
(** A type with origin [From_alias orig] is equivalent to
the expansion of the alias [orig]. *)
[@@deriving eq, ord, show]
type pos_string = Pos_or_decl.t * string [@@deriving eq, ord, show]
type pos_byte_string = Pos_or_decl.t * Ast_defs.byte_string
[@@deriving eq, ord, show]
(** This is similar to Aast.shape_field_name, but contains Pos_or_decl.t
instead of Pos.t. Aast.shape_field_name is used in shape expressions,
while this is used in shape types. *)
type tshape_field_name =
| TSFlit_int of pos_string
| TSFlit_str of pos_byte_string
| TSFclass_const of pos_id * pos_string
[@@deriving eq, ord, show]
(** This is similar to Aast.ShapeField, but contains Pos_or_decl.t
instead of Pos.t. Aast.ShapeField is used in shape expressions,
while this is used in shape types. *)
module TShapeField : sig
type t = tshape_field_name [@@deriving eq, ord]
val pos : t -> Pos_or_decl.t
val name : t -> string
val of_ast : (Pos.t -> Pos_or_decl.t) -> Ast_defs.shape_field_name -> t
end
(** This is similar to Ast_defs.ShapeMap, but contains Pos_or_decl.t
instead of Pos.t. Ast_defs.ShapeMap is used in shape expressions,
while this is used in shape types. *)
module TShapeMap : sig
include WrappedMap.S with type key = TShapeField.t
val pp : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit
val map_and_rekey : 'a t -> (key -> key) -> ('a -> 'b) -> 'b t
end
module TShapeSet : Caml.Set.S with type elt = TShapeField.t
type param_mode =
| FPnormal
| FPinout
[@@deriving eq, show]
type xhp_attr = Xhp_attribute.t [@@deriving eq, show]
(* Denotes the categories of requirements we apply to constructor overrides.
*
* In the default case, we use Inconsistent. If a class has <<__ConsistentConstruct>>,
* or if it inherits a class that has <<__ConsistentConstruct>>, we use inherited.
* If we have a new final class that doesn't extend from <<__ConsistentConstruct>>,
* then we use Final. Only classes that are Inconsistent or Final can have reified
* generics. *)
type consistent_kind =
| Inconsistent
| ConsistentConstruct
| FinalClass
[@@deriving eq, show]
type dependent_type =
(* A reference to some expression. For example:
*
* $x->foo()
*
* The expression $x would have a reference Ident.t
* The expression $x->foo() would have a different one
*)
| DTexpr of Ident.t
[@@deriving eq, ord, show]
type user_attribute_param =
| Classname of string
| EnumClassLabel of string
| String of Ast_defs.byte_string
| Int of string
[@@deriving eq, hash, show]
type user_attribute = {
ua_name: pos_id;
ua_params: user_attribute_param list;
}
[@@deriving eq, show]
type 'ty tparam = {
tp_variance: Ast_defs.variance;
tp_name: pos_id;
tp_tparams: 'ty tparam list;
tp_constraints: (Ast_defs.constraint_kind * 'ty) list;
tp_reified: Aast.reify_kind;
tp_user_attributes: user_attribute list;
}
[@@deriving eq, show]
type 'ty where_constraint = 'ty * Ast_defs.constraint_kind * 'ty
[@@deriving eq, show]
type enforcement =
(* The consumer doesn't enforce the type at runtime *)
| Unenforced
(* The consumer enforces the type at runtime *)
| Enforced
[@@deriving eq, show, ord]
(* = Reason.t * 'phase ty_ *)
type 'phase ty
and decl_ty = decl_phase ty
and locl_ty = locl_phase ty
(** Negation types represent the type of values that fail an `is` test
for either a primitive type, or a class-ish type C<_> *)
and neg_type =
| Neg_prim of Aast.tprim (** The negation of a primitive type *)
| Neg_class of pos_id
(** The negation of a class. If we think of types as denoting sets
of values, then (Neg_class C) is complement (Union tyl. C<tyl>), that is
all values that are not in C<t1, ..., tn> for any application of C to type
arguments. *)
(* A shape may specify whether or not fields are required. For example, consider
this typedef:
type ShapeWithOptionalField = shape(?'a' => ?int);
With this definition, the field 'a' may be unprovided in a shape. In this
case, the field 'a' would have sf_optional set to true.
*)
and 'phase shape_field_type = {
sft_optional: bool;
sft_ty: 'phase ty;
}
and _ ty_ =
(*========== Following Types Exist Only in the Declared Phase ==========*)
(* The late static bound type of a class *)
| Tthis : decl_phase ty_
(* Either an object type or a type alias, ty list are the arguments *)
| Tapply : pos_id * decl_ty list -> decl_phase ty_
| Trefinement : decl_ty * decl_phase class_refinement -> decl_phase ty_
(* "Any" is the type of a variable with a missing annotation, and "mixed" is
* the type of a variable annotated as "mixed". THESE TWO ARE VERY DIFFERENT!
* Any unifies with anything, i.e., it is both a supertype and subtype of any
* other type. You can do literally anything to it; it's the "trust me" type.
* Mixed, on the other hand, is only a supertype of everything. You need to do
* a case analysis to figure out what it is (i.e., its elimination form).
*
* Here's an example to demonstrate:
*
* function f($x): int {
* return $x + 1;
* }
*
* In that example, $x has type Tany. This unifies with anything, so adding
* one to it is allowed, and returning that as int is allowed.
*
* In contrast, if $x were annotated as mixed, adding one to that would be
* a type error -- mixed is not a subtype of int, and you must be a subtype
* of int to take part in addition. (The converse is true though -- int is a
* subtype of mixed.) A case analysis would need to be done on $x, via
* is_int or similar.
*
* mixed exists only in the decl_phase phase because it is desugared into ?nonnull
* during the localization phase.
*)
| Tmixed : decl_phase ty_
| Twildcard : decl_phase ty_
(** Various intepretations, depending on context.
* inferred type e.g. (vec<_> $x) ==> $x[0]
* placeholder in refinement e.g. $x as Vector<_>
* placeholder for higher-kinded formal type parameter e.g. foo<T1<_>>(T1<int> $_)
*)
| Tlike : decl_ty -> decl_phase ty_
(*========== Following Types Exist in Both Phases ==========*)
| Tany : TanySentinel.t -> 'phase ty_
| Tnonnull
(* A dynamic type is a special type which sometimes behaves as if it were a
* top type; roughly speaking, where a specific value of a particular type is
* expected and that type is dynamic, anything can be given. We call this
* behaviour "coercion", in that the types "coerce" to dynamic. In other ways it
* behaves like a bottom type; it can be used in any sort of binary expression
* or even have object methods called from it. However, it is in fact neither.
*
* it captures dynamicism within function scope.
* See tests in typecheck/dynamic/ for more examples.
*)
| Tdynamic
(* Nullable, called "option" in the ML parlance. *)
| Toption : 'phase ty -> 'phase ty_
(* All the primitive types: int, string, void, etc. *)
| Tprim : Aast.tprim -> 'phase ty_
(* A wrapper around fun_type, which contains the full type information for a
* function, method, lambda, etc. *)
| Tfun : 'phase ty fun_type -> 'phase ty_
(* Tuple, with ordered list of the types of the elements of the tuple. *)
| Ttuple : 'phase ty list -> 'phase ty_
(* A wrapper around shape_type, which contains information about shape fields *)
| Tshape : 'phase shape_type -> 'phase ty_
(* The type of a generic parameter. The constraints on a generic parameter
* are accessed through the lenv.tpenv component of the environment, which
* is set up when checking the body of a function or method. See uses of
* Typing_phase.add_generic_parameters_and_constraints. The list denotes
* type arguments (for higher-kinded generics).
*)
| Tgeneric : string * 'phase ty list -> 'phase ty_
(* Union type.
* The values that are members of this type are the union of the values
* that are members of the components of the union.
* Some examples (writing | for binary union)
* Tunion [] is the "nothing" type, with no values
* Tunion [int;float] is the same as num
* Tunion [null;t] is the same as Toption t
*)
| Tunion : 'phase ty list -> 'phase ty_
| Tintersection : 'phase ty list -> 'phase ty_
(* Tvec_or_dict (ty1, ty2) => "vec_or_dict<ty1, ty2>" *)
| Tvec_or_dict : 'phase ty * 'phase ty -> 'phase ty_
(* Name of class, name of type const, remaining names of type consts *)
| Taccess : 'phase taccess_type -> 'phase ty_
(* The type of an opaque type (e.g. a "newtype" outside of the file where it
* was defined) or enum. They are "opaque", which means that they only unify with
* themselves. However, it is possible to have a constraint that allows us to
* relax this. For example:
*
* newtype my_type as int = ...
*
* Outside of the file where the type was defined, this translates to:
*
* Tnewtype ((pos, "my_type"), [], Tprim Tint)
*
* Which means that my_type is abstract, but is subtype of int as well.
*)
| Tnewtype : string * 'phase ty list * 'phase ty -> 'phase ty_
(*========== Below Are Types That Cannot Be Declared In User Code ==========*)
| Tvar : Ident.t -> locl_phase ty_
(* This represents a type alias that lacks necessary type arguments. Given
* type Foo<T1,T2> = ...
* Tunappliedalias "Foo" stands for usages of plain Foo, without supplying
* further type arguments. In particular, Tunappliedalias always stands for
* a higher-kinded type. It is never used for an alias like
* type Foo2 = ...
* that simply doesn't require type arguments.
*)
| Tunapplied_alias : string -> locl_phase ty_
(* see dependent_type *)
| Tdependent : dependent_type * locl_ty -> locl_phase ty_
(* An instance of a class or interface, ty list are the arguments
* If exact=Exact, then this represents instances of *exactly* this class
* If exact=Nonexact, this also includes subclasses
*)
| Tclass : pos_id * exact * locl_ty list -> locl_phase ty_
| Tneg : neg_type -> locl_phase ty_
and exact =
| Exact
| Nonexact of locl_phase class_refinement
and 'phase class_refinement = { cr_consts: 'phase refined_const SMap.t }
and 'phase refined_const = {
rc_bound: 'phase refined_const_bound;
rc_is_ctx: bool;
}
and 'phase refined_const_bound =
| TRexact : 'phase ty -> 'phase refined_const_bound
| TRloose : 'phase refined_const_bounds -> 'phase refined_const_bound
and 'phase refined_const_bounds = {
tr_lower: 'phase ty list;
tr_upper: 'phase ty list;
}
and 'phase taccess_type = 'phase ty * pos_id
(* Whether all fields of this shape are known, types of each of the
* known arms. *)
and 'phase shape_type = {
s_origin: type_origin;
s_unknown_value: 'phase ty;
s_fields: 'phase shape_field_type TShapeMap.t;
}
(* Because Tfun is currently used as both a decl and locl ty, without this,
* the HH\Contexts\defaults alias must be stored in shared memory for a
* decl Tfun record. We can eliminate this if the majority of usages end up
* explicit or if we separate decl and locl Tfuns. *)
and 'ty capability =
| CapDefaults of Pos_or_decl.t (* Should not be used for lambda inference *)
| CapTy of 'ty
(** Companion to fun_params type, intended to consolidate checking of
* implicit params for functions. *)
and 'ty fun_implicit_params = { capability: 'ty capability }
(* The type of a function AND a method *)
and 'ty fun_type = {
ft_tparams: 'ty tparam list;
ft_where_constraints: 'ty where_constraint list;
ft_params: 'ty fun_params;
ft_implicit_params: 'ty fun_implicit_params;
ft_ret: 'ty possibly_enforced_ty;
(* Carries through the sync/async information from the aast *)
ft_flags: int;
ft_ifc_decl: ifc_fun_decl;
ft_cross_package: cross_package_decl;
}
and 'ty possibly_enforced_ty = {
et_enforced: enforcement;
et_type: 'ty;
}
and 'ty fun_param = {
fp_pos: Pos_or_decl.t;
fp_name: string option;
fp_type: 'ty possibly_enforced_ty;
fp_flags: int;
}
and 'ty fun_params = 'ty fun_param list [@@deriving hash]
val nonexact : exact
val is_nonexact : exact -> bool
val refined_const_kind_str : 'phase refined_const -> string
module Flags : sig
val get_ft_return_disposable : 'a fun_type -> bool
val get_ft_returns_readonly : 'a fun_type -> bool
val set_ft_returns_readonly : 'a fun_type -> bool -> 'a fun_type
val get_ft_async : 'a fun_type -> bool
val get_ft_generator : 'a fun_type -> bool
val get_ft_ftk : 'a fun_type -> fun_tparams_kind
val set_ft_ftk : 'a fun_type -> fun_tparams_kind -> 'a fun_type
val set_ft_is_function_pointer : 'a fun_type -> bool -> 'a fun_type
val get_ft_is_function_pointer : 'a fun_type -> bool
val get_ft_fun_kind : 'a fun_type -> Ast_defs.fun_kind
val get_ft_readonly_this : 'a fun_type -> bool
val set_ft_readonly_this : 'a fun_type -> bool -> 'a fun_type
val get_ft_support_dynamic_type : 'a fun_type -> bool
val get_ft_is_memoized : 'a fun_type -> bool
val get_ft_variadic : 'a fun_type -> bool
val get_fp_ifc_can_call : 'a fun_param -> bool
val get_fp_ifc_external : 'a fun_param -> bool
val get_fp_readonly : 'a fun_param -> bool
val fun_kind_to_flags : Ast_defs.fun_kind -> Hh_prelude.Int.t
val make_ft_flags :
Ast_defs.fun_kind ->
return_disposable:bool ->
returns_readonly:bool ->
readonly_this:bool ->
support_dynamic_type:bool ->
is_memoized:bool ->
variadic:bool ->
Hh_prelude.Int.t
val mode_to_flags : param_mode -> int
val make_fp_flags :
mode:param_mode ->
accept_disposable:bool ->
has_default:bool ->
ifc_external:bool ->
ifc_can_call:bool ->
readonly:bool ->
Hh_prelude.Int.t
val get_fp_accept_disposable : 'a fun_param -> bool
val get_fp_has_default : 'a fun_param -> bool
val get_fp_mode : 'a fun_param -> param_mode
end
include module type of Flags
module Pp : sig
val pp_ty : Format.formatter -> 'a ty -> unit
val pp_decl_ty : Format.formatter -> decl_ty -> unit
val pp_locl_ty : Format.formatter -> locl_ty -> unit
val pp_ty_ : Format.formatter -> 'a ty_ -> unit
val pp_taccess_type : Format.formatter -> 'a taccess_type -> unit
val pp_possibly_enforced_ty :
(Format.formatter -> 'a ty -> unit) ->
Format.formatter ->
'a ty possibly_enforced_ty ->
unit
val pp_fun_implicit_params :
Format.formatter -> 'a ty fun_implicit_params -> unit
val pp_shape_field_type : Format.formatter -> 'a shape_field_type -> unit
val pp_fun_type : Format.formatter -> 'a ty fun_type -> unit
val pp_fun_param : Format.formatter -> 'a ty fun_param -> unit
val show_decl_ty : decl_ty -> string
val show_locl_ty : locl_ty -> string
val pp_ifc_fun_decl : Format.formatter -> ifc_fun_decl -> unit
val pp_cross_package_decl : Format.formatter -> cross_package_decl -> unit
end
include module type of Pp
type decl_ty_ = decl_phase ty_
type locl_ty_ = locl_phase ty_
type decl_tparam = decl_ty tparam [@@deriving show]
type locl_tparam = locl_ty tparam
type decl_where_constraint = decl_ty where_constraint [@@deriving show]
type locl_where_constraint = locl_ty where_constraint
type decl_fun_type = decl_ty fun_type
type locl_fun_type = locl_ty fun_type
type decl_possibly_enforced_ty = decl_ty possibly_enforced_ty
type locl_possibly_enforced_ty = locl_ty possibly_enforced_ty [@@deriving show]
type decl_fun_param = decl_ty fun_param
type locl_fun_param = locl_ty fun_param
type decl_fun_params = decl_ty fun_params
type locl_fun_params = locl_ty fun_params
type decl_class_refinement = decl_phase class_refinement
type locl_class_refinement = locl_phase class_refinement
type decl_refined_const = decl_phase refined_const
type locl_refined_const = locl_phase refined_const
type has_member = {
hm_name: Nast.sid;
hm_type: locl_ty;
hm_class_id: Nast.class_id_;
(** This is required to check ambiguous object access, where sometimes
HHVM would access the private member of a parent class instead of the
one from the current class. *)
hm_explicit_targs: Nast.targ list option;
(* - For a "has-property" constraint, this is `None`
* - For a "has-method" constraint, this is `Some targs`, where targs
* is the list of explicit type arguments provided to the method call.
* Note that this list can be empty (i.e. `Some []`) in the case of a
* method not taking type arguments, or when we leave them implicit
*
* We need to know if this is a "has-property" or "has-method" to pass
* the correct `is_method` parameter to `Typing_object_get.obj_get`.
*)
}
[@@deriving show]
type destructure_kind =
| ListDestructure
| SplatUnpack
[@@deriving eq, ord, show]
type destructure = {
(* This represents the standard parameters of a function or the fields in a list
* destructuring assignment. Example:
*
* function take(bool $b, float $f = 3.14, arraykey ...$aks): void {}
* function f((bool, float, int, string) $tup): void {
* take(...$tup);
* }
*
* corresponds to the subtyping assertion
*
* (bool, float, int, string) <: splat([#1], [opt#2], ...#3)
*)
d_required: locl_ty list;
(* Represents the optional parameters in a function, only used for splats *)
d_optional: locl_ty list;
(* Represents a function's variadic parameter, also only used for splats *)
d_variadic: locl_ty option;
(* list() destructuring allows for partial matches on lists, even when the operation
* might throw i.e. list($a) = vec[]; *)
d_kind: destructure_kind;
}
[@@deriving show]
(* A can_index constraint represents the ability to do an array index operation.
* We should have t <: { ci_key; ci_shape; ci_val } when t is a type that supports
* being index with a value of type ci_key, and will return a value of ci_val. The
* ci_shape field is necessary because shapes (and tuples) are required to be
* indexed with certain literals, and so in those cases it is not sufficient to
* record simply the type of the index.
*)
type can_index = {
ci_key: locl_ty;
ci_shape: tshape_field_name option;
ci_val: locl_ty;
ci_expr_pos: Pos.t;
ci_index_pos: Pos.t;
}
[@@deriving show]
(* A can_traverse represents the ability to do a foreach over a certain type.
We should have t <: {ct_key; ct_val; ct_is_await} when type t supports foreach
and doing the foreack will bind values of type ct_val, and optionally bind keys of
type ct_key. *)
type can_traverse = {
ct_key: locl_ty option;
ct_val: locl_ty;
ct_is_await: bool;
ct_reason: Reason.t;
}
[@@deriving show]
type has_type_member = {
htm_id: string;
htm_lower: locl_ty;
htm_upper: locl_ty;
}
[@@deriving show]
(* = Reason.t * constraint_type_ *)
type constraint_type [@@deriving show]
type constraint_type_ =
| Thas_member of has_member
| Thas_type_member of has_type_member
(** [Thas_type_member('T',lo,hi)] is a supertype of all concrete class
types that have a type member [::T] satisfying [lo <: T <: hi] *)
| Tcan_index of can_index
| Tcan_traverse of can_traverse
| Tdestructure of destructure
(** The type of a list destructuring assignment.
Implements valid destructuring operations via subtyping. *)
| TCunion of locl_ty * constraint_type
| TCintersection of locl_ty * constraint_type
[@@deriving show]
type internal_type =
| LoclType of locl_ty
| ConstraintType of constraint_type
[@@deriving show]
(* Abstraction *)
val compare_decl_ty : decl_ty -> decl_ty -> int
val mk : 'phase Reason.t_ * 'phase ty_ -> 'phase ty
val deref : 'phase ty -> 'phase Reason.t_ * 'phase ty_
val get_reason : 'phase ty -> 'phase Reason.t_
val get_node : 'phase ty -> 'phase ty_
val with_reason : 'phase ty -> 'phase Reason.t_ -> 'phase ty
val get_pos : 'phase ty -> Pos_or_decl.t
val map_reason :
'phase ty -> f:('phase Reason.t_ -> 'phase Reason.t_) -> 'phase ty
val map_ty : 'ph ty -> f:('ph ty_ -> 'ph ty_) -> 'ph ty
val mk_constraint_type : Reason.t * constraint_type_ -> constraint_type
val deref_constraint_type : constraint_type -> Reason.t * constraint_type_
val get_reason_i : internal_type -> Reason.t
(** Hack keyword for this visibility *)
val string_of_visibility : ce_visibility -> string |
OCaml | hhvm/hphp/hack/src/typing/typing_defs_flags.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type flags = int
type bit_mask = int
(* Is this bit set in the flags? *)
let is_set (bit : bit_mask) (flags : flags) : bool =
not (Int.equal 0 (Int.bit_and bit flags))
(* Set a single bit to a boolean value *)
let set_bit bit value flags =
if value then
Int.bit_or bit flags
else
Int.bit_and (Int.bit_not bit) flags
type fun_type_flags = int [@@deriving hash]
type fun_param_flags = int [@@deriving hash]
module ClassElt : sig
type t [@@deriving show]
val make :
xhp_attr:Xhp_attribute.t option ->
abstract:bool ->
final:bool ->
superfluous_override:bool ->
lsb:bool ->
synthesized:bool ->
const:bool ->
lateinit:bool ->
dynamicallycallable:bool ->
readonly_prop:bool ->
support_dynamic_type:bool ->
needs_init:bool ->
safe_global_variable:bool ->
t
val is_abstract : t -> bool
val is_final : t -> bool
val has_superfluous_override : t -> bool
val has_lsb : t -> bool
(** Whether a class element comes from a `require extends`. *)
val is_synthesized : t -> bool
val is_const : t -> bool
val has_lateinit : t -> bool
val is_dynamicallycallable : t -> bool
val supports_dynamic_type : t -> bool
val is_readonly_prop : t -> bool
val needs_init : t -> bool
val is_safe_global_variable : t -> bool
val get_xhp_attr : t -> Xhp_attribute.t option
val set_synthesized : t -> t
val reset_superfluous_override : t -> t
end = struct
type t = flags
module Field = struct
type t =
| Abstract
| Final
| SuperfluousOverride
(** Whether the __Override attribute is erroneous, i.e. there is nothing in parents to override.
This is set during decling (because that's the easiest place to spot this error)
so that an error can be emitted later during typing. *)
| Lsb
| Synthesized
| Const
| Lateinit
| Dynamicallycallable
| SupportDynamicType
| XaHasDefault
| XaTagRequired
| XaTagLateinit
| ReadonlyProp
| NeedsInit
| SafeGlobalVariable
(* NB: Keep these flags in sync with typing_defs_flags.rs. *)
[@@deriving enum, show { with_path = false }]
(* [min] is generated by the enum ppx and is unused. This suppresses the warning. *)
let _ = min
let all : t list =
let rec f i acc =
if i < 0 then
acc
else
f (i - 1) (Option.value_exn (of_enum i) :: acc)
in
f max []
let to_bit_mask (field : t) : bit_mask = 1 lsl to_enum field
let list_to_bit_mask (fields : t list) : bit_mask =
List.map fields ~f:to_bit_mask |> List.fold ~init:0 ~f:Int.bit_or
(* The three XA bits are used to encode optional XHP attr.
* Set 1<<10 (0x400) if xa_has_default=true
* Then encode xa_tag as follows:
* Some Required: 1<<11 (0x0800)
* Some lateinit: 1<<12 (0x1000)
* None: 1<<11 | 1<<12 (0x1800)
* If attr is not present at all, then masking with 0x1800 will produce zero.
*)
let xhp_attr_fields : t list = [XaHasDefault; XaTagLateinit; XaTagRequired]
let of_xhp_tag : Xhp_attribute.tag -> t = function
| Xhp_attribute.Required -> XaTagRequired
| Xhp_attribute.LateInit -> XaTagLateinit
let to_xhp_tag : t -> Xhp_attribute.tag = function
| XaTagRequired -> Xhp_attribute.Required
| XaTagLateinit -> Xhp_attribute.LateInit
| _ -> failwith "cannot convert field to xhp attribute tag"
let equal_xhp_tag (field : t) (tag : Xhp_attribute.tag) =
match (field, tag) with
| (XaTagRequired, Xhp_attribute.Required)
| (XaTagLateinit, Xhp_attribute.LateInit) ->
true
| _ -> false
let of_xhp_attr (xa : Xhp_attribute.t option) : t list =
match xa with
| None -> []
| Some { Xhp_attribute.xa_has_default; xa_tag } ->
let tag_fields =
match xa_tag with
| None -> [XaTagRequired; XaTagLateinit]
| Some tag -> [of_xhp_tag tag]
in
if xa_has_default then
XaHasDefault :: tag_fields
else
tag_fields
let to_xhp_attr (fields : t list) : Xhp_attribute.t option =
match fields with
| [] -> None
| _ :: _ ->
let rec to_xhp_attr fields xa =
match fields with
| [] -> xa
| field :: fields ->
let xa =
let update_tag field tag =
match tag with
| None -> Some (to_xhp_tag field)
| Some tag ->
if equal_xhp_tag field tag then
Some tag
else
(* If both XaTagRequired and XaTagLateinit bits are set, then that's
code for xa_tag = None. *)
None
in
match field with
| XaHasDefault -> { xa with Xhp_attribute.xa_has_default = true }
| XaTagRequired
| XaTagLateinit ->
Xhp_attribute.map_tag xa ~f:(update_tag field)
| _ -> xa
in
to_xhp_attr fields xa
in
Some (to_xhp_attr fields Xhp_attribute.init)
end
let is_set (field : Field.t) (flags : t) : bool =
is_set (Field.to_bit_mask field) flags
let set (field : Field.t) (value : bool) (flags : t) : t =
set_bit (Field.to_bit_mask field) value flags
let is_abstract = is_set Field.Abstract
let is_final = is_set Field.Final
let has_superfluous_override = is_set Field.SuperfluousOverride
let has_lsb = is_set Field.Lsb
let is_synthesized = is_set Field.Synthesized
let is_const = is_set Field.Const
let has_lateinit = is_set Field.Lateinit
let is_dynamicallycallable = is_set Field.Dynamicallycallable
let supports_dynamic_type = is_set Field.SupportDynamicType
let is_readonly_prop = is_set Field.ReadonlyProp
let needs_init = is_set Field.NeedsInit
let is_safe_global_variable = is_set Field.SafeGlobalVariable
let get_xhp_attr (flags : t) : Xhp_attribute.t option =
Field.xhp_attr_fields
|> List.filter ~f:(fun field -> is_set field flags)
|> Field.to_xhp_attr
let set_xhp_attr (xa : Xhp_attribute.t option) (flags : t) : t =
let xhp_attr_as_flags = xa |> Field.of_xhp_attr |> Field.list_to_bit_mask in
let reset_xhp_attr =
let xhp_attr_mask = Field.xhp_attr_fields |> Field.list_to_bit_mask in
Int.bit_and (Int.bit_not xhp_attr_mask)
in
flags |> reset_xhp_attr |> Int.bit_or xhp_attr_as_flags
let to_string_map (flags : t) : bool SMap.t =
Field.all
|> List.map ~f:(fun field -> (Field.show field, is_set field flags))
|> SMap.of_list
let show (flags : t) : string = flags |> to_string_map |> SMap.show Bool.pp
let pp (fmt : Format.formatter) (flags : t) : unit =
flags |> to_string_map |> SMap.pp Bool.pp fmt
let make
~xhp_attr
~abstract
~final
~superfluous_override
~lsb
~synthesized
~const
~lateinit
~dynamicallycallable
~readonly_prop
~support_dynamic_type
~needs_init
~safe_global_variable =
let flags = 0 in
let flags = set Field.Abstract abstract flags in
let flags = set Field.Final final flags in
let flags = set Field.SuperfluousOverride superfluous_override flags in
let flags = set Field.Lsb lsb flags in
let flags = set Field.Synthesized synthesized flags in
let flags = set Field.Const const flags in
let flags = set Field.Lateinit lateinit flags in
let flags = set Field.Dynamicallycallable dynamicallycallable flags in
let flags = set_xhp_attr xhp_attr flags in
let flags = set Field.ReadonlyProp readonly_prop flags in
let flags = set Field.SupportDynamicType support_dynamic_type flags in
let flags = set Field.NeedsInit needs_init flags in
let flags = set Field.SafeGlobalVariable safe_global_variable flags in
flags
let set_synthesized = set Field.Synthesized true
let reset_superfluous_override = set Field.SuperfluousOverride false
end
[@@@ocamlformat "disable"]
(* NB: Keep the values of these flags in sync with typing_defs_flags.rs. *)
(* Function type flags *)
let ft_flags_return_disposable = 1 lsl 0
let ft_flags_returns_mutable = 1 lsl 1
let ft_flags_returns_void_to_rx = 1 lsl 2
let ft_flags_async = 1 lsl 4
let ft_flags_generator = 1 lsl 5
(* These flags are used for the self type on FunType and the parameter type on FunParam *)
let mutable_flags_owned = 1 lsl 6
let mutable_flags_borrowed = 1 lsl 7
let mutable_flags_maybe = Int.bit_or mutable_flags_owned mutable_flags_borrowed
let mutable_flags_mask = Int.bit_or mutable_flags_owned mutable_flags_borrowed
let ft_flags_instantiated_targs = 1 lsl 8
let ft_flags_is_function_pointer = 1 lsl 9
let ft_flags_returns_readonly = 1 lsl 10
let ft_flags_readonly_this = 1 lsl 11
let ft_flags_support_dynamic_type = 1 lsl 12
let ft_flags_is_memoized = 1 lsl 13
let ft_flags_variadic = 1 lsl 14
(* fun_param flags *)
let fp_flags_accept_disposable = 1 lsl 0
let fp_flags_inout = 1 lsl 1
let fp_flags_has_default = 1 lsl 2
let fp_flags_ifc_external = 1 lsl 3
let fp_flags_ifc_can_call = 1 lsl 4
(* let fp_flags_via_label_DEPRECATED = 1 lsl 5 *)
(* 6 and 7 are taken by mutability parameters above *)
let fp_flags_readonly = 1 lsl 8 |
OCaml | hhvm/hphp/hack/src/typing/typing_dependent_type.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Typing_defs
module ExprDepTy = struct
module N = Aast
module Env = Typing_env
module TUtils = Typing_utils
type dep =
| Dep_This
| Dep_Cls of string
| Dep_Expr of Ident.t
let new_ () =
let eid = Ident.tmp () in
(Reason.ERexpr eid, Dep_Expr eid)
(* Convert a class_id into a "dependent kind" (dep). This later informs the make_with_dep_kind function
* how to translate a type suitable for substituting for `this` in a method signature.
*)
let from_cid env reason (cid : Nast.class_id_) =
let pos = Reason.to_pos reason in
let (pos, expr_dep_reason, dep) =
match cid with
| N.CIparent ->
(match Env.get_parent_id env with
| Some cls -> (pos, Reason.ERparent cls, Dep_Cls cls)
| None ->
let (ereason, dep) = new_ () in
(pos, ereason, dep))
| N.CIself ->
(match Env.get_self_id env with
| Some cls -> (pos, Reason.ERself cls, Dep_Cls cls)
| None ->
let (ereason, dep) = new_ () in
(pos, ereason, dep))
| N.CI (p, cls) ->
(Pos_or_decl.of_raw_pos p, Reason.ERclass cls, Dep_Cls cls)
| N.CIstatic -> (pos, Reason.ERstatic, Dep_This)
| N.CIexpr (_, p, N.This) ->
(Pos_or_decl.of_raw_pos p, Reason.ERstatic, Dep_This)
(* If it is a local variable then we look up the expression id associated
* with it. If one doesn't exist we generate a new one. We are being
* conservative here because the new expression id we create isn't
* added to the local enviornment.
*)
| N.CIexpr (_, p, N.Lvar (_, x)) ->
let (ereason, dep) =
match Env.get_local_expr_id env x with
| Some eid -> (Reason.ERexpr eid, Dep_Expr eid)
| None -> new_ ()
in
(Pos_or_decl.of_raw_pos p, ereason, dep)
(* If all else fails we generate a new identifier for our expression
* dependent type.
*)
| N.CIexpr (_, p, _) ->
let (ereason, dep) = new_ () in
(Pos_or_decl.of_raw_pos p, ereason, dep)
in
(Reason.Rexpr_dep_type (reason, pos, expr_dep_reason), dep)
(****************************************************************************)
(* A type access "this::T" is translated to "<this>::T" during the
* naming phase. While typing a body, "<this>" is a type hole that needs to
* be filled with a final concrete type. Resolution is specified in typing.ml,
* here is a high level break down:
*
* 1) When a class member "bar" is accessed via "[CID]->bar" or "[CID]::bar"
* we resolve "<this>" in the type of "bar" to "<[CID]>"
*
* 2) When typing a method, we resolve "<this>" in the return type to
* "this"
*
* 3) When typing a method, we resolve "<this>" in parameters of the
* function to "<static>" in static methods or "<$this>" in non-static
* methods
*
* More specific details are explained inline
*)
(****************************************************************************)
let make_with_dep_kind env dep_kind ty =
let (r_dep_ty, dep_ty) = dep_kind in
let apply env ty =
match dep_ty with
| Dep_Cls _ -> (env, mk (r_dep_ty, Tdependent (DTexpr (Ident.tmp ()), ty)))
| Dep_This -> (env, ty)
| Dep_Expr id -> (env, mk (r_dep_ty, Tdependent (DTexpr id, ty)))
in
let rec make ~seen env ty =
let (env, ty) = Env.expand_type env ty in
match deref ty with
| (_, Tclass (_, Exact, _)) -> (env, ty)
| (_, Tclass (((_, x) as c), Nonexact _, tyl)) ->
let class_ = Env.get_class env x in
(* If a class is both final and variant, we must treat it as non-final
* since we can't statically guarantee what the runtime type
* will be.
*)
if
Option.value_map class_ ~default:false ~f:(fun class_ty ->
TUtils.class_is_final_and_invariant class_ty)
then
(env, ty)
else (
match dep_ty with
| Dep_Cls n when String.equal n x ->
(env, mk (r_dep_ty, Tclass (c, Exact, tyl)))
| _ -> apply env ty
)
| (_, Tgeneric (s, _tyargs)) when DependentKind.is_generic_dep_ty s ->
(* TODO(T69551141) handle type arguments *)
(env, ty)
| (_, Tgeneric (name, _)) ->
if SSet.mem name seen then
(env, ty)
else
(* TODO(T69551141) handle type arguments here? *)
let (env, tyl) =
TUtils.get_concrete_supertypes ~abstract_enum:true env ty
in
let (env, tyl') =
List.fold_map tyl ~init:env ~f:(make ~seen:(SSet.add name seen))
in
if tyl_equal tyl tyl' then
(env, ty)
else
apply env ty
| (r, Toption ty) ->
let (env, ty) = make ~seen env ty in
(env, mk (r, Toption ty))
| (_, Tunapplied_alias _) ->
Typing_defs.error_Tunapplied_alias_in_illegal_context ()
| (r, Tnewtype (n, p, ty)) ->
let (env, ty) = make ~seen env ty in
(env, mk (r, Tnewtype (n, p, ty)))
| (_, Tdependent (_, _)) -> (env, ty)
| (r, Tunion tyl) ->
let (env, tyl) = List.fold_map tyl ~init:env ~f:(make ~seen) in
(env, mk (r, Tunion tyl))
| (r, Tintersection tyl) ->
let (env, tyl) = List.fold_map tyl ~init:env ~f:(make ~seen) in
(env, mk (r, Tintersection tyl))
| (r, Taccess (ty, ids)) ->
let (env, ty) = make ~seen env ty in
(env, mk (r, Taccess (ty, ids)))
(* TODO(T36532263) check if this is legal *)
| ( _,
( Tnonnull | Tprim _ | Tshape _ | Ttuple _ | Tdynamic | Tvec_or_dict _
| Tfun _ | Tany _ | Tvar _ | Tneg _ ) ) ->
(env, ty)
in
make ~seen:SSet.empty env ty
let make env ~cid ty =
make_with_dep_kind env (from_cid env (get_reason ty) cid) ty
end |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_dependent_type.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module ExprDepTy : sig
type dep =
| Dep_This
| Dep_Cls of string
| Dep_Expr of Ident.t
val from_cid :
Typing_env_types.env ->
Typing_reason.t ->
Nast.class_id_ ->
Typing_reason.t * dep
val make :
Typing_env_types.env ->
cid:Nast.class_id_ ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty
val make_with_dep_kind :
Typing_env_types.env ->
Typing_reason.t * dep ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty
end |
OCaml | hhvm/hphp/hack/src/typing/typing_disposable.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* Typing code concerned with disposable types. *)
open Hh_prelude
module Env = Typing_env
module Cls = Decl_provider.Class
let is_disposable_class env cls =
let name = Cls.name cls in
String.equal name Naming_special_names.Classes.cIDisposable
|| String.equal name Naming_special_names.Classes.cIAsyncDisposable
|| Typing_utils.has_ancestor_including_req
env
cls
Naming_special_names.Classes.cIDisposable
|| Typing_utils.has_ancestor_including_req
env
cls
Naming_special_names.Classes.cIAsyncDisposable
let is_disposable_visitor env =
object (this)
inherit [string option] Type_visitor.locl_type_visitor
(* Only bother looking at classish types. Other types can spuriously
* claim to implement these interfaces. Ideally we should check
* constrained generics, abstract types, etc.
*)
method! on_tclass acc _ (_, class_name) _ tyl =
let default () = List.fold_left tyl ~f:this#on_type ~init:acc in
match Env.get_class env class_name with
| None -> default ()
| Some c ->
if is_disposable_class env c then
Some (Utils.strip_ns class_name)
else
default ()
end
(* Does ty (or a type embedded in ty) implement IDisposable
* or IAsyncDisposable, directly or indirectly?
* Return Some class_name if it does, None if it doesn't.
*)
let is_disposable_type env ty =
match Env.expand_type env ty with
| (_env, ety) -> (is_disposable_visitor env)#on_type None ety
let enforce_is_disposable env hint =
match hint with
| (_, Aast.Happly ((p, c), _)) -> begin
match Env.get_class env c with
| None -> ()
| Some c ->
if not (is_disposable_class env c || Ast_defs.is_c_interface (Cls.kind c))
then
Typing_error_utils.add_typing_error
~env
Typing_error.(primary @@ Primary.Must_extend_disposable p)
end
| _ -> () |
OCaml | hhvm/hphp/hack/src/typing/typing_dynamic.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Typing_defs
open Common
module Env = Typing_env
module SN = Naming_special_names
module Reason = Typing_reason
module Cls = Decl_provider.Class
(* Add `supportdyn<mixed>` lower and upper bound to any type parameters that are marked <<__RequireDynamic>>
* Just add the upper bound to others. *)
let add_require_dynamic_bounds env cls =
List.fold_left (Cls.tparams cls) ~init:env ~f:(fun env tp ->
let require_dynamic =
Attributes.mem SN.UserAttributes.uaRequireDynamic tp.tp_user_attributes
in
let dtype =
Typing_make_type.supportdyn_mixed
(Reason.Rwitness_from_decl (fst tp.tp_name))
in
let env = Env.add_upper_bound env (snd tp.tp_name) dtype in
if
require_dynamic
(* Implicit pessimisation should ignore the RequireDynamic attribute
because everything should be pessimised enough that it isn't necessary. *)
&& not
(TypecheckerOptions.everything_sdt
Typing_env_types.(env.genv.tcopt))
then
Env.add_lower_bound env (snd tp.tp_name) dtype
else
env)
let is_dynamic_decl env ty =
match get_node ty with
| Tdynamic -> true
| Tgeneric (name, _) when Env.get_require_dynamic env name -> true
| _ -> false
(* Check that a property type is a subtype of dynamic *)
let check_property_sound_for_dynamic_read ~on_error env classname id ty =
if not (Typing_utils.is_supportdyn env ty) then (
let pos = get_pos ty in
Typing_log.log_pessimise_prop
env
(Pos_or_decl.unsafe_to_raw_pos pos)
(snd id);
Some
(on_error
(fst id)
(snd id)
classname
(pos, Typing_print.full_strip_ns env ty))
) else
None
(* The optional ty should be (if not None) the localisation of the decl_ty.
This lets us avoid re-localising the decl type when the caller has already
localised it *)
let check_property_sound_for_dynamic_write
~this_class ~on_error env classname id decl_ty ty =
let te_check = Typing_enforceability.is_enforceable ~this_class env decl_ty in
(* If the property type isn't enforceable, but is a supertype of dynamic,
then the property will still be safe to write via a receiver expression of type
dynamic. *)
if not te_check then (
let ((env, ty_err_opt), ty) =
match ty with
| Some ty -> ((env, None), ty)
| None -> Typing_phase.localize_no_subst ~ignore_errors:true env decl_ty
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
if
not
(Typing_utils.is_any env ty
|| Typing_utils.is_sub_type_for_union
env
(Typing_make_type.dynamic Reason.Rnone)
ty)
then (
let pos = get_pos decl_ty in
Typing_log.log_pessimise_prop
env
(Pos_or_decl.unsafe_to_raw_pos pos)
(snd id);
Some
(on_error
(fst id)
(snd id)
classname
(pos, Typing_print.full_strip_ns_decl env decl_ty))
) else
None
) else
None
let function_parameters_safe_for_dynamic ~this_class env params_decl_ty =
List.for_all params_decl_ty ~f:(fun dtyopt ->
match dtyopt with
| Some dty ->
(* If a parameter isn't enforceable, but is just typed as dynamic,
the method will still be safe to call via a receiver expression of type
dynamic. *)
Typing_enforceability.is_enforceable ~this_class env dty
|| is_dynamic_decl env dty
(* If a parameter isn't typed (e.g. for a lambda), we might infer
* a non-SDT type for it and so need to check again under dynamic *)
| None -> false)
let sound_dynamic_interface_check ~this_class env params_decl_ty ret_locl_ty =
(* 1. check if all the parameters of the method are enforceable *)
let enforceable_params =
function_parameters_safe_for_dynamic ~this_class env params_decl_ty
in
let coercible_return_type =
(* 2. check if the return type is coercible *)
Typing_utils.is_supportdyn env ret_locl_ty
in
enforceable_params && coercible_return_type
let sound_dynamic_interface_check_from_fun_ty ~this_class env fun_ty =
let params_decl_ty =
List.map fun_ty.ft_params ~f:(fun fun_param ->
Some fun_param.fp_type.et_type)
in
let ret_locl_ty =
snd
(Typing_return.make_return_type
~ety_env:empty_expand_env
~this_class
env
~supportdyn:false
~hint_pos:Pos.none
~explicit:(Some fun_ty.ft_ret.et_type)
~default:None)
in
sound_dynamic_interface_check
~this_class
env
params_decl_ty
ret_locl_ty.et_type
(* Given t, construct ~t.
* acc is a boolean that remains false if no change was made (e.g. t = dynamic)
*)
let make_like env changed ty =
if
Typing_defs.is_dynamic ty
|| Option.is_some (Typing_utils.try_strip_dynamic env ty)
then
(changed, ty)
else
let r = get_reason ty in
(true, Typing_make_type.locl_like r ty)
let maybe_wrap_with_supportdyn ~should_wrap locl_r ft =
if should_wrap then
let r = Reason.Rsupport_dynamic_type (Reason.to_pos locl_r) in
let ft =
{
ft with
ft_flags =
Typing_defs_flags.(
set_bit ft_flags_support_dynamic_type false ft.ft_flags);
}
in
Typing_make_type.supportdyn r (mk (locl_r, Tfun ft))
else
mk (locl_r, Tfun ft)
let push_like_tyargs env tyl tparams =
if List.length tyl <> List.length tparams then
(false, tyl)
else
let make_like changed ty tp =
(* Don't both pushing through a contravariant parameter, because
* Contra<~t> <: Contra<t> <: ~Contra<t> by variance and union
* subtyping rules already *)
match tp.tp_variance with
| Ast_defs.Contravariant -> (changed, ty)
| _ ->
let (changed', ty') = make_like env changed ty in
(* Push like onto type argument; if the resulting type is not a subtype of
* the the upper bound on the type parameter, then intersect it with the
* upper bonud so that the resulting type is well-formed.
* For example, dict<~string & arraykey,bool> <: ~dict<string,bool>
* because the first type parameter has an upper bound of arraykey.
*)
let upper_bounds =
List.filter_map tp.tp_constraints ~f:(fun (c, cty) ->
match c with
| Ast_defs.Constraint_as ->
let (_env, cty) =
Typing_phase.localize_no_subst env ~ignore_errors:true cty
in
Some cty
| _ -> None)
in
(* Type meets all bounds, so leave alone *)
if
List.for_all upper_bounds ~f:(fun bound ->
Typing_utils.is_sub_type_for_union env ty' bound)
then
(changed', ty')
else
(changed', mk (get_reason ty, Tintersection (ty' :: upper_bounds)))
in
List.map2_env false tyl tparams ~f:make_like
let rec try_push_like env ty =
match deref ty with
| (r, Ttuple tyl) ->
let (changed, tyl) = List.map_env false tyl ~f:(make_like env) in
( env,
if changed then
Some (mk (r, Ttuple tyl))
else
None )
| (r, Tfun ft) ->
let (changed, ret_ty) = make_like env false ft.ft_ret.et_type in
( env,
if changed then
Some
(mk
(r, Tfun { ft with ft_ret = { ft.ft_ret with et_type = ret_ty } }))
else
None )
| (r, Tshape { s_origin = _; s_unknown_value = kind; s_fields = fields }) ->
let add_like_to_shape_field changed _name { sft_optional; sft_ty } =
let (changed, sft_ty) = make_like env changed sft_ty in
(changed, { sft_optional; sft_ty })
in
let (changed, fields) =
TShapeMap.map_env add_like_to_shape_field false fields
in
( env,
if changed then
Some
(mk
( r,
Tshape
{
s_origin = Missing_origin;
s_unknown_value = kind;
s_fields = fields;
} ))
else
None )
| (r, Tnewtype (n, tyl, bound)) -> begin
match Env.get_typedef env n with
| None -> (env, None)
| Some td ->
let (changed, tyl) = push_like_tyargs env tyl td.td_tparams in
( env,
if changed then
Some (mk (r, Tnewtype (n, tyl, bound)))
else
None )
end
| (r, Tclass ((p, n), exact, tyl)) -> begin
match Env.get_class env n with
| None -> (env, None)
| Some cd ->
let (changed, tyl) = push_like_tyargs env tyl (Cls.tparams cd) in
( env,
if changed then
Some (mk (r, Tclass ((p, n), exact, tyl)))
else
None )
end
| (r, Toption ty) -> begin
match try_push_like env ty with
| (env, Some ty) -> (env, Some (mk (r, Toption ty)))
| (env, None) -> (env, None)
end
| (r, Tvec_or_dict (tk, tv)) ->
let (changed, tyl) = List.map_env false [tk; tv] ~f:(make_like env) in
if changed then
match tyl with
| [tk; tv] -> (env, Some (mk (r, Tvec_or_dict (tk, tv))))
| _ -> assert false
else
(env, None)
| _ -> (env, None)
(* If ty is ~ty0 then return ty0
* Otherwise, recursively apply like-stripping to all covariant positions
* e.g. tuple and shape components, covariant type arguments to generic classes.
*)
let rec strip_covariant_like env ty =
match Typing_utils.try_strip_dynamic env ty with
| Some ty -> (env, ty)
| None ->
(match deref ty with
| (r, Ttuple tyl) ->
let (env, tyl) = List.map_env env ~f:strip_covariant_like tyl in
(env, mk (r, Ttuple tyl))
| (r, Tfun ft) ->
let (env, ret_ty) = strip_covariant_like env ft.ft_ret.et_type in
( env,
mk (r, Tfun { ft with ft_ret = { ft.ft_ret with et_type = ret_ty } }) )
| (r, Tshape { s_origin = _; s_unknown_value = kind; s_fields = fields }) ->
let strip_shape_field env _name { sft_optional; sft_ty } =
let (env, sft_ty) = strip_covariant_like env sft_ty in
(env, { sft_optional; sft_ty })
in
let (env, fields) = TShapeMap.map_env strip_shape_field env fields in
( env,
mk
( r,
Tshape
{
s_origin = Missing_origin;
s_unknown_value = kind;
s_fields = fields;
} ) )
| (r, Tnewtype (n, tyl, bound)) -> begin
match Env.get_typedef env n with
| None -> (env, ty)
| Some td ->
let (env, tyl) = strip_covariant_like_tyargs env tyl td.td_tparams in
let (env, bound) =
if String.equal n Naming_special_names.Classes.cMemberOf then
strip_covariant_like env bound
else
(env, bound)
in
(env, mk (r, Tnewtype (n, tyl, bound)))
end
| (r, Tclass ((p, n), exact, tyl)) -> begin
match Env.get_class env n with
| None -> (env, ty)
| Some cd ->
let (env, tyl) = strip_covariant_like_tyargs env tyl (Cls.tparams cd) in
(env, mk (r, Tclass ((p, n), exact, tyl)))
end
| (r, Toption ty) -> begin
let (env, ty) = strip_covariant_like env ty in
(env, mk (r, Toption ty))
end
| (r, Tvec_or_dict (tk, tv)) ->
let (env, tk) = strip_covariant_like env tk in
let (env, tv) = strip_covariant_like env tv in
(env, mk (r, Tvec_or_dict (tk, tv)))
| _ -> (env, ty))
and strip_covariant_like_tyargs env tyl tparams =
if List.length tyl <> List.length tparams then
(env, tyl)
else
let strip_covariant_like_tyarg env ty tp =
match tp.tp_variance with
| Ast_defs.Contravariant
| Ast_defs.Invariant ->
(env, ty)
| Ast_defs.Covariant -> strip_covariant_like env ty
in
List.map2_env env tyl tparams ~f:strip_covariant_like_tyarg |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_dynamic.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 add_require_dynamic_bounds :
Typing_env_types.env -> Decl_provider.class_decl -> Typing_env_types.env
val check_property_sound_for_dynamic_read :
on_error:('a -> string -> string -> Pos_or_decl.t * string -> Typing_error.t) ->
Typing_env_types.env ->
string ->
'a * string ->
Typing_defs.locl_ty ->
Typing_error.t option
val check_property_sound_for_dynamic_write :
this_class:Decl_provider.Class.t option ->
on_error:('a -> string -> string -> Pos_or_decl.t * string -> Typing_error.t) ->
Typing_env_types.env ->
string ->
'a * string ->
Typing_defs.decl_ty ->
Typing_defs.locl_ty option ->
Typing_error.t option
(* From the signature alone, are function parameter hints safe for dynamic?
* i.e. (1) present, and (2) fully-enforced, or `dynamic`.
*)
val function_parameters_safe_for_dynamic :
this_class:Decl_provider.Class.t option ->
Typing_env_types.env ->
Typing_defs.decl_ty option list ->
bool
(* checks that a method can be invoked in a dynamic context by ensuring that
the types of its arguments are enforceable and its return type can be
coerced to dynamic *)
val sound_dynamic_interface_check :
this_class:Decl_provider.Class.t option ->
Typing_env_types.env ->
Typing_defs.decl_ty option list ->
Typing_defs.locl_ty ->
bool
val sound_dynamic_interface_check_from_fun_ty :
this_class:Decl_provider.Class.t option ->
Typing_env_types.env ->
Typing_defs.decl_ty Typing_defs.fun_type ->
bool
val maybe_wrap_with_supportdyn :
should_wrap:bool ->
Typing_reason.t ->
Typing_defs.locl_ty Typing_defs_core.fun_type ->
Typing_defs.locl_ty
(* Make parameters of SDT types (tuples, shapes, and classes) into like types,
* if that results in a well-formed type, otherwise leave them alone.
* Return None if no change was made.
* Example input: shape('a' => int, 'b' => string)
* Output: shape('a' => ~int, 'b' => ~string)
*
* Example input: dict<int,string>
* Output: dict<int,~string> (because ~int doesn't subtype arraykey)
*)
val try_push_like :
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty option
(* If ty is ~ty0 then return ty0
* Otherwise, recursively apply like-stripping to all covariant positions
* e.g. tuple and shape components, covariant type arguments to generic classes.
*)
val strip_covariant_like :
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty |
OCaml | hhvm/hphp/hack/src/typing/typing_enforceability.ml | (*
* Copyright (c) 2017, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Typing_defs
open Typing_env_types
module Cls = Decl_provider.Class
module Env = Typing_env
module FoldedContextAccess :
Decl_enforceability.ContextAccess with type t = env and type class_t = Cls.t =
struct
type t = env
type class_t = Cls.t
let get_tcopt env = env.genv.tcopt
let get_class_or_typedef ctx name =
(* Preserve the decl access behaviour of the enforceability code that used to be here. *)
ignore (Env.get_class ctx name);
Env.get_class_or_typedef ctx name
let get_typedef = Env.get_typedef
let get_class = Env.get_class
let get_typeconst_type _ cls name =
match Cls.get_typeconst cls name with
| None -> None
| Some tc ->
(match tc.ttc_kind with
| TCAbstract abstract -> abstract.atc_as_constraint
| TCConcrete concrete -> Some concrete.tc_type)
let get_tparams = Cls.tparams
let get_name = Cls.name
let get_enum_type = Cls.enum_type
end
module E = Decl_enforceability.Enforce (FoldedContextAccess)
let get_enforcement ~this_class (env : env) (ty : decl_ty) :
Typing_defs.enforcement =
match E.get_enforcement ~return_from_async:false ~this_class env ty with
| Decl_enforceability.Unenforced _ -> Unenforced
| Decl_enforceability.Enforced _ -> Enforced
let is_enforceable ~this_class (env : env) (ty : decl_ty) =
match get_enforcement ~this_class env ty with
| Enforced -> true
| Unenforced -> false
(* We don't trust that hhvm will enforce things consistent with the .hhi file,
outside of hsl *)
let unenforced_hhi pos_or_decl =
match Pos_or_decl.get_raw_pos_or_decl_reference pos_or_decl with
| `Decl_ref _ -> false
| `Raw p ->
let path = Pos.filename p in
Relative_path.(is_hhi (prefix path))
&&
let suffix = Relative_path.suffix path in
not
(String.is_prefix suffix ~prefix:"hsl_generated/"
|| String.is_prefix suffix ~prefix:"hsl/")
let get_enforced ~this_class env ~explicitly_untrusted ty =
if explicitly_untrusted || unenforced_hhi (get_pos ty) then
Unenforced
else
get_enforcement ~this_class env ty
let compute_enforced_ty
~this_class env ?(explicitly_untrusted = false) (ty : decl_ty) =
let et_enforced = get_enforced ~this_class env ~explicitly_untrusted ty in
{ et_type = ty; et_enforced }
let compute_enforced_and_pessimize_ty
~this_class env ?(explicitly_untrusted = false) (ty : decl_ty) =
compute_enforced_ty ~this_class env ~explicitly_untrusted ty
let handle_awaitable_return
~this_class env ft_fun_kind (ft_ret : decl_possibly_enforced_ty) =
let { et_type = return_type; _ } = ft_ret in
match (ft_fun_kind, get_node return_type) with
| (Ast_defs.FAsync, Tapply ((_, name), [inner_ty]))
when String.equal name Naming_special_names.Classes.cAwaitable ->
let { et_enforced; _ } = compute_enforced_ty ~this_class env inner_ty in
{ et_type = return_type; et_enforced }
| _ -> compute_enforced_and_pessimize_ty ~this_class env return_type
let compute_enforced_and_pessimize_fun_type ~this_class env (ft : decl_fun_type)
=
let { ft_params; ft_ret; _ } = ft in
let ft_fun_kind = get_ft_fun_kind ft in
let ft_ret = handle_awaitable_return ~this_class env ft_fun_kind ft_ret in
let ft_params =
List.map
~f:(fun fp ->
let { fp_type = { et_type; _ }; _ } = fp in
let f =
if equal_param_mode (get_fp_mode fp) FPinout then
compute_enforced_and_pessimize_ty ~this_class
else
compute_enforced_ty ~this_class
in
let fp_type = f env et_type in
{ fp with fp_type })
ft_params
in
{ ft with ft_params; ft_ret }
let compute_enforced_ty = compute_enforced_ty ?explicitly_untrusted:None |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_enforceability.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val is_enforceable :
this_class:Decl_provider.Class.t option ->
Typing_env_types.env ->
Typing_defs.decl_ty ->
bool
val get_enforcement :
this_class:Decl_provider.Class.t option ->
Typing_env_types.env ->
Typing_defs.decl_ty ->
Typing_defs_core.enforcement
val compute_enforced_ty :
this_class:Decl_provider.Class.t option ->
Typing_env_types.env ->
Typing_defs.decl_ty ->
Typing_defs.decl_ty Typing_defs.possibly_enforced_ty
val compute_enforced_and_pessimize_ty :
this_class:Decl_provider.Class.t option ->
Typing_env_types.env ->
?explicitly_untrusted:bool ->
Typing_defs.decl_ty ->
Typing_defs.decl_ty Typing_defs.possibly_enforced_ty
val compute_enforced_and_pessimize_fun_type :
this_class:Decl_provider.Class.t option ->
Typing_env_types.env ->
Typing_defs.decl_fun_type ->
Typing_defs.decl_ty Typing_defs.fun_type |
OCaml | hhvm/hphp/hack/src/typing/typing_enforceable_hint.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
module Env = Typing_env
module Reason = Typing_reason
module Cls = Decl_provider.Class
module SN = Naming_special_names
let validator =
object (this)
inherit Type_validator.type_validator as super
(* Only comes about because naming has reported an error and left Hany *)
method! on_tany acc _ = acc
method! on_tprim acc r prim =
match prim with
| Aast.Tvoid -> this#invalid acc r "the `void` type"
| Aast.Tnoreturn -> this#invalid acc r "the `noreturn` type"
| _ -> acc
method! on_tfun acc r _fun_type = this#invalid acc r "a function type"
method! on_tvar acc r _id = this#invalid acc r "an unknown type"
method! on_typeconst acc class_ typeconst =
match typeconst.ttc_kind with
| TCConcrete _ -> super#on_typeconst acc class_ typeconst
| TCAbstract _
when (* get_typeconst_enforceability should always return Some here, since we
know the typeconst exists (else we wouldn't be in this method).
But since we have to map it to a bool anyway, we just use
Option.value_map. *)
Option.value_map
~f:snd
~default:false
(Cls.get_typeconst_enforceability
class_
(snd typeconst.ttc_name)) ->
super#on_typeconst acc class_ typeconst
| TCAbstract _ ->
let (pos, tconst) = typeconst.ttc_name in
let r = Reason.Rwitness_from_decl pos in
this#invalid acc r
@@ "the abstract type constant "
^ tconst
^ " because it is not marked `<<__Enforceable>>`"
method! on_tgeneric acc r name _tyargs =
(* If we allow higher-kinded generics to be enforceable at some point,
handle type arguments here *)
this#check_generic acc r name
method! on_newtype acc r sid _ as_cstr _super_cstr _ =
if String.equal (snd sid) SN.Classes.cSupportDyn then
this#on_type acc (with_reason as_cstr r)
else
this#invalid acc r "a `newtype`"
method! on_tlike acc _r ty = this#on_type acc ty
method! on_class acc r cls tyl =
match Env.get_class acc.Type_validator.env (snd cls) with
| Some tc ->
let tparams = Cls.tparams tc in
begin
match tyl with
| [] -> acc
(* this case should really be handled by the fold2,
but we still allow class hints without args in certain places *)
| targs ->
List.Or_unequal_lengths.(
begin
match
List.fold2 ~init:acc targs tparams ~f:(fun acc targ tparam ->
let inside_reified_class_generic_position =
acc.Type_validator.inside_reified_class_generic_position
in
if this#is_wildcard targ then begin
if inside_reified_class_generic_position then
this#invalid
acc
r
"a reified type containing a wildcard (`_`)"
else
acc
end else if
Aast.(equal_reify_kind tparam.tp_reified Reified)
then
this#on_type
{
acc with
Type_validator.inside_reified_class_generic_position =
true;
}
targ
else if inside_reified_class_generic_position then
this#on_type acc targ
else
let error_message =
"a type with an erased generic type argument"
in
this#invalid acc r error_message)
with
| Ok new_acc -> new_acc
| Unequal_lengths -> acc (* arity error elsewhere *)
end)
end
| None -> acc
method! on_alias acc r _id tyl ty =
if List.is_empty tyl then
this#on_type acc ty
else
this#invalid
acc
r
"a type with generics, because generics are erased at runtime"
method! on_tunion acc r tyl =
match tyl with
| [] -> this#invalid acc r "the `nothing` type"
| _ -> super#on_tunion acc r tyl
method! on_tintersection acc r _ =
this#invalid
acc
r
"an intersection type, which is restricted to coeffects"
method is_wildcard ty =
match get_node ty with
| Twildcard -> true
| _ -> false
method check_for_wildcards acc tyl s =
match List.filter tyl ~f:this#is_wildcard with
| [] -> acc
| tyl ->
this#invalid_list
acc
(List.map tyl ~f:(fun ty ->
( Typing_defs_core.get_reason ty,
"_ in a " ^ s ^ " (use `mixed` instead)" )))
method! on_ttuple acc _ tyl =
let acc = List.fold_left tyl ~f:this#on_type ~init:acc in
this#check_for_wildcards acc tyl "tuple"
method! on_tshape acc _ { s_fields = fdm; _ } =
let tyl = TShapeMap.values fdm |> List.map ~f:(fun s -> s.sft_ty) in
let acc = List.fold_left tyl ~init:acc ~f:this#on_type in
this#check_for_wildcards acc tyl "shape"
method check_generic acc r name =
(* No need to look at type arguments of generic var, as higher-kinded type params
cannot be enforcable *)
(* TODO(T70069116) implement enforcability check *)
match
( Env.get_reified acc.Type_validator.env name,
Env.get_enforceable acc.Type_validator.env name )
with
| (Aast.Erased, _) ->
this#invalid acc r "an erased generic type parameter"
| (Aast.SoftReified, _) ->
this#invalid acc r "a soft reified generic type parameter"
| (Aast.Reified, false) ->
(* If a reified generic is an argument to a reified class it does not
* need to be enforceable *)
if acc.Type_validator.inside_reified_class_generic_position then
acc
else
this#invalid
acc
r
"a reified type parameter that is not marked `<<__Enforceable>>`"
| (Aast.Reified, true) -> acc
end
let validate_hint = validator#validate_hint ?reification:None
let validate_type = validator#validate_type ?reification:None |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_enforceable_hint.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val validate_hint :
Typing_env_types.env -> Aast.hint -> Type_validator.error_emitter -> unit
val validate_type :
Typing_env_types.env ->
Pos.t ->
Typing_defs.decl_ty ->
Type_validator.error_emitter ->
unit |
OCaml | hhvm/hphp/hack/src/typing/typing_enum.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(*****************************************************************************)
(* Module used to enforce that Enum subclasses are used reasonably.
* Exports the Enum type as the type of all constants, checks that constants
* have the proper type, and restricts what types can be used for enums.
*)
(*****************************************************************************)
open Hh_prelude
open Aast
open Typing_defs
module Phase = Typing_phase
module Cls = Decl_provider.Class
module MakeType = Typing_make_type
let member_type env member_ce =
let (lazy default_result) = member_ce.ce_type in
if Option.is_none (get_ce_xhp_attr member_ce) then
default_result
else
let (stripped_ty, has_like) =
match get_node default_result with
| Tlike ty -> (ty, true)
| _ -> (default_result, false)
in
match get_node stripped_ty with
| Tapply (enum_id, _) ->
(* XHP attribute type transform is necessary to account for
* non-first class Enums:
* attribute MyEnum x; // declaration: MyEnum
* $this->:x; // usage: MyEnumType
*)
let maybe_enum = Typing_env.get_class env (snd enum_id) in
(match maybe_enum with
| None -> default_result
| Some tc ->
(match
Decl_enum.enum_kind
(Cls.pos tc, Cls.name tc)
~is_enum_class:(Ast_defs.is_c_enum_class (Cls.kind tc))
(Cls.enum_type tc)
Option.(
Cls.get_typeconst tc Naming_special_names.FB.tInner >>= fun t ->
(* TODO(T88552052) This code was taking the default of abstract
* type constants as a value *)
match t.ttc_kind with
| TCConcrete { tc_type = t }
| TCAbstract { atc_default = Some t; _ } ->
Some t
| TCAbstract { atc_default = None; _ } -> None)
~get_ancestor:(Cls.get_ancestor tc)
with
| None -> default_result
| Some
{
Decl_enum.base = _;
type_ = enum_ty;
constraint_ = _;
interface = _;
} ->
let ty = mk (get_reason default_result, get_node enum_ty) in
if has_like then
mk (get_reason default_result, Tlike ty)
else
ty))
| _ -> default_result
let enum_check_const ty_exp env cc t =
if Typing_utils.is_tyvar_error env ty_exp || Typing_utils.is_tyvar_error env t
then
(env, None)
else
let p = fst cc.cc_id in
Typing_ops.sub_type
p
Reason.URenum
env
t
ty_exp
Typing_error.Callback.constant_does_not_match_enum_type
(* Check that the `as` bound or the underlying type of an enum is a subtype of
* arraykey. For enum class, check that it is a denotable closed type:
* no free type parameters are allowed, and we also prevent uncertain cases,
* like any, or dynamic. The free status of type parameter is caught during
* naming (Unbound name), so we only check the kind of type that is used.
*)
let enum_check_type env (pos : Pos_or_decl.t) ur ty_interface ty _on_error =
let sd env =
(* Allow pessimised enum class types when sound dynamic is enabled *)
TypecheckerOptions.enable_sound_dynamic (Typing_env.get_tcopt env)
in
let ty_arraykey =
MakeType.arraykey (Reason.Rimplicit_upper_bound (pos, "arraykey"))
in
let rec is_valid_base lty =
Typing_utils.is_tyvar_error env lty
||
match get_node lty with
| Tprim _
| Tnonnull ->
true
| Toption lty -> is_valid_base lty
| Ttuple ltys -> List.for_all ~f:is_valid_base ltys
| Tnewtype (_, ltys, lty) -> List.for_all ~f:is_valid_base (lty :: ltys)
| Tclass (_, _, ltys) -> List.for_all ~f:is_valid_base ltys
| Tunion [ty1; ty2] when is_dynamic ty1 && sd env -> is_valid_base ty2
| Tunion [ty1; ty2] when is_dynamic ty2 && sd env -> is_valid_base ty1
| Tshape { s_fields = shapemap; _ } ->
TShapeMap.for_all (fun _name sfty -> is_valid_base sfty.sft_ty) shapemap
| Tany _
| Tdynamic
| Tfun _
| Tvar _
| Tgeneric _
| Tunion _
| Tintersection _
| Tvec_or_dict _
| Taccess _
| Tunapplied_alias _
| Tdependent _
| Tneg _ ->
false
in
let (env, ty_err_opt) =
match ty_interface with
| Some interface ->
(if not (is_valid_base interface) then
Typing_error_utils.add_typing_error ~env
@@ Typing_error.(
enum
@@ Primary.Enum.Enum_type_bad
{
pos = Pos_or_decl.unsafe_to_raw_pos pos;
is_enum_class = true;
ty_name = lazy (Typing_print.full_strip_ns env interface);
trail = [];
}));
(env, None)
| None ->
let callback =
let open Typing_error in
Callback.always
Primary.(
Enum
(Enum.Enum_type_bad
{
pos = Pos_or_decl.unsafe_to_raw_pos pos;
is_enum_class = false;
ty_name = lazy (Typing_print.full_strip_ns env ty);
trail = [];
}))
in
Typing_ops.sub_type
(Pos_or_decl.unsafe_to_raw_pos pos)
ur
env
ty
ty_arraykey
callback
in
let ty_base = Option.value ~default:ty ty_interface in
(* Enforcement of case types for enum/enum classes is wonky.
* Forbid for now until we can more thoroughly audit the behavior *)
(match get_node ty_base with
| Tnewtype (name, _, _) ->
(match Typing_env.get_typedef env name with
| Some { td_vis = Aast.CaseType; td_pos; _ } ->
Typing_error_utils.add_typing_error ~env
@@ Typing_error.(
enum
@@ Primary.Enum.Enum_type_bad_case_type
{
pos = Pos_or_decl.unsafe_to_raw_pos pos;
ty_name = lazy (Typing_print.full_strip_ns env ty_base);
case_type_decl_pos = td_pos;
})
| _ -> ())
| _ -> ());
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
env
(* Check an enum declaration of the form
* enum E : <ty_exp> as <ty_constraint>
* or
* class E extends Enum<ty_exp>
* where the absence of <ty_constraint> is assumed to default to arraykey.
*
* Check that <ty_exp> is int or string, and that
* ty_exp <: ty_constraint <: arraykey
* Also that each type constant is of type ty_exp.
*)
let enum_class_check env tc consts const_types =
let pos = Cls.pos tc in
let enum_info_opt =
Decl_enum.enum_kind
(pos, Cls.name tc)
~is_enum_class:(Ast_defs.is_c_enum_class (Cls.kind tc))
(Cls.enum_type tc)
Option.(
Cls.get_typeconst tc Naming_special_names.FB.tInner >>= fun t ->
(* TODO(T88552052) This code was taking the default of abstract
* type constants as a value *)
match t.ttc_kind with
| TCConcrete { tc_type = t }
| TCAbstract { atc_default = Some t; _ } ->
Some t
| TCAbstract { atc_default = None; _ } -> None)
~get_ancestor:(Cls.get_ancestor tc)
in
let (env, ty_err_opt) =
match enum_info_opt with
| Some
{
Decl_enum.base = ty_exp;
type_ = _;
constraint_ = ty_constraint;
interface = ty_interface;
} ->
let ((env, ty_err1), ty_exp) =
Phase.localize_no_subst env ~ignore_errors:false ty_exp
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err1;
let ((env, ty_err2), ty_interface) =
match ty_interface with
| Some dty ->
let (env, lty) =
Phase.localize_no_subst env ~ignore_errors:false dty
in
(env, Some lty)
| None -> ((env, None), None)
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err2;
(* Check that ty_exp <: arraykey *)
let env =
enum_check_type
env
pos
Reason.URenum_underlying
ty_interface
ty_exp
Typing_error.Callback.enum_underlying_type_must_be_arraykey
in
(* Check that ty_exp <: ty_constraint <: arraykey *)
let (env, ty_err_opt) =
match ty_constraint with
| None -> (env, None)
| Some ty ->
let ((env, ty_err1), ty) =
Phase.localize_no_subst env ~ignore_errors:false ty
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err1;
let env =
enum_check_type
env
pos
Reason.URenum_cstr
None (* Enum classes do not have constraints *)
ty
Typing_error.Callback.enum_constraint_must_be_arraykey
in
Typing_ops.sub_type
(Pos_or_decl.unsafe_to_raw_pos pos)
Reason.URenum_incompatible_cstr
env
ty_exp
ty
Typing_error.Callback.enum_subtype_must_have_compatible_constraint
in
let (env, ty_errs) =
List.fold2_exn
~f:(fun (env, ty_errs) c cty ->
match enum_check_const ty_exp env c cty with
| (env, Some ty_err) -> (env, ty_err :: ty_errs)
| (env, _) -> (env, ty_errs))
~init:(env, Option.to_list ty_err_opt)
consts
const_types
in
(env, Typing_error.multiple_opt ty_errs)
| None -> (env, None)
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
env |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_enum.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val member_type :
Typing_env_types.env -> Typing_defs.class_elt -> Typing_defs.decl_ty
val enum_class_check :
Typing_env_types.env ->
Decl_provider.Class.t ->
Nast.class_const list ->
Typing_defs.locl_ty list ->
Typing_env_types.env |
OCaml | hhvm/hphp/hack/src/typing/typing_env_from_def.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
module Env = Typing_env
module MakeType = Typing_make_type
(*****************************************************************************)
(* Construct a Typing_env from an AAST toplevel definition.
*)
(*****************************************************************************)
open Aast
let fun_env ?origin ctx fd =
let file = Pos.filename (fst fd.fd_name) in
let droot = Some (Typing_deps.Dep.Fun (snd fd.fd_name)) in
let env = Typing_env_types.empty ?origin ctx file ~mode:fd.fd_mode ~droot in
Typing_inference_env.Identifier_provider.reinitialize ();
env
(* Given a class definition construct a type consisting of the
* class instantiated at its generic parameters. *)
let get_self_from_c c =
let tparams =
List.map c.c_tparams ~f:(fun { tp_name = (p, s); _ } ->
mk
( Reason.Rwitness_from_decl (Pos_or_decl.of_raw_pos p),
Tgeneric (s, []) ))
in
let (name_pos, name) = c.c_name in
let name_pos = Pos_or_decl.of_raw_pos name_pos in
mk (Reason.Rwitness_from_decl name_pos, Tapply ((name_pos, name), tparams))
(** Set 'self' identifier and type in environment. *)
let set_self env c =
let self_id = snd c.c_name in
let self = get_self_from_c c in
(* For enums, localize makes self:: into an abstract type, which we don't
* want *)
let (env, self_ty) =
match c.c_kind with
| Ast_defs.Cenum_class _
| Ast_defs.Cenum ->
( env,
MakeType.class_type (Reason.Rwitness (fst c.c_name)) (snd c.c_name) []
)
| Ast_defs.Cinterface
| Ast_defs.Cclass _
| Ast_defs.Ctrait ->
let ((env, ty_err_opt), res) =
Typing_phase.localize_no_subst env ~ignore_errors:true self
in
Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env);
(env, res)
in
let env = Env.set_self env self_id self_ty in
let env =
Env.add_upper_bound env Naming_special_names.Typehints.this self_ty
in
let env =
if c.c_final then
Env.add_lower_bound env Naming_special_names.Typehints.this self_ty
else
env
in
env
let set_parent env c =
(* In order to type-check a class, we need to know what "parent"
* refers to. Sometimes people write "parent::", when that happens,
* we need to know the type of parent.
*)
match c.c_extends with
| ((_, Happly ((_, parent_id), _)) as parent_ty) :: _ ->
let parent_ty = Decl_hint.hint env.Typing_env_types.decl_env parent_ty in
Env.set_parent env parent_id parent_ty
(* The only case where we have more than one parent class is when
* dealing with interfaces and interfaces cannot use parent.
*)
| _ :: _
| _ ->
env
let class_env ?origin ctx c =
let file = Pos.filename (fst c.c_name) in
let droot = Some (Typing_deps.Dep.Type (snd c.c_name)) in
let env = Typing_env_types.empty ?origin ctx file ~mode:c.c_mode ~droot in
Typing_inference_env.Identifier_provider.reinitialize ();
let env = Env.set_current_module env c.c_module in
let env = set_self env c in
let env = set_parent env c in
env
let typedef_env ?origin ctx t =
let file = Pos.filename (fst t.t_kind) in
let droot = Some (Typing_deps.Dep.Type (snd t.t_name)) in
let env = Typing_env_types.empty ?origin ctx file ~mode:t.t_mode ~droot in
Typing_inference_env.Identifier_provider.reinitialize ();
env
let gconst_env ?origin ctx cst =
let file = Pos.filename (fst cst.cst_name) in
let droot = Some (Typing_deps.Dep.GConst (snd cst.cst_name)) in
let env = Typing_env_types.empty ?origin ctx file ~mode:cst.cst_mode ~droot in
Typing_inference_env.Identifier_provider.reinitialize ();
env
let module_env ?origin ctx md =
let file = Pos.filename (fst md.md_name) in
let droot = Some (Typing_deps.Dep.Module (snd md.md_name)) in
Typing_env_types.empty ?origin ctx file ~mode:md.md_mode ~droot |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_env_from_def.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.
*
*)
(** Construct a Typing_env from an AAST toplevel definition. *)
val fun_env :
?origin:Decl_counters.origin ->
Provider_context.t ->
('a, 'b) Aast.fun_def ->
Typing_env_types.env
val class_env :
?origin:Decl_counters.origin ->
Provider_context.t ->
('a, 'b) Aast.class_ ->
Typing_env_types.env
val typedef_env :
?origin:Decl_counters.origin ->
Provider_context.t ->
('a, 'b) Aast.typedef ->
Typing_env_types.env
val gconst_env :
?origin:Decl_counters.origin ->
Provider_context.t ->
('a, 'b) Aast.gconst ->
Typing_env_types.env
val module_env :
?origin:Decl_counters.origin ->
Provider_context.t ->
('a, 'b) Aast.module_def ->
Typing_env_types.env
val get_self_from_c : ('a, 'b) Aast.class_ -> Typing_defs.decl_ty |
OCaml | hhvm/hphp/hack/src/typing/typing_env_return_info.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* Return type information as gathered from explicit hints or inferred *)
type t = {
(* Return type itself. Awaitable<t> is represented explicitly, not stripped.
* In the case of lambdas without an explicit return type hint, the return
* type is determined by context or is a type variable that may get resolved
* when checking the body of the lambda.
*)
return_type: Typing_defs.locl_possibly_enforced_ty;
(* Does the function or function type have the <<__ReturnDisposable>> attribute? *)
return_disposable: bool;
} |
OCaml | hhvm/hphp/hack/src/typing/typing_env_types.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* cf: typing_env_types_sig.mli - These files should be the same *)
open Hh_prelude
open Typing_defs
type locl_ty = Typing_defs.locl_ty
[@@@warning "-32"]
let show_local_id_set_t _ = "<local_id_set_t>"
let pp_local_id_set_t _ _ = Printf.printf "%s\n" "<local_id_set_t>"
type local_id_set_t = Local_id.Set.t
let show_local_env _ = "<local_env>"
let pp_local_env _ _ = Printf.printf "%s\n" "<local_env>"
type local_env = {
per_cont_env: Typing_per_cont_env.t;
local_using_vars: local_id_set_t;
}
let show_env _ = "<env>"
let pp_env _ _ = Printf.printf "%s\n" "<env>"
let show_genv _ = "<genv>"
let pp_genv _ _ = Printf.printf "%s\n" "<genv>"
let show_tfun _ = "<tfun>"
let pp_tfun _ _ = Printf.printf "%s\n" "<tfun>"
[@@@warning "+32"]
type expr_tree_env = {
dsl: Aast.hint;
outer_locals: Typing_local_types.t;
}
(** See the .mli file for the documentation of fields. *)
type env = {
fresh_typarams: SSet.t;
lenv: local_env;
genv: genv;
decl_env: Decl_env.env;
in_loop: bool;
in_try: bool;
in_expr_tree: expr_tree_env option;
inside_constructor: bool;
checked: Tast.check_status;
tracing_info: Decl_counters.tracing_info option;
tpenv: Type_parameter_env.t;
log_levels: int SMap.t;
inference_env: Typing_inference_env.t;
allow_wildcards: bool;
big_envs: (Pos.t * env) list ref;
fun_tast_info: Tast.fun_tast_info option;
loaded_packages: SSet.t;
}
(** See the .mli file for the documentation of fields. *)
and genv = {
tcopt: TypecheckerOptions.t;
callable_pos: Pos.t;
readonly: bool;
return: Typing_env_return_info.t;
params: (locl_ty * Pos.t * locl_ty option) Local_id.Map.t;
condition_types: decl_ty SMap.t;
parent: (string * decl_ty) option;
self: (string * locl_ty) option;
static: bool;
fun_kind: Ast_defs.fun_kind;
val_kind: Typing_defs.val_kind;
fun_is_ctor: bool;
file: Relative_path.t;
current_module: Ast_defs.id option;
this_internal: bool;
this_support_dynamic_type: bool;
no_auto_likes: bool;
}
let initial_local tpenv =
{
per_cont_env =
Typing_per_cont_env.(initial_locals { empty_entry with tpenv });
local_using_vars = Local_id.Set.empty;
}
let empty ?origin ?(mode = FileInfo.Mstrict) ctx file ~droot =
{
fresh_typarams = SSet.empty;
lenv = initial_local Type_parameter_env.empty;
in_loop = false;
in_try = false;
in_expr_tree = None;
inside_constructor = false;
checked = Tast.COnce;
decl_env = { Decl_env.mode; droot; droot_member = None; ctx };
tracing_info =
Option.map origin ~f:(fun origin -> { Decl_counters.origin; file });
genv =
{
tcopt = Provider_context.get_tcopt ctx;
callable_pos = Pos.none;
readonly = false;
return =
{
(* Actually should get set straight away anyway *)
Typing_env_return_info.return_type =
{
et_type = mk (Reason.Rnone, Tunion []);
et_enforced = Unenforced;
};
return_disposable = false;
};
params = Local_id.Map.empty;
condition_types = SMap.empty;
self = None;
static = false;
val_kind = Other;
parent = None;
fun_kind = Ast_defs.FSync;
fun_is_ctor = false;
file;
current_module = None;
this_internal = false;
this_support_dynamic_type = false;
no_auto_likes = false;
};
tpenv = Type_parameter_env.empty;
log_levels = TypecheckerOptions.log_levels (Provider_context.get_tcopt ctx);
inference_env = Typing_inference_env.empty_inference_env;
allow_wildcards = false;
big_envs = ref [];
fun_tast_info = None;
loaded_packages = SSet.empty;
}
let get_log_level env key =
Option.value (SMap.find_opt key env.log_levels) ~default:0
let next_cont_opt env =
Typing_per_cont_env.get_cont_option
Typing_continuations.Next
env.lenv.per_cont_env
let get_tpenv env =
match next_cont_opt env with
| None -> Type_parameter_env.empty
| Some entry -> entry.Typing_per_cont_env.tpenv
let get_pos_and_kind_of_generic env name =
match Type_parameter_env.get_with_pos name (get_tpenv env) with
| Some r -> Some r
| None -> Type_parameter_env.get_with_pos name env.tpenv
let get_lower_bounds env name tyargs =
let tpenv = get_tpenv env in
let local = Type_parameter_env.get_lower_bounds tpenv name tyargs in
let global = Type_parameter_env.get_lower_bounds env.tpenv name tyargs in
Typing_set.union local global
let get_upper_bounds env name tyargs =
let tpenv = get_tpenv env in
let local = Type_parameter_env.get_upper_bounds tpenv name tyargs in
let global = Type_parameter_env.get_upper_bounds env.tpenv name tyargs in
Typing_set.union local global
(* Get bounds that are both an upper and lower of a given generic *)
let get_equal_bounds env name tyargs =
let lower = get_lower_bounds env name tyargs in
let upper = get_upper_bounds env name tyargs in
Typing_set.inter lower upper
let get_tparams_in_ty_and_acc env acc ty =
let tparams_visitor env =
object (this)
inherit [SSet.t] Type_visitor.locl_type_visitor
method! on_tgeneric acc _ s _ =
(* as for tnewtype: not traversing args, although they may contain Tgenerics *)
SSet.add s acc
(* Perserving behavior but this seems incorrect to me since a newtype may
* contain type arguments with generics
*)
method! on_tdependent acc _ _ _ = acc
method! on_tnewtype acc _ _ _ _ = acc
method! on_tvar acc r ix =
let (_env, ty) =
Typing_inference_env.expand_var env.inference_env r ix
in
match get_node ty with
| Tvar _ -> acc
| _ -> this#on_type acc ty
end
in
(tparams_visitor env)#on_type acc ty |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_env_types.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Typing_defs
(** Local environment includes types of locals and bounds on type parameters. *)
type local_env = {
per_cont_env: Typing_per_cont_env.t;
local_using_vars: Local_id.Set.t;
(** Local variables that were assigned in a `using` clause *)
}
(** Contains contextual information useful when type checking an
expression tree. *)
type expr_tree_env = {
dsl: Aast.hint;
(** The DSL the expression tree is representing. For instance in:
SomeDSL`1 + 1`
This hint would reference `SomeDsl` *)
outer_locals: Typing_local_types.t;
(** The set of locals defined outside the expression tree. Ex:
$x = 10;
SomeDSL`1 + 1`;
`$x` would be in this set *)
}
type env = {
fresh_typarams: SSet.t;
lenv: local_env;
genv: genv;
decl_env: Decl_env.env;
in_loop: bool;
in_try: bool;
in_expr_tree: expr_tree_env option;
(** If set to Some(_), then we are performing type checking within a
expression tree. *)
inside_constructor: bool;
checked: Tast.check_status;
(** Set to true when checking if a <<__SoundDynamicallyCallable>> method body
is well-typed under dyn..dyn->dyn assumptions, that is if it can be safely called
in a dynamic environment. *)
tracing_info: Decl_counters.tracing_info option;
(** Tracing_info is a way, when we record telemetry on costs, to also record which
area of the typing code should be considered the originator of that work,
so we can add up which area contributed most to overall costs. *)
tpenv: Type_parameter_env.t;
(** A set of constraints that are global to a given method *)
log_levels: int SMap.t;
inference_env: Typing_inference_env.t;
allow_wildcards: bool;
big_envs: (Pos.t * env) list ref;
fun_tast_info: Tast.fun_tast_info option;
(** This is only filled in after type-checking the function in question *)
loaded_packages: SSet.t;
(** The set of packages loaded via a "package <pkg>" expression *)
}
and genv = {
tcopt: TypecheckerOptions.t;
callable_pos: Pos.t; (** position of the function/method being checked *)
readonly: bool;
(* Whether readonly analysis is needed on this function *)
return: Typing_env_return_info.t;
params: (locl_ty * Pos.t * locl_ty option) Local_id.Map.t;
(** For each function/method parameter, its type, position, and inout "return" type. *)
condition_types: decl_ty SMap.t;
(** condition types associated with parameters.
For every mayberx parameter that has condition type we create
fresh type parameter (see: make_local_param_ty) and store mapping
fresh type name -> condition type in env so it can be retrieved later *)
parent: (string * decl_ty) option;
(** Identifier and type of the parent class if it exists *)
self: (string * locl_ty) option;
(** Identifier and type (instatiated at its generic parameters) of
the enclosing class if there is one *)
static: bool;
fun_kind: Ast_defs.fun_kind;
val_kind: Typing_defs.val_kind;
fun_is_ctor: bool; (** Is the method a constructor? *)
file: Relative_path.t;
(** The file containing the top-level definition that we are checking *)
current_module: Ast_defs.id option;
(** The module of the top-level definition that we are checking *)
this_internal: bool;
(** Is the definition that we are checking marked internal? *)
this_support_dynamic_type: bool;
(** Is the definition that we are checking marked <<__SupportDynamicType>>? *)
no_auto_likes: bool;
(** Is the definition that we are checking marked <<__NoAutoLikes>>? *)
}
val empty :
?origin:Decl_counters.origin ->
?mode:FileInfo.mode ->
Provider_context.t ->
Relative_path.t ->
droot:Typing_deps.Dep.dependent Typing_deps.Dep.variant option ->
env
val get_log_level : env -> string -> int
val next_cont_opt : env -> Typing_per_cont_env.per_cont_entry option
val get_tpenv : env -> Type_parameter_env.t
val get_pos_and_kind_of_generic :
env -> string -> (Pos_or_decl.t * Typing_kinding_defs.kind) option
val get_lower_bounds :
env -> string -> locl_ty list -> Type_parameter_env.tparam_bounds
val get_upper_bounds :
env -> string -> locl_ty list -> Type_parameter_env.tparam_bounds
val get_equal_bounds :
env -> string -> locl_ty list -> Type_parameter_env.tparam_bounds
val get_tparams_in_ty_and_acc : env -> SSet.t -> locl_ty -> SSet.t |
OCaml | hhvm/hphp/hack/src/typing/typing_equality_check.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Typing_defs
module Env = Typing_env
module TDef = Typing_tdef
module N = Aast
(*****************************************************************************)
(* Check if a comparison is trivially true or false *)
(*****************************************************************************)
let trivial_result_str bop =
match bop with
| Ast_defs.Eqeqeq -> false
| Ast_defs.Diff2 -> true
| _ -> assert false
let trivial_comparison_error env p bop ty1 ty2 trail1 trail2 =
let result = trivial_result_str bop
and tys1 = lazy (Typing_print.error env ty1)
and tys2 = lazy (Typing_print.error env ty2) in
Typing_error_utils.add_typing_error
~env
Typing_error.(
primary
@@ Primary.Trivial_strict_eq
{
pos = p;
result;
left =
Lazy.map tys1 ~f:(fun tys1 ->
Reason.to_string ("This is " ^ tys1) (get_reason ty1));
right =
Lazy.map tys2 ~f:(fun tys2 ->
Reason.to_string ("This is " ^ tys2) (get_reason ty2));
left_trail = trail1;
right_trail = trail2;
})
let eq_incompatible_types env p ty1 ty2 =
let tys1 = lazy (Typing_print.error env ty1)
and tys2 = lazy (Typing_print.error env ty2) in
Typing_error_utils.add_typing_error
~env
Typing_error.(
primary
@@ Primary.Eq_incompatible_types
{
pos = p;
left =
Lazy.map tys1 ~f:(fun tys1 ->
Reason.to_string ("This is " ^ tys1) (get_reason ty1));
right =
Lazy.map tys2 ~f:(fun tys2 ->
Reason.to_string ("This is " ^ tys2) (get_reason ty2));
})
let is_arraykey t =
match get_node t with
| Tprim N.Tarraykey -> true
| _ -> false
let bad_compare_prim_to_enum ty enum_bound =
match get_node enum_bound with
| Tprim enum_bound ->
(match (enum_bound, ty) with
| (N.Tint, (N.Tint | N.Tarraykey | N.Tnum)) -> false
| (N.Tint, _) -> true
| (N.Tstring, (N.Tstring | N.Tarraykey)) -> false
| (N.Tstring, _) -> true
| (N.Tarraykey, (N.Tarraykey | N.Tint | N.Tstring | N.Tnum)) -> false
| (N.Tarraykey, _) -> true
| _ -> false)
| _ -> false
let rec assert_nontrivial p bop env ty1 ty2 =
let ety_env = empty_expand_env in
let (_, ty1) = Env.expand_type env ty1 in
let (_, ety1, trail1) = TDef.force_expand_typedef ~ety_env env ty1 in
let (_, ty2) = Env.expand_type env ty2 in
let (_, ety2, trail2) = TDef.force_expand_typedef ~ety_env env ty2 in
match (get_node ty1, get_node ty2) with
(* Disallow `===` on distinct abstract enum types. *)
(* Future: consider putting this in typed lint not type checking *)
| (Tnewtype (e1, _, bound1), Tnewtype (e2, _, bound2))
when Env.is_enum env e1
&& Env.is_enum env e2
&& is_arraykey bound1
&& is_arraykey bound2 ->
if String.equal e1 e2 then
()
else
eq_incompatible_types env p ety1 ety2
| _ ->
(match (deref ety1, deref ety2) with
| ((_, Tprim N.Tnum), (_, Tprim N.Tarraykey))
| ((_, Tprim N.Tarraykey), (_, Tprim N.Tnum)) ->
()
| ((_, Tprim N.Tnum), (_, Tprim (N.Tint | N.Tfloat)))
| ((_, Tprim (N.Tint | N.Tfloat)), (_, Tprim N.Tnum)) ->
()
| ((_, Tprim N.Tarraykey), (_, Tprim (N.Tint | N.Tstring)))
| ((_, Tprim (N.Tint | N.Tstring)), (_, Tprim N.Tarraykey)) ->
()
| ((_, Tprim N.Tnull), _)
| (_, (_, Tprim N.Tnull)) ->
()
| ((r, Tprim N.Tnoreturn), _)
| (_, (r, Tprim N.Tnoreturn)) ->
Typing_error_utils.add_typing_error
~env
Typing_error.(
wellformedness
@@ Primary.Wellformedness.Noreturn_usage
{
pos = p;
reason =
lazy (Reason.to_string "This always throws or exits" r);
})
| ((r, Tprim N.Tvoid), _)
| (_, (r, Tprim N.Tvoid)) ->
(* Ideally we shouldn't hit this case, but well... *)
Typing_error_utils.add_typing_error
~env
Typing_error.(
wellformedness
@@ Primary.Wellformedness.Void_usage
{ pos = p; reason = lazy (Reason.to_string "This is `void`" r) })
| ((_, Tprim a), (_, Tnewtype (e, _, bound)))
when Env.is_enum env e && bad_compare_prim_to_enum a bound ->
trivial_comparison_error env p bop ty1 bound trail1 trail2
| ((_, Tnewtype (e, _, bound)), (_, Tprim a))
when Env.is_enum env e && bad_compare_prim_to_enum a bound ->
trivial_comparison_error env p bop bound ty2 trail1 trail2
| ((_, Tprim a), (_, Tprim b)) when not (Aast.equal_tprim a b) ->
trivial_comparison_error env p bop ty1 ty2 trail1 trail2
| ((_, Toption ty1), (_, Tprim _)) -> assert_nontrivial p bop env ty1 ty2
| ((_, Tprim _), (_, Toption ty2)) -> assert_nontrivial p bop env ty1 ty2
| ( ( _,
( Tany _ | Tnonnull | Tvec_or_dict _ | Tprim _ | Toption _ | Tdynamic
| Tvar _ | Tfun _ | Tgeneric _ | Tnewtype _ | Tdependent _ | Tclass _
| Ttuple _ | Tunion _ | Tintersection _ | Tshape _ | Taccess _
| Tunapplied_alias _ | Tneg _ ) ),
_ ) ->
()) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_equality_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 assert_nontrivial :
Pos.t ->
Ast_defs.bop ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_defs.locl_ty ->
unit |
OCaml | hhvm/hphp/hack/src/typing/typing_error.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module Error_code = Error_codes.Typing
module Primary = struct
module Shape = struct
type t =
| Invalid_shape_field_name of {
pos: Pos.t;
is_empty: bool;
}
| Invalid_shape_field_literal of {
pos: Pos.t;
witness_pos: Pos.t;
}
| Invalid_shape_field_const of {
pos: Pos.t;
witness_pos: Pos.t;
}
| Invalid_shape_field_type of {
pos: Pos.t;
ty_pos: Pos_or_decl.t;
ty_name: string Lazy.t;
trail: Pos_or_decl.t list;
}
| Shape_field_class_mismatch of {
pos: Pos.t;
class_name: string;
witness_pos: Pos.t;
witness_class_name: string;
}
| Shape_field_type_mismatch of {
pos: Pos.t;
ty_name: string Lazy.t;
witness_pos: Pos.t;
witness_ty_name: string Lazy.t;
}
| Invalid_shape_remove_key of Pos.t
| Shapes_key_exists_always_true of {
pos: Pos.t;
field_name: string;
decl_pos: Pos_or_decl.t;
}
| Shapes_key_exists_always_false of {
pos: Pos.t;
field_name: string;
decl_pos: Pos_or_decl.t;
reason:
[ `Nothing of Pos_or_decl.t Message.t list Lazy.t | `Undefined ];
}
| Shapes_method_access_with_non_existent_field of {
pos: Pos.t;
field_name: string;
decl_pos: Pos_or_decl.t;
method_name: string;
reason:
[ `Nothing of Pos_or_decl.t Message.t list Lazy.t | `Undefined ];
}
| Shapes_access_with_non_existent_field of {
pos: Pos.t;
field_name: string;
decl_pos: Pos_or_decl.t;
reason:
[ `Nothing of Pos_or_decl.t Message.t list Lazy.t | `Undefined ];
}
[@@deriving show]
end
module Enum = struct
type t =
| Enum_switch_redundant of {
pos: Pos.t;
first_pos: Pos.t;
const_name: string;
}
| Enum_switch_nonexhaustive of {
pos: Pos.t;
kind: string;
decl_pos: Pos_or_decl.t;
missing: string list;
}
| Enum_switch_redundant_default of {
pos: Pos.t;
kind: string;
decl_pos: Pos_or_decl.t;
}
| Enum_switch_not_const of Pos.t
| Enum_switch_wrong_class of {
pos: Pos.t;
kind: string;
expected: string;
actual: string;
}
| Enum_type_bad of {
pos: Pos.t;
ty_name: string Lazy.t;
is_enum_class: bool;
trail: Pos_or_decl.t list;
}
| Enum_type_bad_case_type of {
pos: Pos.t;
ty_name: string Lazy.t;
case_type_decl_pos: Pos_or_decl.t;
}
| Enum_constant_type_bad of {
pos: Pos.t;
ty_pos: Pos_or_decl.t;
ty_name: string Lazy.t;
trail: Pos_or_decl.t list;
}
| Enum_type_typedef_nonnull of Pos.t
| Enum_class_label_unknown of {
pos: Pos.t;
label_name: string;
enum_name: string;
decl_pos: Pos_or_decl.t;
most_similar: (string * Pos_or_decl.t) option;
ty_pos: Pos_or_decl.t option;
}
| Enum_class_label_as_expr of Pos.t
| Enum_class_label_member_mismatch of {
pos: Pos.t;
label: string;
expected_ty_msg_opt: Pos_or_decl.t Message.t list Lazy.t option;
}
| Incompatible_enum_inclusion_base of {
pos: Pos.t;
classish_name: string;
src_classish_name: string;
}
| Incompatible_enum_inclusion_constraint of {
pos: Pos.t;
classish_name: string;
src_classish_name: string;
}
| Enum_inclusion_not_enum of {
pos: Pos.t;
classish_name: string;
src_classish_name: string;
}
[@@deriving show]
end
module Expr_tree = struct
type t =
| Expression_tree_non_public_member of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Reified_static_method_in_expr_tree of Pos.t
| This_var_in_expr_tree of Pos.t
| Experimental_expression_trees of Pos.t
| Expression_tree_unsupported_operator of {
pos: Pos.t;
member_name: string;
class_name: string;
}
[@@deriving show]
end
module Readonly = struct
type t =
| Readonly_modified of {
pos: Pos.t;
reason_opt: Pos_or_decl.t Message.t Lazy.t option;
}
| Readonly_mismatch of {
pos: Pos.t;
what: [ `arg_readonly | `arg_mut | `collection_mod | `prop_assign ];
pos_sub: Pos_or_decl.t;
pos_super: Pos_or_decl.t;
}
| Readonly_invalid_as_mut of Pos.t
| Readonly_exception of Pos.t
| Explicit_readonly_cast of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
kind: [ `fn_call | `property | `static_property ];
}
| Readonly_method_call of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Readonly_closure_call of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
suggestion: string;
}
[@@deriving show]
end
module Ifc = struct
type t =
| Illegal_information_flow of {
pos: Pos.t;
secondaries: Pos_or_decl.t list;
source_poss: Pos_or_decl.t list;
source: string;
sink_poss: Pos_or_decl.t list;
sink: string;
}
| Context_implicit_policy_leakage of {
pos: Pos.t;
secondaries: Pos_or_decl.t list;
source_poss: Pos_or_decl.t list;
source: string;
sink_poss: Pos_or_decl.t list;
sink: string;
}
| Unknown_information_flow of {
pos: Pos.t;
what: string;
}
| Ifc_internal_error of {
pos: Pos.t;
msg: string;
}
[@@deriving show]
end
module Coeffect = struct
type t =
| Call_coeffect of {
pos: Pos.t;
available_pos: Pos_or_decl.t;
available_incl_unsafe: string Lazy.t;
required_pos: Pos_or_decl.t;
required: string Lazy.t;
}
| Op_coeffect_error of {
pos: Pos.t;
op_name: string;
locally_available: string Lazy.t;
available_pos: Pos_or_decl.t;
err_code: Error_code.t;
required: string Lazy.t;
suggestion: Pos_or_decl.t Message.t list Lazy.t option;
}
[@@deriving show]
end
module Wellformedness = struct
type t =
| Missing_return of {
pos: Pos.t;
hint_pos: Pos_or_decl.t option;
is_async: bool;
}
| Void_usage of {
pos: Pos.t;
reason: Pos_or_decl.t Message.t list Lazy.t;
}
| Noreturn_usage of {
pos: Pos.t;
reason: Pos_or_decl.t Message.t list Lazy.t;
}
| Returns_with_and_without_value of {
pos: Pos.t;
with_value_pos: Pos.t;
without_value_pos_opt: Pos.t option;
}
| Non_void_annotation_on_return_void_function of {
is_async: bool;
hint_pos: Pos.t;
}
| Tuple_syntax of Pos.t
| Invalid_class_refinement of { pos: Pos.t }
[@@deriving show]
end
module Modules = struct
type t =
| Module_hint of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Module_mismatch of {
pos: Pos.t;
current_module_opt: string option;
decl_pos: Pos_or_decl.t;
target_module: string;
}
| Module_unsafe_trait_access of {
access_pos: Pos.t;
trait_pos: Pos_or_decl.t;
}
| Module_missing_import of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
module_pos: Pos_or_decl.t;
current_module: string;
target_module_opt: string option;
}
| Module_missing_export of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
module_pos: Pos_or_decl.t;
current_module_opt: string option;
target_module: string;
}
| Module_cross_pkg_access of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
module_pos: Pos_or_decl.t;
package_pos: Pos.t;
current_module_opt: string option;
current_package_opt: string option;
target_module_opt: string option;
target_package_opt: string option;
}
| Module_cross_pkg_call of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
current_package_opt: string option;
target_package_opt: string option;
}
| Module_soft_included_access of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
module_pos: Pos_or_decl.t;
package_pos: Pos.t;
current_module_opt: string option;
current_package_opt: string option;
target_module_opt: string option;
target_package_opt: string option;
}
[@@deriving show]
end
module Xhp = struct
type t =
| Xhp_required of {
pos: Pos.t;
why_xhp: string;
ty_reason_msg: Pos_or_decl.t Message.t list Lazy.t;
}
| Illegal_xhp_child of {
pos: Pos.t;
ty_reason_msg: Pos_or_decl.t Message.t list Lazy.t;
}
| Missing_xhp_required_attr of {
pos: Pos.t;
attr: string;
ty_reason_msg: Pos_or_decl.t Message.t list Lazy.t;
}
[@@deriving show]
end
module CaseType = struct
type t =
| Overlapping_variant_types of {
pos: Pos.t;
name: string;
tag: string;
why: Pos_or_decl.t Message.t list Lazy.t;
}
| Unrecoverable_variant_type of {
pos: Pos.t;
name: string;
hints: (Pos.t * string) list;
}
[@@deriving show]
end
type t =
(* Factorised errors *)
| Coeffect of Coeffect.t
| Enum of Enum.t
| Expr_tree of Expr_tree.t
| Ifc of Ifc.t
| Modules of Modules.t
| Readonly of Readonly.t
| Shape of Shape.t
| Wellformedness of Wellformedness.t
| Xhp of Xhp.t
| CaseType of CaseType.t
(* Primary only *)
| Unresolved_tyvar of Pos.t
| Unify_error of {
pos: Pos.t;
msg_opt: string option;
reasons_opt: Pos_or_decl.t Message.t list Lazy.t option;
}
| Generic_unify of {
pos: Pos.t;
msg: string;
}
| Using_error of {
pos: Pos.t;
has_await: bool;
}
| Bad_enum_decl of Pos.t
| Bad_conditional_support_dynamic of {
pos: Pos.t;
child: string;
parent: string;
ty_name: string Lazy.t;
self_ty_name: string Lazy.t;
}
| Bad_decl_override of {
pos: Pos.t;
name: string;
parent_name: string;
}
| Explain_where_constraint of {
pos: Pos.t;
in_class: bool;
decl_pos: Pos_or_decl.t;
}
| Explain_constraint of Pos.t
| Rigid_tvar_escape of {
pos: Pos.t;
what: string;
}
| Invalid_type_hint of Pos.t
| Unsatisfied_req of {
pos: Pos.t;
trait_pos: Pos_or_decl.t;
req_pos: Pos_or_decl.t;
req_name: string;
}
| Unsatisfied_req_class of {
pos: Pos.t;
trait_pos: Pos_or_decl.t;
req_pos: Pos_or_decl.t;
req_name: string;
}
| Req_class_not_final of {
pos: Pos.t;
trait_pos: Pos_or_decl.t;
req_pos: Pos_or_decl.t;
}
| Incompatible_reqs of {
pos: Pos.t;
req_name: string;
req_class_pos: Pos_or_decl.t;
req_extends_pos: Pos_or_decl.t;
}
| Trait_not_used of {
pos: Pos.t;
trait_name: string;
req_class_pos: Pos_or_decl.t;
class_pos: Pos_or_decl.t;
class_name: string;
}
| Invalid_echo_argument of Pos.t
| Index_type_mismatch of {
pos: Pos.t;
is_covariant_container: bool;
msg_opt: string option;
reasons_opt: Pos_or_decl.t Message.t list Lazy.t option;
}
| Member_not_found of {
pos: Pos.t;
kind: [ `method_ | `property ];
class_name: string;
class_pos: Pos_or_decl.t;
member_name: string;
hint: ([ `instance | `static ] * Pos_or_decl.t * string) option Lazy.t;
reason: Pos_or_decl.t Message.t list Lazy.t;
}
| Construct_not_instance_method of Pos.t
| Ambiguous_inheritance of {
pos: Pos.t;
class_name: string;
origin: string;
}
| Expected_tparam of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
n: int;
}
| Typeconst_concrete_concrete_override of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Constant_multiple_concrete_conflict of {
pos: Pos.t;
name: string;
definitions: (Pos_or_decl.t * string option) list;
}
| Invalid_memoized_param of {
pos: Pos.t;
ty_name: string Lazy.t;
reason: Pos_or_decl.t Message.t list Lazy.t;
}
| Invalid_arraykey of {
pos: Pos.t;
ctxt: [ `read | `write ];
container_pos: Pos_or_decl.t;
container_ty_name: string Lazy.t;
key_pos: Pos_or_decl.t;
key_ty_name: string Lazy.t;
}
| Invalid_keyset_value of {
pos: Pos.t;
container_pos: Pos_or_decl.t;
container_ty_name: string Lazy.t;
value_pos: Pos_or_decl.t;
value_ty_name: string Lazy.t;
}
| Invalid_set_value of {
pos: Pos.t;
container_pos: Pos_or_decl.t;
container_ty_name: string Lazy.t;
value_pos: Pos_or_decl.t;
value_ty_name: string Lazy.t;
}
| HKT_alias_with_implicit_constraints of {
pos: Pos.t;
typedef_pos: Pos_or_decl.t;
used_class_in_def_pos: Pos_or_decl.t;
typedef_name: string;
typedef_tparam_name: string;
used_class_in_def_name: string;
used_class_tparam_name: string;
}
| HKT_wildcard of Pos.t
| HKT_implicit_argument of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
param_name: string;
}
| Invalid_substring of {
pos: Pos.t;
ty_name: string Lazy.t;
}
| Unset_nonidx_in_strict of {
pos: Pos.t;
reason: Pos_or_decl.t Message.t list Lazy.t;
}
| Nullable_cast of {
pos: Pos.t;
ty_pos: Pos_or_decl.t;
ty_name: string Lazy.t;
}
| Hh_expect of {
pos: Pos.t;
equivalent: bool;
}
| Null_member of {
pos: Pos.t;
obj_pos_opt: Pos.t option;
ctxt: [ `read | `write ];
kind: [ `method_ | `property ];
member_name: string;
reason: Pos_or_decl.t Message.t list Lazy.t;
}
| Nullsafe_property_write_context of Pos.t
| Uninstantiable_class of {
pos: Pos.t;
class_name: string;
reason_ty_opt: (Pos.t * string Lazy.t) option;
decl_pos: Pos_or_decl.t;
}
| Abstract_const_usage of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
name: string;
}
| Member_not_implemented of {
pos: Pos.t;
member_name: string;
decl_pos: Pos_or_decl.t;
quickfixes: Pos.t Quickfix.t list;
}
| Kind_mismatch of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
tparam_name: string;
expected_kind: string;
actual_kind: string;
}
| Trait_parent_construct_inconsistent of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Top_member of {
pos: Pos.t;
ctxt: [ `read | `write ];
ty_name: string Lazy.t;
decl_pos: Pos_or_decl.t;
kind: [ `method_ | `property ];
name: string;
is_nullable: bool;
ty_reasons: (Pos_or_decl.t * string) list Lazy.t;
}
| Unresolved_tyvar_projection of {
pos: Pos.t;
proj_pos: Pos_or_decl.t;
tconst_name: string;
}
| Cyclic_class_constant of {
pos: Pos.t;
class_name: string;
const_name: string;
}
| Inout_annotation_missing of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Inout_annotation_unexpected of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
param_is_variadic: bool;
qfx_pos: Pos.t;
}
| Inout_argument_bad_type of {
pos: Pos.t;
reasons: Pos_or_decl.t Message.t list Lazy.t;
}
| Invalid_meth_caller_calling_convention of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
convention: string;
}
| Invalid_meth_caller_readonly_return of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Invalid_new_disposable of Pos.t
| Invalid_return_disposable of Pos.t
| Invalid_disposable_hint of {
pos: Pos.t;
class_name: string;
}
| Invalid_disposable_return_hint of {
pos: Pos.t;
class_name: string;
}
| Ambiguous_lambda of {
pos: Pos.t;
uses: Pos_or_decl.t Message.t list Lazy.t;
}
| Wrong_extend_kind of {
pos: Pos.t;
kind: Ast_defs.classish_kind;
name: string;
parent_pos: Pos_or_decl.t;
parent_kind: Ast_defs.classish_kind;
parent_name: string;
}
| Cyclic_class_def of {
pos: Pos.t;
stack: SSet.t;
}
| Trait_reuse_with_final_method of {
pos: Pos.t;
trait_name: string;
parent_cls_name: string Lazy.t;
trace: Pos_or_decl.t Message.t list Lazy.t;
}
| Trait_reuse_inside_class of {
pos: Pos.t;
class_name: string;
trait_name: string;
occurrences: Pos_or_decl.t list;
}
| Invalid_is_as_expression_hint of {
pos: Pos.t;
op: [ `is | `as_ ];
reasons: Pos_or_decl.t Message.t list Lazy.t;
}
| Invalid_enforceable_type of {
pos: Pos.t;
ty_info: Pos_or_decl.t Message.t list Lazy.t;
tp_pos: Pos_or_decl.t;
tp_name: string;
kind: [ `constant | `param ];
}
| Reifiable_attr of {
pos: Pos.t;
ty_info: Pos_or_decl.t Message.t list Lazy.t;
attr_pos: Pos_or_decl.t;
kind: [ `ty | `cnstr | `super_cnstr ];
}
| Invalid_newable_type_argument of {
pos: Pos.t;
tp_pos: Pos_or_decl.t;
tp_name: string;
}
| Invalid_newable_typaram_constraints of {
pos: Pos.t;
tp_name: string;
constraints: string list;
}
| Override_per_trait of {
pos: Pos.t;
class_name: string;
meth_name: string;
trait_name: string;
meth_pos: Pos_or_decl.t;
}
| Should_not_be_override of {
pos: Pos.t;
class_id: string;
id: string;
}
| Trivial_strict_eq of {
pos: Pos.t;
result: bool;
left: Pos_or_decl.t Message.t list Lazy.t;
right: Pos_or_decl.t Message.t list Lazy.t;
left_trail: Pos_or_decl.t list;
right_trail: Pos_or_decl.t list;
}
| Trivial_strict_not_nullable_compare_null of {
pos: Pos.t;
result: bool;
ty_reason_msg: Pos_or_decl.t Message.t list Lazy.t;
}
| Eq_incompatible_types of {
pos: Pos.t;
left: Pos_or_decl.t Message.t list Lazy.t;
right: Pos_or_decl.t Message.t list Lazy.t;
}
| Comparison_invalid_types of {
pos: Pos.t;
left: Pos_or_decl.t Message.t list Lazy.t;
right: Pos_or_decl.t Message.t list Lazy.t;
}
| Strict_eq_value_incompatible_types of {
pos: Pos.t;
left: Pos_or_decl.t Message.t list Lazy.t;
right: Pos_or_decl.t Message.t list Lazy.t;
}
| Deprecated_use of {
pos: Pos.t;
decl_pos_opt: Pos_or_decl.t option;
msg: string;
}
| Cannot_declare_constant of {
pos: Pos.t;
class_pos: Pos.t;
class_name: string;
}
| Invalid_classname of Pos.t
| Illegal_type_structure of {
pos: Pos.t;
msg: string;
}
| Illegal_typeconst_direct_access of Pos.t
| Wrong_expression_kind_attribute of {
pos: Pos.t;
attr_name: string;
expr_kind: string;
attr_class_pos: Pos_or_decl.t;
attr_class_name: string;
intf_name: string;
}
| Ambiguous_object_access of {
pos: Pos.t;
name: string;
self_pos: Pos_or_decl.t;
vis: string;
subclass_pos: Pos_or_decl.t;
class_self: string;
class_subclass: string;
}
| Unserializable_type of {
pos: Pos.t;
message: string;
}
| Invalid_arraykey_constraint of {
pos: Pos.t;
ty_name: string Lazy.t;
}
| Redundant_covariant of {
pos: Pos.t;
msg: string;
suggest: string;
}
| Meth_caller_trait of {
pos: Pos.t;
trait_name: string;
}
| Duplicate_interface of {
pos: Pos.t;
name: string;
others: Pos_or_decl.t list;
}
| Reified_function_reference of Pos.t
| Class_meth_abstract_call of {
pos: Pos.t;
class_name: string;
meth_name: string;
decl_pos: Pos_or_decl.t;
}
| Reinheriting_classish_const of {
pos: Pos.t;
classish_name: string;
src_pos: Pos.t;
src_classish_name: string;
existing_const_origin: string;
const_name: string;
}
| Redeclaring_classish_const of {
pos: Pos.t;
classish_name: string;
redeclaration_pos: Pos.t;
existing_const_origin: string;
const_name: string;
}
| Abstract_function_pointer of {
pos: Pos.t;
class_name: string;
meth_name: string;
decl_pos: Pos_or_decl.t;
}
| Inherited_class_member_with_different_case of {
pos: Pos.t;
member_type: string;
name: string;
name_prev: string;
child_class: string;
prev_class: string;
prev_class_pos: Pos_or_decl.t;
}
| Multiple_inherited_class_member_with_different_case of {
pos: Pos.t;
child_class_name: string;
member_type: string;
class1_name: string;
class1_pos: Pos_or_decl.t;
name1: string;
class2_name: string;
class2_pos: Pos_or_decl.t;
name2: string;
}
| Parent_support_dynamic_type of {
pos: Pos.t;
child_name: string;
child_kind: Ast_defs.classish_kind;
parent_name: string;
parent_kind: Ast_defs.classish_kind;
child_support_dyn: bool;
}
| Property_is_not_enforceable of {
pos: Pos.t;
prop_name: string;
class_name: string;
prop_pos: Pos_or_decl.t;
prop_type: string;
}
| Property_is_not_dynamic of {
pos: Pos.t;
prop_name: string;
class_name: string;
prop_pos: Pos_or_decl.t;
prop_type: string;
}
| Private_property_is_not_enforceable of {
pos: Pos.t;
prop_name: string;
class_name: string;
prop_pos: Pos_or_decl.t;
prop_type: string;
}
| Private_property_is_not_dynamic of {
pos: Pos.t;
prop_name: string;
class_name: string;
prop_pos: Pos_or_decl.t;
prop_type: string;
}
| Immutable_local of Pos.t
| Nonsense_member_selection of {
pos: Pos.t;
kind: string;
}
| Consider_meth_caller of {
pos: Pos.t;
class_name: string;
meth_name: string;
}
| Method_import_via_diamond of {
pos: Pos.t;
class_name: string;
method_pos: Pos_or_decl.t;
method_name: string;
trace1: Pos_or_decl.t Message.t list Lazy.t;
trace2: Pos_or_decl.t Message.t list Lazy.t;
}
| Property_import_via_diamond of {
generic: bool;
pos: Pos.t;
class_name: string;
property_pos: Pos_or_decl.t;
property_name: string;
trace1: Pos_or_decl.t Message.t list Lazy.t;
trace2: Pos_or_decl.t Message.t list Lazy.t;
}
| Unification_cycle of {
pos: Pos.t;
ty_name: string Lazy.t;
}
| Method_variance of Pos.t
| Explain_tconst_where_constraint of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
msgs: Pos_or_decl.t Message.t list Lazy.t;
}
| Format_string of {
pos: Pos.t;
snippet: string;
fmt_string: string;
class_pos: Pos_or_decl.t;
fn_name: string;
class_suggest: string;
}
| Expected_literal_format_string of Pos.t
| Re_prefixed_non_string of {
pos: Pos.t;
reason: [ `non_string | `embedded_expr ];
}
| Bad_regex_pattern of {
pos: Pos.t;
reason:
[ `missing_delim
| `empty_patt
| `invalid_option
| `bad_patt of string
];
}
| Generic_array_strict of Pos.t
| Option_return_only_typehint of {
pos: Pos.t;
kind: [ `void | `noreturn ];
}
| Redeclaring_missing_method of {
pos: Pos.t;
trait_method: string;
}
| Expecting_type_hint of Pos.t
| Expecting_type_hint_variadic of Pos.t
| Expecting_return_type_hint of Pos.t
| Duplicate_using_var of Pos.t
| Illegal_disposable of {
pos: Pos.t;
verb: [ `assigned ];
}
| Escaping_disposable of Pos.t
| Escaping_disposable_param of Pos.t
| Escaping_this of Pos.t
| Must_extend_disposable of Pos.t
| Field_kinds of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Unbound_name of {
pos: Pos.t;
name: string;
class_exists: bool;
}
| Previous_default of Pos.t
| Return_in_void of {
pos: Pos.t;
decl_pos: Pos.t;
}
| This_var_outside_class of Pos.t
| Unbound_global of Pos.t
| Private_inst_meth of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Protected_inst_meth of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Private_meth_caller of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Protected_meth_caller of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Private_class_meth of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Protected_class_meth of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Array_cast of Pos.t
| String_cast of {
pos: Pos.t;
ty_name: string Lazy.t;
}
| Static_outside_class of Pos.t
| Self_outside_class of Pos.t
| New_inconsistent_construct of {
pos: Pos.t;
class_pos: Pos_or_decl.t;
class_name: string;
kind: [ `static | `classname ];
}
| Undefined_parent of Pos.t
| Parent_outside_class of Pos.t
| Parent_abstract_call of {
pos: Pos.t;
meth_name: string;
decl_pos: Pos_or_decl.t;
}
| Self_abstract_call of {
pos: Pos.t;
self_pos: Pos.t;
meth_name: string;
decl_pos: Pos_or_decl.t;
}
| Classname_abstract_call of {
pos: Pos.t;
meth_name: string;
class_name: string;
decl_pos: Pos_or_decl.t;
}
| Static_synthetic_method of {
pos: Pos.t;
meth_name: string;
class_name: string;
decl_pos: Pos_or_decl.t;
}
| Isset_in_strict of Pos.t
| Isset_inout_arg of Pos.t
| Unpacking_disallowed_builtin_function of {
pos: Pos.t;
fn_name: string;
}
| Array_get_arity of {
pos: Pos.t;
name: string;
decl_pos: Pos_or_decl.t;
}
| Undefined_field of {
pos: Pos.t;
name: string;
decl_pos: Pos_or_decl.t;
}
| Array_access of {
pos: Pos.t;
ctxt: [ `read | `write ];
ty_name: string Lazy.t;
decl_pos: Pos_or_decl.t;
}
| Keyset_set of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Array_append of {
pos: Pos.t;
ty_name: string Lazy.t;
decl_pos: Pos_or_decl.t;
}
| Const_mutation of {
pos: Pos.t;
ty_name: string Lazy.t;
decl_pos: Pos_or_decl.t;
}
| Expected_class of {
pos: Pos.t;
suffix: string Lazy.t option;
}
| Unknown_type of {
pos: Pos.t;
expected: string;
reason: Pos_or_decl.t Message.t list Lazy.t;
}
| Parent_in_trait of Pos.t
| Parent_undefined of Pos.t
| Constructor_no_args of Pos.t
| Visibility of {
pos: Pos.t;
msg: string;
decl_pos: Pos_or_decl.t;
reason_msg: string;
}
| Bad_call of {
pos: Pos.t;
ty_name: string Lazy.t;
}
| Extend_final of {
pos: Pos.t;
name: string;
decl_pos: Pos_or_decl.t;
}
| Extend_sealed of {
pos: Pos.t;
parent_pos: Pos_or_decl.t;
parent_name: string;
parent_kind: [ `intf | `trait | `class_ | `enum | `enum_class ];
verb: [ `extend | `implement | `use ];
}
| Sealed_not_subtype of {
pos: Pos.t;
name: string;
child_kind: Ast_defs.classish_kind;
child_pos: Pos_or_decl.t;
child_name: string;
}
| Trait_prop_const_class of {
pos: Pos.t;
name: string;
}
| Implement_abstract of {
pos: Pos.t;
is_final: bool;
decl_pos: Pos_or_decl.t;
trace: Pos_or_decl.t Message.t list Lazy.t;
name: string;
kind: [ `meth | `prop | `const | `ty_const ];
quickfixes: Pos.t Quickfix.t list;
}
| Abstract_member_in_concrete_class of {
pos: Pos.t;
class_name_pos: Pos.t;
is_final: bool;
member_kind: [ `method_ | `property | `constant | `type_constant ];
member_name: string;
}
| Generic_static of {
pos: Pos.t;
typaram_name: string;
}
| Ellipsis_strict_mode of {
pos: Pos.t;
require: [ `Param_name | `Type_and_param_name ];
}
| Object_string of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Object_string_deprecated of Pos.t
| Cyclic_typedef of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Require_args_reify of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Require_generic_explicit of {
pos: Pos.t;
param_name: string;
decl_pos: Pos_or_decl.t;
}
| Invalid_reified_arg of {
pos: Pos.t;
param_name: string;
decl_pos: Pos_or_decl.t;
arg_info: Pos_or_decl.t Message.t list Lazy.t;
}
| Invalid_reified_arg_reifiable of {
pos: Pos.t;
param_name: string;
decl_pos: Pos_or_decl.t;
ty_pos: Pos_or_decl.t;
ty_msg: string Lazy.t;
}
| New_class_reified of {
pos: Pos.t;
class_kind: string;
suggested_class_name: string option;
}
| Class_get_reified of Pos.t
| Static_meth_with_class_reified_generic of {
pos: Pos.t;
generic_pos: Pos.t;
}
| Consistent_construct_reified of Pos.t
| Bad_fn_ptr_construction of Pos.t
| Reified_generics_not_allowed of Pos.t
| New_without_newable of {
pos: Pos.t;
name: string;
}
| Discarded_awaitable of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Unknown_object_member of {
pos: Pos.t;
member_name: string;
elt: [ `meth | `prop ];
reason: Pos_or_decl.t Message.t list Lazy.t;
}
| Non_class_member of {
pos: Pos.t;
member_name: string;
elt: [ `meth | `prop ];
ty_name: string Lazy.t;
decl_pos: Pos_or_decl.t;
}
| Null_container of {
pos: Pos.t;
null_witness: Pos_or_decl.t Message.t list Lazy.t;
}
| Declared_covariant of {
pos: Pos.t;
param_pos: Pos.t;
msgs: Pos.t Message.t list Lazy.t;
}
| Declared_contravariant of {
pos: Pos.t;
param_pos: Pos.t;
msgs: Pos.t Message.t list Lazy.t;
}
| Static_prop_type_generic_param of {
pos: Pos.t;
var_ty_pos: Pos_or_decl.t;
class_pos: Pos_or_decl.t;
}
| Contravariant_this of {
pos: Pos.t;
class_name: string;
typaram_name: string;
}
| Cyclic_typeconst of {
pos: Pos.t;
tyconst_names: string list;
}
| Array_get_with_optional_field of {
recv_pos: Pos.t;
field_pos: Pos.t;
field_name: string;
decl_pos: Pos_or_decl.t;
}
| Mutating_const_property of Pos.t
| Self_const_parent_not of Pos.t
| Unexpected_ty_in_tast of {
pos: Pos.t;
expected_ty: string Lazy.t;
actual_ty: string Lazy.t;
}
| Call_lvalue of Pos.t
| Unsafe_cast_await of Pos.t
(* Primary and secondary *)
| Smember_not_found of {
pos: Pos.t;
kind:
[ `class_constant
| `class_typeconst
| `class_variable
| `static_method
];
class_name: string;
class_pos: Pos_or_decl.t;
member_name: string;
hint: ([ `instance | `static ] * Pos_or_decl.t * string) option;
quickfixes: Pos.t Quickfix.t list;
}
| Type_arity_mismatch of {
pos: Pos.t;
actual: int;
decl_pos: Pos_or_decl.t;
expected: int;
}
| Typing_too_many_args of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
actual: int;
expected: int;
}
| Typing_too_few_args of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
actual: int;
expected: int;
}
| Non_object_member of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
ty_name: string Lazy.t;
ctxt: [ `read | `write ];
member_name: string;
kind: [ `class_typeconst | `method_ | `property ];
}
| Static_instance_intersection of {
class_pos: Pos.t;
instance_pos: Pos_or_decl.t Lazy.t;
static_pos: Pos_or_decl.t Lazy.t;
member_name: string;
kind: [ `meth | `prop ];
}
[@@deriving show]
end
module rec Error : sig
type t =
| Primary of Primary.t
| Apply of Callback.t * t
| Apply_reasons of Reasons_callback.t * Secondary.t
| Assert_in_current_decl of Secondary.t * Pos_or_decl.ctx
| Multiple of t list
| Union of t list
| Intersection of t list
| With_code of t * Error_code.t
[@@deriving show]
val iter :
t -> on_prim:(Primary.t -> unit) -> on_snd:(Secondary.t -> unit) -> unit
val primary : Primary.t -> t
val coeffect : Primary.Coeffect.t -> t
val enum : Primary.Enum.t -> t
val expr_tree : Primary.Expr_tree.t -> t
val ifc : Primary.Ifc.t -> t
val modules : Primary.Modules.t -> t
val readonly : Primary.Readonly.t -> t
val shape : Primary.Shape.t -> t
val wellformedness : Primary.Wellformedness.t -> t
val xhp : Primary.Xhp.t -> t
val casetype : Primary.CaseType.t -> t
val apply_reasons : Secondary.t -> on_error:Reasons_callback.t -> t
val apply : t -> on_error:Callback.t -> t
val assert_in_current_decl : Secondary.t -> ctx:Pos_or_decl.ctx -> t
val intersect : t list -> t
val intersect_opt : t list -> t option
val union : t list -> t
val union_opt : t list -> t option
val multiple : t list -> t
val multiple_opt : t list -> t option
val both : t -> t -> t
val with_code : t -> code:Error_code.t -> t
val count : t -> int
end = struct
type t =
| Primary of Primary.t
| Apply of Callback.t * t
| Apply_reasons of Reasons_callback.t * Secondary.t
| Assert_in_current_decl of Secondary.t * Pos_or_decl.ctx
| Multiple of t list
| Union of t list
| Intersection of t list
| With_code of t * Error_code.t
[@@deriving show]
let iter t ~on_prim ~on_snd =
let rec aux = function
| Primary prim -> on_prim prim
| Apply (cb, t) ->
aux t;
Callback.iter cb ~on_prim
| Apply_reasons (cb, snd_err) ->
Secondary.iter snd_err ~on_prim ~on_snd;
Reasons_callback.iter cb ~on_prim ~on_snd
| Assert_in_current_decl (snd_err, _ctx) ->
Secondary.iter snd_err ~on_prim ~on_snd
| Multiple ts
| Union ts
| Intersection ts ->
List.iter ~f:aux ts
| With_code (t, _) -> aux t
in
aux t
(* -- Constructors ---------------------------------------------------------- *)
let primary prim_err = Primary prim_err
let coeffect err = primary @@ Primary.Coeffect err
let enum err = primary @@ Primary.Enum err
let expr_tree err = primary @@ Primary.Expr_tree err
let ifc err = primary @@ Primary.Ifc err
let modules err = primary @@ Primary.Modules err
let readonly err = primary @@ Primary.Readonly err
let shape err = primary @@ Primary.Shape err
let wellformedness err = primary @@ Primary.Wellformedness err
let xhp err = primary @@ Primary.Xhp err
let casetype err = primary @@ Primary.CaseType err
let apply_reasons t ~on_error = Apply_reasons (on_error, t)
let apply t ~on_error = Apply (on_error, t)
let assert_in_current_decl snd ~ctx = Assert_in_current_decl (snd, ctx)
let group_opt f = function
| [] -> None
| ts -> Some (f ts)
let intersect ts =
match ts with
| [] -> failwith "called on empty list"
| [t] -> t
| _ -> Intersection ts
let intersect_opt = group_opt intersect
let union ts =
match ts with
| [] -> failwith "called on empty list"
| [t] -> t
| _ -> Union ts
let union_opt = group_opt union
let multiple ts =
match ts with
| [] -> failwith "called on empty list"
| [t] -> t
| _ -> Multiple ts
let multiple_opt = group_opt multiple
let both t1 t2 = Multiple [t1; t2]
let with_code t ~code = With_code (t, code)
let rec count t =
match t with
| Primary _ -> 1
| Apply (_, t) -> count t
| Apply_reasons _ -> 1
| Assert_in_current_decl _ -> 1
| Multiple ts
| Union ts
| Intersection ts ->
List.fold ~init:0 ~f:(fun acc t -> acc + count t) ts
| With_code (t, _) -> count t
end
and Secondary : sig
type t =
| Of_error of Error.t
(* Primary and secondary *)
| Smember_not_found of {
pos: Pos_or_decl.t;
kind:
[ `class_constant
| `class_typeconst
| `class_variable
| `static_method
];
class_name: string;
class_pos: Pos_or_decl.t;
member_name: string;
hint: ([ `instance | `static ] * Pos_or_decl.t * string) option;
}
| Type_arity_mismatch of {
pos: Pos_or_decl.t;
actual: int;
decl_pos: Pos_or_decl.t;
expected: int;
}
| Typing_too_many_args of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
actual: int;
expected: int;
}
| Typing_too_few_args of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
actual: int;
expected: int;
}
| Non_object_member of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
ty_name: string Lazy.t;
ctxt: [ `read | `write ];
member_name: string;
kind: [ `class_typeconst | `method_ | `property ];
}
| Rigid_tvar_escape of {
pos: Pos_or_decl.t;
name: string;
}
(* Secondary only *)
| Violated_constraint of {
cstrs: (Pos_or_decl.t * Pos_or_decl.t Message.t) list;
ty_sub: Typing_defs_core.internal_type;
ty_sup: Typing_defs_core.internal_type;
is_coeffect: bool;
}
| Concrete_const_interface_override of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
parent_origin: string;
name: string;
}
| Interface_or_trait_const_multiple_defs of {
pos: Pos_or_decl.t;
origin: string;
name: string;
parent_pos: Pos_or_decl.t;
parent_origin: string;
}
| Interface_typeconst_multiple_defs of {
pos: Pos_or_decl.t;
origin: string;
is_abstract: bool;
name: string;
parent_pos: Pos_or_decl.t;
parent_origin: string;
}
| Visibility_extends of {
pos: Pos_or_decl.t;
vis: string;
parent_pos: Pos_or_decl.t;
parent_vis: string;
}
| Visibility_override_internal of {
pos: Pos_or_decl.t;
module_name: string option;
parent_pos: Pos_or_decl.t;
parent_module: string;
}
| Abstract_tconst_not_allowed of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
tconst_name: string;
}
| Missing_constructor of Pos_or_decl.t
| Missing_field of {
pos: Pos_or_decl.t;
name: string;
decl_pos: Pos_or_decl.t;
}
| Shape_fields_unknown of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Accept_disposable_invariant of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Ifc_external_contravariant of {
pos_sub: Pos_or_decl.t;
pos_super: Pos_or_decl.t;
}
| Invalid_destructure of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
ty_name: string Lazy.t;
}
| Unpack_array_required_argument of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Unpack_array_variadic_argument of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Fun_too_many_args of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
actual: int;
expected: int;
}
| Fun_too_few_args of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
actual: int;
expected: int;
}
| Fun_unexpected_nonvariadic of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Fun_variadicity_hh_vs_php56 of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Required_field_is_optional of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
def_pos: Pos_or_decl.t;
name: string;
}
| Return_disposable_mismatch of {
pos_sub: Pos_or_decl.t;
is_marked_return_disposable: bool;
pos_super: Pos_or_decl.t;
}
| Ifc_policy_mismatch of {
pos: Pos_or_decl.t;
policy: string;
pos_super: Pos_or_decl.t;
policy_super: string;
}
| Overriding_prop_const_mismatch of {
pos: Pos_or_decl.t;
is_const: bool;
parent_pos: Pos_or_decl.t;
parent_is_const: bool;
}
| Override_final of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
}
| Override_async of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
}
| Override_lsb of {
pos: Pos_or_decl.t;
member_name: string;
parent_pos: Pos_or_decl.t;
}
| Multiple_concrete_defs of {
pos: Pos_or_decl.t;
name: string;
origin: string;
class_name: string;
parent_pos: Pos_or_decl.t;
parent_origin: string;
}
| Cyclic_enum_constraint of Pos_or_decl.t
| Inoutness_mismatch of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Decl_override_missing_hint of Pos_or_decl.t
| Bad_lateinit_override of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
parent_is_lateinit: bool;
}
| Bad_method_override of {
pos: Pos_or_decl.t;
member_name: string;
}
| Bad_prop_override of {
pos: Pos_or_decl.t;
member_name: string;
}
| Bad_xhp_attr_required_override of {
pos: Pos_or_decl.t;
tag: string;
parent_pos: Pos_or_decl.t;
parent_tag: string;
}
| Coeffect_subtyping of {
pos: Pos_or_decl.t;
cap: string Lazy.t;
pos_expected: Pos_or_decl.t;
cap_expected: string Lazy.t;
}
| Override_method_support_dynamic_type of {
pos: Pos_or_decl.t;
method_name: string;
parent_pos: Pos_or_decl.t;
parent_origin: string;
}
| Readonly_mismatch of {
pos: Pos_or_decl.t;
kind: [ `fn | `fn_return | `param ];
reason_sub: Pos_or_decl.t Message.t list Lazy.t;
reason_super: Pos_or_decl.t Message.t list Lazy.t;
}
| Cross_package_mismatch of {
pos: Pos_or_decl.t;
reason_sub: Pos_or_decl.t Message.t list Lazy.t;
reason_super: Pos_or_decl.t Message.t list Lazy.t;
}
| Not_sub_dynamic of {
pos: Pos_or_decl.t;
ty_name: string Lazy.t;
dynamic_part: Pos_or_decl.t Message.t list Lazy.t;
}
| Subtyping_error of {
ty_sub: Typing_defs_core.internal_type;
ty_sup: Typing_defs_core.internal_type;
is_coeffect: bool;
}
| Method_not_dynamically_callable of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
}
| This_final of {
pos_sub: Pos_or_decl.t;
pos_super: Pos_or_decl.t;
class_name: string;
}
| Typeconst_concrete_concrete_override of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
}
| Abstract_concrete_override of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
kind: [ `constant | `method_ | `property | `typeconst ];
}
| Override_no_default_typeconst of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
}
| Unsupported_refinement of Pos_or_decl.t
| Missing_class_constant of {
pos: Pos_or_decl.t;
class_name: string;
const_name: string;
}
| Invalid_refined_const_kind of {
pos: Pos_or_decl.t;
class_name: string;
const_name: string;
correct_kind: string;
wrong_kind: string;
}
| Inexact_tconst_access of Pos_or_decl.t * (Pos_or_decl.t * string)
| Violated_refinement_constraint of {
cstr: [ `As | `Super ] * Pos_or_decl.t;
}
[@@deriving show]
val iter :
t -> on_prim:(Primary.t -> unit) -> on_snd:(Secondary.t -> unit) -> unit
end = struct
type t =
| Of_error of Error.t
(* Primary and secondary *)
| Smember_not_found of {
pos: Pos_or_decl.t;
kind:
[ `class_constant
| `class_typeconst
| `class_variable
| `static_method
];
class_name: string;
class_pos: Pos_or_decl.t;
member_name: string;
hint: ([ `instance | `static ] * Pos_or_decl.t * string) option;
}
| Type_arity_mismatch of {
pos: Pos_or_decl.t;
actual: int;
decl_pos: Pos_or_decl.t;
expected: int;
}
| Typing_too_many_args of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
actual: int;
expected: int;
}
| Typing_too_few_args of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
actual: int;
expected: int;
}
| Non_object_member of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
ty_name: string Lazy.t;
ctxt: [ `read | `write ];
member_name: string;
kind: [ `class_typeconst | `method_ | `property ];
}
| Rigid_tvar_escape of {
pos: Pos_or_decl.t;
name: string;
}
(* Secondary only *)
| Violated_constraint of {
cstrs: (Pos_or_decl.t * Pos_or_decl.t Message.t) list;
ty_sub: Typing_defs_core.internal_type;
ty_sup: Typing_defs_core.internal_type;
is_coeffect: bool;
}
| Concrete_const_interface_override of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
parent_origin: string;
name: string;
}
| Interface_or_trait_const_multiple_defs of {
pos: Pos_or_decl.t;
origin: string;
name: string;
parent_pos: Pos_or_decl.t;
parent_origin: string;
}
| Interface_typeconst_multiple_defs of {
pos: Pos_or_decl.t;
origin: string;
is_abstract: bool;
name: string;
parent_pos: Pos_or_decl.t;
parent_origin: string;
}
| Visibility_extends of {
pos: Pos_or_decl.t;
vis: string;
parent_pos: Pos_or_decl.t;
parent_vis: string;
}
| Visibility_override_internal of {
pos: Pos_or_decl.t;
module_name: string option;
parent_pos: Pos_or_decl.t;
parent_module: string;
}
| Abstract_tconst_not_allowed of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
tconst_name: string;
}
| Missing_constructor of Pos_or_decl.t
| Missing_field of {
pos: Pos_or_decl.t;
name: string;
decl_pos: Pos_or_decl.t;
}
| Shape_fields_unknown of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Accept_disposable_invariant of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Ifc_external_contravariant of {
pos_sub: Pos_or_decl.t;
pos_super: Pos_or_decl.t;
}
| Invalid_destructure of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
ty_name: string Lazy.t;
}
| Unpack_array_required_argument of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Unpack_array_variadic_argument of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Fun_too_many_args of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
actual: int;
expected: int;
}
| Fun_too_few_args of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
actual: int;
expected: int;
}
| Fun_unexpected_nonvariadic of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Fun_variadicity_hh_vs_php56 of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Required_field_is_optional of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
def_pos: Pos_or_decl.t;
name: string;
}
| Return_disposable_mismatch of {
pos_sub: Pos_or_decl.t;
is_marked_return_disposable: bool;
pos_super: Pos_or_decl.t;
}
| Ifc_policy_mismatch of {
pos: Pos_or_decl.t;
policy: string;
pos_super: Pos_or_decl.t;
policy_super: string;
}
| Overriding_prop_const_mismatch of {
pos: Pos_or_decl.t;
is_const: bool;
parent_pos: Pos_or_decl.t;
parent_is_const: bool;
}
| Override_final of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
}
| Override_async of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
}
| Override_lsb of {
pos: Pos_or_decl.t;
member_name: string;
parent_pos: Pos_or_decl.t;
}
| Multiple_concrete_defs of {
pos: Pos_or_decl.t;
name: string;
origin: string;
class_name: string;
parent_pos: Pos_or_decl.t;
parent_origin: string;
}
| Cyclic_enum_constraint of Pos_or_decl.t
| Inoutness_mismatch of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Decl_override_missing_hint of Pos_or_decl.t
| Bad_lateinit_override of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
parent_is_lateinit: bool;
}
| Bad_method_override of {
pos: Pos_or_decl.t;
member_name: string;
}
| Bad_prop_override of {
pos: Pos_or_decl.t;
member_name: string;
}
| Bad_xhp_attr_required_override of {
pos: Pos_or_decl.t;
tag: string;
parent_pos: Pos_or_decl.t;
parent_tag: string;
}
| Coeffect_subtyping of {
pos: Pos_or_decl.t;
cap: string Lazy.t;
pos_expected: Pos_or_decl.t;
cap_expected: string Lazy.t;
}
| Override_method_support_dynamic_type of {
pos: Pos_or_decl.t;
method_name: string;
parent_pos: Pos_or_decl.t;
parent_origin: string;
}
| Readonly_mismatch of {
pos: Pos_or_decl.t;
kind: [ `fn | `fn_return | `param ];
reason_sub: Pos_or_decl.t Message.t list Lazy.t;
reason_super: Pos_or_decl.t Message.t list Lazy.t;
}
| Cross_package_mismatch of {
pos: Pos_or_decl.t;
reason_sub: Pos_or_decl.t Message.t list Lazy.t;
reason_super: Pos_or_decl.t Message.t list Lazy.t;
}
| Not_sub_dynamic of {
pos: Pos_or_decl.t;
ty_name: string Lazy.t;
dynamic_part: Pos_or_decl.t Message.t list Lazy.t;
}
| Subtyping_error of {
ty_sub: Typing_defs_core.internal_type;
ty_sup: Typing_defs_core.internal_type;
is_coeffect: bool;
}
| Method_not_dynamically_callable of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
}
| This_final of {
pos_sub: Pos_or_decl.t;
pos_super: Pos_or_decl.t;
class_name: string;
}
| Typeconst_concrete_concrete_override of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
}
| Abstract_concrete_override of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
kind: [ `constant | `method_ | `property | `typeconst ];
}
| Override_no_default_typeconst of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
}
| Unsupported_refinement of Pos_or_decl.t
| Missing_class_constant of {
pos: Pos_or_decl.t;
class_name: string;
const_name: string;
}
| Invalid_refined_const_kind of {
pos: Pos_or_decl.t;
class_name: string;
const_name: string;
correct_kind: string;
wrong_kind: string;
}
| Inexact_tconst_access of Pos_or_decl.t * (Pos_or_decl.t * string)
| Violated_refinement_constraint of {
cstr: [ `As | `Super ] * Pos_or_decl.t;
}
[@@deriving show]
let iter t ~on_prim ~on_snd =
match t with
| Of_error err -> Error.iter ~on_prim ~on_snd err
| snd_err -> on_snd snd_err
end
and Callback : sig
type t =
| Always of Primary.t
| Of_primary of Primary.t
| With_claim_as_reason of t * Primary.t
| With_code of Error_code.t * Pos.t Quickfix.t list
| Retain_code of t
| With_side_effect of t * (unit -> unit)
[@@deriving show]
val iter : t -> on_prim:(Primary.t -> unit) -> unit
val always : Primary.t -> t
val with_side_effect : t -> eff:(unit -> unit) -> t
[@@ocaml.deprecated
"This function will be removed. Please avoid adding side effects to error callbacks."]
val of_primary_error : Primary.t -> t
val with_code : code:Error_code.t -> t
val retain_code : t -> t
val with_claim_as_reason : t -> new_claim:Primary.t -> t
val unify_error : t
val index_type_mismatch : t
val covariant_index_type_mismatch : t
val expected_stringlike : t
val constant_does_not_match_enum_type : t
val enum_underlying_type_must_be_arraykey : t
val enum_constraint_must_be_arraykey : t
val enum_subtype_must_have_compatible_constraint : t
val parameter_default_value_wrong_type : t
val newtype_alias_must_satisfy_constraint : t
val missing_return : t
val inout_return_type_mismatch : t
val class_constant_value_does_not_match_hint : t
val class_property_initializer_type_does_not_match_hint : t
val xhp_attribute_does_not_match_hint : t
val strict_str_concat_type_mismatch : t
val strict_str_interp_type_mismatch : t
val bitwise_math_invalid_argument : t
val inc_dec_invalid_argument : t
val math_invalid_argument : t
val using_error : Pos.t -> has_await:bool -> t
end = struct
type t =
| Always of Primary.t
| Of_primary of Primary.t
| With_claim_as_reason of t * Primary.t
| With_code of Error_code.t * Pos.t Quickfix.t list
| Retain_code of t
| With_side_effect of t * (unit -> unit)
[@@deriving show]
let iter t ~on_prim =
let rec aux = function
| Always prim
| Of_primary prim ->
on_prim prim
| With_claim_as_reason (t, prim) ->
on_prim prim;
aux t
| Retain_code t
| With_side_effect (t, _) ->
aux t
| With_code _ -> ()
in
aux t
(* -- Constructors -------------------------------------------------------- *)
let always err = Always err
let with_side_effect t ~eff = (With_side_effect (t, eff) [@alert.deprecated])
let with_code ~code = With_code (code, [])
let of_primary_error err = Of_primary err
let retain_code t = Retain_code t
let with_claim_as_reason t ~new_claim = With_claim_as_reason (t, new_claim)
(* -- Specific errors ----------------------------------------------------- *)
let unify_error = with_code ~code:Error_code.UnifyError
let index_type_mismatch = with_code ~code:Error_code.IndexTypeMismatch
let covariant_index_type_mismatch =
with_code ~code:Error_code.CovariantIndexTypeMismatch
let expected_stringlike = with_code ~code:Error_code.ExpectedStringlike
let constant_does_not_match_enum_type =
with_code ~code:Error_code.ConstantDoesNotMatchEnumType
let enum_underlying_type_must_be_arraykey =
with_code ~code:Error_code.EnumUnderlyingTypeMustBeArraykey
let enum_constraint_must_be_arraykey =
with_code ~code:Error_code.EnumConstraintMustBeArraykey
let enum_subtype_must_have_compatible_constraint =
with_code ~code:Error_code.EnumSubtypeMustHaveCompatibleConstraint
let parameter_default_value_wrong_type =
with_code ~code:Error_code.ParameterDefaultValueWrongType
let newtype_alias_must_satisfy_constraint =
with_code ~code:Error_code.NewtypeAliasMustSatisfyConstraint
let missing_return = with_code ~code:Error_code.MissingReturnInNonVoidFunction
let inout_return_type_mismatch =
with_code ~code:Error_code.InoutReturnTypeMismatch
let class_constant_value_does_not_match_hint =
with_code ~code:Error_code.ClassConstantValueDoesNotMatchHint
let class_property_initializer_type_does_not_match_hint =
with_code ~code:Error_code.ClassPropertyInitializerTypeDoesNotMatchHint
let xhp_attribute_does_not_match_hint =
with_code ~code:Error_code.XhpAttributeValueDoesNotMatchHint
let strict_str_concat_type_mismatch =
with_code ~code:Error_code.StrictStrConcatTypeMismatch
let strict_str_interp_type_mismatch =
with_code ~code:Error_code.StrictStrInterpTypeMismatch
let bitwise_math_invalid_argument =
with_code ~code:Error_code.BitwiseMathInvalidArgument
let inc_dec_invalid_argument =
with_code ~code:Error_code.IncDecInvalidArgument
let math_invalid_argument = with_code ~code:Error_code.MathInvalidArgument
let using_error pos ~has_await =
let new_claim = Primary.Using_error { pos; has_await } in
with_claim_as_reason ~new_claim @@ retain_code unify_error
end
and Reasons_callback : sig
type op =
| Append
| Prepend
[@@deriving show]
type component =
| Code
| Reasons
| Quickfixes
[@@deriving show]
type t =
| Always of Error.t
| Of_error of Error.t
| Of_callback of Callback.t * Pos.t Message.t Lazy.t
| Retain of t * component
| Incoming_reasons of t * op
| With_code of t * Error_code.t
| With_reasons of t * Pos_or_decl.t Message.t list Lazy.t
| Add_quickfixes of t * Pos.t Quickfix.t list
| Add_reason of t * op * Pos_or_decl.t Message.t Lazy.t
| From_on_error of
((?code:int ->
?quickfixes:Pos.t Quickfix.t list ->
Pos_or_decl.t Message.t list ->
unit)
[@show.opaque])
[@ocaml.deprecated
"This constructor will be removed. Please use the provided combinators for constructing error callbacks."]
| Prepend_on_apply of t * Secondary.t
| Assert_in_current_decl of Error_code.t * Pos_or_decl.ctx
| Drop_reasons_on_apply of t
[@@deriving show]
val iter :
t -> on_prim:(Primary.t -> unit) -> on_snd:(Secondary.t -> unit) -> unit
val from_on_error :
(?code:int ->
?quickfixes:Pos.t Quickfix.t list ->
Pos_or_decl.t Message.t list ->
unit) ->
t
[@@ocaml.deprecated
"This function will be removed. Please use the provided combinators for constructing error callbacks."]
val always : Error.t -> t
val of_error : Error.t -> t
val of_primary_error : Primary.t -> t
val with_claim : Callback.t -> claim:Pos.t Message.t Lazy.t -> t
val with_code : t -> code:Error_code.t -> t
val with_reasons : t -> reasons:Pos_or_decl.t Message.t list Lazy.t -> t
val add_quickfixes : t -> Pos.t Quickfix.t list -> t
val prepend_reason : t -> reason:Pos_or_decl.t Message.t Lazy.t -> t
val append_reason : t -> reason:Pos_or_decl.t Message.t Lazy.t -> t
val append_incoming_reasons : t -> t
val prepend_incoming_reasons : t -> t
val retain_code : t -> t
val retain_reasons : t -> t
val retain_quickfixes : t -> t
val prepend_on_apply : t -> Secondary.t -> t
val drop_reasons_on_apply : t -> t
val assert_in_current_decl : Error_code.t -> ctx:Pos_or_decl.ctx -> t
val unify_error_at : Pos.t -> t
val expr_tree_splice_error :
Pos.t ->
expr_pos:Pos_or_decl.t ->
contextual_reasons:Pos_or_decl.t Message.t list Lazy.t option ->
dsl_opt:string option ->
docs_url:string option Lazy.t ->
t
val bad_enum_decl : Pos.t -> t
val bad_conditional_support_dynamic :
Pos.t ->
child:string ->
parent:string ->
ty_name:string Lazy.t ->
self_ty_name:string Lazy.t ->
t
val bad_decl_override :
name:string -> parent_pos:Pos.t -> parent_name:string -> t
val invalid_class_refinement : Pos.t -> t
val explain_where_constraint :
Pos.t -> in_class:bool -> decl_pos:Pos_or_decl.t -> t
val explain_constraint : Pos.t -> t
val rigid_tvar_escape_at : Pos.t -> string -> t
val invalid_type_hint : Pos.t -> t
val type_constant_mismatch : t -> t
val class_constant_type_mismatch : t -> t
val unsatisfied_req_callback :
class_pos:Pos.t ->
trait_pos:Pos_or_decl.t ->
req_pos:Pos_or_decl.t ->
string ->
t
val invalid_echo_argument_at : Pos.t -> t
val index_type_mismatch_at : Pos.t -> t
val unify_error_assert_primary_pos_in_current_decl : Pos_or_decl.ctx -> t
val invalid_type_hint_assert_primary_pos_in_current_decl :
Pos_or_decl.ctx -> t
end = struct
type op =
| Append
| Prepend
[@@deriving show]
type component =
| Code
| Reasons
| Quickfixes
[@@deriving show]
type t =
| Always of Error.t
| Of_error of Error.t
| Of_callback of Callback.t * Pos.t Message.t Lazy.t
| Retain of t * component
| Incoming_reasons of t * op
| With_code of t * Error_code.t
| With_reasons of t * Pos_or_decl.t Message.t list Lazy.t
| Add_quickfixes of t * Pos.t Quickfix.t list
| Add_reason of t * op * Pos_or_decl.t Message.t Lazy.t
| From_on_error of
((?code:int ->
?quickfixes:Pos.t Quickfix.t list ->
Pos_or_decl.t Message.t list ->
unit)
[@show.opaque])
[@ocaml.deprecated
"This constructor will be removed. Please use the provided combinators for constructing error callbacks."]
| Prepend_on_apply of t * Secondary.t
| Assert_in_current_decl of Error_code.t * Pos_or_decl.ctx
| Drop_reasons_on_apply of t
[@@deriving show]
let iter t ~on_prim ~on_snd =
let rec aux = function
| Always err
| Of_error err ->
Error.iter err ~on_prim ~on_snd
| Of_callback (cb, _) -> Callback.iter cb ~on_prim
| Retain (t, _)
| Incoming_reasons (t, _)
| With_code (t, _)
| With_reasons (t, _)
| Add_quickfixes (t, _)
| Add_reason (t, _, _)
| Prepend_on_apply (t, _)
| Drop_reasons_on_apply t ->
aux t
| From_on_error _
| Assert_in_current_decl _ ->
()
[@@ocaml.warning "-3"]
in
aux t
(* -- Constructors -------------------------------------------------------- *)
let from_on_error f = From_on_error f [@@ocaml.warning "-3"]
let of_error err = Of_error err
let of_primary_error prim_err = Of_error (Error.primary prim_err)
let with_claim no_claim ~claim = Of_callback (no_claim, claim)
let with_code t ~code = With_code (t, code)
let with_reasons t ~reasons = With_reasons (t, reasons)
let add_quickfixes t qfxs = Add_quickfixes (t, qfxs)
let prepend_reason t ~reason = Add_reason (t, Prepend, reason)
let append_reason t ~reason = Add_reason (t, Append, reason)
let append_incoming_reasons t = Incoming_reasons (t, Append)
let prepend_incoming_reasons t = Incoming_reasons (t, Prepend)
let retain_code t = Retain (t, Code)
let retain_reasons t = Retain (t, Reasons)
let retain_quickfixes t = Retain (t, Quickfixes)
let always err = Always err
let prepend_on_apply t snd_err = Prepend_on_apply (t, snd_err)
let drop_reasons_on_apply t = Drop_reasons_on_apply t
let assert_in_current_decl code ~ctx = Assert_in_current_decl (code, ctx)
(* -- Specific callbacks -------------------------------------------------- *)
let unify_error_at pos =
of_error
@@ Error.primary
@@ Primary.Unify_error { pos; msg_opt = None; reasons_opt = None }
let expr_tree_splice_error
pos ~expr_pos ~contextual_reasons ~dsl_opt ~docs_url =
let msg =
match dsl_opt with
| Some dsl_name ->
Printf.sprintf
"This value cannot be inserted (spliced) into a `%s` expression tree"
@@ Utils.strip_ns dsl_name
| None ->
"This value cannot be inserted (spliced) into an expression tree"
in
let reason =
lazy
begin
let (lazy docs_url) = docs_url in
let docs_url =
Option.value
docs_url
~default:"https://docs.hhvm.com/hack/expression-trees/splicing"
in
let msg =
"Hack values need to be converted (lifted) to compatible types before splicing. "
^ Printf.sprintf "For more information see: %s" docs_url
in
(expr_pos, msg)
end
in
let error =
append_reason ~reason
@@ of_error
@@ Error.primary
@@ Primary.Unify_error { pos; msg_opt = Some msg; reasons_opt = None }
in
match contextual_reasons with
| None -> error
| Some reasons -> with_reasons ~reasons error
let bad_enum_decl pos =
retain_code
@@ retain_quickfixes
@@ of_error
@@ Error.primary
@@ Primary.Bad_enum_decl pos
let bad_conditional_support_dynamic pos ~child ~parent ~ty_name ~self_ty_name
=
retain_code
@@ retain_quickfixes
@@ of_primary_error
@@ Primary.Bad_conditional_support_dynamic
{ pos; child; parent; ty_name; self_ty_name }
let bad_decl_override ~name ~parent_pos ~parent_name =
append_incoming_reasons
@@ retain_quickfixes
@@ of_primary_error
@@ Primary.Bad_decl_override { name; pos = parent_pos; parent_name }
let invalid_class_refinement pos =
append_incoming_reasons
@@ retain_code
@@ retain_quickfixes
@@ of_primary_error
@@ Primary.Wellformedness
(Primary.Wellformedness.Invalid_class_refinement { pos })
let explain_where_constraint pos ~in_class ~decl_pos =
append_incoming_reasons
@@ retain_code
@@ retain_quickfixes
@@ of_primary_error
@@ Primary.Explain_where_constraint { pos; in_class; decl_pos }
let explain_constraint pos =
retain_code @@ of_primary_error @@ Primary.Explain_constraint pos
let rigid_tvar_escape_at pos what =
retain_quickfixes
@@ retain_code
@@ of_primary_error
@@ Primary.Rigid_tvar_escape { pos; what }
let invalid_type_hint pos = of_primary_error @@ Primary.Invalid_type_hint pos
let type_constant_mismatch t =
retain_quickfixes @@ with_code ~code:Error_code.TypeConstantMismatch t
let class_constant_type_mismatch t =
retain_quickfixes @@ with_code ~code:Error_code.ClassConstantTypeMismatch t
let unsatisfied_req_callback ~class_pos ~trait_pos ~req_pos req_name =
append_incoming_reasons
@@ retain_code
@@ of_primary_error
@@ Primary.Unsatisfied_req { pos = class_pos; trait_pos; req_pos; req_name }
let invalid_echo_argument_at pos =
of_primary_error @@ Primary.Invalid_echo_argument pos
let index_type_mismatch_at pos =
of_primary_error
@@ Primary.Index_type_mismatch
{
pos;
msg_opt = None;
reasons_opt = None;
is_covariant_container = false;
}
let unify_error_assert_primary_pos_in_current_decl ctx =
assert_in_current_decl Error_code.UnifyError ~ctx
let invalid_type_hint_assert_primary_pos_in_current_decl ctx =
assert_in_current_decl Error_code.InvalidTypeHint ~ctx
end
include Error |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_error.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module Error_code = Error_codes.Typing
module Primary : sig
module Shape : sig
type t =
| Invalid_shape_field_name of {
pos: Pos.t;
is_empty: bool;
}
| Invalid_shape_field_literal of {
pos: Pos.t;
witness_pos: Pos.t;
}
| Invalid_shape_field_const of {
pos: Pos.t;
witness_pos: Pos.t;
}
| Invalid_shape_field_type of {
pos: Pos.t;
ty_pos: Pos_or_decl.t;
ty_name: string Lazy.t;
trail: Pos_or_decl.t list;
}
| Shape_field_class_mismatch of {
pos: Pos.t;
class_name: string;
witness_pos: Pos.t;
witness_class_name: string;
}
| Shape_field_type_mismatch of {
pos: Pos.t;
ty_name: string Lazy.t;
witness_pos: Pos.t;
witness_ty_name: string Lazy.t;
}
| Invalid_shape_remove_key of Pos.t
| Shapes_key_exists_always_true of {
pos: Pos.t;
field_name: string;
decl_pos: Pos_or_decl.t;
}
| Shapes_key_exists_always_false of {
pos: Pos.t;
field_name: string;
decl_pos: Pos_or_decl.t;
reason:
[ `Nothing of Pos_or_decl.t Message.t list Lazy.t | `Undefined ];
}
| Shapes_method_access_with_non_existent_field of {
pos: Pos.t;
field_name: string;
decl_pos: Pos_or_decl.t;
method_name: string;
reason:
[ `Nothing of Pos_or_decl.t Message.t list Lazy.t | `Undefined ];
}
| Shapes_access_with_non_existent_field of {
pos: Pos.t;
field_name: string;
decl_pos: Pos_or_decl.t;
reason:
[ `Nothing of Pos_or_decl.t Message.t list Lazy.t | `Undefined ];
}
[@@deriving show]
end
module Enum : sig
type t =
| Enum_switch_redundant of {
pos: Pos.t;
first_pos: Pos.t;
const_name: string;
}
| Enum_switch_nonexhaustive of {
pos: Pos.t;
kind: string;
decl_pos: Pos_or_decl.t;
missing: string list;
}
| Enum_switch_redundant_default of {
pos: Pos.t;
kind: string;
decl_pos: Pos_or_decl.t;
}
| Enum_switch_not_const of Pos.t
| Enum_switch_wrong_class of {
pos: Pos.t;
kind: string;
expected: string;
actual: string;
}
| Enum_type_bad of {
pos: Pos.t;
ty_name: string Lazy.t;
is_enum_class: bool;
trail: Pos_or_decl.t list;
}
| Enum_type_bad_case_type of {
pos: Pos.t;
ty_name: string Lazy.t;
case_type_decl_pos: Pos_or_decl.t;
}
| Enum_constant_type_bad of {
pos: Pos.t;
ty_pos: Pos_or_decl.t;
ty_name: string Lazy.t;
trail: Pos_or_decl.t list;
}
| Enum_type_typedef_nonnull of Pos.t
| Enum_class_label_unknown of {
pos: Pos.t;
label_name: string;
enum_name: string;
decl_pos: Pos_or_decl.t;
most_similar: (string * Pos_or_decl.t) option;
ty_pos: Pos_or_decl.t option;
}
| Enum_class_label_as_expr of Pos.t
| Enum_class_label_member_mismatch of {
pos: Pos.t;
label: string;
expected_ty_msg_opt: Pos_or_decl.t Message.t list Lazy.t option;
}
| Incompatible_enum_inclusion_base of {
pos: Pos.t;
classish_name: string;
src_classish_name: string;
}
| Incompatible_enum_inclusion_constraint of {
pos: Pos.t;
classish_name: string;
src_classish_name: string;
}
| Enum_inclusion_not_enum of {
pos: Pos.t;
classish_name: string;
src_classish_name: string;
}
[@@deriving show]
end
module Expr_tree : sig
type t =
| Expression_tree_non_public_member of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Reified_static_method_in_expr_tree of Pos.t
| This_var_in_expr_tree of Pos.t
| Experimental_expression_trees of Pos.t
| Expression_tree_unsupported_operator of {
pos: Pos.t;
member_name: string;
class_name: string;
}
[@@deriving show]
end
module Readonly : sig
type t =
| Readonly_modified of {
pos: Pos.t;
reason_opt: Pos_or_decl.t Message.t Lazy.t option;
}
| Readonly_mismatch of {
pos: Pos.t;
what: [ `arg_readonly | `arg_mut | `collection_mod | `prop_assign ];
pos_sub: Pos_or_decl.t;
pos_super: Pos_or_decl.t;
}
| Readonly_invalid_as_mut of Pos.t
| Readonly_exception of Pos.t
| Explicit_readonly_cast of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
kind: [ `fn_call | `property | `static_property ];
}
| Readonly_method_call of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Readonly_closure_call of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
suggestion: string;
}
[@@deriving show]
end
module Ifc : sig
type t =
| Illegal_information_flow of {
pos: Pos.t;
secondaries: Pos_or_decl.t list;
source_poss: Pos_or_decl.t list;
source: string;
sink_poss: Pos_or_decl.t list;
sink: string;
}
| Context_implicit_policy_leakage of {
pos: Pos.t;
secondaries: Pos_or_decl.t list;
source_poss: Pos_or_decl.t list;
source: string;
sink_poss: Pos_or_decl.t list;
sink: string;
}
| Unknown_information_flow of {
pos: Pos.t;
what: string;
}
| Ifc_internal_error of {
pos: Pos.t;
msg: string;
}
[@@deriving show]
end
module Coeffect : sig
type t =
| Call_coeffect of {
pos: Pos.t;
available_pos: Pos_or_decl.t;
available_incl_unsafe: string Lazy.t;
required_pos: Pos_or_decl.t;
required: string Lazy.t;
}
| Op_coeffect_error of {
pos: Pos.t;
op_name: string;
locally_available: string Lazy.t;
available_pos: Pos_or_decl.t;
err_code: Error_code.t;
required: string Lazy.t;
suggestion: Pos_or_decl.t Message.t list Lazy.t option;
}
[@@deriving show]
end
module Wellformedness : sig
type t =
| Missing_return of {
pos: Pos.t;
hint_pos: Pos_or_decl.t option;
is_async: bool;
}
| Void_usage of {
pos: Pos.t;
reason: Pos_or_decl.t Message.t list Lazy.t;
}
| Noreturn_usage of {
pos: Pos.t;
reason: Pos_or_decl.t Message.t list Lazy.t;
}
| Returns_with_and_without_value of {
pos: Pos.t;
with_value_pos: Pos.t;
without_value_pos_opt: Pos.t option;
}
| Non_void_annotation_on_return_void_function of {
is_async: bool;
hint_pos: Pos.t;
}
| Tuple_syntax of Pos.t
| Invalid_class_refinement of { pos: Pos.t }
[@@deriving show]
end
module Modules : sig
type t =
| Module_hint of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Module_mismatch of {
pos: Pos.t;
current_module_opt: string option;
decl_pos: Pos_or_decl.t;
target_module: string;
}
| Module_unsafe_trait_access of {
access_pos: Pos.t;
trait_pos: Pos_or_decl.t;
}
| Module_missing_import of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
module_pos: Pos_or_decl.t;
current_module: string;
target_module_opt: string option;
}
| Module_missing_export of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
module_pos: Pos_or_decl.t;
current_module_opt: string option;
target_module: string;
}
| Module_cross_pkg_access of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
module_pos: Pos_or_decl.t;
package_pos: Pos.t;
current_module_opt: string option;
current_package_opt: string option;
target_module_opt: string option;
target_package_opt: string option;
}
| Module_cross_pkg_call of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
current_package_opt: string option;
target_package_opt: string option;
}
| Module_soft_included_access of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
module_pos: Pos_or_decl.t;
package_pos: Pos.t;
current_module_opt: string option;
current_package_opt: string option;
target_module_opt: string option;
target_package_opt: string option;
}
[@@deriving show]
end
module Xhp : sig
type t =
| Xhp_required of {
pos: Pos.t;
why_xhp: string;
ty_reason_msg: Pos_or_decl.t Message.t list Lazy.t;
}
| Illegal_xhp_child of {
pos: Pos.t;
ty_reason_msg: Pos_or_decl.t Message.t list Lazy.t;
}
| Missing_xhp_required_attr of {
pos: Pos.t;
attr: string;
ty_reason_msg: Pos_or_decl.t Message.t list Lazy.t;
}
[@@deriving show]
end
module CaseType : sig
type t =
| Overlapping_variant_types of {
pos: Pos.t;
name: string;
tag: string;
why: Pos_or_decl.t Message.t list Lazy.t;
}
| Unrecoverable_variant_type of {
pos: Pos.t;
name: string;
hints: (Pos.t * string) list;
}
[@@deriving show]
end
(** Specific error information readily transformable into a user error *)
type t =
(* == Factorised errors ================================================= *)
| Coeffect of Coeffect.t
| Enum of Enum.t
| Expr_tree of Expr_tree.t
| Ifc of Ifc.t
| Modules of Modules.t
| Readonly of Readonly.t
| Shape of Shape.t
| Wellformedness of Wellformedness.t
| Xhp of Xhp.t
| CaseType of CaseType.t
(* == Primary only ====================================================== *)
| Unresolved_tyvar of Pos.t
| Unify_error of {
pos: Pos.t;
msg_opt: string option;
reasons_opt: Pos_or_decl.t Message.t list Lazy.t option;
}
| Generic_unify of {
pos: Pos.t;
msg: string;
}
| Using_error of {
pos: Pos.t;
has_await: bool;
}
| Bad_enum_decl of Pos.t
| Bad_conditional_support_dynamic of {
pos: Pos.t;
child: string;
parent: string;
ty_name: string Lazy.t;
self_ty_name: string Lazy.t;
}
| Bad_decl_override of {
pos: Pos.t;
name: string;
parent_name: string;
}
| Explain_where_constraint of {
pos: Pos.t;
in_class: bool;
decl_pos: Pos_or_decl.t;
}
| Explain_constraint of Pos.t
| Rigid_tvar_escape of {
pos: Pos.t;
what: string;
}
| Invalid_type_hint of Pos.t
| Unsatisfied_req of {
pos: Pos.t;
trait_pos: Pos_or_decl.t;
req_pos: Pos_or_decl.t;
req_name: string;
}
| Unsatisfied_req_class of {
pos: Pos.t;
trait_pos: Pos_or_decl.t;
req_pos: Pos_or_decl.t;
req_name: string;
}
| Req_class_not_final of {
pos: Pos.t;
trait_pos: Pos_or_decl.t;
req_pos: Pos_or_decl.t;
}
| Incompatible_reqs of {
pos: Pos.t;
req_name: string;
req_class_pos: Pos_or_decl.t;
req_extends_pos: Pos_or_decl.t;
}
| Trait_not_used of {
pos: Pos.t;
trait_name: string;
req_class_pos: Pos_or_decl.t;
class_pos: Pos_or_decl.t;
class_name: string;
}
| Invalid_echo_argument of Pos.t
| Index_type_mismatch of {
pos: Pos.t;
is_covariant_container: bool;
msg_opt: string option;
reasons_opt: Pos_or_decl.t Message.t list Lazy.t option;
}
| Member_not_found of {
pos: Pos.t;
kind: [ `method_ | `property ];
class_name: string;
class_pos: Pos_or_decl.t;
member_name: string;
hint: ([ `instance | `static ] * Pos_or_decl.t * string) option Lazy.t;
reason: Pos_or_decl.t Message.t list Lazy.t;
}
| Construct_not_instance_method of Pos.t
| Ambiguous_inheritance of {
pos: Pos.t;
class_name: string;
origin: string;
}
| Expected_tparam of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
n: int;
}
| Typeconst_concrete_concrete_override of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Constant_multiple_concrete_conflict of {
pos: Pos.t;
name: string;
definitions: (Pos_or_decl.t * string option) list;
}
| Invalid_memoized_param of {
pos: Pos.t;
ty_name: string Lazy.t;
reason: Pos_or_decl.t Message.t list Lazy.t;
}
| Invalid_arraykey of {
pos: Pos.t;
ctxt: [ `read | `write ];
container_pos: Pos_or_decl.t;
container_ty_name: string Lazy.t;
key_pos: Pos_or_decl.t;
key_ty_name: string Lazy.t;
}
| Invalid_keyset_value of {
pos: Pos.t;
container_pos: Pos_or_decl.t;
container_ty_name: string Lazy.t;
value_pos: Pos_or_decl.t;
value_ty_name: string Lazy.t;
}
| Invalid_set_value of {
pos: Pos.t;
container_pos: Pos_or_decl.t;
container_ty_name: string Lazy.t;
value_pos: Pos_or_decl.t;
value_ty_name: string Lazy.t;
}
| HKT_alias_with_implicit_constraints of {
pos: Pos.t;
typedef_pos: Pos_or_decl.t;
used_class_in_def_pos: Pos_or_decl.t;
typedef_name: string;
typedef_tparam_name: string;
used_class_in_def_name: string;
used_class_tparam_name: string;
}
| HKT_wildcard of Pos.t
| HKT_implicit_argument of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
param_name: string;
}
| Invalid_substring of {
pos: Pos.t;
ty_name: string Lazy.t;
}
| Unset_nonidx_in_strict of {
pos: Pos.t;
reason: Pos_or_decl.t Message.t list Lazy.t;
}
| Nullable_cast of {
pos: Pos.t;
ty_pos: Pos_or_decl.t;
ty_name: string Lazy.t;
}
| Hh_expect of {
pos: Pos.t;
equivalent: bool;
}
| Null_member of {
pos: Pos.t;
obj_pos_opt: Pos.t option;
ctxt: [ `read | `write ];
kind: [ `method_ | `property ];
member_name: string;
reason: Pos_or_decl.t Message.t list Lazy.t;
}
| Nullsafe_property_write_context of Pos.t
| Uninstantiable_class of {
pos: Pos.t;
class_name: string;
reason_ty_opt: (Pos.t * string Lazy.t) option;
decl_pos: Pos_or_decl.t;
}
| Abstract_const_usage of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
name: string;
}
| Member_not_implemented of {
pos: Pos.t;
member_name: string;
decl_pos: Pos_or_decl.t;
quickfixes: Pos.t Quickfix.t list;
}
| Kind_mismatch of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
tparam_name: string;
expected_kind: string;
actual_kind: string;
}
| Trait_parent_construct_inconsistent of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Top_member of {
pos: Pos.t;
ctxt: [ `read | `write ];
ty_name: string Lazy.t;
decl_pos: Pos_or_decl.t;
kind: [ `method_ | `property ];
name: string;
is_nullable: bool;
ty_reasons: (Pos_or_decl.t * string) list Lazy.t;
}
| Unresolved_tyvar_projection of {
pos: Pos.t;
proj_pos: Pos_or_decl.t;
tconst_name: string;
}
| Cyclic_class_constant of {
pos: Pos.t;
class_name: string;
const_name: string;
}
| Inout_annotation_missing of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Inout_annotation_unexpected of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
param_is_variadic: bool;
qfx_pos: Pos.t;
}
| Inout_argument_bad_type of {
pos: Pos.t;
reasons: Pos_or_decl.t Message.t list Lazy.t;
}
| Invalid_meth_caller_calling_convention of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
convention: string;
}
| Invalid_meth_caller_readonly_return of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Invalid_new_disposable of Pos.t
| Invalid_return_disposable of Pos.t
| Invalid_disposable_hint of {
pos: Pos.t;
class_name: string;
}
| Invalid_disposable_return_hint of {
pos: Pos.t;
class_name: string;
}
| Ambiguous_lambda of {
pos: Pos.t;
uses: Pos_or_decl.t Message.t list Lazy.t;
}
| Wrong_extend_kind of {
pos: Pos.t;
kind: Ast_defs.classish_kind;
name: string;
parent_pos: Pos_or_decl.t;
parent_kind: Ast_defs.classish_kind;
parent_name: string;
}
| Cyclic_class_def of {
pos: Pos.t;
stack: SSet.t;
}
| Trait_reuse_with_final_method of {
pos: Pos.t;
trait_name: string;
parent_cls_name: string Lazy.t;
trace: Pos_or_decl.t Message.t list Lazy.t;
}
| Trait_reuse_inside_class of {
pos: Pos.t;
class_name: string;
trait_name: string;
occurrences: Pos_or_decl.t list;
}
| Invalid_is_as_expression_hint of {
pos: Pos.t;
op: [ `is | `as_ ];
reasons: Pos_or_decl.t Message.t list Lazy.t;
}
| Invalid_enforceable_type of {
pos: Pos.t;
ty_info: Pos_or_decl.t Message.t list Lazy.t;
tp_pos: Pos_or_decl.t;
tp_name: string;
kind: [ `constant | `param ];
}
| Reifiable_attr of {
pos: Pos.t;
ty_info: Pos_or_decl.t Message.t list Lazy.t;
attr_pos: Pos_or_decl.t;
kind: [ `ty | `cnstr | `super_cnstr ];
}
| Invalid_newable_type_argument of {
pos: Pos.t;
tp_pos: Pos_or_decl.t;
tp_name: string;
}
| Invalid_newable_typaram_constraints of {
pos: Pos.t;
tp_name: string;
constraints: string list;
}
| Override_per_trait of {
pos: Pos.t;
class_name: string;
meth_name: string;
trait_name: string;
meth_pos: Pos_or_decl.t;
}
| Should_not_be_override of {
pos: Pos.t;
class_id: string;
id: string;
}
| Trivial_strict_eq of {
pos: Pos.t;
result: bool;
left: Pos_or_decl.t Message.t list Lazy.t;
right: Pos_or_decl.t Message.t list Lazy.t;
left_trail: Pos_or_decl.t list;
right_trail: Pos_or_decl.t list;
}
| Trivial_strict_not_nullable_compare_null of {
pos: Pos.t;
result: bool;
ty_reason_msg: Pos_or_decl.t Message.t list Lazy.t;
}
| Eq_incompatible_types of {
pos: Pos.t;
left: Pos_or_decl.t Message.t list Lazy.t;
right: Pos_or_decl.t Message.t list Lazy.t;
}
| Comparison_invalid_types of {
pos: Pos.t;
left: Pos_or_decl.t Message.t list Lazy.t;
right: Pos_or_decl.t Message.t list Lazy.t;
}
| Strict_eq_value_incompatible_types of {
pos: Pos.t;
left: Pos_or_decl.t Message.t list Lazy.t;
right: Pos_or_decl.t Message.t list Lazy.t;
}
| Deprecated_use of {
pos: Pos.t;
decl_pos_opt: Pos_or_decl.t option;
msg: string;
}
| Cannot_declare_constant of {
pos: Pos.t;
class_pos: Pos.t;
class_name: string;
}
| Invalid_classname of Pos.t
| Illegal_type_structure of {
pos: Pos.t;
msg: string;
}
| Illegal_typeconst_direct_access of Pos.t
| Wrong_expression_kind_attribute of {
pos: Pos.t;
attr_name: string;
expr_kind: string;
attr_class_pos: Pos_or_decl.t;
attr_class_name: string;
intf_name: string;
}
| Ambiguous_object_access of {
pos: Pos.t;
name: string;
self_pos: Pos_or_decl.t;
vis: string;
subclass_pos: Pos_or_decl.t;
class_self: string;
class_subclass: string;
}
| Unserializable_type of {
pos: Pos.t;
message: string;
}
| Invalid_arraykey_constraint of {
pos: Pos.t;
ty_name: string Lazy.t;
}
| Redundant_covariant of {
pos: Pos.t;
msg: string;
suggest: string;
}
| Meth_caller_trait of {
pos: Pos.t;
trait_name: string;
}
| Duplicate_interface of {
pos: Pos.t;
name: string;
others: Pos_or_decl.t list;
}
| Reified_function_reference of Pos.t
| Class_meth_abstract_call of {
pos: Pos.t;
class_name: string;
meth_name: string;
decl_pos: Pos_or_decl.t;
}
| Reinheriting_classish_const of {
pos: Pos.t;
classish_name: string;
src_pos: Pos.t;
src_classish_name: string;
existing_const_origin: string;
const_name: string;
}
| Redeclaring_classish_const of {
pos: Pos.t;
classish_name: string;
redeclaration_pos: Pos.t;
existing_const_origin: string;
const_name: string;
}
| Abstract_function_pointer of {
pos: Pos.t;
class_name: string;
meth_name: string;
decl_pos: Pos_or_decl.t;
}
| Inherited_class_member_with_different_case of {
pos: Pos.t;
member_type: string;
name: string;
name_prev: string;
child_class: string;
prev_class: string;
prev_class_pos: Pos_or_decl.t;
}
| Multiple_inherited_class_member_with_different_case of {
pos: Pos.t;
child_class_name: string;
member_type: string;
class1_name: string;
class1_pos: Pos_or_decl.t;
name1: string;
class2_name: string;
class2_pos: Pos_or_decl.t;
name2: string;
}
| Parent_support_dynamic_type of {
pos: Pos.t;
child_name: string;
child_kind: Ast_defs.classish_kind;
parent_name: string;
parent_kind: Ast_defs.classish_kind;
child_support_dyn: bool;
}
| Property_is_not_enforceable of {
pos: Pos.t;
prop_name: string;
class_name: string;
prop_pos: Pos_or_decl.t;
prop_type: string;
}
| Property_is_not_dynamic of {
pos: Pos.t;
prop_name: string;
class_name: string;
prop_pos: Pos_or_decl.t;
prop_type: string;
}
| Private_property_is_not_enforceable of {
pos: Pos.t;
prop_name: string;
class_name: string;
prop_pos: Pos_or_decl.t;
prop_type: string;
}
| Private_property_is_not_dynamic of {
pos: Pos.t;
prop_name: string;
class_name: string;
prop_pos: Pos_or_decl.t;
prop_type: string;
}
| Immutable_local of Pos.t
| Nonsense_member_selection of {
pos: Pos.t;
kind: string;
}
| Consider_meth_caller of {
pos: Pos.t;
class_name: string;
meth_name: string;
}
| Method_import_via_diamond of {
pos: Pos.t;
class_name: string;
method_pos: Pos_or_decl.t;
method_name: string;
trace1: Pos_or_decl.t Message.t list Lazy.t;
trace2: Pos_or_decl.t Message.t list Lazy.t;
}
| Property_import_via_diamond of {
generic: bool;
pos: Pos.t;
class_name: string;
property_pos: Pos_or_decl.t;
property_name: string;
trace1: Pos_or_decl.t Message.t list Lazy.t;
trace2: Pos_or_decl.t Message.t list Lazy.t;
}
| Unification_cycle of {
pos: Pos.t;
ty_name: string Lazy.t;
}
| Method_variance of Pos.t
| Explain_tconst_where_constraint of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
msgs: Pos_or_decl.t Message.t list Lazy.t;
}
| Format_string of {
pos: Pos.t;
snippet: string;
fmt_string: string;
class_pos: Pos_or_decl.t;
fn_name: string;
class_suggest: string;
}
| Expected_literal_format_string of Pos.t
| Re_prefixed_non_string of {
pos: Pos.t;
reason: [ `non_string | `embedded_expr ];
}
| Bad_regex_pattern of {
pos: Pos.t;
reason:
[ `missing_delim
| `empty_patt
| `invalid_option
| `bad_patt of string
];
}
| Generic_array_strict of Pos.t
| Option_return_only_typehint of {
pos: Pos.t;
kind: [ `void | `noreturn ];
}
| Redeclaring_missing_method of {
pos: Pos.t;
trait_method: string;
}
| Expecting_type_hint of Pos.t
| Expecting_type_hint_variadic of Pos.t
| Expecting_return_type_hint of Pos.t
| Duplicate_using_var of Pos.t
| Illegal_disposable of {
pos: Pos.t;
verb: [ `assigned ];
}
| Escaping_disposable of Pos.t
| Escaping_disposable_param of Pos.t
| Escaping_this of Pos.t
| Must_extend_disposable of Pos.t
| Field_kinds of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Unbound_name of {
pos: Pos.t;
name: string;
class_exists: bool;
}
| Previous_default of Pos.t
| Return_in_void of {
pos: Pos.t;
decl_pos: Pos.t;
}
| This_var_outside_class of Pos.t
| Unbound_global of Pos.t
| Private_inst_meth of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Protected_inst_meth of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Private_meth_caller of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Protected_meth_caller of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Private_class_meth of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Protected_class_meth of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Array_cast of Pos.t
| String_cast of {
pos: Pos.t;
ty_name: string Lazy.t;
}
| Static_outside_class of Pos.t
| Self_outside_class of Pos.t
| New_inconsistent_construct of {
pos: Pos.t;
class_pos: Pos_or_decl.t;
class_name: string;
kind: [ `static | `classname ];
}
| Undefined_parent of Pos.t
| Parent_outside_class of Pos.t
| Parent_abstract_call of {
pos: Pos.t;
meth_name: string;
decl_pos: Pos_or_decl.t;
}
| Self_abstract_call of {
pos: Pos.t;
self_pos: Pos.t;
meth_name: string;
decl_pos: Pos_or_decl.t;
}
| Classname_abstract_call of {
pos: Pos.t;
meth_name: string;
class_name: string;
decl_pos: Pos_or_decl.t;
}
| Static_synthetic_method of {
pos: Pos.t;
meth_name: string;
class_name: string;
decl_pos: Pos_or_decl.t;
}
| Isset_in_strict of Pos.t
| Isset_inout_arg of Pos.t
| Unpacking_disallowed_builtin_function of {
pos: Pos.t;
fn_name: string;
}
| Array_get_arity of {
pos: Pos.t;
name: string;
decl_pos: Pos_or_decl.t;
}
| Undefined_field of {
pos: Pos.t;
name: string;
decl_pos: Pos_or_decl.t;
}
| Array_access of {
pos: Pos.t;
ctxt: [ `read | `write ];
ty_name: string Lazy.t;
decl_pos: Pos_or_decl.t;
}
| Keyset_set of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Array_append of {
pos: Pos.t;
ty_name: string Lazy.t;
decl_pos: Pos_or_decl.t;
}
| Const_mutation of {
pos: Pos.t;
ty_name: string Lazy.t;
decl_pos: Pos_or_decl.t;
}
| Expected_class of {
pos: Pos.t;
suffix: string Lazy.t option;
}
| Unknown_type of {
pos: Pos.t;
expected: string;
reason: Pos_or_decl.t Message.t list Lazy.t;
}
| Parent_in_trait of Pos.t
| Parent_undefined of Pos.t
| Constructor_no_args of Pos.t
| Visibility of {
pos: Pos.t;
msg: string;
decl_pos: Pos_or_decl.t;
reason_msg: string;
}
| Bad_call of {
pos: Pos.t;
ty_name: string Lazy.t;
}
| Extend_final of {
pos: Pos.t;
name: string;
decl_pos: Pos_or_decl.t;
}
| Extend_sealed of {
pos: Pos.t;
parent_pos: Pos_or_decl.t;
parent_name: string;
parent_kind: [ `intf | `trait | `class_ | `enum | `enum_class ];
verb: [ `extend | `implement | `use ];
}
| Sealed_not_subtype of {
pos: Pos.t;
name: string;
child_kind: Ast_defs.classish_kind;
child_pos: Pos_or_decl.t;
child_name: string;
}
| Trait_prop_const_class of {
pos: Pos.t;
name: string;
}
| Implement_abstract of {
pos: Pos.t;
is_final: bool;
decl_pos: Pos_or_decl.t;
trace: Pos_or_decl.t Message.t list Lazy.t;
name: string;
kind: [ `meth | `prop | `const | `ty_const ];
quickfixes: Pos.t Quickfix.t list;
}
| Abstract_member_in_concrete_class of {
pos: Pos.t;
class_name_pos: Pos.t;
is_final: bool;
member_kind: [ `method_ | `property | `constant | `type_constant ];
member_name: string;
}
| Generic_static of {
pos: Pos.t;
typaram_name: string;
}
| Ellipsis_strict_mode of {
pos: Pos.t;
require: [ `Param_name | `Type_and_param_name ];
}
| Object_string of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Object_string_deprecated of Pos.t
| Cyclic_typedef of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Require_args_reify of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Require_generic_explicit of {
pos: Pos.t;
param_name: string;
decl_pos: Pos_or_decl.t;
}
| Invalid_reified_arg of {
pos: Pos.t;
param_name: string;
decl_pos: Pos_or_decl.t;
arg_info: Pos_or_decl.t Message.t list Lazy.t;
}
| Invalid_reified_arg_reifiable of {
pos: Pos.t;
param_name: string;
decl_pos: Pos_or_decl.t;
ty_pos: Pos_or_decl.t;
ty_msg: string Lazy.t;
}
| New_class_reified of {
pos: Pos.t;
class_kind: string;
suggested_class_name: string option;
}
| Class_get_reified of Pos.t
| Static_meth_with_class_reified_generic of {
pos: Pos.t;
generic_pos: Pos.t;
}
| Consistent_construct_reified of Pos.t
| Bad_fn_ptr_construction of Pos.t
| Reified_generics_not_allowed of Pos.t
| New_without_newable of {
pos: Pos.t;
name: string;
}
| Discarded_awaitable of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
}
| Unknown_object_member of {
pos: Pos.t;
member_name: string;
elt: [ `meth | `prop ];
reason: Pos_or_decl.t Message.t list Lazy.t;
}
| Non_class_member of {
pos: Pos.t;
member_name: string;
elt: [ `meth | `prop ];
ty_name: string Lazy.t;
decl_pos: Pos_or_decl.t;
}
| Null_container of {
pos: Pos.t;
null_witness: Pos_or_decl.t Message.t list Lazy.t;
}
| Declared_covariant of {
pos: Pos.t;
param_pos: Pos.t;
msgs: Pos.t Message.t list Lazy.t;
}
| Declared_contravariant of {
pos: Pos.t;
param_pos: Pos.t;
msgs: Pos.t Message.t list Lazy.t;
}
| Static_prop_type_generic_param of {
pos: Pos.t;
var_ty_pos: Pos_or_decl.t;
class_pos: Pos_or_decl.t;
}
| Contravariant_this of {
pos: Pos.t;
class_name: string;
typaram_name: string;
}
| Cyclic_typeconst of {
pos: Pos.t;
tyconst_names: string list;
}
| Array_get_with_optional_field of {
recv_pos: Pos.t;
field_pos: Pos.t;
field_name: string;
decl_pos: Pos_or_decl.t;
}
| Mutating_const_property of Pos.t
| Self_const_parent_not of Pos.t
| Unexpected_ty_in_tast of {
pos: Pos.t;
expected_ty: string Lazy.t;
actual_ty: string Lazy.t;
}
| Call_lvalue of Pos.t
| Unsafe_cast_await of Pos.t
(* == Primary and secondary =============================================== *)
| Smember_not_found of {
pos: Pos.t;
kind:
[ `class_constant
| `class_typeconst
| `class_variable
| `static_method
];
class_name: string;
class_pos: Pos_or_decl.t;
member_name: string;
hint: ([ `instance | `static ] * Pos_or_decl.t * string) option;
quickfixes: Pos.t Quickfix.t list;
}
| Type_arity_mismatch of {
pos: Pos.t;
actual: int;
decl_pos: Pos_or_decl.t;
expected: int;
}
| Typing_too_many_args of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
actual: int;
expected: int;
}
| Typing_too_few_args of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
actual: int;
expected: int;
}
| Non_object_member of {
pos: Pos.t;
decl_pos: Pos_or_decl.t;
ty_name: string Lazy.t;
ctxt: [ `read | `write ];
member_name: string;
kind: [ `class_typeconst | `method_ | `property ];
}
| Static_instance_intersection of {
class_pos: Pos.t;
instance_pos: Pos_or_decl.t Lazy.t;
static_pos: Pos_or_decl.t Lazy.t;
member_name: string;
kind: [ `meth | `prop ];
}
[@@deriving show]
end
module rec Error : sig
type t =
| Primary of Primary.t
| Apply of Callback.t * t
| Apply_reasons of Reasons_callback.t * Secondary.t
| Assert_in_current_decl of Secondary.t * Pos_or_decl.ctx
| Multiple of t list
| Union of t list
| Intersection of t list
| With_code of t * Error_code.t
end
and Secondary : sig
(** Specific error information which needs to be given a primary position from
the AST being typed to be transformable into a user error.
This can be done via applying a [Reasons_callback.t] using
[apply_reasons].
*)
type t =
| Of_error of Error.t
(* == Primary and secondary =============================================== *)
| Smember_not_found of {
pos: Pos_or_decl.t;
kind:
[ `class_constant
| `class_typeconst
| `class_variable
| `static_method
];
class_name: string;
class_pos: Pos_or_decl.t;
member_name: string;
hint: ([ `instance | `static ] * Pos_or_decl.t * string) option;
}
| Type_arity_mismatch of {
pos: Pos_or_decl.t;
actual: int;
decl_pos: Pos_or_decl.t;
expected: int;
}
| Typing_too_many_args of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
actual: int;
expected: int;
}
| Typing_too_few_args of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
actual: int;
expected: int;
}
| Non_object_member of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
ty_name: string Lazy.t;
ctxt: [ `read | `write ];
member_name: string;
kind: [ `class_typeconst | `method_ | `property ];
}
| Rigid_tvar_escape of {
pos: Pos_or_decl.t;
name: string;
}
(* == Secondary only ====================================================== *)
| Violated_constraint of {
cstrs: (Pos_or_decl.t * Pos_or_decl.t Message.t) list;
ty_sub: Typing_defs_core.internal_type;
ty_sup: Typing_defs_core.internal_type;
is_coeffect: bool;
}
| Concrete_const_interface_override of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
parent_origin: string;
name: string;
}
| Interface_or_trait_const_multiple_defs of {
pos: Pos_or_decl.t;
origin: string;
name: string;
parent_pos: Pos_or_decl.t;
parent_origin: string;
}
| Interface_typeconst_multiple_defs of {
pos: Pos_or_decl.t;
origin: string;
is_abstract: bool;
name: string;
parent_pos: Pos_or_decl.t;
parent_origin: string;
}
| Visibility_extends of {
pos: Pos_or_decl.t;
vis: string;
parent_pos: Pos_or_decl.t;
parent_vis: string;
}
| Visibility_override_internal of {
pos: Pos_or_decl.t;
module_name: string option;
parent_pos: Pos_or_decl.t;
parent_module: string;
}
| Abstract_tconst_not_allowed of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
tconst_name: string;
}
| Missing_constructor of Pos_or_decl.t
| Missing_field of {
pos: Pos_or_decl.t;
name: string;
decl_pos: Pos_or_decl.t;
}
| Shape_fields_unknown of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Accept_disposable_invariant of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Ifc_external_contravariant of {
pos_sub: Pos_or_decl.t;
pos_super: Pos_or_decl.t;
}
| Invalid_destructure of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
ty_name: string Lazy.t;
}
| Unpack_array_required_argument of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Unpack_array_variadic_argument of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Fun_too_many_args of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
actual: int;
expected: int;
}
| Fun_too_few_args of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
actual: int;
expected: int;
}
| Fun_unexpected_nonvariadic of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Fun_variadicity_hh_vs_php56 of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Required_field_is_optional of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
def_pos: Pos_or_decl.t;
name: string;
}
| Return_disposable_mismatch of {
pos_sub: Pos_or_decl.t;
is_marked_return_disposable: bool;
pos_super: Pos_or_decl.t;
}
| Ifc_policy_mismatch of {
pos: Pos_or_decl.t;
policy: string;
pos_super: Pos_or_decl.t;
policy_super: string;
}
| Overriding_prop_const_mismatch of {
pos: Pos_or_decl.t;
is_const: bool;
parent_pos: Pos_or_decl.t;
parent_is_const: bool;
}
| Override_final of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
}
| Override_async of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
}
| Override_lsb of {
pos: Pos_or_decl.t;
member_name: string;
parent_pos: Pos_or_decl.t;
}
| Multiple_concrete_defs of {
pos: Pos_or_decl.t;
name: string;
origin: string;
class_name: string;
parent_pos: Pos_or_decl.t;
parent_origin: string;
}
| Cyclic_enum_constraint of Pos_or_decl.t
| Inoutness_mismatch of {
pos: Pos_or_decl.t;
decl_pos: Pos_or_decl.t;
}
| Decl_override_missing_hint of Pos_or_decl.t
| Bad_lateinit_override of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
parent_is_lateinit: bool;
}
| Bad_method_override of {
pos: Pos_or_decl.t;
member_name: string;
}
| Bad_prop_override of {
pos: Pos_or_decl.t;
member_name: string;
}
| Bad_xhp_attr_required_override of {
pos: Pos_or_decl.t;
tag: string;
parent_pos: Pos_or_decl.t;
parent_tag: string;
}
| Coeffect_subtyping of {
pos: Pos_or_decl.t;
cap: string Lazy.t;
pos_expected: Pos_or_decl.t;
cap_expected: string Lazy.t;
}
| Override_method_support_dynamic_type of {
pos: Pos_or_decl.t;
method_name: string;
parent_pos: Pos_or_decl.t;
parent_origin: string;
}
| Readonly_mismatch of {
pos: Pos_or_decl.t;
kind: [ `fn | `fn_return | `param ];
reason_sub: Pos_or_decl.t Message.t list Lazy.t;
reason_super: Pos_or_decl.t Message.t list Lazy.t;
}
| Cross_package_mismatch of {
pos: Pos_or_decl.t;
reason_sub: Pos_or_decl.t Message.t list Lazy.t;
reason_super: Pos_or_decl.t Message.t list Lazy.t;
}
| Not_sub_dynamic of {
pos: Pos_or_decl.t;
ty_name: string Lazy.t;
dynamic_part: Pos_or_decl.t Message.t list Lazy.t;
}
| Subtyping_error of {
ty_sub: Typing_defs_core.internal_type;
ty_sup: Typing_defs_core.internal_type;
is_coeffect: bool;
}
| Method_not_dynamically_callable of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
}
| This_final of {
pos_sub: Pos_or_decl.t;
pos_super: Pos_or_decl.t;
class_name: string;
}
| Typeconst_concrete_concrete_override of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
}
| Abstract_concrete_override of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
kind: [ `constant | `method_ | `property | `typeconst ];
}
| Override_no_default_typeconst of {
pos: Pos_or_decl.t;
parent_pos: Pos_or_decl.t;
}
| Unsupported_refinement of Pos_or_decl.t
| Missing_class_constant of {
pos: Pos_or_decl.t;
class_name: string;
const_name: string;
}
| Invalid_refined_const_kind of {
pos: Pos_or_decl.t;
class_name: string;
const_name: string;
correct_kind: string;
wrong_kind: string;
}
| Inexact_tconst_access of Pos_or_decl.t * (Pos_or_decl.t * string)
| Violated_refinement_constraint of {
cstr: [ `As | `Super ] * Pos_or_decl.t;
}
[@@deriving show]
end
and Callback : sig
(** A mechanism to apply transformations to primary errors *)
type t =
| Always of Primary.t
| Of_primary of Primary.t
| With_claim_as_reason of t * Primary.t
| With_code of Error_code.t * Pos.t Quickfix.t list
| Retain_code of t
| With_side_effect of t * (unit -> unit)
[@@deriving show]
(* -- Constructors -------------------------------------------------------- *)
(** Ignore any arguments and always return the given base error *)
val always : Primary.t -> t
(** Perform an aribrary side-effects when the error is evaluated *)
val with_side_effect : t -> eff:(unit -> unit) -> t
[@@ocaml.deprecated
"This function will be removed. Please avoid adding side effects to error callbacks."]
(** Provide default code, claim, reasons and quickfixes from the supplied
`Primary.t` error *)
val of_primary_error : Primary.t -> t
(** Provide a default error code *)
val with_code : code:Error_code.t -> t
(** Ignore any incoming error code argument and use the existing one *)
val retain_code : t -> t
(** Fix the claim of the callback to `new_claim` and add the received claim
argument to the list of reasons *)
val with_claim_as_reason : t -> new_claim:Primary.t -> t
(* -- Specific callbacks -------------------------------------------------- *)
val unify_error : t
val index_type_mismatch : t
val covariant_index_type_mismatch : t
val expected_stringlike : t
val constant_does_not_match_enum_type : t
val enum_underlying_type_must_be_arraykey : t
val enum_constraint_must_be_arraykey : t
val enum_subtype_must_have_compatible_constraint : t
val parameter_default_value_wrong_type : t
val newtype_alias_must_satisfy_constraint : t
val missing_return : t
val inout_return_type_mismatch : t
val class_constant_value_does_not_match_hint : t
val class_property_initializer_type_does_not_match_hint : t
val xhp_attribute_does_not_match_hint : t
val strict_str_concat_type_mismatch : t
val strict_str_interp_type_mismatch : t
val bitwise_math_invalid_argument : t
val inc_dec_invalid_argument : t
val math_invalid_argument : t
val using_error : Pos.t -> has_await:bool -> t
end
and Reasons_callback : sig
(** A mechanism to apply transformations to secondary errors *)
type op =
| Append
| Prepend
[@@deriving show]
type component =
| Code
| Reasons
| Quickfixes
[@@deriving show]
type t =
| Always of Error.t
| Of_error of Error.t
| Of_callback of Callback.t * Pos.t Message.t Lazy.t
| Retain of t * component
| Incoming_reasons of t * op
| With_code of t * Error_code.t
| With_reasons of t * Pos_or_decl.t Message.t list Lazy.t
| Add_quickfixes of t * Pos.t Quickfix.t list
| Add_reason of t * op * Pos_or_decl.t Message.t Lazy.t
| From_on_error of
((?code:int ->
?quickfixes:Pos.t Quickfix.t list ->
Pos_or_decl.t Message.t list ->
unit)
[@show.opaque])
[@ocaml.deprecated
"This constructor will be removed. Please use the provided combinators for constructing error callbacks."]
| Prepend_on_apply of t * Secondary.t
| Assert_in_current_decl of Error_code.t * Pos_or_decl.ctx
| Drop_reasons_on_apply of t
[@@deriving show]
(* -- Constructors -------------------------------------------------------- *)
(** Construct a `Reasons_callback.t` from a side-effecting function. This is
included to support legacy code only and will be removed once that code is
migrated *)
val from_on_error :
(?code:int ->
?quickfixes:Pos.t Quickfix.t list ->
Pos_or_decl.t Message.t list ->
unit) ->
t
[@@ocaml.deprecated
"This function will be removed. Please use the provided combinators for constructing error callbacks."]
(** Create a constant `Reasons_callback.t` which defaults to the value of the
supplied `Error.t` when applied. Each component of that error may be
subsequently overridden if a value for that component is supplied during
evaluation *)
val of_error : Error.t -> t
(** Create a `Reasons_callback.t` which defaults to the value of the supplied
`Primary.t` error when applied; this is equivalent
to `of_error @@ primary err`
*)
val of_primary_error : Primary.t -> t
(** Replace the current default claim with the claim from the supplied
`Pos.t Message.t` *)
val with_claim : Callback.t -> claim:Pos.t Message.t Lazy.t -> t
(** Replace the current default error code with the supplied one *)
val with_code : t -> code:Error_code.t -> t
(** Replace the current list of reasons with those supplied. This is typically
used in combination with `retain_reasons` to fix the `reasons` of the
`User_error.t` that is obtained when the callback is applied
*)
val with_reasons : t -> reasons:Pos_or_decl.t Message.t list Lazy.t -> t
(** Add a `quickfix` to the `User_error.t` generated when the callback is
applied
*)
val add_quickfixes : t -> Pos.t Quickfix.t list -> t
(** Add the `reason` to the start of current list of reasons *)
val prepend_reason : t -> reason:Pos_or_decl.t Message.t Lazy.t -> t
(** Add the `reason` to the end of current list of reasons *)
val append_reason : t -> reason:Pos_or_decl.t Message.t Lazy.t -> t
(** When applied, append the supplied reasons to the current list of reasons *)
val append_incoming_reasons : t -> t
(** When applied, prepend the supplied reasons to the current list of reasons *)
val prepend_incoming_reasons : t -> t
(** Ignore the incoming error code argument when evaluating to a `User_error.t`.
This is equivalent to the following function, given some callback `on_error`:
`(fun ?code:_ ?quickfixes reasons -> on_error ?quickfixes reasons)`
*)
val retain_code : t -> t
(** Ignore the incoming reasons argument when evaluating to a `User_error.t`.
This is equivalent to the following function, given some callback `on_error`:
`(fun ?code ?quickfixes _ -> on_error ?code ?quickfixes)`
*)
val retain_reasons : t -> t
(** Ignore the incoming quickfixes component when evaluating to a `User_error.t`.
This is equivalent to the following function, given some callback `on_error`:
`(fun ?code ?quickfixes:_ reasons -> on_error ?code reasons)`
*)
val retain_quickfixes : t -> t
(** Create a constant `Reasons_callback.t` which always evaluates to the
supplied `Error.t` when applied
This is equivalent to the following function, for some `error` of type
`Error.t`:
`(fun ?code:_ ?quickfixes:_ _ -> error)`
This is also the same as:
`retain_code @@ retain_reasons @@ reatain_quickfixes @@ of_error error`
*)
val always : Error.t -> t
(** Applying the `Reasons_callback.t` `(prepend_on_apply err snd_err1) snd_err2`
is the same as applying `err` the secondary error created by prepending
`snd_err1` to `snd_err2`.
The `Secondary.t` error created by the prepending operation has the same
code of `snd_err1` and the reasons from `snd_err1` prepended to those of
`snd_err2`.
*)
val prepend_on_apply : t -> Secondary.t -> t
(** Creates a callback that ignores the secondary reasons that are passed
when it is applied and then proceeds with the callback it wraps. This
construct is only helpful if the wrapped callback contains enough
context to generate a usable error message. *)
val drop_reasons_on_apply : t -> t
(* Applying the `Reasons_callback.t` `(assert_in_current_decl code ctx) err`
will evaluate the `Secondary.t` `err` then use the head of the list of
reasons as claim in the resulting error, given the position for that
reason is in the current decl. *)
val assert_in_current_decl : Error_code.t -> ctx:Pos_or_decl.ctx -> t
(* -- Specific callbacks -------------------------------------------------- *)
val unify_error_at : Pos.t -> t
val expr_tree_splice_error :
Pos.t ->
expr_pos:Pos_or_decl.t ->
contextual_reasons:Pos_or_decl.t Message.t list Lazy.t option ->
dsl_opt:string option ->
docs_url:string option Lazy.t ->
t
val bad_enum_decl : Pos.t -> t
val bad_conditional_support_dynamic :
Pos.t ->
child:string ->
parent:string ->
ty_name:string Lazy.t ->
self_ty_name:string Lazy.t ->
t
val bad_decl_override :
name:string -> parent_pos:Pos.t -> parent_name:string -> t
val invalid_class_refinement : Pos.t -> t
val explain_where_constraint :
Pos.t -> in_class:bool -> decl_pos:Pos_or_decl.t -> t
val explain_constraint : Pos.t -> t
val rigid_tvar_escape_at : Pos.t -> string -> t
val invalid_type_hint : Pos.t -> t
val type_constant_mismatch : t -> t
val class_constant_type_mismatch : t -> t
val unsatisfied_req_callback :
class_pos:Pos.t ->
trait_pos:Pos_or_decl.t ->
req_pos:Pos_or_decl.t ->
string ->
t
val invalid_echo_argument_at : Pos.t -> t
val index_type_mismatch_at : Pos.t -> t
val unify_error_assert_primary_pos_in_current_decl : Pos_or_decl.ctx -> t
val invalid_type_hint_assert_primary_pos_in_current_decl :
Pos_or_decl.ctx -> t
end
type t = Error.t
val pp : Format.formatter -> t -> unit
val show : t -> string
(** Iterate over an error calling `on_prim` and `on_snd` when each `Primary.t`
and `Secondary.t` error is encountered, respectively. *)
val iter :
t -> on_prim:(Primary.t -> unit) -> on_snd:(Secondary.t -> unit) -> unit
(* -- Constructors -------------------------------------------------------- *)
(** Lift a `Primary.t` error to a `Typing_error.t` *)
val primary : Primary.t -> t
(** Lift a `Primary.Coeffect.t` error to a `Typing_error.t` *)
val coeffect : Primary.Coeffect.t -> t
(** Lift a `Primary.Enum.t` error to a `Typing_error.t` *)
val enum : Primary.Enum.t -> t
(** Lift a `Primary.Expr_tree.t` error to a `Typing_error.t` *)
val expr_tree : Primary.Expr_tree.t -> t
(** Lift a `Primary.Coeffect.t` error to a `Typing_error.t` *)
val ifc : Primary.Ifc.t -> t
(** Lift a `Primary.Modules.t` error to a `Typing_error.t` *)
val modules : Primary.Modules.t -> t
(** Lift a `Primary.Readonly.t` error to a `Typing_error.t` *)
val readonly : Primary.Readonly.t -> t
(** Lift a `Primary.Shape.t` error to a `Typing_error.t` *)
val shape : Primary.Shape.t -> t
(** Lift a `Primary.Wellformedness.t` error to a `Typing_error.t` *)
val wellformedness : Primary.Wellformedness.t -> t
(** Lift a `Primary.Xhp.t` error to a `Typing_error.t` *)
val xhp : Primary.Xhp.t -> t
(** Lift a `Primary.CaseType.t` error to a `Typing_error.t` *)
val casetype : Primary.CaseType.t -> t
(** Apply a the `Reasons_callback.t` to the supplied `Secondary.t` error, using
the reasons and error code associated with that error *)
val apply_reasons : Secondary.t -> on_error:Reasons_callback.t -> t
(** Apply a the `Callback.t` to the supplied `Secondary.t` error, using
the claim, reasons, quickfixes and error code associated with that error *)
val apply : t -> on_error:Callback.t -> t
(** Lift a `Secondary.t` error to a `Typing_error.t` by asserting that the
position of the first reason is in the current decl and treating it as a
claim *)
val assert_in_current_decl : Secondary.t -> ctx:Pos_or_decl.ctx -> t
(** Report a list of errors at each type of an intersection *)
val intersect : t list -> t
(** Calling `intersect_opt xs` returns `None` if the list is empty and `intersect xs` otherwise *)
val intersect_opt : t list -> t option
(** Report a list of errors at each type of a union*)
val union : t list -> t
(** Calling `union_opt xs` returns `None` if the list is empty and `union xs` otherwise *)
val union_opt : t list -> t option
(** Report multiple errors at a single type *)
val multiple : t list -> t
(** Calling `multiple_opt xs` returns `None` if the list is empty and `multiple xs` otherwise *)
val multiple_opt : t list -> t option
(** Report two errors at a single type; `both t1 t2` is the same as
`multiple [t1;t2]`*)
val both : t -> t -> t
(** Modify the code that will be reported when evaluated to a `User_error.t` *)
val with_code : t -> code:Error_code.t -> t
val count : t -> int |
OCaml | hhvm/hphp/hack/src/typing/typing_error_utils.ml | (*
* Copyrighd (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Core
module Error_code = Error_codes.Typing
type error =
Error_code.t
* Pos.t Message.t Lazy.t
* Pos_or_decl.t Message.t list Lazy.t
* Pos.t Quickfix.t list
module Common = struct
let map2 ~f x y = Lazy.(x >>= fun x -> map ~f:(fun y -> f x y) y)
(* The contents of the following error message can trigger `hh rage` in
* sandcastle. If you change it, please make sure the existing trigger in
* `flib/intern/sandcastle/hack/SandcastleCheckHackOnDiffsStep.php` still
* catches this error message. *)
let please_file_a_bug_message =
let hacklang_feedback_support_link =
"https://fb.workplace.com/groups/hackforhiphop/"
in
let hh_rage = Markdown_lite.md_codify "hh rage" in
Printf.sprintf
"Please run %s and post in %s."
hh_rage
hacklang_feedback_support_link
let reasons_of_trail trail =
List.map trail ~f:(fun pos -> (pos, "Typedef definition comes from here"))
let typing_too_many_args pos decl_pos actual expected =
let claim =
lazy
( pos,
Printf.sprintf
"Too many arguments (expected %d but got %d)"
expected
actual )
and reasons = lazy [(decl_pos, "Definition is here")] in
(Error_code.TypingTooManyArgs, claim, reasons)
let typing_too_few_args pos decl_pos actual expected =
let claim =
lazy
( pos,
Printf.sprintf
"Too few arguments (required %d but got %d)"
expected
actual )
and reasons = lazy [(decl_pos, "Definition is here")] in
(Error_code.TypingTooFewArgs, claim, reasons)
let snot_found_suggestion orig similar kind =
match similar with
| (`instance, pos, v) -> begin
match kind with
| `static_method ->
Render.suggestion_message ~modifier:"instance method " orig v pos
| `class_constant ->
Render.suggestion_message ~modifier:"instance property " orig v pos
| `class_variable
| `class_typeconst ->
Render.suggestion_message orig v pos
end
| (`static, pos, v) -> Render.suggestion_message orig v pos
let smember_not_found pos kind member_name class_name class_pos hint =
let claim =
lazy
( pos,
Printf.sprintf
"No %s %s in %s"
(Render.string_of_class_member_kind kind)
(Markdown_lite.md_codify member_name)
(Markdown_lite.md_codify @@ Render.strip_ns class_name) )
in
let reasons =
lazy
(let default =
[
( class_pos,
"Declaration of "
^ (Markdown_lite.md_codify @@ Render.strip_ns class_name)
^ " is here" );
]
in
Option.value_map hint ~default ~f:(fun similar ->
snot_found_suggestion member_name similar kind :: default))
in
(Error_code.SmemberNotFound, claim, reasons)
let non_object_member pos ctxt ty_name member_name kind decl_pos =
let code =
match ctxt with
| `read -> Error_code.NonObjectMemberRead
| `write -> Error_code.NonObjectMemberWrite
in
let claim =
lazy
(let msg_start =
Printf.sprintf
"You are trying to access the %s %s but this is %s"
(Render.string_of_class_member_kind kind)
(Markdown_lite.md_codify member_name)
ty_name
in
let msg =
if String.equal ty_name "a shape" then
msg_start ^ ". Did you mean `$foo['" ^ member_name ^ "']` instead?"
else
msg_start
in
(pos, msg))
and reasons = lazy [(decl_pos, "Definition is here")] in
(code, claim, reasons)
let badpos_message =
Printf.sprintf
"Incomplete position information! Your type error is in this file, but we could only find related positions in another file. %s"
please_file_a_bug_message
let badpos_message_2 =
Printf.sprintf
"Incomplete position information! We couldn't find the exact line of your type error in this definition. %s"
please_file_a_bug_message
let wrap_error_in_different_file ~current_file ~current_span reasons =
let claim =
lazy
(let message =
List.map reasons ~f:(fun (pos, msg) ->
Pos.print_verbose_relative (Pos_or_decl.unsafe_to_raw_pos pos)
^ ": "
^ msg)
in
let stack =
Exception.get_current_callstack_string 99 |> Exception.clean_stack
in
HackEventLogger.type_check_primary_position_bug
~current_file
~message
~stack;
if Pos.equal current_span Pos.none then
(Pos.make_from current_file, badpos_message)
else
(current_span, badpos_message_2))
in
(claim, reasons)
let eval_assert ctx current_span (code, reasons) : error option =
match Lazy.force reasons with
| (pos, msg) :: rest as reasons ->
let (claim, reasons) =
match
Pos_or_decl.fill_in_filename_if_in_current_decl
~current_decl_and_file:ctx
pos
with
| Some pos -> (lazy (pos, msg), rest)
| _ ->
wrap_error_in_different_file
~current_file:ctx.Pos_or_decl.file
~current_span
reasons
in
Some (code, claim, lazy reasons, [])
| _ -> None
end
module Eval_result : sig
type 'a t
val empty : 'a t
val single : 'a -> 'a t
val multiple : 'a t list -> 'a t
val union : 'a t list -> 'a t
val intersect : 'a t list -> 'a t
val of_option : 'a option -> 'a t
val map : 'a t -> f:('a -> 'b) -> 'b t
val bind : 'a t -> f:('a -> 'b t) -> 'b t
val iter : 'a t -> f:('a -> unit) -> unit
val suppress_intersection : 'a t -> is_suppressed:('a -> bool) -> 'a t
end = struct
type 'a t =
| Empty
| Single of 'a
| Multiple of 'a t list
| Union of 'a t list
| Intersect of 'a t list
let empty = Empty
let single a = Single a
let multiple = function
| [] -> Empty
| xs -> Multiple xs
let union = function
| [] -> Empty
| xs -> Union xs
let intersect = function
| [] -> Empty
| xs -> Intersect xs
let of_option = function
| Some x -> Single x
| _ -> Empty
let map t ~f =
let rec aux = function
| Empty -> Empty
| Single x -> Single (f x)
| Multiple xs -> Multiple (List.map ~f:aux xs)
| Union xs -> Union (List.map ~f:aux xs)
| Intersect xs -> Intersect (List.map ~f:aux xs)
in
aux t
let bind t ~f =
let rec aux = function
| Empty -> Empty
| Single x -> f x
| Multiple xs -> Multiple (List.map ~f:aux xs)
| Union xs -> Union (List.map ~f:aux xs)
| Intersect xs -> Intersect (List.map ~f:aux xs)
in
aux t
let iter t ~f =
let rec aux = function
| Empty -> ()
| Single x -> f x
| Multiple xs
| Union xs
| Intersect xs ->
List.iter ~f:aux xs
in
aux t
let is_suppressed t p =
let rec f = function
| Intersect xs -> List.exists ~f xs
| Multiple xs
| Union xs ->
List.for_all ~f xs
| Empty -> false
| Single x -> p x
in
f t
let suppress_intersection t ~is_suppressed:p =
let p t = is_suppressed t p in
let rec aux t =
match t with
| Intersect xs -> auxs [] xs
| Multiple xs -> multiple @@ List.map ~f:aux xs
| Union xs -> union @@ List.map ~f:aux xs
| _ -> t
and auxs acc = function
| [] -> intersect @@ List.rev acc
| next :: rest ->
if p next then
aux next
else
auxs (next :: acc) rest
in
aux t
end
module Eval_primary = struct
module Eval_shape = struct
let invalid_shape_field_type pos ty_pos ty_name trail =
let reasons =
lazy
((ty_pos, "Not " ^ Lazy.force ty_name)
:: Common.reasons_of_trail trail)
and claim =
lazy (pos, "A shape field name must be an `int` or `string`")
in
(Error_code.InvalidShapeFieldType, claim, reasons, [])
let invalid_shape_field_name pos =
let claim =
lazy
( pos,
"Shape access requires a string literal, integer literal, or a class constant"
)
in
(Error_code.InvalidShapeFieldName, claim, lazy [], [])
let invalid_shape_field_name_empty pos =
let claim = lazy (pos, "A shape field name cannot be an empty string") in
(Error_code.InvalidShapeFieldNameEmpty, claim, lazy [], [])
let invalid_shape_field_literal pos witness_pos =
let claim = lazy (pos, "Shape uses literal string as field name")
and reason =
lazy
[
(Pos_or_decl.of_raw_pos witness_pos, "But expected a class constant");
]
in
(Error_code.InvalidShapeFieldLiteral, claim, reason, [])
let invalid_shape_field_const pos witness_pos =
let claim = lazy (pos, "Shape uses class constant as field name")
and reason =
lazy
[
(Pos_or_decl.of_raw_pos witness_pos, "But expected a literal string");
]
in
(Error_code.InvalidShapeFieldConst, claim, reason, [])
let shape_field_class_mismatch pos class_name witness_pos witness_class_name
=
let claim =
lazy
( pos,
"Shape field name is class constant from "
^ Markdown_lite.md_codify class_name )
and reason =
lazy
[
( Pos_or_decl.of_raw_pos witness_pos,
"But expected constant from "
^ Markdown_lite.md_codify witness_class_name );
]
in
(Error_code.ShapeFieldClassMismatch, claim, reason, [])
let shape_field_type_mismatch pos ty_name witness_pos witness_ty_name =
let claim =
lazy
(pos, "Shape field name is " ^ Lazy.force ty_name ^ " class constant")
and reason =
lazy
[
( Pos_or_decl.of_raw_pos witness_pos,
"But expected " ^ Lazy.force witness_ty_name );
]
in
(Error_code.ShapeFieldTypeMismatch, claim, reason, [])
let invalid_shape_remove_key pos =
let claim =
lazy (pos, "You can only unset fields of **local** variables")
in
(Error_code.InvalidShapeRemoveKey, claim, lazy [], [])
let shapes_key_exists_always_true pos field_name decl_pos =
let claim = lazy (pos, "This `Shapes::keyExists()` check is always true")
and reason =
lazy
[
( decl_pos,
"The field "
^ Markdown_lite.md_codify field_name
^ " exists because of this definition" );
]
in
(Error_code.ShapesKeyExistsAlwaysTrue, claim, reason, [])
let shape_field_non_existence_reason pos name = function
| `Undefined ->
lazy
[
( pos,
"The field "
^ Markdown_lite.md_codify name
^ " is not defined in this shape" );
]
| `Nothing reason ->
Lazy.map reason ~f:(fun reason ->
( pos,
"The type of the field "
^ Markdown_lite.md_codify name
^ " in this shape doesn't allow any values" )
:: reason)
let shapes_key_exists_always_false pos field_name decl_pos reason =
let claim = lazy (pos, "This `Shapes::keyExists()` check is always false")
and reason =
shape_field_non_existence_reason decl_pos field_name reason
in
(Error_code.ShapesKeyExistsAlwaysFalse, claim, reason, [])
let shapes_method_access_with_non_existent_field
pos field_name method_name decl_pos reason =
let claim =
lazy
( pos,
"You are calling "
^ Markdown_lite.md_codify ("Shapes::" ^ method_name ^ "()")
^ " on a field known to not exist" )
and reason =
shape_field_non_existence_reason decl_pos field_name reason
in
(Error_code.ShapesMethodAccessWithNonExistentField, claim, reason, [])
let shapes_access_with_non_existent_field pos field_name decl_pos reason =
let claim = lazy (pos, "You are accessing a field known to not exist")
and reason =
shape_field_non_existence_reason decl_pos field_name reason
in
(Error_code.ShapeAccessWithNonExistentField, claim, reason, [])
let to_error t ~env:_ =
let open Typing_error.Primary.Shape in
match t with
| Invalid_shape_field_type { pos; ty_pos; ty_name; trail } ->
invalid_shape_field_type pos ty_pos ty_name trail
| Invalid_shape_field_name { pos; is_empty = false } ->
invalid_shape_field_name pos
| Invalid_shape_field_name { pos; is_empty = true } ->
invalid_shape_field_name_empty pos
| Invalid_shape_field_literal { pos; witness_pos } ->
invalid_shape_field_literal pos witness_pos
| Invalid_shape_field_const { pos; witness_pos } ->
invalid_shape_field_const pos witness_pos
| Shape_field_class_mismatch
{ pos; class_name; witness_pos; witness_class_name } ->
shape_field_class_mismatch pos class_name witness_pos witness_class_name
| Shape_field_type_mismatch { pos; ty_name; witness_pos; witness_ty_name }
->
shape_field_type_mismatch pos ty_name witness_pos witness_ty_name
| Invalid_shape_remove_key pos -> invalid_shape_remove_key pos
| Shapes_key_exists_always_true { pos; field_name; decl_pos } ->
shapes_key_exists_always_true pos field_name decl_pos
| Shapes_key_exists_always_false { pos; field_name; decl_pos; reason } ->
shapes_key_exists_always_false pos field_name decl_pos reason
| Shapes_method_access_with_non_existent_field
{ pos; field_name; method_name; decl_pos; reason } ->
shapes_method_access_with_non_existent_field
pos
field_name
method_name
decl_pos
reason
| Shapes_access_with_non_existent_field
{ pos; field_name; decl_pos; reason } ->
shapes_access_with_non_existent_field pos field_name decl_pos reason
end
module Eval_enum = struct
let enum_class_label_member_mismatch pos label expected_ty_msg_opt =
let claim = lazy (pos, "Enum class label/member mismatch")
and reasons =
match expected_ty_msg_opt with
| Some expected_ty_msg ->
Lazy.map expected_ty_msg ~f:(fun expected_ty_msg ->
expected_ty_msg
@ [
( Pos_or_decl.of_raw_pos pos,
Format.sprintf "But got an enum class label: `#%s`" label );
])
| None ->
lazy
[
( Pos_or_decl.of_raw_pos pos,
Format.sprintf "Unexpected enum class label: `#%s`" label );
]
in
(Error_code.UnifyError, claim, reasons, [])
let enum_type_bad pos is_enum_class ty_name trail =
let claim =
Lazy.map ty_name ~f:(fun ty_name ->
let ty = Markdown_lite.md_codify ty_name in
let msg =
if is_enum_class then
"Invalid base type for an enum class: "
else
"Enums must be `int` or `string` or `arraykey`, not "
in
(pos, msg ^ ty))
and reasons = lazy (Common.reasons_of_trail trail) in
(Error_code.EnumTypeBad, claim, reasons, [])
let enum_type_bad_case_type pos ty_name case_type_decl_pos =
let claim =
lazy
(pos, "Cannot use a case type as the base type for an enum/enum class")
and reasons =
Lazy.map ty_name ~f:(fun ty_name ->
let ty = Markdown_lite.md_codify ty_name in
[(case_type_decl_pos, ty ^ " is declared as a case type here")])
in
(Error_code.EnumTypeBad, claim, reasons, [])
let enum_constant_type_bad pos ty_pos ty_name trail =
let claim = lazy (pos, "Enum constants must be an `int` or `string`")
and reasons =
Lazy.map ty_name ~f:(fun ty_name ->
(ty_pos, "Not " ^ Markdown_lite.md_codify ty_name)
:: Common.reasons_of_trail trail)
in
(Error_code.EnumConstantTypeBad, claim, reasons, [])
let enum_type_typedef_nonnull pos =
let claim =
lazy (pos, "Can't use `typedef` that resolves to nonnull in enum")
in
(Error_code.EnumTypeTypedefNonnull, claim, lazy [], [])
let enum_switch_redundant pos first_pos const_name =
let claim = lazy (pos, "Redundant `case` statement")
and reason =
lazy
[
( Pos_or_decl.of_raw_pos first_pos,
Markdown_lite.md_codify const_name ^ " already handled here" );
]
in
(Error_code.EnumSwitchRedundant, claim, reason, [])
let enum_switch_nonexhaustive pos kind decl_pos missing =
let claim =
lazy
( pos,
"`switch` statement nonexhaustive; at least the following cases are missing: "
^ (List.map ~f:Markdown_lite.md_codify missing
|> String.concat ~sep:", ") )
and reason = lazy [(decl_pos, kind ^ " declared here")] in
(Error_code.EnumSwitchNonexhaustive, claim, reason, [])
let enum_switch_redundant_default pos kind decl_pos =
let claim =
lazy
( pos,
"All cases already covered; a redundant `default` case prevents "
^ "detecting future errors. If your goal is to guard against "
^ "invalid values for this type, do an `is` check before the switch."
)
and reason = lazy [(decl_pos, kind ^ " declared here")] in
(Error_code.EnumSwitchRedundantDefault, claim, reason, [])
let enum_switch_not_const pos =
let claim =
lazy (pos, "Case in `switch` on enum is not an enum constant")
in
(Error_code.EnumSwitchNotConst, claim, lazy [], [])
let enum_switch_wrong_class pos kind expected actual =
let claim =
lazy
( pos,
"Switching on "
^ kind
^ Markdown_lite.md_codify expected
^ " but using constant from "
^ Markdown_lite.md_codify actual )
in
(Error_code.EnumSwitchWrongClass, claim, lazy [], [])
let enum_class_label_unknown
pos label_name enum_name decl_pos most_similar ty_pos =
let enum_name = Markdown_lite.md_codify (Render.strip_ns enum_name) in
let claim =
lazy
( pos,
Printf.sprintf
"Enum class %s does not contain a label named %s."
enum_name
(Markdown_lite.md_codify label_name) )
in
let decl_reason =
[(decl_pos, Printf.sprintf "%s is defined here" enum_name)]
in
let (similar_reason, quickfixes) =
match most_similar with
| Some (similar_name, similar_pos) ->
( [
( similar_pos,
Printf.sprintf
"Did you mean %s?"
(Markdown_lite.md_codify similar_name) );
],
[
Quickfix.make
~title:("Change to " ^ Markdown_lite.md_codify similar_name)
~new_text:similar_name
pos;
] )
| None -> ([], [])
in
let ty_reason =
match ty_pos with
| Some ty_pos ->
[
( ty_pos,
Printf.sprintf
"This is why I expected an enum class label from %s."
enum_name );
]
| None -> []
in
let reason = lazy (decl_reason @ similar_reason @ ty_reason) in
(Error_code.EnumClassLabelUnknown, claim, reason, quickfixes)
let enum_class_label_as_expr pos =
let claim =
lazy
( pos,
"Not enough type information to infer the type of this enum class label."
)
in
(Error_code.EnumClassLabelAsExpression, claim, lazy [], [])
let incompatible_enum_inclusion_base pos classish_name src_classish_name =
let claim =
lazy
( pos,
"Enum "
^ Render.strip_ns classish_name
^ " includes enum "
^ Render.strip_ns src_classish_name
^ " but their base types are incompatible" )
in
(Error_code.IncompatibleEnumInclusion, claim, lazy [], [])
let incompatible_enum_inclusion_constraint
pos classish_name src_classish_name =
let claim =
lazy
( pos,
"Enum "
^ Render.strip_ns classish_name
^ " includes enum "
^ Render.strip_ns src_classish_name
^ " but their constraints are incompatible" )
in
(Error_code.IncompatibleEnumInclusion, claim, lazy [], [])
let enum_inclusion_not_enum pos classish_name src_classish_name =
let claim =
lazy
( pos,
"Enum "
^ Render.strip_ns classish_name
^ " includes "
^ Render.strip_ns src_classish_name
^ " which is not an enum" )
in
(Error_code.IncompatibleEnumInclusion, claim, lazy [], [])
let to_error t ~env:_ =
let open Typing_error.Primary.Enum in
match t with
| Enum_type_bad { pos; is_enum_class; ty_name; trail } ->
enum_type_bad pos is_enum_class ty_name trail
| Enum_type_bad_case_type { pos; ty_name; case_type_decl_pos } ->
enum_type_bad_case_type pos ty_name case_type_decl_pos
| Enum_constant_type_bad { pos; ty_pos; ty_name; trail } ->
enum_constant_type_bad pos ty_pos ty_name trail
| Enum_type_typedef_nonnull pos -> enum_type_typedef_nonnull pos
| Enum_switch_redundant { pos; first_pos; const_name } ->
enum_switch_redundant pos first_pos const_name
| Enum_switch_nonexhaustive { pos; kind; decl_pos; missing } ->
enum_switch_nonexhaustive pos kind decl_pos missing
| Enum_switch_redundant_default { pos; kind; decl_pos } ->
enum_switch_redundant_default pos kind decl_pos
| Enum_switch_not_const pos -> enum_switch_not_const pos
| Enum_switch_wrong_class { pos; kind; expected; actual } ->
enum_switch_wrong_class pos kind expected actual
| Enum_class_label_unknown
{ pos; label_name; enum_name; decl_pos; most_similar; ty_pos } ->
enum_class_label_unknown
pos
label_name
enum_name
decl_pos
most_similar
ty_pos
| Enum_class_label_as_expr pos -> enum_class_label_as_expr pos
| Enum_class_label_member_mismatch { pos; label; expected_ty_msg_opt } ->
enum_class_label_member_mismatch pos label expected_ty_msg_opt
| Incompatible_enum_inclusion_base
{ pos; classish_name; src_classish_name } ->
incompatible_enum_inclusion_base pos classish_name src_classish_name
| Incompatible_enum_inclusion_constraint
{ pos; classish_name; src_classish_name } ->
incompatible_enum_inclusion_constraint
pos
classish_name
src_classish_name
| Enum_inclusion_not_enum { pos; classish_name; src_classish_name } ->
enum_inclusion_not_enum pos classish_name src_classish_name
end
module Eval_expr_tree = struct
let expression_tree_non_public_member pos decl_pos =
let claim =
lazy (pos, "Cannot access non-public members within expression trees.")
and reason = lazy [(decl_pos, "Member defined here")] in
(Error_code.ExpressionTreeNonPublicProperty, claim, reason, [])
let reified_static_method_in_expr_tree pos =
let claim =
lazy
( pos,
"Static method calls on reified generics are not permitted in Expression Trees."
)
in
(Error_code.ReifiedStaticMethodInExprTree, claim, lazy [], [])
let this_var_in_expr_tree pos =
let claim = lazy (pos, "`$this` is not bound inside expression trees") in
(Error_code.ThisVarOutsideClass, claim, lazy [], [])
let experimental_expression_trees pos =
let claim =
lazy
( pos,
"This type is not permitted as an expression tree visitor. It is not included in "
^ "`allowed_expression_tree_visitors` in `.hhconfig`, and this file does not "
^ "contain `<<file:__EnableUnstableFeatures('expression_trees')>>`."
)
in
(Error_code.ExperimentalExpressionTrees, claim, lazy [], [])
let expression_tree_unsupported_operator pos member_name class_name =
let claim =
lazy
( pos,
match member_name with
| "__bool" ->
(* If the user writes `if ($not_bool)`, provide a more specific
error rather than a generic missing method error for
`$not_bool->__bool()`. *)
Printf.sprintf
"`%s` cannot be used as a boolean (it has no instance method named `__bool`)"
class_name
| _ ->
(* If the user writes `$not_int + ...`, provide a more specific
error rather than a generic missing method error for
`$not_int->__plus(...)`. *)
Printf.sprintf
"`%s` does not support this operator (it has no instance method named `%s`)"
class_name
member_name )
in
(Error_code.MemberNotFound, claim, lazy [], [])
let to_error t ~env:_ =
let open Typing_error.Primary.Expr_tree in
match t with
| Expression_tree_non_public_member { pos; decl_pos } ->
expression_tree_non_public_member pos decl_pos
| Reified_static_method_in_expr_tree pos ->
reified_static_method_in_expr_tree pos
| This_var_in_expr_tree pos -> this_var_in_expr_tree pos
| Experimental_expression_trees pos -> experimental_expression_trees pos
| Expression_tree_unsupported_operator { pos; member_name; class_name } ->
expression_tree_unsupported_operator pos member_name class_name
end
module Eval_readonly = struct
let readonly_modified pos reason_opt =
let claim =
lazy (pos, "This value is readonly, its properties cannot be modified")
and reason =
Option.value_map
reason_opt
~default:(lazy [])
~f:(Lazy.map ~f:List.return)
in
(Error_code.ReadonlyValueModified, claim, reason, [])
let readonly_mismatch pos what pos_sub pos_super =
let (msg, msg_sub, msg_super) =
match what with
| `prop_assign ->
( "property assignment",
"readonly",
"But it's being assigned to a mutable property" )
| `collection_mod ->
("collection modification", "readonly", "But this value is mutable")
| `arg_readonly ->
( "argument",
"readonly",
"It is incompatible with this parameter, which is mutable" )
| `arg_mut ->
( "argument",
"mutable",
"It is incompatible with this parameter, which is readonly" )
in
let claim = lazy (pos, Format.sprintf "Invalid %s" msg)
and reason =
lazy
[
(pos_sub, Format.sprintf "This expression is %s" msg_sub);
(pos_super, msg_super);
]
in
(Error_code.ReadonlyMismatch, claim, reason, [])
let readonly_invalid_as_mut pos =
let claim =
lazy
( pos,
"Only value types and arrays can be converted to mutable. This value can never be a primitive."
)
in
(Error_code.ReadonlyInvalidAsMut, claim, lazy [], [])
let readonly_exception pos =
let claim =
lazy
( pos,
"This exception is readonly; throwing readonly exceptions is not currently supported."
)
in
(Error_code.ReadonlyException, claim, lazy [], [])
let explicit_readonly_cast pos decl_pos kind =
let qf_pos = Pos.shrink_to_start pos in
let quickfixes =
[Quickfix.make ~title:"Insert `readonly`" ~new_text:"readonly " qf_pos]
in
let kind_str =
match kind with
| `fn_call -> "function call"
| `property -> "property"
| `static_property -> "static property"
in
let claim =
lazy
( pos,
"This "
^ kind_str
^ " returns a readonly value. It must be explicitly wrapped in a readonly expression."
)
and reason = lazy [(decl_pos, "The " ^ kind_str ^ " is defined here.")] in
(Error_code.ExplicitReadonlyCast, claim, reason, quickfixes)
let readonly_method_call pos decl_pos =
let claim =
lazy
( pos,
"This expression is readonly, so it can only call readonly methods"
)
and reason = lazy [(decl_pos, "This method is not readonly")] in
(Error_code.ReadonlyMethodCall, claim, reason, [])
let readonly_closure_call pos decl_pos suggestion =
let claim =
lazy
( pos,
"This function is readonly, so it must be marked readonly at declaration time to be called."
)
and reason = lazy [(decl_pos, "Did you mean to " ^ suggestion ^ "?")] in
(Error_code.ReadonlyClosureCall, claim, reason, [])
let to_error t ~env:_ =
let open Typing_error.Primary.Readonly in
match t with
| Readonly_modified { pos; reason_opt } ->
readonly_modified pos reason_opt
| Readonly_mismatch { pos; what; pos_sub; pos_super } ->
readonly_mismatch pos what pos_sub pos_super
| Readonly_invalid_as_mut pos -> readonly_invalid_as_mut pos
| Readonly_exception pos -> readonly_exception pos
| Explicit_readonly_cast { pos; decl_pos; kind } ->
explicit_readonly_cast pos decl_pos kind
| Readonly_method_call { pos; decl_pos } ->
readonly_method_call pos decl_pos
| Readonly_closure_call { pos; decl_pos; suggestion } ->
readonly_closure_call pos decl_pos suggestion
end
module Eval_ifc = struct
let illegal_information_flow
pos secondaries source_poss source sink_poss sink =
let explain poss node printer reasons =
let msg = printer node in
List.map ~f:(fun pos -> (pos, msg)) poss @ reasons
in
let source = Markdown_lite.md_codify source in
let sink = Markdown_lite.md_codify sink in
let sprintf_main = sprintf "Data with policy %s appears in context %s." in
let claim = lazy (pos, sprintf_main source sink) in
let reasons =
lazy
(let sprintf = Printf.sprintf in
let sprintf_source =
sprintf "This may be the data source with policy %s"
in
let sprintf_sink =
sprintf "This may be the data sink with policy %s"
in
let other_occurrences =
let f p =
(p, "Another program point contributing to the illegal flow")
in
List.map ~f secondaries
in
[]
|> explain source_poss source sprintf_source
|> explain sink_poss sink sprintf_sink
|> List.append other_occurrences
|> List.rev)
in
(Error_code.IllegalInformationFlow, claim, reasons, [])
let ifc_internal_error pos msg =
let claim =
lazy
( pos,
"IFC Internal Error: "
^ msg
^ ". If you see this error and aren't expecting it, please `hh rage` and let the Hack team know."
)
in
(Error_code.IFCInternalError, claim, lazy [], [])
let unknown_information_flow pos what =
let claim =
lazy
( pos,
"Unable to analyze information flow for "
^ what
^ ". This might be unsafe." )
in
(Error_code.UnknownInformationFlow, claim, lazy [], [])
let context_implicit_policy_leakage
pos secondaries source_poss source sink_poss sink =
let claim =
lazy
( pos,
Printf.sprintf
"Context-implicit policy leaks into %s via %s."
(Markdown_lite.md_codify sink)
(Markdown_lite.md_codify source) )
and reasons =
lazy
(let program_point p =
(p, "Another program point contributing to the leakage")
in
let explain_source p = (p, "Leakage source") in
let explain_sink p = (p, "Leakage sink") in
List.map ~f:program_point secondaries
@ List.map ~f:explain_source source_poss
@ List.map ~f:explain_sink sink_poss)
in
(Error_code.ContextImplicitPolicyLeakage, claim, reasons, [])
let to_error t ~env:_ =
let open Typing_error.Primary.Ifc in
match t with
| Illegal_information_flow
{ pos; secondaries; source_poss; source; sink_poss; sink } ->
illegal_information_flow
pos
secondaries
source_poss
source
sink_poss
sink
| Ifc_internal_error { pos; msg } -> ifc_internal_error pos msg
| Unknown_information_flow { pos; what } ->
unknown_information_flow pos what
| Context_implicit_policy_leakage
{ pos; secondaries; source_poss; source; sink_poss; sink } ->
context_implicit_policy_leakage
pos
secondaries
source_poss
source
sink_poss
sink
end
module Eval_coeffect = struct
let call_coeffect
pos available_pos available_incl_unsafe required_pos required =
let reasons =
Common.map2
available_incl_unsafe
required
~f:(fun available_incl_unsafe required ->
[
( available_pos,
"From this declaration, the context of this function body provides "
^ available_incl_unsafe );
( required_pos,
"But the function being called requires " ^ required );
])
and claim =
lazy
( pos,
"This call is not allowed because its capabilities are incompatible with the context"
)
in
(Error_code.CallCoeffects, claim, reasons, [])
let op_coeffect_error
pos op_name required available_pos locally_available suggestion err_code
=
let reasons =
Common.map2
(Option.value ~default:(lazy []) suggestion)
locally_available
~f:(fun suggestion locally_available ->
let x =
( available_pos,
"The local (enclosing) context provides " ^ locally_available )
in
x :: suggestion)
and claim =
Lazy.map required ~f:(fun required ->
( pos,
op_name
^ " requires "
^ required
^ ", which is not provided by the context." ))
in
(err_code, claim, reasons, [])
let to_error t ~env:_ =
let open Typing_error.Primary.Coeffect in
match t with
| Op_coeffect_error
{
pos;
op_name;
required;
available_pos;
locally_available;
suggestion;
err_code;
} ->
op_coeffect_error
pos
op_name
required
available_pos
locally_available
suggestion
err_code
| Call_coeffect
{ pos; available_pos; available_incl_unsafe; required_pos; required }
->
call_coeffect
pos
available_pos
available_incl_unsafe
required_pos
required
end
module Eval_wellformedness = struct
let missing_return pos hint_pos is_async =
let return_type =
if is_async then
"Awaitable<void>"
else
"void"
in
let quickfixes =
match hint_pos with
| None -> []
| Some hint_pos ->
[
Quickfix.make
~title:("Change to " ^ Markdown_lite.md_codify return_type)
~new_text:"void"
(Pos_or_decl.unsafe_to_raw_pos hint_pos);
]
in
let claim = lazy (pos, "Invalid return type") in
(Error_code.MissingReturnInNonVoidFunction, claim, lazy [], quickfixes)
let void_usage pos reason =
let claim =
lazy (pos, "You are using the return value of a `void` function")
in
(Error_code.VoidUsage, claim, reason, [])
let noreturn_usage pos reason =
let claim =
lazy (pos, "You are using the return value of a `noreturn` function")
in
(Error_code.NoreturnUsage, claim, reason, [])
let returns_with_and_without_value pos with_value_pos without_value_pos_opt
=
let claim =
lazy (pos, "This function can exit with and without returning a value")
and reason =
lazy
((Pos_or_decl.of_raw_pos with_value_pos, "Returning a value here.")
:: Option.value_map
without_value_pos_opt
~default:
[
( Pos_or_decl.of_raw_pos pos,
"This function does not always return a value" );
]
~f:(fun p ->
[(Pos_or_decl.of_raw_pos p, "Returning without a value here")])
)
in
(Error_code.ReturnsWithAndWithoutValue, claim, reason, [])
let non_void_annotation_on_return_void_function is_async hint_pos =
let (async_indicator, return_type) =
if is_async then
("Async f", "Awaitable<void>")
else
("F", "void")
in
let claim =
lazy
( hint_pos,
Printf.sprintf
"%sunctions that do not return a value must have a type of %s"
async_indicator
return_type )
in
let quickfixes =
[
Quickfix.make
~title:("Change to " ^ Markdown_lite.md_codify return_type)
~new_text:return_type
hint_pos;
]
in
(Error_code.NonVoidAnnotationOnReturnVoidFun, claim, lazy [], quickfixes)
let tuple_syntax p =
( Error_code.TupleSyntax,
lazy (p, "Did you want a *tuple*? Try `(X,Y)`, not `tuple<X,Y>`"),
lazy [],
[] )
let invalid_class_refinement pos =
( Error_code.InvalidClassRefinement,
lazy (pos, "Invalid class refinement"),
lazy [],
[] )
let to_error t ~env:_ =
let open Typing_error.Primary.Wellformedness in
match t with
| Missing_return { pos; hint_pos; is_async } ->
missing_return pos hint_pos is_async
| Void_usage { pos; reason } -> void_usage pos reason
| Noreturn_usage { pos; reason } -> noreturn_usage pos reason
| Returns_with_and_without_value
{ pos; with_value_pos; without_value_pos_opt } ->
returns_with_and_without_value pos with_value_pos without_value_pos_opt
| Non_void_annotation_on_return_void_function { is_async; hint_pos } ->
non_void_annotation_on_return_void_function is_async hint_pos
| Tuple_syntax pos -> tuple_syntax pos
| Invalid_class_refinement { pos } -> invalid_class_refinement pos
end
module Eval_modules = struct
let module_hint pos decl_pos =
let claim = lazy (pos, "You cannot use this type in a public declaration.")
and reason = lazy [(decl_pos, "It is declared as `internal` here")] in
(Error_code.ModuleHintError, claim, reason, [])
let module_mismatch pos current_module_opt decl_pos target_module =
let claim =
lazy
( pos,
Printf.sprintf
"Cannot access an internal element from module `%s` %s"
target_module
(match current_module_opt with
| Some m -> Printf.sprintf "in module `%s`" m
| None -> "outside of a module") )
and reason =
lazy
[(decl_pos, Printf.sprintf "This is from module `%s`" target_module)]
in
(Error_code.ModuleError, claim, reason, [])
let module_unsafe_trait_access access_pos trait_pos =
( Error_code.ModuleError,
lazy
( access_pos,
"Cannot access `internal` members inside a non-internal trait" ),
lazy
[
( trait_pos,
"This trait must be made `internal` to access other internal members"
);
],
[] )
let module_missing_import
pos decl_pos module_pos current_module target_module_opt =
let target_module =
match target_module_opt with
| Some m -> m
| None -> "global"
in
let claim =
lazy
( pos,
Printf.sprintf
"Cannot access a public element from module '%s' in module '%s'"
target_module
current_module )
and reason =
lazy
[
(decl_pos, Printf.sprintf "This is from module `%s`" target_module);
( module_pos,
Printf.sprintf
"Module '%s' does not import the public members of module '%s'"
current_module
target_module );
]
in
(Error_code.ModuleError, claim, reason, [])
let module_missing_export
pos decl_pos module_pos current_module_opt target_module =
let current_module =
match current_module_opt with
| Some m -> m
| None -> "global"
in
let claim =
lazy
( pos,
Printf.sprintf
"Cannot access a public element from module '%s' in module '%s'"
target_module
current_module )
and reason =
lazy
[
(decl_pos, Printf.sprintf "This is from module `%s`" target_module);
( module_pos,
Printf.sprintf
"Module '%s' does not export its public members to module '%s'"
target_module
current_module );
]
in
(Error_code.ModuleError, claim, reason, [])
let get_module_str m_opt =
match m_opt with
| Some s -> Printf.sprintf "module `%s`" s
| None -> "outside of a module"
let get_package_str p_opt =
match p_opt with
| Some s -> Printf.sprintf "package `%s`" s
| None -> "the default package"
let module_cross_pkg_call
(pos : Pos.t)
(decl_pos : Pos_or_decl.t)
(current_package_opt : string option)
(target_package_opt : string option) =
let current_package = get_package_str current_package_opt in
let target_package =
match target_package_opt with
| Some s -> s
| None ->
failwith "target package can't be default for cross_package call"
in
let claim =
lazy
( pos,
Printf.sprintf
"Cannot reference this CrossPackage method using package %s from %s"
target_package
current_package )
and reason =
lazy
[
( decl_pos,
Printf.sprintf
"This function is marked cross package, so requires the package %s to be loaded. You can check if package %s is loaded by placing this call inside a block like `if(package %s)`"
target_package
target_package
target_package );
]
in
(Error_code.InvalidCrossPackage, claim, reason, [])
let module_cross_pkg_access
(pos : Pos.t)
(decl_pos : Pos_or_decl.t)
(module_pos : Pos_or_decl.t)
(package_pos : Pos.t)
(current_module_opt : string option)
(current_package_opt : string option)
(target_module_opt : string option)
(target_package_opt : string option)
(soft : bool) =
let current_module = get_module_str current_module_opt in
let target_module = get_module_str target_module_opt in
let current_package = get_package_str current_package_opt in
let target_package = get_package_str target_package_opt in
let is_default = Pos.equal Pos.none package_pos in
let relationship =
if soft then
"only soft includes"
else
"does not include"
in
let claim =
lazy
( pos,
Printf.sprintf
"Cannot access a public element in %s from %s"
target_package
current_package )
and reason =
lazy
[
( decl_pos,
Printf.sprintf
"This is from %s, which is in %s"
target_module
target_package );
( module_pos,
Printf.sprintf
"But this is from %s, which belongs to %s"
current_module
current_package );
( (if is_default then
module_pos
else
Pos_or_decl.of_raw_pos package_pos),
Printf.sprintf
"And %s %s %s"
current_package
relationship
target_package );
]
in
let error_code =
if soft then
Error_code.InvalidCrossPackageSoft
else
Error_code.InvalidCrossPackage
in
(error_code, claim, reason, [])
let to_error t ~env:_ =
let open Typing_error.Primary.Modules in
match t with
| Module_hint { pos; decl_pos } -> module_hint pos decl_pos
| Module_mismatch { pos; current_module_opt; decl_pos; target_module } ->
module_mismatch pos current_module_opt decl_pos target_module
| Module_unsafe_trait_access { access_pos; trait_pos } ->
module_unsafe_trait_access access_pos trait_pos
| Module_missing_import
{ pos; decl_pos; module_pos; current_module; target_module_opt } ->
module_missing_import
pos
decl_pos
module_pos
current_module
target_module_opt
| Module_missing_export
{ pos; decl_pos; module_pos; current_module_opt; target_module } ->
module_missing_export
pos
decl_pos
module_pos
current_module_opt
target_module
| Module_cross_pkg_call
{ pos; decl_pos; current_package_opt; target_package_opt } ->
module_cross_pkg_call
pos
decl_pos
current_package_opt
target_package_opt
| Module_cross_pkg_access
{
pos;
decl_pos;
module_pos;
package_pos;
current_module_opt;
current_package_opt;
target_module_opt;
target_package_opt;
} ->
module_cross_pkg_access
pos
decl_pos
module_pos
package_pos
current_module_opt
current_package_opt
target_module_opt
target_package_opt
false (* Soft *)
| Module_soft_included_access
{
pos;
decl_pos;
module_pos;
package_pos;
current_module_opt;
current_package_opt;
target_module_opt;
target_package_opt;
} ->
module_cross_pkg_access
pos
decl_pos
module_pos
package_pos
current_module_opt
current_package_opt
target_module_opt
target_package_opt
true (* Soft *)
end
module Eval_xhp = struct
let xhp_required pos why_xhp ty_reason_msg =
let claim = lazy (pos, "An XHP instance was expected") in
( Error_code.XhpRequired,
claim,
Lazy.map ty_reason_msg ~f:(fun ty_reason_msg ->
(Pos_or_decl.of_raw_pos pos, why_xhp) :: ty_reason_msg),
[] )
let illegal_xhp_child pos ty_reason_msg =
let claim = lazy (pos, "XHP children must be compatible with XHPChild") in
(Error_code.IllegalXhpChild, claim, ty_reason_msg, [])
let missing_xhp_required_attr pos attr ty_reason_msg =
let claim =
lazy
( pos,
"Required attribute "
^ Markdown_lite.md_codify attr
^ " is missing." )
in
(Error_code.MissingXhpRequiredAttr, claim, ty_reason_msg, [])
let to_error t ~env:_ =
let open Typing_error.Primary.Xhp in
match t with
| Xhp_required { pos; why_xhp; ty_reason_msg } ->
xhp_required pos why_xhp ty_reason_msg
| Illegal_xhp_child { pos; ty_reason_msg } ->
illegal_xhp_child pos ty_reason_msg
| Missing_xhp_required_attr { pos; attr; ty_reason_msg } ->
missing_xhp_required_attr pos attr ty_reason_msg
end
module Eval_casetype = struct
let overlapping_variant_types pos name tag why =
let claim =
lazy
( pos,
let name = Utils.strip_ns name in
Printf.sprintf
"The case type `%s` cannot be decomposed because it contains overlapping variant types. The following types share the same runtime data type `%s`:"
name
tag )
in
(Error_code.IllegalCaseTypeVariants, claim, why, [])
let unrecoverable_variant_type pos name hints =
let transform (p, n) =
(Pos_or_decl.of_raw_pos p, Printf.sprintf "`%s` cannot be recovered" n)
in
( Error_code.IllegalCaseTypeVariants,
lazy
( pos,
Printf.sprintf
"The case type `%s` is invalid because one or more of its variants cannot be recovered using type tests"
name ),
lazy (List.map hints ~f:transform),
[] )
let to_error t ~env:_ =
let open Typing_error.Primary.CaseType in
match t with
| Overlapping_variant_types { pos; name; tag; why } ->
overlapping_variant_types pos name tag why
| Unrecoverable_variant_type { pos; name; hints } ->
unrecoverable_variant_type pos name hints
end
let unify_error pos msg_opt reasons_opt =
let claim = lazy (pos, Option.value ~default:"Typing error" msg_opt)
and reasons = Option.value ~default:(lazy []) reasons_opt in
(Error_code.UnifyError, claim, reasons, [])
let generic_unify pos msg =
let claim = lazy (pos, msg) in
(Error_code.GenericUnify, claim, lazy [], [])
let unresolved_tyvar pos =
let claim =
lazy
(pos, "The type of this expression contains an unresolved type variable")
in
(Error_code.UnresolvedTypeVariable, claim, lazy [], [])
let using_error pos has_await =
let claim =
lazy
(let (note, cls) =
if has_await then
(" with await", Naming_special_names.Classes.cIAsyncDisposable)
else
("", Naming_special_names.Classes.cIDisposable)
in
( pos,
Printf.sprintf
"This expression is used in a `using` clause%s so it must have type `%s`"
note
cls ))
in
(Error_code.UnifyError, claim, lazy [], [])
let bad_enum_decl pos =
( Error_code.BadEnumExtends,
lazy (pos, "This enum declaration is invalid."),
lazy [],
[] )
let bad_conditional_support_dynamic pos child parent ty_name self_ty_name =
let claim =
Lazy.(
ty_name >>= fun ty_name ->
self_ty_name >>= fun self_ty_name ->
let statement =
ty_name
^ " is subtype of dynamic implies "
^ self_ty_name
^ " is subtype of dynamic"
in
return
( pos,
"Class "
^ Render.strip_ns child
^ " must support dynamic at least as often as "
^ Render.strip_ns parent
^ ":\n"
^ statement ))
in
(Error_code.BadConditionalSupportDynamic, claim, lazy [], [])
let bad_decl_override name parent_pos parent_name =
( Error_code.BadDeclOverride,
lazy
( parent_pos,
Printf.sprintf
"Some members in class %s are incompatible with those declared in type %s"
(Render.strip_ns name |> Markdown_lite.md_codify)
(Render.strip_ns parent_name |> Markdown_lite.md_codify) ),
lazy [],
[] )
let explain_where_constraint pos decl_pos in_class =
( Error_code.TypeConstraintViolation,
lazy (pos, "A `where` type constraint is violated here"),
lazy
[
( decl_pos,
Printf.sprintf "This is the %s with `where` type constraints"
@@
if in_class then
"class"
else
"method" );
],
[] )
let explain_constraint pos =
( Error_code.TypeConstraintViolation,
lazy (pos, "Some type arguments violate their constraints"),
lazy [],
[] )
let rigid_tvar_escape pos what =
( Error_code.RigidTVarEscape,
lazy (pos, "Rigid type variable escapes its " ^ what),
lazy [],
[] )
let invalid_type_hint pos =
(Error_code.InvalidTypeHint, lazy (pos, "Invalid type hint"), lazy [], [])
let unsatisfied_req pos trait_pos req_name req_pos =
let reasons =
lazy
(let r =
( trait_pos,
"This requires to extend or implement " ^ Render.strip_ns req_name
)
in
if Pos_or_decl.equal trait_pos req_pos then
[r]
else
[r; (req_pos, "Required here")])
and claim =
lazy
( pos,
"This class does not satisfy all the requirements of its traits or interfaces."
)
in
(Error_code.UnsatisfiedReq, claim, reasons, [])
let unsatisfied_req_class pos trait_pos req_name req_pos =
let reasons =
lazy
(let r =
(trait_pos, "This requires to be exactly " ^ Render.strip_ns req_name)
in
if Pos_or_decl.equal trait_pos req_pos then
[r]
else
[r; (req_pos, "Required here")])
and claim =
lazy
( pos,
"This class does not satisfy all the requirements of its traits or interfaces."
)
in
(Error_code.UnsatisfiedReq, claim, reasons, [])
let req_class_not_final pos trait_pos req_pos =
let reasons =
lazy
(let r =
(trait_pos, "The trait with a require class constraint is used here")
in
if Pos_or_decl.equal trait_pos req_pos then
[r]
else
[r; (req_pos, "The require class constraint is here")])
and claim =
lazy
( pos,
"This class must be final because it uses a trait with a require class constraint."
)
in
(Error_code.UnsatisfiedReq, claim, reasons, [])
let incompatible_reqs pos req_name req_class_pos req_extends_pos =
let reasons =
lazy
(let r1 =
( req_class_pos,
"This requires exactly class " ^ Render.strip_ns req_name )
in
let r2 =
( req_extends_pos,
"This requires a subtype of class " ^ Render.strip_ns req_name )
in
[r1; r2])
in
let claim = lazy (pos, "This trait defines incompatible requirements.") in
(Error_code.UnsatisfiedReq, claim, reasons, [])
let trait_not_used pos trait_name req_class_pos class_pos class_name =
let class_name = Render.strip_ns class_name in
let reasons =
lazy
[
(class_pos, "Class " ^ class_name ^ " is defined here.");
(req_class_pos, "The require class requirement is here.");
]
in
let claim =
lazy
( pos,
"Trait "
^ Render.strip_ns trait_name
^ " requires class "
^ Render.strip_ns class_name
^ " but "
^ Render.strip_ns class_name
^ " does not use it. Either use the trait or delete it." )
in
(Error_code.TraitNotUsed, claim, reasons, [])
let invalid_echo_argument pos =
let claim =
lazy
( pos,
"Invalid "
^ Markdown_lite.md_codify "echo"
^ "/"
^ Markdown_lite.md_codify "print"
^ " argument" )
in
(Error_code.InvalidEchoArgument, claim, lazy [], [])
let index_type_mismatch pos is_covariant_container msg_opt reasons_opt =
let code =
if is_covariant_container then
Error_code.CovariantIndexTypeMismatch
else
Error_code.IndexTypeMismatch
and claim =
lazy (pos, Option.value ~default:"Invalid index expression" msg_opt)
and reasons = Option.value reasons_opt ~default:(lazy []) in
(code, claim, reasons, [])
let member_not_found pos kind member_name class_name class_pos hint reason =
let kind_str =
match kind with
| `method_ -> "instance method"
| `property -> "property"
in
let claim =
lazy
( pos,
Printf.sprintf
"No %s %s in %s"
kind_str
(Markdown_lite.md_codify member_name)
(Markdown_lite.md_codify @@ Render.strip_ns class_name) )
in
let default =
Lazy.map reason ~f:(fun reason ->
reason
@ [
( class_pos,
"Declaration of "
^ (Markdown_lite.md_codify @@ Render.strip_ns class_name)
^ " is here" );
])
in
let reasons =
Option.value_map hint ~default ~f:(function
| (`instance, pos, v) ->
Lazy.map default ~f:(fun default ->
Render.suggestion_message member_name v pos :: default)
| (`static, pos, v) ->
let modifier =
match kind with
| `method_ -> "static method "
| `property -> "static property "
in
Lazy.map default ~f:(fun default ->
Render.suggestion_message member_name ~modifier v pos :: default))
in
let quickfixes =
Option.value_map hint ~default:[] ~f:(fun (_, _, new_text) ->
[Quickfix.make ~title:("Change to ->" ^ new_text) ~new_text pos])
in
(Error_code.MemberNotFound, claim, reasons, quickfixes)
let construct_not_instance_method pos =
let claim =
lazy
( pos,
"`__construct` is not an instance method and shouldn't be invoked directly"
)
in
(Error_code.ConstructNotInstanceMethod, claim, lazy [], [])
let ambiguous_inheritance pos origin class_name =
let claim =
lazy
( pos,
"This declaration was inherited from an object of type "
^ Markdown_lite.md_codify origin
^ ". Redeclare this member in "
^ Markdown_lite.md_codify class_name
^ " with a compatible signature." )
in
(Error_code.UnifyError, claim, lazy [], [])
let expected_tparam pos n decl_pos =
let claim =
lazy
( pos,
"Expected "
^
match n with
| 0 -> "no type parameters"
| 1 -> "exactly one type parameter"
| n -> string_of_int n ^ " type parameters" )
and reasons = lazy [(decl_pos, "Definition is here")] in
(Error_code.ExpectedTparam, claim, reasons, [])
let typeconst_concrete_concrete_override pos decl_pos =
let reasons = lazy [(decl_pos, "Previously defined here")]
and claim = lazy (pos, "Cannot re-declare this type constant") in
(Error_code.TypeconstConcreteConcreteOverride, claim, reasons, [])
let constant_multiple_concrete_conflict pos name definitions =
let reasons =
lazy
(List.mapi
~f:(fun i (p, via) ->
let first =
if i = 0 then
"One"
else
"Another"
in
let message =
Format.sprintf "%s conflicting definition is here" first
in
let full_message =
match via with
| Some parent_name ->
Format.sprintf "%s, inherited through %s" message parent_name
| None -> message
in
(p, full_message))
definitions)
in
let claim =
lazy
( pos,
Format.sprintf
"Constant %s is defined concretely in multiple ancestors"
name )
in
(Error_code.ConcreteConstInterfaceOverride, claim, reasons, [])
let invalid_memoized_param pos reason =
let claim =
lazy
( pos,
"Parameters to memoized function must be null, bool, int, float, string, an object deriving IMemoizeParam, or a Container thereof. See also http://docs.hhvm.com/hack/attributes/special#__memoize"
)
in
(Error_code.InvalidMemoizedParam, claim, reason, [])
let invalid_arraykey
pos container_pos container_ty_name key_pos key_ty_name ctxt =
let reasons =
lazy
[
(container_pos, "This container is " ^ container_ty_name);
( key_pos,
String.capitalize key_ty_name
^ " cannot be used as a key for "
^ container_ty_name );
]
and claim =
lazy (pos, "This value is not a valid key type for this container")
and code =
Error_code.(
match ctxt with
| `read -> IndexTypeMismatch
| `write -> InvalidArrayKeyWrite)
in
(code, claim, reasons, [])
let invalid_keyset_value
pos container_pos container_ty_name value_pos value_ty_name =
let reasons =
lazy
[
(container_pos, "This container is " ^ container_ty_name);
(value_pos, String.capitalize value_ty_name ^ " is not an arraykey");
]
and claim = lazy (pos, "Keyset values must be arraykeys") in
(Error_code.IndexTypeMismatch, claim, reasons, [])
let invalid_set_value
pos container_pos container_ty_name value_pos value_ty_name =
let reasons =
lazy
[
(container_pos, "This container is " ^ container_ty_name);
(value_pos, String.capitalize value_ty_name ^ " is not an arraykey");
]
and claim = lazy (pos, "Set values must be arraykeys") in
(Error_code.IndexTypeMismatch, claim, reasons, [])
let hkt_alias_with_implicit_constraints
pos
typedef_name
typedef_pos
used_class_in_def_pos
used_class_in_def_name
used_class_tparam_name
typedef_tparam_name =
let reasons =
lazy
[
( typedef_pos,
"The definition of " ^ Render.strip_ns typedef_name ^ " is here." );
( used_class_in_def_pos,
"The definition of "
^ Render.strip_ns typedef_name
^ " relies on "
^ Render.strip_ns used_class_in_def_name
^ " and the constraints that "
^ Render.strip_ns used_class_in_def_name
^ " imposes on its type parameter "
^ Render.strip_ns used_class_tparam_name
^ " then become implicit constraints on the type parameter "
^ typedef_tparam_name
^ " of "
^ Render.strip_ns typedef_name
^ "." );
]
and claim =
lazy
( pos,
Format.sprintf
"The type %s implicitly imposes constraints on its type parameters. Therefore, it cannot be used as a higher-kinded type at this time."
@@ Render.strip_ns typedef_name )
in
(Error_code.HigherKindedTypesUnsupportedFeature, claim, reasons, [])
let hkt_wildcard pos =
let claim =
lazy
( pos,
"You are supplying _ where a higher-kinded type is expected."
^ " We cannot infer higher-kinded type arguments at this time, please state the actual type."
)
in
(Error_code.HigherKindedTypesUnsupportedFeature, claim, lazy [], [])
let hkt_implicit_argument pos decl_pos param_name =
let param_desc =
(* This should be Naming_special_names.Typehints.wildcard, but its not available in this
module *)
if String.equal param_name "_" then
"the anonymous generic parameter"
else
"the generic parameter " ^ param_name
in
let claim =
lazy
( pos,
"You left out the type arguments here such that they may be inferred."
^ " However, a higher-kinded type is expected in place of "
^ param_desc
^ ", meaning that the type arguments cannot be inferred."
^ " Please provide the type arguments explicitly." )
and reasons =
lazy
[
( decl_pos,
Format.sprintf
{|%s was declared to be higher-kinded here.|}
param_desc );
]
in
(Error_code.HigherKindedTypesUnsupportedFeature, claim, reasons, [])
let invalid_substring pos ty_name =
let claim =
lazy
( pos,
"Expected an object convertible to string but got "
^ Lazy.force ty_name )
in
(Error_code.InvalidSubString, claim, lazy [], [])
let nullable_cast pos ty_pos ty_name =
let reasons =
Lazy.map ty_name ~f:(fun ty_name ->
[(ty_pos, "This is " ^ Markdown_lite.md_codify ty_name)])
and claim = lazy (pos, "Casting from a nullable type is forbidden") in
(Error_code.NullableCast, claim, reasons, [])
let hh_expect pos equivalent =
let (claim, error_code) =
if equivalent then
( lazy (pos, "hh_expect_equivalent type mismatch"),
Error_code.HHExpectEquivalentFailure )
else
(lazy (pos, "hh_expect type mismatch"), Error_code.HHExpectFailure)
in
(error_code, claim, lazy [], [])
let null_member pos ~obj_pos_opt ctxt kind member_name reason =
let claim =
lazy
( pos,
Printf.sprintf
"You are trying to access the %s %s but this object can be null."
(match kind with
| `method_ -> "method"
| `property -> "property")
(Markdown_lite.md_codify member_name) )
in
let error_code =
match ctxt with
| `read -> Error_code.NullMemberRead
| `write -> Error_code.NullMemberWrite
in
let quickfixes =
match obj_pos_opt with
| Some obj_pos ->
let (obj_pos_start_line, _) = Pos.line_column obj_pos in
(* let (obj_pos_end_line, obj_pos_end_column) = Pos.end_line_column obj_pos in *)
let (rhs_pos_start_line, rhs_pos_start_column) = Pos.line_column pos in
(*
heuristic: if the lhs and rhs of the Objget are on the same line, then we assume they are
separated by two characters (`->`). So we do not generate a quickfix for chained Objgets:
```
obj
->rhs
```
*)
if obj_pos_start_line = rhs_pos_start_line then
let width = 2 (* length of "->" *) in
let quickfix_pos =
pos
|> Pos.set_col_start (rhs_pos_start_column - width)
|> Pos.set_col_end rhs_pos_start_column
in
[
Quickfix.make ~title:"Add null-safe get" ~new_text:"?->" quickfix_pos;
]
else
[]
| None -> []
in
(error_code, claim, reason, quickfixes)
let typing_too_many_args pos decl_pos actual expected =
let (code, claim, reasons) =
Common.typing_too_many_args pos decl_pos actual expected
in
(code, claim, reasons, [])
let typing_too_few_args pos decl_pos actual expected =
let (code, claim, reasons) =
Common.typing_too_few_args pos decl_pos actual expected
in
(code, claim, reasons, [])
let non_object_member pos ctxt ty_name member_name kind decl_pos =
let (code, claim, reasons) =
Common.non_object_member
pos
ctxt
(Lazy.force ty_name)
member_name
kind
decl_pos
in
(code, claim, reasons, [])
let static_instance_intersection
class_pos instance_pos static_pos member_name kind =
let claim =
lazy
( class_pos,
"This class overrides some members with a different staticness" )
in
( Error_code.StaticDynamic,
claim,
lazy
[
( Lazy.force instance_pos,
"The "
^ (match kind with
| `meth -> "method"
| `prop -> "property")
^ " "
^ Markdown_lite.md_codify member_name
^ " is declared as non-static here" );
( Lazy.force static_pos,
"But it conflicts with an inherited static declaration here" );
],
[] )
let nullsafe_property_write_context pos =
let claim =
lazy
( pos,
"`?->` syntax not supported here, this function effectively does a write"
)
in
(Error_code.NullsafePropertyWriteContext, claim, lazy [], [])
let uninstantiable_class pos class_name reason_ty_opt decl_pos =
let default_claim =
lazy
( pos,
Markdown_lite.md_codify (Render.strip_ns class_name)
^ " is uninstantiable" )
and default_reasons = lazy [(decl_pos, "Declaration is here")] in
let (claim, reasons) =
match reason_ty_opt with
| Some (reason_pos, ty_name) ->
let claim =
Lazy.map ty_name ~f:(fun ty_name ->
( reason_pos,
"This would be " ^ ty_name ^ " which must be instantiable" ))
and reasons =
Lazy.(
default_claim >>= fun claim ->
default_reasons >>= fun reasons ->
return (Message.map ~f:Pos_or_decl.of_raw_pos claim :: reasons))
in
(claim, reasons)
| _ -> (default_claim, default_reasons)
in
(Error_code.UninstantiableClass, claim, reasons, [])
let abstract_const_usage pos name decl_pos =
let claim =
lazy
( pos,
"Cannot reference abstract constant "
^ Markdown_lite.md_codify (Render.strip_ns name)
^ " directly" )
and reason = lazy [(decl_pos, "Declaration is here")] in
(Error_code.AbstractConstUsage, claim, reason, [])
let type_arity_mismatch pos decl_pos actual expected =
let claim =
lazy
( pos,
Printf.sprintf
"Wrong number of type arguments (expected %d, got %d)"
expected
actual )
and reasons = lazy [(decl_pos, "Definition is here")] in
(Error_code.TypeArityMismatch, claim, reasons, [])
let member_not_implemented parent_pos member_name decl_pos quickfixes =
let claim = lazy (parent_pos, "This interface is not properly implemented")
and reasons =
lazy
[
( decl_pos,
Printf.sprintf
"Method %s does not have an implementation"
(Markdown_lite.md_codify member_name) );
]
in
(Error_code.MemberNotImplemented, claim, reasons, quickfixes)
let kind_mismatch pos decl_pos tparam_name expected_kind actual_kind =
let claim =
lazy
( pos,
"This is "
^ actual_kind
^ ", but "
^ expected_kind
^ " was expected here." )
and reason =
lazy
[
( decl_pos,
"We are expecting "
^ expected_kind
^ " due to the definition of "
^ tparam_name
^ " here." );
]
in
(Error_code.KindMismatch, claim, reason, [])
let trait_parent_construct_inconsistent pos decl_pos =
let claim =
lazy
( pos,
"This use of `parent::__construct` requires that the parent class be marked <<__ConsistentConstruct>>"
)
and reason = lazy [(decl_pos, "Parent definition is here")] in
(Error_code.TraitParentConstructInconsistent, claim, reason, [])
let top_member pos ctxt ty_name decl_pos kind name is_nullable ty_reasons =
let claim =
Lazy.map ty_name ~f:(fun ty_name ->
let kind_str =
match kind with
| `method_ -> "method"
| `property -> "property"
in
( pos,
Printf.sprintf
"You are trying to access the %s %s but this is %s. Use a **specific** class or interface name."
kind_str
(Markdown_lite.md_codify name)
ty_name ))
and reason =
lazy
begin
let reasons = Lazy.force ty_reasons in
if List.length reasons = 0 then
[(decl_pos, "Definition is here")]
else
reasons
end
and code =
Error_code.(
match ctxt with
| `read when is_nullable -> NullMemberRead
| `write when is_nullable -> NullMemberWrite
| `read -> NonObjectMemberRead
| `write -> NonObjectMemberWrite)
in
(code, claim, reason, [])
let unresolved_tyvar_projection pos proj_pos tconst_name =
let claim =
lazy
( pos,
"Can't access a type constant "
^ tconst_name
^ " from an unresolved type" )
and reason =
lazy
[
(proj_pos, "Access happens here");
( Pos_or_decl.of_raw_pos pos,
"Disambiguate the types using explicit type annotations here." );
]
in
(Error_code.UnresolvedTypeVariableProjection, claim, reason, [])
let cyclic_class_constant pos class_name const_name =
let claim =
lazy
( pos,
"Cannot declare self-referencing constant "
^ const_name
^ " in "
^ Render.strip_ns class_name )
in
(Error_code.CyclicClassConstant, claim, lazy [], [])
let inout_annotation_missing pos1 pos2 =
let claim = lazy (pos1, "This argument should be annotated with `inout`") in
let reason = lazy [(pos2, "Because this is an `inout` parameter")] in
let pos = Pos.shrink_to_start pos1 in
( Error_code.InoutAnnotationMissing,
claim,
reason,
[Quickfix.make ~title:"Insert `inout` annotation" ~new_text:"inout " pos]
)
let inout_annotation_unexpected pos1 pos2 pos2_is_variadic pos3 =
let claim = lazy (pos1, "Unexpected `inout` annotation for argument") in
let reason =
lazy
[
( pos2,
if pos2_is_variadic then
"A variadic parameter can never be `inout`"
else
"This is a normal parameter (does not have `inout`)" );
]
in
( Error_code.InoutAnnotationUnexpected,
claim,
reason,
[Quickfix.make ~title:"Remove `inout` annotation" ~new_text:"" pos3] )
let inout_argument_bad_type pos reasons =
let claim =
lazy
( pos,
"Expected argument marked `inout` to be contained in a local or "
^ "a value-typed container (e.g. vec, dict, keyset, array). "
^ "To use `inout` here, assign to/from a temporary local variable." )
in
(Error_code.InoutArgumentBadType, claim, reasons, [])
let invalid_meth_caller_calling_convention pos decl_pos convention =
let claim =
lazy
( pos,
"`meth_caller` does not support methods with the "
^ convention
^ " calling convention" )
and reason =
lazy
[
( decl_pos,
"This is why I think this method uses the `inout` calling convention"
);
]
in
(Error_code.InvalidMethCallerCallingConvention, claim, reason, [])
let invalid_meth_caller_readonly_return pos decl_pos =
let claim =
lazy
( pos,
"`meth_caller` does not support methods that return `readonly` objects"
)
in
let reason =
lazy
[
( decl_pos,
"This is why I think this method returns a `readonly` object" );
]
in
(Error_code.InvalidMethCallerReadonlyReturn, claim, reason, [])
let invalid_new_disposable pos =
let claim =
lazy
( pos,
"Disposable objects may only be created in a `using` statement or `return` from function marked `<<__ReturnDisposable>>`"
)
in
(Error_code.InvalidNewDisposable, claim, lazy [], [])
let invalid_return_disposable pos =
let claim =
lazy
( pos,
"Return expression must be new disposable in function marked `<<__ReturnDisposable>>`"
)
in
(Error_code.InvalidReturnDisposable, claim, lazy [], [])
let invalid_disposable_hint pos class_name =
let claim =
lazy
( pos,
"Parameter with type "
^ Markdown_lite.md_codify class_name
^ " must not implement `IDisposable` or `IAsyncDisposable`. "
^ "Please use `<<__AcceptDisposable>>` attribute or create disposable object with `using` statement instead."
)
in
(Error_code.InvalidDisposableHint, claim, lazy [], [])
let invalid_disposable_return_hint pos class_name =
let claim =
lazy
( pos,
"Return type "
^ Markdown_lite.md_codify class_name
^ " must not implement `IDisposable` or `IAsyncDisposable`. Please add `<<__ReturnDisposable>>` attribute."
)
in
(Error_code.InvalidDisposableReturnHint, claim, lazy [], [])
let ambiguous_lambda pos uses =
let claim =
lazy
( pos,
"Lambda has parameter types that could not be determined at definition site."
)
and reason =
Lazy.map uses ~f:(fun uses ->
( Pos_or_decl.of_raw_pos pos,
Printf.sprintf
"%d distinct use types were determined: please add type hints to lambda parameters."
(List.length uses) )
:: List.map uses ~f:(fun (pos, ty) ->
(pos, "This use has type " ^ Markdown_lite.md_codify ty)))
in
(Error_code.AmbiguousLambda, claim, reason, [])
let smember_not_found
pos kind member_name class_name class_pos hint quickfixes =
let (code, claim, reasons) =
Common.smember_not_found pos kind member_name class_name class_pos hint
in
(code, claim, reasons, quickfixes)
let wrong_extend_kind pos kind name parent_pos parent_kind parent_name =
let reason =
lazy
(let parent_kind_str = Ast_defs.string_of_classish_kind parent_kind in
[(parent_pos, "This is " ^ parent_kind_str ^ ".")])
in
let claim =
lazy
(let parent_name = Render.strip_ns parent_name in
let child_name = Render.strip_ns name in
let use_msg =
Printf.sprintf
" Did you mean to add `use %s;` within the body of %s?"
parent_name
(Markdown_lite.md_codify child_name)
in
let child_msg =
match kind with
| Ast_defs.Cclass _ ->
let extends_msg = "Classes can only extend other classes." in
let suggestion =
if Ast_defs.is_c_interface parent_kind then
" Did you mean `implements " ^ parent_name ^ "`?"
else if Ast_defs.is_c_trait parent_kind then
use_msg
else
""
in
extends_msg ^ suggestion
| Ast_defs.Cinterface ->
let extends_msg = "Interfaces can only extend other interfaces." in
let suggestion =
if Ast_defs.is_c_trait parent_kind then
use_msg
else
""
in
extends_msg ^ suggestion
| Ast_defs.Cenum_class _ ->
"Enum classes can only extend other enum classes."
| Ast_defs.Cenum ->
(* This case should never happen, as the type checker will have already caught
it with EnumTypeBad. But just in case, report this error here too. *)
"Enums can only extend int, string, or arraykey."
| Ast_defs.Ctrait ->
(* This case should never happen, as the parser will have caught it before
we get here. *)
"A trait cannot use `extends`. This is a parser error."
in
(pos, child_msg))
in
(Error_code.WrongExtendKind, claim, reason, [])
let cyclic_class_def pos stack =
let claim =
lazy
(let stack =
SSet.fold
(fun x y ->
(Render.strip_ns x |> Markdown_lite.md_codify) ^ " " ^ y)
stack
""
in
(pos, "Cyclic class definition : " ^ stack))
in
(Error_code.CyclicClassDef, claim, lazy [], [])
let trait_reuse_with_final_method use_pos trait_name parent_cls_name trace =
let claim =
lazy
( use_pos,
Printf.sprintf
"Traits with final methods cannot be reused, and `%s` is already used by `%s`."
(Render.strip_ns trait_name)
(Render.strip_ns parent_cls_name) )
in
(Error_code.TraitReuse, claim, trace, [])
let trait_reuse_inside_class c_pos c_name trait occurrences =
let claim =
lazy
(let c_name = Render.strip_ns c_name |> Markdown_lite.md_codify in
let trait = Render.strip_ns trait |> Markdown_lite.md_codify in
let err =
"Class " ^ c_name ^ " uses trait " ^ trait ^ " multiple times"
in
(c_pos, err))
in
( Error_code.TraitReuseInsideClass,
claim,
lazy (List.map ~f:(fun p -> (p, "used here")) occurrences),
[] )
let invalid_is_as_expression_hint hint_pos op reasons =
let op =
match op with
| `is -> "is"
| `as_ -> "as"
in
let claim =
lazy
(hint_pos, "Invalid " ^ Markdown_lite.md_codify op ^ " expression hint")
and reasons =
Lazy.map reasons ~f:(fun reasons ->
List.map reasons ~f:(fun (ty_pos, ty_str) ->
( ty_pos,
"The "
^ Markdown_lite.md_codify op
^ " operator cannot be used with "
^ ty_str )))
in
(Error_code.InvalidIsAsExpressionHint, claim, reasons, [])
let invalid_enforceable_type targ_pos ty_info kind tp_pos tp_name =
let reason =
Lazy.map ty_info ~f:(fun ty_info ->
let kind_str =
match kind with
| `constant -> "constant"
| `param -> "parameter"
in
let (ty_pos, ty_str) = List.hd_exn ty_info in
[
( tp_pos,
"Type "
^ kind_str
^ " "
^ Markdown_lite.md_codify tp_name
^ " was declared `__Enforceable` here" );
(ty_pos, "This type is not enforceable because it has " ^ ty_str);
])
in
( Error_code.InvalidEnforceableTypeArgument,
lazy (targ_pos, "Invalid type"),
reason,
[] )
let reifiable_attr attr_pos kind decl_pos ty_info =
let claim =
lazy
(let decl_kind =
match kind with
| `ty -> "type"
| `cnstr -> "constraint"
| `super_cnstr -> "super_constraint"
in
(decl_pos, "Invalid " ^ decl_kind))
in
let reason =
Lazy.map ty_info ~f:(fun ty_info ->
let (ty_pos, ty_msg) = List.hd_exn ty_info in
[
(attr_pos, "This type constant has the `__Reifiable` attribute");
(ty_pos, "It cannot contain " ^ ty_msg);
])
in
(Error_code.DisallowPHPArraysAttr, claim, reason, [])
let invalid_newable_type_argument pos tp_pos tp_name =
( Error_code.InvalidNewableTypeArgument,
lazy
( pos,
"A newable type argument must be a concrete class or a newable type parameter."
),
lazy
[
( tp_pos,
"Type parameter "
^ Markdown_lite.md_codify tp_name
^ " was declared `__Newable` here" );
],
[] )
let invalid_newable_type_param_constraints
(tparam_pos, tparam_name) constraint_list =
let claim =
lazy
(let partial =
if List.is_empty constraint_list then
"No constraints"
else
"The constraints "
^ String.concat
~sep:", "
(List.map ~f:Render.strip_ns constraint_list)
in
let msg =
"The type parameter "
^ Markdown_lite.md_codify tparam_name
^ " has the `<<__Newable>>` attribute. "
^ "Newable type parameters must be constrained with `as`, and exactly one of those constraints must be a valid newable class. "
^ "The class must either be final, or it must have the `<<__ConsistentConstruct>>` attribute or extend a class that has it. "
^ partial
^ " are valid newable classes"
in
(tparam_pos, msg))
in
(Error_code.InvalidNewableTypeParamConstraints, claim, lazy [], [])
let override_per_trait class_name meth_name trait_name m_pos =
let claim =
lazy
(let (c_pos, c_name) = class_name in
let err_msg =
Printf.sprintf
"`%s::%s` is marked `__Override` but `%s` does not define or inherit a `%s` method."
(Render.strip_ns trait_name)
meth_name
(Render.strip_ns c_name)
meth_name
in
(c_pos, err_msg))
in
( Error_code.OverridePerTrait,
claim,
lazy
[
( m_pos,
"Declaration of " ^ Markdown_lite.md_codify meth_name ^ " is here"
);
],
[] )
let should_not_be_override pos class_id id =
( Error_code.ShouldNotBeOverride,
lazy
( pos,
Printf.sprintf
"%s has no parent class with a method %s to override"
(Render.strip_ns class_id |> Markdown_lite.md_codify)
(Markdown_lite.md_codify id) ),
lazy [],
[] )
let typedef_trail_entry pos = (pos, "Typedef definition comes from here")
let trivial_strict_eq p b left right left_trail right_trail =
let claim =
lazy
(let b =
Markdown_lite.md_codify
(if b then
"true"
else
"false")
in
let msg = sprintf "This expression is always %s" b in
(p, msg))
and reason =
Lazy.(
left >>= fun left ->
right >>= fun right ->
let left_trail = List.map left_trail ~f:typedef_trail_entry in
let right_trail = List.map right_trail ~f:typedef_trail_entry in
return (left @ left_trail @ right @ right_trail))
in
(Error_code.TrivialStrictEq, claim, reason, [])
let trivial_strict_not_nullable_compare_null p result type_reason =
let claim =
lazy
(let b =
Markdown_lite.md_codify
(if result then
"true"
else
"false")
in
let msg = sprintf "This expression is always %s" b in
(p, msg))
in
(Error_code.NotNullableCompareNullTrivial, claim, type_reason, [])
let eq_incompatible_types p left right =
let claim = lazy (p, "This equality test has incompatible types")
and reason = lazy (left @ right) in
(Error_code.EqIncompatibleTypes, claim, reason, [])
let comparison_invalid_types p left right =
let claim =
lazy
( p,
"This comparison has invalid types. Only comparisons in which both arguments are strings, nums, DateTime, or DateTimeImmutable are allowed"
)
and reason = lazy (left @ right) in
(Error_code.ComparisonInvalidTypes, claim, reason, [])
let strict_eq_value_incompatible_types p left right =
let claim =
lazy
( p,
"The arguments to this value equality test are not the same types or are not the allowed types (int, bool, float, string, vec, keyset, dict). The behavior for this test is changing and will soon either be universally false or throw an exception."
)
and reason = lazy (left @ right) in
(Error_code.StrictEqValueIncompatibleTypes, claim, reason, [])
let deprecated_use pos ?(pos_def = None) msg =
let reason =
lazy
(match pos_def with
| Some pos_def -> [(pos_def, "Definition is here")]
| None -> [])
in
(Error_code.DeprecatedUse, lazy (pos, msg), reason, [])
let cannot_declare_constant pos (class_pos, class_name) =
( Error_code.CannotDeclareConstant,
lazy (pos, "Cannot declare a constant in an enum"),
lazy
[
( Pos_or_decl.of_raw_pos class_pos,
(Render.strip_ns class_name |> Markdown_lite.md_codify)
^ " was defined as an enum here" );
],
[] )
let invalid_classname p =
( Error_code.InvalidClassname,
lazy (p, "Not a valid class name"),
lazy [],
[] )
let illegal_type_structure pos msg =
let claim =
lazy
(let msg =
"The two arguments to `type_structure()` must be:"
^ "\n - first: `ValidClassname::class` or an object of that class"
^ "\n - second: a single-quoted string literal containing the name"
^ " of a type constant of that class\n"
^ msg
in
(pos, msg))
in
(Error_code.IllegalTypeStructure, claim, lazy [], [])
let illegal_typeconst_direct_access pos =
let claim =
lazy
(let msg =
"Type constants cannot be directly accessed. "
^ "Use `type_structure(ValidClassname::class, 'TypeConstName')` instead"
in
(pos, msg))
in
(Error_code.IllegalTypeStructure, claim, lazy [], [])
let wrong_expression_kind_attribute
expr_kind pos attr attr_class_pos attr_class_name intf_name =
let claim =
lazy
( pos,
Printf.sprintf
"The %s attribute cannot be used on %s."
(Render.strip_ns attr |> Markdown_lite.md_codify)
expr_kind )
in
let reason =
lazy
[
( attr_class_pos,
Printf.sprintf
"The attribute's class is defined here. To be available for use on %s, the %s class must implement %s."
expr_kind
(Render.strip_ns attr_class_name |> Markdown_lite.md_codify)
(Render.strip_ns intf_name |> Markdown_lite.md_codify) );
]
in
(Error_code.WrongExpressionKindAttribute, claim, reason, [])
let ambiguous_object_access
pos name self_pos vis subclass_pos class_self class_subclass =
let reason =
lazy
(let class_self = Render.strip_ns class_self in
let class_subclass = Render.strip_ns class_subclass in
[
( self_pos,
"You will access the private instance declared in "
^ Markdown_lite.md_codify class_self );
( subclass_pos,
"Instead of the "
^ vis
^ " instance declared in "
^ Markdown_lite.md_codify class_subclass );
])
in
( Error_code.AmbiguousObjectAccess,
lazy
( pos,
"This object access to "
^ Markdown_lite.md_codify name
^ " is ambiguous" ),
reason,
[] )
let unserializable_type pos message =
( Error_code.UnserializableType,
lazy
( pos,
"Unserializable type (could not be converted to JSON and back again): "
^ message ),
lazy [],
[] )
let invalid_arraykey_constraint pos t =
( Error_code.InvalidArrayKeyConstraint,
lazy
( pos,
"This type is "
^ t
^ ", which cannot be used as an arraykey (string | int)" ),
lazy [],
[] )
let redundant_covariant pos msg suggest =
( Error_code.RedundantGeneric,
lazy
( pos,
"This generic parameter is redundant because it only appears in a covariant (output) position"
^ msg
^ ". Consider replacing uses of generic parameter with "
^ Markdown_lite.md_codify suggest
^ " or specifying `<<__Explicit>>` on the generic parameter" ),
lazy [],
[] )
let meth_caller_trait pos trait_name =
( Error_code.MethCallerTrait,
lazy
( pos,
(Render.strip_ns trait_name |> Markdown_lite.md_codify)
^ " is a trait which cannot be used with `meth_caller`. Use a class instead."
),
lazy [],
[] )
let duplicate_interface pos name others =
( Error_code.DuplicateInterface,
lazy
( pos,
Printf.sprintf
"Interface %s is used more than once in this declaration."
(Render.strip_ns name |> Markdown_lite.md_codify) ),
lazy (List.map others ~f:(fun pos -> (pos, "Here is another occurrence"))),
[] )
let reified_function_reference call_pos =
( Error_code.ReifiedFunctionReference,
lazy
( call_pos,
"Invalid function reference. This function requires reified generics. Prefer using a lambda instead."
),
lazy [],
[] )
let class_meth_abstract_call cname meth_name call_pos decl_pos =
let cname = Render.strip_ns cname in
( Error_code.ClassMethAbstractCall,
lazy
( call_pos,
"Cannot create a class_meth of "
^ cname
^ "::"
^ meth_name
^ "; it is abstract." ),
lazy [(decl_pos, "Declaration is here")],
[] )
let reinheriting_classish_const
dest_classish_pos
dest_classish_name
src_classish_pos
src_classish_name
existing_const_origin
const_name =
( Error_code.RedeclaringClassishConstant,
lazy
( src_classish_pos,
Render.strip_ns dest_classish_name
^ " cannot re-inherit constant "
^ const_name
^ " from "
^ Render.strip_ns src_classish_name ),
lazy
[
( Pos_or_decl.of_raw_pos dest_classish_pos,
"because it already inherited it via "
^ Render.strip_ns existing_const_origin );
],
[] )
let redeclaring_classish_const
classish_pos
classish_name
redeclaration_pos
existing_const_origin
const_name =
( Error_code.RedeclaringClassishConstant,
lazy
( redeclaration_pos,
Render.strip_ns classish_name
^ " cannot re-declare constant "
^ const_name ),
lazy
[
( Pos_or_decl.of_raw_pos classish_pos,
"because it already inherited it via "
^ Render.strip_ns existing_const_origin );
],
[] )
let abstract_function_pointer cname meth_name call_pos decl_pos =
( Error_code.AbstractFunctionPointer,
lazy
( call_pos,
"Cannot create a function pointer to "
^ Markdown_lite.md_codify (Render.strip_ns cname ^ "::" ^ meth_name)
^ "; it is abstract" ),
lazy [(decl_pos, "Declaration is here")],
[] )
let inherited_class_member_with_different_case
member_type name name_prev p child_class prev_class prev_class_pos =
let name = Render.strip_ns name in
let name_prev = Render.strip_ns name_prev in
let claim =
lazy
(let child_class = Render.strip_ns child_class in
( p,
child_class
^ " inherits a "
^ member_type
^ " named "
^ Markdown_lite.md_codify name_prev
^ " whose name differs from this one ("
^ Markdown_lite.md_codify name
^ ") only by case." ))
in
let reasons =
lazy
(let prev_class = Render.strip_ns prev_class in
[
( prev_class_pos,
"It was inherited from "
^ prev_class
^ " as "
^ (Render.highlight_differences name name_prev
|> Markdown_lite.md_codify)
^ ". If you meant to override it, please use the same casing as the inherited "
^ member_type
^ "."
^ " Otherwise, please choose a different name for the new "
^ member_type );
])
in
(Error_code.InheritedMethodCaseDiffers, claim, reasons, [])
let multiple_inherited_class_member_with_different_case
~member_type ~name1 ~name2 ~class1 ~class2 ~child_class ~child_p ~p1 ~p2 =
let name1 = Render.strip_ns name1 in
let name2 = Render.strip_ns name2 in
let class1 = Render.strip_ns class1 in
let class2 = Render.strip_ns class2 in
let claim =
lazy
(let child_class = Render.strip_ns child_class in
( child_p,
Markdown_lite.md_codify child_class
^ " inherited two versions of the "
^ member_type
^ " "
^ Markdown_lite.md_codify name1
^ " whose names differ only by case." ))
in
let reasons =
lazy
[
( p1,
"It inherited "
^ Markdown_lite.md_codify name1
^ " from "
^ class1
^ " here." );
( p2,
"And "
^ Markdown_lite.md_codify name2
^ " from "
^ class2
^ " here. Please rename these "
^ member_type
^ "s to the same casing." );
]
in
(Error_code.InheritedMethodCaseDiffers, claim, reasons, [])
let classish_kind_to_string = function
| Ast_defs.Cclass _ -> "class "
| Ast_defs.Ctrait -> "trait "
| Ast_defs.Cinterface -> "interface "
| Ast_defs.Cenum_class _ -> "enum class "
| Ast_defs.Cenum -> "enum "
let parent_support_dynamic_type
pos
(child_name, child_kind)
(parent_name, parent_kind)
child_support_dynamic_type =
let claim =
lazy
(let kinds_to_use child_kind parent_kind =
match (child_kind, parent_kind) with
| (_, Ast_defs.Cclass _) -> "extends "
| (_, Ast_defs.Ctrait) -> "uses "
| (Ast_defs.Cinterface, Ast_defs.Cinterface) -> "extends "
| (_, Ast_defs.Cinterface) -> "implements "
| (_, Ast_defs.Cenum_class _)
| (_, Ast_defs.Cenum) ->
""
in
let child_name =
Markdown_lite.md_codify (Render.strip_ns child_name)
in
let child_kind_s = classish_kind_to_string child_kind in
let parent_name =
Markdown_lite.md_codify (Render.strip_ns parent_name)
in
let parent_kind_s = classish_kind_to_string parent_kind in
( pos,
String.capitalize child_kind_s
^ child_name
^ (if child_support_dynamic_type then
" cannot "
else
" must ")
^ "declare <<__SupportDynamicType>> because it "
^ kinds_to_use child_kind parent_kind
^ parent_kind_s
^ parent_name
^ " which does"
^
if child_support_dynamic_type then
" not"
else
"" ))
in
(Error_code.ImplementsDynamic, claim, lazy [], [])
let property_is_not_enforceable pos prop_name class_name (prop_pos, prop_type)
=
let prop_name = Markdown_lite.md_codify prop_name in
let claim =
lazy
(let class_name =
Markdown_lite.md_codify (Render.strip_ns class_name)
in
( pos,
"Class "
^ class_name
^ " cannot support dynamic because property "
^ prop_name
^ " does not have an enforceable type" ))
and reason =
lazy
(let prop_type = Markdown_lite.md_codify prop_type in
[(prop_pos, "Property " ^ prop_name ^ " has type " ^ prop_type)])
in
(Error_code.ImplementsDynamic, claim, reason, [])
let property_is_not_dynamic pos prop_name class_name (prop_pos, prop_type) =
let prop_name = Markdown_lite.md_codify prop_name in
let claim =
lazy
(let class_name =
Markdown_lite.md_codify (Render.strip_ns class_name)
in
( pos,
"Class "
^ class_name
^ " cannot support dynamic because property "
^ prop_name
^ " cannot be assigned to dynamic" ))
and reason =
lazy
(let prop_type = Markdown_lite.md_codify prop_type in
[(prop_pos, "Property " ^ prop_name ^ " has type " ^ prop_type)])
in
(Error_code.ImplementsDynamic, claim, reason, [])
let private_property_is_not_enforceable
pos prop_name class_name (prop_pos, prop_type) =
let prop_name = Markdown_lite.md_codify prop_name in
let claim =
lazy
(let class_name =
Markdown_lite.md_codify (Render.strip_ns class_name)
in
( pos,
"Cannot write to property "
^ prop_name
^ " through dynamic type because private property in "
^ class_name
^ " does not have an enforceable type" ))
and reason =
lazy
(let prop_type = Markdown_lite.md_codify prop_type in
[(prop_pos, "Property " ^ prop_name ^ " has type " ^ prop_type)])
in
(Error_code.PrivateDynamicWrite, claim, reason, [])
let private_property_is_not_dynamic
pos prop_name class_name (prop_pos, prop_type) =
let prop_name = Markdown_lite.md_codify prop_name in
let claim =
lazy
(let class_name =
Markdown_lite.md_codify (Render.strip_ns class_name)
in
( pos,
"Cannot read from property "
^ prop_name
^ " through dynamic type because private property in "
^ class_name
^ " cannot be assigned to dynamic" ))
and reason =
lazy
(let prop_type = Markdown_lite.md_codify prop_type in
[(prop_pos, "Property " ^ prop_name ^ " has type " ^ prop_type)])
in
(Error_code.PrivateDynamicRead, claim, reason, [])
let immutable_local pos =
( Error_code.ImmutableLocal,
lazy
( pos,
(* TODO: generalize this error message in the future for arbitrary immutable locals *)
"This variable cannot be reassigned because it is used for a dependent context"
),
lazy [],
[] )
let nonsense_member_selection pos kind =
( Error_code.NonsenseMemberSelection,
lazy
( pos,
"Dynamic member access requires a local variable, not `" ^ kind ^ "`."
),
lazy [],
[] )
let consider_meth_caller pos class_name meth_name =
( Error_code.ConsiderMethCaller,
lazy
( pos,
"Function pointer syntax requires a static method. "
^ "Use `meth_caller("
^ Render.strip_ns class_name
^ "::class, '"
^ meth_name
^ "')` to create a function pointer to the instance method" ),
lazy [],
[] )
let method_import_via_diamond
pos class_name method_pos method_name trace1 trace2 =
let claim =
lazy
(let class_name =
Markdown_lite.md_codify (Render.strip_ns class_name)
in
let method_name =
Markdown_lite.md_codify (Render.strip_ns method_name)
in
( pos,
"Class "
^ class_name
^ " inherits trait method "
^ method_name
^ " via multiple traits. Remove the multiple paths or override the method"
))
in
let reason =
Lazy.(
trace1 >>= fun trace1 ->
trace2 >>= fun trace2 ->
return
(((method_pos, "Trait method is defined here") :: trace1) @ trace2))
in
(Error_code.DiamondTraitMethod, claim, reason, [])
let property_import_via_diamond
generic pos class_name property_pos property_name trace1 trace2 =
let claim =
lazy
(let class_name =
Markdown_lite.md_codify (Render.strip_ns class_name)
in
let property_name =
Markdown_lite.md_codify (Render.strip_ns property_name)
in
( pos,
"Class "
^ class_name
^ " inherits "
^ (if generic then
"generic "
else
"")
^ "trait property "
^ property_name
^ " via multiple paths"
^ (if generic then
" at different types."
else
".")
^
if not generic then
" Currently, traits with properties are not supported by "
^ "the <<__EnableMethodTraitDiamond>> experimental feature."
else
"" ))
in
let reason =
Lazy.(
trace1 >>= fun trace1 ->
trace2 >>= fun trace2 ->
return
(((property_pos, "Trait property is defined here") :: trace1) @ trace2))
in
(Error_code.DiamondTraitProperty, claim, reason, [])
let unification_cycle pos ty =
( Error_code.UnificationCycle,
lazy
( pos,
"Type circularity: in order to type-check this expression it "
^ "is necessary for a type [rec] to be equal to type "
^ Markdown_lite.md_codify ty ),
lazy [],
[] )
let method_variance pos =
( Error_code.MethodVariance,
lazy
( pos,
"Covariance or contravariance is not allowed in type parameters of methods or functions."
),
lazy [],
[] )
let explain_tconst_where_constraint use_pos definition_pos msgl =
let claim = lazy (use_pos, "A `where` type constraint is violated here")
and reason =
Lazy.map msgl ~f:(fun msgl ->
( definition_pos,
"This method's `where` constraints contain a generic type access" )
:: msgl)
in
(Error_code.TypeConstraintViolation, claim, reason, [])
let format_string pos snippet s class_pos fname class_suggest =
( Error_code.FormatString,
lazy
( pos,
"Invalid format string "
^ Markdown_lite.md_codify snippet
^ " in "
^ Markdown_lite.md_codify ("\"" ^ s ^ "\"") ),
lazy
[
( class_pos,
"You can add a new format specifier by adding "
^ Markdown_lite.md_codify (fname ^ "()")
^ " to "
^ Markdown_lite.md_codify class_suggest );
],
[] )
let expected_literal_format_string pos =
( Error_code.ExpectedLiteralFormatString,
lazy (pos, "This argument must be a literal format string"),
lazy [],
[] )
let re_prefixed_non_string pos reason =
let claim =
lazy
(let non_strings =
match reason with
| `embedded_expr -> "Strings with embedded expressions"
| `non_string -> "Non-strings"
in
(pos, non_strings ^ " are not allowed to be to be `re`-prefixed"))
in
(Error_code.RePrefixedNonString, claim, lazy [], [])
let bad_regex_pattern pos reason =
let claim =
lazy
(let s =
match reason with
| `bad_patt s -> s
| `empty_patt -> "This pattern is empty"
| `missing_delim -> "Missing delimiter(s)"
| `invalid_option -> "Invalid global option(s)"
in
(pos, "Bad regex pattern; " ^ s ^ "."))
in
(Error_code.BadRegexPattern, claim, lazy [], [])
let generic_array_strict p =
( Error_code.GenericArrayStrict,
lazy (p, "You cannot have an array without generics in strict mode"),
lazy [],
[] )
let option_return_only_typehint p kind =
let claim =
lazy
(let (typehint, reason) =
match kind with
| `void -> ("?void", "only return implicitly")
| `noreturn -> ("?noreturn", "never return")
in
( p,
Markdown_lite.md_codify typehint
^ " is a nonsensical typehint; a function cannot both "
^ reason
^ " and return null." ))
in
(Error_code.OptionReturnOnlyTypehint, claim, lazy [], [])
let redeclaring_missing_method p trait_method =
( Error_code.RedeclaringMissingMethod,
lazy
( p,
"Attempting to redeclare a trait method "
^ Markdown_lite.md_codify trait_method
^ " which was never inherited. "
^ "You might be trying to redeclare a non-static method as `static` or vice-versa."
),
lazy [],
[] )
let expecting_type_hint p =
( Error_code.ExpectingTypeHint,
lazy (p, "Was expecting a type hint"),
lazy [],
[] )
let expecting_type_hint_variadic p =
( Error_code.ExpectingTypeHintVariadic,
lazy (p, "Was expecting a type hint on this variadic parameter"),
lazy [],
[] )
let expecting_return_type_hint p =
( Error_code.ExpectingReturnTypeHint,
lazy (p, "Was expecting a return type hint"),
lazy [],
[] )
let duplicate_using_var pos =
( Error_code.DuplicateUsingVar,
lazy (pos, "Local variable already used in `using` statement"),
lazy [],
[] )
let illegal_disposable pos verb =
let claim =
lazy
(let verb =
match verb with
| `assigned -> "assigned"
in
( pos,
"Disposable objects must only be " ^ verb ^ " in a `using` statement"
))
in
(Error_code.IllegalDisposable, claim, lazy [], [])
let escaping_disposable pos =
( Error_code.EscapingDisposable,
lazy
( pos,
"Variable from `using` clause may only be used as receiver in method invocation "
^ "or passed to function with `<<__AcceptDisposable>>` parameter attribute"
),
lazy [],
[] )
let escaping_disposable_parameter pos =
( Error_code.EscapingDisposableParameter,
lazy
( pos,
"Parameter with `<<__AcceptDisposable>>` attribute may only be used as receiver in method invocation "
^ "or passed to another function with `<<__AcceptDisposable>>` parameter attribute"
),
lazy [],
[] )
let escaping_this pos =
( Error_code.EscapingThis,
lazy
( pos,
"`$this` implementing `IDisposable` or `IAsyncDisposable` may only be used as receiver in method invocation "
^ "or passed to another function with `<<__AcceptDisposable>>` parameter attribute"
),
lazy [],
[] )
let must_extend_disposable pos =
( Error_code.MustExtendDisposable,
lazy
( pos,
"A disposable type may not extend a class or use a trait that is not disposable"
),
lazy [],
[] )
let field_kinds pos1 pos2 =
( Error_code.FieldKinds,
lazy (pos1, "You cannot use this kind of field (value)"),
lazy [(pos2, "Mixed with this kind of field (key => value)")],
[] )
let unbound_name_typing pos name class_exists =
let quickfixes =
match class_exists with
| true ->
let newpos = Pos.shrink_to_start pos in
[
Quickfix.make
~title:("Add " ^ Markdown_lite.md_codify "new")
~new_text:"new "
newpos;
]
| false -> []
in
( Error_code.UnboundNameTyping,
lazy
( pos,
"Unbound name (typing): "
^ Markdown_lite.md_codify (Render.strip_ns name) ),
lazy [],
quickfixes )
let previous_default p =
( Error_code.PreviousDefault,
lazy
( p,
"A previous parameter has a default value.\n"
^ "Remove all the default values for the preceding parameters,\n"
^ "or add a default value to this one." ),
lazy [],
[] )
let return_in_void pos1 pos2 =
( Error_code.ReturnInVoid,
lazy (pos1, "You cannot return a value"),
lazy [(Pos_or_decl.of_raw_pos pos2, "This is a `void` function")],
[] )
let this_var_outside_class p =
( Error_code.ThisVarOutsideClass,
lazy (p, "Can't use `$this` outside of a class"),
lazy [],
[] )
let unbound_global cst_pos =
( Error_code.UnboundGlobal,
lazy (cst_pos, "Unbound global constant (Typing)"),
lazy [],
[] )
let private_inst_meth use_pos def_pos =
( Error_code.PrivateInstMeth,
lazy
( use_pos,
"You cannot use this method with `inst_meth` (whether you are in the same class or not)."
),
lazy [(def_pos, "It is declared as `private` here")],
[] )
let protected_inst_meth use_pos def_pos =
( Error_code.ProtectedInstMeth,
lazy
( use_pos,
"You cannot use this method with `inst_meth` (whether you are in the same class hierarchy or not)."
),
lazy [(def_pos, "It is declared as `protected` here")],
[] )
let private_meth_caller use_pos def_pos =
( Error_code.PrivateMethCaller,
lazy
( use_pos,
"You cannot access this method with `meth_caller` (even from the same class hierarchy)"
),
lazy [(def_pos, "It is declared as `private` here")],
[] )
let protected_meth_caller use_pos def_pos =
( Error_code.ProtectedMethCaller,
lazy
( use_pos,
"You cannot access this method with `meth_caller` (even from the same class hierarchy)"
),
lazy [(def_pos, "It is declared as `protected` here")],
[] )
let private_class_meth use_pos def_pos =
( Error_code.PrivateClassMeth,
lazy
( use_pos,
"You cannot use this method with `class_meth` (whether you are in the same class or not)."
),
lazy [(def_pos, "It is declared as `private` here")],
[] )
let protected_class_meth use_pos def_pos =
( Error_code.ProtectedClassMeth,
lazy
( use_pos,
"You cannot use this method with `class_meth` (whether you are in the same class hierarchy or not)."
),
lazy [(def_pos, "It is declared as `protected` here")],
[] )
let array_cast pos =
( Error_code.ArrayCast,
lazy
( pos,
"(array) cast forbidden; arrays with unspecified key and value types are not allowed"
),
lazy [],
[] )
let string_cast pos ty =
( Error_code.StringCast,
lazy
( pos,
Printf.sprintf
"Cannot cast a value of type %s to string. Only primitives may be used in a `(string)` cast."
(Markdown_lite.md_codify ty) ),
lazy [],
[] )
let static_outside_class pos =
( Error_code.StaticOutsideClass,
lazy (pos, "`static` is undefined outside of a class"),
lazy [],
[] )
let self_outside_class pos =
( Error_code.SelfOutsideClass,
lazy (pos, "`self` is undefined outside of a class"),
lazy [],
[] )
let new_inconsistent_construct new_pos (cpos, cname) kind =
let claim =
lazy
(let name = Render.strip_ns cname in
let preamble =
match kind with
| `static ->
"Can't use `new static()` for " ^ Markdown_lite.md_codify name
| `classname ->
"Can't use `new` on "
^ Markdown_lite.md_codify ("classname<" ^ name ^ ">")
in
( new_pos,
preamble
^ "; `__construct` arguments are not guaranteed to be consistent in child classes"
))
in
( Error_code.NewStaticInconsistent,
claim,
lazy
[
( cpos,
"This declaration is neither `final` nor uses the `<<__ConsistentConstruct>>` attribute"
);
],
[] )
let undefined_parent pos =
( Error_code.UndefinedParent,
lazy (pos, "The parent class is undefined"),
lazy [],
[] )
let parent_outside_class pos =
( Error_code.ParentOutsideClass,
lazy (pos, "`parent` is undefined outside of a class"),
lazy [],
[] )
let parent_abstract_call call_pos meth_name decl_pos =
( Error_code.AbstractCall,
lazy
( call_pos,
"Cannot call "
^ Markdown_lite.md_codify ("parent::" ^ meth_name ^ "()")
^ "; it is abstract" ),
lazy [(decl_pos, "Declaration is here")],
[] )
let self_abstract_call call_pos meth_name self_pos decl_pos =
let quickfixes =
[
Quickfix.make
~title:
("Change to " ^ Markdown_lite.md_codify ("static::" ^ meth_name))
~new_text:"static"
self_pos;
]
in
( Error_code.AbstractCall,
lazy
( call_pos,
"Cannot call "
^ Markdown_lite.md_codify ("self::" ^ meth_name ^ "()")
^ "; it is abstract. Did you mean "
^ Markdown_lite.md_codify ("static::" ^ meth_name ^ "()")
^ "?" ),
lazy [(decl_pos, "Declaration is here")],
quickfixes )
let classname_abstract_call call_pos meth_name cname decl_pos =
( Error_code.AbstractCall,
lazy
( call_pos,
"Cannot call "
^ Markdown_lite.md_codify
(Render.strip_ns cname ^ "::" ^ meth_name ^ "()")
^ "; it is abstract" ),
lazy [(decl_pos, "Declaration is here")],
[] )
let static_synthetic_method call_pos meth_name cname decl_pos =
let cname = Render.strip_ns cname in
( Error_code.StaticSyntheticMethod,
lazy
( call_pos,
"Cannot call "
^ Markdown_lite.md_codify (cname ^ "::" ^ meth_name ^ "()")
^ "; "
^ Markdown_lite.md_codify meth_name
^ " is not defined in "
^ Markdown_lite.md_codify cname ),
lazy [(decl_pos, "Declaration is here")],
[] )
let isset_in_strict pos =
( Error_code.IssetEmptyInStrict,
lazy
( pos,
"`isset` tends to hide errors due to variable typos and so is limited to dynamic checks in "
^ "`strict` mode" ),
lazy [],
[] )
let isset_inout_arg pos =
( Error_code.InoutInPseudofunction,
lazy (pos, "`isset` does not allow arguments to be passed by `inout`"),
lazy [],
[] )
let unset_nonidx_in_strict pos msgs =
( Error_code.UnsetNonidxInStrict,
lazy
( pos,
"In `strict` mode, `unset` is banned except on dynamic, "
^ "darray, keyset, or dict indexing" ),
msgs,
[] )
let unpacking_disallowed_builtin_function pos name =
( Error_code.UnpackingDisallowed,
lazy
( pos,
"Arg unpacking is disallowed for "
^ Markdown_lite.md_codify (Render.strip_ns name) ),
lazy [],
[] )
let array_get_arity pos1 name pos2 =
( Error_code.ArrayGetArity,
lazy
( pos1,
"You cannot use this "
^ (Render.strip_ns name |> Markdown_lite.md_codify) ),
lazy [(pos2, "It is missing its type parameters")],
[] )
let undefined_field use_pos name shape_type_pos =
( Error_code.UndefinedField,
lazy
( use_pos,
"This shape doesn't have a field " ^ Markdown_lite.md_codify name ),
lazy [(shape_type_pos, "The shape is defined here")],
[] )
let array_access code pos1 pos2 ty =
( code,
lazy
(pos1, "This is not an object of type `KeyedContainer`, this is " ^ ty),
lazy
(if not Pos_or_decl.(equal pos2 none) then
[(pos2, "Definition is here")]
else
[]),
[] )
let array_access_read = array_access Error_code.ArrayAccessRead
let array_access_write = array_access Error_code.ArrayAccessWrite
let keyset_set pos1 pos2 =
( Error_code.KeysetSet,
lazy (pos1, "Elements in a keyset cannot be assigned, use append instead."),
lazy
(if not Pos_or_decl.(equal pos2 none) then
[(pos2, "Definition is here")]
else
[]),
[] )
let array_append pos1 pos2 ty =
( Error_code.ArrayAppend,
lazy (pos1, ty ^ " does not allow array append"),
lazy
(if not Pos_or_decl.(equal pos2 none) then
[(pos2, "Definition is here")]
else
[]),
[] )
let const_mutation pos1 pos2 ty =
( Error_code.ConstMutation,
lazy (pos1, "You cannot mutate this"),
lazy
(if not Pos_or_decl.(equal pos2 none) then
[(pos2, "This is " ^ ty)]
else
[]),
[] )
let expected_class pos suffix =
( Error_code.ExpectedClass,
lazy (pos, "Was expecting a class" ^ suffix),
lazy [],
[] )
let unknown_type pos description r =
let claim =
lazy (pos, "Was expecting " ^ description ^ " but type is unknown")
in
(Error_code.UnknownType, claim, r, [])
let parent_in_trait pos =
( Error_code.ParentInTrait,
lazy
( pos,
"You can only use `parent::` in traits that specify `require extends SomeClass`"
),
lazy [],
[] )
let parent_undefined pos =
(Error_code.ParentUndefined, lazy (pos, "parent is undefined"), lazy [], [])
let constructor_no_args pos =
( Error_code.ConstructorNoArgs,
lazy (pos, "This constructor expects no argument"),
lazy [],
[] )
let visibility p msg1 p_vis msg2 =
(Error_code.Visibility, lazy (p, msg1), lazy [(p_vis, msg2)], [])
let bad_call pos ty =
( Error_code.BadCall,
lazy (pos, "This call is invalid, this is not a function, it is " ^ ty),
lazy [],
[] )
let extend_final extend_pos decl_pos name =
( Error_code.ExtendFinal,
lazy
( extend_pos,
"You cannot extend final class "
^ Markdown_lite.md_codify (Render.strip_ns name) ),
lazy [(decl_pos, "Declaration is here")],
[] )
let extend_sealed child_pos parent_pos parent_name parent_kind verb =
let claim =
lazy
(let parent_kind =
match parent_kind with
| `intf -> "interface"
| `trait -> "trait"
| `class_ -> "class"
| `enum -> "enum"
| `enum_class -> "enum class"
and verb =
match verb with
| `extend -> "extend"
| `implement -> "implement"
| `use -> "use"
and name = Render.strip_ns parent_name in
( child_pos,
"You cannot "
^ verb
^ " sealed "
^ parent_kind
^ " "
^ Markdown_lite.md_codify name ))
in
( Error_code.ExtendSealed,
claim,
lazy [(parent_pos, "Declaration is here")],
[] )
let sealed_not_subtype parent_pos parent_name child_name child_kind child_pos
=
let claim =
lazy
(let parent_name = Render.strip_ns parent_name
and child_name = Render.strip_ns child_name
and (child_kind, verb) =
match child_kind with
| Ast_defs.Cclass _ -> ("Class", "extend")
| Ast_defs.Cinterface -> ("Interface", "implement")
| Ast_defs.Ctrait -> ("Trait", "use")
| Ast_defs.Cenum -> ("Enum", "use")
| Ast_defs.Cenum_class _ -> ("Enum Class", "extend")
in
( parent_pos,
child_kind
^ " "
^ Markdown_lite.md_codify child_name
^ " in sealed allowlist for "
^ Markdown_lite.md_codify parent_name
^ ", but does not "
^ verb
^ " "
^ Markdown_lite.md_codify parent_name ))
in
( Error_code.SealedNotSubtype,
claim,
lazy [(child_pos, "Definition is here")],
[] )
let trait_prop_const_class pos x =
( Error_code.TraitPropConstClass,
lazy
( pos,
"Trait declaration of non-const property "
^ Markdown_lite.md_codify x
^ " is incompatible with a const class" ),
lazy [],
[] )
let implement_abstract pos1 is_final pos2 x kind qfxs trace =
let kind =
match kind with
| `meth -> "method"
| `prop -> "property"
| `const -> "constant"
| `ty_const -> "type constant"
in
let claim =
lazy
(let name = "abstract " ^ kind ^ " " ^ Markdown_lite.md_codify x in
let msg1 =
if is_final then
"This class was declared as `final`. It must provide an implementation for the "
^ name
else
"This class must be declared `abstract`, or provide an implementation for the "
^ name
in
(pos1, msg1))
in
( Error_code.ImplementAbstract,
claim,
lazy
(Lazy.force trace
@ [(pos2, Printf.sprintf "The %s is defined here" kind)]),
qfxs )
let abstract_member_in_concrete_class
~member_pos ~class_name_pos ~is_final member_kind member_name =
let claim =
lazy
( member_pos,
Printf.sprintf
"%s `%s%s` is abstract but the class is %s. Either provide an implementation here."
(match member_kind with
| `method_ -> "Method"
| `property -> "Property"
| `constant -> "Constant"
| `type_constant -> "Type constant")
(match member_kind with
| `property -> "$"
| _ -> "")
member_name
(if is_final then
"final"
else
"concrete") )
in
let reasons =
lazy
[
( Pos_or_decl.of_raw_pos class_name_pos,
Printf.sprintf
"Or make the class abstract%s."
(if is_final then
" and not final"
else
"") );
]
in
(Error_code.AbstractMemberInConcreteClass, claim, reasons, [])
let generic_static pos x =
( Error_code.GenericStatic,
lazy
( pos,
"This static variable cannot use the type parameter "
^ Markdown_lite.md_codify x
^ "." ),
lazy [],
[] )
let ellipsis_strict_mode pos require =
let claim =
lazy
( pos,
match require with
| `Param_name ->
"Variadic function arguments require a name in strict mode, e.g. `...$args`."
| `Type_and_param_name ->
"Variadic function arguments require a name and type in strict mode, e.g. `int ...$args`."
)
in
(Error_code.EllipsisStrictMode, claim, lazy [], [])
let object_string pos1 pos2 =
( Error_code.ObjectString,
lazy (pos1, "You cannot use this object as a string"),
lazy [(pos2, "This object doesn't implement `__toString`")],
[] )
let object_string_deprecated pos =
( Error_code.ObjectString,
lazy
( pos,
"You cannot use this object as a string\nImplicit conversions of Stringish objects to string are deprecated."
),
lazy [],
[] )
let cyclic_typedef def_pos use_pos =
( Error_code.CyclicTypedef,
lazy (def_pos, "Cyclic type definition"),
lazy [(use_pos, "Cyclic use is here")],
[] )
let require_args_reify arg_pos def_pos =
( Error_code.RequireArgsReify,
lazy
( arg_pos,
"All type arguments must be specified because a type parameter is reified"
),
lazy [(def_pos, "Definition is here")],
[] )
let require_generic_explicit arg_pos def_pos def_name =
( Error_code.RequireGenericExplicit,
lazy
( arg_pos,
"Illegal wildcard (`_`): generic type parameter "
^ Markdown_lite.md_codify def_name
^ " must be specified explicitly" ),
lazy [(def_pos, "Definition is here")],
[] )
let invalid_reified_argument hint_pos def_name def_pos arg_info =
let reason =
Lazy.map arg_info ~f:(fun arg_info ->
let (arg_pos, arg_kind) = List.hd_exn arg_info in
[
( arg_pos,
"This is "
^ arg_kind
^ ", it cannot be used as a reified type argument" );
(def_pos, Markdown_lite.md_codify def_name ^ " is reified");
])
in
( Error_code.InvalidReifiedArgument,
lazy (hint_pos, "Invalid reified hint"),
reason,
[] )
let invalid_reified_argument_reifiable arg_pos def_name def_pos ty_pos ty_msg
=
( Error_code.InvalidReifiedArgument,
lazy (arg_pos, "PHP arrays cannot be used as a reified type argument"),
lazy
[
(ty_pos, String.capitalize ty_msg);
(def_pos, Markdown_lite.md_codify def_name ^ " is reified");
],
[] )
let new_class_reified pos class_type suggested_class =
let claim =
lazy
(let suggestion =
match suggested_class with
| Some s ->
let s = Render.strip_ns s in
sprintf ". Try `new %s` instead." s
| None -> ""
in
( pos,
sprintf
"Cannot call `new %s` because the current class has reified generics%s"
class_type
suggestion ))
in
(Error_code.NewClassReified, claim, lazy [], [])
let class_get_reified pos =
( Error_code.ClassGetReified,
lazy (pos, "Cannot access static properties on reified generics"),
lazy [],
[] )
let static_meth_with_class_reified_generic meth_pos generic_pos =
( Error_code.StaticMethWithClassReifiedGeneric,
lazy
( meth_pos,
"Static methods cannot use generics reified at the class level. Try reifying them at the static method itself."
),
lazy
[
( Pos_or_decl.of_raw_pos generic_pos,
"Class-level reified generic used here." );
],
[] )
let consistent_construct_reified pos =
( Error_code.ConsistentConstructReified,
lazy
( pos,
"This class or one of its ancestors is annotated with `<<__ConsistentConstruct>>`. It cannot have reified generics."
),
lazy [],
[] )
let bad_function_pointer_construction pos =
( Error_code.BadFunctionPointerConstruction,
lazy (pos, "Function pointers must be explicitly named"),
lazy [],
[] )
let reified_generics_not_allowed pos =
( Error_code.InvalidReifiedFunctionPointer,
lazy
( pos,
"Creating function pointers with reified generics is not currently allowed"
),
lazy [],
[] )
let new_without_newable pos name =
( Error_code.NewWithoutNewable,
lazy
( pos,
Markdown_lite.md_codify name
^ " cannot be used with `new` because it does not have the `<<__Newable>>` attribute"
),
lazy [],
[] )
let discarded_awaitable pos1 pos2 =
( Error_code.DiscardedAwaitable,
lazy
( pos1,
"This expression is of type `Awaitable`, but it's "
^ "either being discarded or used in a dangerous way before "
^ "being awaited" ),
lazy [(pos2, "This is why I think it is `Awaitable`")],
[] )
let elt_type_to_string = function
| `meth -> "method"
| `prop -> "property"
let unknown_object_member pos s elt r =
let claim =
lazy
(let elt = elt_type_to_string elt in
let msg =
Printf.sprintf
"You are trying to access the %s %s on a value whose class is unknown."
elt
(Markdown_lite.md_codify s)
in
(pos, msg))
in
(Error_code.UnknownObjectMember, claim, r, [])
let non_class_member pos1 s elt ty pos2 =
let claim =
lazy
(let elt = elt_type_to_string elt in
let msg =
Printf.sprintf
"You are trying to access the static %s %s but this is %s"
elt
(Markdown_lite.md_codify s)
ty
in
(pos1, msg))
in
(Error_code.NonClassMember, claim, lazy [(pos2, "Definition is here")], [])
let null_container p null_witness =
( Error_code.NullContainer,
lazy
( p,
"You are trying to access an element of this container"
^ " but the container could be `null`. " ),
null_witness,
[] )
let declared_covariant pos1 pos2 emsg =
let reason =
Lazy.map emsg ~f:(fun emsg ->
[
( Pos_or_decl.of_raw_pos pos1,
"This is where the parameter was declared as covariant `+`" );
]
@ List.map emsg ~f:(Message.map ~f:Pos_or_decl.of_raw_pos))
in
( Error_code.DeclaredCovariant,
lazy (pos2, "Illegal usage of a covariant type parameter"),
reason,
[] )
let declared_contravariant pos1 pos2 emsg =
let reason =
Lazy.map emsg ~f:(fun emsg ->
[
( Pos_or_decl.of_raw_pos pos1,
"This is where the parameter was declared as contravariant `-`" );
]
@ List.map emsg ~f:(Message.map ~f:Pos_or_decl.of_raw_pos))
in
( Error_code.DeclaredContravariant,
lazy (pos2, "Illegal usage of a contravariant type parameter"),
reason,
[] )
let static_property_type_generic_param generic_pos class_pos var_type_pos =
( Error_code.ClassVarTypeGenericParam,
lazy
( generic_pos,
"A generic parameter cannot be used in the type of a static property"
),
lazy
[
( var_type_pos,
"This is where the type of the static property was declared" );
(class_pos, "This is the class containing the static property");
],
[] )
let contravariant_this pos class_name tp =
( Error_code.ContravariantThis,
lazy
( pos,
"The `this` type cannot be used in this "
^ "contravariant position because its enclosing class "
^ Markdown_lite.md_codify class_name
^ " "
^ "is final and has a variant type parameter "
^ Markdown_lite.md_codify tp ),
lazy [],
[] )
let cyclic_typeconst pos sl =
let claim =
lazy
(let sl =
List.map sl ~f:(fun s ->
Render.strip_ns s |> Markdown_lite.md_codify)
in
(pos, "Cyclic type constant:\n " ^ String.concat ~sep:" -> " sl))
in
(Error_code.CyclicTypeconst, claim, lazy [], [])
let array_get_with_optional_field
~(field_pos : Pos.t) ~(recv_pos : Pos.t) ~decl_pos name =
let (_, recv_end_col) = Pos.end_line_column recv_pos in
let open_bracket_pos =
recv_pos
|> Pos.set_col_start recv_end_col
|> Pos.set_col_end (recv_end_col + 1)
in
let (_, field_end_col) = Pos.end_line_column field_pos in
let close_bracket_pos =
field_pos
|> Pos.set_col_start field_end_col
|> Pos.set_col_end (field_end_col + 1)
in
let quickfixes =
[
Quickfix.make_with_edits
~title:"Change to `Shapes::idx()`"
~edits:
[
(")", close_bracket_pos);
(", ", open_bracket_pos);
("Shapes::idx(", Pos.shrink_to_start recv_pos);
];
]
in
( Error_code.ArrayGetWithOptionalField,
lazy
( field_pos,
Printf.sprintf
"The field %s may not be present in this shape. Use `??` or `Shapes::idx()` instead."
(Markdown_lite.md_codify name) ),
lazy [(decl_pos, "This is where the field was declared as optional.")],
quickfixes )
let mutating_const_property pos =
( Error_code.AssigningToConst,
lazy (pos, "Cannot mutate a `__Const` property"),
lazy [],
[] )
let self_const_parent_not pos =
( Error_code.SelfConstParentNot,
lazy (pos, "A `__Const` class may only extend other `__Const` classes"),
lazy [],
[] )
let unexpected_ty_in_tast pos ~actual_ty ~expected_ty =
( Error_code.UnexpectedTy,
lazy
( pos,
"Unexpected type in TAST: expected "
^ Markdown_lite.md_codify expected_ty
^ ", got "
^ Markdown_lite.md_codify actual_ty ),
lazy [],
[] )
let call_lvalue pos =
( Error_code.CallLvalue,
lazy
( pos,
"Array updates cannot be applied to function results. Use a local variable instead."
),
lazy [],
[] )
let unsafe_cast_await pos =
( Error_code.UnsafeCastAwait,
lazy
(pos, "UNSAFE_CAST cannot be used as the operand of an await operation"),
lazy [],
[] )
let to_error t ~env =
let open Typing_error.Primary in
match t with
| Coeffect err -> Eval_coeffect.to_error err ~env
| Enum err -> Eval_enum.to_error err ~env
| Expr_tree err -> Eval_expr_tree.to_error err ~env
| Ifc err -> Eval_ifc.to_error err ~env
| Modules err -> Eval_modules.to_error err ~env
| Readonly err -> Eval_readonly.to_error err ~env
| Shape err -> Eval_shape.to_error err ~env
| Wellformedness err -> Eval_wellformedness.to_error err ~env
| Xhp err -> Eval_xhp.to_error err ~env
| CaseType err -> Eval_casetype.to_error err ~env
| Unify_error { pos; msg_opt; reasons_opt } ->
unify_error pos msg_opt reasons_opt
| Generic_unify { pos; msg } -> generic_unify pos msg
| Unresolved_tyvar pos -> unresolved_tyvar pos
| Using_error { pos; has_await } -> using_error pos has_await
| Bad_enum_decl pos -> bad_enum_decl pos
| Bad_conditional_support_dynamic
{ pos; child; parent; ty_name; self_ty_name } ->
bad_conditional_support_dynamic pos child parent ty_name self_ty_name
| Bad_decl_override { pos; name; parent_name } ->
bad_decl_override name pos parent_name
| Explain_where_constraint { pos; decl_pos; in_class } ->
explain_where_constraint pos decl_pos in_class
| Explain_constraint pos -> explain_constraint pos
| Rigid_tvar_escape { pos; what } -> rigid_tvar_escape pos what
| Invalid_type_hint pos -> invalid_type_hint pos
| Unsatisfied_req { pos; trait_pos; req_name; req_pos } ->
unsatisfied_req pos trait_pos req_name req_pos
| Unsatisfied_req_class { pos; trait_pos; req_name; req_pos } ->
unsatisfied_req_class pos trait_pos req_name req_pos
| Req_class_not_final { pos; trait_pos; req_pos } ->
req_class_not_final pos trait_pos req_pos
| Incompatible_reqs { pos; req_name; req_class_pos; req_extends_pos } ->
incompatible_reqs pos req_name req_class_pos req_extends_pos
| Trait_not_used { pos; trait_name; req_class_pos; class_pos; class_name }
->
trait_not_used pos trait_name req_class_pos class_pos class_name
| Invalid_echo_argument pos -> invalid_echo_argument pos
| Index_type_mismatch { pos; is_covariant_container; msg_opt; reasons_opt }
->
index_type_mismatch pos is_covariant_container msg_opt reasons_opt
| Member_not_found
{ pos; kind; member_name; class_name; class_pos; hint; reason } ->
member_not_found
pos
kind
member_name
class_name
class_pos
(Lazy.force hint)
reason
| Construct_not_instance_method pos -> construct_not_instance_method pos
| Ambiguous_inheritance { pos; origin; class_name } ->
ambiguous_inheritance pos origin class_name
| Expected_tparam { pos; n; decl_pos } -> expected_tparam pos n decl_pos
| Typeconst_concrete_concrete_override { pos; decl_pos } ->
typeconst_concrete_concrete_override pos decl_pos
| Constant_multiple_concrete_conflict { pos; name; definitions } ->
constant_multiple_concrete_conflict pos name definitions
| Invalid_memoized_param { pos; reason; _ } ->
invalid_memoized_param pos reason
| Invalid_arraykey
{ pos; container_pos; container_ty_name; key_pos; key_ty_name; ctxt } ->
invalid_arraykey
pos
container_pos
(Lazy.force container_ty_name)
key_pos
(Lazy.force key_ty_name)
ctxt
| Invalid_keyset_value
{ pos; container_pos; container_ty_name; value_pos; value_ty_name } ->
invalid_keyset_value
pos
container_pos
(Lazy.force container_ty_name)
value_pos
(Lazy.force value_ty_name)
| Invalid_set_value
{ pos; container_pos; container_ty_name; value_pos; value_ty_name } ->
invalid_set_value
pos
container_pos
(Lazy.force container_ty_name)
value_pos
(Lazy.force value_ty_name)
| HKT_alias_with_implicit_constraints
{
pos;
typedef_name;
typedef_pos;
used_class_in_def_pos;
used_class_in_def_name;
used_class_tparam_name;
typedef_tparam_name;
_;
} ->
hkt_alias_with_implicit_constraints
pos
typedef_name
typedef_pos
used_class_in_def_pos
used_class_in_def_name
used_class_tparam_name
typedef_tparam_name
| HKT_wildcard pos -> hkt_wildcard pos
| HKT_implicit_argument { pos; decl_pos; param_name } ->
hkt_implicit_argument pos decl_pos param_name
| Object_string_deprecated pos -> object_string_deprecated pos
| Invalid_substring { pos; ty_name } -> invalid_substring pos ty_name
| Unset_nonidx_in_strict { pos; reason } ->
unset_nonidx_in_strict pos reason
| Nullable_cast { pos; ty_pos; ty_name } -> nullable_cast pos ty_pos ty_name
| Hh_expect { pos; equivalent } -> hh_expect pos equivalent
| Null_member { pos; obj_pos_opt; ctxt; kind; member_name; reason } ->
null_member pos ~obj_pos_opt ctxt kind member_name reason
| Typing_too_many_args { pos; decl_pos; actual; expected } ->
typing_too_many_args pos decl_pos actual expected
| Typing_too_few_args { pos; decl_pos; actual; expected } ->
typing_too_few_args pos decl_pos actual expected
| Non_object_member { pos; ctxt; ty_name; member_name; kind; decl_pos } ->
non_object_member pos ctxt ty_name member_name kind decl_pos
| Static_instance_intersection
{ class_pos; instance_pos; static_pos; member_name; kind } ->
static_instance_intersection
class_pos
instance_pos
static_pos
member_name
kind
| Nullsafe_property_write_context pos -> nullsafe_property_write_context pos
| Uninstantiable_class { pos; class_name; reason_ty_opt; decl_pos } ->
uninstantiable_class pos class_name reason_ty_opt decl_pos
| Abstract_const_usage { pos; name; decl_pos } ->
abstract_const_usage pos name decl_pos
| Type_arity_mismatch { pos; decl_pos; actual; expected } ->
type_arity_mismatch pos decl_pos actual expected
| Member_not_implemented { pos; member_name; decl_pos; quickfixes } ->
member_not_implemented pos member_name decl_pos quickfixes
| Kind_mismatch { pos; decl_pos; tparam_name; expected_kind; actual_kind }
->
kind_mismatch pos decl_pos tparam_name expected_kind actual_kind
| Trait_parent_construct_inconsistent { pos; decl_pos } ->
trait_parent_construct_inconsistent pos decl_pos
| Top_member
{ pos; ctxt; ty_name; decl_pos; kind; name; is_nullable; ty_reasons } ->
top_member pos ctxt ty_name decl_pos kind name is_nullable ty_reasons
| Unresolved_tyvar_projection { pos; proj_pos; tconst_name } ->
unresolved_tyvar_projection pos proj_pos tconst_name
| Cyclic_class_constant { pos; class_name; const_name } ->
cyclic_class_constant pos class_name const_name
| Inout_annotation_missing { pos; decl_pos } ->
inout_annotation_missing pos decl_pos
| Inout_annotation_unexpected { pos; decl_pos; param_is_variadic; qfx_pos }
->
inout_annotation_unexpected pos decl_pos param_is_variadic qfx_pos
| Inout_argument_bad_type { pos; reasons } ->
inout_argument_bad_type pos reasons
| Invalid_meth_caller_calling_convention { pos; decl_pos; convention } ->
invalid_meth_caller_calling_convention pos decl_pos convention
| Invalid_meth_caller_readonly_return { pos; decl_pos } ->
invalid_meth_caller_readonly_return pos decl_pos
| Invalid_new_disposable pos -> invalid_new_disposable pos
| Invalid_return_disposable pos -> invalid_return_disposable pos
| Invalid_disposable_hint { pos; class_name } ->
invalid_disposable_hint pos class_name
| Invalid_disposable_return_hint { pos; class_name } ->
invalid_disposable_return_hint pos class_name
| Ambiguous_lambda { pos; uses } -> ambiguous_lambda pos uses
| Wrong_extend_kind
{ pos; kind; name; parent_pos; parent_kind; parent_name } ->
wrong_extend_kind pos kind name parent_pos parent_kind parent_name
| Smember_not_found
{ pos; kind; member_name; class_name; class_pos; hint; quickfixes } ->
smember_not_found
pos
kind
member_name
class_name
class_pos
hint
quickfixes
| Cyclic_class_def { pos; stack } -> cyclic_class_def pos stack
| Trait_reuse_with_final_method
{ pos; trait_name; parent_cls_name = (lazy parent_cls_name); trace } ->
trait_reuse_with_final_method pos trait_name parent_cls_name trace
| Trait_reuse_inside_class { pos; class_name; trait_name; occurrences } ->
trait_reuse_inside_class pos class_name trait_name occurrences
| Invalid_is_as_expression_hint { pos; op; reasons } ->
invalid_is_as_expression_hint pos op reasons
| Invalid_enforceable_type { pos; ty_info; tp_pos; tp_name; kind } ->
invalid_enforceable_type pos ty_info kind tp_pos tp_name
| Reifiable_attr { pos; ty_info; attr_pos; kind } ->
reifiable_attr attr_pos kind pos ty_info
| Invalid_newable_type_argument { pos; tp_pos; tp_name } ->
invalid_newable_type_argument pos tp_pos tp_name
| Invalid_newable_typaram_constraints { pos; tp_name; constraints } ->
invalid_newable_type_param_constraints (pos, tp_name) constraints
| Override_per_trait { pos; class_name; meth_name; trait_name; meth_pos } ->
override_per_trait (pos, class_name) meth_name trait_name meth_pos
| Should_not_be_override { pos; class_id; id } ->
should_not_be_override pos class_id id
| Trivial_strict_eq { pos; result; left; right; left_trail; right_trail } ->
trivial_strict_eq pos result left right left_trail right_trail
| Trivial_strict_not_nullable_compare_null { pos; result; ty_reason_msg } ->
trivial_strict_not_nullable_compare_null pos result ty_reason_msg
| Eq_incompatible_types { pos; left; right } ->
eq_incompatible_types pos (Lazy.force left) (Lazy.force right)
| Comparison_invalid_types { pos; left; right } ->
comparison_invalid_types pos (Lazy.force left) (Lazy.force right)
| Strict_eq_value_incompatible_types { pos; left; right } ->
strict_eq_value_incompatible_types
pos
(Lazy.force left)
(Lazy.force right)
| Deprecated_use { pos; decl_pos_opt; msg } ->
deprecated_use pos ~pos_def:decl_pos_opt msg
| Cannot_declare_constant { pos; class_pos; class_name } ->
cannot_declare_constant pos (class_pos, class_name)
| Invalid_classname pos -> invalid_classname pos
| Illegal_type_structure { pos; msg } -> illegal_type_structure pos msg
| Illegal_typeconst_direct_access pos -> illegal_typeconst_direct_access pos
| Wrong_expression_kind_attribute
{
pos;
attr_name;
expr_kind;
attr_class_pos;
attr_class_name;
intf_name;
} ->
wrong_expression_kind_attribute
expr_kind
pos
attr_name
attr_class_pos
attr_class_name
intf_name
| Ambiguous_object_access
{ pos; name; self_pos; vis; subclass_pos; class_self; class_subclass }
->
ambiguous_object_access
pos
name
self_pos
vis
subclass_pos
class_self
class_subclass
| Unserializable_type { pos; message } -> unserializable_type pos message
| Invalid_arraykey_constraint { pos; ty_name } ->
invalid_arraykey_constraint pos @@ Lazy.force ty_name
| Redundant_covariant { pos; msg; suggest } ->
redundant_covariant pos msg suggest
| Meth_caller_trait { pos; trait_name } -> meth_caller_trait pos trait_name
| Duplicate_interface { pos; name; others } ->
duplicate_interface pos name others
| Reified_function_reference pos -> reified_function_reference pos
| Class_meth_abstract_call { pos; class_name; meth_name; decl_pos } ->
class_meth_abstract_call class_name meth_name pos decl_pos
| Reinheriting_classish_const
{
pos;
classish_name;
src_pos;
src_classish_name;
existing_const_origin;
const_name;
} ->
reinheriting_classish_const
pos
classish_name
src_pos
src_classish_name
existing_const_origin
const_name
| Redeclaring_classish_const
{
pos;
classish_name;
redeclaration_pos;
existing_const_origin;
const_name;
} ->
redeclaring_classish_const
pos
classish_name
redeclaration_pos
existing_const_origin
const_name
| Abstract_function_pointer { pos; class_name; meth_name; decl_pos } ->
abstract_function_pointer class_name meth_name pos decl_pos
| Inherited_class_member_with_different_case
{
pos;
member_type;
name;
name_prev;
child_class;
prev_class;
prev_class_pos;
} ->
inherited_class_member_with_different_case
member_type
name
name_prev
pos
child_class
prev_class
prev_class_pos
| Multiple_inherited_class_member_with_different_case
{
pos;
child_class_name;
member_type;
class1_name;
class1_pos;
name1;
class2_name;
class2_pos;
name2;
} ->
multiple_inherited_class_member_with_different_case
~member_type
~name1
~name2
~class1:class1_name
~class2:class2_name
~child_class:child_class_name
~child_p:pos
~p1:class1_pos
~p2:class2_pos
| Parent_support_dynamic_type
{
pos;
child_name;
child_kind;
parent_name;
parent_kind;
child_support_dyn;
} ->
parent_support_dynamic_type
pos
(child_name, child_kind)
(parent_name, parent_kind)
child_support_dyn
| Property_is_not_enforceable
{ pos; prop_name; class_name; prop_pos; prop_type } ->
property_is_not_enforceable pos prop_name class_name (prop_pos, prop_type)
| Property_is_not_dynamic
{ pos; prop_name; class_name; prop_pos; prop_type } ->
property_is_not_dynamic pos prop_name class_name (prop_pos, prop_type)
| Private_property_is_not_enforceable
{ pos; prop_name; class_name; prop_pos; prop_type } ->
private_property_is_not_enforceable
pos
prop_name
class_name
(prop_pos, prop_type)
| Private_property_is_not_dynamic
{ pos; prop_name; class_name; prop_pos; prop_type } ->
private_property_is_not_dynamic
pos
prop_name
class_name
(prop_pos, prop_type)
| Immutable_local pos -> immutable_local pos
| Nonsense_member_selection { pos; kind } ->
nonsense_member_selection pos kind
| Consider_meth_caller { pos; class_name; meth_name } ->
consider_meth_caller pos class_name meth_name
| Method_import_via_diamond
{ pos; class_name; method_pos; method_name; trace1; trace2 } ->
method_import_via_diamond
pos
class_name
method_pos
method_name
trace1
trace2
| Property_import_via_diamond
{
generic;
pos;
class_name;
property_pos;
property_name;
trace1;
trace2;
} ->
property_import_via_diamond
generic
pos
class_name
property_pos
property_name
trace1
trace2
| Unification_cycle { pos; ty_name } ->
unification_cycle pos @@ Lazy.force ty_name
| Method_variance pos -> method_variance pos
| Explain_tconst_where_constraint { pos; decl_pos; msgs } ->
explain_tconst_where_constraint pos decl_pos msgs
| Format_string
{ pos; snippet; fmt_string; class_pos; fn_name; class_suggest } ->
format_string pos snippet fmt_string class_pos fn_name class_suggest
| Expected_literal_format_string pos -> expected_literal_format_string pos
| Re_prefixed_non_string { pos; reason } ->
re_prefixed_non_string pos reason
| Bad_regex_pattern { pos; reason } -> bad_regex_pattern pos reason
| Generic_array_strict pos -> generic_array_strict pos
| Option_return_only_typehint { pos; kind } ->
option_return_only_typehint pos kind
| Redeclaring_missing_method { pos; trait_method } ->
redeclaring_missing_method pos trait_method
| Expecting_type_hint pos -> expecting_type_hint pos
| Expecting_type_hint_variadic pos -> expecting_type_hint_variadic pos
| Expecting_return_type_hint pos -> expecting_return_type_hint pos
| Duplicate_using_var pos -> duplicate_using_var pos
| Illegal_disposable { pos; verb } -> illegal_disposable pos verb
| Escaping_disposable pos -> escaping_disposable pos
| Escaping_disposable_param pos -> escaping_disposable_parameter pos
| Escaping_this pos -> escaping_this pos
| Must_extend_disposable pos -> must_extend_disposable pos
| Field_kinds { pos; decl_pos } -> field_kinds pos decl_pos
| Unbound_name { pos; name; class_exists } ->
unbound_name_typing pos name class_exists
| Previous_default pos -> previous_default pos
| Return_in_void { pos; decl_pos } -> return_in_void pos decl_pos
| This_var_outside_class pos -> this_var_outside_class pos
| Unbound_global pos -> unbound_global pos
| Private_inst_meth { pos; decl_pos } -> private_inst_meth pos decl_pos
| Protected_inst_meth { pos; decl_pos } -> protected_inst_meth pos decl_pos
| Private_meth_caller { pos; decl_pos } -> private_meth_caller pos decl_pos
| Protected_meth_caller { pos; decl_pos } ->
protected_meth_caller pos decl_pos
| Private_class_meth { pos; decl_pos } -> private_class_meth pos decl_pos
| Protected_class_meth { pos; decl_pos } ->
protected_class_meth pos decl_pos
| Array_cast pos -> array_cast pos
| String_cast { pos; ty_name } -> string_cast pos @@ Lazy.force ty_name
| Static_outside_class pos -> static_outside_class pos
| Self_outside_class pos -> self_outside_class pos
| New_inconsistent_construct { pos; class_pos; class_name; kind } ->
new_inconsistent_construct pos (class_pos, class_name) kind
| Undefined_parent pos -> undefined_parent pos
| Parent_outside_class pos -> parent_outside_class pos
| Parent_abstract_call { pos; meth_name; decl_pos } ->
parent_abstract_call pos meth_name decl_pos
| Self_abstract_call { pos; self_pos; meth_name; decl_pos } ->
self_abstract_call pos meth_name self_pos decl_pos
| Classname_abstract_call { pos; meth_name; class_name; decl_pos } ->
classname_abstract_call pos meth_name class_name decl_pos
| Static_synthetic_method { pos; meth_name; class_name; decl_pos } ->
static_synthetic_method pos meth_name class_name decl_pos
| Isset_in_strict pos -> isset_in_strict pos
| Isset_inout_arg pos -> isset_inout_arg pos
| Unpacking_disallowed_builtin_function { pos; fn_name } ->
unpacking_disallowed_builtin_function pos fn_name
| Array_get_arity { pos; name; decl_pos } ->
array_get_arity pos name decl_pos
| Undefined_field { pos; name; decl_pos } ->
undefined_field pos name decl_pos
| Array_access { pos; ctxt = `read; ty_name; decl_pos } ->
array_access_read pos decl_pos @@ Lazy.force ty_name
| Array_access { pos; ctxt = `write; ty_name; decl_pos } ->
array_access_write pos decl_pos @@ Lazy.force ty_name
| Keyset_set { pos; decl_pos } -> keyset_set pos decl_pos
| Array_append { pos; ty_name; decl_pos } ->
array_append pos decl_pos @@ Lazy.force ty_name
| Const_mutation { pos; ty_name; decl_pos } ->
const_mutation pos decl_pos @@ Lazy.force ty_name
| Expected_class { pos; suffix } ->
expected_class pos Option.(value_map ~default:"" ~f:Lazy.force suffix)
| Unknown_type { pos; expected; reason } -> unknown_type pos expected reason
| Parent_in_trait pos -> parent_in_trait pos
| Parent_undefined pos -> parent_undefined pos
| Constructor_no_args pos -> constructor_no_args pos
| Visibility { pos; msg; decl_pos; reason_msg } ->
visibility pos msg decl_pos reason_msg
| Bad_call { pos; ty_name } -> bad_call pos @@ Lazy.force ty_name
| Extend_final { pos; name; decl_pos } -> extend_final pos decl_pos name
| Extend_sealed { pos; parent_pos; parent_name; parent_kind; verb } ->
extend_sealed pos parent_pos parent_name parent_kind verb
| Sealed_not_subtype { pos; name; child_kind; child_pos; child_name } ->
sealed_not_subtype pos name child_name child_kind child_pos
| Trait_prop_const_class { pos; name } -> trait_prop_const_class pos name
| Implement_abstract
{ pos; is_final; decl_pos; trace; name; kind; quickfixes } ->
implement_abstract pos is_final decl_pos name kind quickfixes trace
| Abstract_member_in_concrete_class
{ pos; class_name_pos; is_final; member_kind; member_name } ->
abstract_member_in_concrete_class
~member_pos:pos
~class_name_pos
~is_final
member_kind
member_name
| Generic_static { pos; typaram_name } -> generic_static pos typaram_name
| Ellipsis_strict_mode { pos; require } -> ellipsis_strict_mode pos require
| Object_string { pos; decl_pos } -> object_string pos decl_pos
| Cyclic_typedef { pos; decl_pos } -> cyclic_typedef pos decl_pos
| Require_args_reify { pos; decl_pos } -> require_args_reify pos decl_pos
| Require_generic_explicit { pos; param_name; decl_pos } ->
require_generic_explicit pos decl_pos param_name
| Invalid_reified_arg { pos; param_name; decl_pos; arg_info } ->
invalid_reified_argument pos param_name decl_pos arg_info
| Invalid_reified_arg_reifiable
{ pos; param_name : string; decl_pos; ty_pos; ty_msg } ->
invalid_reified_argument_reifiable pos param_name decl_pos ty_pos
@@ Lazy.force ty_msg
| New_class_reified { pos; class_kind; suggested_class_name } ->
new_class_reified pos class_kind suggested_class_name
| Class_get_reified pos -> class_get_reified pos
| Static_meth_with_class_reified_generic { pos; generic_pos } ->
static_meth_with_class_reified_generic pos generic_pos
| Consistent_construct_reified pos -> consistent_construct_reified pos
| Bad_fn_ptr_construction pos -> bad_function_pointer_construction pos
| Reified_generics_not_allowed pos -> reified_generics_not_allowed pos
| New_without_newable { pos; name } -> new_without_newable pos name
| Discarded_awaitable { pos; decl_pos } -> discarded_awaitable pos decl_pos
| Unknown_object_member { pos; member_name; elt; reason } ->
unknown_object_member pos member_name elt reason
| Non_class_member { pos; member_name; elt; ty_name; decl_pos } ->
non_class_member pos member_name elt (Lazy.force ty_name) decl_pos
| Null_container { pos; null_witness } -> null_container pos null_witness
| Declared_covariant { pos; param_pos; msgs } ->
declared_covariant param_pos pos msgs
| Declared_contravariant { pos; param_pos; msgs } ->
declared_contravariant pos param_pos msgs
| Static_prop_type_generic_param { pos; var_ty_pos; class_pos } ->
static_property_type_generic_param pos class_pos var_ty_pos
| Contravariant_this { pos; class_name; typaram_name } ->
contravariant_this pos class_name typaram_name
| Cyclic_typeconst { pos; tyconst_names } ->
cyclic_typeconst pos tyconst_names
| Array_get_with_optional_field
{ recv_pos; field_pos; field_name; decl_pos } ->
array_get_with_optional_field field_name ~decl_pos ~recv_pos ~field_pos
| Mutating_const_property pos -> mutating_const_property pos
| Self_const_parent_not pos -> self_const_parent_not pos
| Unexpected_ty_in_tast { pos; expected_ty; actual_ty } ->
unexpected_ty_in_tast
pos
~expected_ty:(Lazy.force expected_ty)
~actual_ty:(Lazy.force actual_ty)
| Call_lvalue pos -> call_lvalue pos
| Unsafe_cast_await pos -> unsafe_cast_await pos
end
module rec Eval_error : sig
val eval :
Typing_error.Error.t ->
env:Typing_env_types.env ->
current_span:Pos.t ->
error Eval_result.t
val to_user_error :
Typing_error.Error.t ->
env:Typing_env_types.env ->
current_span:Pos.t ->
(Pos.t, Pos_or_decl.t) User_error.t Eval_result.t
end = struct
let eval t ~env ~current_span =
let open Typing_error.Error in
let rec aux ~k = function
| Primary base ->
k @@ Eval_result.single @@ Eval_primary.to_error base ~env
| With_code (t, code) ->
aux t ~k:(fun res ->
k
@@ Eval_result.map res ~f:(fun (_, claim, reason, qfx) ->
(code, claim, reason, qfx)))
| Intersection ts -> auxs ~k:(fun xs -> k @@ Eval_result.intersect xs) ts
| Union ts -> auxs ~k:(fun xs -> k @@ Eval_result.union xs) ts
| Multiple ts -> auxs ~k:(fun xs -> k @@ Eval_result.multiple xs) ts
| Apply (cb, err) ->
aux err ~k:(fun t ->
k
@@ Eval_result.bind t ~f:(fun (code, claim, reasons, quickfixes) ->
Eval_result.single
@@ Eval_callback.apply
cb
~env
~code
~claim
~reasons
~quickfixes))
| Apply_reasons (cb, snd_err) ->
k
@@ Eval_result.bind ~f:(fun (code, reasons) ->
Eval_reasons_callback.apply_help
cb
~code
~reasons
~env
~current_span)
@@ Eval_secondary.eval snd_err ~env ~current_span
| Assert_in_current_decl (snd_err, ctx) ->
k
@@ Eval_result.bind ~f:(fun e ->
Eval_result.of_option @@ Common.eval_assert ctx current_span e)
@@ Eval_secondary.eval snd_err ~env ~current_span
and auxs ~k = function
| [] -> k []
| next :: rest ->
aux next ~k:(fun x -> auxs rest ~k:(fun xs -> k @@ (x :: xs)))
in
aux ~k:Fn.id t
let make_error (code, claim, reasons, quickfixes) ~custom_msgs =
User_error.make
(Error_code.to_enum code)
(Lazy.force claim)
(Lazy.force reasons)
~quickfixes
~custom_msgs
let render_custom_error
(t : (string, Custom_error_eval.Value.t) Base.Either.t list) ~env =
List.fold_right
t
~f:(fun v acc ->
match v with
| Core.Either.First str -> str ^ acc
| Either.Second (Custom_error_eval.Value.Name (_, nm)) ->
Markdown_lite.md_codify nm ^ acc
| Either.Second (Custom_error_eval.Value.Ty ty) ->
(Markdown_lite.md_codify
@@ Typing_print.with_blank_tyvars (fun () ->
Typing_print.full_strip_ns_i env
@@ Typing_defs_core.LoclType ty))
^ acc)
~init:""
let to_user_error t ~env ~current_span =
let result = eval t ~env ~current_span in
let custom_err_config =
TypecheckerOptions.custom_error_config (Typing_env.get_tcopt env)
in
let custom_msgs =
List.map ~f:(render_custom_error ~env)
@@ Custom_error_eval.eval custom_err_config ~err:t
in
Eval_result.map ~f:(make_error ~custom_msgs) result
end
and Eval_secondary : sig
val eval :
Typing_error.Secondary.t ->
env:Typing_env_types.env ->
current_span:Pos.t ->
(Error_code.t * Pos_or_decl.t Message.t list Lazy.t) Eval_result.t
end = struct
let fun_too_many_args pos decl_pos actual expected =
let reasons =
lazy
[
( pos,
Printf.sprintf
"Too many mandatory arguments (expected %d but got %d)"
expected
actual );
(decl_pos, "Because of this definition");
]
in
(Error_code.FunTooManyArgs, reasons)
let fun_too_few_args pos decl_pos actual expected =
let reasons =
lazy
[
( pos,
Printf.sprintf
"Too few arguments (required %d but got %d)"
expected
actual );
(decl_pos, "Because of this definition");
]
in
(Error_code.FunTooFewArgs, reasons)
let fun_unexpected_nonvariadic pos decl_pos =
let reasons =
lazy
[
(pos, "Should have a variadic argument");
(decl_pos, "Because of this definition");
]
in
(Error_code.FunUnexpectedNonvariadic, reasons)
let fun_variadicity_hh_vs_php56 pos decl_pos =
let reasons =
lazy
[
(pos, "Variadic arguments: `...`-style is not a subtype of `...$args`");
(decl_pos, "Because of this definition");
]
in
(Error_code.FunVariadicityHhVsPhp56, reasons)
let type_arity_mismatch pos actual decl_pos expected =
let reasons =
lazy
[
(pos, "This type has " ^ string_of_int actual ^ " arguments");
(decl_pos, "This one has " ^ string_of_int expected);
]
in
(Error_code.TypeArityMismatch, reasons)
(* In typing_coercion.ml we sometimes check t1 <: t2 by adding dynamic
to check t1 < t|dynamic. In that case, we use the Rdynamic_coercion
reason so that we can detect it here and not print the dynamic if there
is a type error. *)
let detect_attempting_dynamic_coercion_reason r ty =
let open Typing_defs_core in
match r with
| Typing_reason.Rdynamic_coercion r ->
(match ty with
| LoclType lty ->
(match get_node lty with
| Tunion [t1; t2] ->
(match (get_node t1, get_node t2) with
| (Tdynamic, _) -> (r, LoclType t2)
| (_, Tdynamic) -> (r, LoclType t1)
| _ -> (r, ty))
| _ -> (r, ty))
| _ -> (r, ty))
| _ -> (r, ty)
let describe_coeffect env ty =
lazy
(let (env, ty) = Typing_utils.simplify_intersections env ty in
Typing_print.coeffects env ty)
let describe_ty_default env ty =
Typing_print.with_blank_tyvars (fun () ->
Typing_print.full_strip_ns_i env ty)
let describe_ty ~is_coeffect =
(* Optimization: specialize on partial application, i.e.
* let describe_ty_sub = describe_ty ~is_coeffect in
* will check the flag only once, not every time the function is called *)
if not is_coeffect then
describe_ty_default
else
fun env -> function
| Typing_defs_core.LoclType ty -> Lazy.force @@ describe_coeffect env ty
| ty -> describe_ty_default env ty
let rec describe_ty_super ~is_coeffect env ty =
let open Typing_defs_core in
let describe_ty_super = describe_ty_super ~is_coeffect in
let print = (describe_ty ~is_coeffect) env in
let default () = print ty in
match ty with
| LoclType ty ->
let (env, ty) = Typing_env.expand_type env ty in
(match Typing_defs_core.get_node ty with
| Typing_defs_core.Tvar v ->
let upper_bounds =
Internal_type_set.elements (Typing_env.get_tyvar_upper_bounds env v)
in
(* The constraint graph is transitively closed so we can filter tyvars. *)
let upper_bounds =
List.filter upper_bounds ~f:(fun t -> not (Typing_defs.is_tyvar_i t))
in
(match upper_bounds with
| [] -> "some type not known yet"
| tyl ->
let (locl_tyl, cstr_tyl) =
List.partition_tf tyl ~f:Typing_defs.is_locl_type
in
let sep =
match (locl_tyl, cstr_tyl) with
| (_ :: _, _ :: _) -> " and "
| _ -> ""
in
let locl_descr =
match locl_tyl with
| [] -> ""
| tyl ->
"of type "
^ (String.concat ~sep:" & " (List.map tyl ~f:print)
|> Markdown_lite.md_codify)
in
let cstr_descr =
String.concat
~sep:" and "
(List.map cstr_tyl ~f:(describe_ty_super env))
in
"something " ^ locl_descr ^ sep ^ cstr_descr)
| Toption ty when Typing_defs.is_tyvar ty ->
"`null` or " ^ describe_ty_super env (LoclType ty)
| _ -> Markdown_lite.md_codify (default ()))
| ConstraintType ty ->
(match deref_constraint_type ty with
| (_, Thas_member hm) ->
let {
hm_name = (_, name);
hm_type = _;
hm_class_id = _;
hm_explicit_targs = targs;
} =
hm
in
(match targs with
| None -> Printf.sprintf "an object with property `%s`" name
| Some _ -> Printf.sprintf "an object with method `%s`" name)
| (_, Thas_type_member htm) ->
let { htm_id = id; htm_lower = lo; htm_upper = up } = htm in
if phys_equal lo up then
(* We use physical equality as a heuristic to generate
slightly more readable descriptions. *)
Printf.sprintf
"a class with `{type %s = %s}`"
id
(describe_ty ~is_coeffect:false env (LoclType lo))
else
let bound_desc ~prefix ~is_trivial bnd =
if is_trivial env bnd then
""
else
prefix ^ describe_ty ~is_coeffect:false env (LoclType bnd)
in
Printf.sprintf
"a class with `{type %s%s%s}`"
id
(bound_desc
~prefix:" super "
~is_trivial:Typing_utils.is_nothing
lo)
(bound_desc ~prefix:" as " ~is_trivial:Typing_utils.is_mixed up)
| (_, Tcan_traverse _) -> "an array that can be traversed with foreach"
| (_, Tcan_index _) -> "an array that can be indexed"
| (_, Tdestructure _) ->
Markdown_lite.md_codify
(Typing_print.with_blank_tyvars (fun () ->
Typing_print.full_strip_ns_i env (ConstraintType ty)))
| (_, TCunion (lty, cty)) ->
Printf.sprintf
"%s or %s"
(describe_ty_super env (LoclType lty))
(describe_ty_super env (ConstraintType cty))
| (_, TCintersection (lty, cty)) ->
Printf.sprintf
"%s and %s"
(describe_ty_super env (LoclType lty))
(describe_ty_super env (ConstraintType cty)))
let describe_ty_sub ~is_coeffect env ety =
let ty_descr = describe_ty ~is_coeffect env ety in
let ty_constraints =
match ety with
| Typing_defs.LoclType ty -> Typing_print.constraints_for_type env ty
| Typing_defs.ConstraintType _ -> ""
in
let ( = ) = String.equal in
let ty_constraints =
(* Don't say `T as T` as it's not helpful (occurs in some coffect errors). *)
if ty_constraints = "as " ^ ty_descr then
""
else if ty_constraints = "" then
""
else
" " ^ ty_constraints
in
Markdown_lite.md_codify (ty_descr ^ ty_constraints)
let explain_subtype_failure is_coeffect ~ty_sub ~ty_sup env =
lazy
(let r_super = Typing_defs.reason ty_sup in
let r_sub = Typing_defs.reason ty_sub in
let (r_super, ty_sup) =
detect_attempting_dynamic_coercion_reason r_super ty_sup
in
let ty_super_descr = describe_ty_super ~is_coeffect env ty_sup in
let ty_sub_descr = describe_ty_sub ~is_coeffect env ty_sub in
let (ty_super_descr, ty_sub_descr) =
if String.equal ty_super_descr ty_sub_descr then
( "exactly the type " ^ ty_super_descr,
"the nonexact type " ^ ty_sub_descr )
else
(ty_super_descr, ty_sub_descr)
in
let left =
Typing_reason.to_string ("Expected " ^ ty_super_descr) r_super
in
let right = Typing_reason.to_string ("But got " ^ ty_sub_descr) r_sub in
left @ right)
let subtyping_error is_coeffect ~ty_sub ~ty_sup env =
( Error_code.UnifyError,
explain_subtype_failure is_coeffect ~ty_sub ~ty_sup env )
let violated_constraint cstrs is_coeffect ~ty_sub ~ty_sup env =
let reason =
Lazy.map
~f:(fun reasons ->
let pos_msg = "This type constraint is violated" in
let f (p_cstr, (p_tparam, tparam)) =
[
( p_tparam,
Printf.sprintf
"%s is a constrained type parameter"
(Markdown_lite.md_codify tparam) );
(p_cstr, pos_msg);
]
in
let msgs = List.concat_map ~f cstrs in
msgs @ reasons)
(explain_subtype_failure is_coeffect ~ty_sub ~ty_sup env)
in
(Error_code.TypeConstraintViolation, reason)
let concrete_const_interface_override pos parent_pos name parent_origin =
let reasons =
lazy
[
( pos,
"Non-abstract constants defined in an interface cannot be overridden when implementing or extending that interface."
);
( parent_pos,
"You could make "
^ Markdown_lite.md_codify name
^ " abstract in "
^ (Markdown_lite.md_codify @@ Render.strip_ns parent_origin)
^ "." );
]
in
(Error_code.ConcreteConstInterfaceOverride, reasons)
let interface_or_trait_const_multiple_defs
pos origin parent_pos parent_origin name =
let reasons =
lazy
(let parent_origin = Render.strip_ns parent_origin
and child_origin = Render.strip_ns origin in
[
( pos,
"Non-abstract constants defined in an interface or trait cannot conflict with other inherited constants."
);
( parent_pos,
Markdown_lite.md_codify name
^ " inherited from "
^ Markdown_lite.md_codify parent_origin );
( pos,
"conflicts with constant "
^ Markdown_lite.md_codify name
^ " inherited from "
^ Markdown_lite.md_codify child_origin
^ "." );
])
in
(Error_code.ConcreteConstInterfaceOverride, reasons)
let interface_typeconst_multiple_defs
pos parent_pos name origin parent_origin is_abstract =
let reasons =
lazy
(let parent_origin = Render.strip_ns parent_origin
and child_origin = Render.strip_ns origin
and child_pos = pos
and child =
if is_abstract then
"abstract type constant with default value"
else
"concrete type constant"
in
[
( pos,
"Concrete and abstract type constants with default values in an interface cannot conflict with inherited"
^ " concrete or abstract type constants with default values." );
( parent_pos,
Markdown_lite.md_codify name
^ " inherited from "
^ Markdown_lite.md_codify parent_origin );
( child_pos,
"conflicts with "
^ Markdown_lite.md_codify child
^ " "
^ Markdown_lite.md_codify name
^ " inherited from "
^ Markdown_lite.md_codify child_origin
^ "." );
])
in
(Error_code.ConcreteConstInterfaceOverride, reasons)
let missing_field pos name decl_pos =
let reasons =
lazy
[
(pos, "The field " ^ Markdown_lite.md_codify name ^ " is missing");
(decl_pos, "The field " ^ Markdown_lite.md_codify name ^ " is defined");
]
in
(Error_code.MissingField, reasons)
let shape_fields_unknown pos decl_pos =
let reasons =
lazy
[
( pos,
"This shape type allows unknown fields, and so it may contain fields other than those explicitly declared in its declaration."
);
( decl_pos,
"It is incompatible with a shape that does not allow unknown fields."
);
]
in
(Error_code.ShapeFieldsUnknown, reasons)
let abstract_tconst_not_allowed pos decl_pos tconst_name =
let reasons =
lazy
[
(pos, "An abstract type constant is not allowed in this position.");
( decl_pos,
Printf.sprintf
"%s is abstract here."
(Markdown_lite.md_codify tconst_name) );
]
in
(Error_code.AbstractTconstNotAllowed, reasons)
let invalid_destructure pos decl_pos ty_name =
let reasons =
lazy
[
( pos,
"This expression cannot be destructured with a `list(...)` expression"
);
(decl_pos, "This is " ^ Markdown_lite.md_codify @@ Lazy.force ty_name);
]
in
(Error_code.InvalidDestructure, reasons)
let unpack_array_required_argument pos decl_pos =
let reasons =
lazy
[
( pos,
"An array cannot be unpacked into the required arguments of a function"
);
(decl_pos, "Definition is here");
]
in
(Error_code.SplatArrayRequired, reasons)
let unpack_array_variadic_argument pos decl_pos =
let reasons =
lazy
[
( pos,
"A function that receives an unpacked array as an argument must have a variadic parameter to accept the elements of the array"
);
(decl_pos, "Definition is here");
]
in
(Error_code.SplatArrayRequired, reasons)
let overriding_prop_const_mismatch pos is_const parent_pos =
let reasons =
lazy
(let (msg, reason_msg) =
if is_const then
("This property is `__Const`", "This property is not `__Const`")
else
("This property is not `__Const`", "This property is `__Const`")
in
[(pos, msg); (parent_pos, reason_msg)])
in
(Error_code.OverridingPropConstMismatch, reasons)
let visibility_extends pos vis parent_pos parent_vis =
let reasons =
lazy
[
(pos, "This member visibility is: " ^ Markdown_lite.md_codify vis);
(parent_pos, Markdown_lite.md_codify parent_vis ^ " was expected");
]
in
(Error_code.VisibilityExtends, reasons)
let visibility_override_internal pos module_name parent_module parent_pos =
let reasons =
lazy
(let msg =
match module_name with
| None ->
Printf.sprintf
"Cannot override this member outside module `%s`"
parent_module
| Some m ->
Printf.sprintf "Cannot override this member in module `%s`" m
in
[
(pos, msg);
( parent_pos,
Printf.sprintf
"This member is internal to module `%s`"
parent_module );
])
in
(Error_code.ModuleError, reasons)
let missing_constructor pos =
let reasons = lazy [(pos, "The constructor is not implemented")] in
(Error_code.MissingConstructor, reasons)
let accept_disposable_invariant pos decl_pos =
let reasons =
lazy
[
(pos, "This parameter is marked `<<__AcceptDisposable>>`");
(decl_pos, "This parameter is not marked `<<__AcceptDisposable>>`");
]
in
(Error_code.AcceptDisposableInvariant, reasons)
let ifc_external_contravariant pos_sub pos_super =
let reasons =
lazy
[
( pos_super,
"Parameters with `<<__External>>` must be overridden by other parameters with <<__External>>. This parameter is marked `<<__External>>`"
);
(pos_sub, "But this parameter is not marked `<<__External>>`");
]
in
(Error_code.IFCExternalContravariant, reasons)
let required_field_is_optional pos name decl_pos def_pos =
let reasons =
lazy
[
(pos, "The field " ^ Markdown_lite.md_codify name ^ " is **optional**");
( decl_pos,
"The field "
^ Markdown_lite.md_codify name
^ " is defined as **required**" );
(def_pos, Markdown_lite.md_codify name ^ " is defined here");
]
in
(Error_code.RequiredFieldIsOptional, reasons)
let return_disposable_mismatch pos_sub is_marked_return_disposable pos_super =
let reasons =
lazy
(let (msg, reason_msg) =
if is_marked_return_disposable then
( "This is marked `<<__ReturnDisposable>>`.",
"This is not marked `<<__ReturnDisposable>>`." )
else
( "This is not marked `<<__ReturnDisposable>>`.",
"This is marked `<<__ReturnDisposable>>`." )
in
[(pos_super, msg); (pos_sub, reason_msg)])
in
(Error_code.ReturnDisposableMismatch, reasons)
let ifc_policy_mismatch pos policy pos_super policy_super =
let reasons =
lazy
[
( pos,
"IFC policies must be invariant with respect to inheritance. This method is policied with "
^ policy );
( pos_super,
"This is incompatible with its inherited policy, which is "
^ policy_super );
]
in
(Error_code.IFCPolicyMismatch, reasons)
let override_final pos parent_pos =
let reasons =
lazy
[
(pos, "You cannot override this method");
(parent_pos, "It was declared as final");
]
in
(Error_code.OverrideFinal, reasons)
let override_async pos parent_pos =
let reasons =
lazy
[
(pos, "You cannot override this method with a non-async method");
(parent_pos, "It was declared as async");
]
in
(Error_code.OverrideAsync, reasons)
let override_lsb pos member_name parent_pos =
let reasons =
lazy
[
( pos,
"Member "
^ Markdown_lite.md_codify member_name
^ " may not override `__LSB` member of parent" );
(parent_pos, "This is being overridden");
]
in
(Error_code.OverrideLSB, reasons)
let multiple_concrete_defs pos origin name parent_pos parent_origin class_name
=
let reasons =
lazy
(let child_origin = Markdown_lite.md_codify @@ Render.strip_ns origin
and parent_origin =
Markdown_lite.md_codify @@ Render.strip_ns parent_origin
and class_ = Markdown_lite.md_codify @@ Render.strip_ns class_name
and name = Markdown_lite.md_codify name in
[
( pos,
child_origin
^ " and "
^ parent_origin
^ " both declare ambiguous implementations of "
^ name
^ "." );
(pos, child_origin ^ "'s definition is here.");
(parent_pos, parent_origin ^ "'s definition is here.");
( pos,
"Redeclare "
^ name
^ " in "
^ class_
^ " with a compatible signature." );
])
in
(Error_code.MultipleConcreteDefs, reasons)
let cyclic_enum_constraint pos =
let reasons = lazy [(pos, "Cyclic enum constraint")] in
(Error_code.CyclicEnumConstraint, reasons)
let inoutness_mismatch pos decl_pos =
let reasons =
lazy
[
(pos, "This is an `inout` parameter");
(decl_pos, "It is incompatible with a normal parameter");
]
in
(Error_code.InoutnessMismatch, reasons)
let decl_override_missing_hint pos =
let reasons =
lazy
[
( pos,
"When redeclaring class members, both declarations must have a typehint"
);
]
in
(Error_code.DeclOverrideMissingHint, reasons)
let bad_lateinit_override pos parent_pos parent_is_lateinit =
let reasons =
lazy
(let verb =
if parent_is_lateinit then
"is"
else
"is not"
in
[
( pos,
"Redeclared properties must be consistently declared `__LateInit`"
);
(parent_pos, "The property " ^ verb ^ " declared `__LateInit` here");
])
in
(Error_code.BadLateInitOverride, reasons)
let bad_xhp_attr_required_override pos parent_pos parent_tag tag =
let reasons =
lazy
[
(pos, "Redeclared attribute must not be less strict");
( parent_pos,
"The attribute is " ^ parent_tag ^ ", which is stricter than " ^ tag
);
]
in
(Error_code.BadXhpAttrRequiredOverride, reasons)
let coeffect_subtyping pos cap pos_expected cap_expected =
let reasons =
lazy
[
( pos_expected,
"Expected a function that requires " ^ Lazy.force cap_expected );
(pos, "But got a function that requires " ^ Lazy.force cap);
]
in
(Error_code.SubtypeCoeffects, reasons)
let not_sub_dynamic pos ty_name dynamic_part =
let reasons =
Lazy.map dynamic_part ~f:(fun xs ->
xs
@ [
( pos,
"Type "
^ (Markdown_lite.md_codify @@ Lazy.force ty_name)
^ " is not a subtype of `dynamic` under dynamic-aware subtyping"
);
])
in
(Error_code.UnifyError, reasons)
let override_method_support_dynamic_type
pos method_name parent_origin parent_pos =
let reasons =
lazy
[
( pos,
"Method "
^ method_name
^ " must be declared <<__SupportDynamicType>> because it overrides method in class "
^ Render.strip_ns parent_origin
^ " which does." );
(parent_pos, "Overridden method is defined here.");
]
in
(Error_code.ImplementsDynamic, reasons)
let readonly_mismatch pos kind reason_sub reason_super =
let reasons =
Lazy.(
reason_sub >>= fun reason_sub ->
reason_super >>= fun reason_super ->
return
(( pos,
match kind with
| `fn -> "Function readonly mismatch"
| `fn_return -> "Function readonly return mismatch"
| `param -> "Mismatched parameter readonlyness" )
:: reason_sub
@ reason_super))
in
(Error_code.ReadonlyMismatch, reasons)
let cross_package_mismatch pos reason_sub reason_super =
let reasons =
Lazy.(
reason_sub >>= fun reason_sub ->
reason_super >>= fun reason_super ->
return (((pos, "Cross package mismatch") :: reason_sub) @ reason_super))
in
(Error_code.InvalidCrossPackage, reasons)
let typing_too_many_args pos decl_pos actual expected =
let (code, claim, reasons) =
Common.typing_too_many_args pos decl_pos actual expected
in
let reasons =
Lazy.(
claim >>= fun x ->
reasons >>= fun xs -> return (x :: xs))
in
(code, reasons)
let typing_too_few_args pos decl_pos actual expected =
let (code, claim, reasons) =
Common.typing_too_few_args pos decl_pos actual expected
in
let reasons =
Lazy.(
claim >>= fun x ->
reasons >>= fun xs -> return (x :: xs))
in
(code, reasons)
let non_object_member pos ctxt ty_name member_name kind decl_pos =
let (code, claim, reasons) =
Common.non_object_member
pos
ctxt
(Lazy.force ty_name)
member_name
kind
decl_pos
in
let reasons =
Lazy.(
claim >>= fun x ->
reasons >>= fun xs -> return (x :: xs))
in
(code, reasons)
let rigid_tvar_escape pos name =
( Error_code.RigidTVarEscape,
lazy [(pos, "Rigid type variable " ^ name ^ " is escaping")] )
let smember_not_found pos kind member_name class_name class_pos hint =
let (code, claim, reasons) =
Common.smember_not_found pos kind member_name class_name class_pos hint
in
let reasons =
Lazy.(
claim >>= fun x ->
reasons >>= fun xs -> return (x :: xs))
in
(code, reasons)
let bad_method_override pos member_name =
let reasons =
lazy
[
( pos,
"The method "
^ (Render.strip_ns member_name |> Markdown_lite.md_codify)
^ " is not compatible with the overridden method" );
]
in
(Error_code.BadMethodOverride, reasons)
let bad_prop_override pos member_name =
let reasons =
lazy
[
( pos,
"The property "
^ (Render.strip_ns member_name |> Markdown_lite.md_codify)
^ " has the wrong type" );
]
in
(Error_code.BadMethodOverride, reasons)
let method_not_dynamically_callable pos parent_pos =
let reasons =
lazy
[
(parent_pos, "This method is `__DynamicallyCallable`.");
(pos, "This method is **not**.");
]
in
(Error_code.BadMethodOverride, reasons)
let this_final pos_sub pos_super class_name =
let reasons =
lazy
(let n = Render.strip_ns class_name |> Markdown_lite.md_codify in
let message1 = "Since " ^ n ^ " is not final" in
let message2 = "this might not be a " ^ n in
[(pos_super, message1); (pos_sub, message2)])
in
(Error_code.ThisFinal, reasons)
let typeconst_concrete_concrete_override pos parent_pos =
( Error_code.TypeconstConcreteConcreteOverride,
lazy
[
(pos, "Cannot re-declare this type constant");
(parent_pos, "Previously defined here");
] )
let abstract_concrete_override pos parent_pos kind =
let reasons =
lazy
(let kind_str =
match kind with
| `method_ -> "method"
| `typeconst -> "type constant"
| `constant -> "constant"
| `property -> "property"
in
[
(pos, "Cannot re-declare this " ^ kind_str ^ " as abstract");
(parent_pos, "Previously defined here");
])
in
(Error_code.AbstractConcreteOverride, reasons)
let override_no_default_typeconst pos parent_pos =
( Error_code.OverrideNoDefaultTypeconst,
lazy
[
(pos, "This abstract type constant does not have a default type");
( parent_pos,
"It cannot override an abstract type constant that has a default type"
);
] )
let unsupported_refinement pos =
( Error_code.UnsupportedRefinement,
lazy [(pos, "Unsupported refinement, only class types can be refined")] )
let missing_class_constant pos class_name const_name =
( Error_code.SmemberNotFound,
lazy
[
( pos,
Printf.sprintf
"Class %s has no constant %s"
(Render.strip_ns class_name |> Markdown_lite.md_codify)
(Markdown_lite.md_codify const_name) );
] )
let invalid_refined_const_kind
pos class_name const_name correct_kind wrong_kind =
( Error_code.InvalidRefinedConstKind,
lazy
[
( pos,
Printf.sprintf
"Constant %s in %s is not a %s, did you mean %s?"
(Markdown_lite.md_codify const_name)
(Render.strip_ns class_name |> Markdown_lite.md_codify)
wrong_kind
correct_kind );
] )
let inexact_tconst_access pos id =
( Error_code.InexactTConstAccess,
lazy
[
(fst id, "Type member `" ^ snd id ^ "` cannot be accessed");
(pos, " on a loose refinement");
] )
let violated_refinement_constraint (kind, pos) =
let kind =
match kind with
| `As -> "`as` or `=`"
| `Super -> "`super`"
in
( Error_code.UnifyError,
lazy [(pos, "This " ^ kind ^ " refinement constraint is violated")] )
let eval t ~env ~current_span =
let open Typing_error.Secondary in
match t with
| Of_error err ->
Eval_result.map ~f:(fun (code, claim, reasons, _quickfixes) ->
(* We discard quickfixes here because a secondary error
can be in a decl and it doesn't make sense to quickfix a decl *)
let reasons =
Lazy.(
claim >>= fun x ->
reasons >>= fun xs ->
return (Message.map ~f:Pos_or_decl.of_raw_pos x :: xs))
in
(code, reasons))
@@ Eval_error.eval err ~env ~current_span
| Fun_too_many_args { pos; decl_pos; actual; expected } ->
Eval_result.single (fun_too_many_args pos decl_pos actual expected)
| Fun_too_few_args { pos; decl_pos; actual; expected } ->
Eval_result.single (fun_too_few_args pos decl_pos actual expected)
| Fun_unexpected_nonvariadic { pos; decl_pos } ->
Eval_result.single (fun_unexpected_nonvariadic pos decl_pos)
| Fun_variadicity_hh_vs_php56 { pos; decl_pos } ->
Eval_result.single (fun_variadicity_hh_vs_php56 pos decl_pos)
| Type_arity_mismatch { pos; actual; decl_pos; expected } ->
Eval_result.single (type_arity_mismatch pos actual decl_pos expected)
| Violated_constraint { cstrs; ty_sub; ty_sup; is_coeffect } ->
Eval_result.single
(violated_constraint cstrs is_coeffect ~ty_sub ~ty_sup env)
| Concrete_const_interface_override { pos; parent_pos; name; parent_origin }
->
Eval_result.single
(concrete_const_interface_override pos parent_pos name parent_origin)
| Interface_or_trait_const_multiple_defs
{ pos; origin; parent_pos; parent_origin; name } ->
Eval_result.single
(interface_or_trait_const_multiple_defs
pos
origin
parent_pos
parent_origin
name)
| Interface_typeconst_multiple_defs
{ pos; parent_pos; name; origin; parent_origin; is_abstract } ->
Eval_result.single
(interface_typeconst_multiple_defs
pos
parent_pos
name
origin
parent_origin
is_abstract)
| Missing_field { pos; name; decl_pos } ->
Eval_result.single (missing_field pos name decl_pos)
| Shape_fields_unknown { pos; decl_pos } ->
Eval_result.single (shape_fields_unknown pos decl_pos)
| Abstract_tconst_not_allowed { pos; decl_pos; tconst_name } ->
Eval_result.single (abstract_tconst_not_allowed pos decl_pos tconst_name)
| Invalid_destructure { pos; decl_pos; ty_name } ->
Eval_result.single (invalid_destructure pos decl_pos ty_name)
| Unpack_array_required_argument { pos; decl_pos } ->
Eval_result.single (unpack_array_required_argument pos decl_pos)
| Unpack_array_variadic_argument { pos; decl_pos } ->
Eval_result.single (unpack_array_variadic_argument pos decl_pos)
| Overriding_prop_const_mismatch { pos; is_const; parent_pos; _ } ->
Eval_result.single
(overriding_prop_const_mismatch pos is_const parent_pos)
| Visibility_extends { pos; vis; parent_pos; parent_vis } ->
Eval_result.single (visibility_extends pos vis parent_pos parent_vis)
| Visibility_override_internal
{ pos; module_name; parent_module; parent_pos } ->
Eval_result.single
(visibility_override_internal pos module_name parent_module parent_pos)
| Missing_constructor pos -> Eval_result.single (missing_constructor pos)
| Accept_disposable_invariant { pos; decl_pos } ->
Eval_result.single (accept_disposable_invariant pos decl_pos)
| Ifc_external_contravariant { pos_sub; pos_super } ->
Eval_result.single (ifc_external_contravariant pos_sub pos_super)
| Required_field_is_optional { pos; name; decl_pos; def_pos } ->
Eval_result.single (required_field_is_optional pos name decl_pos def_pos)
| Return_disposable_mismatch
{ pos_sub; is_marked_return_disposable; pos_super } ->
Eval_result.single
(return_disposable_mismatch
pos_sub
is_marked_return_disposable
pos_super)
| Ifc_policy_mismatch { pos; policy; pos_super; policy_super } ->
Eval_result.single (ifc_policy_mismatch pos policy pos_super policy_super)
| Override_final { pos; parent_pos } ->
Eval_result.single (override_final pos parent_pos)
| Override_async { pos; parent_pos } ->
Eval_result.single (override_async pos parent_pos)
| Override_lsb { pos; member_name; parent_pos } ->
Eval_result.single (override_lsb pos member_name parent_pos)
| Multiple_concrete_defs
{ pos; origin; name; parent_pos; parent_origin; class_name } ->
Eval_result.single
(multiple_concrete_defs
pos
origin
name
parent_pos
parent_origin
class_name)
| Cyclic_enum_constraint pos ->
Eval_result.single (cyclic_enum_constraint pos)
| Inoutness_mismatch { pos; decl_pos } ->
Eval_result.single (inoutness_mismatch pos decl_pos)
| Decl_override_missing_hint pos ->
Eval_result.single (decl_override_missing_hint pos)
| Bad_lateinit_override { pos; parent_pos; parent_is_lateinit } ->
Eval_result.single
(bad_lateinit_override pos parent_pos parent_is_lateinit)
| Bad_xhp_attr_required_override { pos; parent_pos; parent_tag; tag } ->
Eval_result.single
(bad_xhp_attr_required_override pos parent_pos parent_tag tag)
| Coeffect_subtyping { pos; cap; pos_expected; cap_expected } ->
Eval_result.single (coeffect_subtyping pos cap pos_expected cap_expected)
| Not_sub_dynamic { pos; ty_name; dynamic_part } ->
Eval_result.single (not_sub_dynamic pos ty_name dynamic_part)
| Override_method_support_dynamic_type
{ pos; method_name; parent_origin; parent_pos } ->
Eval_result.single
(override_method_support_dynamic_type
pos
method_name
parent_origin
parent_pos)
| Readonly_mismatch { pos; kind; reason_sub; reason_super } ->
Eval_result.single (readonly_mismatch pos kind reason_sub reason_super)
| Cross_package_mismatch { pos; reason_sub; reason_super } ->
Eval_result.single (cross_package_mismatch pos reason_sub reason_super)
| Typing_too_many_args { pos; decl_pos; actual; expected } ->
Eval_result.single (typing_too_many_args pos decl_pos actual expected)
| Typing_too_few_args { pos; decl_pos; actual; expected } ->
Eval_result.single (typing_too_few_args pos decl_pos actual expected)
| Non_object_member { pos; ctxt; ty_name; member_name; kind; decl_pos } ->
Eval_result.single
(non_object_member pos ctxt ty_name member_name kind decl_pos)
| Rigid_tvar_escape { pos; name } ->
Eval_result.single (rigid_tvar_escape pos name)
| Smember_not_found { pos; kind; member_name; class_name; class_pos; hint }
->
Eval_result.single
(smember_not_found pos kind member_name class_name class_pos hint)
| Bad_method_override { pos; member_name } ->
Eval_result.single (bad_method_override pos member_name)
| Bad_prop_override { pos; member_name } ->
Eval_result.single (bad_prop_override pos member_name)
| Subtyping_error { ty_sub; ty_sup; is_coeffect } ->
Eval_result.single (subtyping_error is_coeffect ~ty_sub ~ty_sup env)
| Method_not_dynamically_callable { pos; parent_pos } ->
Eval_result.single (method_not_dynamically_callable pos parent_pos)
| This_final { pos_sub; pos_super; class_name } ->
Eval_result.single (this_final pos_sub pos_super class_name)
| Typeconst_concrete_concrete_override { pos; parent_pos } ->
Eval_result.single (typeconst_concrete_concrete_override pos parent_pos)
| Abstract_concrete_override { pos; parent_pos; kind } ->
Eval_result.single (abstract_concrete_override pos parent_pos kind)
| Override_no_default_typeconst { pos; parent_pos } ->
Eval_result.single (override_no_default_typeconst pos parent_pos)
| Unsupported_refinement pos ->
Eval_result.single (unsupported_refinement pos)
| Missing_class_constant { pos; class_name; const_name } ->
Eval_result.single (missing_class_constant pos class_name const_name)
| Invalid_refined_const_kind
{ pos; class_name; const_name; correct_kind; wrong_kind } ->
Eval_result.single
(invalid_refined_const_kind
pos
class_name
const_name
correct_kind
wrong_kind)
| Inexact_tconst_access (pos, id) ->
Eval_result.single (inexact_tconst_access pos id)
| Violated_refinement_constraint { cstr } ->
Eval_result.single (violated_refinement_constraint cstr)
end
and Eval_callback : sig
val apply :
?code:Error_code.t ->
?reasons:Pos_or_decl.t Message.t list Lazy.t ->
?quickfixes:Pos.t Quickfix.t list ->
Typing_error.Callback.t ->
env:Typing_env_types.env ->
claim:Pos.t Message.t Lazy.t ->
error
end = struct
type error_state = {
code_opt: Error_code.t option;
claim_opt: Pos.t Message.t Lazy.t option;
reasons: Pos_or_decl.t Message.t list Lazy.t;
quickfixes: Pos.t Quickfix.t list;
}
let rec eval t ~env ~st =
let open Typing_error.Callback in
match t with
| With_side_effect (t, eff) ->
eff ();
eval t ~env ~st
| Always err ->
let (code, claim, reasons, quickfixes) = Eval_primary.to_error err ~env in
(code, Some claim, reasons, quickfixes)
| Of_primary err ->
let (code, _claim, _reasons, qfs) = Eval_primary.to_error err ~env in
( Option.value ~default:code st.code_opt,
st.claim_opt,
st.reasons,
qfs @ st.quickfixes )
| With_claim_as_reason (err, claim_from) ->
let reasons =
Option.value_map
~default:st.reasons
~f:(fun claim ->
Lazy.(
claim >>= fun claim ->
st.reasons >>= fun reasons ->
return (Tuple2.map_fst ~f:Pos_or_decl.of_raw_pos claim :: reasons)))
st.claim_opt
in
let (_, claim, _, _) = Eval_primary.to_error claim_from ~env in
eval err ~env ~st:{ st with claim_opt = Some claim; reasons }
| Retain_code t -> eval t ~env ~st:{ st with code_opt = None }
| With_code (code, qfs) ->
( Option.value ~default:code st.code_opt,
st.claim_opt,
st.reasons,
qfs @ st.quickfixes )
let apply ?code ?(reasons = lazy []) ?(quickfixes = []) t ~env ~claim =
let st = { code_opt = code; claim_opt = Some claim; reasons; quickfixes } in
let (code, claim_opt, reasons, quickfixes) = eval t ~env ~st in
(code, Option.value ~default:claim claim_opt, reasons, quickfixes)
end
and Eval_reasons_callback : sig
val apply_help :
?code:Error_code.t ->
?claim:Pos.t Message.t Lazy.t ->
?reasons:Pos_or_decl.t Message.t list Lazy.t ->
?quickfixes:Pos.t Quickfix.t list ->
Typing_error.Reasons_callback.t ->
env:Typing_env_types.env ->
current_span:Pos.t ->
error Eval_result.t
val apply :
?code:Error_code.t ->
?claim:Pos.t Message.t Lazy.t ->
?reasons:Pos_or_decl.t Message.t list Lazy.t ->
?quickfixes:Pos.t Quickfix.t list ->
Typing_error.Reasons_callback.t ->
env:Typing_env_types.env ->
current_span:Pos.t ->
(Pos.t, Pos_or_decl.t) User_error.t Eval_result.t
end = struct
module Error_state = struct
type t = {
code_opt: Error_code.t option;
claim_opt: Pos.t Message.t Lazy.t option;
reasons_opt: Pos_or_decl.t Message.t list Lazy.t option;
quickfixes_opt: Pos.t Quickfix.t list option;
}
let with_code t code_opt =
{ t with code_opt = Option.first_some t.code_opt code_opt }
let prepend_secondary
{ claim_opt; reasons_opt; quickfixes_opt; _ } snd_err ~env ~current_span
=
Eval_result.map
(Eval_secondary.eval snd_err ~env ~current_span)
~f:(fun (code, reasons) ->
let reasons_opt =
Some
(match reasons_opt with
| None -> lazy []
| Some rlz ->
Lazy.(
rlz >>= fun rlz ->
reasons >>= fun reasons -> return (reasons @ rlz)))
in
{ code_opt = Some code; claim_opt; reasons_opt; quickfixes_opt })
(** Replace any missing values in the error state with those of the error *)
let with_defaults
{ code_opt; claim_opt; reasons_opt; quickfixes_opt }
err
~env
~current_span =
Eval_result.map ~f:(fun (code, claim, reasons, quickfixes) ->
Option.
( value code_opt ~default:code,
value claim_opt ~default:claim,
value reasons_opt ~default:reasons,
value quickfixes_opt ~default:quickfixes ))
@@ Eval_error.eval err ~env ~current_span
end
let eval_callback
k Error_state.{ code_opt; reasons_opt; quickfixes_opt; _ } ~env ~claim =
Eval_callback.apply
?code:code_opt
?reasons:reasons_opt
?quickfixes:quickfixes_opt
~env
~claim
k
let eval t ~env ~st ~current_span =
let open Typing_error.Reasons_callback in
let rec aux t st =
match t with
| From_on_error f ->
let code = Option.map ~f:Error_code.to_enum st.Error_state.code_opt
and quickfixes = st.Error_state.quickfixes_opt
and reasons =
Option.value_map ~default:[] ~f:Lazy.force st.Error_state.reasons_opt
in
f ?code ?quickfixes reasons;
Eval_result.empty
| Always err -> Eval_error.eval err ~env ~current_span
| Of_error err -> Error_state.with_defaults st err ~env ~current_span
| Of_callback (k, claim) ->
Eval_result.single @@ eval_callback k st ~env ~claim
| Assert_in_current_decl (default, ctx) ->
let Error_state.{ code_opt; reasons_opt; _ } = st in
let crs =
Option.(value ~default code_opt, value ~default:(lazy []) reasons_opt)
in
let res_opt = Common.eval_assert ctx current_span crs in
Eval_result.of_option res_opt
| With_code (err, code) ->
let st = Error_state.with_code st @@ Some code in
aux err st
| With_reasons (err, reasons) ->
aux err Error_state.{ st with reasons_opt = Some reasons }
| Add_quickfixes (err, qfxs) ->
aux
err
Error_state.
{
st with
quickfixes_opt =
Option.first_some
(Option.map ~f:(List.append qfxs) st.quickfixes_opt)
(Some qfxs);
}
| Add_reason (err, op, reason) -> aux_reason_op op err reason st
| Retain (t, comp) -> aux_retain t comp st
| Incoming_reasons (err, op) ->
Eval_result.map ~f:(fun ((code, claim, reasons, qfxs) as err) ->
match (st.Error_state.reasons_opt, op) with
| (None, _) -> err
| (Some rs, Append) ->
(code, claim, Common.map2 ~f:(fun x y -> x @ y) reasons rs, qfxs)
| (Some rs, Prepend) ->
(code, claim, Common.map2 ~f:(fun x y -> x @ y) rs reasons, qfxs))
@@ aux err Error_state.{ st with reasons_opt = None }
| Prepend_on_apply (t, snd_err) ->
Eval_result.bind
~f:(aux t)
(Error_state.prepend_secondary st snd_err ~env ~current_span)
| Drop_reasons_on_apply t ->
let st = Error_state.{ st with reasons_opt = Some (lazy []) } in
aux t st
[@@ocaml.warning "-3"]
and aux_reason_op op err base_reason (Error_state.{ reasons_opt; _ } as st)
=
let reasons_opt =
Some
(match reasons_opt with
| None -> Lazy.map base_reason ~f:(fun x -> [x])
| Some reasons_lz ->
(match op with
| Append ->
Lazy.(
reasons_lz >>= fun rs ->
base_reason >>= fun r -> return (rs @ [r]))
| Prepend ->
Lazy.(
reasons_lz >>= fun rs ->
base_reason >>= fun r -> return (r :: rs))))
in
aux err Error_state.{ st with reasons_opt }
and aux_retain t comp st =
match comp with
| Code -> aux t Error_state.{ st with code_opt = None }
| Reasons -> aux t Error_state.{ st with reasons_opt = None }
| Quickfixes -> aux t Error_state.{ st with quickfixes_opt = None }
in
aux t st
let apply_help ?code ?claim ?reasons ?quickfixes t ~env ~current_span =
let claim =
Option.map claim ~f:(Lazy.map ~f:(Message.map ~f:Pos_or_decl.of_raw_pos))
in
let reasons_opt =
match (claim, reasons) with
| (Some claim, Some reasons) ->
Some (Common.map2 claim reasons ~f:(fun x xs -> x :: xs))
| (Some claim, _) -> Some (Lazy.map ~f:(fun claim -> [claim]) claim)
| _ -> reasons
in
eval
t
~env
~st:
Error_state.
{
code_opt = code;
claim_opt = None;
reasons_opt;
quickfixes_opt = quickfixes;
}
~current_span
let apply ?code ?claim ?reasons ?quickfixes t ~env ~current_span =
let f (code, claim, reasons, quickfixes) =
User_error.make
(Error_code.to_enum code)
(Lazy.force claim)
(Lazy.force reasons)
~quickfixes
in
Eval_result.map ~f
@@ apply_help ?code ?claim ?reasons ?quickfixes t ~env ~current_span
end
let is_suppressed User_error.{ claim; code; _ } =
Errors.fixme_present Message.(get_message_pos claim) code
let add_typing_error err ~env =
Eval_result.iter ~f:Errors.add_error
@@ Eval_result.suppress_intersection ~is_suppressed
@@ Eval_error.to_user_error
err
~env
~current_span:(Errors.get_current_span ())
(* Until we return a list of errors from typing, we have to apply
'client errors' to a callback for using in subtyping *)
let apply_callback_to_errors errors on_error ~env =
let on_error
User_error.
{ code; claim; reasons; custom_msgs = _; quickfixes = _; is_fixmed = _ }
=
let code = Option.value_exn (Error_code.of_enum code) in
Eval_result.iter ~f:Errors.add_error
@@ Eval_result.suppress_intersection ~is_suppressed
@@ Eval_reasons_callback.apply
on_error
~code
~claim:(lazy claim)
~reasons:(lazy reasons)
~env
~current_span:(Errors.get_current_span ())
in
Errors.iter errors ~f:on_error
let apply_error_from_reasons_callback ?code ?claim ?reasons ?quickfixes err ~env
=
Eval_result.iter ~f:Errors.add_error
@@ Eval_result.suppress_intersection ~is_suppressed
@@ Eval_reasons_callback.apply
?code
?claim
?reasons
?quickfixes
err
~env
~current_span:(Errors.get_current_span ())
let claim_as_reason : Pos.t Message.t -> Pos_or_decl.t Message.t =
(fun (p, m) -> (Pos_or_decl.of_raw_pos p, m))
(** TODO: Remove use of `User_error.t` representation for nested error &
callback application *)
let ambiguous_inheritance pos class_ origin error on_error ~env =
let User_error.
{ code; claim; reasons; custom_msgs = _; quickfixes = _; is_fixmed = _ }
=
error
in
let origin = Render.strip_ns origin in
let class_ = Render.strip_ns class_ in
let message =
"This declaration was inherited from an object of type "
^ Markdown_lite.md_codify origin
^ ". Redeclare this member in "
^ Markdown_lite.md_codify class_
^ " with a compatible signature."
in
let code = Option.value_exn (Error_codes.Typing.of_enum code) in
apply_error_from_reasons_callback
on_error
~code
~reasons:(lazy ((claim_as_reason claim :: reasons) @ [(pos, message)]))
~env |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_error_utils.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val add_typing_error : Typing_error.t -> env:Typing_env_types.env -> unit
val apply_error_from_reasons_callback :
?code:Error_codes.Typing.t ->
?claim:Pos.t Message.t Lazy.t ->
?reasons:Pos_or_decl.t Message.t list Lazy.t ->
?quickfixes:Pos.t Quickfix.t list ->
Typing_error.Reasons_callback.t ->
env:Typing_env_types.env ->
unit
val apply_callback_to_errors :
Errors.t ->
Typing_error.Reasons_callback.t ->
env:Typing_env_types.env ->
unit
val ambiguous_inheritance :
Pos_or_decl.t ->
string ->
string ->
(Pos.t, Pos_or_decl.t) User_error.t ->
Typing_error.Reasons_callback.t ->
env:Typing_env_types.env ->
unit |
OCaml | hhvm/hphp/hack/src/typing/typing_escape.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Common
open Typing_defs
module Cls = Decl_provider.Class
module Env = Typing_env
module ITySet = Internal_type_set
module Reason = Typing_reason
module TUtils = Typing_utils
module TySet = Typing_set
(** This module contains functions to clear rigid type variables from types
and from the inference environment. We say that a type variable is
"rigid" when it only unifies with itself. Examples of such type variables
include type parameters and expression-dependent types. Any such rigid
type variable needs to be cleared after type-checking lambdas & loops
for soundness.
*)
(* Here is an example program that would bogusly type check if we did not
clear rigid type variables properly:
$f = (mixed $arg) ==> ($arg as Box<_>);
$bs = $f($str_box as mixed) : Box<T#1>
$bi = $f($int_box as mixed) : Box<T#1> // unsound!
$bi->set($bs->get()); // should not work
We do not want the type of the two calls to $f to unify; this module
prevents unsoundness by clearing T#1 from the result of the lambda.
In this particular case, an error is generated.
*)
(* TODO(T92111151): Adding existential types to Hack locl types might
help in simplifying the logic below by harnessing Typing_subtype.
Namely, elimination of a rigid type T#1 in a type C[T#1] would
simply quantify T#1 away (preserving its constraints).
*)
type rigid_tvar =
| Rtv_tparam of string
| Rtv_dependent of Ident.t
(********************************************************************)
(* Eliminating rigid type variables *)
(********************************************************************)
(* Many languages cannot "eliminate" escaping types and will simply raise
an error when such an escape happens. In Hack, we can do a bit better
using subtyping. For example, if a lambda returns [vec<T#1>] where
T#1 must be eliminated, we can type the return value as [vec<mixed>]
instead, or [vec<Foo>] if we happen to know that T#1 <: Foo. More
generally, a type T to be eliminated can be replaced with the
intersection of its upper bounds in covariant position, and with the
union of its lower bounds in contravariant positions. This replacement
is what the [eliminate] function performs.
Because Hack is effectful, it is not sufficient to eliminate rigid type
variables in the return type of lambdas, we must also make sure they
do not escape in bounds of type variables that existed before typing
a lambda. For example, consider:
$v = Vector{}
$f = (mixed $x) ==> {
invariant($x is Box<_>, "");
$v[] = $x->get();
}
// we do not want $v : Vector<T#1>; instead we want Vector<mixed>
Improper rigid type variables handling would lead $v to have type
Vector<T#1> leaving the door open to soundness holes. To prevent this
problem we provide [refresh_*] functions that act on the inference
environment. When doing so the question of the variance in constraints
comes in.
Inference can be understood as producing the following result: "under the
constraints C on tyvars, the program P has type T"; which we will write
more compactly as [C ==> P:T]. You can see that C stands on the LHS of an
implication, i.e., it is in *contravariant* position. This amounts to
remarking that if C' is such that C'[tvs] ==> C[tvs] for all tvs then
[C ==> P:T] implies [C' ==> P:T]. Consequently, it is always sound to
make a constraints set stronger (harder to satisfy). Concretely, if we
have a type variable #2021 with constraint #2021 <: arraykey, we can
soundly replace the constraint with #2021 <: int; that is: upper bounds
of type variables are *contravariant*. Dually, lower bounds are
*covariant*. This remark underpins the implementation of [refresh_tvar].
*)
type elim_info = {
pos: Pos_or_decl.t;
upper_bounds: TySet.t;
lower_bounds: TySet.t;
}
type remove_map = rigid_tvar -> elim_info option
type refresh_env = {
env: Typing_env_types.env; (** the underlying typing env *)
tvars: Typing_error.Reasons_callback.t IMap.t;
(** an accumulator used to remember all the type variabes
that appeared when refreshing a type; the map is used as a
set, and error callbacks are merely used for reporting *)
remove: remove_map;
(** the list of all the type parameters to eliminate with their
bounds *)
on_error: Typing_error.Reasons_callback.t;
(** sometimes eliminating a rigid type is not possible and we must
surface an error to the user *)
scope_kind: string * Pos.t;
(** a string and position describing the language construct for which
we are preventing escapes (e.g., "lambda") *)
elim_bogus_taccess: bool;
(** a boolean indicating whether or not the elimination procedure
should eliminate bogus Tgenerics of the form A::T where T is
an abstract const type in A
TODO(T91765587): kill bogus type access generics *)
}
(* refresh_ functions will return [Elim ...] when they eliminated a rigid
type variable from their result. [Unchanged] is returned when nothing
has changed in the data to refresh. *)
type changed =
| Elim of Pos_or_decl.t * string
| Unchanged
(* Using [with_default], all the refresh_ functions take care of returning
*exactly* their argument if the refreshing did not change anything.
I conjecture that this plays nice with the GC: if nothing changes all the
temporary fresh objects will sit root-less in the minor heap and get
collected for very cheap. If we instead used the fresh results as
replacements of the originals we would create roots for them and may
eventually have to collect the original copies with a constly compaction
of the major heap *)
let with_default ~default (renv, res, changed) =
match changed with
| Elim _ -> (renv, res, changed)
| Unchanged -> (renv, default, Unchanged)
let ( || ) ch1 ch2 =
match ch1 with
| Elim _ -> ch1
| Unchanged -> ch2
let is_bogus_taccess tp =
(* In typing_taccess.ml some type parameters of the form I::T are
generated when T is abstract; these types are bogus and should
be eliminated from our internal data structures but, in the
meantime, we cope with them here by ignoring them.
TODO(T91765587): kill bogus type access generics *)
String.is_substring ~substring:"::" tp && Char.(tp.[0] <> '<')
let rec eliminate ~ty_orig ~rtv_pos ~name ~ubs ~lbs renv v =
let r =
let (what, wpos) = renv.scope_kind in
Reason.Rrigid_tvar_escape (wpos, what, name, get_reason ty_orig)
in
match v with
| Ast_defs.Contravariant ->
let lbs = TySet.elements lbs in
let (env, lbty) = Typing_union.union_list renv.env r lbs in
(* a type that depends on type variables to be eliminated may be
generated by the union computation; so we recursively eliminate
them *)
let elim_bogus_taccess = renv.elim_bogus_taccess in
let renv = { renv with env; elim_bogus_taccess = true } in
let (renv, lbty, _) = refresh_type renv v lbty in
let lbty = with_reason lbty r in
let renv = { renv with elim_bogus_taccess } in
(renv, lbty, Elim (rtv_pos, name))
| Ast_defs.Covariant ->
let ubs = TySet.elements ubs in
let (env, ubty) = Typing_intersection.intersect_list renv.env r ubs in
let elim_bogus_taccess = renv.elim_bogus_taccess in
let renv = { renv with env; elim_bogus_taccess = true } in
(* ditto *)
let (renv, ubty, _) = refresh_type renv v ubty in
let ubty = with_reason ubty r in
let renv = { renv with elim_bogus_taccess } in
(renv, ubty, Elim (rtv_pos, name))
| Ast_defs.Invariant ->
let name = Markdown_lite.md_codify name in
let snd_err =
Typing_error.Secondary.Rigid_tvar_escape { pos = rtv_pos; name }
in
Typing_error_utils.add_typing_error
~env:renv.env
Typing_error.(
apply_reasons
~on_error:(Reasons_callback.retain_code renv.on_error)
snd_err);
(renv, ty_orig, Unchanged)
and refresh_type renv v ty_orig =
let (env, ty) = Env.expand_type renv.env ty_orig in
let renv = { renv with env } in
with_default ~default:ty_orig
@@
match deref ty with
| (_, (Tany _ | Tnonnull | Tdynamic | Tprim _ | Tunapplied_alias _ | Tneg _))
->
(renv, ty_orig, Unchanged)
| (r, Toption ty1) ->
let (renv, ty1, changed) = refresh_type renv v ty1 in
(renv, mk (r, Toption ty1), changed)
| (r, Tfun ft) ->
let enforced_ty (renv, changed) v ({ et_type; et_enforced = _ } as et) =
let (renv, et_type, changed') = refresh_type renv v et_type in
((renv, changed || changed'), { et with et_type })
in
let param_v = Ast_defs.swap_variance v in
let ft_param
renvch ({ fp_type; fp_pos = _; fp_name = _; fp_flags = _ } as fp) =
let (renvch, fp_type) = enforced_ty renvch param_v fp_type in
(renvch, { fp with fp_type })
in
let (renvch, ft_params) =
List.map_env (renv, Unchanged) ft.ft_params ~f:ft_param
in
let ((renv, changed), ft_ret) = enforced_ty renvch v ft.ft_ret in
(renv, mk (r, Tfun { ft with ft_params; ft_ret }), changed)
| (r, Ttuple l) ->
let (renv, l, changed) = refresh_types renv v l in
(renv, mk (r, Ttuple l), changed)
| (r, Tshape { s_origin = _; s_unknown_value = sk; s_fields = sm }) ->
let (renv, sm, ch) =
TShapeMap.fold
(fun sfn { sft_optional; sft_ty } (renv, sm, ch) ->
let (renv, sft_ty, ch') = refresh_type renv v sft_ty in
let sm = TShapeMap.add sfn { sft_optional; sft_ty } sm in
(renv, sm, ch || ch'))
sm
(renv, TShapeMap.empty, Unchanged)
in
( renv,
mk
( r,
Tshape
{
s_origin = Missing_origin;
s_unknown_value = sk;
(* TODO(shapes) refresh_type s_unknown_value *)
s_fields = sm;
} ),
ch )
| (_, Tvar v) ->
let renv = { renv with tvars = IMap.add v renv.on_error renv.tvars } in
(renv, ty_orig, Unchanged)
| (r, Tgeneric (name, _ (* TODO(T70068435) assumes no args *))) -> begin
(* look if the Tgeneric has to go away and kill it using its
bounds if the variance of the current occurrence permits it *)
match renv.remove (Rtv_tparam name) with
| None -> (renv, ty_orig, Unchanged)
| Some _ when is_bogus_taccess name && not renv.elim_bogus_taccess ->
(renv, ty_orig, Unchanged)
| Some { pos; lower_bounds = lbs; upper_bounds = ubs } ->
let rtv_pos =
if Pos_or_decl.(equal pos none) then
Reason.to_pos r
else
pos
in
eliminate ~ty_orig ~rtv_pos ~name ~ubs ~lbs renv v
end
| (r, Tdependent ((DTexpr id as dt), ty1)) -> begin
match renv.remove (Rtv_dependent id) with
| None ->
let (renv, ty1, ch1) = refresh_type renv v ty1 in
(renv, mk (r, Tdependent (dt, ty1)), ch1)
| Some _ ->
let lbs = TySet.empty in
let ubs = TySet.singleton ty1 in
let rtv_pos = Reason.to_pos r in
let name = DependentKind.to_string dt in
eliminate ~ty_orig ~rtv_pos ~name ~ubs ~lbs renv v
end
| (r, Tunion l) ->
let (renv, l, changed) = refresh_types renv v l in
begin
match changed with
| Elim _ ->
let (env, ty) = Typing_union.union_list renv.env r l in
let renv = { renv with env } in
(renv, ty, changed)
| Unchanged -> (renv, ty_orig, Unchanged)
end
| (r, Tintersection l) ->
let (renv, l, changed) = refresh_types renv v l in
begin
match changed with
| Elim _ ->
let (env, ty) = Typing_intersection.intersect_list renv.env r l in
let renv = { renv with env } in
(renv, ty, changed)
| Unchanged -> (renv, ty_orig, Unchanged)
end
| (r, Tvec_or_dict (ty1, ty2)) ->
let (renv, ty1, ch1) = refresh_type renv v ty1 in
let (renv, ty2, ch2) = refresh_type renv v ty2 in
(renv, mk (r, Tvec_or_dict (ty1, ty2)), ch1 || ch2)
| (r, Taccess (ty1, id)) ->
let (renv, ty1, ch1) = refresh_type renv Ast_defs.Invariant ty1 in
(renv, mk (r, Taccess (ty1, id)), ch1)
| (r, Tnewtype (name, l, bnd)) ->
let vl =
match Env.get_typedef env name with
| Some { td_tparams; _ } ->
List.map td_tparams ~f:(fun t -> t.tp_variance)
| None -> List.map l ~f:(fun _ -> Ast_defs.Invariant)
in
let (renv, l, ch) = refresh_types_w_variance renv v vl l in
(renv, mk (r, Tnewtype (name, l, bnd)), ch)
| (r, Tclass ((p, cid), e, l)) ->
let vl =
match Env.get_class env cid with
| None -> List.map l ~f:(fun _ -> Ast_defs.Invariant)
| Some cls -> List.map (Cls.tparams cls) ~f:(fun t -> t.tp_variance)
in
let (renv, l, ch) = refresh_types_w_variance renv v vl l in
(renv, mk (r, Tclass ((p, cid), e, l)), ch)
and refresh_types renv v l =
let rec go renv changed tl acc =
match tl with
| [] -> (renv, List.rev acc, changed)
| ty :: tl ->
let (renv, ty, changed') = refresh_type renv v ty in
go renv (changed || changed') tl (ty :: acc)
in
with_default ~default:l (go renv Unchanged l [])
and refresh_types_w_variance renv v vl tl =
let rec go renv changed vl tl acc =
match (vl, tl) with
| ([], _)
| (_, []) ->
(renv, List.rev acc, changed)
| (var :: vl, ty :: tl) ->
let v =
match var with
| Ast_defs.Invariant -> Ast_defs.Invariant
| Ast_defs.Covariant -> v
| Ast_defs.Contravariant -> Ast_defs.swap_variance v
in
let (renv, ty, changed') = refresh_type renv v ty in
go renv (changed || changed') vl tl (ty :: acc)
in
with_default ~default:tl (go renv Unchanged vl tl [])
let refresh_type_opt renv v tyo =
match tyo with
| None -> (renv, None, Unchanged)
| Some ty ->
let (renv, ty, ch) = refresh_type renv v ty in
(renv, Some ty, ch)
let rec refresh_ctype renv v cty_orig =
let inv = Ast_defs.Invariant in
with_default ~default:cty_orig
@@
match deref_constraint_type cty_orig with
| (r, Thas_member hm) ->
let { hm_type; hm_name = _; hm_class_id = _; hm_explicit_targs = _ } = hm in
let (renv, hm_type, changed) = refresh_type renv inv hm_type in
(renv, mk_constraint_type (r, Thas_member { hm with hm_type }), changed)
| (r, Thas_type_member htm) ->
let { htm_id; htm_lower; htm_upper } = htm in
let v' = Ast_defs.swap_variance v in
let (renv, htm_upper, ch1) = refresh_type renv v htm_upper in
let (renv, htm_lower, ch2) = refresh_type renv v' htm_lower in
let htm = { htm_id; htm_lower; htm_upper } in
(renv, mk_constraint_type (r, Thas_type_member htm), ch1 || ch2)
| (r, Tcan_index ci) ->
let (renv, ci_val, ch1) = refresh_type renv inv ci.ci_val in
let (renv, ci_key, ch2) = refresh_type renv inv ci.ci_key in
( renv,
mk_constraint_type (r, Tcan_index { ci with ci_val; ci_key }),
ch1 || ch2 )
| (r, Tcan_traverse ct) ->
let (renv, ct_val, ch1) = refresh_type renv inv ct.ct_val in
let (renv, ct_key, ch2) =
match ct.ct_key with
| None -> (renv, None, Unchanged)
| Some ct_key ->
let (renv, ct_key, ch2) = refresh_type renv inv ct_key in
(renv, Some ct_key, ch2)
in
( renv,
mk_constraint_type (r, Tcan_traverse { ct with ct_val; ct_key }),
ch1 || ch2 )
| (r, Tdestructure { d_required; d_optional; d_variadic; d_kind }) ->
let (renv, d_required, ch1) = refresh_types renv inv d_required in
let (renv, d_optional, ch2) = refresh_types renv inv d_optional in
let (renv, d_variadic, ch3) = refresh_type_opt renv inv d_variadic in
let des = { d_required; d_optional; d_variadic; d_kind } in
(renv, mk_constraint_type (r, Tdestructure des), ch1 || ch2 || ch3)
| (r, TCunion (lty, cty)) ->
let (renv, lty, ch1) = refresh_type renv v lty in
let (renv, cty, ch2) = refresh_ctype renv v cty in
(renv, mk_constraint_type (r, TCunion (lty, cty)), ch1 || ch2)
| (r, TCintersection (lty, cty)) ->
let (renv, lty, ch1) = refresh_type renv v lty in
let (renv, cty, ch2) = refresh_ctype renv v cty in
(renv, mk_constraint_type (r, TCintersection (lty, cty)), ch1 || ch2)
let refresh_bounds renv v tys =
ITySet.fold
(fun ity (renv, del, add) ->
match ity with
| LoclType lty ->
let (renv, lty, changed) = refresh_type renv v lty in
begin
match changed with
| Unchanged -> (renv, del, add)
| Elim (pos, name) ->
(renv, ITySet.add ity del, (LoclType lty, pos, name) :: add)
end
| ConstraintType cty ->
let (renv, cty, changed) = refresh_ctype renv v cty in
begin
match changed with
| Unchanged -> (renv, del, add)
| Elim (pos, name) ->
(renv, ITySet.add ity del, (ConstraintType cty, pos, name) :: add)
end)
tys
(renv, ITySet.empty, [])
let refresh_tvar tv (on_error : Typing_error.Reasons_callback.t) renv =
(* restore the error context of one local variable causing us to visit
this tvar *)
let renv = { renv with on_error } in
let tv_ity = LoclType (mk (Reason.none, Tvar tv)) in
let elim_on_error pos name =
let name = Markdown_lite.md_codify name in
Some
Typing_error.Reasons_callback.(
with_reasons
~reasons:
(lazy [(pos, "Could not remove rigid type variable " ^ name)])
@@ retain_code
@@ retain_quickfixes on_error)
in
let (renv, e1) =
let ubs = Env.get_tyvar_upper_bounds renv.env tv in
let var = Ast_defs.Contravariant in
let add_bound (env, ty_errs) (ity, pos, name) =
match TUtils.sub_type_i env tv_ity ity (elim_on_error pos name) with
| (env, None) -> (env, ty_errs)
| (env, Some ty_err) -> (env, ty_err :: ty_errs)
in
let (renv, del, add) = refresh_bounds renv var ubs in
if ITySet.is_empty del && List.is_empty add then
(renv, None)
else
let ubs = Env.get_tyvar_upper_bounds renv.env tv in
let ubs = ITySet.diff ubs del in
let env = Env.set_tyvar_upper_bounds renv.env tv ubs in
let (env, ty_errs) = List.fold ~init:(env, []) ~f:add_bound add in
({ renv with env }, Typing_error.multiple_opt ty_errs)
in
let (renv, e2) =
let lbs = Env.get_tyvar_lower_bounds renv.env tv in
let var = Ast_defs.Covariant in
let add_bound (env, ty_errs) (ity, pos, name) =
match TUtils.sub_type_i env ity tv_ity (elim_on_error pos name) with
| (env, None) -> (env, ty_errs)
| (env, Some ty_err) -> (env, ty_err :: ty_errs)
in
let (renv, del, add) = refresh_bounds renv var lbs in
if ITySet.is_empty del && List.is_empty add then
(renv, None)
else
let lbs = Env.get_tyvar_lower_bounds renv.env tv in
let lbs = ITySet.diff lbs del in
let env = Env.set_tyvar_lower_bounds renv.env tv lbs in
let (env, ty_errs) = List.fold ~init:(env, []) ~f:add_bound add in
({ renv with env }, Typing_error.multiple_opt ty_errs)
in
Option.(
iter ~f:(Typing_error_utils.add_typing_error ~env:renv.env)
@@ merge e1 e2 ~f:Typing_error.both);
renv
let rec refresh_tvars seen renv =
if IMap.is_empty renv.tvars then
renv.env
else
let tvars = renv.tvars in
let renv = { renv with tvars = IMap.empty } in
let renv = IMap.fold refresh_tvar tvars renv in
let seen = IMap.fold (fun v _ -> ISet.add v) tvars seen in
let tvars = ISet.fold IMap.remove seen renv.tvars in
let renv = { renv with tvars } in
refresh_tvars seen renv
let refresh_locals renv =
let locals =
match Env.next_cont_opt renv.env with
| None -> Typing_local_types.empty
| Some { Typing_per_cont_env.local_types; _ } -> local_types
in
(* save the original error callback & use it to create one callback
per local in the fold below *)
let on_error = renv.on_error in
Local_id.Map.fold
(fun local
Typing_local_types.{ ty = lty; defined; bound_ty; pos; eid = _ }
renv ->
if defined then
let on_error =
let pos = Pos_or_decl.of_raw_pos pos in
let name = Markdown_lite.md_codify (Local_id.to_string local) in
let reason = lazy (pos, "in the type of local " ^ name) in
Typing_error.Reasons_callback.append_reason on_error ~reason
in
let renv = { renv with on_error } in
let (renv, lty, changed) = refresh_type renv Ast_defs.Covariant lty in
match changed with
| Elim _ ->
{
renv with
env =
Env.set_local ~is_defined:true ~bound_ty renv.env local lty pos;
}
| Unchanged -> renv
else
renv)
locals
renv
let refresh_env_and_type ~remove:(types, remove) ~pos env ty =
if List.is_empty types then
(* nothing to clear, just return the inputs *)
(env, ty)
else (
Typing_log.log_escape
(Pos_or_decl.of_raw_pos pos)
env
"Clearing escaping types:"
types;
let what = "lambda" in
let on_error =
Typing_error.Reasons_callback.rigid_tvar_escape_at pos what
in
let renv =
{
env;
tvars = IMap.empty;
remove;
on_error;
scope_kind = (what, pos);
elim_bogus_taccess = false;
}
in
let renv = refresh_locals renv in
let on_error =
let pos = Pos_or_decl.of_raw_pos pos in
Typing_error.Reasons_callback.append_reason
on_error
~reason:(lazy (pos, "in the return type of this lambda"))
in
let renv = { renv with on_error } in
let (renv, ty, _) = refresh_type renv Ast_defs.Covariant ty in
(refresh_tvars ISet.empty renv, ty)
)
(********************************************************************)
(* Computing escaping types *)
(********************************************************************)
type snapshot = {
tpmap: (Pos_or_decl.t * Typing_kinding_defs.kind) SMap.t;
nextid: int;
(* nextid is used to detect if an expression-dependent type is fresh
or not; we snapshot it at some time and all ids larger than the
snapshot were allocated after the snapshot time *)
}
type escaping_rigid_tvars = string list * remove_map
let snapshot_env env =
let gtp = Type_parameter_env.get_tparams (Env.get_global_tpenv env) in
let ltp = Type_parameter_env.get_tparams (Env.get_tpenv env) in
{ tpmap = SMap.union gtp ltp; nextid = Ident.tmp () }
let escaping_from_snapshot snap env =
let is_global tp =
(* Oh, that's nice... *)
String.length tp > 6 && String.(sub ~pos:0 ~len:6 tp = "this::")
in
let eidmap =
let inverse_map m = IMap.fold (fun k v -> IMap.add v k) m IMap.empty in
inverse_map (Reason.get_expr_display_id_map ())
in
let { nextid; _ } = snap in
let is_old_dep_expr tp =
(* but it gets better! *)
let rec atoi s i acc =
if Char.(s.[i] = '>') then
acc
else
atoi s (i + 1) ((10 * acc) + Char.(to_int s.[i] - to_int '0'))
in
String.length tp > 6
&& String.(sub ~pos:0 ~len:6 tp = "<expr#")
&&
match IMap.find_opt (atoi tp 6 0) eidmap with
| Some id -> id < nextid
| None -> false
in
let tpmap =
Type_parameter_env.get_tparams (Env.get_global_tpenv env)
|> Typing_continuations.Map.fold
(fun _ c ->
SMap.union
(Type_parameter_env.get_tparams c.Typing_per_cont_env.tpenv))
(Typing_lenv.get_all_locals env)
|> SMap.fold (fun x _ -> SMap.remove x) snap.tpmap
|> SMap.filter (fun tp _ ->
(not (is_global tp)) && not (is_old_dep_expr tp))
in
( SMap.keys tpmap,
function
| Rtv_tparam name ->
Option.map (SMap.find_opt name tpmap) ~f:(fun (pos, tpi) ->
{
pos;
upper_bounds = tpi.Typing_kinding_defs.upper_bounds;
lower_bounds = tpi.Typing_kinding_defs.lower_bounds;
})
| Rtv_dependent id ->
let empty_info =
{
pos = Pos_or_decl.none;
upper_bounds = TySet.empty;
lower_bounds = TySet.empty;
}
in
if id > nextid then
Some empty_info
else
None ) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_escape.mli | open Typing_defs
open Typing_env_types
type snapshot
type escaping_rigid_tvars
val snapshot_env : env -> snapshot
val escaping_from_snapshot : snapshot -> env -> escaping_rigid_tvars
val refresh_env_and_type :
remove:escaping_rigid_tvars -> pos:Pos.t -> env -> locl_ty -> env * locl_ty |
OCaml | hhvm/hphp/hack/src/typing/typing_expand.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
(*****************************************************************************)
(* Gets rid of all the type variables,
* this is only useful when declaring class constants.
* The thing is, we don't want any type variable left in
* type declarations, (it would force us to maintain a global
* substitution, which would be way too big).
*)
(*****************************************************************************)
let visitor =
object
inherit Type_mapper.deep_type_mapper
inherit! Type_mapper.tvar_expanding_type_mapper
end
(*****************************************************************************)
(* External API *)
(*****************************************************************************)
let fully_expand env ty = snd (visitor#on_type (Type_mapper.fresh_env env) ty)
let fully_expand_i env ty =
Typing_defs.(
match ty with
| ConstraintType _ -> ty
| LoclType ty -> LoclType (fully_expand env ty)) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_expand.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(*****************************************************************************)
(* Gets rid of all the type variables,
* this is only useful when declaring class constants.
* The thing is, we don't want any type variable left in
* type declarations, (it would force us to maintain a global
* substitution, which would be way too big).
*)
(*****************************************************************************)
val fully_expand :
Typing_env_types.env -> Typing_defs.locl_ty -> Typing_defs.locl_ty
val fully_expand_i :
Typing_env_types.env -> Typing_defs.internal_type -> Typing_defs.internal_type |
OCaml | hhvm/hphp/hack/src/typing/typing_extends.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(*****************************************************************************)
(* Checks that a class implements an interface *)
(*****************************************************************************)
open Hh_prelude
open Option.Monad_infix
open Typing_defs
module Env = Typing_env
module Dep = Typing_deps.Dep
module TUtils = Typing_utils
module Inst = Decl_instantiate
module Phase = Typing_phase
module SN = Naming_special_names
module Cls = Decl_provider.Class
module MakeType = Typing_make_type
module TCO = TypecheckerOptions
module MemberKind = struct
type t =
| Property
| Static_property
| Method
| Static_method
| Constructor of { is_consistent: bool }
[@@deriving eq, ord]
let is_method = function
| Method
| Static_method ->
true
| Property
| Static_property
| Constructor _ ->
false
let is_property = function
| Property
| Static_property ->
true
| Method
| Static_method
| Constructor _ ->
false
let is_functional member_kind =
match member_kind with
| Method
| Static_method
| Constructor _ ->
true
| Property
| Static_property ->
false
let is_constructor = function
| Constructor _ -> true
| _ -> false
let is_static = function
| Property
| Method
| Constructor _ ->
false
| Static_property
| Static_method ->
true
end
module MemberKindMap = WrappedMap.Make (MemberKind)
module MemberNameMap = SMap
(* This is used to merge members from all parents (direct ancestors) of a class.
* Certain class hierarchies are heavy in diamond patterns so merging members avoids doing the
* same member subtyping multiple times. *)
module ParentClassElt = struct
type parent = Pos.t * Cls.t
type t = {
class_elt: class_elt;
parent: parent; (** The parent this class element is from. *)
errors_if_not_overriden: Typing_error.t Lazy.t list;
(** A list of errors to be added if that class element
is not overridden in the class being checked. *)
}
let make ?errors_if_not_overriden (class_elt, parent) =
{
class_elt;
parent;
errors_if_not_overriden = Option.value errors_if_not_overriden ~default:[];
}
(* Class elements with the same names and origins should be equal
modulo type instantiations, which is why we also need to compare types.
For example,
interface I<T> {
public function foo():T;
}
interface I1 extends I<string> {}
interface I2 extends I<int> {}
class C implements I1, I2 {
public function foo():int { return 3; }
}
When unioning members of I1 and I2, we have two `foo` members with the same
origin (`I`) but with different types. *)
let compare : t -> t -> int =
fun { class_elt = elt1; _ } { class_elt = elt2; _ } ->
let {
ce_visibility = _;
ce_type = type1;
ce_origin = origin1;
ce_deprecated = _;
ce_pos = _;
ce_flags = _;
} =
elt1
in
let {
ce_visibility = _;
ce_type = type2;
ce_origin = origin2;
ce_deprecated = _;
ce_pos = _;
ce_flags = _;
} =
elt2
in
match String.compare origin1 origin2 with
| 0 -> compare_decl_ty (Lazy.force type1) (Lazy.force type2)
| x -> x
end
module ParentClassEltSet =
Reordered_argument_collections.Reordered_argument_set
(Caml.Set.Make (ParentClassElt))
module ParentClassConst = struct
type t = {
class_const: class_const;
parent: ParentClassElt.parent;
}
let make class_const parent = { class_const; parent }
let compare { class_const = left; _ } { class_const = right; _ } =
String.compare left.cc_origin right.cc_origin
end
module ParentClassConstSet = Caml.Set.Make (ParentClassConst)
module ParentTypeConst = struct
type t = {
typeconst: typeconst_type;
parent: ParentClassElt.parent;
}
let make typeconst parent = { typeconst; parent }
let compare { typeconst = left; _ } { typeconst = right; _ } =
String.compare left.ttc_origin right.ttc_origin
end
module ParentTypeConstSet = Caml.Set.Make (ParentTypeConst)
let constructor_is_consistent kind =
match kind with
| ConsistentConstruct
| FinalClass ->
true
| Inconsistent -> false
(*****************************************************************************)
(* Given a map of members, check that the overriding is correct.
* Please note that 'members' has a very general meaning here.
* It can be class variables, methods, static methods etc ... The same logic
* is applied to verify that the overriding is correct.
*)
(*****************************************************************************)
(* Rules for visibility *)
let check_visibility env parent_vis c_vis parent_pos pos on_error =
match (parent_vis, c_vis) with
| (Vprivate _, _) ->
(* The only time this case should come into play is when the
* parent_class_elt comes from a trait *)
()
| (Vpublic, Vpublic)
| (Vprotected _, Vprotected _)
| (Vprotected _, Vpublic)
| (Vinternal _, Vpublic) ->
()
| (Vinternal parent_module, (Vprotected _ | Vprivate _)) ->
let err =
Typing_error.Secondary.Visibility_override_internal
{ pos; module_name = None; parent_pos; parent_module }
in
Typing_error_utils.add_typing_error ~env
@@ Typing_error.(apply_reasons ~on_error err)
| (Vinternal parent_m, Vinternal child_m) ->
let err_opt =
match
Typing_modules.can_access_internal
~env
~current:(Some child_m)
~target:(Some parent_m)
with
| `Yes -> None
| `Disjoint (current, target) ->
Some
(Typing_error.Secondary.Visibility_override_internal
{
pos;
module_name = Some current;
parent_pos;
parent_module = target;
})
| `Outside target ->
Some
(Typing_error.Secondary.Visibility_override_internal
{ pos; module_name = None; parent_pos; parent_module = target })
(* TODO(T109499403) This case *is* possible, but because it refers to
* class members in traits, any code that runs afoul of this rule will
* also violate the nast check requiring that any trait member in a
* non-internal trait must also be non-internal. I can't even figure out
* a test case where this also doesn't violate _other_ rules about
* referencing internal symbols in modules, e.g.:
*
*
* internal trait Quuz {
* internal function lol(): void {}
* }
*
* trait Corge {
* use Quuz;
* internal function lol(): void {}
* }
*
* This code snippet alone raises two errors. One for `use Quuz`,
* and one for `Corge::lol`.
*
*)
| `OutsideViaTrait _ -> None
in
Option.iter err_opt ~f:(fun err ->
Typing_error_utils.add_typing_error ~env
@@ Typing_error.(apply_reasons ~on_error err))
| _ ->
let parent_vis = Typing_defs.string_of_visibility parent_vis in
let vis = Typing_defs.string_of_visibility c_vis in
let err =
Typing_error.Secondary.Visibility_extends
{ pos; vis; parent_pos; parent_vis }
in
Typing_error_utils.add_typing_error ~env
@@ Typing_error.(apply_reasons ~on_error err)
let check_class_elt_visibility env parent_class_elt class_elt on_error =
let parent_vis = parent_class_elt.ce_visibility in
let c_vis = class_elt.ce_visibility in
let (lazy parent_pos) = parent_class_elt.ce_pos in
let (lazy pos) = class_elt.ce_pos in
check_visibility env parent_vis c_vis parent_pos pos on_error
let get_member member_kind class_ =
match member_kind with
| MemberKind.Property -> Cls.get_prop class_
| MemberKind.Static_property -> Cls.get_sprop class_
| MemberKind.Method -> Cls.get_method class_
| MemberKind.Static_method -> Cls.get_smethod class_
| MemberKind.Constructor _ -> (fun _ -> fst (Cls.construct class_))
type missing_member_info = {
member_name: string;
member_kind: MemberKind.t;
parent_class_elt: class_elt;
parent_pos: Pos.t;
is_override: bool;
}
let stub_all_methods_quickfix
~(class_name : string)
~(title : string)
(methods : missing_member_info list) : Pos.t Quickfix.t =
let method_texts =
List.map
methods
~f:(fun { member_name; parent_class_elt; member_kind; is_override; _ } ->
let is_static = MemberKind.is_static member_kind in
Typing_skeleton.of_method
member_name
parent_class_elt
~is_static
~is_override)
in
let new_text = String.concat method_texts in
Quickfix.make_classish ~title ~new_text ~classish_name:class_name
(* Emit an error for every missing method or property in this
class. Offer a single quickfix for adding all the missing
methods. *)
let members_missing_error
env
(class_pos : Pos.t)
(class_ : Cls.t)
(members : missing_member_info list) : unit =
let (missing_methods, missing_props) =
List.partition_tf members ~f:(fun { member_kind; _ } ->
MemberKind.is_functional member_kind)
in
let (class_methods, interface_methods) =
List.partition_tf missing_methods ~f:(fun { is_override; _ } -> is_override)
in
List.iteri
interface_methods
~f:(fun i { parent_pos; member_name; parent_class_elt; _ } ->
let quickfixes =
match i with
| 0 ->
[
stub_all_methods_quickfix
~class_name:(Cls.name class_)
~title:"Add stubs for missing interface methods"
interface_methods;
]
| _ -> []
in
let (lazy defn_pos) = parent_class_elt.ce_pos in
let err =
Typing_error.(
primary
@@ Primary.Member_not_implemented
{
pos = parent_pos;
member_name;
decl_pos = defn_pos;
quickfixes;
})
in
Typing_error_utils.add_typing_error ~env err);
List.iteri class_methods ~f:(fun i { member_name; parent_class_elt; _ } ->
let quickfixes =
match i with
| 0 ->
[
stub_all_methods_quickfix
~class_name:(Cls.name class_)
~title:"Add stubs for missing inherited methods"
class_methods;
]
| _ -> []
in
let trace =
lazy
(Ancestor_route.describe_route
env
~classish:(Cls.name class_)
~ancestor:parent_class_elt.ce_origin)
in
Typing_error_utils.add_typing_error
~env
Typing_error.(
primary
@@ Primary.Implement_abstract
{
is_final = Cls.final class_;
pos = class_pos;
decl_pos = Lazy.force parent_class_elt.ce_pos;
trace;
kind = `meth;
name = member_name;
quickfixes;
}));
List.iter missing_props ~f:(fun { member_name; parent_class_elt; _ } ->
let trace =
lazy
(Ancestor_route.describe_route
env
~classish:(Cls.name class_)
~ancestor:parent_class_elt.ce_origin)
in
Typing_error_utils.add_typing_error
~env
Typing_error.(
primary
@@ Primary.Implement_abstract
{
is_final = Cls.final class_;
pos = class_pos;
decl_pos = Lazy.force parent_class_elt.ce_pos;
trace;
kind = `prop;
name = member_name;
quickfixes = [];
}))
let check_subtype_methods
env ~check_return on_error (r_ancestor, ft_ancestor) (r_child, ft_child) ()
=
Typing_subtype_method.(
(* Add deps here when we override *)
subtype_method_decl
~check_return
env
r_child
ft_child
r_ancestor
ft_ancestor
on_error)
(* An abstract member can be declared in multiple ancestors. Sometimes these
* declarations can be different, but yet compatible depending on which ancestor
* we inherit the member from. For example:
*
* interface I1 { abstract public function foo(): int; }
* interface I2 { abstract public function foo(): mixed; }
*
* abstract class C implements I1, I2 {}
*
* I1::foo() is compatible with I2::foo(), but not vice versa. Hack chooses the
* signature for C::foo() arbitrarily and can report an error if we make a
* "wrong" choice. We check for this case and emit an extra line in the error
* instructing the programmer to redeclare the member to remove the ambiguity.
*
* Note: We could detect this case and make the correct choice for the user, but
* this would require invalidating the current entry we have in the typing heap
* for this class. We cannot make this choice earlier during typing_decl because
* a class we depend on during the subtyping may not have been declared yet.
*)
(* TODO(jjwu): get rid of this for type constants too, and we can delete *)
let check_ambiguous_inheritance f parent child pos class_ origin on_error ~env =
Errors.try_when
(f parent child)
~if_error_and:(fun () ->
String.( <> ) (Cls.name class_) origin
&& Errors.has_no_errors (f child parent))
~then_:(fun error ->
Typing_error_utils.ambiguous_inheritance
pos
(Cls.name class_)
origin
error
on_error
~env)
(** Checks that we're not overriding a final method. *)
let check_override_final_method env parent_class_elt class_elt on_error =
let is_override_of_final_method =
get_ce_final parent_class_elt
&& String.( <> ) parent_class_elt.ce_origin class_elt.ce_origin
in
if is_override_of_final_method && not (get_ce_synthesized class_elt) then
(* we have a final method being overridden by a user-declared method *)
let (lazy parent_pos) = parent_class_elt.ce_pos in
let (lazy pos) = class_elt.ce_pos in
Typing_error_utils.add_typing_error
~env
Typing_error.(
apply_reasons ~on_error @@ Secondary.Override_final { pos; parent_pos })
(** Checks that methods annotated with __DynamicallyCallable are only overridden with
dynamically callable method. *)
let check_dynamically_callable
env member_name parent_class_elt class_elt on_error =
if
get_ce_dynamicallycallable parent_class_elt
&& not (get_ce_dynamicallycallable class_elt)
then
let (lazy parent_pos) = parent_class_elt.ce_pos in
let (lazy pos) = class_elt.ce_pos in
let (snd_err1, snd_err2) =
Typing_error.Secondary.
( Bad_method_override { pos; member_name },
Method_not_dynamically_callable { pos; parent_pos } )
in
(* Modify the callback so that we append `snd_err2` to `snd_err1` when
evaluating *)
let on_error =
Typing_error.Reasons_callback.prepend_on_apply on_error snd_err1
in
Typing_error_utils.add_typing_error ~env
@@ Typing_error.apply_reasons ~on_error snd_err2
(** Check that we are not overriding an __LSB property *)
let check_lsb_overrides
env member_kind member_name parent_class_elt class_elt on_error =
let parent_is_lsb = get_ce_lsb parent_class_elt in
if MemberKind.equal MemberKind.Static_property member_kind && parent_is_lsb
then
(* __LSB attribute is being overridden *)
let (lazy parent_pos) = parent_class_elt.ce_pos in
let (lazy pos) = class_elt.ce_pos in
Typing_error_utils.add_typing_error ~env
@@ Typing_error.(
apply_reasons ~on_error
@@ Secondary.Override_lsb { pos; parent_pos; member_name })
(** Check that __LateInit annotation on members are consistent between parents and children. *)
let check_lateinit env parent_class_elt class_elt on_error =
let lateinit_diff =
Bool.( <> ) (get_ce_lateinit parent_class_elt) (get_ce_lateinit class_elt)
in
if lateinit_diff then
let (lazy parent_pos) = parent_class_elt.ce_pos in
let (lazy child_pos) = class_elt.ce_pos in
Typing_error_utils.add_typing_error ~env
@@ Typing_error.(
apply_reasons ~on_error
@@ Secondary.Bad_lateinit_override
{
pos = child_pos;
parent_pos;
parent_is_lateinit = get_ce_lateinit parent_class_elt;
})
let check_async env ft_parent ft_child parent_pos pos on_error =
match (get_ft_async ft_parent, get_ft_async ft_child) with
| (true, false) ->
Typing_error_utils.add_typing_error
~env
Typing_error.(
apply_reasons ~on_error @@ Secondary.Override_async { pos; parent_pos })
| _ -> ()
let check_xhp_attr_required env parent_class_elt class_elt on_error =
if not (TCO.check_xhp_attribute (Env.get_tcopt env)) then
()
else
let is_less_strict = function
| (Some Xhp_attribute.Required, _)
| (Some Xhp_attribute.LateInit, Some Xhp_attribute.LateInit)
| (Some Xhp_attribute.LateInit, None)
| (None, None) ->
false
| (_, _) -> true
in
let parent_attr = get_ce_xhp_attr parent_class_elt in
let attr = get_ce_xhp_attr class_elt in
match (parent_attr, attr) with
| ( Some { Xhp_attribute.xa_tag = parent_tag; _ },
Some { Xhp_attribute.xa_tag = tag; _ } )
when is_less_strict (tag, parent_tag) ->
let (lazy parent_pos) = parent_class_elt.ce_pos in
let (lazy child_pos) = class_elt.ce_pos in
let lateinit = Markdown_lite.md_codify "@lateinit" in
let required = Markdown_lite.md_codify "@required" in
let show_tag_opt = function
| None -> Printf.sprintf "not %s or %s" required lateinit
| Some Xhp_attribute.Required -> required
| Some Xhp_attribute.LateInit -> lateinit
in
Typing_error_utils.add_typing_error ~env
@@ Typing_error.(
apply_reasons ~on_error
@@ Secondary.Bad_xhp_attr_required_override
{
pos = child_pos;
tag = show_tag_opt tag;
parent_pos;
parent_tag = show_tag_opt parent_tag;
})
| (_, _) -> ()
let add_pessimisation_dependency
env child_cls member_name member_kind parent_cls =
let result =
(* For the time being we only care about methods *)
match member_kind with
| MemberKind.Method ->
( Cls.get_method child_cls member_name,
Cls.get_method parent_cls member_name,
Some (Typing_pessimisation_deps.Method member_name) )
| MemberKind.Static_method ->
( Cls.get_smethod child_cls member_name,
Cls.get_smethod parent_cls member_name,
Some (Typing_pessimisation_deps.SMethod member_name) )
| _ -> (None, None, None)
in
match result with
| (Some child_elt, Some parent_elt, Some member) ->
(* We resolve both the parent and child to their origin. This allows us
* to perform hierarchy poisioning for traits correctly: If a class C
* gets a definition of some method foo by using a trait D, then the
* following two conditions hold simultaneously:
* a) If a child of C pessimises foo, then D::foo must be pessimised.
* b) If the definition of foo in requires it to be pessimised, then
* all users of C::foo must be aware of that. Further, if C::foo
* overrides P::foo in some parent P of C, then this P::foo must be
* poisoned.
*
*
* To resolve this, we effectively unify C:ffoo and D::foo in the
* (pessimisation) dependency graph:
* Elsewhere, we make sure that all users of C::foo point to D::foo
* instead. Here, we make sure that we mark D::foo as overriding P::foo
* and any direct overrider of C::foo is marked as overriding D::foo
* instead. *)
let child_name = child_elt.Typing_defs.ce_origin in
let parent_name = parent_elt.Typing_defs.ce_origin in
Typing_pessimisation_deps.add_override_dep
(Env.get_deps_mode env)
member
~child_name
~parent_name
| _ -> ()
let add_member_dep
env class_ parent_class (member_kind, member_name, member_origin) =
let origin_pos = Cls.pos parent_class in
if not (Pos_or_decl.is_hhi origin_pos) then (
let dep =
match member_kind with
| MemberKind.Method -> Dep.Method (member_origin, member_name)
| MemberKind.Static_method -> Dep.SMethod (member_origin, member_name)
| MemberKind.Static_property -> Dep.SProp (member_origin, member_name)
| MemberKind.Property -> Dep.Prop (member_origin, member_name)
| MemberKind.Constructor _ -> Dep.Constructor member_origin
in
let class_name = Cls.name class_ in
Typing_deps.add_idep (Env.get_deps_mode env) (Dep.Type class_name) dep;
if TCO.record_fine_grained_dependencies @@ Env.get_tcopt env then
add_pessimisation_dependency
env
class_
member_name
member_kind
parent_class
)
let check_compatible_sound_dynamic_attributes
env member_name member_kind parent_class_elt class_elt on_error =
if
(not (MemberKind.is_constructor member_kind))
&& TCO.enable_sound_dynamic (Provider_context.get_tcopt (Env.get_ctx env))
&& get_ce_support_dynamic_type parent_class_elt
&& not (get_ce_support_dynamic_type class_elt)
then
let (lazy pos) = class_elt.ce_pos in
let (lazy parent_pos) = parent_class_elt.ce_pos in
Typing_error_utils.add_typing_error ~env
@@ Typing_error.(
apply_reasons ~on_error
@@ Secondary.Override_method_support_dynamic_type
{
pos;
parent_pos;
parent_origin = parent_class_elt.ce_origin;
method_name = member_name;
})
let check_prop_const_mismatch env parent_class_elt class_elt on_error =
if Bool.( <> ) (get_ce_const class_elt) (get_ce_const parent_class_elt) then
Typing_error_utils.add_typing_error
~env
Typing_error.(
apply_reasons ~on_error
@@ Secondary.Overriding_prop_const_mismatch
{
pos = Lazy.force class_elt.ce_pos;
is_const = get_ce_const class_elt;
parent_pos = Lazy.force parent_class_elt.ce_pos;
parent_is_const = get_ce_const parent_class_elt;
})
let check_abstract_overrides_concrete env member_kind parent_class_elt class_elt
=
if (not (get_ce_abstract parent_class_elt)) && get_ce_abstract class_elt then
(* It is valid for abstract class to extend a concrete class, but it cannot
* redefine already concrete members as abstract.
* See override_abstract_concrete.php test case for example. *)
Typing_error_utils.add_typing_error
~env
Typing_error.(
assert_in_current_decl ~ctx:(Env.get_current_decl_and_file env)
@@ Secondary.Abstract_concrete_override
{
pos = Lazy.force class_elt.ce_pos;
parent_pos = Lazy.force parent_class_elt.ce_pos;
kind =
(if MemberKind.is_functional member_kind then
`method_
else
`property);
})
let detect_multiple_concrete_defs
(class_elt, class_) (parent_class_elt, parent_class) =
(* We want to check if there are conflicting trait declarations of a class member.
* If the parent we are checking is a trait and the member's origin both isn't
* that parent and isn't the class itself, then it must come from another trait
* and there is a conflict.
*
* We rule out cases where any of the traits' member
* is synthetic (from a requirement) or abstract. *)
match Cls.kind parent_class with
| Ast_defs.Ctrait ->
(not (get_ce_synthesized class_elt))
&& (not (get_ce_abstract class_elt))
&& (not (get_ce_abstract parent_class_elt))
&& String.( <> ) class_elt.ce_origin (Cls.name class_)
| Ast_defs.(Cinterface | Cclass _ | Cenum | Cenum_class _) -> false
let check_multiple_concrete_definitions
env
member_name
member_kind
(class_elt, class_)
(parent_class_elt, parent_class)
on_error =
if
(MemberKind.is_functional member_kind || get_ce_const class_elt)
&& detect_multiple_concrete_defs
(class_elt, class_)
(parent_class_elt, parent_class)
then
(* Multiple concrete trait definitions, error *)
Typing_error_utils.add_typing_error
~env
Typing_error.(
apply_reasons ~on_error
@@ Secondary.Multiple_concrete_defs
{
pos = Lazy.force class_elt.ce_pos;
parent_pos = Lazy.force parent_class_elt.ce_pos;
origin = class_elt.ce_origin;
parent_origin = parent_class_elt.ce_origin;
name = member_name;
class_name = Cls.name class_;
})
(* Get the type of the value that is returned: for an async function that has
* declared return type Awaitable<t>, this is t, otherwise it's just
* the declared return type
*)
let get_return_value_type ft =
match (get_ft_async ft, deref ft.ft_ret.et_type) with
| (true, (_, Tapply ((_, class_name), [inner_ty])))
when String.equal class_name SN.Classes.cAwaitable ->
inner_ty
| _ -> ft.ft_ret.et_type
let maybe_poison_ancestors
env
ft_parent
ft_child
parent_class
child_class
origin
member_name
member_kind =
if TCO.like_casts (Provider_context.get_tcopt (Env.get_ctx env)) then
let parent_return_ty = get_return_value_type ft_parent in
let child_return_ty = get_return_value_type ft_child in
let (declared_class, declared_return_ty) =
if String.equal (Cls.name child_class) origin then
(child_class, child_return_ty)
else
match Env.get_class env origin with
| None -> (child_class, child_return_ty)
| Some c ->
(match Env.get_member true env c member_name with
| None -> (child_class, child_return_ty)
| Some elt ->
let (lazy fty) = elt.ce_type in
(match get_node fty with
| Tfun ft -> (c, get_return_value_type ft)
| _ -> (child_class, child_return_ty)))
in
match
( Typing_enforceability.get_enforcement
~this_class:(Some parent_class)
env
parent_return_ty,
Typing_enforceability.get_enforcement
~this_class:(Some declared_class)
env
declared_return_ty )
with
(* If the parent itself overrides a fully-enforced return type
* then we need to "copy down" any intersection, so record this in the log
*)
| (Unenforced, Unenforced) ->
let child_pos =
Pos_or_decl.unsafe_to_raw_pos (get_pos ft_child.ft_ret.et_type)
in
let parent_pos =
Pos_or_decl.unsafe_to_raw_pos (get_pos ft_parent.ft_ret.et_type)
in
let p = Pos.to_absolute parent_pos in
let s = Printf.sprintf "!,%s,%d" (Pos.filename p) (Pos.line p) in
Typing_log.log_pessimise_return env child_pos (Some s)
| (Enforced, Unenforced) -> begin
match get_node parent_return_ty with
| Tmixed -> ()
| _ ->
let enforced_declared_ty =
Typing_partial_enforcement.get_enforced_type
env
(Some declared_class)
declared_return_ty
in
let tmp_env =
let self_ty =
MakeType.class_type
Reason.Rnone
origin
(List.map (Cls.tparams declared_class) ~f:(fun tp ->
MakeType.generic Reason.Rnone (snd tp.tp_name)))
in
Env.env_with_tpenv
env
(Type_parameter_env.add_upper_bound
Type_parameter_env.empty
SN.Typehints.this
self_ty)
in
let child_pos =
Pos_or_decl.unsafe_to_raw_pos (get_pos ft_child.ft_ret.et_type)
in
let enforced_parent_ty =
Typing_partial_enforcement.get_enforced_type
env
(Some parent_class)
parent_return_ty
in
(* We need that the enforced child type is a subtype of the enforced parent type *)
let sub1 =
Phase.is_sub_type_decl
~coerce:(Some Typing_logic.CoerceToDynamic)
tmp_env
enforced_declared_ty
enforced_parent_ty
in
(* But also the original child type should be a subtype of the enforced parent type *)
let sub2 =
Phase.is_sub_type_decl
~coerce:(Some Typing_logic.CoerceToDynamic)
tmp_env
declared_return_ty
enforced_parent_ty
in
if sub1 && sub2 then
let ty_str =
Typing_print.full_decl (Env.get_tcopt env) enforced_parent_ty
in
(* Hack to remove "\\" if XHP type is rendered as "\\:X" *)
(* TODO: fix Typing_print so that it renders XHP correctly *)
let ty_str =
let re = Str.regexp "\\\\:" in
Str.global_replace re ":" ty_str
in
Typing_log.log_pessimise_return env child_pos (Some ty_str)
else
Cls.all_ancestor_names child_class
|> List.map ~f:(Env.get_class env)
|> List.filter_opt
|> List.iter ~f:(fun cls ->
MemberKind.(
match member_kind with
| Static_method -> Cls.get_smethod cls member_name
| Method -> Cls.get_method cls member_name
| _ -> None)
|> Option.iter ~f:(fun elt ->
let (lazy fty) = elt.ce_type in
match get_node fty with
| Tfun { ft_ret; _ } ->
let pos =
Pos_or_decl.unsafe_to_raw_pos
(get_pos ft_ret.et_type)
in
(* The ^ denotes poisoning *)
Typing_log.log_pessimise_poisoned_return
env
pos
(Cls.name child_class ^ "::" ^ member_name)
| _ -> ()))
end
| _ -> ()
(* Check that overriding is correct *)
let check_override
env
~check_member_unique
member_name
member_kind
class_
parent_class
parent_class_elt
class_elt
on_error =
(* If the class element is defined in the class that we're checking, then
* don't wrap with the extra
* "Class ... does not correctly implement all required members" message *)
let on_error =
if String.equal class_elt.ce_origin (Cls.name class_) then
Env.unify_error_assert_primary_pos_in_current_decl env
else
on_error
in
if MemberKind.is_method member_kind then begin
(* We first verify that we aren't overriding a final method. We only check
* for final overrides on methods, not properties. Constructors have their
* own code-path with this check, see `check_constructors`
*)
check_override_final_method env parent_class_elt class_elt on_error;
check_dynamically_callable
env
member_name
parent_class_elt
class_elt
on_error
end;
(* Verify that we are not overriding an __LSB property *)
check_lsb_overrides
env
member_kind
member_name
parent_class_elt
class_elt
on_error;
check_lateinit env parent_class_elt class_elt on_error;
check_xhp_attr_required env parent_class_elt class_elt on_error;
check_class_elt_visibility env parent_class_elt class_elt on_error;
check_prop_const_mismatch env parent_class_elt class_elt on_error;
check_abstract_overrides_concrete env member_kind parent_class_elt class_elt;
let (lazy pos) = class_elt.ce_pos in
let (lazy parent_pos) = parent_class_elt.ce_pos in
let snd_err =
let open Typing_error.Secondary in
if MemberKind.is_functional member_kind then
Bad_method_override { pos; member_name }
else
Bad_prop_override { pos; member_name }
in
(* Modify the `Typing_error.Reasons_callback.t` so that we always end up
with the error code given by `snd_err` and the reasons of whatever
error it is applied to are appended to the reasons given by `snd_err`
*)
let on_error =
Typing_error.Reasons_callback.prepend_on_apply on_error snd_err
in
if check_member_unique then
check_multiple_concrete_definitions
env
member_name
member_kind
(class_elt, class_)
(parent_class_elt, parent_class)
on_error;
check_compatible_sound_dynamic_attributes
env
member_name
member_kind
parent_class_elt
class_elt
on_error;
let (lazy fty_child) = class_elt.ce_type in
let (lazy fty_parent) = parent_class_elt.ce_type in
match (deref fty_parent, deref fty_child) with
| ((_, Tany _), (_, Tany _)) -> env
| ((_, Tany _), _) ->
Typing_error_utils.add_typing_error
~env
Typing_error.(
apply_reasons ~on_error
@@ Secondary.Decl_override_missing_hint parent_pos);
env
| (_, (_, Tany _)) ->
Typing_error_utils.add_typing_error
~env
Typing_error.(
apply_reasons ~on_error @@ Secondary.Decl_override_missing_hint pos);
env
| ((r_parent, Tfun ft_parent), (r_child, Tfun ft_child)) ->
(match member_kind with
| MemberKind.Constructor { is_consistent = false } ->
(* we don't check that constructor signatures follow
* subtyping rules except with __ConsistentConstruct *)
env
| _ ->
maybe_poison_ancestors
env
ft_parent
ft_child
parent_class
class_
class_elt.ce_origin
member_name
member_kind;
check_async
env
ft_parent
ft_child
(Typing_reason.to_pos r_parent)
(Typing_reason.to_pos r_child)
on_error;
check_ambiguous_inheritance
(check_subtype_methods
env
~check_return:(not (MemberKind.is_constructor member_kind))
on_error)
(Typing_reason.localize r_parent, ft_parent)
(Typing_reason.localize r_child, ft_child)
pos
class_
class_elt.ce_origin
on_error
~env)
| _ ->
let (env, ty_err_opt) =
if get_ce_const class_elt then
Phase.sub_type_decl env fty_child fty_parent @@ Some on_error
else
Typing_ops.unify_decl
pos
Typing_reason.URnone
env
on_error
fty_parent
fty_child
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
env
(* Constants and type constants with declared values in declared interfaces can never be
* overridden by other inherited constants.
* Constants from traits are taken into account only if the --enable-strict-const-semantics is enabled
* @precondition: both constants must not be synthesized
*)
let conflict_with_declared_interface_or_trait
?(include_traits = true)
env
implements
parent_class
class_
parent_origin
origin
const_name =
let strict_const_semantics =
TCO.enable_strict_const_semantics (Env.get_tcopt env) > 0
in
let is_inherited_and_conflicts_with_parent =
String.( <> ) origin (Cls.name class_) && String.( <> ) origin parent_origin
in
let child_const_from_used_trait =
if strict_const_semantics && include_traits then
match Env.get_class env origin with
| Some cls -> Cls.kind cls |> Ast_defs.is_c_trait
| None -> false
else
false
in
(* True if a declared interface on class_ has a concrete constant with
the same name and origin as child constant *)
let child_const_from_declared_interface =
match Env.get_class env origin with
| Some cls ->
Cls.kind cls |> Ast_defs.is_c_interface
&&
if strict_const_semantics && include_traits then
true
else
List.fold implements ~init:false ~f:(fun acc (_, iface) ->
acc
||
match Cls.get_const iface const_name with
| None -> false
| Some const -> String.( = ) const.cc_origin origin)
| None -> false
in
match Cls.kind parent_class with
| Ast_defs.Cinterface -> is_inherited_and_conflicts_with_parent
| Ast_defs.Cclass _ ->
is_inherited_and_conflicts_with_parent
&& (child_const_from_declared_interface || child_const_from_used_trait)
| Ast_defs.Ctrait ->
is_inherited_and_conflicts_with_parent
&& (child_const_from_declared_interface || child_const_from_used_trait)
&&
(* constant must be declared on a trait (or interface if include_traits == true) to conflict *)
(match Env.get_class env parent_origin with
| Some cls ->
if strict_const_semantics && include_traits then
Cls.kind cls |> fun k ->
Ast_defs.is_c_trait k || Ast_defs.is_c_interface k
else
Cls.kind cls |> Ast_defs.is_c_trait
| None -> false)
| Ast_defs.Cenum_class _
| Ast_defs.Cenum ->
false
let check_abstract_const_in_concrete_class
env (class_pos, class_) (const_name, class_const) =
let is_final = Cls.final class_ in
if Ast_defs.is_c_concrete (Cls.kind class_) || is_final then
match class_const.cc_abstract with
| CCAbstract _ ->
let trace =
lazy
(Ancestor_route.describe_route
env
~classish:(Cls.name class_)
~ancestor:class_const.cc_origin)
in
Typing_error_utils.add_typing_error
~env
Typing_error.(
primary
@@ Primary.Implement_abstract
{
is_final;
pos = class_pos;
decl_pos = class_const.cc_pos;
trace;
kind = `const;
name = const_name;
quickfixes = [];
})
| Typing_defs.CCConcrete -> ()
let check_const_override
env
implements
const_name
parent_class
(class_pos, class_)
parent_class_const
class_const
on_error =
if String.equal parent_class_const.cc_origin class_const.cc_origin then (
check_abstract_const_in_concrete_class
env
(class_pos, class_)
(const_name, class_const);
env
) else
let parent_kind = Cls.kind parent_class in
let class_kind = Cls.kind class_ in
(* Shared preconditions for const_interface_member_not_unique and
is_bad_interface_const_override *)
let is_concrete = function
| CCConcrete -> true
| CCAbstract _ -> false
in
let both_are_non_synthetic_and_concrete =
(* Synthetic *)
(not class_const.cc_synthesized)
(* The parent we are checking is synthetic, no point in checking *)
&& (not parent_class_const.cc_synthesized)
(* Only check if parent and child have concrete definitions *)
&& is_concrete class_const.cc_abstract
&& is_concrete parent_class_const.cc_abstract
in
let const_interface_or_trait_member_not_unique =
(* Similar to detect_multiple_concrete_defs, we check if there are multiple
concrete implementations of class constants with no override.
*)
conflict_with_declared_interface_or_trait
env
implements
parent_class
class_
parent_class_const.cc_origin
class_const.cc_origin
const_name
&& both_are_non_synthetic_and_concrete
in
let is_bad_interface_const_override =
(* HHVM does not support one specific case of overriding constants:
If the original constant was defined as non-abstract in an interface or trait,
it cannot be overridden when implementing or extending that interface or using that trait. *)
if Ast_defs.is_c_interface parent_kind then
both_are_non_synthetic_and_concrete
(* Check that the constant is indeed defined in class_ *)
&& String.( = ) class_const.cc_origin (Cls.name class_)
else
false
in
let is_abstract_concrete_override =
match (parent_class_const.cc_abstract, class_const.cc_abstract) with
| (CCConcrete, CCAbstract _) -> true
| _ -> false
in
let remove_hh_member_of dty =
match get_node dty with
| Tapply (_hh_member_of, [_enum; dty]) -> dty
| _ -> dty
in
let class_const_type =
if Ast_defs.is_c_enum_class class_kind then
remove_hh_member_of class_const.cc_type
else
class_const.cc_type
in
let parent_class_const_type =
if Ast_defs.is_c_enum_class parent_kind then
remove_hh_member_of parent_class_const.cc_type
else
parent_class_const.cc_type
in
let ty_err_opt1 =
if const_interface_or_trait_member_not_unique then
let snd_err =
Typing_error.Secondary.Interface_or_trait_const_multiple_defs
{
pos = class_const.cc_pos;
name = const_name;
origin = class_const.cc_origin;
parent_pos = parent_class_const.cc_pos;
parent_origin = parent_class_const.cc_origin;
}
in
Some (Typing_error.apply_reasons ~on_error snd_err)
else if is_bad_interface_const_override then
let snd_err =
Typing_error.Secondary.Concrete_const_interface_override
{
pos = class_const.cc_pos;
name = const_name;
parent_pos = parent_class_const.cc_pos;
parent_origin = parent_class_const.cc_origin;
}
in
Some (Typing_error.apply_reasons ~on_error snd_err)
else if is_abstract_concrete_override then
let snd_err =
Typing_error.Secondary.Abstract_concrete_override
{
pos = class_const.cc_pos;
parent_pos = parent_class_const.cc_pos;
kind = `constant;
}
in
Some
(Typing_error.assert_in_current_decl
~ctx:(Env.get_current_decl_and_file env)
snd_err)
else
None
in
Option.iter ty_err_opt1 ~f:(Typing_error_utils.add_typing_error ~env);
let (env, ty_err_opt2) =
Phase.sub_type_decl env class_const_type parent_class_const_type
@@ Some
(Typing_error.Reasons_callback.class_constant_type_mismatch on_error)
in
Option.iter ty_err_opt2 ~f:(Typing_error_utils.add_typing_error ~env);
env
let check_inherited_member_is_dynamically_callable
env
inheriting_class
parent_class
(member_kind, member_name, parent_class_elt) =
let (inheriting_class_pos, inheriting_class) = inheriting_class in
if
TCO.enable_sound_dynamic (Provider_context.get_tcopt (Env.get_ctx env))
&& Cls.get_support_dynamic_type inheriting_class
&& not (Cls.get_support_dynamic_type parent_class)
(* TODO: ideally refactor so the last test is not systematically performed on all methods *)
then
match Cls.kind parent_class with
| Ast_defs.Cclass _
| Ast_defs.Ctrait -> begin
match member_kind with
| MemberKind.Method ->
if not (Typing_defs.get_ce_support_dynamic_type parent_class_elt) then
(* since the attribute is missing run the inter check *)
let (lazy (ty : decl_ty)) = parent_class_elt.ce_type in
(match get_node ty with
| Tfun fun_ty ->
if
not
(Typing_dynamic.sound_dynamic_interface_check_from_fun_ty
~this_class:(Some parent_class)
env
fun_ty)
then
Errors.method_is_not_dynamically_callable
inheriting_class_pos
member_name
(Cls.name inheriting_class)
false
(Some
( Lazy.force parent_class_elt.ce_pos,
parent_class_elt.ce_origin ))
None
| _ -> ())
| MemberKind.Static_method
| MemberKind.Static_property
| MemberKind.Property
| MemberKind.Constructor _ ->
()
end
| Ast_defs.Cinterface
| Ast_defs.Cenum_class _
| Ast_defs.Cenum ->
()
let eager_resolve_member_via_req_class
env parent_class_elt class_ member_kind member_name =
let member_element_opt = get_member member_kind class_ member_name in
let req_class_constraints = Cls.all_ancestor_req_class_requirements class_ in
if List.is_empty req_class_constraints then
(* fast path: if class_ does not have require class constraints then eager resolution cannot apply *)
member_element_opt
else
Option.map member_element_opt ~f:(fun member_element ->
(* eager resolution should happen only if one of the matched elements is defined in an interface
* so check the kind of the classish where the elements are defined
*)
let origin_is_interface el =
match Env.get_class env el.ce_origin with
| None -> false
| Some el -> Ast_defs.is_c_interface (Cls.kind el)
in
let parent_element_origin_is_interface =
origin_is_interface parent_class_elt
in
let element_origin_is_interface = origin_is_interface member_element in
if
Ast_defs.is_c_trait (Cls.kind class_)
&& (parent_element_origin_is_interface || element_origin_is_interface)
then
if String.equal member_element.ce_origin (Cls.name class_) then
member_element
else
(* Since at least one of the elements is not defined in a trait, and the base trait has a
* require class constraint, perform eager fetch of the element via the required class.
*)
let member_element_in_req_class =
List.find_map
(Cls.all_ancestor_req_class_requirements class_)
~f:(fun (_, req_ty) ->
let (_, (_, cn), _) = TUtils.unwrap_class_type req_ty in
Decl_provider.get_class (Env.get_ctx env) cn >>= fun cnc ->
get_member member_kind cnc member_name)
in
match member_element_in_req_class with
| Some member_element_in_req_class ->
{
member_element_in_req_class with
ce_flags =
Typing_defs_flags.ClassElt.set_synthesized
member_element_in_req_class.ce_flags;
}
| None -> member_element
else
member_element)
let check_class_against_parent_class_elt
(on_error : Pos.t * string -> Typing_error.Reasons_callback.t)
(class_pos, class_)
member_kind
member_name
{
ParentClassElt.class_elt = parent_class_elt;
parent = (parent_name_pos, parent_class);
errors_if_not_overriden;
}
env : missing_member_info list * Typing_env_types.env =
add_member_dep
env
class_
parent_class
(member_kind, member_name, parent_class_elt.ce_origin);
let member_element_opt =
(* If a trait does not define the element itself, but will inherit the element from a
* require class constraint then eagerly compare the element from the required class
* against the parent class elements. This is useful to eagerly solve conflicts between
* interfaces implemented by the trait.
* However, the eager resolution should not be applied to solve conflicts due to multiple
* definitions in traits used by the trait, as HHVM does not perform the eager resolution
* and fatals when flattening the trait methods.
*)
eager_resolve_member_via_req_class
env
parent_class_elt
class_
member_kind
member_name
in
match member_element_opt with
| Some class_elt ->
if String.equal parent_class_elt.ce_origin class_elt.ce_origin then (
(* Case where the child's element comes from the parent being checked. *)
(* if the child class implements dynamic, all inherited methods should be dynamically callable *)
check_inherited_member_is_dynamically_callable
env
(class_pos, class_)
parent_class
(member_kind, member_name, parent_class_elt);
errors_if_not_overriden
|> List.iter ~f:(fun err ->
err |> Lazy.force |> Typing_error_utils.add_typing_error ~env);
let is_final = Cls.final class_ in
let missing_members =
if
(Ast_defs.is_c_concrete (Cls.kind class_) || is_final)
&& Typing_defs_flags.ClassElt.is_abstract class_elt.ce_flags
then
[
{
member_name;
parent_class_elt;
parent_pos = parent_name_pos;
member_kind;
is_override = true;
};
]
else
[]
in
(missing_members, env)
) else
(* We can skip this check if the class elements have the same origin, as we are
essentially comparing a method against itself *)
( [],
check_override
~check_member_unique:true
env
member_name
member_kind
class_
parent_class
parent_class_elt
class_elt
(on_error (parent_name_pos, Cls.name parent_class)) )
| None ->
(* The only case when a member belongs to a parent but not the child is if the parent is an
interface and the child is a concrete class. Otherwise, the member would have been inherited.
In this case, this is an error because the concrete class fails to implement the parent interface. *)
( [
{
member_name;
parent_class_elt;
parent_pos = parent_name_pos;
member_kind;
is_override = false;
};
],
env )
(**
* [check_static_member_intersection class_ class_pos parent_members] looks for
* intersections in the static and instance members of [class_] (at [class_pos])
* via a precomputed list of class members in [parent_members]. We emit an
* error if there exists a class member that is defined as both static, and
* instance, as it will unconditionally fatal in HHVM. For example,
* the following code will fatal:
*
* abstract class Foo { public int $bar; }
* trait Baz { public static int $bar; }
* final class Quxx extends Foo { use Baz; }
*)
let check_static_member_intersection
env
(class_ : Cls.t)
(class_pos : Pos.t)
(parent_members : ParentClassEltSet.t MemberNameMap.t MemberKindMap.t) =
let check_single_member
(member_kind : MemberKind.t)
(name : MemberNameMap.key)
(parent_members : ParentClassEltSet.t)
(acc :
(MemberNameMap.key * Typing_defs.class_elt * Typing_defs.class_elt) list)
=
let name =
match member_kind with
| MemberKind.Property -> String.chop_prefix_if_exists ~prefix:"$" name
| MemberKind.Static_property -> "$" ^ name
| MemberKind.Static_method
| MemberKind.Method
| MemberKind.Constructor _ ->
name
in
match get_member member_kind class_ name with
| None -> acc
| Some class_elt ->
( name,
(ParentClassEltSet.choose parent_members).ParentClassElt.class_elt,
class_elt )
:: acc
in
let gather_violations parent_member_kind child_member_kind =
MemberKindMap.find_opt parent_member_kind parent_members
|> Option.value ~default:MemberNameMap.empty
|> fun map ->
MemberNameMap.fold (check_single_member child_member_kind) map []
in
let on_error ~member_name ~static_elem ~instance_elem ~kind =
Typing_error_utils.add_typing_error ~env
@@ Typing_error.(
primary
@@ Primary.Static_instance_intersection
{
class_pos;
instance_pos = instance_elem.ce_pos;
static_pos = static_elem.ce_pos;
member_name;
kind;
})
in
let find_intersections static_member_kind instance_member_kind kind =
let violations =
gather_violations static_member_kind instance_member_kind
in
List.iter violations ~f:(fun (member_name, static_elem, instance_elem) ->
on_error ~member_name ~static_elem ~instance_elem ~kind);
let violations =
gather_violations instance_member_kind static_member_kind
in
List.iter violations ~f:(fun (member_name, instance_elem, static_elem) ->
on_error ~member_name ~static_elem ~instance_elem ~kind)
in
find_intersections MemberKind.Static_method MemberKind.Method `meth;
find_intersections MemberKind.Static_property MemberKind.Property `prop;
()
let check_members_from_all_parents
env
((class_pos : Pos.t), class_)
(on_error : Pos.t * string -> Typing_error.Reasons_callback.t)
(parent_members : ParentClassEltSet.t MemberNameMap.t MemberKindMap.t) =
let check member_kind member_map (acc, env) =
let check member_name class_elts (acc, env) =
let check elt (acc, env) =
let (missing, env) =
check_class_against_parent_class_elt
on_error
(class_pos, class_)
member_kind
member_name
elt
env
in
(acc @ missing, env)
in
ParentClassEltSet.fold ~f:check class_elts ~init:(acc, env)
in
MemberNameMap.fold check member_map (acc, env)
in
let (missing_members, env) =
MemberKindMap.fold check parent_members ([], env)
in
members_missing_error env class_pos class_ missing_members;
check_static_member_intersection env class_ class_pos parent_members;
env
let make_all_members ~parent_class =
let wrap_constructor (ctor, kind) =
( MemberKind.Constructor { is_consistent = constructor_is_consistent kind },
ctor
|> Option.map ~f:(fun x -> (SN.Members.__construct, x))
|> Option.to_list )
in
[
(MemberKind.Property, Cls.props parent_class);
(MemberKind.Static_property, Cls.sprops parent_class);
(MemberKind.Method, Cls.methods parent_class);
(MemberKind.Static_method, Cls.smethods parent_class);
Cls.construct parent_class |> wrap_constructor;
]
(* The phantom class element that represents the default constructor:
* public function __construct()[] {}
*
* It isn't added to the tc_construct only because that's used to
* determine whether a child class needs to call parent::__construct *)
let default_constructor_ce class_ =
let (pos, name) = (Cls.pos class_, Cls.name class_) in
let r = Reason.Rwitness_from_decl pos in
(* reason doesn't get used in, e.g. arity checks *)
let ft =
{
ft_tparams = [];
ft_where_constraints = [];
ft_params = [];
ft_implicit_params = { capability = CapTy (MakeType.mixed r) };
ft_ret = { et_type = MakeType.void r; et_enforced = Unenforced };
ft_flags = 0;
ft_ifc_decl = default_ifc_fun_decl;
ft_cross_package = None;
}
in
{
ce_visibility = Vpublic;
ce_type = lazy (mk (r, Tfun ft));
ce_origin = name;
ce_deprecated = None;
ce_pos = lazy pos;
ce_flags =
make_ce_flags
~xhp_attr:None
~abstract:false
~final:false
~const:false
~lateinit:false
~superfluous_override:false
~lsb:false
~synthesized:true
~dynamicallycallable:false
~readonly_prop:false
~support_dynamic_type:false
~needs_init:false
~safe_global_variable:false;
}
(* When an interface defines a constructor, we check that they are compatible *)
let check_constructors env parent_class class_ psubst on_error =
let parent_is_interface = Ast_defs.is_c_interface (Cls.kind parent_class) in
let parent_is_consistent =
constructor_is_consistent (snd (Cls.construct parent_class))
in
let env =
if parent_is_interface || parent_is_consistent then
match (fst (Cls.construct parent_class), fst (Cls.construct class_)) with
| (Some parent_cstr, _) when get_ce_synthesized parent_cstr -> env
| (Some parent_cstr, None) ->
let (lazy pos) = parent_cstr.ce_pos in
Typing_error_utils.add_typing_error
~env
Typing_error.(
apply_reasons ~on_error @@ Secondary.Missing_constructor pos);
env
| (_, Some cstr) when get_ce_superfluous_override cstr ->
(* <<__UNSAFE_Construct>> *)
env
| (opt_parent_cstr, Some cstr)
when Option.is_some opt_parent_cstr || parent_is_consistent ->
let parent_cstr =
match opt_parent_cstr with
| Some parent_cstr -> parent_cstr
| None -> default_constructor_ce parent_class
in
if String.( <> ) parent_cstr.ce_origin cstr.ce_origin then
let parent_cstr = Inst.instantiate_ce psubst parent_cstr in
check_override
env
~check_member_unique:false
SN.Members.__construct
(MemberKind.Constructor { is_consistent = true })
class_
parent_class
parent_cstr
cstr
on_error
else
env
| (_, _) -> env
else
env
in
begin
match (fst (Cls.construct parent_class), fst (Cls.construct class_)) with
| (Some parent_cstr, _) when get_ce_synthesized parent_cstr -> ()
| (Some parent_cstr, Some child_cstr) ->
check_override_final_method env parent_cstr child_cstr on_error
| (_, _) -> ()
end;
env
(** Checks if a child is compatible with the type constant of its parent.
This requires the child's constraint and assigned type to be a subtype of
the parent's type constant. *)
let tconst_subsumption
env
class_name
parent_typeconst
parent_tconst_enforceable
child_typeconst
on_error =
let (pos, name) = child_typeconst.ttc_name in
let parent_pos = fst parent_typeconst.ttc_name in
match (parent_typeconst.ttc_kind, child_typeconst.ttc_kind) with
| ( TCAbstract { atc_default = Some _; _ },
TCAbstract { atc_default = None; _ } ) ->
Typing_error_utils.add_typing_error
~env
Typing_error.(
assert_in_current_decl ~ctx:(Env.get_current_decl_and_file env)
@@ Secondary.Override_no_default_typeconst { pos; parent_pos });
env
| (TCConcrete _, TCAbstract _) ->
(* It is valid for abstract class to extend a concrete class, but it cannot
* redefine already concrete members as abstract.
* See typecheck/tconst/subsume_tconst5.php test case for example. *)
Typing_error_utils.add_typing_error
~env
Typing_error.(
assert_in_current_decl ~ctx:(Env.get_current_decl_and_file env)
@@ Secondary.Abstract_concrete_override
{ pos; parent_pos; kind = `typeconst });
env
| _ ->
let inherited = not (String.equal child_typeconst.ttc_origin class_name) in
(* If the class element is inherited from a parent class, we must
* wrap any error with
* "Class [class_name] does not correctly implement all required members"
* and the primary position should be on [class_name]
*)
let on_error =
if inherited then
on_error
else
Env.unify_error_assert_primary_pos_in_current_decl env
in
(* Check that the child's constraint is compatible with the parent. If the
* parent has a constraint then the child must also have a constraint if it
* is abstract.
*
* Check that the child's assigned type satisifies parent constraint
*)
let default =
MakeType.generic (Reason.Rtconst_no_cstr child_typeconst.ttc_name) name
in
let is_coeffect =
parent_typeconst.ttc_is_ctx || child_typeconst.ttc_is_ctx
in
let check_cstrs reason env sub super =
Option.value ~default:(env, None)
@@ Option.map2
sub
super
~f:(Typing_ops.sub_type_decl ~is_coeffect ~on_error pos reason env)
in
(* TODO(T88552052) This can be greatly simplified by adopting the { A = S..T } representation
* from DOT and implementing the Typ-<:-Typ rule, Amin 2016 *)
let env =
match parent_typeconst.ttc_kind with
| TCAbstract
{
atc_as_constraint = p_as_opt;
atc_super_constraint = p_super_opt;
_;
} -> begin
match child_typeconst.ttc_kind with
| TCAbstract
{
atc_as_constraint = c_as_opt;
atc_super_constraint = c_super_opt;
_;
} ->
(* TODO(T88552052) this transformation can be done with mixed and nothing *)
let c_as_opt = Some (Option.value c_as_opt ~default) in
let c_super_opt = Some (Option.value c_super_opt ~default) in
let (env, e1) =
check_cstrs Reason.URsubsume_tconst_cstr env c_as_opt p_as_opt
in
let (env, e2) =
check_cstrs Reason.URsubsume_tconst_cstr env p_super_opt c_super_opt
in
let ty_err_opt = Option.merge e1 e2 ~f:Typing_error.both in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
env
| TCConcrete { tc_type = c_t } ->
let (env, e1) =
check_cstrs Reason.URtypeconst_cstr env (Some c_t) p_as_opt
in
let (env, e2) =
check_cstrs Reason.URtypeconst_cstr env p_super_opt (Some c_t)
in
let ty_err_opt = Option.merge e1 e2 ~f:Typing_error.both in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
env
end
| TCConcrete _ ->
begin
match child_typeconst.ttc_kind with
| TCConcrete _ ->
if
TCO.typeconst_concrete_concrete_error (Env.get_tcopt env)
&& not inherited
then
Typing_error_utils.add_typing_error
~env
Typing_error.(
assert_in_current_decl
~ctx:(Env.get_current_decl_and_file env)
@@ Secondary.Typeconst_concrete_concrete_override
{ pos; parent_pos })
| _ -> ()
end;
env
in
(* Don't recheck inherited type constants: errors will
* have been emitted already for the parent *)
(if inherited then
()
else
match (child_typeconst.ttc_kind, parent_tconst_enforceable) with
| (TCAbstract { atc_default = Some ty; _ }, (tp_pos, true))
| (TCConcrete { tc_type = ty }, (tp_pos, true)) ->
let emit_error pos ty_info =
Typing_error_utils.add_typing_error
~env
Typing_error.(
primary
@@ Primary.Invalid_enforceable_type
{ pos; ty_info; kind = `constant; tp_pos; tp_name = name })
in
Typing_enforceable_hint.validate_type
env
(fst child_typeconst.ttc_name |> Pos_or_decl.unsafe_to_raw_pos)
ty
emit_error
| _ ->
();
(match parent_typeconst.ttc_reifiable with
| None -> ()
| Some pos ->
Typing_const_reifiable.check_reifiable env child_typeconst pos));
(* If the parent cannot be overridden, we unify the types otherwise we ensure
* the child's assigned type is compatible with the parent's
*
* TODO(T88552052) restrict concrete typeconst overriding
*)
let parent_is_final =
match parent_typeconst.ttc_kind with
| TCConcrete _ -> true
| TCAbstract _ -> false
in
let check env x y =
if parent_is_final then
Typing_ops.unify_decl
pos
Reason.URsubsume_tconst_assign
env
on_error
x
y
else
Typing_ops.sub_type_decl
~on_error
pos
Reason.URsubsume_tconst_assign
env
y
x
in
(* TODO(T88552052) this fetching of types is a temporary hack; this whole check will be eliminated *)
let opt_type__LEGACY t =
match t.ttc_kind with
| TCConcrete { tc_type = t } -> Some t
| TCAbstract _ -> None
in
let (env, ty_err_opt) =
Option.value ~default:(env, None)
@@ Option.map2
(opt_type__LEGACY parent_typeconst)
(opt_type__LEGACY child_typeconst)
~f:(check env)
in
Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env);
env
let check_abstract_typeconst_in_concrete_class env (class_pos, class_) tconst =
let is_final = Cls.final class_ in
if Ast_defs.is_c_concrete (Cls.kind class_) || is_final then
match tconst.ttc_kind with
| TCAbstract _ ->
let (typeconst_pos, typeconst_name) = tconst.ttc_name in
let trace =
lazy
(Ancestor_route.describe_route
env
~classish:(Cls.name class_)
~ancestor:tconst.ttc_origin)
in
Typing_error_utils.add_typing_error
~env
Typing_error.(
primary
@@ Primary.Implement_abstract
{
is_final;
pos = class_pos;
decl_pos = typeconst_pos;
trace;
kind = `ty_const;
name = typeconst_name;
quickfixes = [];
})
| TCConcrete _ -> ()
let check_typeconst_override
env
implements
(class_pos, class_)
parent_tconst
tconst
parent_class
on_error =
if String.equal parent_tconst.ttc_origin tconst.ttc_origin then (
check_abstract_typeconst_in_concrete_class env (class_pos, class_) tconst;
env
) else
let tconst_check parent_tconst tconst () =
let parent_tconst_enforceable =
(* We know that this typeconst exists in the parent (else we would not
have successfully looked up [parent_tconst]), so we know that
[get_typeconst_enforceability] will return Some. *)
Option.value_exn
(Cls.get_typeconst_enforceability parent_class (snd tconst.ttc_name))
in
tconst_subsumption
env
(Cls.name class_)
parent_tconst
parent_tconst_enforceable
tconst
on_error
in
let env =
check_ambiguous_inheritance
tconst_check
parent_tconst
tconst
(fst tconst.ttc_name)
class_
tconst.ttc_origin
on_error
~env
in
let (pos, name) = tconst.ttc_name in
let parent_pos = fst parent_tconst.ttc_name in
(* Temporarily skip checks on context constants
*
* TODO(T89366955) elimninate this check *)
let is_context_constant =
match (parent_tconst.ttc_kind, tconst.ttc_kind) with
| ( TCAbstract { atc_default = Some hint1; _ },
TCAbstract { atc_default = Some hint2; _ } ) ->
(match (deref hint1, deref hint2) with
| ((_, Tintersection _), _)
| (_, (_, Tintersection _)) ->
true
| _ -> false)
| (TCAbstract { atc_default = Some hint; _ }, _)
| (_, TCAbstract { atc_default = Some hint; _ }) ->
(match deref hint with
| (_, Tintersection _) -> true
| _ -> false)
| _ -> false
in
(match (parent_tconst.ttc_kind, tconst.ttc_kind) with
| (TCConcrete _, TCConcrete _)
| ( TCAbstract { atc_default = Some _; _ },
TCAbstract { atc_default = Some _; _ } ) ->
if
(not is_context_constant)
&& (not tconst.ttc_synthesized)
&& (not parent_tconst.ttc_synthesized)
&& conflict_with_declared_interface_or_trait
~include_traits:false
env
implements
parent_class
class_
parent_tconst.ttc_origin
tconst.ttc_origin
name
then
let child_is_abstract = is_typeconst_type_abstract tconst in
let err =
Typing_error.Secondary.Interface_typeconst_multiple_defs
{
pos;
name;
is_abstract = child_is_abstract;
origin = tconst.ttc_origin;
parent_pos;
parent_origin = parent_tconst.ttc_origin;
}
in
Typing_error_utils.add_typing_error ~env
@@ Typing_error.(apply_reasons ~on_error err)
| _ -> ());
env
(* Use the [on_error] callback if we need to wrap the basic error with a
* "Class ... does not correctly implement all required members"
* message pointing at the class being checked.
*)
let check_class_extends_parent_constructors
env (parent_class : (Pos.t * string) * decl_ty list * Cls.t) class_ on_error
=
let (_, parent_tparaml, parent_class) = parent_class in
let psubst = Inst.make_subst (Cls.tparams parent_class) parent_tparaml in
let env = check_constructors env parent_class class_ psubst on_error in
env
(** Eliminate all synthesized members (those from requirements) plus
all private members unless they're from traits. *)
let filter_privates_and_synthethized
~(is_trait : bool) (members : ('a * class_elt) list) : ('a * class_elt) list
=
let eliminate class_elt =
get_ce_synthesized class_elt
|| ((not is_trait) && Typing_defs.class_elt_is_private_not_lsb class_elt)
in
let keep class_elt = not (eliminate class_elt) in
List.filter members ~f:(fun (_name, class_elt) -> keep class_elt)
let make_parent_member_map
((parent_name_pos, _parent_name), parent_tparaml, parent_class) :
ParentClassElt.parent * class_elt MemberNameMap.t MemberKindMap.t =
let psubst = Inst.make_subst (Cls.tparams parent_class) parent_tparaml in
let member_map =
make_all_members ~parent_class
|> MemberKindMap.of_list
|> MemberKindMap.map (fun members ->
members
|> filter_privates_and_synthethized
~is_trait:(Ast_defs.is_c_trait (Cls.kind parent_class))
|> SMap.of_list
|> SMap.map (Inst.instantiate_ce psubst))
in
((parent_name_pos, parent_class), member_map)
(** Check for multiple kinds of forbidden hierarchy diamonds involving traits:
- Any kind of diamond involving final methods is forbidden unless the class has __EnableMethodTraitDiamond
and the diamond involves only traits.
- Diamonds involving only traits, with the trait at the top of the diamond containing at least one method,
are only allowed if the classish has __EnableMethodTraitDiamond attribute.
- Any kind of diamond involving properties with a generic type instantiated differently along the
two paths of the diamond is forbidden.
[check_trait_diamonds env ~allow_diamonds ~class_name ~member_name elt elts member_kind] considers [elt] and [elts].
Members from [elt] union [elts] have the same name [member_name]. [elts] represents all the members with this member name
that we've seen so far from the parents we are merging. In this function, we'll detect diamonds by checking if
[elt] has the same origin as one of the elements in [elts] and produce an error if that diamond is forbidden. *)
let check_trait_diamonds
env
~(allow_diamonds : bool)
~class_name
~member_name
((class_elt, (pos, parent)) as parent_class_elt)
elts
member_kind :
(ParentClassElt.t * ParentClassEltSet.t)
* ((string * string) * Typing_error.t) option =
let default_parent_class_elt () = ParentClassElt.make parent_class_elt in
if
(* We'll check some of those conditions later but check them first
here to avoid an expensive set lookup if we can. *)
(* Note that we never check that the origin of class_elt is a trait, because that
would require a decl heap lookup which is expensive. But that should follow from the
following facts: 1) the parent from which class_elt comes from is a trait - 2) the member
is not synthetic, i.e. not from a `require extends`, since we've filtered those out earlier -
3) the member is not abstract, so not from a `require implements` either. *)
Ast_defs.is_c_trait (Cls.kind parent)
&& (not (get_ce_abstract class_elt))
&& (MemberKind.is_method member_kind
&& ((not allow_diamonds) || get_ce_final class_elt)
|| MemberKind.is_property member_kind)
then
(* Let's search for a diamond. *)
(* We want to find an existing element with the same origin,
* i.o.w, find a diamond.
* Set.find_first_opt only works for 'monotonic' `f` which is
* not the case for the equality test, and Set.find_opt
* uses the polymorphic equaliy: we only want to test for origin.
* Set doesn't provide a `find with condition` so we do an iteration
* and bail at the first occurrence we spot
*
* This works in a deterministic way because the set we are working
* with has the invariant that each element have a unique origin.
*)
let candidate =
ParentClassEltSet.find_one_opt
elts
~f:(fun { ParentClassElt.class_elt = prev_class_elt; _ } ->
String.equal class_elt.ce_origin prev_class_elt.ce_origin)
in
match candidate with
| None -> ((default_parent_class_elt (), elts), None)
| Some
({
ParentClassElt.class_elt = prev_class_elt;
parent = (_, prev_parent);
errors_if_not_overriden = err;
} as prev_parent_class_elt) ->
if
MemberKind.is_method member_kind
&& get_ce_final class_elt
&& ((not allow_diamonds) || Cls.kind prev_parent |> Ast_defs.is_c_class)
then
let error =
(* We want only one such error per diamond (instead of one per diamond per final method),
so let's return the diamond corners and the error and let the caller aggregate per diamond. *)
Some
( (Cls.name prev_parent, class_elt.ce_origin),
Trait_reuse_check.trait_reuse_with_final_method_error
env
class_elt
~class_name:(snd class_name)
~first_using_parent_or_trait:prev_parent
~second_using_trait:(pos, parent) )
in
(* Let's keep the previous parent class element, whose parent is a class,
to detect additional such errors if there are more diamonds. *)
((prev_parent_class_elt, elts), error)
else if
MemberKind.is_method member_kind
&& (not allow_diamonds)
&& Cls.kind prev_parent |> Ast_defs.is_c_trait
then
let parent_class_elt =
ParentClassElt.make
parent_class_elt
~errors_if_not_overriden:
(lazy
(Trait_reuse_check.method_import_via_diamond_error
env
class_name
(member_name, class_elt)
~first_using_trait:prev_parent
~second_using_trait:parent)
:: err)
in
let elts =
ParentClassEltSet.remove elts (default_parent_class_elt ())
in
((parent_class_elt, elts), None)
else if MemberKind.is_property member_kind then
if allow_diamonds then begin
(* traits with properties cannot be inherited via multiple paths
if the base class has the <<__EnableMethodTraitDiamond>> attribute *)
Trait_reuse_check.property_import_via_diamond_error
~generic:false
env
class_name
(member_name, class_elt)
~first_using_trait:prev_parent
~second_using_trait:parent;
((default_parent_class_elt (), elts), None)
end else if
not
(ty_equal
(Lazy.force class_elt.ce_type)
(Lazy.force prev_class_elt.ce_type))
then begin
(* it is unsound to use a trait that defines a generic property
at different types along multiple paths *)
Trait_reuse_check.property_import_via_diamond_error
~generic:true
env
class_name
(member_name, class_elt)
~first_using_trait:prev_parent
~second_using_trait:parent;
((default_parent_class_elt (), elts), None)
end else
((default_parent_class_elt (), elts), None)
else
((default_parent_class_elt (), elts), None)
else
((default_parent_class_elt (), elts), None)
(** Selects the minimum classes out of a list using the partial ordering
provided by the subtyping relationship. *)
let minimum_classes env classes =
let is_sub_type x y =
Decl_provider.get_class (Env.get_ctx env) x
>>= (fun x -> Cls.get_ancestor x y)
|> Option.is_some
in
let add_min is_lower x mins =
let rec go mins result =
match mins with
| [] -> x :: result
| y :: ys ->
if is_lower x y then
go ys result
else if is_lower y x then
List.rev_append result mins
else
go ys (y :: result)
in
go mins []
in
List.fold classes ~init:[] ~f:(fun minimum_classes class_ ->
add_min is_sub_type class_ minimum_classes)
let check_no_conflicting_inherited_concrete_constants
env name constants class_pos =
let open ParentClassConst in
let definitions =
ParentClassConstSet.filter
(fun { class_const = { cc_abstract; _ }; _ } ->
match cc_abstract with
| CCConcrete -> true
| CCAbstract _ -> false)
constants
|> ParentClassConstSet.elements
in
if List.length definitions > 1 then
let err =
Typing_error.Primary.Constant_multiple_concrete_conflict
{
pos = class_pos;
name;
definitions =
List.map
~f:(fun { class_const; parent } ->
let parent_name = Cls.name (snd parent) in
let via =
if String.(parent_name <> class_const.cc_origin) then
Some (Utils.strip_ns parent_name)
else
None
in
(class_const.cc_pos, via))
definitions;
}
in
Typing_error_utils.add_typing_error ~env (Typing_error.primary err)
(* When a class inherits a concrete type constant from two different points in its hierarchy
* (e.g. a parent class and an interface) HHVM will fail to load the class, and the flag
* -vEval.TraitConstantInterfaceBehavior=1 extends this behavior to traits. This function reports
* such cases, pointing to the definitions of the constants and reporting which parent brings them
* in, e.g. declared in an interface brought in via a trait use. *)
let check_no_conflicting_inherited_concrete_typeconsts
env name typeconsts class_pos =
let open ParentTypeConst in
let definitions =
ParentTypeConstSet.filter
(fun { typeconst = { ttc_kind; ttc_synthesized; _ }; _ } ->
match ttc_kind with
| TCConcrete _ ->
if TCO.enable_strict_const_semantics (Env.get_tcopt env) > 2 then
not ttc_synthesized
else
true
| TCAbstract _ -> false)
typeconsts
|> ParentTypeConstSet.elements
in
if List.length definitions > 1 then
let err =
Typing_error.Primary.Constant_multiple_concrete_conflict
{
pos = class_pos;
name;
definitions =
List.map
~f:(fun { typeconst; parent } ->
let parent_name = Cls.name (snd parent) in
let via =
if String.(parent_name <> typeconst.ttc_origin) then
Some (Utils.strip_ns parent_name)
else
None
in
(fst typeconst.ttc_name, via))
definitions;
}
in
Typing_error_utils.add_typing_error ~env (Typing_error.primary err)
let union_parent_constants parents : ParentClassConstSet.t MemberNameMap.t =
let get_declared_consts ((parent_name_pos, _), parent_tparaml, parent_class) =
let psubst = Inst.make_subst (Cls.tparams parent_class) parent_tparaml in
let consts =
Cls.consts parent_class
|> List.filter ~f:(fun (_, cc) -> not cc.cc_synthesized)
|> List.map ~f:(Tuple.T2.map_snd ~f:(Inst.instantiate_cc psubst))
in
((parent_name_pos, parent_class), consts)
in
parents
|> List.map ~f:get_declared_consts
|> List.fold ~init:MemberNameMap.empty ~f:(fun acc (parent, consts) ->
List.fold
~init:acc
~f:(fun acc (name, const) ->
let open ParentClassConstSet in
let elt = ParentClassConst.make const parent in
MemberNameMap.update
name
(function
| None -> Some (singleton elt)
| Some elts -> Some (add elt elts))
acc)
consts)
let union_parent_typeconsts env parents : ParentTypeConstSet.t MemberNameMap.t =
let get_declared_consts ((parent_name_pos, _), parent_tparaml, parent_class) =
let psubst = Inst.make_subst (Cls.tparams parent_class) parent_tparaml in
let typeconsts =
Cls.typeconsts parent_class
|> List.filter ~f:(fun (_, ttc) ->
TCO.enable_strict_const_semantics (Env.get_tcopt env) > 2
|| not ttc.ttc_synthesized)
|> List.map
~f:(Tuple.T2.map_snd ~f:(Inst.instantiate_typeconst_type psubst))
in
((parent_name_pos, parent_class), typeconsts)
in
parents
|> List.map ~f:get_declared_consts
|> List.fold ~init:MemberNameMap.empty ~f:(fun acc (parent, typeconsts) ->
List.fold
~init:acc
~f:(fun acc (name, typeconst) ->
let open ParentTypeConstSet in
let elt = ParentTypeConst.make typeconst parent in
MemberNameMap.update
name
(function
| None -> Some (singleton elt)
| Some elts -> Some (add elt elts))
acc)
typeconsts)
let check_class_extends_parents_constants
env
implements
(class_ast, class_)
(parents : ((Pos.t * string) * decl_ty list * Cls.t) list)
(on_error : Pos.t * string -> Typing_error.Reasons_callback.t) =
let constants : ParentClassConstSet.t MemberNameMap.t =
union_parent_constants parents
in
let class_pos = fst class_ast.Aast.c_name in
MemberNameMap.fold
(fun const_name inherited env ->
if TCO.enable_strict_const_semantics (Env.get_tcopt env) > 1 then
check_no_conflicting_inherited_concrete_constants
env
const_name
inherited
class_pos;
(* TODO(vmladenov): factor individual checks out of check_const_override and remove [implements] parameter *)
ParentClassConstSet.fold
(fun ParentClassConst.
{
parent = (parent_pos, parent_class);
class_const = parent_const;
}
env ->
match Cls.get_const class_ const_name with
| Some const ->
(* skip checks for typeconst derived class constants *)
(match Cls.get_typeconst class_ const_name with
| None ->
check_const_override
env
implements
const_name
parent_class
(class_pos, class_)
parent_const
const
(on_error (parent_pos, Cls.name parent_class))
| Some _ -> env)
| None ->
let err =
Typing_error.(
primary
@@ Primary.Member_not_implemented
{
pos = parent_pos;
member_name = const_name;
decl_pos = parent_const.cc_pos;
quickfixes = [];
})
in
Typing_error_utils.add_typing_error ~env err;
env)
inherited
env)
constants
env
let check_class_extends_parents_typeconsts
env
implements
(class_ast, class_)
(parents : ((Pos.t * string) * decl_ty list * Cls.t) list)
(on_error : Pos.t * string -> Typing_error.Reasons_callback.t) =
let typeconsts : ParentTypeConstSet.t MemberNameMap.t =
union_parent_typeconsts env parents
in
let class_pos = fst class_ast.Aast.c_name in
MemberNameMap.fold
(fun tconst_name inherited env ->
if TCO.enable_strict_const_semantics (Env.get_tcopt env) > 1 then
check_no_conflicting_inherited_concrete_typeconsts
env
tconst_name
inherited
class_pos;
ParentTypeConstSet.fold
(fun ParentTypeConst.
{
parent = (parent_pos, parent_class);
typeconst = parent_tconst;
}
env ->
(* If class_ is a trait that has a require class C constraint, and C provides a concrete definition
* for the type constant, and the parent definition is abstract, then compare the parent type constant
* against the type constant defined in the required class.
* Otherwise compare it against the type constant defined in class_, if any.
* However, if the parent definition is a concrete type constant, then we can skip checking type constants
* inherited via require class constants, as these must be concrete and a conflict check will be
* performed on the class itself *)
let is_parent_tconst_abstract =
is_typeconst_type_abstract parent_tconst
in
let class_tconst_opt =
let tconst_element = Cls.get_typeconst class_ tconst_name in
if
Ast_defs.is_c_trait (Cls.kind class_) && is_parent_tconst_abstract
then
Option.map tconst_element ~f:(fun tconst_element ->
if String.equal tconst_element.ttc_origin (Cls.name class_)
then
tconst_element
else
let tconst_element_in_req_class =
List.find_map
(Cls.all_ancestor_req_class_requirements class_)
~f:(fun (_, req_ty) ->
let (_, (_, cn), _) =
TUtils.unwrap_class_type req_ty
in
Decl_provider.get_class (Env.get_ctx env) cn
>>= fun cnc ->
(* Since only final classes can satisfy require class constraints, if the type constant is
* found in the require class then it must be concrete. No need to check that here. *)
Cls.get_typeconst cnc tconst_name)
in
match tconst_element_in_req_class with
| Some tconst_element_in_req_class ->
{
tconst_element_in_req_class with
ttc_synthesized = true;
}
| None -> tconst_element)
else
tconst_element
in
match class_tconst_opt with
| Some tconst ->
check_typeconst_override
env
implements
(class_pos, class_)
parent_tconst
tconst
parent_class
(on_error (parent_pos, Cls.name parent_class))
| None ->
(* The only case when a member belongs to a parent but not the child is if the parent is an
interface and the child is a concrete class. Otherwise, the member would have been inherited. *)
let err =
Typing_error.(
primary
@@ Primary.Member_not_implemented
{
pos = parent_pos;
member_name = tconst_name;
decl_pos = fst parent_tconst.ttc_name;
quickfixes = [];
})
in
Typing_error_utils.add_typing_error ~env err;
env)
inherited
env)
typeconsts
env
let merge_member_maps
env
~allow_diamonds
~class_name
(acc_map : ParentClassEltSet.t MemberNameMap.t MemberKindMap.t)
((parent, map) :
ParentClassElt.parent * class_elt MemberNameMap.t MemberKindMap.t) :
ParentClassEltSet.t MemberNameMap.t MemberKindMap.t =
let errors_per_diamond = ref SMap.empty in
let members =
MemberKindMap.fold
(fun mem_kind
(members : class_elt MemberNameMap.t)
(acc_map : ParentClassEltSet.t MemberNameMap.t MemberKindMap.t) ->
let members_for_mem_kind =
match MemberKindMap.find_opt mem_kind acc_map with
| None ->
MemberNameMap.map
(fun elt ->
ParentClassElt.make (elt, parent) |> ParentClassEltSet.singleton)
members
| Some prev_members ->
let members =
MemberNameMap.merge
(fun member_name elt elts ->
match (elt, elts) with
| (None, None) -> None
| (Some elt, None) ->
Some
(ParentClassElt.make (elt, parent)
|> ParentClassEltSet.singleton)
| (None, (Some _ as elts)) -> elts
| (Some elt, Some elts) ->
let ((elt, elts), error) =
check_trait_diamonds
env
~allow_diamonds
~class_name
~member_name
(elt, parent)
elts
mem_kind
in
(* We want only one error per diamond, so we aggregate errors in
`errors_per_diamond` before adding them later. *)
Option.iter error ~f:(fun ((parent, origin), error) ->
errors_per_diamond :=
SMap.add
parent
(SMap.add
~combine:(fun x _ -> x)
origin
error
(SMap.find_opt parent !errors_per_diamond
|> Option.value ~default:SMap.empty))
!errors_per_diamond);
Some (ParentClassEltSet.add elts elt))
members
prev_members
in
members
in
MemberKindMap.add mem_kind members_for_mem_kind acc_map)
map
acc_map
in
SMap.iter
(fun _ errors_per_origin ->
SMap.keys errors_per_origin
|> minimum_classes env
|> List.iter ~f:(fun origin ->
SMap.find origin errors_per_origin
|> Typing_error_utils.add_typing_error ~env))
!errors_per_diamond;
members
let union_parent_members env class_ast parents :
ParentClassEltSet.t MemberNameMap.t MemberKindMap.t =
let allow_diamonds =
Naming_attributes.mem
SN.UserAttributes.uaEnableMethodTraitDiamond
class_ast.Aast.c_user_attributes
in
let class_name = class_ast.Aast.c_name in
parents
|> List.map ~f:make_parent_member_map
|> List.fold
~init:MemberKindMap.empty
~f:(merge_member_maps env ~allow_diamonds ~class_name)
let check_class_extends_parents_members
env
(class_ast, class_)
(parents : ((Pos.t * string) * decl_ty list * Cls.t) list)
(on_error : Pos.t * string -> Typing_error.Reasons_callback.t) =
let members : ParentClassEltSet.t MemberNameMap.t MemberKindMap.t =
union_parent_members env class_ast parents
in
check_members_from_all_parents
env
(fst class_ast.Aast.c_name, class_)
on_error
members
let check_consts_are_not_abstract
env ~is_final ~class_name_pos (consts : Nast.class_const list) =
List.iter consts ~f:(fun const ->
match const.Aast.cc_kind with
| Aast.CCAbstract _ ->
Typing_error_utils.add_typing_error
~env
Typing_error.(
primary
@@ Primary.Abstract_member_in_concrete_class
{
pos = fst const.Aast.cc_id;
class_name_pos;
is_final;
member_kind = `constant;
member_name = snd const.Aast.cc_id;
})
| Aast.CCConcrete _ -> ())
let check_typeconsts_are_not_abstract env ~is_final ~class_name_pos typeconsts =
List.iter typeconsts ~f:(fun tc ->
match tc.Aast.c_tconst_kind with
| Aast.TCAbstract _ ->
Typing_error_utils.add_typing_error
~env
Typing_error.(
primary
@@ Primary.Abstract_member_in_concrete_class
{
pos = fst tc.Aast.c_tconst_name;
class_name_pos;
is_final;
member_kind = `type_constant;
member_name = snd tc.Aast.c_tconst_name;
})
| Aast.TCConcrete _ -> ())
let check_properties_are_not_abstract
env ~is_final ~class_name_pos (properties : Nast.class_var list) =
List.iter properties ~f:(fun property ->
if property.Aast.cv_abstract then
Typing_error_utils.add_typing_error
~env
Typing_error.(
primary
@@ Primary.Abstract_member_in_concrete_class
{
pos = fst property.Aast.cv_id;
class_name_pos;
is_final;
member_kind = `property;
member_name = snd property.Aast.cv_id;
}))
let check_methods_are_not_abstract
env ~is_final ~class_name_pos (methods : Nast.method_ list) =
List.iter methods ~f:(fun (method_ : (unit, unit) Aast.method_) ->
if method_.Aast.m_abstract then
Typing_error_utils.add_typing_error
~env
Typing_error.(
primary
@@ Primary.Abstract_member_in_concrete_class
{
pos = fst method_.Aast.m_name;
class_name_pos;
is_final;
member_kind = `method_;
member_name = snd method_.Aast.m_name;
}))
(** Error if there are abstract members in a concrete class' AST. *)
let check_concrete_has_no_abstract_members env (class_ : Nast.class_) =
let {
Aast.c_kind;
c_final = is_final;
c_typeconsts;
c_consts;
c_vars;
c_methods;
c_name = (class_name_pos, _);
_;
} =
class_
in
if Ast_defs.is_c_concrete c_kind || is_final then (
check_consts_are_not_abstract env ~class_name_pos ~is_final c_consts;
check_typeconsts_are_not_abstract env ~class_name_pos ~is_final c_typeconsts;
check_properties_are_not_abstract env ~class_name_pos ~is_final c_vars;
check_methods_are_not_abstract env ~class_name_pos ~is_final c_methods
);
(* Checking that a concrete class does not inherit abstract members is checked
* when checking against a class' parents. *)
()
(*****************************************************************************)
(* The externally visible function *)
(*****************************************************************************)
(* [parents] also contains traits.
Here's a simple example showing why we need to check overriding traits:
trait T {
public function foo(): void {}
public function bar(): void {
$this->foo();
}
}
class A {
use T;
public function foo(int $x): void {}
}
Overriding foo this way is unsound due to bar using foo,
so A::foo needs to be a subtype of T::foo.
*)
let check_implements_extends_uses
env
~implements
~(parents : (Aast.hint * Typing_defs.decl_ty) list)
(class_ast, class_) =
let (name_pos, name) = class_ast.Aast.c_name in
let implements =
let decl_ty_to_cls x =
let (_, (pos, name), _) = TUtils.unwrap_class_type x in
Env.get_class env name >>| fun class_ -> (pos, class_)
in
List.filter_map implements ~f:decl_ty_to_cls
in
let on_error (parent_name_pos, parent_name) : Typing_error.Reasons_callback.t
=
(* sadly, enum error reporting requires this to keep the error in the file
with the enum *)
if String.equal parent_name SN.Classes.cHH_BuiltinEnum then
Typing_error.Reasons_callback.bad_enum_decl name_pos
else
Typing_error.Reasons_callback.bad_decl_override
~name
~parent_pos:parent_name_pos
~parent_name
in
let parents =
let destructure_type ((p, _h), ty) =
let (_, (_, name), tparaml) = TUtils.unwrap_class_type ty in
Env.get_class env name >>| fun class_ -> ((p, name), tparaml, class_)
in
List.filter_map parents ~f:destructure_type
in
let env =
List.fold ~init:env parents ~f:(fun env ((parent_name, _, _) as parent) ->
check_class_extends_parent_constructors
env
parent
class_
(on_error parent_name))
in
let env =
check_class_extends_parents_constants
env
implements
(class_ast, class_)
parents
on_error
in
let env =
check_class_extends_parents_typeconsts
env
implements
(class_ast, class_)
parents
on_error
in
let env =
check_class_extends_parents_members env (class_ast, class_) parents on_error
in
check_concrete_has_no_abstract_members env class_ast;
env |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_extends.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(** Checks that a classish type implements its interfaces, extends its base class, and
uses its traits.
[implements] is the list of interfaces the classish type directly implements.
[parents] is the list of direct ancestors and traits the class directly uses. *)
val check_implements_extends_uses :
Typing_env_types.env ->
(* All directly implemented interfaces *)
implements:Typing_defs.decl_ty list ->
(* All direct parents (interfaces, base type, traits) *)
parents:(Aast.hint * Typing_defs.decl_ty) list ->
(* The type to be checked *)
Nast.class_ * Decl_provider.Class.t ->
Typing_env_types.env |
OCaml | hhvm/hphp/hack/src/typing/typing_exts.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(*
Ad-hoc rules for typing some common idioms
For printf-style functions: If the last argument (before varargs) of a
function has the type FormatString<X>, we assume that the format
string is interpreted by the formatter X, which should look like this:
interface PrintfFormatter {
function format_0x25() : string;
function format_x(int) : string;
function format_f(float) : string;
function format_upcase_l() : PrintfFormatter;
}
Each method can return a string or another formatter (for
multi-character sequences like %Ld); the parameters are copied into
the function signature when instantiating it at the call site.
*)
open Hh_prelude
open Typing_defs
open Typing_env_types
open Aast
module Env = Typing_env
module Reason = Typing_reason
module Print = Typing_print
module SN = Naming_special_names
let magic_method_name input =
match input with
| None -> "format_eof"
| Some c ->
let uc = Char.uppercase c and lc = Char.lowercase c in
if Char.equal lc uc then
Printf.sprintf "format_0x%02x" (Char.to_int lc)
else if Char.equal c uc then
"format_upcase_" ^ String.make 1 lc
else
"format_" ^ String.make 1 lc
let lookup_magic_type (env : env) use_pos (class_ : locl_ty) (fname : string) :
env * (locl_fun_params * locl_ty option) option =
match get_node (Typing_utils.strip_dynamic env class_) with
| Tclass ((_, className), _, []) ->
let ( >>= ) = Option.( >>= ) in
let ce_type =
let lookup_def c =
Option.first_some
(Env.get_member true env c fname)
(Env.get_member true env c "format_wild")
in
Env.get_class env className >>= lookup_def
>>= fun { ce_type = (lazy ty); ce_pos = (lazy pos); _ } ->
match deref ty with
| (_, Tfun fty) ->
(* Ugly hack to remove like-type from return syntactically so that in dynamic mode
* we don't simplify it to dynamic.
*)
let fty =
{
fty with
ft_ret =
{
fty.ft_ret with
et_type =
(match get_node fty.ft_ret.et_type with
| Tlike ty -> ty
| _ -> fty.ft_ret.et_type);
};
}
in
let ety_env = empty_expand_env in
let instantiation =
Typing_phase.{ use_pos; use_name = fname; explicit_targs = [] }
in
Some
(Typing_phase.localize_ft
~instantiation
~def_pos:pos
~ety_env
env
fty)
| _ -> None
in
begin
match ce_type with
| Some
( (env, ty_err_opt),
{ ft_params = pars; ft_ret = { et_type = ty; _ }; _ } ) ->
Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env);
let (env, ty) = Env.expand_type env ty in
let ty_opt =
match get_node ty with
| Tprim Tstring -> None
| Tdynamic -> None
| _ -> Some ty
in
(env, Some (pars, ty_opt))
| _ -> (env, None)
end
| _ -> (env, None)
let get_char s i =
if i >= String.length s then
None
else
Some s.[i]
let parse_printf_string env s pos (class_ : locl_ty) : env * locl_fun_params =
let rec read_text env i : env * locl_fun_params =
match get_char s i with
| Some '%' -> read_modifier env (i + 1) class_ i
| Some _ -> read_text env (i + 1)
| None -> (env, [])
and read_modifier env i class_ i0 : env * locl_fun_params =
let fname = magic_method_name (get_char s i) in
let snippet =
String.sub s ~pos:i0 ~len:(min (i + 1) (String.length s) - i0)
in
let add_reason =
List.map ~f:(fun p ->
let et_type =
p.fp_type.et_type
|> map_reason ~f:(fun r -> Reason.Rformat (pos, snippet, r))
in
{ p with fp_type = { p.fp_type with et_type } })
in
match lookup_magic_type env pos class_ fname with
| (env, Some (good_args, None)) ->
let (env, xs) = read_text env (i + 1) in
(env, add_reason good_args @ xs)
| (env, Some (good_args, Some next)) ->
let (env, xs) = read_modifier env (i + 1) next i0 in
(env, add_reason good_args @ xs)
| (env, None) ->
Typing_error_utils.add_typing_error
~env
Typing_error.(
primary
@@ Primary.Format_string
{
pos;
snippet;
fmt_string = s;
class_pos = get_pos class_;
fn_name = fname;
class_suggest = Print.full_strip_ns env class_;
});
let (env, xs) = read_text env (i + 1) in
(env, add_reason xs)
in
read_text env 0
type ('a, 'b) either =
| Left of 'a
| Right of 'b
let mapM (f : 's -> 'x -> 's * 'y) : 'st -> 'x list -> 's * 'y list =
let rec f' st xs =
match xs with
| [] -> (st, [])
| x :: xs ->
let (st', x') = f st x in
let (st'', xs') = f' st' xs in
(st'', x' :: xs')
in
f'
(* If expr is a constant string, that string, otherwise a position
where it is obviously not *)
let rec const_string_of (env : env) (e : Nast.expr) :
env * (Pos.t, string) either =
let glue x y =
match (x, y) with
| (Right sx, Right sy) -> Right (sx ^ sy)
| (Left p, _) -> Left p
| (_, Left p) -> Left p
in
match e with
| (_, _, String s) -> (env, Right s)
(* It's an invariant that this is going to fail, but look for the best
* evidence *)
| (_, p, String2 xs) ->
let (env, xs) = mapM const_string_of env (List.rev xs) in
(env, List.fold_right ~f:glue xs ~init:(Left p))
| (_, _, Binop Aast.{ bop = Ast_defs.Dot; lhs; rhs }) ->
let (env, stra) = const_string_of env lhs in
let (env, strb) = const_string_of env rhs in
(env, glue stra strb)
| (_, p, _) -> (env, Left p)
let get_format_string_type_arg t =
match get_node t with
| Tnewtype (fs, [ty], _) when SN.Classes.is_format_string fs -> Some ty
| _ -> None
let rec get_possibly_like_format_string_type_arg t =
match get_node t with
| Tunion [t1; t2] when is_dynamic t1 ->
get_possibly_like_format_string_type_arg t2
| Toption t -> get_possibly_like_format_string_type_arg t
| _ -> get_format_string_type_arg t
(* Specialize a function type using whatever we can tell about the args *)
let retype_magic_func
(env : env)
(ft : locl_fun_type)
(el : (Ast_defs.param_kind * Nast.expr) list) : env * locl_fun_type =
let rec f env param_types (args : (Ast_defs.param_kind * Nast.expr) list) :
env * locl_fun_params option =
match (param_types, args) with
| ([{ fp_type = { et_type; _ }; _ }], [(_, (_, _, Null))])
when is_some (get_possibly_like_format_string_type_arg et_type) ->
(env, None)
| ([({ fp_type = { et_type; _ }; _ } as fp)], (_, arg) :: _) -> begin
match get_possibly_like_format_string_type_arg et_type with
| Some type_arg ->
(match const_string_of env arg with
| (env, Right str) ->
let (_, pos, _) = arg in
let (env, argl) = parse_printf_string env str pos type_arg in
( env,
Some
({
fp with
fp_type =
{
et_type = mk (get_reason et_type, Tprim Tstring);
et_enforced = Unenforced;
};
}
:: argl) )
| (env, Left pos) ->
Typing_error_utils.add_typing_error
~env
Typing_error.(primary @@ Primary.Expected_literal_format_string pos);
(env, None))
| None -> (env, None)
end
| (param :: params, _ :: args) ->
(match f env params args with
| (env, None) -> (env, None)
| (env, Some xs) -> (env, Some (param :: xs)))
| _ -> (env, None)
in
let non_variadic_param_types =
if get_ft_variadic ft then
List.drop_last_exn ft.ft_params
else
ft.ft_params
in
match f env non_variadic_param_types el with
| (env, None) -> (env, ft)
| (env, Some xs) ->
( env,
{
ft with
ft_params = xs;
ft_flags =
Typing_defs_flags.(set_bit ft_flags_variadic false ft.ft_flags);
} ) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_exts.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.
*
*)
(** Ad-hoc rules for typing some common idioms
For printf-style functions: If the last argument (before varargs) of a
function has the type FormatString<X>, we assume that the format
string is interpreted by the formatter X, which should look like this:
interface PrintfFormatter {
function format_0x25() : string;
function format_x(int) : string;
function format_f(float) : string;
function format_upcase_l() : PrintfFormatter;
}
Each method can return a string or another formatter (for
multi-character sequences like %Ld); the parameters are copied into
the function signature when instantiating it at the call site. *)
val retype_magic_func :
Typing_env_types.env ->
Typing_defs.locl_fun_type ->
(Ast_defs.param_kind * Nast.expr) list ->
Typing_env_types.env * Typing_defs.locl_fun_type |
OCaml | hhvm/hphp/hack/src/typing/typing_fake_members.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module Reason = Typing_reason
module S = struct
type t = Local_id.t * Reason.blame
let compare (lid1, _) (lid2, _) = Local_id.compare lid1 lid2
end
(* A set that treats blame as metadata *)
module BlameSet = struct
include Caml.Set.Make (S)
let find_opt lid blame_set =
filter (fun (lid', _) -> Local_id.equal lid lid') blame_set |> choose_opt
let member lid blame_set =
exists (fun (lid', _) -> Local_id.equal lid lid') blame_set
let add lid blame blame_set = add (lid, blame) blame_set
let remove lid blame_set =
filter (fun (lid', _) -> not @@ Local_id.equal lid lid') blame_set
let attach_blame blame blame_set =
map (fun (lid, _) -> (lid, blame)) blame_set
end
(* A ledger consisting [valid] and [invalid] fake member sets.
*
* Those in [invalid] have been invalidated by a call, lambda, assignment, or
* by going out of scope described by the blame attached to the element, but
* [valid] are fake members that can still be used in typing. For example
*
* // { valid = []; invalid = [] }
* if ($x::f is nonnull) { // P0
* // { valid = [("$x::f", Blame_out_of_scope P0)]; invalid = [] }
* foo(); // P1
* // { valid = []; invalid = [("$x::f", Blame_call P1)] }
* if ($y::g is nonnull) { // P2
* // { valid = [("$y::g", Blame_out_of_scope P2)]; invalid = [("$x::f", Blame_call P1)] }
* $f = () ==> ... // P3
* // { valid = []; invalid = [("$x::f", Blame_lambda P3); ("$y::g", Blame_lambda P2)] }
* $y::g = 42; // P4
* // { valid = [("$y::g", Blame_out_of_scope P4)]; invalid = [("$x::f", Blame_call P1)] }
* . } // { valid = []; invalid = [("$y::g", Blame_out_of_scope P4); ("$x::f", Blame_lambda P3)] }
*)
type t = {
valid: BlameSet.t;
(* Non-empty and disjoint from valid. *)
invalid: BlameSet.t;
}
(* An empty validation ledger *)
let empty = { valid = BlameSet.empty; invalid = BlameSet.empty }
(* Combine validation ledger information at a join point *)
let join ledger1 ledger2 =
let old_valid = BlameSet.union ledger1.valid ledger2.valid in
let old_invalid = BlameSet.union ledger1.invalid ledger2.invalid in
let valid = BlameSet.inter ledger1.valid ledger2.valid in
let invalid = BlameSet.union old_invalid (BlameSet.diff old_valid valid) in
{ valid; invalid }
(* Does ledger1 entail ledger2? *)
let sub ledger1 ledger2 =
BlameSet.subset ledger2.valid ledger1.valid
&& BlameSet.subset ledger1.invalid ledger2.invalid
let is_valid ledger lid = BlameSet.member lid ledger.valid
let is_invalid ledger lid =
Option.map (BlameSet.find_opt lid ledger.invalid) ~f:snd
let conditionally_forget predicate (ledger : t) blame : t =
let (to_invalidate, valid) = BlameSet.partition predicate ledger.valid in
(* Don't allocate if there is nothing to forget *)
if BlameSet.is_empty to_invalidate then
ledger
else
let to_invalidate = BlameSet.attach_blame blame to_invalidate in
{ valid; invalid = BlameSet.union to_invalidate ledger.invalid }
let forget = conditionally_forget (const true)
let forget_prefixed (ledger : t) prefix_lid blame : t =
let is_prefixed (fake_id, _blame) =
String.is_prefix
~prefix:(Local_id.to_string prefix_lid ^ "->")
(Local_id.to_string fake_id)
in
conditionally_forget is_prefixed ledger blame
let forget_suffixed (ledger : t) suffix blame : t =
let is_prefixed (fake_id, _blame) =
String.is_suffix ~suffix:("->" ^ suffix) (Local_id.to_string fake_id)
in
conditionally_forget is_prefixed ledger blame
let add ledger lid pos =
let reason = Reason.(Blame (pos, BSout_of_scope)) in
{
valid = BlameSet.add lid reason ledger.valid;
invalid = BlameSet.remove lid ledger.invalid;
}
let blame_as_log_value (Reason.Blame (p, blame_source)) =
match blame_source with
| Reason.BScall ->
Typing_log_value.(make_map [("Blame_call", pos_as_value p)])
| Reason.BSlambda ->
Typing_log_value.(make_map [("Blame_lambda", pos_as_value p)])
| Reason.BSassignment ->
Typing_log_value.(make_map [("Blame_assigment", pos_as_value p)])
| Reason.BSout_of_scope ->
Typing_log_value.(make_map [("Blame_out_of_scope", pos_as_value p)])
let as_log_value ledger =
let log_blame_set_as_value set =
Typing_log_value.make_map
(List.map (BlameSet.elements set) ~f:(fun (lid, blame_opt) ->
( Typing_log_value.local_id_as_string lid,
blame_as_log_value blame_opt )))
in
Typing_log_value.(
make_map
[
( "Fake member ledger",
make_map
[
("valid", log_blame_set_as_value ledger.valid);
("invalid", log_blame_set_as_value ledger.invalid);
] );
])
let make_id obj_name member_name =
let obj_name =
match obj_name with
| (_, _, Aast.This) -> Typing_defs.this
| (_, _, Aast.Lvar (_, x)) -> x
| _ -> assert false
in
Local_id.make_unscoped (Local_id.to_string obj_name ^ "->" ^ member_name)
let make_static_id cid member_name =
let class_name = Nast.class_id_to_str cid in
Local_id.make_unscoped (class_name ^ "::" ^ member_name) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_fake_members.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module Reason = Typing_reason
(* Validation information for fake members *)
type t
(* Initial validation *)
val empty : t
(* Does one validation information entail another? *)
val sub : t -> t -> bool
(* Merge validation information at a join point.
* If join x y = z
* then sub x z = true and sub y z = true
*)
val join : t -> t -> t
(* Is this identifier a fake member that is valid? *)
val is_valid : t -> Local_id.t -> bool
(* Has this identifier been invalidated? If so, return position of
* the event that is responsible *)
val is_invalid : t -> Local_id.t -> Reason.blame option
(* Invalidate all fake members, and remember the position of the event
* that is responsible *)
val forget : t -> Reason.blame -> t
(* Invalidate fake members that are prefixed by some identifier, and remember
* the position of the assignment that is responsible *)
val forget_prefixed : t -> Local_id.t -> Reason.blame -> t
(* Invalidate fake members that are suffixed by some identifier, and remember
* the position of the assignment that is responsible *)
val forget_suffixed : t -> string -> Reason.blame -> t
(* Add a valid fake member access *)
val add : t -> Local_id.t -> Pos.t -> t
(* Convert to a value for logging *)
val as_log_value : t -> Typing_log_value.value
(* Make identifiers *)
val make_static_id : Nast.class_id_ -> string -> Local_id.t
val make_id : Nast.expr -> string -> Local_id.t |
OCaml | hhvm/hphp/hack/src/typing/typing_func_terminality.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
open Typing_defs
module Env = Typing_env
module Cls = Decl_provider.Class
(* Not adding a Typing_dep here because it will be added when the
* Nast is fully processed (by the caller of this code) *)
let get_fun ctx name =
match Decl_provider.get_fun ctx name with
| Some { fe_type; _ } -> begin
match get_node fe_type with
| Tfun ft -> Some ft
| _ -> None
end
| _ -> None
let get_static_meth
(ctx : Provider_context.t) (cls_name : string) (meth_name : string) =
match Decl_provider.get_class ctx cls_name with
| None -> None
| Some cls -> begin
match Cls.get_smethod cls meth_name with
| None -> None
| Some { Typing_defs.ce_type = (lazy ty); _ } -> begin
match get_node ty with
| Tfun fty -> Some fty
| _ -> None
end
end
let funopt_is_noreturn = function
| Some { ft_ret = { et_type; _ }; _ } -> is_prim Tnoreturn et_type
| _ -> false
let static_meth_is_noreturn env ci meth_id =
let class_name =
match ci with
| CI cls_id -> Some (snd cls_id)
| CIself
| CIstatic ->
Env.get_self_id env
| CIparent -> Env.get_parent_id env
| CIexpr _ -> None
(* we declared the types, but didn't check the bodies yet
so can't tell anything here *)
in
match class_name with
| Some class_name ->
funopt_is_noreturn
(get_static_meth (Env.get_ctx env) class_name (snd meth_id))
| None -> false
let typed_expression_exits (ty, _, _e) = is_type_no_return (get_node ty)
let expression_exits env (_, _, e) =
match e with
| Call { func = (_, _, Id (_, fun_name)); _ } ->
funopt_is_noreturn @@ get_fun (Env.get_ctx env) fun_name
| Call { func = (_, _, Class_const ((_, _, ci), meth_id)); _ } ->
static_meth_is_noreturn env ci meth_id
| _ -> false
let is_noreturn env =
let (_env, ret_ty) =
Env.expand_type
env
(Env.get_return env).Typing_env_return_info.return_type.et_type
in
is_prim Tnoreturn ret_ty |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_func_terminality.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val is_noreturn : Typing_env_types.env -> bool
val typed_expression_exits : Tast.expr -> bool
val expression_exits : Typing_env_types.env -> ('a, 'b) Aast.expr -> bool |
OCaml | hhvm/hphp/hack/src/typing/typing_generic_constraint.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module TUtils = Typing_utils
module Env = Typing_env
open Typing_defs
open Typing_env_types
let check_constraint
env ck ty ~cstr_ty (on_error : Typing_error.Reasons_callback.t option) =
Typing_log.(
log_with_level env "sub" ~level:1 (fun () ->
log_types
(get_pos ty)
env
[
Log_head
( "Typing_generic_constraint.check_constraint",
[Log_type ("ty", ty); Log_type ("cstr_ty", cstr_ty)] );
]));
if not (Env.is_consistent env) then
(env, None)
else
let (env, ety) = Env.expand_type env ty in
let (env, ecstr_ty) = Env.expand_type env cstr_ty in
match ck with
| Ast_defs.Constraint_as -> TUtils.sub_type env ety cstr_ty on_error
| Ast_defs.Constraint_eq ->
(* An equality constraint is the same as two commuting `as`
* constraints, i.e. X=Y is { X as Y, Y as X }. Thus, add
* add both expansions to the environment. We don't expand
* both sides of the equation simultaniously, to preserve an
* easier convergence indication. *)
let (env, e1) = TUtils.sub_type env ecstr_ty ty on_error in
let (env, e2) = TUtils.sub_type env ety cstr_ty on_error in
(env, Option.merge e1 e2 ~f:Typing_error.both)
| Ast_defs.Constraint_super -> TUtils.sub_type env ecstr_ty ty on_error
let check_tparams_constraint (env : env) ~use_pos ck ~cstr_ty ty =
check_constraint env ck ty ~cstr_ty
@@ Some (Typing_error.Reasons_callback.explain_constraint use_pos)
let check_where_constraint
~in_class (env : env) ~use_pos ~definition_pos ck ~cstr_ty ty =
check_constraint env ck ty ~cstr_ty
@@ Some
(Typing_error.Reasons_callback.explain_where_constraint
use_pos
~in_class
~decl_pos:definition_pos) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_generic_constraint.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.
*
*)
(** Add a constraint to the environment.
Raise an error if any inconsistency is detected. *)
val check_constraint :
Typing_env_types.env ->
Ast_defs.constraint_kind ->
Typing_defs.locl_ty ->
cstr_ty:Typing_defs.locl_ty ->
Typing_error.Reasons_callback.t option ->
Typing_env_types.env * Typing_error.t option
(** Add an [as] or [super] constraint to the environment.
Raise an error if any inconsistency is detected. *)
val check_tparams_constraint :
Typing_env_types.env ->
use_pos:Pos.t ->
Ast_defs.constraint_kind ->
cstr_ty:Typing_defs.locl_ty ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_error.t option
(** Add a [where] constraint to the environment.
Raise an error if any inconsistency is detected. *)
val check_where_constraint :
in_class:bool ->
Typing_env_types.env ->
use_pos:Pos.t ->
definition_pos:Pos_or_decl.t ->
Ast_defs.constraint_kind ->
cstr_ty:Typing_defs.locl_ty ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_error.t option |
OCaml | hhvm/hphp/hack/src/typing/typing_generic_rules.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Common
open Typing_defs
module Env = Typing_env
module TySet = Typing_set
module SN = Naming_special_names
(* Return upper bounds of a generic parameter, transitively following bounds
* that are themselves parameters. Detect cycles. *)
let get_transitive_upper_bounds env ty =
let rec iter seen env acc tyl =
match tyl with
| [] -> (env, acc)
| ty :: tyl ->
let (env, ety) = Env.expand_type env ty in
(match get_node ety with
| Tgeneric (n, tyargs) ->
if SSet.mem n seen then
iter seen env acc tyl
else
iter
(SSet.add n seen)
env
acc
(TySet.elements (Env.get_upper_bounds env n tyargs) @ tyl)
| _ -> iter seen env (TySet.add ty acc) tyl)
in
let (env, resl) = iter SSet.empty env TySet.empty [ty] in
(env, TySet.elements resl)
(* Apply generic typing rules. Here, assume E[e:t] is some expression with a
* subexpression e of type t. For example, E[x:C] is `x->method(e1,..,en)` (method
* invocation on object of class C) or E[x:vec<int>] is `x[e1] = e2` (array
* assignment on a vec<int>).
* 1. Lift unions: if e:t1|t2 and E[e:t1] : u1 and E[e:t2] : u2
* then E[e:t1|t2] : u1|u2. (Note: both sides of union must succeed.)
* 2. Lift intersections: if e:t1&t2 and E[e:t1] : u1 and E[e:t2] : u2
* then E[e:t1&t2] : u1&u2. If E[e:t1] : u1 but E[e:t2] does not type,
* then E[e:t1&t2] : u1 (and similar for the other way round).
* 3. Apply subsumption wrt upper bounds on generics and abstract types:
* If e:T and generic parameter T has upper bound t and E[e:t] : u,
* then E[e:T] : u.
* For the implementation below, ty is the type of the subexpression e,
* and f is the checker for the context E[e:ty].
* We iterate the rule through intersections, unions, and bounds.
*)
let is_shape t =
match get_node t with
| Tshape _ -> true
| _ -> false
let is_arraykey t =
match get_node t with
| Tprim Aast.Tarraykey -> true
| _ -> false
let fold_errs errs =
List.fold_left (List.rev errs) ~init:(Ok []) ~f:(fun acc res ->
match (acc, res) with
| (Ok xs, Ok x) -> Ok (x :: xs)
| (Ok xs, Error (ty_actual, ty_expect)) ->
Error (ty_actual :: xs, ty_expect :: xs)
| (Error (xs, ys), Ok x) -> Error (x :: xs, x :: ys)
| (Error (xs, ys), Error (ty_actual, ty_expect)) ->
Error (ty_actual :: xs, ty_expect :: ys))
let intersect_errs env errs =
Result.fold
~ok:(fun tys ->
let (env, ty) = Typing_intersection.intersect_list env Reason.none tys in
(env, Ok ty))
~error:(fun (actuals, expects) ->
let (env, ty_actual) =
Typing_intersection.intersect_list env Reason.none actuals
in
let (env, ty_expect) =
Typing_intersection.intersect_list env Reason.none expects
in
(env, Error (ty_actual, ty_expect)))
@@ fold_errs errs
let union_errs env errs =
Result.fold
~ok:(fun tys ->
let (env, ty) = Typing_union.union_list env Reason.none tys in
(env, Ok ty))
~error:(fun (actuals, expects) ->
let (env, ty_actual) = Typing_union.union_list env Reason.none actuals in
let (env, ty_expect) = Typing_union.union_list env Reason.none expects in
(env, Error (ty_actual, ty_expect)))
@@ fold_errs errs
(* Here we have a function returns the updated environment, a local type
and results indicating type errors for both and index expression and
the rhs expression of an assignment *)
let apply_rules_with_array_index_value_ty_mismatches
?(ignore_type_structure = false) ?(preserve_supportdyn = true) env ty f =
let rec iter ~supportdyn ~is_nonnull env ty =
let (env, ety) = Env.expand_type env ty in
(* This is the base case: not a union or intersection or bounded abstract type *)
let default () = f env ~supportdyn ty in
match deref ety with
(* For intersections, collect up all successful applications and compute
* the intersection of the types and intersection of errors
*)
| (r, Tintersection tyl) ->
let (is_nonnull, ty_err_opt) =
Typing_solver.is_sub_type env ty (Typing_make_type.nonnull Reason.none)
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
let (env, res) =
Typing_utils.run_on_intersection
env
~f:(iter ~supportdyn ~is_nonnull)
tyl
in
let (tys, arr_errs, key_errs, val_errs) = List.unzip4 res in
let (env, arr_ty_mismatch) = intersect_errs env arr_errs in
let (env, key_ty_mismatch) = intersect_errs env key_errs in
let (env, val_ty_mismatch) = intersect_errs env val_errs in
let (env, ty) = Typing_intersection.intersect_list env r tys in
(env, (ty, arr_ty_mismatch, key_ty_mismatch, val_ty_mismatch))
| (_, Tnewtype (cid, _, _))
when String.equal cid SN.Classes.cSupportDyn
&& Tast.is_under_dynamic_assumptions env.Typing_env_types.checked ->
(* If we are under_dynamic_assumptions, we might want to take advantage of
the dynamic in supportdyn<t>, so don't break it apart as in the next case. *)
default ()
(* Preserve supportdyn<_> across operation *)
| (r, Tnewtype (cid, _, bound)) when String.equal cid SN.Classes.cSupportDyn
->
let (env, (ty, arr_errs, key_errs, val_errs)) =
iter ~supportdyn:true ~is_nonnull env bound
in
let (env, ty) =
if preserve_supportdyn then
Typing_utils.make_supportdyn r env ty
else
(env, ty)
in
(env, (ty, arr_errs, key_errs, val_errs))
(* For unions, just apply rule of components and compute union of result *)
| (r, Tunion tyl) ->
let (env, tys, arr_errs, key_errs, val_errs) =
List.fold_left
tyl
~init:(env, [], [], [], [])
~f:(fun (env, tys, arr_errs, key_errs, val_errs) ty ->
let (env, (ty, arr_err, key_err, val_err)) =
iter ~supportdyn ~is_nonnull env ty
in
( env,
ty :: tys,
arr_err :: arr_errs,
key_err :: key_errs,
val_err :: val_errs ))
in
let (env, arr_ty_mismatch) = union_errs env arr_errs in
let (env, key_ty_mismatch) = union_errs env key_errs in
let (env, val_ty_mismatch) = union_errs env val_errs in
let (env, ty) = Typing_union.union_list env r tys in
(env, (ty, arr_ty_mismatch, key_ty_mismatch, val_ty_mismatch))
(* Special case for `TypeStructure<_> as shape { ... }`, because some clients care about the
* fact that we have the special type TypeStructure *)
| (_, Tnewtype (cid, _, bound))
when String.equal cid SN.FB.cTypeStructure
&& is_shape bound
&& ignore_type_structure ->
default ()
(* Enums with arraykey upper bound are treated as "abstract" *)
| (_, Tnewtype (cid, _, bound))
when Env.is_enum env cid && is_arraykey bound ->
default ()
(* If there is an explicit upper bound, delegate to it *)
| (_, (Tnewtype (_, _, ty) | Tdependent (_, ty))) ->
iter ~supportdyn ~is_nonnull env ty
(* For type parameters with upper bounds, delegate to intersection of the upper bounds *)
| (r, Tgeneric _) ->
let (env, tyl) = get_transitive_upper_bounds env ty in
if List.is_empty tyl then
default ()
else
let (env, ty) = Typing_intersection.intersect_list env r tyl in
let (env, ty) =
if is_nonnull then
Typing_solver.non_null env (get_pos ty) ty
else
(env, ty)
in
iter ~supportdyn ~is_nonnull env ty
| _ -> default ()
in
let (env, (ty, arr_ty_mismatch, key_ty_mismatch, val_ty_mismatch)) =
iter ~supportdyn:false ~is_nonnull:false env ty
in
let opt_of_res =
Result.fold ~ok:(fun _ -> None) ~error:(fun tys -> Some tys)
in
let arr_err_opt = opt_of_res arr_ty_mismatch
and key_err_opt = opt_of_res key_ty_mismatch
and val_err_opt = opt_of_res val_ty_mismatch in
(env, (ty, arr_err_opt, key_err_opt, val_err_opt))
let apply_rules_with_index_value_ty_mismatches
?ignore_type_structure ~preserve_supportdyn env ty f =
let g env ~supportdyn ty =
let (env, (ty, idx_ty_mismatch, val_ty_mismatch)) = f env ~supportdyn ty in
(env, (ty, Ok ty, idx_ty_mismatch, val_ty_mismatch))
in
let (env, (ty, _, idx_ty_mismatch, val_ty_mismatch)) =
apply_rules_with_array_index_value_ty_mismatches
~preserve_supportdyn
?ignore_type_structure
env
ty
g
in
(env, (ty, idx_ty_mismatch, val_ty_mismatch)) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_generic_rules.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 apply_rules_with_index_value_ty_mismatches :
?ignore_type_structure:bool ->
preserve_supportdyn:bool ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
(Typing_env_types.env ->
supportdyn:bool ->
Typing_defs.locl_ty ->
Typing_env_types.env
* (Typing_defs.locl_ty
* (Typing_defs.locl_ty, Typing_defs.locl_ty * Typing_defs.locl_ty) result
* (Typing_defs.locl_ty, Typing_defs.locl_ty * Typing_defs.locl_ty) result)) ->
Typing_env_types.env
* (Typing_defs.locl_ty
* (Typing_defs.locl_ty * Typing_defs.locl_ty) option
* (Typing_defs.locl_ty * Typing_defs.locl_ty) option)
val apply_rules_with_array_index_value_ty_mismatches :
?ignore_type_structure:bool ->
?preserve_supportdyn:bool ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
(Typing_env_types.env ->
supportdyn:bool ->
Typing_defs.locl_ty ->
Typing_env_types.env
* (Typing_defs.locl_ty
* (Typing_defs.locl_ty, Typing_defs.locl_ty * Typing_defs.locl_ty) result
* (Typing_defs.locl_ty, Typing_defs.locl_ty * Typing_defs.locl_ty) result
* (Typing_defs.locl_ty, Typing_defs.locl_ty * Typing_defs.locl_ty) result)) ->
Typing_env_types.env
* (Typing_defs.locl_ty
* (Typing_defs.locl_ty * Typing_defs.locl_ty) option
* (Typing_defs.locl_ty * Typing_defs.locl_ty) option
* (Typing_defs.locl_ty * Typing_defs.locl_ty) option) |
OCaml | hhvm/hphp/hack/src/typing/typing_helpers.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* This module implements the typing.
*
* Given an Nast.program, it infers the type of all the local
* variables, and checks that all the types are correct (aka
* consistent) *)
open Hh_prelude
open Common
open Typing_defs
open Typing_env_types
open Aast
module Env = Typing_env
module SN = Naming_special_names
module MakeType = Typing_make_type
module ExpectedTy : sig
[@@@warning "-32"]
type t = private {
pos: Pos.t;
reason: Typing_reason.ureason;
ty: locl_possibly_enforced_ty;
coerce: Typing_logic.coercion_direction option;
}
[@@deriving show]
[@@@warning "+32"]
val make :
?coerce:Typing_logic.coercion_direction option ->
Pos.t ->
Typing_reason.ureason ->
locl_ty ->
t
(* We will allow coercion to this expected type, if et_enforced=Enforced *)
val make_and_allow_coercion :
Pos.t -> Typing_reason.ureason -> locl_possibly_enforced_ty -> t
(* If type is an unsolved type variable, don't create an expected type *)
val make_and_allow_coercion_opt :
Typing_env_types.env ->
Pos.t ->
Typing_reason.ureason ->
locl_possibly_enforced_ty ->
t option
end = struct
(* Some mutually recursive inference functions in typing.ml pass around an ~expected argument that
* enables bidirectional type checking. This module abstracts away that type so that it can be
* extended and modified without having to touch every consumer. *)
type t = {
pos: Pos.t;
reason: Typing_reason.ureason;
ty: locl_possibly_enforced_ty;
coerce: Typing_logic.coercion_direction option;
}
[@@deriving show]
let make_and_allow_coercion_opt env pos reason ty =
let (_env, ety) = Env.expand_type env ty.et_type in
match get_node ety with
| Tvar v when Internal_type_set.is_empty (Env.get_tyvar_upper_bounds env v)
->
None
| _ -> Some { pos; reason; ty; coerce = None }
let make_and_allow_coercion pos reason ty = { pos; reason; ty; coerce = None }
let make ?coerce pos reason locl_ty =
let res =
make_and_allow_coercion pos reason (MakeType.unenforced locl_ty)
in
match coerce with
| None -> res
| Some coerce -> { res with coerce }
end
let decl_error_to_typing_error decl_error =
let primary =
match decl_error with
| Decl_defs.Wrong_extend_kind
{ pos; kind; name; parent_pos; parent_kind; parent_name } ->
Typing_error.Primary.Wrong_extend_kind
{ pos; kind; name; parent_pos; parent_kind; parent_name }
| Decl_defs.Cyclic_class_def { pos; stack } ->
Typing_error.Primary.Cyclic_class_def { pos; stack }
in
Typing_error.primary primary
let add_decl_error decl_error ~env =
Typing_error_utils.add_typing_error
~env
(decl_error_to_typing_error decl_error)
let add_decl_errors ~env = List.iter ~f:(add_decl_error ~env)
(*****************************************************************************)
(* Handling function/method arguments *)
(*****************************************************************************)
let param_has_attribute param attr =
List.exists param.param_user_attributes ~f:(fun { ua_name; _ } ->
String.equal attr (snd ua_name))
let has_accept_disposable_attribute param =
param_has_attribute param SN.UserAttributes.uaAcceptDisposable
let with_timeout env fun_name (do_ : env -> 'b) : 'b option =
let timeout = TypecheckerOptions.(timeout @@ Env.get_tcopt env) in
if Int.equal timeout 0 then
Some (do_ env)
else
let big_envs = ref [] in
let env = { env with big_envs } in
Timeout.with_timeout
~timeout
~on_timeout:(fun _ ->
(*List.iter !big_envs (fun (p, env) ->
Typing_log.log_key "WARN: environment is too big.";
Typing_log.hh_show_env p env); *)
let (pos, fn_name) = fun_name in
Errors.typechecker_timeout pos fn_name timeout;
None)
~do_:(fun _ -> Some (do_ env))
(* If the localized types of the return type is a tyvar we force it to be covariant.
The same goes for parameter types, but this time we force them to be contravariant
*)
let set_tyvars_variance_in_callable env return_ty param_tys =
Env.log_env_change "set_tyvars_variance_in_callable" env
@@
let set_variance = Env.set_tyvar_variance ~for_all_vars:true in
let env = set_variance env return_ty in
let env =
List.fold param_tys ~init:env ~f:(fun env opt_ty ->
match opt_ty with
| None -> env
| Some ty -> set_variance ~flip:true env ty)
in
env
let reify_kind = function
| Erased -> Aast.Erased
| SoftReified -> Aast.SoftReified
| Reified -> Aast.Reified
let hint_fun_decl ~params ~ret env =
let ret_decl_ty =
Decl_fun_utils.hint_to_type_opt env.decl_env (hint_of_type_hint ret)
in
let params_decl_ty =
List.map
~f:(fun h ->
Decl_fun_utils.hint_to_type_opt
env.decl_env
(hint_of_type_hint h.param_type_hint))
params
in
(ret_decl_ty, params_decl_ty) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_helpers.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module ExpectedTy : sig
type t = private {
pos: Pos.t;
reason: Typing_reason.ureason;
ty: Typing_defs.locl_possibly_enforced_ty;
coerce: Typing_logic.coercion_direction option;
}
val make :
?coerce:Typing_logic.coercion_direction option ->
Pos.t ->
Typing_reason.ureason ->
Typing_defs.locl_ty ->
t
val make_and_allow_coercion :
Pos.t -> Typing_reason.ureason -> Typing_defs.locl_possibly_enforced_ty -> t
val make_and_allow_coercion_opt :
Typing_env_types.env ->
Pos.t ->
Typing_reason.ureason ->
Typing_defs.locl_possibly_enforced_ty ->
t option
end
val set_tyvars_variance_in_callable :
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_defs.locl_ty option list ->
Typing_env_types.env
val has_accept_disposable_attribute : ('a, 'b) Aast.fun_param -> bool
val add_decl_errors :
env:Typing_env_types.env -> Decl_defs.decl_error list -> unit
val with_timeout :
Typing_env_types.env ->
Pos.t * string ->
(Typing_env_types.env -> 'b) ->
'b option
val reify_kind : Aast.reify_kind -> Aast.reify_kind
(** Convert a function signature hint (method or toplevel function) into a bunch
of decl_tys. *)
val hint_fun_decl :
params:Nast.fun_param list ->
ret:Nast.type_hint ->
Typing_env_types.env ->
Typing_defs.decl_ty option * Typing_defs.decl_ty option list |
OCaml | hhvm/hphp/hack/src/typing/typing_inference_env.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Typing_defs
module ITySet = Internal_type_set
module Occ = Typing_tyvar_occurrences
module TL = Typing_logic
exception InconsistentTypeVarState of string
[@@@warning "-32"]
let pp _ _ = Printf.printf "%s\n" "<inference_env>"
[@@@warning "+32"]
type tyvar_constraints = {
appears_covariantly: bool;
(** Does this type variable appear covariantly in the type of the expression? *)
appears_contravariantly: bool;
(** Does this type variable appear contravariantly in the type of the expression?
If it appears in an invariant position then both will be true; if it doesn't
appear at all then both will be false. *)
lower_bounds: ITySet.t;
upper_bounds: ITySet.t;
type_constants:
(pos_id (* id of the type constant "T", containing its position. *)
* locl_ty)
SMap.t;
(** Map associating a type to each type constant id of this variable.
Whenever we localize "T1::T" in a constraint, we add a fresh type variable
indexed by "T" in the type_constants of the type variable representing T1.
This allows to properly check constraints on "T1::T". *)
}
type solving_info =
| TVIType of locl_ty (** when the type variable is bound to a type *)
| TVIConstraints of tyvar_constraints
(** when the type variable is still unsolved *)
type tyvar_info = {
tyvar_pos: Pos.t;
(** Where was the type variable introduced? (e.g. generic method invocation,
new object construction) *)
eager_solve_failed: bool;
solving_info: solving_info;
}
type tvenv = tyvar_info IMap.t
type identifier = int [@@deriving eq]
module Identifier_provider : sig
val reinitialize : unit -> unit
val make_identifier : unit -> identifier
end = struct
let counter : int ref = ref 0
let reinitialize () =
counter := 0;
()
let make_identifier () =
let identifier = !counter in
counter := !counter + 1;
identifier
end
type t = {
tvenv: tvenv;
tyvars_stack: (Pos.t * identifier list) list;
subtype_prop: TL.subtype_prop;
tyvar_occurrences: Typing_tyvar_occurrences.t;
}
module Log = struct
open Typing_log_value
let tyvar_constraints_as_value tvcstr =
let {
appears_covariantly;
appears_contravariantly;
type_constants;
lower_bounds;
upper_bounds;
} =
tvcstr
in
make_map
[
("appears_covariantly", bool_as_value appears_covariantly);
("appears_contravariantly", bool_as_value appears_contravariantly);
("lower_bounds", internal_type_set_as_value lower_bounds);
("upper_bounds", internal_type_set_as_value upper_bounds);
( "type_constants",
smap_as_value (fun (_, ty) -> locl_type_as_value ty) type_constants );
]
let solving_info_as_value sinfo =
match sinfo with
| TVIType ty -> variant_as_value "TVIType" (locl_type_as_value ty)
| TVIConstraints tvcstr ->
variant_as_value "TVIConstraints" (tyvar_constraints_as_value tvcstr)
let tyvar_info_as_value tvinfo =
let { tyvar_pos; eager_solve_failed; solving_info } = tvinfo in
make_map
[
("tyvar_pos", pos_as_value tyvar_pos);
("eager_solve_failed", bool_as_value eager_solve_failed);
("solving_info", solving_info_as_value solving_info);
]
let tvenv_as_value tvenv =
Map
(IMap.fold
(fun i tvinfo m ->
SMap.add (var_as_string i) (tyvar_info_as_value tvinfo) m)
tvenv
SMap.empty)
let tyvars_stack_as_value tyvars_stack =
List
(List.map tyvars_stack ~f:(fun (_p, l) ->
List (List.map l ~f:(fun i -> Atom (var_as_string i)))))
let inference_env_as_value env =
let { tvenv; tyvars_stack; subtype_prop; tyvar_occurrences } = env in
make_map
[
("tvenv", tvenv_as_value tvenv);
("tyvars_stack", tyvars_stack_as_value tyvars_stack);
("subtype_prop", subtype_prop_as_value subtype_prop);
("tyvar_occurrences", Occ.Log.as_value tyvar_occurrences);
]
let solving_info_to_json
(p_locl_ty : locl_ty -> string)
(p_internal_type : internal_type -> string)
solving_info =
let open Hh_json in
let constraints_to_json
{
appears_covariantly;
appears_contravariantly;
lower_bounds;
upper_bounds;
type_constants = _;
} =
let bounds_to_json bs =
ITySet.elements bs
|> List.map ~f:(fun b -> JSON_String (p_internal_type b))
in
JSON_Object
[
("appears_covariantly", JSON_Bool appears_covariantly);
("appears_contravariantly", JSON_Bool appears_contravariantly);
("lower_bounds", JSON_Array (bounds_to_json lower_bounds));
("upper_bounds", JSON_Array (bounds_to_json upper_bounds));
]
in
let locl_ty_to_json x = JSON_String (p_locl_ty x) in
match solving_info with
| TVIType locl_ty -> JSON_Object [("type", locl_ty_to_json locl_ty)]
| TVIConstraints cstr ->
JSON_Object [("constraints", constraints_to_json cstr)]
let tyvar_to_json
(p_locl_ty : locl_ty -> string)
(p_internal_type : internal_type -> string)
(env : t)
(v : identifier) =
let open Hh_json in
match IMap.find_opt v env.tvenv with
| None -> JSON_Null
| Some { tyvar_pos; eager_solve_failed; solving_info } ->
JSON_Object
[
("tyvar_pos", string_ @@ Pos.string (Pos.to_absolute tyvar_pos));
("eager_solve_failed", JSON_Bool eager_solve_failed);
( "solving_info",
solving_info_to_json p_locl_ty p_internal_type solving_info );
]
end
let empty_tvenv = IMap.empty
let empty_inference_env =
{
tvenv = empty_tvenv;
tyvars_stack = [];
subtype_prop = TL.valid;
tyvar_occurrences = Occ.init;
}
let empty_tyvar_constraints =
{
lower_bounds = ITySet.empty;
upper_bounds = ITySet.empty;
appears_covariantly = false;
appears_contravariantly = false;
type_constants = SMap.empty;
}
let empty_tyvar_info pos =
{
tyvar_pos = pos;
eager_solve_failed = false;
solving_info = TVIConstraints empty_tyvar_constraints;
}
let get_tyvar_info_opt env v = IMap.find_opt v env.tvenv
let set_tyvar_info env v tvinfo =
{ env with tvenv = IMap.add v tvinfo env.tvenv }
let get_solving_info_opt env var =
match get_tyvar_info_opt env var with
| None -> None
| Some tvinfo -> Some tvinfo.solving_info
let set_solving_info env ?(tyvar_pos = Pos.none) x solving_info =
let tvinfo =
Option.value
(get_tyvar_info_opt env x)
~default:(empty_tyvar_info tyvar_pos)
in
let tvinfo = { tvinfo with solving_info } in
set_tyvar_info env x tvinfo
let tyvar_occurs_in_tyvar env = Occ.occurs_in env.tyvar_occurrences
let get_tyvar_occurrences env = Occ.get_tyvar_occurrences env.tyvar_occurrences
let get_tyvars_in_tyvar env = Occ.get_tyvars_in_tyvar env.tyvar_occurrences
let contains_unsolved_tyvars env =
Occ.contains_unsolved_tyvars env.tyvar_occurrences
let tyvar_is_solved env var =
match get_solving_info_opt env var with
| None -> false
| Some sinfo ->
(match sinfo with
| TVIConstraints _ -> false
| TVIType _ -> true)
(** Get type variables in a type that are either unsolved or
solved to a type that itself contains unsolved type variables. *)
let get_unsolved_vars_in_ty env ty =
let gatherer =
object
inherit [ISet.t] Type_visitor.locl_type_visitor
method! on_tvar vars _r v =
(* Add it if it has unsolved type vars or if it is itself unsolved. *)
if
(not (tyvar_is_solved env v))
|| Occ.contains_unsolved_tyvars env.tyvar_occurrences v
then
ISet.add v vars
else
vars
end
in
gatherer#on_type ISet.empty ty
let make_tyvars_occur_in_tyvar env vars ~occur_in:x =
{
env with
tyvar_occurrences =
Occ.make_tyvars_occur_in_tyvar env.tyvar_occurrences vars ~occur_in:x;
}
let make_tyvar_no_more_occur_in_tyvar env v ~no_more_in:v' =
{
env with
tyvar_occurrences =
Occ.make_tyvar_no_more_occur_in_tyvar
env.tyvar_occurrences
v
~no_more_in:v';
}
let get_direct_binding env v =
match get_solving_info_opt env v with
| None
| Some (TVIConstraints _) ->
None
| Some (TVIType ty) -> Some ty
let bind env ?(tyvar_pos = Pos.none) v ty =
set_solving_info env ~tyvar_pos v (TVIType ty)
let update_tyvar_occurrences env v ty =
let env =
{ env with tyvar_occurrences = Occ.unbind_tyvar env.tyvar_occurrences v }
in
let unsolved_vars_in_ty = get_unsolved_vars_in_ty env ty in
let env = make_tyvars_occur_in_tyvar env unsolved_vars_in_ty ~occur_in:v in
env
let add env ?(tyvar_pos = Pos.none) v ty =
let env = bind env ~tyvar_pos v ty in
let env = update_tyvar_occurrences env v ty in
env
let get_type env r v =
let rec get r v aliases =
let shorten_paths () =
ISet.fold (fun v' env -> add env v' (mk (r, Tvar v))) aliases env
in
match get_solving_info_opt env v with
| Some (TVIType ty) -> begin
match deref ty with
| (r, Tvar v') ->
if ISet.mem v aliases then
raise
@@ InconsistentTypeVarState
"Two type variables are aliasing each other!";
get r v' (ISet.add v aliases)
| _ ->
let env = shorten_paths () in
(env, ty)
end
| None
| Some (TVIConstraints _) ->
let env = shorten_paths () in
(env, mk (r, Tvar v))
in
get r v ISet.empty
let create_tyvar_constraints variance =
let (appears_covariantly, appears_contravariantly) =
match variance with
| Some Ast_defs.Invariant -> (true, true)
| Some Ast_defs.Covariant -> (true, false)
| Some Ast_defs.Contravariant -> (false, true)
| None -> (false, false)
in
let tyvar_constraints =
{
empty_tyvar_constraints with
appears_covariantly;
appears_contravariantly;
}
in
TVIConstraints tyvar_constraints
let fresh_unsolved_tyvar env v ?variance tyvar_pos =
let solving_info = create_tyvar_constraints variance in
let tvinfo = { tyvar_pos; solving_info; eager_solve_failed = false } in
set_tyvar_info env v tvinfo
let add_current_tyvar ?variance env p v =
let env = fresh_unsolved_tyvar env v ?variance p in
match env.tyvars_stack with
| (expr_pos, tyvars) :: rest ->
{ env with tyvars_stack = (expr_pos, v :: tyvars) :: rest }
| _ -> env
let fresh_type_reason ?variance env p r =
let v = Identifier_provider.make_identifier () in
let env = add_current_tyvar ?variance env p v in
(env, mk (r, Tvar v))
let fresh_type ?variance env p =
fresh_type_reason env p (Reason.Rtype_variable p) ?variance
let fresh_type_invariant = fresh_type ~variance:Ast_defs.Invariant
let wrap_ty_in_var env r ty =
let v = Identifier_provider.make_identifier () in
let tvinfo =
{
tyvar_pos = Reason.to_pos r |> Pos_or_decl.unsafe_to_raw_pos;
eager_solve_failed = false;
solving_info = TVIType ty;
}
in
let env = set_tyvar_info env v tvinfo in
let env = update_tyvar_occurrences env v ty in
(env, mk (r, Tvar v))
let open_tyvars env p = { env with tyvars_stack = (p, []) :: env.tyvars_stack }
let close_tyvars env =
match env.tyvars_stack with
| [] -> raise @@ InconsistentTypeVarState "close_tyvars: empty stack"
| _ :: rest -> { env with tyvars_stack = rest }
let get_current_tyvars env =
match env.tyvars_stack with
| [] -> []
| (_, tyvars) :: _ -> tyvars
let get_tyvar_constraints_opt env var =
match get_solving_info_opt env var with
| Some (TVIConstraints constraints) -> Some constraints
| None
| Some (TVIType _) ->
None
let get_tyvar_constraints_exn env var =
match get_solving_info_opt env var with
| None ->
raise
@@ InconsistentTypeVarState
(Printf.sprintf
"Attempting to get constraints for non-existing type variable #%d."
var)
| Some (TVIType _) ->
raise
@@ InconsistentTypeVarState
(Printf.sprintf
"Attempting to get constraints for already solved type variable #%d."
var)
| Some (TVIConstraints constraints) -> constraints
let set_tyvar_constraints env v tyvar_constraints =
set_solving_info env v (TVIConstraints tyvar_constraints)
let get_tyvar_eager_solve_fail env v =
match get_tyvar_info_opt env v with
| None -> false
| Some tvinfo -> tvinfo.eager_solve_failed
let expand_var env r v =
let (env, ty) = get_type env r v in
if get_tyvar_eager_solve_fail env v then
(env, mk (Reason.Rsolve_fail (Reason.to_pos r), get_node ty))
else
(env, ty)
let expand_type env x =
match deref x with
| (r, Tvar x) -> expand_var env r x
| _ -> (env, x)
let full_expander =
object (this)
inherit [t] Type_mapper_generic.internal_type_mapper
method! on_tvar env r v =
let (env, ty) = expand_var env r v in
match get_node ty with
| Tvar _ -> (env, ty)
| _ -> this#on_type env ty
end
let fully_expand_type env ty = full_expander#on_type env ty
let expand_internal_type env ty =
match ty with
| ConstraintType _ -> (env, ty)
| LoclType ty ->
let (env, ty) = expand_type env ty in
(env, LoclType ty)
let get_tyvar_pos env var =
match get_tyvar_info_opt env var with
| None -> Pos.none
| Some tvinfo -> tvinfo.tyvar_pos
let get_tyvar_lower_bounds_opt env v =
Option.map (get_tyvar_constraints_opt env v) ~f:(fun x -> x.lower_bounds)
let get_tyvar_upper_bounds_opt env v =
Option.map (get_tyvar_constraints_opt env v) ~f:(fun x -> x.upper_bounds)
let get_tyvar_lower_bounds env var : ITySet.t =
match get_solving_info_opt env var with
| None -> ITySet.empty
| Some solving_info ->
(match solving_info with
| TVIType ty -> ITySet.singleton (LoclType ty)
| TVIConstraints cstr -> cstr.lower_bounds)
let get_tyvar_upper_bounds env var : ITySet.t =
match get_solving_info_opt env var with
| None -> ITySet.empty
| Some solving_info ->
(match solving_info with
| TVIType ty -> ITySet.singleton (LoclType ty)
| TVIConstraints cstr -> cstr.upper_bounds)
let set_tyvar_lower_bounds env var lower_bounds =
let tyvar_constraints = get_tyvar_constraints_exn env var in
let tyvar_constraints = { tyvar_constraints with lower_bounds } in
let env = set_tyvar_constraints env var tyvar_constraints in
env
let set_tyvar_upper_bounds env var upper_bounds =
let tyvar_constraints = get_tyvar_constraints_exn env var in
let tyvar_constraints = { tyvar_constraints with upper_bounds } in
let env = set_tyvar_constraints env var tyvar_constraints in
env
let set_tyvar_eager_solve_fail env v =
match get_tyvar_info_opt env v with
| None -> env
| Some tvinfo ->
let tvinfo = { tvinfo with eager_solve_failed = true } in
set_tyvar_info env v tvinfo
let get_tyvar_appears_covariantly env var =
match get_tyvar_constraints_opt env var with
| Some cstr -> cstr.appears_covariantly
| None -> false
let get_tyvar_appears_contravariantly env var =
match get_tyvar_constraints_opt env var with
| Some cstr -> cstr.appears_contravariantly
| None -> false
let get_tyvar_appears_invariantly env var =
get_tyvar_appears_covariantly env var
&& get_tyvar_appears_contravariantly env var
let set_tyvar_appears_covariantly env v =
let tyvar_constraints = get_tyvar_constraints_exn env v in
let tyvar_constraints =
{ tyvar_constraints with appears_covariantly = true }
in
let env = set_tyvar_constraints env v tyvar_constraints in
env
let set_tyvar_appears_contravariantly env v =
let tyvar_constraints = get_tyvar_constraints_exn env v in
let tyvar_constraints =
{ tyvar_constraints with appears_contravariantly = true }
in
let env = set_tyvar_constraints env v tyvar_constraints in
env
let get_tyvar_type_consts env var =
match get_tyvar_constraints_opt env var with
| Some cstr -> cstr.type_constants
| None -> SMap.empty
let get_tyvar_type_const env var (_, tyconstid) =
SMap.find_opt tyconstid (get_tyvar_type_consts env var)
let set_tyvar_type_const env var ((_, tyconstid_) as tyconstid) ty =
let tvinfo = get_tyvar_constraints_exn env var in
let type_constants =
SMap.add tyconstid_ (tyconstid, ty) tvinfo.type_constants
in
let env = set_tyvar_constraints env var { tvinfo with type_constants } in
(* We don't want to solve such type variables too early, because of valid
* code patterns like that one:
*
* abstract class A { abstract type const T; }
*
* function f<TA as A, T>(TA $_, T $_) : ... where T = TA::T
*
* We force it covariantly until we can implement a proper fix to
* avoid eager solving (to the upperbound) as it would bind TA to
* an abstract class
*)
let env = set_tyvar_appears_covariantly env var in
env
(** Conjoin a subtype proposition onto the subtype_prop in the environment *)
let add_subtype_prop env prop =
{ env with subtype_prop = TL.conj env.subtype_prop prop }
let get_current_pos_from_tyvar_stack env =
match env.tyvars_stack with
| (p, _) :: _ -> Some p
| _ -> None
(* Add a single new upper bound [ty] to type variable [var] in [env.tvenv].
* If the optional [intersect] operation is supplied, then use this to avoid
* adding redundant bounds by merging the type with existing bounds. This makes
* sense because a conjunction of upper bounds
* (v <: t1) /\ ... /\ (v <: tn)
* is equivalent to a single upper bound
* v <: (t1 & ... & tn)
*)
let add_tyvar_upper_bound ?intersect env var (ty : internal_type) =
let tvconstraints = get_tyvar_constraints_exn env var in
let upper_bounds =
match intersect with
| None -> ITySet.add ty tvconstraints.upper_bounds
| Some intersect ->
ITySet.of_list (intersect ty (ITySet.elements tvconstraints.upper_bounds))
in
let env = set_tyvar_constraints env var { tvconstraints with upper_bounds } in
env
(* Add a single new lower bound [ty] to type variable [var] in [env.tvenv].
* If the optional [union] operation is supplied, then use this to avoid
* adding redundant bounds by merging the type with existing bounds. This makes
* sense because a conjunction of lower bounds
* (t1 <: v) /\ ... /\ (tn <: v)
* is equivalent to a single lower bound
* (t1 | ... | tn) <: v
*)
let add_tyvar_lower_bound ?union env var ty =
let tvconstraints = get_tyvar_constraints_exn env var in
let lower_bounds =
match union with
| None -> ITySet.add ty tvconstraints.lower_bounds
| Some union ->
ITySet.of_list (union ty (ITySet.elements tvconstraints.lower_bounds))
in
let env = set_tyvar_constraints env var { tvconstraints with lower_bounds } in
env
(* Remove type variable `upper_var` from the upper bounds on `var`, if it exists
*)
let remove_tyvar_upper_bound env var upper_var =
match get_tyvar_constraints_opt env var with
| None -> env
| Some tvconstraints ->
let upper_bounds =
ITySet.filter
(fun ty ->
let (_env, ty) = expand_internal_type env ty in
not @@ InternalType.is_var_v ty ~v:upper_var)
tvconstraints.upper_bounds
in
set_tyvar_constraints env var { tvconstraints with upper_bounds }
(* Remove type variable `lower_var` from the lower bounds on `var`, if it exists
*)
let remove_tyvar_lower_bound env var lower_var =
match get_tyvar_constraints_opt env var with
| None -> env
| Some tvconstraints ->
let lower_bounds =
ITySet.filter
(fun ty ->
let (_env, ty) = expand_internal_type env ty in
not @@ InternalType.is_var_v ty ~v:lower_var)
tvconstraints.lower_bounds
in
set_tyvar_constraints env var { tvconstraints with lower_bounds }
let get_vars (env : t) = IMap.keys env.tvenv
let get_unsolved_vars (env : t) : identifier list =
IMap.fold
(fun v tvinfo vars ->
match tvinfo.solving_info with
| TVIConstraints _ -> v :: vars
| TVIType _ -> vars)
env.tvenv
[]
module Size = struct
(* This can be useful to debug type which blow up in size *)
let ty_size env ty =
let ty_size_visitor =
object
inherit [int] Type_visitor.locl_type_visitor as super
method! on_type acc ty = 1 + super#on_type acc ty
method! on_tvar acc r v =
let (_, ty) = expand_var env r v in
match get_node ty with
| Tvar v' when equal_identifier v' v -> acc
| _ -> super#on_type acc ty
end
in
ty_size_visitor#on_type 0 ty
let rec constraint_type_size env ty =
let type_size_list env l =
List.fold ~init:0 ~f:(fun size ty -> size + ty_size env ty) l
in
let type_size_option ~f opt = Option.value_map ~default:0 ~f opt in
match deref_constraint_type ty with
| (_, Tdestructure d) ->
let { d_required; d_optional; d_variadic; _ } = d in
1
+ type_size_list env d_required
+ type_size_list env d_optional
+ type_size_option ~f:(ty_size env) d_variadic
| (_, Thas_member hm) -> 1 + ty_size env hm.hm_type
| (_, Thas_type_member htm) ->
1 + ty_size env htm.htm_lower + ty_size env htm.htm_upper
| (_, Tcan_index ci) -> 1 + ty_size env ci.ci_val + ty_size env ci.ci_key
| (_, Tcan_traverse ct) ->
1 + ty_size env ct.ct_val + type_size_option ~f:(ty_size env) ct.ct_key
| (_, TCunion (lty, cty))
| (_, TCintersection (lty, cty)) ->
1 + ty_size env lty + constraint_type_size env cty
let internal_type_size env ty =
match ty with
| LoclType ty -> ty_size env ty
| ConstraintType ty -> constraint_type_size env ty
let internal_type_set_size env tys =
ITySet.elements tys
|> List.map ~f:(internal_type_size env)
|> List.fold ~init:0 ~f:( + )
let type_constants_size env tconsts =
SMap.map (fun (_id, ty) -> ty_size env ty) tconsts |> fun m ->
SMap.fold (fun _ x y -> x + y) m 0
let solving_info_size env solving_info =
match solving_info with
| TVIType ty -> ty_size env ty
| TVIConstraints tvcstr ->
let {
appears_covariantly = _;
appears_contravariantly = _;
upper_bounds;
lower_bounds;
type_constants;
} =
tvcstr
in
let ubound_size = internal_type_set_size env upper_bounds in
let lbound_size = internal_type_set_size env lower_bounds in
let tconst_size = type_constants_size env type_constants in
ubound_size + lbound_size + tconst_size
let tyvar_info_size env tvinfo =
let { tyvar_pos = _; solving_info; eager_solve_failed = _ } = tvinfo in
solving_info_size env solving_info
let inference_env_size env =
let { tvenv; subtype_prop = _; tyvars_stack = _; tyvar_occurrences = _ } =
env
in
IMap.map (tyvar_info_size env) tvenv |> fun m ->
IMap.fold (fun _ x y -> x + y) m 0
end
(* The following merging logic is used to gather all the information we have
* on a global type variable from multiple sub-graphs. It simply unions
* all the constraints and does not try to do anything clever like
* keeping the graph transitively closed. *)
let merge_constraints cstr1 cstr2 =
let {
lower_bounds = lb1;
upper_bounds = ub1;
type_constants = tc1;
appears_covariantly = cov1;
appears_contravariantly = contra1;
} =
cstr1
in
let {
lower_bounds = lb2;
upper_bounds = ub2;
type_constants = tc2;
appears_covariantly = cov2;
appears_contravariantly = contra2;
} =
cstr2
in
{
lower_bounds = ITySet.union lb1 lb2;
upper_bounds = ITySet.union ub1 ub2;
appears_covariantly = cov1 || cov2;
appears_contravariantly = contra1 || contra2;
type_constants =
(* Type constants must already have been made equivalent, so picking any should be fine *)
(* TODO: that might actually not be true during initial merging, but let's fix that later. *)
SMap.union tc1 tc2;
}
let solving_info_as_constraints sinfo =
match sinfo with
| TVIConstraints c -> c
| TVIType ty ->
{
lower_bounds = ITySet.singleton (LoclType ty);
upper_bounds = ITySet.singleton (LoclType ty);
appears_covariantly = false;
appears_contravariantly = false;
type_constants = SMap.empty;
}
let merge_solving_infos sinfo1 sinfo2 =
let cstr1 = solving_info_as_constraints sinfo1 in
let cstr2 = solving_info_as_constraints sinfo2 in
let cstr = merge_constraints cstr1 cstr2 in
TVIConstraints cstr
let merge_tyvar_infos tvinfo1 tvinfo2 =
let { tyvar_pos = pos1; eager_solve_failed = esf1; solving_info = sinfo1 } =
tvinfo1
in
let { tyvar_pos = pos2; eager_solve_failed = esf2; solving_info = sinfo2 } =
tvinfo2
in
{
tyvar_pos =
(if Pos.equal pos1 Pos.none then
pos2
else
pos1);
eager_solve_failed = esf1 || esf2;
solving_info = merge_solving_infos sinfo1 sinfo2;
}
let merge_tyvars env v1 v2 =
if equal_identifier v1 v2 then
env
else
let tvenv = env.tvenv in
let tvinfo1 = IMap.find v1 env.tvenv in
let tvinfo2 = IMap.find v2 env.tvenv in
let tvinfo = merge_tyvar_infos tvinfo1 tvinfo2 in
let tvenv = IMap.add v2 tvinfo tvenv in
let env = { env with tvenv } in
let env = add env v1 (mk (Reason.none, Tvar v2)) in
let env = remove_tyvar_lower_bound env v2 v2 in
let env = remove_tyvar_upper_bound env v2 v2 in
env
let simple_merge env1 env2 =
let {
tvenv = tvenv1;
subtype_prop = subtype_prop1;
tyvars_stack = tyvars_stack1;
tyvar_occurrences = tyvar_occurrences1;
} =
env1
in
let {
tvenv = tvenv2;
subtype_prop = _;
tyvars_stack = _;
tyvar_occurrences = _;
} =
env2
in
let tvenv =
IMap.merge
(fun _v tvinfo1 tvinfo2 ->
match (tvinfo1, tvinfo2) with
| (None, None) -> None
| (Some tvinfo, None)
| (None, Some tvinfo) ->
Some tvinfo
| (Some tvinfo1, Some tvinfo2) ->
let {
tyvar_pos = tyvar_pos1;
eager_solve_failed = eager_solve_failed1;
solving_info = sinfo1;
} =
tvinfo1
in
let {
tyvar_pos = tyvar_pos2;
eager_solve_failed = eager_solve_failed2;
solving_info = sinfo2;
} =
tvinfo2
in
let tvinfo =
{
tyvar_pos =
(if Pos.equal tyvar_pos1 Pos.none then
tyvar_pos2
else
tyvar_pos1);
eager_solve_failed = eager_solve_failed1 || eager_solve_failed2;
solving_info =
(match (sinfo1, sinfo2) with
| (TVIConstraints _, TVIType ty)
| (TVIType ty, TVIConstraints _) ->
TVIType ty
| (TVIConstraints _, TVIConstraints _)
| (TVIType _, TVIType _) ->
sinfo1);
}
in
Some tvinfo)
tvenv1
tvenv2
in
{
tvenv;
subtype_prop = subtype_prop1;
tyvars_stack = tyvars_stack1;
tyvar_occurrences = tyvar_occurrences1;
}
let get_nongraph_subtype_prop env = env.subtype_prop
let is_alias_for_another_var env v =
match get_solving_info_opt env v with
| Some (TVIType ty) -> begin
match get_node ty with
| Tvar v' when Int.( <> ) v v' -> true
| _ -> false
end
| _ -> false
(** Some ty vars in the map will carry no additional information, e.g.
some ty vars belong to methods declared in parent classes, even
when these methods are not used in the subclass itself. In those cases,
the ty var will be registered, but the accompagnying ty var info
will contain nothing useful. It will in essence be an identity element
under the merge operation. *)
let solving_info_carries_information = function
| TVIType _ -> true
| TVIConstraints tvcstr ->
let {
appears_covariantly;
appears_contravariantly;
upper_bounds;
lower_bounds;
type_constants;
} =
tvcstr
in
appears_contravariantly
|| appears_covariantly
|| (not @@ ITySet.is_empty upper_bounds)
|| (not @@ ITySet.is_empty lower_bounds)
|| (not @@ SMap.is_empty type_constants)
let tyvar_info_carries_information tvinfo =
let { tyvar_pos = _; solving_info; eager_solve_failed = _ } = tvinfo in
solving_info_carries_information solving_info
let compress env =
let { tvenv; subtype_prop; tyvars_stack; tyvar_occurrences } = env in
let tvenv = IMap.filter (fun _k -> tyvar_info_carries_information) tvenv in
{ tvenv; subtype_prop; tyvars_stack; tyvar_occurrences }
let remove_var_from_bounds
env v ~search_in_upper_bounds_of ~search_in_lower_bounds_of =
let env =
ISet.fold
(fun v' env ->
Option.fold
(get_tyvar_upper_bounds_opt env v')
~init:env
~f:(fun env bounds ->
ITySet.filter (InternalType.is_not_var_v ~v) bounds
|> set_tyvar_upper_bounds env v'))
search_in_upper_bounds_of
env
in
let env =
ISet.fold
(fun v' env ->
Option.fold
(get_tyvar_lower_bounds_opt env v')
~init:env
~f:(fun env bounds ->
ITySet.filter (InternalType.is_not_var_v ~v) bounds
|> set_tyvar_lower_bounds env v'))
search_in_lower_bounds_of
env
in
env
let remove_var_from_tyvars_stack tyvars_stack var =
List.map tyvars_stack ~f:(fun (p, vars) ->
(p, List.filter vars ~f:(fun v -> not (equal_identifier var v))))
let replace_var_by_ty_in_prop prop v ty =
let rec replace prop =
match prop with
| TL.IsSubtype (cd, ty1, ty2) ->
let ty1 =
if InternalType.is_var_v ty1 ~v then
LoclType ty
else
ty1
in
let ty2 =
if InternalType.is_var_v ty2 ~v then
LoclType ty
else
ty2
in
TL.IsSubtype (cd, ty1, ty2)
| TL.Disj (f, props) ->
let props = List.map props ~f:replace in
TL.Disj (f, props)
| TL.Conj props ->
let props = List.map props ~f:replace in
TL.Conj props
in
replace prop
let remove_var env var ~search_in_upper_bounds_of ~search_in_lower_bounds_of =
let env =
remove_var_from_bounds
env
var
~search_in_upper_bounds_of
~search_in_lower_bounds_of
in
let (env, ty) = expand_var env Reason.none var in
let { tvenv; tyvars_stack; tyvar_occurrences; subtype_prop } = env in
let tyvar_occurrences = Occ.remove_var tyvar_occurrences var in
let tvenv = IMap.remove var tvenv in
let tyvars_stack = remove_var_from_tyvars_stack tyvars_stack var in
let subtype_prop = replace_var_by_ty_in_prop subtype_prop var ty in
{ tvenv; tyvars_stack; tyvar_occurrences; subtype_prop }
(** This is a horrible thing meant to throw a warning when some invariant turns out
to be wrong (namely a variable should not yet be solved) and to help us get back
on our feet when this happens. Once we figure out why this invariant is wrong,
this function should die. *)
let unsolve env v =
let { tvenv; tyvars_stack; subtype_prop; tyvar_occurrences } = env in
match IMap.find_opt v tvenv with
| None -> env
| Some tvinfo ->
let { solving_info; tyvar_pos; eager_solve_failed } = tvinfo in
(match solving_info with
| TVIConstraints _ -> env
| TVIType ty ->
let stack = Caml.Printexc.get_callstack 50 in
Printf.eprintf
"Did not expect variable #%d to be solved already. Unsolving it.\n"
v;
Caml.Printexc.print_raw_backtrace stderr stack;
Printf.eprintf "%!";
let solving_info =
TVIConstraints
{
appears_covariantly = false;
appears_contravariantly = false;
upper_bounds = ITySet.singleton (LoclType ty);
lower_bounds = ITySet.singleton (LoclType ty);
type_constants = SMap.empty;
}
in
let tvinfo = { solving_info; tyvar_pos; eager_solve_failed } in
let tvenv = IMap.add v tvinfo tvenv in
{ tvenv; tyvars_stack; subtype_prop; tyvar_occurrences }) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_inference_env.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Typing_defs
exception InconsistentTypeVarState of string
(** contains the inference env, containing all the information necessary to
perform type inference. *)
type t
(** Module providing identifiers for type variables. *)
module Identifier_provider : sig
(** Re-initialize identifier provider for each type inference scope. *)
val reinitialize : unit -> unit
end
module Log : sig
val inference_env_as_value : t -> Typing_log_value.value
(** Convert a type variable from an environment into json *)
val tyvar_to_json :
(locl_ty -> string) ->
(internal_type -> string) ->
t ->
Ident.t ->
Hh_json.json
end
val pp : Format.formatter -> t -> unit
val empty_inference_env : t
val fresh_type : ?variance:Ast_defs.variance -> t -> Pos.t -> t * locl_ty
(** Same as fresh_type but takes a specific reason as parameter. *)
val fresh_type_reason :
?variance:Ast_defs.variance -> t -> Pos.t -> Reason.t -> t * locl_ty
val fresh_type_invariant : t -> Pos.t -> t * locl_ty
val open_tyvars : t -> Pos.t -> t
val get_current_tyvars : t -> Ident.t list
val close_tyvars : t -> t
val tyvar_is_solved : t -> Ident.t -> bool
val tyvar_occurs_in_tyvar : t -> Ident.t -> in_:Ident.t -> bool
val get_tyvar_occurrences : t -> Ident.t -> ISet.t
val get_tyvars_in_tyvar : t -> Ident.t -> ISet.t
val contains_unsolved_tyvars : t -> Ident.t -> bool
val make_tyvar_no_more_occur_in_tyvar : t -> int -> no_more_in:int -> t
val bind : t -> ?tyvar_pos:Pos.t -> Ident.t -> locl_ty -> t
val add : t -> ?tyvar_pos:Pos.t -> Ident.t -> locl_ty -> t
val get_direct_binding : t -> Ident.t -> locl_ty option
val get_type : t -> Reason.t -> Ident.t -> t * locl_ty
val expand_var : t -> Reason.t -> Ident.t -> t * locl_ty
val expand_type : t -> locl_ty -> t * locl_ty
val expand_internal_type : t -> internal_type -> t * internal_type
val fully_expand_type : t -> locl_ty -> t * locl_ty
val get_tyvar_pos : t -> Ident.t -> Pos.t
(* Get or add to bounds on type variables *)
val get_tyvar_lower_bounds : t -> Ident.t -> Internal_type_set.t
val get_tyvar_upper_bounds : t -> Ident.t -> Internal_type_set.t
val set_tyvar_lower_bounds : t -> Ident.t -> Internal_type_set.t -> t
val set_tyvar_upper_bounds : t -> Ident.t -> Internal_type_set.t -> t
(* Optionally supply intersection or union operations to simplify the bounds *)
val add_tyvar_upper_bound :
?intersect:(internal_type -> internal_type list -> internal_type list) ->
t ->
Ident.t ->
internal_type ->
t
val add_tyvar_lower_bound :
?union:(internal_type -> internal_type list -> internal_type list) ->
t ->
Ident.t ->
internal_type ->
t
val remove_tyvar_upper_bound : t -> Ident.t -> Ident.t -> t
val remove_tyvar_lower_bound : t -> Ident.t -> Ident.t -> t
val set_tyvar_appears_covariantly : t -> Ident.t -> t
val set_tyvar_appears_contravariantly : t -> Ident.t -> t
val set_tyvar_eager_solve_fail : t -> Ident.t -> t
val get_tyvar_appears_covariantly : t -> Ident.t -> bool
val get_tyvar_appears_contravariantly : t -> Ident.t -> bool
val get_tyvar_appears_invariantly : t -> Ident.t -> bool
val wrap_ty_in_var : t -> Typing_reason.t -> locl_ty -> t * locl_ty
val get_tyvar_eager_solve_fail : t -> Ident.t -> bool
val get_tyvar_type_const : t -> Ident.t -> pos_id -> (pos_id * locl_ty) option
val set_tyvar_type_const : t -> Ident.t -> pos_id -> locl_ty -> t
val get_tyvar_type_consts : t -> Ident.t -> (pos_id * locl_ty) SMap.t
val add_subtype_prop : t -> Typing_logic.subtype_prop -> t
val get_current_pos_from_tyvar_stack : t -> Pos.t option
(** Get the list of all type variables in the environment *)
val get_vars : t -> Ident.t list
(** Get the list of all unsolved type variables in the environment *)
val get_unsolved_vars : t -> Ident.t list
module Size : sig
val ty_size : t -> locl_ty -> int
val inference_env_size : t -> int
end
(** Only merge the tvenv parts. Resolve conflicts stupidly by taking the first mapping of the two. *)
val simple_merge : t -> t -> t
(** Merge type variables by transferring all constraints from the first to the second
and binding the first to the second.
Does not perform anything clever, especially does not perform any transitive closure.
Will throw an exception of the type variables are already solved. *)
val merge_tyvars : t -> Ident.t -> Ident.t -> t
(** Gets the part of the subtype proposition that should not be added to the
constraint graph (e.g. because it contains disjunctions). *)
val get_nongraph_subtype_prop : t -> Typing_logic.subtype_prop
val is_alias_for_another_var : t -> Ident.t -> bool
(** Remove variables containing no information. *)
val compress : t -> t
(** Remove solved variable from environment by replacing it by its binding. *)
val remove_var :
t ->
Ident.t ->
search_in_upper_bounds_of:ISet.t ->
search_in_lower_bounds_of:ISet.t ->
t
val unsolve : t -> Ident.t -> t |
OCaml | hhvm/hphp/hack/src/typing/typing_intersection.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Common
open Typing_defs
module Env = Typing_env
module MkType = Typing_make_type
module Reason = Typing_reason
module TySet = Typing_set
module Utils = Typing_utils
exception Nothing
(** Computes the negation of a type when it is known, which is currently the case
for null, nonnull, mixed, nothing, primitives, and classes.
Otherwise approximate up or down according to
`approx` parameter: If approx is `ApproxUp`, return mixed, else if it is `ApproxDown`,
return nothing. *)
let negate_type env r ty ~approx =
let (env, ty) = Env.expand_type env ty in
let neg_ty =
match get_node ty with
| Tprim Aast.Tnull -> MkType.nonnull r
| Tprim tp -> MkType.neg r (Neg_prim tp)
| Tneg (Neg_prim tp) -> MkType.prim_type r tp
| Tneg (Neg_class (_, c)) when Utils.class_has_no_params env c ->
MkType.class_type r c []
| Tnonnull -> MkType.null r
| Tclass (c, Nonexact _, _) -> MkType.neg r (Neg_class c)
| _ ->
if Utils.equal_approx approx Utils.ApproxUp then
MkType.mixed r
else
MkType.nothing r
in
(env, neg_ty)
(** Decompose nullable types into unions with null
decompose_nullable ?A = null | A
decompose_nullable ?(A | ?B) = null | A | B
The implementation has the side-effect of flattening unions if the type is
nullable, e.g.,
decompose_optional ?(A | (B | C)) = null | A | B | C
*)
let decompose_nullable ty =
let rec has_option (ty : 'a ty) : bool =
match deref ty with
| (_, Toption _) -> true
| (_, Tunion tyl) -> List.exists ~f:has_option tyl
| _ -> false
in
let rec peel (ty_acc : 'a ty list) (ty : 'a ty) : 'a ty list =
match deref ty with
| (_, Toption ty) -> peel ty_acc ty
| (_, Tunion tyl) -> List.fold ~init:ty_acc ~f:peel tyl
| _ -> ty :: ty_acc
in
if has_option ty then
let r = get_reason ty in
let null_ty = MkType.null r in
let tyl = peel [null_ty] ty in
let tyl = TySet.elements (TySet.of_list tyl) in
MkType.union r tyl
else
ty
(** Build a union from a list of types. Flatten if any of the types themselves are union.
Also, pull nullable out to a top-level Toption. Undoes decompose atomic.
*)
let recompose_atomic env r tyl =
let rec traverse nullable dynamic tyl_acc tyl =
match tyl with
| [] -> (nullable, dynamic, List.rev tyl_acc)
| ty :: tyl ->
if Utils.is_nothing env ty then
traverse nullable dynamic tyl_acc tyl
else (
match deref ty with
| (r, Toption ty) -> traverse (Some r) dynamic (ty :: tyl_acc) tyl
| (r, Tprim Aast.Tnull) -> traverse (Some r) dynamic tyl_acc tyl
| (r, Tdynamic) -> traverse nullable (Some r) tyl_acc tyl
| (_, Tunion tyl') -> traverse nullable dynamic tyl_acc (tyl' @ tyl)
| _ -> traverse nullable dynamic (ty :: tyl_acc) tyl
)
in
let (nullable_r, dynamic_r, tyl) = traverse None None [] tyl in
Utils.make_union env r tyl nullable_r dynamic_r
(* Destructure an intersection into a list of its sub-types,
decending into sub-intersections.
*)
let destruct_inter_list env tyl =
let orr r_opt r = Some (Option.value r_opt ~default:r) in
let rec dest_inter env ty tyl tyl_res r_inter =
let (env, ty) = Env.expand_type env ty in
match deref ty with
| (r, Tintersection tyl') ->
destruct_inter_list env (tyl' @ tyl) tyl_res (orr r_inter r)
| _ -> destruct_inter_list env tyl (ty :: tyl_res) r_inter
and destruct_inter_list env tyl tyl_res r_union =
match tyl with
| [] -> (env, (tyl_res, r_union))
| ty :: tyl -> dest_inter env ty tyl tyl_res r_union
in
destruct_inter_list env tyl [] None
(** Number of '&' symbols in an intersection representation. E.g. for (A & B),
returns 1, for A, returns 0. *)
let number_of_inter_symbols env ty =
let rec n_inter env tyl n =
match tyl with
| [] -> (env, n)
| ty :: tyl ->
let (env, ty) = Env.expand_type env ty in
begin
match get_node ty with
| Tintersection tyl' ->
n_inter env (tyl' @ tyl) (List.length tyl' - 1 + n)
| Tunion tyl' -> n_inter env (tyl' @ tyl) n
| Toption ty -> n_inter env (ty :: tyl) n
| _ -> n_inter env tyl n
end
in
n_inter env [ty] 0
let collapses env ty1 ty2 ~inter_ty =
let (env, n_inter_inter) = number_of_inter_symbols env inter_ty in
let (env, n_inter1) = number_of_inter_symbols env ty1 in
let (env, n_inter2) = number_of_inter_symbols env ty2 in
(env, n_inter_inter <= n_inter1 + n_inter2)
let make_intersection env r tyl =
let ty = MkType.intersection r tyl in
let (env, ty) = Utils.wrap_union_inter_ty_in_var env r ty in
(env, ty)
(** Computes the intersection (greatest lower bound) of two types.
For the intersection of unions, attempt to simplify by using the distributivity
of intersection over union. Uses the the `collapses` test function to make sure
the resulting type is no greater in size than the trivial `Tintersection [ty1; ty2]`. *)
let rec intersect env ~r ty1 ty2 =
if ty_equal ty1 ty2 then
(env, ty1)
else
let (env, ty1) = Env.expand_type env ty1 in
let (env, ty2) = Env.expand_type env ty2 in
if Utils.is_sub_type_for_union env ty1 ty2 then
(env, ty1)
else if Utils.is_sub_type_for_union env ty2 ty1 then
(env, ty2)
else if Utils.is_type_disjoint env ty1 ty2 then (
let inter_ty = MkType.nothing r in
Typing_log.log_intersection ~level:2 env r ty1 ty2 ~inter_ty;
(env, inter_ty)
) else
(* Attempt to simplify any case types involved in the intersection.
If simplification occurs we re-run [intersect] with the simplified type
until no more simplications can be performed.
Note: Re-running [intersect] when neither [ty1] or [ty2] has been
simplified will lead to infinite recursion.
*)
let (env, simplified_ty1_opt) =
try_simplifying_case_type env ~case_type:ty1 ~intersect_ty:ty2
in
let (env, simplified_ty2_opt) =
try_simplifying_case_type env ~case_type:ty2 ~intersect_ty:ty1
in
match (simplified_ty1_opt, simplified_ty2_opt) with
| (Some simplified_ty1, None) -> intersect env ~r simplified_ty1 ty2
| (None, Some simplified_ty2) -> intersect env ~r ty1 simplified_ty2
| (Some simplified_ty1, Some simplified_ty2) ->
intersect env ~r simplified_ty1 simplified_ty2
| (None, None) ->
let ty1 = decompose_nullable ty1 in
let ty2 = decompose_nullable ty2 in
let (env, inter_ty) =
try
match (deref ty1, deref ty2) with
| ((_, Ttuple tyl1), (_, Ttuple tyl2))
when Int.equal (List.length tyl1) (List.length tyl2) ->
let (env, inter_tyl) =
List.map2_env env tyl1 tyl2 ~f:(intersect ~r)
in
(env, mk (r, Ttuple inter_tyl))
(* Runtime representation of tuples is vec, which can be observed in Hack via refinement.
* Therefore it's sound to simplify vec<t> & (t1,...,tn) to (t & t1, ..., t & tn)
* but because we don't support subtyping directly between tuples and vecs, we need
* to keep the vec conjunct i.e. simplify to vec<t> & (t & t1, ..., t & tn)
*)
| (((_, Tclass ((_, cn), _, [ty])) as vty), (rt, Ttuple tyl))
| ((rt, Ttuple tyl), ((_, Tclass ((_, cn), _, [ty])) as vty))
when String.equal cn Naming_special_names.Collections.cVec ->
let (env, inter_tyl) =
List.map_env env tyl ~f:(fun env ty' -> intersect ~r env ty ty')
in
make_intersection env r [mk vty; mk (rt, Ttuple inter_tyl)]
| ( ( _,
Tshape
{
s_origin = _;
s_unknown_value = shape_kind1;
s_fields = fdm1;
} ),
( _,
Tshape
{
s_origin = _;
s_unknown_value = shape_kind2;
s_fields = fdm2;
} ) ) ->
let (env, shape_kind, fdm) =
intersect_shapes env r (shape_kind1, fdm1) (shape_kind2, fdm2)
in
( env,
mk
( r,
Tshape
{
s_origin = Missing_origin;
s_unknown_value = shape_kind;
s_fields = fdm;
} ) )
| ((_, Tintersection tyl1), (_, Tintersection tyl2)) ->
intersect_lists env r tyl1 tyl2
(* Simplify `supportdyn<t> & u` to `supportdyn<t & u>`. Do not apply if `u` is
* a type variable, else we end up with recursion in constraints. *)
| ((r, Tnewtype (name1, [ty1arg], _)), _)
when String.equal name1 Naming_special_names.Classes.cSupportDyn
&& not (is_tyvar ty2) ->
let (env, ty) = intersect ~r env ty1arg ty2 in
let (env, res) = Utils.simple_make_supportdyn r env ty in
(env, res)
| (_, (r, Tnewtype (name1, [ty2arg], _)))
when String.equal name1 Naming_special_names.Classes.cSupportDyn
&& not (is_tyvar ty1) ->
let (env, ty) = intersect ~r env ty1 ty2arg in
let (env, res) = Utils.simple_make_supportdyn r env ty in
(env, res)
| ((_, Tintersection tyl), _) -> intersect_lists env r [ty2] tyl
| (_, (_, Tintersection tyl)) -> intersect_lists env r [ty1] tyl
| ((r1, Tunion tyl1), (r2, Tunion tyl2)) ->
let (common_tyl, tyl1', tyl2') =
Typing_algebra.factorize_common_types tyl1 tyl2
in
let (env, not_common_tyl) =
intersect_unions env r (r1, tyl1') (r2, tyl2')
in
recompose_atomic env r (common_tyl @ not_common_tyl)
| ((r_union, Tunion tyl), ty)
| (ty, (r_union, Tunion tyl)) ->
let (env, inter_tyl) =
intersect_ty_union env r (mk ty) (r_union, tyl)
in
recompose_atomic env r inter_tyl
| ((_, Tprim Aast.Tnum), (_, Tprim Aast.Tarraykey))
| ((_, Tprim Aast.Tarraykey), (_, Tprim Aast.Tnum)) ->
(env, MkType.int r)
| ( (_, Tneg (Neg_prim (Aast.Tint | Aast.Tarraykey))),
(_, Tprim Aast.Tnum) )
| ( (_, Tprim Aast.Tnum),
(_, Tneg (Neg_prim (Aast.Tint | Aast.Tarraykey))) ) ->
(env, MkType.float r)
| ((_, Tneg (Neg_prim Aast.Tfloat)), (_, Tprim Aast.Tnum))
| ((_, Tprim Aast.Tnum), (_, Tneg (Neg_prim Aast.Tfloat))) ->
(env, MkType.int r)
| ((_, Tneg (Neg_prim Aast.Tstring)), ty_ak)
| (ty_ak, (_, Tneg (Neg_prim Aast.Tstring))) ->
if
(* Ocaml warns about ambiguous or-pattern variables under guard if this is in a when clause*)
Utils.is_sub_type_for_union
env
(mk ty_ak)
(MkType.arraykey Reason.Rnone)
then
intersect env ~r (mk ty_ak) (MkType.int r)
else
make_intersection env r [ty1; ty2]
| ((_, Tneg (Neg_prim (Aast.Tint | Aast.Tnum))), ty_ak)
| (ty_ak, (_, Tneg (Neg_prim (Aast.Tint | Aast.Tnum)))) ->
if
Utils.is_sub_type_for_union
env
(mk ty_ak)
(MkType.arraykey Reason.Rnone)
then
intersect env ~r (mk ty_ak) (MkType.string r)
else
make_intersection env r [ty1; ty2]
| _ -> make_intersection env r [ty1; ty2]
with
| Nothing -> (env, MkType.nothing r)
in
Typing_log.log_intersection ~level:2 env r ty1 ty2 ~inter_ty;
(env, inter_ty)
(** Attempts to simplify an intersection involving a case type and another type. If [case_type]
is a case type, we fetch the list of variant types, then filter this list down to only the types
that intersect with the data types associated with [ty]. If the resulting filtered type is a
not a union type, we consider it to be a simplified version of the case type and return it.
Otherwise simplification fails and [None] is returned. As an example consider:
[case_type] = int | vec<int> | string
[ty] = not int & not string
This will result in simplifying the case type to `vec<int>`
If instead we had:
[ty] = not int
This would fail to simplify because the result filtered type would be `vec<int> | string`
Finally if we had:
[ty] = not vec
This would succeed, because the union `int | string` would simplify to `arraykey`
*)
and try_simplifying_case_type env ~case_type ~intersect_ty =
match deref case_type with
| (r, Tnewtype (name, ty_args, _)) ->
let (env, variants_opt) =
Typing_case_types.get_variant_tys env name ty_args
in
begin
match variants_opt with
| Some variants ->
let (env, filtered_ty) =
Typing_case_types.filter_variants_using_datatype
env
r
variants
intersect_ty
in
if Typing_defs.is_union filtered_ty then
(env, None)
else
(env, Some filtered_ty)
| None -> (env, None)
end
| (r, Tintersection tyl) ->
(* For each type in [tyl] try to simplify all case types that are present, filtering based on
the intersection of all other types in the intersection.
[acc] will contain the rebuilt list with any case types that could be simplified replaced with their simplified form
[changed] will be `true` if a case type in the list was simplified, otherwise it will be `false*)
let rec simplify_all_case_types env tyl (acc, changed) =
match tyl with
| ty :: tyl ->
let (env, simplified_ty_opt) =
try_simplifying_case_type
env
~case_type:ty
~intersect_ty:(MkType.intersection r ((intersect_ty :: tyl) @ acc))
in
let result =
match simplified_ty_opt with
| Some simplified_ty -> (simplified_ty :: acc, true)
| None -> (ty :: acc, changed)
in
simplify_all_case_types env tyl result
| [] -> (env, acc, changed)
in
let (env, simplified_tyl, changed) =
simplify_all_case_types env tyl ([], false)
in
if changed then
let (env, simplified_ty) = intersect_list env r simplified_tyl in
(env, Some simplified_ty)
else
(env, None)
| _ -> (env, None)
and intersect_shapes env r (shape_kind1, fdm1) (shape_kind2, fdm2) =
let (env, fdm) =
TShapeMap.merge_env env fdm1 fdm2 ~combine:(fun env _sfn sft1 sft2 ->
match
((is_nothing shape_kind1, sft1), (is_nothing shape_kind2, sft2))
with
| ((_, None), (_, None))
| ((_, Some { sft_optional = true; _ }), (true, None))
| ((true, None), (_, Some { sft_optional = true; _ })) ->
(env, None)
| ((_, Some { sft_optional = false; _ }), (true, None))
| ((true, None), (_, Some { sft_optional = false; _ })) ->
raise Nothing
| ((_, Some sft), (_, None)) ->
let (env, ty) = intersect env ~r shape_kind2 sft.sft_ty in
(env, Some { sft with sft_ty = ty })
| ((_, None), (_, Some sft)) ->
let (env, ty) = intersect env ~r shape_kind1 sft.sft_ty in
(env, Some { sft with sft_ty = ty })
| ( (_, Some { sft_optional = opt1; sft_ty = ty1 }),
(_, Some { sft_optional = opt2; sft_ty = ty2 }) ) ->
let opt = opt1 && opt2 in
let (env, ty) = intersect env ~r ty1 ty2 in
(env, Some { sft_optional = opt; sft_ty = ty }))
in
let (env, shape_kind) = intersect env ~r shape_kind1 shape_kind2 in
(env, shape_kind, fdm)
and intersect_lists env r tyl1 tyl2 =
let rec intersect_lists env tyl1 tyl2 acc_tyl =
match (tyl1, tyl2) with
| ([], _) -> (env, tyl2 @ acc_tyl)
| (_, []) -> (env, tyl1 @ acc_tyl)
| (ty1 :: tyl1', _) ->
let (env, (inter_ty, missed_inter_tyl2)) =
intersect_ty_tyl env r ty1 tyl2
in
intersect_lists env tyl1' missed_inter_tyl2 (inter_ty :: acc_tyl)
in
let (env, tyl) = intersect_lists env tyl1 tyl2 [] in
make_intersection env r tyl
and intersect_ty_tyl env r ty tyl =
let rec intersect_ty_tyl env ty tyl missed_inter_tyl =
match tyl with
| [] -> (env, (ty, missed_inter_tyl))
| ty' :: tyl' ->
let (env, ty_opt) = try_intersect env r ty ty' in
begin
match ty_opt with
| None -> intersect_ty_tyl env ty tyl' (ty' :: missed_inter_tyl)
| Some inter_ty -> intersect_ty_tyl env inter_ty tyl' missed_inter_tyl
end
in
intersect_ty_tyl env ty tyl []
and try_intersect env r ty1 ty2 =
let (env, ty) = intersect env ~r ty1 ty2 in
let (env, ty) = Env.expand_type env ty in
match get_node ty with
| Tintersection _ -> (env, None)
| _ -> (env, Some ty)
and intersect_unions env r (r1, tyl1) (r2, tyl2) =
(* The order matters. (A | B | C) & (A | B) gets simplified to (A | B)
while (A | B) & (A | B | C) would become A | B | ((A | B) & C), so we
put the longest union first as a heuristic. *)
let ((r1, tyl1), (r2, tyl2)) =
if List.length tyl1 >= List.length tyl2 then
((r1, tyl1), (r2, tyl2))
else
((r2, tyl2), (r1, tyl1))
in
let union_ty1 = MkType.union r1 tyl1 in
intersect_ty_union env r union_ty1 (r2, tyl2)
(** For (A1 | .. | An) & B, compute each of the A1 & B, .. , An & B.
Keep those which collapse (see `collapses` function) with B
and leave the others unchanged.
So if I is the set of indices i such that Ai collapses with B,
and J the set of indices such that this is not the case,
the result would be
(|_{i in I} (Ai & B)) | (B & (|_{j in J} Aj))
*)
and intersect_ty_union env r (ty1 : locl_ty) (r_union, tyl2) =
let (env, inter_tyl) =
List.map_env env tyl2 ~f:(fun env ty2 -> intersect env ~r ty1 ty2)
in
let zipped = List.zip_exn tyl2 inter_tyl in
let (collapsed, not_collapsed) =
List.partition_tf zipped ~f:(fun (ty2, inter_ty) ->
snd @@ collapses env ty1 ty2 ~inter_ty)
in
let collapsed = List.map collapsed ~f:snd in
let not_collapsed =
match not_collapsed with
| [] -> []
| [(_ty2, inter_ty)] -> [inter_ty]
| _ ->
let not_collapsed = List.map not_collapsed ~f:fst in
[MkType.intersection r [ty1; MkType.union r_union not_collapsed]]
in
(env, not_collapsed @ collapsed)
and intersect_list env r tyl =
(* We need to match tyl here because we'd mess the reason if tyl was just
[mixed] *)
match tyl with
| [] -> (env, MkType.mixed r)
| ty :: tyl -> List.fold_left_env env tyl ~init:ty ~f:(intersect ~r)
let normalize_intersection env ?on_tyvar tyl =
let orr r_opt r = Some (Option.value r_opt ~default:r) in
let rec normalize_intersection env r tyl tys_acc =
match tyl with
| [] -> (env, r, tys_acc)
| ty :: tyl ->
let (env, ty) = Env.expand_type env ty in
let proceed env ty =
normalize_intersection env r tyl (TySet.add ty tys_acc)
in
begin
match (deref ty, on_tyvar) with
| ((r', Tvar v), Some on_tyvar) ->
let (env, ty') = on_tyvar env r' v in
if ty_equal ty ty' then
proceed env ty
else
normalize_intersection env r (ty' :: tyl) tys_acc
| ((r', Tintersection tyl'), _) ->
normalize_intersection env (orr r r') (tyl' @ tyl) tys_acc
| ((_, Tunion _), _) ->
let (env, ty) = Utils.simplify_unions env ty ?on_tyvar in
let (env, ety) = Env.expand_type env ty in
begin
match get_node ety with
| Tunion _ -> proceed env ty
| _ -> normalize_intersection env r (ty :: tyl) tys_acc
end
| _ -> proceed env ty
end
in
normalize_intersection env None tyl TySet.empty
let simplify_intersections env ?on_tyvar ty =
let r = get_reason ty in
let (env, r', tys) = normalize_intersection env [ty] ?on_tyvar in
let r = Option.value r' ~default:r in
intersect_list env r (TySet.elements tys)
let intersect env ~r ty1 ty2 =
let (env, inter_ty) = intersect env ~r ty1 ty2 in
Typing_log.log_intersection ~level:1 env r ty1 ty2 ~inter_ty;
(env, inter_ty)
let rec intersect_i env r ty1 lty2 =
let ty2 = LoclType lty2 in
if Utils.is_sub_type_for_union_i env ty1 ty2 then
(env, ty1)
else if Utils.is_sub_type_for_union_i env ty2 ty1 then
(env, ty2)
else
let (env, ty) =
match ty1 with
| LoclType lty1 ->
let (env, ty) = intersect env ~r lty1 lty2 in
(env, LoclType ty)
| ConstraintType cty1 ->
(match deref_constraint_type cty1 with
| (r, TCintersection (lty1, cty1)) ->
let (env, lty) = intersect env ~r lty1 lty2 in
( env,
ConstraintType (mk_constraint_type (r, TCintersection (lty, cty1)))
)
| (r, TCunion (lty1, cty1)) ->
(* Distribute intersection over union.
At the moment local types in TCunion can only be
unions or intersections involving only null and nonnull,
so applying distributivity allows for simplifying the types. *)
let (env, lty) = intersect env ~r lty1 lty2 in
let (env, ty) = intersect_i env r (ConstraintType cty1) lty2 in
(match ty with
| LoclType ty ->
let (env, ty) = Utils.union env lty ty in
(env, LoclType ty)
| ConstraintType cty ->
(env, ConstraintType (mk_constraint_type (r, TCunion (lty, cty)))))
| (_, Thas_member _)
| (_, Thas_type_member _)
| (_, Tcan_index _)
| (_, Tcan_traverse _)
| (_, Tdestructure _) ->
( env,
ConstraintType (mk_constraint_type (r, TCintersection (lty2, cty1)))
))
in
match ty with
| LoclType _ -> (env, ty)
| ConstraintType ty -> Utils.simplify_constraint_type env ty
let () = Utils.negate_type_ref := negate_type
let () = Utils.simplify_intersections_ref := simplify_intersections
let () = Utils.intersect_list_ref := intersect_list |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_intersection.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Typing_defs
open Typing_env_types
module Reason = Typing_reason
module Utils = Typing_utils
val negate_type :
env -> Reason.t -> locl_ty -> approx:Utils.approx -> env * locl_ty
val intersect : env -> r:Reason.t -> locl_ty -> locl_ty -> env * locl_ty
val intersect_list : env -> Reason.t -> locl_ty list -> env * locl_ty
val simplify_intersections :
env ->
?on_tyvar:(env -> Reason.t -> int -> env * locl_ty) ->
locl_ty ->
env * locl_ty
val intersect_i :
env -> Typing_reason.t -> internal_type -> locl_ty -> env * internal_type
val destruct_inter_list :
env -> locl_ty list -> env * (locl_ty list * Reason.t option) |
OCaml | hhvm/hphp/hack/src/typing/typing_kinding.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Common
open Utils
open Typing_defs
open Typing_kinding_defs
module Env = Typing_env
module Cls = Decl_provider.Class
module KindDefs = Typing_kinding_defs
module TGenConstraint = Typing_generic_constraint
module TUtils = Typing_utils
module Subst = Decl_subst
module Locl_Inst = struct
let rec instantiate subst (ty : locl_ty) =
let merge_hk_type orig_r orig_var ty args =
let (r, ty_) = deref ty in
let res_ty_ =
match ty_ with
| Tclass (n, exact, existing_args) ->
(* We could insist on existing_args = [] here unless we want to support partial application. *)
Tclass (n, exact, existing_args @ args)
| Tnewtype (n, existing_args, bound) ->
Tnewtype (n, existing_args @ args, bound)
| Tunapplied_alias _ -> failwith "not implemented"
| Tgeneric (n, existing_args) ->
(* Same here *)
Tgeneric (n, existing_args @ args)
| _ ->
(* We could insist on args = [] here, everything else is a kinding error *)
ty_
in
mk (Reason.Rinstantiate (r, orig_var, orig_r), res_ty_)
in
(* PERF: If subst is empty then instantiation is a no-op. We can save a
* significant amount of CPU by avoiding recursively deconstructing the ty
* data type.
*)
if SMap.is_empty subst then
ty
else
match deref ty with
| (r, Tgeneric (x, args)) ->
let args = List.map args ~f:(instantiate subst) in
(match SMap.find_opt x subst with
| Some x_ty -> merge_hk_type r x x_ty args
| None -> mk (r, Tgeneric (x, args)))
| (r, ty) ->
let ty = instantiate_ subst ty in
mk (r, ty)
and instantiate_ subst x =
match x with
| Tgeneric _ -> assert false
| Tvec_or_dict (ty1, ty2) ->
let ty1 = instantiate subst ty1 in
let ty2 = instantiate subst ty2 in
Tvec_or_dict (ty1, ty2)
| (Tvar _ | Tdynamic | Tnonnull | Tany _ | Tprim _ | Tneg _) as x -> x
| Ttuple tyl ->
let tyl = List.map tyl ~f:(instantiate subst) in
Ttuple tyl
| Tunion tyl ->
let tyl = List.map tyl ~f:(instantiate subst) in
Tunion tyl
| Tintersection tyl ->
let tyl = List.map tyl ~f:(instantiate subst) in
Tintersection tyl
| Toption ty ->
let ty = instantiate subst ty in
(* we want to avoid double option: ??T *)
(match get_node ty with
| Toption _ as ty_node -> ty_node
| _ -> Toption ty)
| Tfun ft ->
let tparams = ft.ft_tparams in
let outer_subst = subst in
let subst =
List.fold_left
~f:
begin
(fun subst t -> SMap.remove (snd t.tp_name) subst)
end
~init:subst
tparams
in
let params =
List.map ft.ft_params ~f:(fun param ->
let ty = instantiate_possibly_enforced_ty subst param.fp_type in
{ param with fp_type = ty })
in
let ret = instantiate_possibly_enforced_ty subst ft.ft_ret in
let tparams =
List.map tparams ~f:(fun t ->
{
t with
tp_constraints =
List.map t.tp_constraints ~f:(fun (ck, ty) ->
(ck, instantiate subst ty));
})
in
let where_constraints =
List.map ft.ft_where_constraints ~f:(fun (ty1, ck, ty2) ->
(instantiate subst ty1, ck, instantiate outer_subst ty2))
in
Tfun
{
ft with
ft_params = params;
ft_ret = ret;
ft_tparams = tparams;
ft_where_constraints = where_constraints;
}
| Tnewtype (x, tyl, bound) ->
let tyl = List.map tyl ~f:(instantiate subst) in
let bound = instantiate subst bound in
Tnewtype (x, tyl, bound)
| Tclass (x, exact, tyl) ->
let tyl = List.map tyl ~f:(instantiate subst) in
Tclass (x, exact, tyl)
| Tshape { s_origin = _; s_unknown_value = kind; s_fields = fdm } ->
let fdm = ShapeFieldMap.map (instantiate subst) fdm in
Tshape
{
s_origin = Missing_origin;
s_unknown_value = kind;
(* TODO(shapes) instantiate s_unknown_value *)
s_fields = fdm;
}
| Tunapplied_alias _ -> failwith "this shouldn't be here"
| Tdependent (dep, ty) ->
let ty = instantiate subst ty in
Tdependent (dep, ty)
| Taccess (ty, ids) ->
let ty = instantiate subst ty in
Taccess (ty, ids)
and instantiate_possibly_enforced_ty subst et =
{ et_type = instantiate subst et.et_type; et_enforced = et.et_enforced }
end
(* TODO(T70068435)
This is a workaround for the problem that alias and newtype definitions do not spell out
the constraints they may implicitly impose on their parameters.
Consider:
class Foo<T1 as num> {...}
type Bar<T2> = Foo<T2>;
Here, T2 of Bar implicitly has the bound T2 as num. However, in the current design, we only
ever check that when expanding Bar, the argument in place of T2 satisfies all the
implicit bounds.
However, this is not feasible for using aliases and newtypes as higher-kinded types, where we
use them without expanding them.
In the long-term, we would like to be able to infer the implicit bounds and use those for
the purposes of kind-checking. For now, we just detect if there *are* implicit bounds, and
if so reject using the alias/newtype as an HK type.
*)
let check_typedef_usable_as_hk_type env use_pos typedef_name typedef_info =
let report_constraint violating_type used_class used_class_tparam_name =
let tparams_in_ty = Env.get_tparams env violating_type in
let tparams_of_typedef =
List.fold typedef_info.td_tparams ~init:SSet.empty ~f:(fun s tparam ->
SSet.add (snd tparam.tp_name) s)
in
let intersection = SSet.inter tparams_in_ty tparams_of_typedef in
if SSet.is_empty intersection then
(* Just violated constraints inside the typedef that do not involve
the type parameters of the typedef we are looking at. Nothing to report at this point *)
None
else
(* We choose an arbitrary element. If a constraint violation were to contain multiple
tparams of the typedef, we can live with only showing the user one of them. *)
let typedef_tparam_name = SSet.min_elt intersection in
let (used_class_in_def_pos, used_class_in_def_name) = used_class in
let typedef_pos = typedef_info.td_pos in
Some
Typing_error.(
Reasons_callback.always
@@ primary
@@ Primary.HKT_alias_with_implicit_constraints
{
pos = use_pos;
typedef_pos;
used_class_in_def_pos;
typedef_name;
typedef_tparam_name;
used_class_in_def_name;
used_class_tparam_name;
})
in
let check_tapply r class_sid type_args =
let decl_ty = Typing_make_type.apply r class_sid type_args in
let ((env, ty_err_opt), locl_ty) =
TUtils.localize_no_subst env ~ignore_errors:true decl_ty
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
match get_node (TUtils.get_base_type env locl_ty) with
| Tclass (cls_name, _, tyl) when not (List.is_empty tyl) ->
(match Env.get_class env (snd cls_name) with
| Some cls ->
let tc_tparams = Cls.tparams cls in
let ety_env =
{ empty_expand_env with substs = Subst.make_locl tc_tparams tyl }
in
iter2_shortest
begin
fun { tp_name = (_p, x); tp_constraints = cstrl; _ } ty ->
List.iter cstrl ~f:(fun (ck, cstr_ty) ->
let ((env, ty_err1), cstr_ty) =
TUtils.localize ~ety_env env cstr_ty
in
Option.iter
~f:(Typing_error_utils.add_typing_error ~env)
ty_err1;
let (_env, ty_err2) =
TGenConstraint.check_constraint env ck ty ~cstr_ty
@@ report_constraint ty cls_name x
in
Option.iter
ty_err2
~f:(Typing_error_utils.add_typing_error ~env))
end
tc_tparams
tyl
| _ -> ())
| _ -> ()
in
let visitor =
object
inherit [unit] Type_visitor.decl_type_visitor
method! on_tapply _ r name args = check_tapply r name args
end
in
visitor#on_type () typedef_info.td_type;
maybe visitor#on_type () typedef_info.td_as_constraint;
maybe visitor#on_type () typedef_info.td_super_constraint
(* TODO(T70068435)
This is a workaround until we support proper kind-checking of HK types that impose constraints
on their arguments.
For now, we reject using any class as a HK type that has any constraints on its type parameters.
*)
let check_class_usable_as_hk_type pos class_info =
let class_name = Cls.name class_info in
let tparams = Cls.tparams class_info in
let has_tparam_constraints =
List.exists tparams ~f:(fun tp -> not (List.is_empty tp.tp_constraints))
in
if has_tparam_constraints then
Errors.add_error
Naming_error.(
to_user_error @@ HKT_class_with_constraints_used { pos; class_name })
let report_kind_error env ~use_pos ~def_pos ~tparam_name ~expected ~actual =
let actual_kind = Simple.description_of_kind actual in
let expected_kind = Simple.description_of_kind expected in
Typing_error_utils.add_typing_error ~env
@@ Typing_error.(
primary
@@ Primary.Kind_mismatch
{
pos = use_pos;
decl_pos = def_pos;
tparam_name;
actual_kind;
expected_kind;
})
module Simple = struct
(* TODO(T70068435) Once we support constraints on higher-kinded types, this should only be used
during the localization of declaration site types, everything else should be doing full
kind-checking (including constraints) *)
let is_subkind _env ~(sub : Simple.kind) ~(sup : Simple.kind) =
let rec is_subk subk superk =
let param_compare =
List.fold2
(Simple.get_named_parameter_kinds subk)
(Simple.get_named_parameter_kinds superk)
~init:true
~f:(fun ok (_, param_sub) (_, param_sup) ->
(* Treating parameters contravariantly here. For simple subkinding, it doesn't make
a difference, though *)
ok && is_subk param_sup param_sub)
in
let open List.Or_unequal_lengths in
match param_compare with
| Unequal_lengths -> false
| Ok r -> r
in
is_subk sub sup
let rec check_targs_well_kinded
~allow_missing_targs
~in_signature
~def_pos
~use_pos
env
(tyargs : decl_ty list)
(nkinds : Simple.named_kind list) =
let exp_len = List.length nkinds in
let act_len = List.length tyargs in
let arity_mistmatch_okay = Int.equal act_len 0 && allow_missing_targs in
if Int.( <> ) exp_len act_len && not arity_mistmatch_okay then
Typing_error_utils.add_typing_error
~env
Typing_error.(
primary
@@ Primary.Type_arity_mismatch
{
pos = use_pos;
decl_pos = def_pos;
expected = exp_len;
actual = act_len;
});
let length = min exp_len act_len in
let (tyargs, nkinds) = (List.take tyargs length, List.take nkinds length) in
List.iter2_exn tyargs nkinds ~f:(check_targ_well_kinded ~in_signature env)
and check_targ_well_kinded ~in_signature env tyarg (nkind : Simple.named_kind)
=
let kind = snd nkind in
match get_node tyarg with
| Twildcard ->
let is_higher_kinded = Simple.get_arity kind > 0 in
if is_higher_kinded then (
let pos =
get_reason tyarg |> Reason.to_pos |> Pos_or_decl.unsafe_to_raw_pos
in
Errors.add_error Naming_error.(to_user_error @@ HKT_wildcard pos);
check_well_kinded ~in_signature env tyarg nkind
)
| _ -> check_well_kinded ~in_signature env tyarg nkind
and check_possibly_enforced_ty ~in_signature env enf_ty =
check_well_kinded_type
~allow_missing_targs:false
~in_signature
env
enf_ty.et_type
and check_well_kinded_type
~allow_missing_targs ~in_signature env (ty : decl_ty) =
let (r, ty_) = deref ty in
let use_pos = Reason.to_pos r |> Pos_or_decl.unsafe_to_raw_pos in
let check =
check_well_kinded_type ~allow_missing_targs:false ~in_signature env
in
let check_against_tparams def_pos tyargs tparams =
let kinds = Simple.named_kinds_of_decl_tparams tparams in
check_targs_well_kinded
~allow_missing_targs
~def_pos
~use_pos
env
tyargs
kinds
in
match ty_ with
| Tany _
| Tnonnull
| Tprim _
| Tdynamic
| Tmixed
| Twildcard
| Tthis ->
()
| Tvec_or_dict (tk, tv) ->
check tk;
check tv
| Tlike ty
| Toption ty ->
check ty
| Ttuple tyl
| Tunion tyl
| Tintersection tyl ->
List.iter tyl ~f:check
| Taccess (ty, _) ->
(* Because type constants cannot depend on type parameters,
we allow Foo::the_type even if Foo has type parameters *)
check_well_kinded_type ~allow_missing_targs:true ~in_signature env ty
| Trefinement (ty, rs) ->
check ty;
Class_refinement.iter check rs
| Tshape { s_fields = map; _ } ->
TShapeMap.iter (fun _ sft -> check sft.sft_ty) map
| Tfun ft ->
check_possibly_enforced_ty ~in_signature env ft.ft_ret;
List.iter ft.ft_params ~f:(fun p ->
check_possibly_enforced_ty ~in_signature env p.fp_type)
(* FIXME shall we inspect tparams and where_constraints *)
(* List.iter ft.ft_where_constraints (fun (ty1, _, ty2) -> check ty1; check ty2 ); *)
| Tgeneric (name, targs) -> begin
match Env.get_pos_and_kind_of_generic env name with
| Some (def_pos, gen_kind) ->
let param_nkinds =
Simple.from_full_kind gen_kind |> Simple.get_named_parameter_kinds
in
check_targs_well_kinded
~allow_missing_targs:false
~in_signature
~def_pos
~use_pos
env
targs
param_nkinds
| None -> ()
end
| Tapply ((_p, cid), argl) -> begin
match Env.get_class_or_typedef env cid with
| Some (Env.ClassResult class_info) ->
Option.iter
~f:(Typing_error_utils.add_typing_error ~env)
(Typing_visibility.check_top_level_access
~in_signature
~use_pos
~def_pos:(Cls.pos class_info)
env
(Cls.internal class_info)
(Cls.get_module class_info));
let tparams = Cls.tparams class_info in
check_against_tparams ~in_signature (Cls.pos class_info) argl tparams
| Some (Env.TypedefResult typedef) ->
Option.iter
~f:(Typing_error_utils.add_typing_error ~env)
(Typing_visibility.check_top_level_access
~in_signature
~use_pos
~def_pos:typedef.td_pos
env
typedef.td_internal
(Option.map typedef.td_module ~f:snd));
check_against_tparams
~in_signature
typedef.td_pos
argl
typedef.td_tparams
| None -> ()
end
| Tnewtype (name, tyl, _) ->
(match Env.get_typedef env name with
| Some typedef ->
Option.iter
~f:(Typing_error_utils.add_typing_error ~env)
(Typing_visibility.check_top_level_access
~in_signature
~use_pos
~def_pos:typedef.td_pos
env
typedef.td_internal
(Option.map typedef.td_module ~f:snd));
check_against_tparams
~in_signature
typedef.td_pos
tyl
typedef.td_tparams
| None -> ())
and check_well_kinded
~in_signature env (ty : decl_ty) (expected_nkind : Simple.named_kind) =
let (expected_name, expected_kind) = expected_nkind in
let r = get_reason ty in
let use_pos = Reason.to_pos r |> Pos_or_decl.unsafe_to_raw_pos in
let kind_error actual_kind env =
let (def_pos, tparam_name) = expected_name in
report_kind_error
env
~use_pos
~def_pos
~tparam_name
~actual:actual_kind
~expected:expected_kind
in
let check_against_tparams tparams =
let overall_kind = Simple.type_with_params_to_simple_kind tparams in
if not (is_subkind env ~sub:overall_kind ~sup:expected_kind) then
kind_error overall_kind env
in
if Int.( = ) (Simple.get_arity expected_kind) 0 then
check_well_kinded_type ~allow_missing_targs:false ~in_signature env ty
else
match get_node ty with
| Tapply ((_pos, name), []) -> begin
match Env.get_class_or_typedef env name with
| Some (Env.ClassResult class_info) ->
let tparams = Cls.tparams class_info in
check_class_usable_as_hk_type use_pos class_info;
check_against_tparams tparams
| Some (Env.TypedefResult typedef) ->
let tparams = typedef.td_tparams in
check_typedef_usable_as_hk_type env use_pos name typedef;
check_against_tparams tparams
| None -> ()
end
| Tgeneric (name, []) -> begin
match Env.get_pos_and_kind_of_generic env name with
| Some (_pos, gen_kind) ->
let get_kind = Simple.from_full_kind gen_kind in
if not (is_subkind env ~sub:get_kind ~sup:expected_kind) then
kind_error get_kind env
| None -> ()
end
| Tgeneric (_, targs)
| Tapply (_, targs) ->
Errors.add_error
Naming_error.(
to_user_error
@@ HKT_partial_application
{
pos = Reason.to_pos r |> Pos_or_decl.unsafe_to_raw_pos;
count = List.length targs;
})
| Tany _ -> ()
| _ -> kind_error (Simple.fully_applied_type ()) env
(* Export the version that doesn't expose allow_missing_targs *)
let check_well_kinded_type ~in_signature env (ty : decl_ty) =
check_well_kinded_type ~allow_missing_targs:false ~in_signature env ty
let check_well_kinded_hint ~in_signature env hint =
let decl_ty = Decl_hint.hint env.Typing_env_types.decl_env hint in
check_well_kinded_type ~in_signature env decl_ty
let check_well_kinded_context_hint ~in_signature env hint =
let decl_ty = Decl_hint.context_hint env.Typing_env_types.decl_env hint in
check_well_kinded_type ~in_signature env decl_ty
end |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_kinding.mli | open Typing_defs
module KindDefs = Typing_kinding_defs
module Locl_Inst : sig
val instantiate : locl_ty SMap.t -> locl_ty -> locl_ty
end
(** Simple well-kindedness checks do not take constraints into account. *)
module Simple : sig
(** Check that the given type is a well-kinded, fully-applied type. In other
words, check that the given decl_ty has kind *. Otherwise, reports errors.
Check that classes mentioned in types are accessible from the current
module, and accessible also from outside if in_signature=true. *)
val check_well_kinded_type :
in_signature:bool -> Typing_env_types.env -> decl_ty -> unit
(** Check that the given type is a well-kinded type whose kind matches the provided one.
Otherwise, reports errors.
Check that classes mentioned in types are accessible from the current
module, and accessible also from outside if in_signature=true. *)
val check_well_kinded :
in_signature:bool ->
Typing_env_types.env ->
decl_ty ->
KindDefs.Simple.named_kind ->
unit
(** Runs check_well_kinded_type after translating hint to decl type
Check that classes mentioned in hints are accessible from the current
module, and accessible also from outside if in_signature=true. *)
val check_well_kinded_hint :
in_signature:bool -> Typing_env_types.env -> Aast.hint -> unit
val check_well_kinded_context_hint :
in_signature:bool -> Typing_env_types.env -> Aast.hint -> unit
val is_subkind :
Typing_env_types.env ->
sub:KindDefs.Simple.kind ->
sup:KindDefs.Simple.kind ->
bool
end |
OCaml | hhvm/hphp/hack/src/typing/typing_kinding_defs.ml | open Hh_prelude
open Common
open Typing_defs
module TySet = Typing_set
module SN = Naming_special_names
type tparam_bounds = TySet.t
type kind = {
lower_bounds: tparam_bounds;
upper_bounds: tparam_bounds;
reified: Aast.reify_kind;
enforceable: bool;
newable: bool;
require_dynamic: bool;
parameters: named_kind list;
}
and named_kind = pos_id * kind
let dummy_name = (Pos_or_decl.none, "")
let with_dummy_name k = (dummy_name, k)
let get_arity k = List.length k.parameters
let string_of_kind (kind : kind) =
let rec stringify toplevel k =
match k.parameters with
| [] -> "Type"
| params ->
let parts = List.map params ~f:(fun (_, pk) -> stringify false pk) in
let res = String.concat ~sep:" -> " parts ^ " -> Type" in
if toplevel then
res
else
"(" ^ res ^ ")"
in
stringify true kind
let description_of_kind kind =
match kind.parameters with
| [] -> "a fully-applied type"
| params
when List.for_all params ~f:(fun (_, param) ->
Int.( = ) 0 (get_arity param)) ->
(* no higher-order arguments *)
let param_count = List.length params in
let args_desc =
if Int.( = ) 1 param_count then
"a single (fully-applied) type argument"
else
string_of_int param_count ^ "(fully-applied) type arguments"
in
"a type constructor expecting " ^ args_desc
| _ -> "a type constructor of kind " ^ string_of_kind kind
let rec remove_bounds kind =
{
kind with
lower_bounds = TySet.empty;
upper_bounds = TySet.empty;
parameters =
List.map kind.parameters ~f:(fun (n, k) -> (n, remove_bounds k));
}
module Simple = struct
type bounds_for_wildcard =
| NonLocalized of (Ast_defs.constraint_kind * decl_ty) list
| Localized of {
wc_lower: tparam_bounds;
wc_upper: tparam_bounds;
}
(* Gives us access to the non-simple kind after shadowing it below *)
type full_kind = kind
type named_full_kind = named_kind
type kind = full_kind * bounds_for_wildcard
type named_kind = pos_id * kind
(* let without_wildcard_bounds k = (k, None) *)
let string_of_kind (k, _) = string_of_kind k
let description_of_kind (k, _) = description_of_kind k
let get_arity sk = get_arity (fst sk)
let fully_applied_type
?(reified = Aast.Erased) ?(enforceable = false) ?(newable = false) () :
kind =
( {
lower_bounds = TySet.empty;
upper_bounds = TySet.empty;
reified;
enforceable;
newable;
require_dynamic = false;
parameters = [];
},
NonLocalized [] )
let to_full_kind_without_bounds kind = remove_bounds (fst kind)
let get_wilcard_bounds = snd
(* not public *)
let rec named_internal_kind_of_decl_tparam decl_tparam : named_full_kind =
let { tp_name; tp_reified = reified; tp_user_attributes; _ } =
decl_tparam
in
let enforceable =
Attributes.mem SN.UserAttributes.uaEnforceable tp_user_attributes
in
let newable =
Attributes.mem SN.UserAttributes.uaNewable tp_user_attributes
in
let (st, _) = fully_applied_type ~reified ~enforceable ~newable () in
( tp_name,
{
st with
parameters = named_internal_kinds_of_decl_tparams decl_tparam.tp_tparams;
} )
(* not public *)
and named_internal_kinds_of_decl_tparams (tparams : decl_tparam list) :
named_full_kind list =
List.map tparams ~f:named_internal_kind_of_decl_tparam
(* public *)
and named_kind_of_decl_tparam decl_tparam : named_kind =
let (name, internal_kind) =
named_internal_kind_of_decl_tparam decl_tparam
in
(name, (internal_kind, NonLocalized decl_tparam.tp_constraints))
(* public *)
let named_kinds_of_decl_tparams decl_tparams : named_kind list =
List.map decl_tparams ~f:named_kind_of_decl_tparam
let type_with_params_to_simple_kind ?reified ?enforceable ?newable tparams =
let (st, _) = fully_applied_type ?reified ?enforceable ?newable () in
( { st with parameters = named_internal_kinds_of_decl_tparams tparams },
NonLocalized [] )
let get_named_parameter_kinds (kind, _) : named_kind list =
List.map kind.parameters ~f:(fun (n, fk) -> (n, (fk, NonLocalized [])))
let from_full_kind fk =
let wildcard_bounds =
Localized { wc_lower = fk.lower_bounds; wc_upper = fk.upper_bounds }
in
(* We don't actually have to remove any of the bounds inside of the kind itself.
The fact that the bounds are still there is hidden behind this module's interface, which
denies access to them *)
(fk, wildcard_bounds)
let with_dummy_name = with_dummy_name
end |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_kinding_defs.mli | open Typing_defs
module TySet = Typing_set
type tparam_bounds = TySet.t
(** The main representation of kinds in Hack. A record r of OCaml type kind can both represent
fully-applied Hack types (e.g., of kind * ) and higher-kinded types.
If r.parameters = [], we have a fully applied type.
Otherwise, if, for example r.parameters = [(n1, r1); (n2;r2)], then
r represents a type constructor with two (curried) arguments
(i.e., r stands for kind * -> * -> * ).
Here, n1 and n2 are the names of those parameters. The names are then bound
and can be used in the involved constraints (unless the name is the wildcarf name _ ).
In the example above, this means that n1 and n2 are bound in the constraints of r1 and r2, as well as
r.upper_bounds and r.lower_bounds.
*)
type kind = {
lower_bounds: tparam_bounds;
upper_bounds: tparam_bounds;
reified: Aast.reify_kind;
(** = Reified if generic parameter is marked `reify`, = Erased otherwise *)
enforceable: bool;
(** Set if generic parameter has attribute <<__Enforceable>> *)
newable: bool; (** Set if generic parameter has attribute <<__Newable>> *)
require_dynamic: bool;
(** Set if class is marked <<__SupportDynamicType>> and
generic parameter does *not* have attribute <<__NoRequireDynamic>> *)
parameters: named_kind list;
}
and named_kind = pos_id * kind
(** This can be used in situations where we don't have a name for a type
parameter at hand. All error functions must be aware of this and not print the dummy name. *)
val dummy_name : pos_id
(** Simple kinds are used in situations where we want to check well-kindedness, but
ignore type constraints. Most importantly, this is used in Typing_phase.
In other words, simple kinds can be seen as kinds that are just built from * and ->,
whereas full kinds *additionally* also carry constraints.
For technical reasons, simple kinds must, however, carry some degree of information about
bounds: During localiazation, we may come across a type like T<_>, where the user provided
a wildcard for the type argument and T is either a (higher-kinded) type parameter or a
class/type name. In this case, we introduce a fresh type parameter in the environment, which
is used as an abstract type standing in for the type argument. We then add those constraints
to the fresh parameter that T imposes on its type parameter.
To this end, we need to know the constraints T imposes on its parameters, while only having the
kind of T at hand. To this end, simple kinds carry around constraints at the toplevel.
However, the nested kinds (i.e., the kinds of the type parameters) always have empty constraints.
Implementation note: Internally, simple and full kinds are represented similarly. Using two
different types for them is mostly a matter of hygiene, in order to prevent mixing up the two
sorts of kinds. Therefore, we keep the type of simple kinds abstract here.
*)
module Simple : sig
(* Gives us access to the non-simple kind after shadowing it below *)
type full_kind = kind
type kind
type named_kind = pos_id * kind
type bounds_for_wildcard =
| NonLocalized of (Ast_defs.constraint_kind * decl_ty) list
| Localized of {
wc_lower: tparam_bounds;
wc_upper: tparam_bounds;
}
(** Creates a general description of a kind, built from "Type" and "->". *)
val string_of_kind : kind -> string
(** Creates a human-readable representation of a kind, suitable for error messages. *)
val description_of_kind : kind -> string
val get_arity : kind -> int
val fully_applied_type :
?reified:Aast.reify_kind ->
?enforceable:bool ->
?newable:bool ->
unit ->
kind
val named_kind_of_decl_tparam : decl_tparam -> named_kind
val named_kinds_of_decl_tparams : decl_tparam list -> named_kind list
val get_wilcard_bounds : kind -> bounds_for_wildcard
val to_full_kind_without_bounds : kind -> full_kind
val type_with_params_to_simple_kind :
?reified:Aast.reify_kind ->
?enforceable:bool ->
?newable:bool ->
decl_tparam list ->
kind
val get_named_parameter_kinds : kind -> named_kind list
val from_full_kind : full_kind -> kind
val with_dummy_name : kind -> named_kind
end |
OCaml | hhvm/hphp/hack/src/typing/typing_lenv.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module Env = Typing_env
open Typing_env_types
module C = Typing_continuations
module LEnvC = Typing_per_cont_env
module LEnvOps = Typing_per_cont_ops
module Union = Typing_union
(*****************************************************************************)
(* Module dealing with local environments. *)
(*****************************************************************************)
let get_all_locals env = env.lenv.per_cont_env
(*****************************************************************************)
(* Functions dealing with old style local environment *)
(*****************************************************************************)
let union
env
~join_pos
Typing_local_types.
{
ty = ty1;
defined = defined1;
bound_ty = bound_ty1;
pos = pos1;
eid = eid1;
}
Typing_local_types.
{
ty = ty2;
defined = defined2;
bound_ty = bound_ty2;
pos = pos2;
eid = eid2;
} =
let (env, ty) = Union.union ~approx_cancel_neg:true env ty1 ty2 in
let (env, bound_ty) =
match (bound_ty1, bound_ty2) with
| (None, None) -> (env, None)
| (Some ty, None)
| (None, Some ty) ->
(env, Some ty)
| (Some ty1, Some ty2) ->
let (env, ty) =
Typing_intersection.intersect
~r:(Typing_defs_core.get_reason ty1)
env
ty1
ty2
in
(env, Some ty)
in
let pos =
if phys_equal ty ty1 || Pos.equal Pos.none pos2 then
pos1
else if phys_equal ty ty2 || Pos.equal Pos.none pos1 then
pos2
else
Pos.none
in
let eid =
if Ident.equal eid1 eid2 then
eid1
else
Ident.tmp ()
in
match bound_ty with
| None ->
Typing_local_types.
(env, { ty; defined = defined1 && defined2; bound_ty; pos; eid })
| Some bound_ty ->
let (env, err_opt) =
Typing_subtype.sub_type
env
ty
bound_ty
(Some (Typing_error.Reasons_callback.unify_error_at join_pos))
in
let ty =
match err_opt with
| None -> ty
| Some err ->
Typing_error_utils.add_typing_error ~env err;
(* If the new type or bound violates the old one, then we want to
check the remainder of the code with the type of the variable
set to the bound *)
bound_ty
in
Typing_local_types.
( env,
{
ty;
defined = defined1 && defined2;
bound_ty = Some bound_ty;
pos;
eid;
} )
let get_cont_option env cont =
let local_types = get_all_locals env in
LEnvC.get_cont_option cont local_types
let drop_cont env cont =
let local_types = get_all_locals env in
let local_types = LEnvC.drop_cont cont local_types in
Env.env_with_locals env local_types
let drop_conts env conts =
let local_types = get_all_locals env in
let local_types = LEnvC.drop_conts conts local_types in
Env.env_with_locals env local_types
let replace_cont env cont ctxopt =
let local_types = get_all_locals env in
let local_types = LEnvC.replace_cont cont ctxopt local_types in
Env.env_with_locals env local_types
let restore_conts_from env fromlocals conts =
let local_types = get_all_locals env in
let local_types =
LEnvOps.restore_conts_from local_types ~from:fromlocals conts
in
Env.env_with_locals env local_types
let restore_and_merge_conts_from env ~join_pos fromlocals conts =
let local_types = get_all_locals env in
let (env, local_types) =
LEnvOps.restore_and_merge_conts_from
env
(union ~join_pos)
local_types
~from:fromlocals
conts
in
Env.env_with_locals env local_types
(* Merge all continuations in the provided list and update the 'next'
* continuation with the result. *)
let update_next_from_conts env ~join_pos cont_list =
let local_types = get_all_locals env in
let (env, local_types) =
LEnvOps.update_next_from_conts env (union ~join_pos) local_types cont_list
in
Env.env_with_locals env local_types
(* After this call, the provided continuation will be the union of itself and
* the next continuation *)
let save_and_merge_next_in_cont env ~join_pos cont =
let local_types = get_all_locals env in
let (env, local_types) =
LEnvOps.save_and_merge_next_in_cont env (union ~join_pos) local_types cont
in
Env.env_with_locals env local_types
let move_and_merge_next_in_cont env ~join_pos cont =
let local_types = get_all_locals env in
let (env, local_types) =
LEnvOps.move_and_merge_next_in_cont env (union ~join_pos) local_types cont
in
Env.env_with_locals env local_types
let union_contextopts ~join_pos = LEnvOps.union_opts (union ~join_pos)
let union_by_cont env ~join_pos lenv1 lenv2 =
let locals1 = lenv1.per_cont_env in
let locals2 = lenv2.per_cont_env in
let (env, locals) =
LEnvOps.union_by_cont env (union ~join_pos) locals1 locals2
in
Env.env_with_locals env locals
let join_fake lenv1 lenv2 =
let nextctxopt1 = LEnvC.get_cont_option C.Next lenv1.per_cont_env in
let nextctxopt2 = LEnvC.get_cont_option C.Next lenv2.per_cont_env in
match (nextctxopt1, nextctxopt2) with
| (Some c1, Some c2) ->
Typing_fake_members.join c1.LEnvC.fake_members c2.LEnvC.fake_members
| (None, None) -> Typing_fake_members.empty
| (Some c1, None) -> c1.LEnvC.fake_members
| (None, Some c2) -> c2.LEnvC.fake_members
let union_lenvs_ env ~join_pos parent_lenv lenv1 lenv2 =
let fake_members = join_fake lenv1 lenv2 in
let local_using_vars = parent_lenv.local_using_vars in
let env = union_by_cont env ~join_pos lenv1 lenv2 in
let lenv = { env.lenv with local_using_vars } in
let per_cont_env =
LEnvC.update_cont_entry C.Next lenv.per_cont_env (fun entry ->
LEnvC.{ entry with fake_members })
in
let lenv = { lenv with per_cont_env } in
({ env with lenv }, lenv)
(* Used when we want the new local environment to be the union
* of 2 local environments. Typical use case is an if statement.
* $x = 0;
* if(...) { $x = ''; } else { $x = 'foo'; }
* We want $x to be a string past this point.
* We check that the locals are defined in both branches
* when that is the case, their type becomes the union (least upper bound)
* of the types it had in each branch.
*)
let union_lenvs env ~join_pos parent_lenv lenv1 lenv2 =
fst @@ union_lenvs_ env ~join_pos parent_lenv lenv1 lenv2
let rec union_lenv_list env ~join_pos parent_lenv = function
| []
| [_] ->
env
| lenv1 :: lenv2 :: lenvlist ->
let (env, lenv) = union_lenvs_ env ~join_pos parent_lenv lenv1 lenv2 in
union_lenv_list env ~join_pos parent_lenv (lenv :: lenvlist)
let stash_and_do env conts f =
let parent_locals = get_all_locals env in
let env = drop_conts env conts in
let (env, res) = f env in
let env = restore_conts_from env parent_locals conts in
(env, res)
let env_with_empty_fakes env =
let per_cont_env =
LEnvC.update_cont_entry C.Next env.lenv.per_cont_env (fun entry ->
LEnvC.{ entry with fake_members = Typing_fake_members.empty })
in
{ env with lenv = { env.lenv with per_cont_env } }
let has_next env =
match get_cont_option env C.Next with
| None -> false
| Some _ -> true |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_lenv.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Typing_env_types
(*****************************************************************************)
(* Functions dealing with old style local environment *)
(*****************************************************************************)
val get_all_locals : env -> Typing_per_cont_env.t
val get_cont_option :
env -> Typing_continuations.t -> Typing_per_cont_env.per_cont_entry option
val drop_cont : env -> Typing_continuations.t -> env
val drop_conts : env -> Typing_continuations.t list -> env
val replace_cont :
env ->
Typing_continuations.t ->
Typing_per_cont_env.per_cont_entry option ->
env
val restore_conts_from :
env -> Typing_per_cont_env.t -> Typing_continuations.t list -> env
val restore_and_merge_conts_from :
env ->
join_pos:Pos.t ->
Typing_per_cont_env.t ->
Typing_continuations.t list ->
env
val update_next_from_conts :
env -> join_pos:Pos.t -> Typing_continuations.t list -> env
val save_and_merge_next_in_cont :
env -> join_pos:Pos.t -> Typing_continuations.t -> env
val move_and_merge_next_in_cont :
env -> join_pos:Pos.t -> Typing_continuations.t -> env
val union :
env ->
join_pos:Pos.t ->
Typing_local_types.local ->
Typing_local_types.local ->
env * Typing_local_types.local
val union_by_cont : env -> join_pos:Pos.t -> local_env -> local_env -> env
val union_contextopts :
join_pos:Pos.t ->
env ->
Typing_per_cont_env.per_cont_entry option ->
Typing_per_cont_env.per_cont_entry option ->
env * Typing_per_cont_env.per_cont_entry option
val union_lenvs :
env -> join_pos:Pos.t -> local_env -> local_env -> local_env -> env
val union_lenv_list :
env -> join_pos:Pos.t -> local_env -> local_env list -> env
(* When entering control flow structures, some
* preexisting continuations must be stashed away and then restored
* on exiting those control flow structures.
*
* For example, on entering a loop, preexisting 'break' and 'continue'
* continuations from any enclosing loops must be stashed away so as not to
* interfere with them. *)
val stash_and_do :
env -> Typing_continuations.t list -> (env -> env * 'a) -> env * 'a
val env_with_empty_fakes : env -> env
val has_next : env -> bool |
OCaml | hhvm/hphp/hack/src/typing/typing_local_ops.ml | (*
* Copyright (c) 2020, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Typing_defs_core
open Typing_env_types
module Env = Typing_env
module SN = Naming_special_names
let check_local_capability (mk_required : env -> env * locl_ty) mk_err_opt env =
(* gate the check behavior on coeffects TC option *)
let tcopt = Env.get_tcopt env in
let should_skip_check =
(not @@ TypecheckerOptions.local_coeffects tcopt)
|| TypecheckerOptions.enable_sound_dynamic tcopt
&& Tast.is_under_dynamic_assumptions env.checked
(* When inside an expression tree, expressions are virtualized and
thus never executed. Safe to skip coeffect checks in this case. *)
|| Env.is_in_expr_tree env
in
if not should_skip_check then (
let available = Env.get_local env Typing_coeffects.local_capability_id in
let (env, required) = mk_required env in
let err_opt = mk_err_opt available required in
let (env, ty_err_opt) =
Typing_subtype.sub_type_or_fail
env
available.Typing_local_types.ty
required
err_opt
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
env
) else
env
let enforce_local_capability
?((* Run-time enforced ops must have the default as it's unfixmeable *)
err_code = Error_codes.Typing.OpCoeffects)
?suggestion
(mk_required : env -> env * locl_ty)
(op : string)
(op_pos : Pos.t)
env =
check_local_capability
mk_required
(fun available required ->
Some
Typing_error.(
coeffect
@@ Primary.Coeffect.Op_coeffect_error
{
pos = op_pos;
op_name = op;
locally_available =
Typing_coeffects.pretty env available.Typing_local_types.ty;
available_pos =
Typing_defs.get_pos available.Typing_local_types.ty;
required = Typing_coeffects.pretty env required;
err_code;
suggestion;
}))
env
module Capabilities = struct
module Reason = Typing_reason
include SN.Capabilities
let mk special_name env =
let r = Reason.Rnone in
let ((env, ty_err_opt), res) =
Typing_make_type.apply r (Reason.to_pos r, special_name) []
|> Typing_phase.localize_no_subst ~ignore_errors:true env
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
(env, res)
end
let enforce_memoize_object pos env =
(* Allow zoned_shallow/local policies to memoize objects,
since those will convert to PolicyShardedMemoize after conversion to zoned *)
(* We use ImplicitPolicy instead of ImplicitPolicyShallow just to not error
for zoned, since memoizing a zoned function already has a different error
associated with it. *)
let (env, zoned) = Capabilities.(mk implicitPolicy) env in
let (env, access_globals) = Capabilities.(mk accessGlobals) env in
let mk_zoned_or_access_globals env =
let r = Reason.Rnone in
(env, Typing_make_type.union r [zoned; access_globals])
in
check_local_capability
mk_zoned_or_access_globals
(fun available _required ->
Some
Typing_error.(
coeffect
@@ Primary.Coeffect.Op_coeffect_error
{
pos;
op_name = "Memoizing object parameters";
locally_available =
Typing_coeffects.pretty env available.Typing_local_types.ty;
available_pos =
Typing_defs.get_pos available.Typing_local_types.ty;
(* Use access globals in error message *)
required = Typing_coeffects.pretty env access_globals;
(* Temporarily FIXMEable error for memoizing objects. Once ~65 current cases are removed
we can change this *)
err_code = Error_codes.Typing.MemoizeObjectWithoutGlobals;
suggestion = None;
}))
env
let enforce_io =
enforce_local_capability Capabilities.(mk io) "`echo` or `print` builtin"
let enforce_enum_class_variant =
enforce_local_capability
Capabilities.(mk writeProperty)
"Accessing an enum class constant"
(* basic local mutability checks *)
let rec is_byval_collection_or_string_or_any_type env ty =
let check ty =
let open Aast in
let (env, ty) = Env.expand_type env ty in
match get_node ty with
| Toption inner -> is_byval_collection_or_string_or_any_type env inner
| Tclass ((_, x), _, _) ->
String.equal x SN.Collections.cVec
|| String.equal x SN.Collections.cDict
|| String.equal x SN.Collections.cKeyset
| Tvec_or_dict _
| Ttuple _
| Tshape _
| Tprim Tstring
| Tdynamic
| Tany _ ->
true
| Tunion tyl ->
List.for_all tyl ~f:(is_byval_collection_or_string_or_any_type env)
| Tintersection tyl ->
List.exists tyl ~f:(is_byval_collection_or_string_or_any_type env)
| Tgeneric _
| Tnewtype _
| Tdependent _ ->
(* FIXME we should probably look at the upper bounds here. *)
false
| Tnonnull
| Tprim _
| Tfun _
| Tvar _
| Taccess _
| Tneg _ ->
false
| Tunapplied_alias _ ->
Typing_defs.error_Tunapplied_alias_in_illegal_context ()
in
let (_, tl) =
Typing_utils.get_concrete_supertypes ~abstract_enum:true env ty
in
List.for_all tl ~f:check
let mutating_this_in_ctor env (_, _, e) : bool =
match e with
| Aast.This when Env.fun_is_constructor env -> true
| _ -> false
let rec is_valid_mutable_subscript_expression_target env v =
let open Aast in
match v with
| (_, _, Hole (e, _, _, _)) ->
is_valid_mutable_subscript_expression_target env e
| (ty, _, Lvar _) -> is_byval_collection_or_string_or_any_type env ty
| (ty, _, Array_get (e, _)) ->
is_byval_collection_or_string_or_any_type env ty
&& is_valid_mutable_subscript_expression_target env e
| (ty, _, Obj_get (e, _, _, _)) ->
is_byval_collection_or_string_or_any_type env ty
&& (is_valid_mutable_subscript_expression_target env e
|| mutating_this_in_ctor env e)
| (_, _, ReadonlyExpr e) -> is_valid_mutable_subscript_expression_target env e
| _ -> false
let is_valid_append_target _env ty =
(* TODO(coeffects) move this to typing.ml and completely redesign
the line below (as it was in Tast_check) doesn't do the right thing *)
(* let (_env, ty) = Env.expand_type _env ty in *)
match get_node ty with
| Tclass ((_, n), _, []) ->
String.( <> ) n SN.Collections.cVector
&& String.( <> ) n SN.Collections.cSet
&& String.( <> ) n SN.Collections.cMap
| Tclass ((_, n), _, [_]) ->
String.( <> ) n SN.Collections.cVector
&& String.( <> ) n SN.Collections.cSet
| Tclass ((_, n), _, [_; _]) -> String.( <> ) n SN.Collections.cMap
| _ -> true
let rec check_assignment_or_unset_target
~is_assignment
?append_pos_opt
env
te1
capability_available
capability_required =
let fail ?suggestion op_name pos =
Some
Typing_error.(
coeffect
@@ Primary.Coeffect.Op_coeffect_error
{
pos;
op_name;
suggestion;
locally_available =
Typing_coeffects.pretty
env
capability_available.Typing_local_types.ty;
available_pos =
Typing_defs.get_pos capability_available.Typing_local_types.ty;
required = Typing_coeffects.pretty env capability_required;
err_code = Error_codes.Typing.OpCoeffects;
})
in
let (_, p, expr_) = te1 in
let open Aast in
match expr_ with
| Hole (e, _, _, _) ->
check_assignment_or_unset_target
~is_assignment
?append_pos_opt
env
e
capability_available
capability_required
| Obj_get (e1, _, _, _) when mutating_this_in_ctor env e1 -> None
| Array_get ((ty1, _, _), i)
when is_assignment && not (is_valid_append_target env ty1) ->
let is_append = Option.is_none i in
let msg_prefix =
if is_append then
"Appending to a Hack Collection object"
else
"Assigning to an element of a Hack Collection object via `[]`"
in
fail msg_prefix (Option.value append_pos_opt ~default:p)
| Array_get (e1, _) when is_valid_mutable_subscript_expression_target env e1
->
None
(* we already report errors about statics in rx context, no need to do it twice *)
| Class_get _ -> None
| Obj_get _
| Array_get _ ->
if is_assignment then
fail
("This object's property is being mutated (used as an lvalue)"
^ "\nSetting non-mutable object properties")
p
else
fail "Non-mutable argument for `unset`" p
| _ -> None
(* END logic from Typed AST check in basic_reactivity_check *)
let rec check_assignment env (x, append_pos_opt, te_) =
let open Ast_defs in
match te_ with
| Aast.Hole ((_, _, e), _, _, _) -> check_assignment env (x, append_pos_opt, e)
| Aast.Unop ((Uincr | Udecr | Upincr | Updecr), te1)
| Aast.(Binop { bop = Eq _; lhs = te1; _ }) ->
check_local_capability
Capabilities.(mk writeProperty)
(check_assignment_or_unset_target
~is_assignment:true
~append_pos_opt
env
te1)
env
| _ -> env
let check_unset_target env (tel : (Ast_defs.param_kind * Tast.expr) list) =
List.fold ~init:env tel ~f:(fun env (_, te) ->
check_local_capability
Capabilities.(mk writeProperty)
(fun available required ->
check_assignment_or_unset_target
~is_assignment:false
env
te
available
required)
env) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_local_ops.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 check_assignment : Typing_env_types.env -> Tast.expr -> Typing_env_types.env
val enforce_io : Pos.t -> Typing_env_types.env -> Typing_env_types.env
val enforce_memoize_object :
Pos.t -> Typing_env_types.env -> Typing_env_types.env
val enforce_enum_class_variant :
Pos.t -> Typing_env_types.env -> Typing_env_types.env
val check_unset_target :
Typing_env_types.env ->
(Ast_defs.param_kind * Tast.expr) list ->
Typing_env_types.env |
OCaml | hhvm/hphp/hack/src/typing/typing_local_types.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Typing_defs
(* Along with a type, each local variable has a expression id associated with
* it. This is used when generating expression dependent types for the 'this'
* type. The idea is that if two local variables have the same expression_id
* then they refer to the same late bound type, and thus have compatible
* 'this' types.
*)
type expression_id = Ident.t [@@deriving eq, show]
type local = {
(* The type of the local *)
ty: locl_ty;
(* True if the variable is definitely defined. False if it might not be.
* This will happen when there is a typed local declared along some control
* paths but not others. In this case, using the variable is still an
* error, but any assigning to it should still follow the bound. *)
defined: bool;
(* The bound on the variable if it is a typed local. *)
bound_ty: locl_ty option;
(* The position at which the variable got its type. *)
pos: Pos.t;
eid: expression_id;
}
[@@deriving show]
type t = local Local_id.Map.t
let empty = Local_id.Map.empty
let add_to_local_types id local m = Local_id.Map.add ?combine:None id local m |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_local_types.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type expression_id = Ident.t [@@deriving eq, show]
type local = {
ty: Typing_defs.locl_ty;
defined: bool;
bound_ty: Typing_defs.locl_ty option;
pos: Pos.t;
eid: expression_id;
}
[@@deriving show]
type t = local Local_id.Map.t
val empty : t
val add_to_local_types :
Local_id.t -> 'a -> 'a Local_id.Map.t -> 'a Local_id.Map.t |
OCaml | hhvm/hphp/hack/src/typing/typing_log.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Typing_defs
open Typing_env_types
module Inf = Typing_inference_env
module Pr = Typing_print
module TPEnv = Type_parameter_env
module TySet = Typing_set
open Tty
open Typing_log_value
(*****************************************************************************)
(* Logging type inference environment *)
(*****************************************************************************)
(* Eventual input to Tty.cprint *)
let out_channel = ref stdout
let logBuffer = ref []
let indentLevel = ref 0
let accumulatedLength = ref 0
let lnewline () =
match !logBuffer with
| [] -> ()
| _ ->
cprint
~out_channel:!out_channel
~color_mode:Color_Auto
((Normal White, String.make (2 * !indentLevel) ' ')
:: List.rev ((Normal White, "\n") :: !logBuffer));
Out_channel.flush !out_channel;
accumulatedLength := 0;
logBuffer := []
let lprintf c =
Printf.ksprintf (fun s ->
let len = String.length s in
logBuffer := (c, s) :: !logBuffer;
if !accumulatedLength + len > 80 then
lnewline ()
else
accumulatedLength := !accumulatedLength + len)
let lnewline_open () =
lnewline ();
indentLevel := !indentLevel + 1
let lnewline_close () =
lnewline ();
indentLevel := !indentLevel - 1
let indentEnv ?(color = Normal Yellow) message f =
lnewline ();
lprintf color "%s" message;
lnewline_open ();
f ();
lnewline_close ()
(* Most recent environment. We only display diffs *)
let lastenv =
ref
(Typing_env_types.empty
(Provider_context.empty_for_debugging
~popt:ParserOptions.default
~tcopt:TypecheckerOptions.default
~deps_mode:(Typing_deps_mode.InMemoryMode None))
Relative_path.default
~droot:None)
let iterations : int Pos.Map.t ref = ref Pos.Map.empty
let iterations_decl : int Pos_or_decl.Map.t ref = ref Pos_or_decl.Map.empty
(* Universal representation of a delta between values
*)
type delta =
| Updated of value (* For bools, atoms, lists, replaced sets, replaced maps *)
| Unchanged
(* Set has had some elements removed, some added *)
| Set_delta of {
added: SSet.t;
removed: SSet.t;
}
(* Map has some new keys, some removed keys, and deltas to existing keys.
* All other keys assumed to be unchanged.
*)
| Map_delta of {
added: value SMap.t;
removed: SSet.t;
changed: delta SMap.t;
}
let rec compute_value_delta (oldval : value) (newval : value) : delta =
match (oldval, newval) with
| (Bool b1, Bool b2) ->
if Bool.equal b1 b2 then
Unchanged
else
Updated newval
| (Atom s1, Atom s2) ->
if String.equal s1 s2 then
Unchanged
else
Updated newval
| (Type t1, Type t2) ->
if equal_internal_type t1 t2 then
Unchanged
else
Updated newval
| (SubtypeProp p1, SubtypeProp p2) ->
if Typing_logic.equal_subtype_prop p1 p2 then
Unchanged
else
Updated newval
| (Set s1, Set s2) ->
let added = SSet.diff s2 s1 in
let removed = SSet.diff s1 s2 in
if SSet.is_empty added && SSet.is_empty removed then
Unchanged
else
Set_delta { added; removed }
| (List l1, List l2) ->
if List.equal equal_value l1 l2 then
Unchanged
else
Updated newval
| (Map m1, Map m2) ->
let removed =
SMap.fold
(fun i _ s ->
match SMap.find_opt i m2 with
| None -> SSet.add i s
| Some _ -> s)
m1
SSet.empty
in
let added =
SMap.fold
(fun i v m ->
match SMap.find_opt i m1 with
| None -> SMap.add i v m
| _ -> m)
m2
SMap.empty
in
let changed =
SMap.fold
(fun i oldx m ->
match SMap.find_opt i m2 with
| None -> m
| Some newx ->
(match compute_value_delta oldx newx with
| Unchanged -> m
| d -> SMap.add i d m))
m1
SMap.empty
in
if SSet.is_empty removed && SMap.is_empty added && SMap.is_empty changed
then
Unchanged
else
Map_delta { removed; added; changed }
(* Type has changed! *)
| (_, _) -> Updated newval
let is_leaf_value v =
match v with
| Atom _
| Bool _
| List _ ->
true
| Map m when SMap.is_empty m -> true
| Set _ -> true
| _ -> false
let log_key key = lprintf (Normal Yellow) "%s" key
let log_sset s =
match SSet.elements s with
| [] -> lprintf (Normal Green) "{}"
| [s] -> lprintf (Normal Green) "{%s}" s
| s :: ss ->
lprintf (Normal Green) "{";
lprintf (Normal Green) "%s" s;
List.iter ss ~f:(fun s -> lprintf (Normal Green) ",%s" s);
lprintf (Normal Green) "}"
let rec log_value env value =
match value with
| Atom s -> lprintf (Normal Green) "%s" s
| Bool b ->
lprintf
(Normal Green)
"%s"
(if b then
"true"
else
"false")
| List [] -> lprintf (Normal Green) "[]"
| List (v :: vs) ->
lprintf (Normal Green) "[";
log_value env v;
List.iter vs ~f:(fun v ->
lprintf (Normal Green) ",";
log_value env v);
lprintf (Normal Green) "]"
| Map m ->
if SMap.is_empty m then
lprintf (Normal Green) "{}"
else
SMap.iter (log_key_value env "") m
| Set s -> log_sset s
| Type ty -> Pr.debug_i env ty |> lprintf (Normal Green) "%s"
| SubtypeProp prop -> Pr.subtype_prop env prop |> lprintf (Normal Green) "%s"
and log_key_value env prefix k v =
if is_leaf_value v then (
lprintf (Normal Green) "%s" prefix;
log_key k;
lprintf (Normal Yellow) " ";
log_value env v;
lnewline ()
) else (
lnewline ();
lprintf (Normal Green) "%s" prefix;
log_key k;
lnewline_open ();
log_value env v;
lnewline_close ()
)
let is_leaf_delta d =
match d with
| Updated v -> is_leaf_value v
(* | Added d | Removed d | Updated d -> is_leaf_delta d*)
| _ -> false
let rec log_delta env delta =
match delta with
| Updated v -> log_value env v
| Unchanged -> ()
| Set_delta { added; removed } ->
if not (SSet.is_empty added) then (
lprintf (Bold Green) " += ";
log_sset added
);
if not (SSet.is_empty removed) then (
lprintf (Bold Red) " -= ";
log_sset removed
)
| Map_delta { added; removed; changed } ->
SSet.iter
(fun k ->
lprintf (Bold Red) "-";
log_key k;
lnewline ())
removed;
SMap.iter (log_key_value env "+") added;
SMap.iter (log_key_delta env) changed
and log_key_delta env k d =
if is_leaf_delta d then (
log_key k;
lprintf (Normal Yellow) " ";
log_delta env d;
lnewline ()
) else (
lnewline ();
log_key k;
lprintf (Normal Yellow) " ";
lnewline_open ();
log_delta env d;
lnewline_close ()
)
let type_as_value env ty = Atom (Pr.debug env ty)
let decl_type_as_value env ty = Atom (Pr.debug_decl env ty)
let possibly_enforced_type_as_value env et =
Atom
((match et.et_enforced with
| Enforced -> "enforced "
| Unenforced -> "")
^ Pr.debug env et.et_type)
let return_info_as_value env return_info =
let Typing_env_return_info.{ return_type; return_disposable } = return_info in
make_map
[
("return_type", possibly_enforced_type_as_value env return_type);
("return_disposable", Bool return_disposable);
]
let local_id_map_as_value f m =
Map
(Local_id.Map.fold
(fun id x m -> SMap.add (local_id_as_string id) (f x) m)
m
SMap.empty)
let reify_kind_as_value k =
string_as_value
(match k with
| Aast.Erased -> "erased"
| Aast.SoftReified -> "soft_reified"
| Aast.Reified -> "reified")
let tyset_as_value env tys =
Set (TySet.fold (fun t s -> SSet.add (Pr.debug env t) s) tys SSet.empty)
let rec tparam_info_as_value env tpinfo =
let Typing_kinding_defs.
{
lower_bounds;
upper_bounds;
reified;
enforceable;
newable;
require_dynamic;
parameters;
} =
tpinfo
in
make_map
[
("lower_bounds", tyset_as_value env lower_bounds);
("upper_bounds", tyset_as_value env upper_bounds);
("reified", reify_kind_as_value reified);
("enforceable", bool_as_value enforceable);
("newable", bool_as_value newable);
("require_dynamic", bool_as_value require_dynamic);
("parameters", named_tparam_info_list_as_value env parameters);
]
and named_tparam_info_list_as_value env parameters =
let param_values =
List.map parameters ~f:(fun (name, param) ->
list_as_value
[string_as_value (snd name); tparam_info_as_value env param])
in
list_as_value param_values
let tpenv_as_value env tpenv =
make_map
[
( "tparams",
Map
(TPEnv.fold
(fun name tpinfo m ->
SMap.add name (tparam_info_as_value env tpinfo) m)
tpenv
SMap.empty) );
("consistent", bool_as_value (TPEnv.is_consistent tpenv));
]
let per_cont_entry_as_value env f entry =
make_map
[
( "local_types",
local_id_map_as_value f entry.Typing_per_cont_env.local_types );
( "fake_members",
Typing_fake_members.as_log_value entry.Typing_per_cont_env.fake_members
);
("tpenv", tpenv_as_value env entry.Typing_per_cont_env.tpenv);
]
let continuations_map_as_value f m =
Map
(Typing_continuations.Map.fold
(fun k x m -> SMap.add (Typing_continuations.to_string k) (f x) m)
m
SMap.empty)
let local_as_value
env Typing_local_types.{ ty; defined; bound_ty; pos = _; eid } =
let bound =
match bound_ty with
| None -> ""
| Some ty ->
"(let"
^ (if defined then
""
else
" (undefined)")
^ " : "
^ Pr.debug env ty
^ ")"
in
Atom (Printf.sprintf "%s %s [expr_id=%d]" (Pr.debug env ty) bound eid)
let per_cont_env_as_value env per_cont_env =
continuations_map_as_value
(per_cont_entry_as_value env (local_as_value env))
per_cont_env
let log_position p ?function_name f =
let n =
match Pos.Map.find_opt p !iterations with
| None ->
iterations := Pos.Map.add p 1 !iterations;
1
| Some n ->
iterations := Pos.Map.add p (n + 1) !iterations;
n + 1
in
(* If we've hit this many iterations then something must have gone wrong
* so let's not bother spewing to the log *)
if n > 10000 then
()
else
indentEnv
~color:(Bold Yellow)
((Pos.string @@ Pos.to_absolute p)
^ (if Int.equal n 1 then
""
else
"[" ^ string_of_int n ^ "]")
^
match function_name with
| None -> ""
| Some n -> " {" ^ n ^ "}")
f
let log_pos_or_decl p ?function_name f =
let n =
match Pos_or_decl.Map.find_opt p !iterations_decl with
| None ->
iterations_decl := Pos_or_decl.Map.add p 1 !iterations_decl;
1
| Some n ->
iterations_decl := Pos_or_decl.Map.add p (n + 1) !iterations_decl;
n + 1
in
(* If we've hit this many iterations then something must have gone wrong
* so let's not bother spewing to the log *)
if n > 10000 then
()
else
indentEnv
~color:(Bold Yellow)
(Pos_or_decl.show_as_absolute_file_line_characters p
^ (if Int.equal n 1 then
""
else
"[" ^ string_of_int n ^ "]")
^
match function_name with
| None -> ""
| Some n -> " {" ^ n ^ "}")
f
let log_with_level env key ~level log_f =
if Typing_env_types.get_log_level env key >= level then
log_f ()
else
()
let log_subtype_prop env message prop =
lprintf (Tty.Bold Tty.Green) "%s: " message;
lprintf (Tty.Normal Tty.Green) "%s" (Pr.subtype_prop env prop);
lnewline ()
let fun_kind_to_string k =
match k with
| Ast_defs.FSync -> "normal"
| Ast_defs.FAsync -> "async"
| Ast_defs.FGenerator -> "generator"
| Ast_defs.FAsyncGenerator -> "async generator"
let val_kind_to_string k =
match k with
| Other -> "other"
| Lval -> "lval"
| LvalSubexpr -> "lval subexpression"
let lenv_as_value env lenv =
let { per_cont_env; local_using_vars } = lenv in
make_map
[
("per_cont_env", per_cont_env_as_value env per_cont_env);
("local_using_vars", local_id_set_as_value local_using_vars);
]
let param_as_value env (ty, _pos, ty_opt) =
let ty_str = Pr.debug env ty in
match ty_opt with
| None -> Atom ty_str
| Some ty2 ->
let ty2_str = Pr.debug env ty2 in
Atom (Printf.sprintf "%s inout %s" ty_str ty2_str)
let genv_as_value env genv =
let {
tcopt = _;
callable_pos;
readonly;
return;
params;
condition_types;
parent;
self;
static;
val_kind;
fun_kind;
fun_is_ctor;
file = _;
current_module;
this_internal;
this_support_dynamic_type;
no_auto_likes;
} =
genv
in
make_map
([
("readonly", bool_as_value readonly);
("return", return_info_as_value env return);
("callable_pos", pos_as_value callable_pos);
("params", local_id_map_as_value (param_as_value env) params);
( "condition_types",
smap_as_value (decl_type_as_value env) condition_types );
("static", bool_as_value static);
("val_kind", string_as_value (val_kind_to_string val_kind));
("fun_kind", string_as_value (fun_kind_to_string fun_kind));
("fun_is_ctor", bool_as_value fun_is_ctor);
("this_internal", bool_as_value this_internal);
("this_support_dynamic_type", bool_as_value this_support_dynamic_type);
("no_auto_likes", bool_as_value no_auto_likes);
]
@ (match current_module with
| Some current_module ->
[("current_module", string_as_value @@ Ast_defs.show_id current_module)]
| None -> [])
@ (match parent with
| Some (parent_id, parent_ty) ->
[
("parent_id", string_as_value parent_id);
("parent_ty", decl_type_as_value env parent_ty);
]
| None -> [])
@
match self with
| Some (self_id, self_ty) ->
[
("self_id", string_as_value self_id);
("self_ty", type_as_value env self_ty);
]
| None -> [])
let fun_tast_info_as_map = function
| None -> make_map []
| Some r ->
let open Tast in
let { has_implicit_return; has_readonly } = r in
make_map
[
("has_implicit_return", bool_as_value has_implicit_return);
("has_readonly", bool_as_value has_readonly);
]
let checked_as_value check_status = Atom (Tast.show_check_status check_status)
let in_expr_tree_as_value env = function
| None -> bool_as_value false
| Some { dsl = hint; outer_locals } ->
make_map
[
("dsl", Atom (Aast_defs.show_hint hint));
("outer_locals", local_id_map_as_value (local_as_value env) outer_locals);
]
let env_as_value env =
let {
fresh_typarams;
lenv;
genv;
decl_env = _;
tracing_info = _;
in_loop;
in_try;
in_expr_tree;
inside_constructor;
checked;
tpenv;
log_levels = _;
allow_wildcards;
inference_env;
big_envs = _;
fun_tast_info;
loaded_packages = _;
} =
env
in
make_map
[
("fresh_typarams", Set fresh_typarams);
("lenv", lenv_as_value env lenv);
("genv", genv_as_value env genv);
("in_loop", bool_as_value in_loop);
("in_try", bool_as_value in_try);
("in_expr_tree", in_expr_tree_as_value env in_expr_tree);
("inside_constructor", bool_as_value inside_constructor);
("checked", checked_as_value checked);
("tpenv", tpenv_as_value env tpenv);
("allow_wildcards", bool_as_value allow_wildcards);
("inference_env", Inf.Log.inference_env_as_value inference_env);
("fun_tast_info", fun_tast_info_as_map fun_tast_info);
]
let log_env_diff p ?function_name old_env new_env =
let value = env_as_value new_env in
let old_value = env_as_value old_env in
let d = compute_value_delta old_value value in
match d with
| Unchanged -> ()
| _ -> log_position p ?function_name (fun () -> log_delta new_env d)
(* Log the environment: local_types, subst, tenv and tpenv *)
let hh_show_env ?function_name p env =
log_with_level env "show" ~level:0 @@ fun () ->
let old_env = !lastenv in
lastenv := env;
log_env_diff ?function_name p old_env env
let hh_show_full_env p env =
log_with_level env "show" ~level:0 @@ fun () ->
let empty_env = { env with inference_env = Inf.empty_inference_env } in
log_env_diff p empty_env env
(* Log the type of an expression *)
let hh_show p env ty =
log_with_level env "show" ~level:0 @@ fun () ->
let s1 = Pr.with_blank_tyvars (fun () -> Pr.debug env ty) in
let s2 = Pr.constraints_for_type env ty in
log_position p (fun () ->
lprintf (Normal Green) "%s" s1;
if String.( <> ) s2 "" then lprintf (Normal Green) " %s" s2;
lnewline ())
(* Simple type of possible log data *)
type log_structure =
| Log_head of string * log_structure list
| Log_type of string * Typing_defs.locl_ty
| Log_decl_type of string * Typing_defs.decl_ty
| Log_type_i of string * Typing_defs.internal_type
let log_types p env items =
log_pos_or_decl p (fun () ->
let rec go items =
List.iter items ~f:(fun item ->
match item with
| Log_head (message, items) ->
indentEnv ~color:(Normal Yellow) message (fun () -> go items)
| Log_type (message, ty) ->
let s = Pr.debug env ty in
lprintf (Bold Green) "%s: " message;
lprintf (Normal Green) "%s" s;
lnewline ()
| Log_decl_type (message, ty) ->
let s = Pr.debug_decl env ty in
lprintf (Bold Green) "%s: " message;
lprintf (Normal Green) "%s" s;
lnewline ()
| Log_type_i (message, ty) ->
let s = Pr.debug_i env ty in
lprintf (Bold Green) "%s: " message;
lprintf (Normal Green) "%s" s;
lnewline ())
in
go items)
let log_escape ?(level = 1) p env msg vars =
log_with_level env "escape" ~level (fun () ->
log_pos_or_decl p (fun () ->
indentEnv ~color:(Normal Yellow) msg (fun () -> ());
if not (List.is_empty vars) then (
lnewline ();
List.iter vars ~f:(lprintf (Normal Green) "%s ")
)))
let log_prop level p message env prop =
log_with_level env "prop" ~level (fun () ->
log_pos_or_decl p (fun () -> log_subtype_prop env message prop))
let log_new_tvar env p tvar message =
log_with_level env "prop" ~level:2 (fun () ->
log_types
(Pos_or_decl.of_raw_pos p)
env
[Log_head (message, [Log_type ("type variable", tvar)])])
let log_tparam_instantiation env p tparam_name tvar =
let message =
Printf.sprintf "Instantiating type parameter %s with" tparam_name
in
log_new_tvar env p tvar message
let log_new_tvar_for_new_object env p tvar cname tparam =
let message =
Printf.sprintf
"Creating new type var for type parameter %s while instantiating object %s"
(snd tparam.tp_name)
(snd cname)
in
log_new_tvar env p tvar message
let log_new_tvar_for_tconst env (p, tvar) (_p, tconstid) tvar_for_tconst =
let message =
Printf.sprintf "Creating new type var for #%d::%s" tvar tconstid
in
log_new_tvar env p tvar_for_tconst message
let log_new_tvar_for_tconst_access env p tvar class_name (_p, tconst) =
let message =
Printf.sprintf
"Creating type var with the same constraints as %s::%s"
class_name
tconst
in
log_new_tvar env p tvar message
let log_intersection ~level env r ty1 ty2 ~inter_ty =
log_with_level env "inter" ~level (fun () ->
log_types
(Reason.to_pos r)
env
[
Log_head
( "Intersecting",
[
Log_type ("ty1", ty1);
Log_type ("ty2", ty2);
Log_type ("intersection", inter_ty);
] );
])
let log_type_access ~level root (p, type_const_name) (env, result_ty) =
( log_with_level env "tyconst" ~level @@ fun () ->
log_types
p
env
[
Log_head
( "Accessing type constant " ^ type_const_name ^ " of",
[Log_type ("type", root); Log_type ("result", result_ty)] );
] );
(env, result_ty)
let log_localize ~level ety_env (decl_ty : decl_ty) (env, result_ty) =
( log_with_level env "localize" ~level @@ fun () ->
log_types
(get_pos result_ty)
env
[
Log_head
( "Localizing",
[
Log_head
( Printf.sprintf
"expand_visible_newtype: %b"
ety_env.expand_visible_newtype,
[] );
Log_decl_type ("decl type", decl_ty);
Log_type ("result", result_ty);
] );
] );
(env, result_ty)
let log_pessimise_ ?(level = 1) env kind pos name =
let log_level = Typing_env_types.get_log_level env "pessimise" in
if log_level >= level then
let p = Pos_or_decl.unsafe_to_raw_pos pos in
let (file, line) =
let p = Pos.to_absolute p in
(Pos.filename p, Pos.line p)
in
if log_level > 1 then
Hh_logger.log "pessimise:\t%s,%s,%d,%s" kind file line name
else (
lnewline ();
lprintf (Normal Yellow) "pessimise:\t%s,%s,%d,%s" kind file line name;
lnewline ()
)
let log_pessimise_prop env pos prop_name =
log_pessimise_ env "prop" (Pos_or_decl.of_raw_pos pos) ("$" ^ prop_name)
let log_pessimise_param env ~is_promoted_property pos mode param_name =
if
is_promoted_property
|| (match mode with
| Ast_defs.Pinout _ -> true
| _ -> false)
|| Typing_env_types.get_log_level env "pessimise.params" >= 1
then
log_pessimise_
env
(if is_promoted_property then
"prop"
else
"param")
(Pos_or_decl.of_raw_pos pos)
param_name
let log_pessimise_return ?level env pos opt_bound =
log_pessimise_
?level
env
"ret"
(Pos_or_decl.of_raw_pos pos)
(Option.value ~default:"" opt_bound)
let log_pessimise_poisoned_return ?level env pos member =
log_pessimise_ ?level env "ret" (Pos_or_decl.of_raw_pos pos) ("^" ^ member)
let log_sd_pass ?(level = 1) env pos =
log_with_level env "sd_pass" ~level @@ fun () ->
let (file, line) =
let p = Pos.to_absolute pos in
(Pos.filename p, Pos.line p)
in
lnewline ();
lprintf (Normal Yellow) "sound dynamic pass:\t%s,%d" file line;
lnewline ()
let increment_feature_count env s =
if TypecheckerOptions.language_feature_logging env.genv.tcopt then
Measure.sample s 1.0
module GlobalInference = struct
let log_cat = "gi"
let log_merging_subgraph env pos =
log_with_level env log_cat ~level:1 (fun () ->
log_position pos (fun () ->
log_key "merging subgraph for function at this position"))
let log_merging_var env pos var =
log_with_level env log_cat ~level:1 (fun () ->
log_position pos (fun () ->
log_key (Printf.sprintf "merging type variable %d" var)))
end
module GI = GlobalInference |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_log.mli | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val out_channel : Stdlib.out_channel ref
val log_key : string -> unit
val log_env_diff :
Pos.t ->
?function_name:string ->
Typing_env_types.env ->
Typing_env_types.env ->
unit
val hh_show_env : ?function_name:string -> Pos.t -> Typing_env_types.env -> unit
val hh_show_full_env : Pos.t -> Typing_env_types.env -> unit
val hh_show : Pos.t -> Typing_env_types.env -> Typing_defs.locl_ty -> unit
(** Simple type of possible log data *)
type log_structure =
| Log_head of string * log_structure list
| Log_type of string * Typing_defs.locl_ty
| Log_decl_type of string * Typing_defs.decl_ty
| Log_type_i of string * Typing_defs.internal_type
val log_with_level :
Typing_env_types.env -> string -> level:int -> (unit -> unit) -> unit
val log_types :
Pos_or_decl.t -> Typing_env_types.env -> log_structure list -> unit
val log_escape :
?level:int ->
Pos_or_decl.t ->
Typing_env_types.env ->
string ->
string list ->
unit
val log_prop :
int ->
Pos_or_decl.t ->
string ->
Typing_env_types.env ->
Typing_logic.subtype_prop ->
unit
val log_tparam_instantiation :
Typing_env_types.env -> Pos.t -> string -> Typing_defs.locl_ty -> unit
val log_new_tvar_for_new_object :
Typing_env_types.env ->
Pos.t ->
Typing_defs.locl_ty ->
'a * string ->
'b Typing_defs.tparam ->
unit
val log_new_tvar_for_tconst :
Typing_env_types.env ->
Pos.t * Ident.t ->
Typing_defs.pos_id ->
Typing_defs.locl_ty ->
unit
val log_new_tvar_for_tconst_access :
Typing_env_types.env ->
Pos.t ->
Typing_defs.locl_ty ->
string ->
Typing_defs.pos_id ->
unit
val log_intersection :
level:int ->
Typing_env_types.env ->
Typing_reason.t ->
Typing_defs.locl_ty ->
Typing_defs.locl_ty ->
inter_ty:Typing_defs.locl_ty ->
unit
val log_type_access :
level:int ->
Typing_defs.locl_ty ->
Typing_defs.pos_id ->
Typing_env_types.env * Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty
val log_localize :
level:int ->
Typing_defs.expand_env ->
Typing_defs.decl_ty ->
Typing_env_types.env * Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty
val increment_feature_count : Typing_env_types.env -> string -> unit
val log_pessimise_prop : Typing_env_types.env -> Pos.t -> string -> unit
val log_pessimise_return :
?level:int -> Typing_env_types.env -> Pos.t -> string option -> unit
val log_pessimise_poisoned_return :
?level:int -> Typing_env_types.env -> Pos.t -> string -> unit
val log_pessimise_param :
Typing_env_types.env ->
is_promoted_property:bool ->
Pos.t ->
Ast_defs.param_kind ->
string ->
unit
val log_sd_pass : ?level:int -> Typing_env_types.env -> Pos.t -> unit
module GlobalInference : sig
val log_merging_subgraph : Typing_env_types.env -> Pos.t -> unit
val log_merging_var : Typing_env_types.env -> Pos.t -> Ident.t -> unit
end
module GI = GlobalInference |
OCaml | hhvm/hphp/hack/src/typing/typing_logic.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Typing_defs
type coercion_direction =
| CoerceToDynamic
| CoerceFromDynamic
[@@deriving show, eq]
(* See comment in .mli file *)
type subtype_prop =
| IsSubtype of coercion_direction option * internal_type * internal_type
| Conj of subtype_prop list
| Disj of Typing_error.t option * subtype_prop list
[@@deriving show]
let rec equal_subtype_prop p1 p2 =
match (p1, p2) with
| (IsSubtype (c1, ty1, ty1'), IsSubtype (c2, ty2, ty2')) ->
Option.equal equal_coercion_direction c1 c2
&& equal_internal_type ty1 ty2
&& equal_internal_type ty1' ty2'
| (Conj ps1, Conj ps2)
| (Disj (_, ps1), Disj (_, ps2)) ->
Int.equal (List.length ps1) (List.length ps2)
&& List.for_all2_exn ps1 ps2 ~f:equal_subtype_prop
| (_, (IsSubtype _ | Conj _ | Disj _)) -> false
let rec size (p : subtype_prop) : int =
match p with
| IsSubtype _ -> 1
| Conj l
| Disj (_, l) ->
let sizes = List.map l ~f:size in
List.fold ~init:0 ~f:( + ) sizes
(** Sum of the sizes of the disjunctions. *)
let rec n_disj (p : subtype_prop) : int =
match p with
| IsSubtype _ -> 0
| Conj l ->
let n_disjs = List.map l ~f:n_disj in
List.fold ~init:0 ~f:( + ) n_disjs
| Disj (_, l) ->
let n_disjs = List.map l ~f:n_disj in
List.length l + List.fold ~init:0 ~f:( + ) n_disjs
(** Sum of the sizes of the conjunctions. *)
let rec n_conj (p : subtype_prop) : int =
match p with
| IsSubtype _ -> 0
| Disj (_, l) ->
let n_conjs = List.map l ~f:n_conj in
List.fold ~init:0 ~f:( + ) n_conjs
| Conj l ->
let n_conjs = List.map l ~f:n_conj in
List.length l + List.fold ~init:0 ~f:( + ) n_conjs
let valid = Conj []
let invalid ~fail = Disj (fail, [])
(* Is this proposition always true? (e.g. Conj [] but also Disj [Conj []; Disj (_, [])]
* if not simplified
*)
let rec is_valid p =
match p with
| Conj ps -> List.for_all ps ~f:is_valid
| Disj (_, ps) -> List.exists ps ~f:is_valid
| IsSubtype _ -> false
(* Is this proposition always false? e.g. Unsat _ but also Conj [Conj []; Disj (_, [])]
* if not simplified
*)
and is_unsat p =
match p with
| Conj ps -> List.exists ps ~f:is_unsat
| Disj (_, ps) -> List.for_all ps ~f:is_unsat
| IsSubtype _ -> false
let rec get_error_if_unsat p =
match p with
| Disj (err, ps) ->
if List.for_all ps ~f:is_unsat then
err
else
None
| Conj ps -> List.find_map ps ~f:get_error_if_unsat
| IsSubtype _ -> None
(* Smart constructor for binary conjunction *)
let conj p1 p2 =
if equal_subtype_prop p1 p2 then
p1
else
match (p1, p2) with
| (Conj [], p)
| (p, Conj []) ->
p
| (Conj ps1, Conj ps2) -> Conj (ps1 @ ps2)
(* Preserve the order to maintain legacy behaviour. If two errors share the
* same position then the first one to be emitted wins.
* TODO: consider relaxing this behaviour *)
| (Conj ps, _) -> Conj (ps @ [p2])
| (_, Conj ps) -> Conj (p1 :: ps)
| (_, _) -> Conj [p1; p2]
let conj_list ps = List.fold ~init:(Conj []) ps ~f:conj
let add_prop p ps =
if List.exists ps ~f:(equal_subtype_prop p) then
ps
else
p :: ps
(* Smart constructor for binary disjunction *)
let disj ~fail p1 p2 =
if equal_subtype_prop p1 p2 then
p1
else
match (p1, p2) with
| (_, _) when is_valid p1 || is_valid p2 -> Conj []
| (_, _) when is_unsat p1 && is_unsat p2 -> Disj (fail, [])
| (_, _) when is_unsat p1 -> Disj (fail, [p2])
| (_, _) when is_unsat p2 -> Disj (fail, [p1])
| (Disj (_, ps1), Disj (_, ps2)) ->
Disj (fail, List.fold ps2 ~init:ps1 ~f:(fun ps p -> add_prop p ps))
| (_, Disj (_, ps)) -> Disj (fail, add_prop p1 ps)
| (Disj (_, ps), _) -> Disj (fail, add_prop p2 ps)
| (_, _) -> Disj (fail, [p1; p2]) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_logic.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Typing_defs
type coercion_direction =
| CoerceToDynamic
| CoerceFromDynamic
[@@deriving show, eq]
(* Logical proposition about types *)
type subtype_prop =
| IsSubtype of coercion_direction option * internal_type * internal_type
(** IsSubtype(Some cd, ty1, ty2), if ty1 is a subtype of ty2 while potentially
coercing to or from dynamic (depending on cd), written ty1 ~> ty2.
IsSubtype(None, ty1, ty2) if ty1 is a subtype of ty2, written ty1 <: ty2
*)
| Conj of subtype_prop list (** Conjunction. Conj [] means "true" *)
| Disj of Typing_error.t option * subtype_prop list
(** Disjunction. Disj f [] means "false". The error message function f
wraps the error that should be produced in this case. *)
[@@deriving show]
val equal_subtype_prop : subtype_prop -> subtype_prop -> bool
val size : subtype_prop -> int
(** Sum of the sizes of the disjunctions. *)
val n_disj : subtype_prop -> int
(** Sum of the sizes of the conjunctions. *)
val n_conj : subtype_prop -> int
val valid : subtype_prop
val invalid : fail:Typing_error.t option -> subtype_prop
val is_valid : subtype_prop -> bool
val is_unsat : subtype_prop -> bool
val get_error_if_unsat : subtype_prop -> Typing_error.t option
val conj : subtype_prop -> subtype_prop -> subtype_prop
val conj_list : subtype_prop list -> subtype_prop
val disj :
fail:Typing_error.t option -> subtype_prop -> subtype_prop -> subtype_prop |
OCaml | hhvm/hphp/hack/src/typing/typing_logic_helpers.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Typing_env_types
module TL = Typing_logic
let with_error fail ((env, p) : env * TL.subtype_prop) : env * TL.subtype_prop =
match (TL.get_error_if_unsat p, fail) with
| (Some ty_err1, Some ty_err2) ->
(env, TL.Disj (Some (Typing_error.both ty_err1 ty_err2), []))
| _ -> (env, TL.conj p (TL.invalid ~fail))
(* If `b` is false then fail with error function `f` *)
let check_with b f r =
if not b then
with_error f r
else
r
let valid env : env * TL.subtype_prop = (env, TL.valid)
let ( &&& ) (env, p1) (f : env -> env * TL.subtype_prop) =
match TL.get_error_if_unsat p1 with
| Some ty_err1 ->
let (env, p2) = f env in
begin
match TL.get_error_if_unsat p2 with
| Some ty_err2 ->
(env, TL.Disj (Some (Typing_error.both ty_err1 ty_err2), []))
| None -> (env, p1)
end
| None ->
let (env, p2) = f env in
(env, TL.conj p1 p2)
let if_unsat (f : env -> env * TL.subtype_prop) (env, p) =
if TL.is_unsat p then
f env
else
(env, p)
let ( ||| ) ~fail (env, p1) (f : env -> env * TL.subtype_prop) =
if TL.is_valid p1 then
(env, p1)
else
let (env, p2) = f env in
(env, TL.disj ~fail p1 p2)
(* We *know* that the assertion is unsatisfiable *)
let invalid ~fail env = (env, TL.invalid ~fail) |
OCaml | hhvm/hphp/hack/src/typing/typing_log_value.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* Universal representation of an environment, for pretty-printing and delta computation
*)
type value =
| Bool of bool
| Atom of string
| List of value list
| Set of SSet.t
| Map of value SMap.t
| Type of Typing_defs.internal_type
| SubtypeProp of Typing_logic.subtype_prop
[@@deriving eq]
let make_map l = Map (SMap.of_list l)
let bool_as_value v = Bool v
let string_as_value s = Atom s
let smap_as_value f m = Map (SMap.map f m)
let list_as_value l = List l
let internal_type_as_value ty = Type ty
let locl_type_as_value ty = internal_type_as_value (Typing_defs.LoclType ty)
let internal_type_set_as_value tys =
Internal_type_set.elements tys
|> List.map internal_type_as_value
|> list_as_value
let subtype_prop_as_value prop = SubtypeProp prop
let pos_as_value p = string_as_value (Pos.string (Pos.to_absolute p))
let reason_as_value r =
string_as_value (Format.asprintf "%a" Typing_reason.pp r)
let local_id_as_string id =
Printf.sprintf "%s[#%d]" (Local_id.get_name id) (Local_id.to_int id)
let local_id_set_as_value s =
Set
(Local_id.Set.fold
(fun id s -> SSet.add (local_id_as_string id) s)
s
SSet.empty)
let var_as_string v = Printf.sprintf "#%d" v
let varset_as_value s =
Set (ISet.fold (fun v s -> SSet.add (var_as_string v) s) s SSet.empty)
let variant_as_value name v = make_map [(name, v)] |
OCaml | hhvm/hphp/hack/src/typing/typing_make_type.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Typing_defs
module SN = Naming_special_names
module Reason = Typing_reason
module Nast = Aast
let class_type r name tyl =
mk (r, Tclass ((Reason.to_pos r, name), nonexact, tyl))
let classname r tyl = class_type r SN.Classes.cClassname tyl
let prim_type r t = mk (r, Tprim t)
(* Make a negation type *)
let neg r neg_t =
match neg_t with
(* Represent the negation of Tnull as Tnonnull, instead of Tneg Tnull *)
| Neg_prim Nast.Tnull -> mk (r, Tnonnull)
| _ -> mk (r, Tneg neg_t)
let traversable r ty = class_type r SN.Collections.cTraversable [ty]
let keyed_traversable r kty vty =
class_type r SN.Collections.cKeyedTraversable [kty; vty]
let keyed_container r kty vty =
class_type r SN.Collections.cKeyedContainer [kty; vty]
let awaitable r ty = class_type r SN.Classes.cAwaitable [ty]
let generator r key value send =
class_type r SN.Classes.cGenerator [key; value; send]
let async_generator r key value send =
class_type r SN.Classes.cAsyncGenerator [key; value; send]
let async_iterator r ty = class_type r SN.Classes.cAsyncIterator [ty]
let async_keyed_iterator r ty1 ty2 =
class_type r SN.Classes.cAsyncKeyedIterator [ty1; ty2]
let pair r ty1 ty2 = class_type r SN.Collections.cPair [ty1; ty2]
let dict r kty vty = class_type r SN.Collections.cDict [kty; vty]
let keyset r ty = class_type r SN.Collections.cKeyset [ty]
let vec r ty = class_type r SN.Collections.cVec [ty]
let any_array r kty vty = class_type r SN.Collections.cAnyArray [kty; vty]
let container r ty = class_type r SN.Collections.cContainer [ty]
let throwable r = class_type r SN.Classes.cThrowable []
let datetime r = class_type r SN.Classes.cDateTime []
let datetime_immutable r = class_type r SN.Classes.cDateTimeImmutable []
let const_vector r ty = class_type r SN.Collections.cConstVector [ty]
let const_collection r ty = class_type r SN.Collections.cConstCollection [ty]
let collection r ty = class_type r SN.Collections.cCollection [ty]
let spliceable r ty1 ty2 ty3 =
class_type r SN.Classes.cSpliceable [ty1; ty2; ty3]
let vec_or_dict r kty vty = mk (r, Tvec_or_dict (kty, vty))
let int r = prim_type r Nast.Tint
let bool r = prim_type r Nast.Tbool
let string r = prim_type r Nast.Tstring
let float r = prim_type r Nast.Tfloat
let num r = prim_type r Nast.Tnum
let arraykey r = prim_type r Nast.Tarraykey
let void r = prim_type r Nast.Tvoid
let null r = prim_type r Nast.Tnull
let nonnull r = mk (r, Tnonnull)
let dynamic r = mk (r, Tdynamic)
let like r ty = mk (r, Tlike ty)
let locl_like r ty =
if is_dynamic ty then
ty
else
match get_node ty with
| Tprim Aast.Tnoreturn
| Tany _ ->
ty
| Tunion tys when List.exists Typing_defs.is_dynamic tys -> ty
| _ -> mk (r, Tunion [dynamic r; ty])
let supportdyn r ty =
match get_node ty with
| Tnewtype (c, _, _) when String.equal c SN.Classes.cSupportDyn -> ty
| Tunion [] -> ty
| _ -> mk (r, Tnewtype (SN.Classes.cSupportDyn, [ty], ty))
let supportdyn_nonnull r = supportdyn r (nonnull r)
let mixed r = mk (r, Toption (nonnull r))
let nothing r = mk (r, Tunion [])
let shape r kind map =
mk
( r,
Tshape
{ s_origin = Missing_origin; s_unknown_value = kind; s_fields = map } )
let closed_shape r map = shape r (nothing r) map
let open_shape r map = shape r (mixed r) map
let supportdyn_mixed ?(mixed_reason = Reason.Rnone) r =
supportdyn r (mixed mixed_reason)
let hh_formatstring r ty =
mk (r, Tnewtype (SN.Classes.cHHFormatString, [ty], mixed r))
let resource r = prim_type r Nast.Tresource
let tyvar r v = mk (r, Tvar v)
let generic ?(type_args = []) r n = mk (r, Tgeneric (n, type_args))
let this r = mk (r, Tgeneric (SN.Typehints.this, []))
let taccess r ty id = mk (r, Taccess (ty, id))
let nullable : type a. a Reason.t_ -> a ty -> a ty =
fun r ty ->
(* Cheap avoidance of double nullable *)
match get_node ty with
| Toption _ as ty_ -> mk (r, ty_)
| Tunion [] -> null r
| _ -> mk (r, Toption ty)
let apply r id tyl = mk (r, Tapply (id, tyl))
let tuple r tyl = mk (r, Ttuple tyl)
let union r tyl =
match tyl with
| [ty] -> ty
| _ -> mk (r, Tunion tyl)
let intersection r tyl =
match tyl with
| [] -> mixed r
| [ty] -> ty
| _ -> mk (r, Tintersection tyl)
let unenforced ty = { et_type = ty; et_enforced = Unenforced }
let enforced ty = { et_type = ty; et_enforced = Enforced }
let has_member r ~name ~ty ~class_id ~explicit_targs =
ConstraintType
(mk_constraint_type
( r,
Thas_member
{
hm_name = name;
hm_type = ty;
hm_class_id = class_id;
hm_explicit_targs = explicit_targs;
} ))
let list_destructure r tyl =
ConstraintType
(mk_constraint_type
( r,
Tdestructure
{
d_required = tyl;
d_optional = [];
d_variadic = None;
d_kind = ListDestructure;
} ))
let simple_variadic_splat r ty =
ConstraintType
(mk_constraint_type
( r,
Tdestructure
{
d_required = [];
d_optional = [];
d_variadic = Some ty;
d_kind = SplatUnpack;
} ))
let capability r name : locl_ty = class_type r name []
let default_capability p : locl_ty =
let r = Reason.Rdefault_capability p in
intersection
r
SN.Capabilities.
[
class_type r writeProperty [];
class_type r accessGlobals [];
class_type r rxLocal [];
class_type r systemLocal [];
class_type r implicitPolicyLocal [];
class_type r io [];
]
let default_capability_unsafe p : locl_ty = mixed (Reason.Rhint p) |
OCaml | hhvm/hphp/hack/src/typing/typing_memoize.ml | (*
* Copyright (c) 2017, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
open Typing_defs
open Typing_env_types
module Env = Typing_env
module SN = Naming_special_names
module MakeType = Typing_make_type
let check_param : env -> Nast.fun_param -> unit =
fun env { param_type_hint; param_pos; param_name; _ } ->
let error ty =
let ty_name = lazy (Typing_print.error env ty) in
let msgl =
Lazy.map ty_name ~f:(fun ty_name ->
Reason.to_string ("This is " ^ ty_name) (get_reason ty))
in
Typing_error.Primary.Invalid_memoized_param
{ pos = param_pos; reason = msgl; ty_name }
in
let check_memoizable env pos ty =
let rec check_memoizable : env -> locl_ty -> unit =
fun env ty ->
let (env, ty) = Env.expand_type env ty in
let ety_env = empty_expand_env in
let ty = Typing_utils.strip_dynamic env ty in
let ((env, ty_err_opt), ty, _) =
Typing_tdef.force_expand_typedef ~ety_env env ty
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
if not (Typing_utils.is_tyvar_error env ty) then
match get_node ty with
| Tprim (Tnull | Tarraykey | Tbool | Tint | Tfloat | Tstring | Tnum) ->
()
| Tnonnull
| Tany _
| Tdynamic
| Tneg _ ->
let (_ : env) = Typing_local_ops.enforce_memoize_object pos env in
()
| Tprim (Tvoid | Tresource | Tnoreturn) ->
Typing_error_utils.add_typing_error ~env
@@ Typing_error.primary
@@ error ty
| Toption ty -> check_memoizable env ty
| Ttuple tyl -> List.iter tyl ~f:(check_memoizable env)
(* Just accept all generic types for now. Stricter check_memoizables to come later. *)
| Tgeneric _ ->
(* FIXME fun fact:
the comment above about "stricter check_memoizables to come later" was added in revision
in August 2015 *)
()
| Tnewtype (id, _, _) when String.equal SN.Classes.cEnumClassLabel id ->
(* The underlying representation of an Enum Class Label is a
* resource, so this must behave like Tresource. *)
Typing_error_utils.add_typing_error ~env
@@ Typing_error.primary
@@ error ty
| Tnewtype (name, [ty], _) when String.equal name SN.Classes.cSupportDyn
->
check_memoizable env ty
(* For parameter type 'this::TID' defined by 'type const TID as Bar' check_memoizables
* Bar recursively. Also enums represented using AKnewtype.
*)
| Tnewtype (_, _, ty)
| Tdependent (_, ty) ->
check_memoizable env ty
(* Handling Tunion and Tintersection case here for completeness, even though it
* shouldn't be possible to have an unresolved type when check_memoizableing
* the method declaration. No corresponding test case for this.
*)
| Tunion tyl
| Tintersection tyl ->
List.iter tyl ~f:(check_memoizable env)
| Tvec_or_dict (_, ty) -> check_memoizable env ty
| Tshape { s_fields = fdm; _ } ->
(* TODO(shapes) should unknown type affect memoizability? *)
TShapeMap.iter
begin
(fun _ { sft_ty; _ } -> check_memoizable env sft_ty)
end
fdm
| Tclass _ ->
let env = Env.open_tyvars env pos in
let (env, type_param) = Env.fresh_type env pos in
let container_type = MakeType.container Reason.none type_param in
let (env, ty_err_opt) =
Typing_utils.sub_type env ty container_type
@@ Some (Typing_error.Reasons_callback.unify_error_at pos)
in
let is_container = Option.is_none ty_err_opt in
let mixed = MakeType.mixed Reason.none in
let hackarray = MakeType.any_array Reason.none mixed mixed in
let is_hackarray = Typing_utils.is_sub_type env ty hackarray in
let env =
if not is_hackarray then
(* Check if it's a UNSAFEsingleton memoize param *)
let singleton =
MakeType.class_type
Reason.none
SN.Classes.cUNSAFESingletonMemoizeParam
[]
in
if Typing_utils.is_sub_type env ty singleton then
env
else
Typing_local_ops.enforce_memoize_object pos env
else
env
in
let env = Env.set_tyvar_variance env container_type in
let (env, e1) = Typing_solver.close_tyvars_and_solve env in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) e1;
if is_container then
check_memoizable env type_param
else
let base_error = error ty in
let ((env, ty_err_opt), (tfty, _tal)) =
Typing_object_get.obj_get
~obj_pos:param_pos
~is_method:true
~inst_meth:false
~meth_caller:false
~nullsafe:None
~coerce_from_ty:None
~explicit_targs:[]
~class_id:
(CIexpr
( (),
param_pos,
Lvar (param_pos, Local_id.make_unscoped param_name) ))
~member_id:(pos, SN.Members.mGetInstanceKey)
~on_error:Typing_error.Callback.(always base_error)
env
ty
in
Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env);
ignore
(Typing.call
~expected:None
~expr_pos:pos
~recv_pos:pos
env
tfty
[]
None)
| Tunapplied_alias _ ->
Typing_defs.error_Tunapplied_alias_in_illegal_context ()
| Taccess _ -> ()
| Tfun _
| Tvar _ ->
Typing_error_utils.add_typing_error ~env
@@ Typing_error.primary
@@ error ty
in
check_memoizable env ty
in
match hint_of_type_hint param_type_hint with
| None -> ()
| Some hint ->
let (hint_pos, _) = hint in
let ((env, ty_err_opt), ty) =
Typing_phase.localize_hint_no_subst env ~ignore_errors:true hint
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
check_memoizable env hint_pos ty
let check : env -> Nast.user_attribute list -> Nast.fun_param list -> unit =
fun env user_attributes params ->
if
Naming_attributes.mem SN.UserAttributes.uaMemoize user_attributes
|| Naming_attributes.mem SN.UserAttributes.uaMemoizeLSB user_attributes
then
List.iter ~f:(check_param env) params
let check_function : env -> Nast.fun_ -> unit =
fun env { f_user_attributes; f_params; _ } ->
check env f_user_attributes f_params
let check_method : env -> Nast.method_ -> unit =
fun env { m_user_attributes; m_params; _ } ->
check env m_user_attributes m_params |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_memoize.mli | (*
* Copyright (c) 2017, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(** Checks if a function can be memoized. If the function cannot be
memoized this will add an error to the global error list. *)
val check_function : Typing_env_types.env -> Nast.fun_ -> unit
(** Checks if a method can be memoized. If the method cannot be
memoized this will add an error to the global error list. *)
val check_method : Typing_env_types.env -> Nast.method_ -> unit |
OCaml | hhvm/hphp/hack/src/typing/typing_modules.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 Typing_defs
module Env = Typing_env
module Cls = Decl_provider.Class
let can_access_internal
~(env : Typing_env_types.env)
~(current : string option)
~(target : string option) =
match (current, target) with
| (None, None)
| (Some _, None) ->
`Yes
| (None, Some m) -> `Outside m
| (Some m_current, Some m_target) when String.equal m_current m_target ->
(match Env.get_self_id env with
| None -> `Yes
| Some self ->
(match Env.get_class env self with
| Some cls
when Ast_defs.is_c_trait (Cls.kind cls)
&& (not (Cls.internal cls))
&& not (Cls.is_module_level_trait cls) ->
`OutsideViaTrait (Cls.pos cls)
| Some _
| None ->
`Yes))
| (Some current, Some target) -> `Disjoint (current, target)
let satisfies_rule test_module_opt rule =
match rule with
(* A 'global' rule, so match if the module is empty (i.e. the code is not in a module) *)
| MRGlobal -> Option.is_none test_module_opt
(* A wildcard rule like 'a.x.*', so match if the rule matches the prefix of the module *)
| MRPrefix rule_module_prefix ->
(* The '*' rule matches everyone *)
if String.length rule_module_prefix = 0 then
true
else (
match test_module_opt with
(* No module, so fail *)
| None -> false
(* Make sure the prefix is correct (and is followed by '.') *)
| Some module_ ->
let prefix_length = String.length rule_module_prefix in
let test_length = String.length module_ in
prefix_length = 0
|| String.is_prefix module_ ~prefix:rule_module_prefix
&& (test_length = prefix_length
|| Char.equal module_.[prefix_length] '.')
)
(* An exact rule like 'a.x', so match if the name matches the module *)
| MRExact rule_module ->
(match test_module_opt with
(* No module, so fail *)
| None -> false
(* Make sure names are exact *)
| Some module_ -> String.equal rule_module module_)
let satisfies_rules test_module_opt rules =
match rules with
| None -> true
| Some rules_list ->
if List.length rules_list = 0 then
false
else
List.exists rules_list ~f:(satisfies_rule test_module_opt)
let find_module_symbol env name_opt =
match name_opt with
| None -> None
| Some name -> Some (name, Env.get_module env name)
let satisfies_import_rules env current target =
match find_module_symbol env current with
| None
| Some (_, None) ->
None
| Some (current_module_name, Some current_module_symbol) ->
if satisfies_rules target current_module_symbol.mdt_imports then
None
else
Some (current_module_name, current_module_symbol.mdt_pos)
let satisfies_export_rules env current target =
match find_module_symbol env target with
| None
| Some (_, None) ->
None
| Some (target_module_name, Some target_module_symbol) ->
if satisfies_rules current target_module_symbol.mdt_exports then
None
else
Some (target_module_name, target_module_symbol.mdt_pos)
let satisfies_package_deps env current_pkg target_pkg =
match (current_pkg, target_pkg) with
| (_, None) -> None
| (None, Some target_pkg_info) ->
if Env.is_package_loaded env (Package.get_package_name target_pkg_info) then
None
else
Some (Pos.none, Package.Unrelated)
(* Anyone can call code outside of a package *)
| (Some current_pkg_info, Some target_pkg_info) ->
Package.(
(match relationship current_pkg_info target_pkg_info with
| Equal
| Includes ->
None
| (Soft_includes | Unrelated) as r ->
if Env.is_package_loaded env (Package.get_package_name target_pkg_info)
then
None
else
Some (get_package_pos current_pkg_info, r)))
let satisfies_pkg_rules env current target =
let target_pkg = Option.bind target ~f:(Env.get_package_for_module env) in
let (current_pkg, current_module_pos) =
match find_module_symbol env current with
| None
| Some (_, None) ->
(None, Pos_or_decl.none)
| Some (current_module_name, Some current_module_symbol) ->
( Env.get_package_for_module env current_module_name,
current_module_symbol.mdt_pos )
in
match satisfies_package_deps env current_pkg target_pkg with
| None -> None
| Some (current_package_pos, r) ->
Some ((current_package_pos, current_module_pos), r)
let can_access_public
~(env : Typing_env_types.env)
~(current : string option)
~(target : string option) =
if Option.equal String.equal current target then
`Yes
else
match satisfies_import_rules env current target with
| Some current_module -> `ImportsNotSatisfied current_module
| None ->
(match satisfies_export_rules env current target with
| Some target_module -> `ExportsNotSatisfied target_module
| None ->
(match satisfies_pkg_rules env current target with
| Some (current_module, Package.Soft_includes) ->
`PackageSoftIncludes current_module
| Some (current_module, Package.Unrelated) ->
`PackageNotSatisfied current_module
| Some (_, Package.(Equal | Includes)) ->
Utils.assert_false_log_backtrace
(Some "Package constraints are satisfied with equal and includes")
| None -> `Yes))
let is_class_visible (env : Typing_env_types.env) (cls : Cls.t) =
if Cls.internal cls then
match
can_access_internal
~env
~current:(Env.get_current_module env)
~target:(Cls.get_module cls)
with
| `Yes -> true
| _ -> false
else
true |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_modules.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.
*
*)
(** [can_access_internal ~env ~current ~target] returns whether a symbol defined in
* module [current] is allowed to access an internal symbol defined in
* [target] under [env].
*)
val can_access_internal :
env:Typing_env_types.env ->
current:string option ->
target:string option ->
[ `Yes
| `Disjoint of string * string
| `Outside of string
| `OutsideViaTrait of Pos_or_decl.t
]
(** [can_access_public ~env ~current ~target] returns whether a symbol defined in
* module [current] is allowed to access an public symbol defined in
* [target] under [env].
*)
val can_access_public :
env:Typing_env_types.env ->
current:string option ->
target:string option ->
[ `Yes
| `ImportsNotSatisfied of string * Pos_or_decl.t
| `ExportsNotSatisfied of string * Pos_or_decl.t
| `PackageNotSatisfied of Pos.t * Pos_or_decl.t
| `PackageSoftIncludes of Pos.t * Pos_or_decl.t
]
val is_class_visible : Typing_env_types.env -> Decl_provider.class_decl -> bool
val satisfies_package_deps :
Typing_env_types.env ->
Package.t option ->
Package.t option ->
(Pos.t * Package.package_relationship) option |
OCaml | hhvm/hphp/hack/src/typing/typing_native.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module SN = Naming_special_names
let is_native_fun ~env f =
TypecheckerOptions.is_systemlib
(Provider_context.get_tcopt (Typing_env.get_ctx env))
&& Naming_attributes.mem SN.UserAttributes.uaNative f.Aast.f_user_attributes
let is_native_meth ~env m =
TypecheckerOptions.is_systemlib
(Provider_context.get_tcopt (Typing_env.get_ctx env))
&& Naming_attributes.mem SN.UserAttributes.uaNative m.Aast.m_user_attributes |
OCaml | hhvm/hphp/hack/src/typing/typing_object_get.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Common
open Tast
open Typing_defs
open Utils
module TUtils = Typing_utils
module Reason = Typing_reason
module Env = Typing_env
module Union = Typing_union
module Inter = Typing_intersection
module SN = Naming_special_names
module TVis = Typing_visibility
module Phase = Typing_phase
module MakeType = Typing_make_type
module Cls = Decl_provider.Class
type ty_mismatch = (locl_ty, locl_ty * locl_ty) result
type internal_result =
Typing_env_types.env
* Typing_error.t option
* (locl_ty * targ list)
* ty_mismatch
* ty_mismatch option
let merge_ty_err
ty_err_opt1 (env, ty_err_opt2, tals, lval_mismatch, rval_mismatch_opt) =
let ty_err_opt = Option.merge ty_err_opt1 ty_err_opt2 ~f:Typing_error.both in
(env, ty_err_opt, tals, lval_mismatch, rval_mismatch_opt)
(** Common arguments to internal `obj_get_...` functions *)
type obj_get_args = {
inst_meth: bool;
meth_caller: bool;
is_method: bool;
is_nonnull: bool;
nullsafe: Reason.t option;
obj_pos: pos;
coerce_from_ty:
(MakeType.Nast.pos * Reason.ureason * Typing_defs.locl_ty) option;
explicit_targs: Nast.targ list;
this_ty: locl_ty;
this_ty_conjunct: locl_ty;
is_parent_call: bool;
dep_kind: Reason.t * Typing_dependent_type.ExprDepTy.dep;
seen: SSet.t;
}
let log_obj_get env helper id_pos ty this_ty =
let (fn_name, ty_name) =
match helper with
| `concrete -> ("obj_get_concrete_ty", "concrete_ty")
| `inner -> ("obj_get_inner", "receiver_ty")
in
Typing_log.(
log_with_level env "obj_get" ~level:2 (fun () ->
log_types
(Pos_or_decl.of_raw_pos id_pos)
env
[
Log_head
(fn_name, [Log_type (ty_name, ty); Log_type ("this_ty", this_ty)]);
]))
let mk_ety_env class_info paraml this_ty =
{
empty_expand_env with
this_ty;
substs = TUtils.make_locl_subst_for_class_tparams class_info paraml;
}
let mk_mismatch_intersection env errs_res =
Result.fold
errs_res
~ok:(fun tys ->
let (env, ty) = Inter.intersect_list env Reason.none tys in
(env, Ok ty))
~error:(fun (actuals, expecteds) ->
let (env, ty_actual) = Inter.intersect_list env Reason.none actuals in
let (env, ty_expect) = Inter.intersect_list env Reason.none expecteds in
(env, Error (ty_actual, ty_expect)))
let mk_mismatch_union env =
Result.fold
~ok:(fun tys ->
let (env, ty) = Union.union_list env Reason.none tys in
(env, Ok ty))
~error:(fun (actuals, expecteds) ->
let (env, ty_acutal) = Union.union_list env Reason.none actuals in
let (env, ty_expect) = Union.union_list env Reason.none expecteds in
(env, Error (ty_acutal, ty_expect)))
let fold_mismatches mismatches =
List.fold_left mismatches ~init:(Ok []) ~f:(fun acc err ->
match (acc, err) with
| (Ok xs, Ok x) -> Ok (x :: xs)
| (Ok xs, Error (x, y)) -> Error (x :: xs, y :: xs)
| (Error (xs, ys), Ok x) -> Error (x :: xs, x :: ys)
| (Error (xs, ys), Error (x, y)) -> Error (x :: xs, y :: ys))
let fold_mismatch_opts opt_errs =
Option.(map ~f:fold_mismatches @@ all opt_errs)
let smember_not_found
pos ~is_const ~is_method ~is_function_pointer class_ member_name on_error =
let kind =
if is_const then
`class_constant
else if is_method then
`static_method
else
`class_variable
in
let error hint =
let (class_pos, class_name) = (Cls.pos class_, Cls.name class_) in
let quickfixes =
Option.value_map hint ~default:[] ~f:(fun (_, _, new_text) ->
[Quickfix.make ~title:("Change to ::" ^ new_text) ~new_text pos])
in
Typing_error.(
apply ~on_error
@@ primary
@@ Primary.Smember_not_found
{ pos; kind; class_name; class_pos; member_name; hint; quickfixes })
in
let static_suggestion =
Env.suggest_static_member is_method class_ member_name
in
let method_suggestion = Env.suggest_member is_method class_ member_name in
match (static_suggestion, method_suggestion) with
(* If there is a normal method of the same name and the
* syntax is a function pointer, suggest meth_caller *)
| (_, Some (_, v)) when is_function_pointer && String.equal v member_name ->
Typing_error.(
primary
@@ Primary.Consider_meth_caller
{ pos; class_name = Cls.name class_; meth_name = member_name })
(* If there is a normal method of the same name, suggest it *)
| (Some _, Some (def_pos, v)) when String.equal v member_name ->
error (Some (`instance, def_pos, v))
(* Otherwise suggest a different static method *)
| (Some (def_pos, v), _) -> error (Some (`static, def_pos, v))
(* Fallback to closest normal method *)
| (None, Some (def_pos, v)) -> error (Some (`instance, def_pos, v))
| (None, None) -> error None
let member_not_found
(env : Typing_env_types.env) pos ~is_method class_ member_name r on_error =
let cls_name = strip_ns (Cls.name class_) in
if
Env.is_in_expr_tree env
&& is_method
&& String.is_prefix member_name ~prefix:"__"
then
Typing_error.(
expr_tree
@@ Primary.Expr_tree.Expression_tree_unsupported_operator
{ class_name = cls_name; member_name; pos })
else
let (class_pos, class_name) = (Cls.pos class_, Cls.name class_) in
let reason =
lazy
(Reason.to_string
("This is why I think it is an object of type " ^ cls_name)
r)
in
let hint =
lazy
(let method_suggestion =
Env.suggest_member is_method class_ member_name
in
let static_suggestion =
Env.suggest_static_member is_method class_ member_name
in
match (method_suggestion, static_suggestion) with
(* Prefer suggesting a different method, unless there's a
static method whose name matches exactly. *)
| (Some _, Some (def_pos, v)) when String.equal v member_name ->
Some (`static, def_pos, v)
| (Some (def_pos, v), _) -> Some (`instance, def_pos, v)
| (None, Some (def_pos, v)) -> Some (`static, def_pos, v)
| (None, None) -> None)
in
Typing_error.(
apply ~on_error
@@ primary
@@ Primary.Member_not_found
{
pos;
kind =
(if is_method then
`method_
else
`property);
class_name;
class_pos;
member_name;
hint;
reason;
})
let sound_dynamic_err_opt args env ((_, id_str) as id) read_context =
(* Any access to a *private* member through dynamic might potentially
* be unsound, if the receiver is an instance of a class that implements dynamic,
* as we do no checks on enforceability or subtype-dynamic at the definition site
* of private members.
*)
match Env.get_self_class env with
| Some self_class
when Cls.get_support_dynamic_type self_class || not (Cls.final self_class)
->
(match Env.get_member args.is_method env self_class id_str with
| Some { ce_visibility = Vprivate _; ce_type = (lazy ty); _ }
when not args.is_method ->
if read_context then
let ((env, lclz_ty_err_opt), locl_ty) =
Phase.localize_no_subst ~ignore_errors:true env ty
in
Option.merge ~f:Typing_error.both lclz_ty_err_opt
@@ Typing_dynamic.check_property_sound_for_dynamic_read
~on_error:(fun pos prop_name class_name (prop_pos, prop_type) ->
Typing_error.(
primary
@@ Primary.Private_property_is_not_dynamic
{ pos; prop_name; class_name; prop_pos; prop_type }))
env
(Cls.name self_class)
id
locl_ty
else
Typing_dynamic.check_property_sound_for_dynamic_write
~this_class:(Some self_class)
~on_error:(fun pos prop_name class_name (prop_pos, prop_type) ->
Typing_error.(
primary
@@ Primary.Private_property_is_not_enforceable
{ pos; prop_name; class_name; prop_pos; prop_type }))
env
(Cls.name self_class)
id
ty
None
| _ -> None)
| _ -> None
let widen_class_for_obj_get ~is_method ~nullsafe member_name env ty =
match deref ty with
| (_, Tprim Tnull) ->
if Option.is_some nullsafe then
((env, None), Some ty)
else
((env, None), None)
| (r2, Tclass (((_, class_name) as class_id), _, tyl)) ->
let default () =
let ty = mk (r2, Tclass (class_id, nonexact, tyl)) in
((env, None), Some ty)
in
begin
match Env.get_class env class_name with
| None -> default ()
| Some class_info ->
(match Env.get_member is_method env class_info member_name with
| Some { ce_origin; _ } ->
(* If this member was inherited then we obtain the type from which
* it is inherited as our wider type *)
if String.equal ce_origin class_name then
default ()
else (
match Cls.get_ancestor class_info ce_origin with
| None -> default ()
| Some basety ->
let ety_env =
{
empty_expand_env with
substs =
TUtils.make_locl_subst_for_class_tparams class_info tyl;
this_ty = ty;
}
in
let (env, basety) = Phase.localize ~ety_env env basety in
(env, Some basety)
)
| None -> ((env, None), None))
end
| _ -> ((env, None), None)
(* `ty` is expected to be the type for a property or method that has been
* accessed using the nullsafe operatore e.g. $x?->prop or $x?->foo(...).
*
* For properties, just make the type nullable.
* For methods, we expect a function type, and make the return type nullable.
* But in the case that we have type nothing, we just use the type `null`.
* The `call` helper will deal appropriately with it.
* Similarly if we have dynamic, or err, or any, we leave as dynamic/err/any respectively.
*)
let rec make_nullable_member_type env ~is_method id_pos pos ty =
if is_method then
let (env, ty) = Env.expand_type env ty in
match deref ty with
| (r, Tfun tf) ->
let (env, ty) =
make_nullable_member_type
~is_method:false
env
id_pos
pos
tf.ft_ret.et_type
in
(env, mk (r, Tfun { tf with ft_ret = { tf.ft_ret with et_type = ty } }))
| (r, Tunion (_ :: _ as tyl)) ->
let (env, tyl) =
List.map_env env tyl ~f:(fun env ty ->
make_nullable_member_type ~is_method env id_pos pos ty)
in
Union.union_list env r tyl
| (r, Tintersection tyl) ->
let (env, tyl) =
List.map_env env tyl ~f:(fun env ty ->
make_nullable_member_type ~is_method env id_pos pos ty)
in
Inter.intersect_list env r tyl
| (r, Tnewtype (name, [tyarg], _))
when String.equal name SN.Classes.cSupportDyn ->
let (env, ty) =
make_nullable_member_type ~is_method env id_pos pos tyarg
in
(env, MakeType.supportdyn r ty)
| (_, (Tdynamic | Tany _)) -> (env, ty)
| (_, Tunion []) -> (env, MakeType.null (Reason.Rnullsafe_op pos))
| _ ->
(* Shouldn't happen *)
make_nullable_member_type ~is_method:false env id_pos pos ty
else
let (env, ty) =
Typing_solver.non_null env (Pos_or_decl.of_raw_pos id_pos) ty
in
(env, MakeType.nullable (Reason.Rnullsafe_op pos) ty)
(* Return true if the `this` type appears in a covariant
* (resp. contravariant, if contra=true) position in ty.
*)
let rec this_appears_covariantly ~contra env ty =
let rec this_appears_covariantly_params tparams tyl =
match (tparams, tyl) with
| (tp :: tparams, ty :: tyl) ->
begin
match tp.tp_variance with
| Ast_defs.Covariant -> this_appears_covariantly ~contra env ty
| Ast_defs.Contravariant ->
this_appears_covariantly ~contra:(not contra) env ty
| Ast_defs.Invariant ->
this_appears_covariantly ~contra env ty
|| this_appears_covariantly ~contra:(not contra) env ty
end
|| this_appears_covariantly_params tparams tyl
| _ -> false
in
match get_node ty with
| Tthis -> not contra
| Ttuple tyl
| Tunion tyl
| Tintersection tyl ->
List.exists tyl ~f:(this_appears_covariantly ~contra env)
| Tfun ft ->
this_appears_covariantly ~contra env ft.ft_ret.et_type
|| List.exists ft.ft_params ~f:(fun fp ->
this_appears_covariantly ~contra:(not contra) env fp.fp_type.et_type)
| Tshape { s_fields = fm; _ } ->
let fields = TShapeMap.elements fm in
List.exists fields ~f:(fun (_, f) ->
this_appears_covariantly ~contra env f.sft_ty)
| Taccess (ty, _)
| Trefinement (ty, _)
| Tlike ty
| Toption ty ->
this_appears_covariantly ~contra env ty
| Tvec_or_dict (ty1, ty2) ->
this_appears_covariantly ~contra env ty1
|| this_appears_covariantly ~contra env ty2
| Tapply (pos_name, tyl) ->
let tparams =
match Env.get_class_or_typedef env (snd pos_name) with
| Some (Env.TypedefResult { td_tparams; _ }) -> td_tparams
| Some (Env.ClassResult cls) -> Cls.tparams cls
| None -> []
in
this_appears_covariantly_params tparams tyl
| Tmixed
| Twildcard
| Tany _
| Tnonnull
| Tdynamic
| Tprim _
| Tgeneric _ ->
false
| Tnewtype (name, tyl, _) ->
let tparams =
match Env.get_typedef env name with
| Some { td_tparams; _ } -> td_tparams
| None -> []
in
this_appears_covariantly_params tparams tyl
(** We know that the receiver is a concrete class, not a generic with
bounds, or a Tunion. *)
let rec obj_get_concrete_ty
args env concrete_ty ((id_pos, id_str) as id) on_error : internal_result =
log_obj_get env `concrete id_pos concrete_ty args.this_ty;
let dflt_rval_mismatch =
Option.map ~f:(fun (_, _, ty) -> Ok ty) args.coerce_from_ty
and dflt_lval_mismatch = Ok concrete_ty in
let default
?(lval_mismatch = dflt_lval_mismatch)
?(rval_mismatch = dflt_rval_mismatch)
ty_err_opt =
let (env, ty) = Env.fresh_type_error env id_pos in
(env, ty_err_opt, (ty, []), lval_mismatch, rval_mismatch)
in
let read_context = Option.is_none args.coerce_from_ty in
let (env, concrete_ty) = Env.expand_type env concrete_ty in
match deref concrete_ty with
| (r, Tclass ((_, class_name), _, paraml)) ->
obj_get_concrete_class
args
env
concrete_ty
(id_pos, id_str)
r
class_name
paraml
on_error
| (_, Tdynamic) ->
let err_opt =
if TypecheckerOptions.enable_sound_dynamic (Env.get_tcopt env) then
sound_dynamic_err_opt args env id read_context
else
None
in
let ty = MakeType.dynamic (Reason.Rdynamic_prop id_pos) in
(env, err_opt, (ty, []), dflt_lval_mismatch, dflt_rval_mismatch)
| (_, Tany _) ->
(env, None, (concrete_ty, []), dflt_lval_mismatch, dflt_rval_mismatch)
| (r, Tnonnull) ->
let ty_reasons =
match r with
| Reason.Ropaque_type_from_module _ ->
lazy (Reason.to_string "This type is mixed" r)
| _ -> lazy []
in
let ty_err =
Typing_error.(
primary
@@ Primary.Top_member
{
pos = id_pos;
name = id_str;
ctxt =
(if read_context then
`read
else
`write);
kind =
(if args.is_method then
`method_
else
`property);
is_nullable = false;
decl_pos = get_pos concrete_ty;
ty_name = lazy (Typing_print.error env concrete_ty);
ty_reasons;
})
in
let ty_nothing = MakeType.nothing Reason.none in
let lval_mismatch = Error (concrete_ty, ty_nothing) in
default ~lval_mismatch (Some ty_err)
| _ ->
let ty_err =
Typing_error.(
apply ~on_error
@@ primary
@@ Primary.Non_object_member
{
pos = id_pos;
ctxt =
(if read_context then
`read
else
`write);
kind =
(if args.is_method then
`method_
else
`property);
member_name = id_str;
ty_name = lazy (Typing_print.error env concrete_ty);
decl_pos = get_pos concrete_ty;
})
in
let ty_nothing = MakeType.nothing Reason.none in
let lval_mismatch = Error (concrete_ty, ty_nothing) in
default ~lval_mismatch (Some ty_err)
and get_member_from_constraints
args env class_info ((id_pos, _) as id) reason params on_error :
internal_result =
let ety_env = mk_ety_env class_info params args.this_ty in
let upper_bounds = Cls.upper_bounds_on_this class_info in
let ((env, upper_ty_errs), upper_bounds) =
List.map_env_ty_err_opt
env
upper_bounds
~f:(fun env up -> Phase.localize ~ety_env env up)
~combine_ty_errs:Typing_error.multiple_opt
in
let (env, inter_ty) =
Inter.intersect_list env (Reason.Rwitness id_pos) upper_bounds
in
merge_ty_err upper_ty_errs
@@ obj_get_inner
{
args with
nullsafe = None;
obj_pos = Reason.to_pos reason |> Pos_or_decl.unsafe_to_raw_pos;
is_nonnull = true;
}
env
inter_ty
id
on_error
and obj_get_concrete_class
args
env
concrete_ty
((id_pos, id_str) as id)
reason
class_name
params
on_error : internal_result =
match Env.get_class env class_name with
| None ->
let ty = MakeType.nothing (Reason.Rmissing_class id_pos) in
( env,
None,
(ty, []),
Ok concrete_ty,
Option.map ~f:(fun (_, _, ty) -> Ok ty) args.coerce_from_ty )
| Some class_info ->
let (env, params) =
if List.length params <> List.length (Cls.tparams class_info) then
(* We've already generated an arity error so just fill out params
* with error types *)
List.map_env env (Cls.tparams class_info) ~f:(fun env _ ->
Env.fresh_type_error env id_pos)
else
(env, params)
in
let old_member_info = Env.get_member args.is_method env class_info id_str in
let self_id = Option.value (Env.get_self_id env) ~default:"" in
let ancestor_tyargs =
match Cls.get_ancestor class_info self_id with
| Some self_class_type -> begin
match get_node self_class_type with
| Tapply (_, tyargs) -> Some tyargs
| _ -> None
end
| None ->
let all_reqs = Cls.all_ancestor_reqs class_info in
let filtered =
List.filter_map all_reqs ~f:(fun (_, ty) ->
match get_node ty with
| Tapply ((_, name), tyargs) when String.equal name self_id ->
Some tyargs
| _ -> None)
in
List.hd filtered
in
let (member_info, shadowed) =
match ancestor_tyargs with
| Some tyargs -> begin
(* We look up the current context to see if there is a field/method with
* private visibility. If there is one, that one takes precedence *)
match Env.get_self_class env with
| None -> (old_member_info, false)
| Some self_class -> begin
match Env.get_member args.is_method env self_class id_str with
| Some ({ ce_visibility = Vprivate _; _ } as ce) ->
let ce =
Decl_instantiate.(
instantiate_ce (make_subst (Cls.tparams self_class) tyargs) ce)
in
(* if a trait T has a require class C constraint, and both T and C
* define a private member with the same name, then the two members
* are aliased, not shadowed. In this case, self_class is the trait
* and the ancestor is the required class. We can set the `shadowed`
* bit by checking if self_class is a class or trait, there is
* no need to additionally check if the trait has a require class
* attribute. *)
(Some ce, Ast_defs.is_c_class (Cls.kind self_class))
| _ -> (old_member_info, false)
end
end
| None -> (old_member_info, false)
in
begin
match member_info with
| None ->
obj_get_concrete_class_without_member_info
args
env
concrete_ty
id
reason
class_info
params
on_error
| Some member_info ->
obj_get_concrete_class_with_member_info
args
env
concrete_ty
id
self_id
shadowed
reason
class_name
class_info
params
old_member_info
member_info
on_error
end
and obj_get_concrete_class_with_member_info
args
env
concrete_ty
((id_pos, id_str) as id)
self_id
shadowed
reason
class_name
class_info
params
old_member_info
member_info
on_error : internal_result =
let dflt_rval_mismatch =
Option.map ~f:(fun (_, _, ty) -> Ok ty) args.coerce_from_ty
and dflt_lval_mismatch = Ok concrete_ty in
let { ce_visibility = vis; ce_type = (lazy member_); ce_deprecated; _ } =
member_info
in
let mem_pos = get_pos member_ in
let ty_err_opts =
[
Option.bind old_member_info ~f:(fun old_member_info ->
if
shadowed
&& not
(String.equal member_info.ce_origin old_member_info.ce_origin)
then
let (lazy old_member) = old_member_info.ce_type in
Some
Typing_error.(
primary
@@ Primary.Ambiguous_object_access
{
pos = id_pos;
name = id_str;
self_pos = get_pos member_;
vis =
Typing_defs.string_of_visibility
old_member_info.ce_visibility;
subclass_pos = get_pos old_member;
class_self = self_id;
class_subclass = class_name;
})
else
None);
TVis.check_obj_access
~is_method:args.is_method
~use_pos:id_pos
~def_pos:mem_pos
env
vis;
TVis.check_deprecated ~use_pos:id_pos ~def_pos:mem_pos env ce_deprecated;
(if args.is_parent_call && get_ce_abstract member_info then
Some
Typing_error.(
primary
@@ Primary.Parent_abstract_call
{ meth_name = id_str; pos = id_pos; decl_pos = mem_pos })
else
None);
TVis.check_expression_tree_vis ~use_pos:id_pos ~def_pos:mem_pos env vis;
(if args.inst_meth then
TVis.check_inst_meth_access ~use_pos:id_pos ~def_pos:mem_pos vis
else
None);
(if
args.meth_caller
&& TypecheckerOptions.meth_caller_only_public_visibility
(Env.get_tcopt env)
then
TVis.check_meth_caller_access ~use_pos:id_pos ~def_pos:mem_pos vis
else
None);
]
in
let member_decl_ty = Typing_enum.member_type env member_info in
let widen_this = this_appears_covariantly ~contra:true env member_decl_ty in
let ety_env = mk_ety_env class_info params args.this_ty in
let ((env, lcl_ty_err_opt), member_ty, tal, et_enforced, lval_mismatch) =
match deref member_decl_ty with
| (r, Tfun ft) when args.is_method ->
(* We special case function types here to be able to pass explicit type
* parameters. *)
let ((env, lclz_ty_err_opt), explicit_targs) =
Phase.localize_targs
~check_well_kinded:true
~is_method:args.is_method
~use_pos:id_pos
~def_pos:mem_pos
~use_name:(strip_ns id_str)
env
ft.ft_tparams
(List.map ~f:snd args.explicit_targs)
in
let ft =
Typing_enforceability.compute_enforced_and_pessimize_fun_type
~this_class:(Some class_info)
env
ft
in
let ((env, ft1_ty_err_opt), ft1) =
Phase.(
localize_ft
~instantiation:
{ use_name = strip_ns id_str; use_pos = id_pos; explicit_targs }
~ety_env:{ ety_env with on_error = None }
~def_pos:mem_pos
env
ft)
in
let cross_pkg_error_opt =
TVis.check_cross_package
~use_pos:id_pos
~def_pos:mem_pos
env
ft.ft_cross_package
in
let should_wrap =
TypecheckerOptions.enable_sound_dynamic (Env.get_tcopt env)
&& get_ce_support_dynamic_type member_info
in
let (ft_ty1, lval_mismatch) =
let lval_mismatch =
if should_wrap then
(* If this is supportdyn, suppress the Hole on the receiver *)
dflt_lval_mismatch
else
(* Phase.localize_ft will report an error, generated in
Typing_generic_constraint.check_where_constraint,
if we have a 4323 *)
match ft1_ty_err_opt with
| Some _ -> Error (concrete_ty, MakeType.nothing Reason.none)
| _ -> dflt_lval_mismatch
in
( Typing_dynamic.maybe_wrap_with_supportdyn
~should_wrap
(Reason.localize r)
ft1,
lval_mismatch )
in
let ((env, ft_ty_err_opt), ft_ty) =
if widen_this then
let ety_env = { ety_env with this_ty = args.this_ty_conjunct } in
let ((env, ft2_ty_err_opt), ft2) =
Phase.(
localize_ft
~instantiation:
{
use_name = strip_ns id_str;
use_pos = id_pos;
explicit_targs;
}
~ety_env:{ ety_env with on_error = None }
~def_pos:mem_pos
env
ft)
in
let ft_ty2 =
Typing_dynamic.maybe_wrap_with_supportdyn
~should_wrap
(Reason.localize r)
ft2
in
let (env, ty) =
Inter.intersect_list env (Reason.localize r) [ft_ty1; ft_ty2]
in
(* TODO: should we be taking the intersection of the errors? *)
let ty_err_opt =
Option.merge ft1_ty_err_opt ft2_ty_err_opt ~f:(fun e1 e2 ->
Typing_error.multiple [e1; e2])
in
((env, ty_err_opt), ty)
else
((env, ft1_ty_err_opt), ft_ty1)
in
let ty_err_opt =
Option.merge lclz_ty_err_opt ft_ty_err_opt ~f:Typing_error.both
|> Option.merge cross_pkg_error_opt ~f:Typing_error.both
in
((env, ty_err_opt), ft_ty, explicit_targs, Unenforced, lval_mismatch)
| _ ->
let is_xhp_attr = Option.is_some (get_ce_xhp_attr member_info) in
let { et_type; et_enforced } =
Typing_enforceability.compute_enforced_and_pessimize_ty
~this_class:(Some class_info)
env
member_decl_ty
~explicitly_untrusted:is_xhp_attr
in
let (env, member_ty) = Phase.localize ~ety_env env et_type in
(* TODO(T52753871): same as for class_get *)
(env, member_ty, [], et_enforced, dflt_lval_mismatch)
in
let (env, (member_ty, tal)) =
if Cls.has_upper_bounds_on_this_from_constraints class_info then
let (env, (ty, tal), succeed) =
let res =
get_member_from_constraints
args
env
class_info
id
reason
params
on_error
in
match res with
| (env, None, ty, _, _) -> (env, ty, true)
| _ -> (env, (MakeType.mixed Reason.Rnone, []), false)
in
if succeed then
let (env, member_ty) =
Inter.intersect env ~r:(Reason.Rwitness id_pos) member_ty ty
in
(env, (member_ty, tal))
else
(env, (member_ty, tal))
else
(env, (member_ty, tal))
in
(* TODO: iterate over the returned error rather than side effecting on
error evaluation *)
let eff () =
let open Typing_env_types in
if Tast.is_under_dynamic_assumptions env.checked then
Typing_log.log_pessimise_prop
env
(Pos_or_decl.unsafe_to_raw_pos mem_pos)
id_str
in
let (env, coerce_ty_err_opt, rval_mismatch) =
Option.value_map
args.coerce_from_ty
~default:(env, None, dflt_rval_mismatch)
~f:(fun (p, ur, ty) ->
let err =
Typing_error.Callback.(
(with_side_effect ~eff unify_error [@alert "-deprecated"]))
in
let ety = { et_type = member_ty; et_enforced } in
let (env, coerce_ty_err_opt) =
Typing_coercion.coerce_type
p
ur
env
ty
(TUtils.make_like_if_enforced env ety)
err
in
let coerce_ty_mismatch =
match coerce_ty_err_opt with
| None -> Ok ty
| _ -> Error (ty, member_ty)
in
(env, coerce_ty_err_opt, Some coerce_ty_mismatch))
in
let ty_err_opt =
Typing_error.multiple_opt
@@ List.filter_map
~f:Fn.id
(lcl_ty_err_opt :: coerce_ty_err_opt :: ty_err_opts)
in
(env, ty_err_opt, (member_ty, tal), lval_mismatch, rval_mismatch)
and obj_get_concrete_class_without_member_info
args
env
concrete_ty
((id_pos, id_str) as id)
reason
class_info
params
on_error : internal_result =
let dflt_rval_mismatch =
Option.map ~f:(fun (_, _, ty) -> Ok ty) args.coerce_from_ty
and dflt_lval_mismatch = Ok concrete_ty in
let default
?(lval_mismatch = dflt_lval_mismatch)
?(rval_mismatch = dflt_rval_mismatch)
ty_err_opt =
let (env, ty) = Env.fresh_type_error env id_pos in
(env, ty_err_opt, (ty, []), lval_mismatch, rval_mismatch)
in
if Cls.has_upper_bounds_on_this_from_constraints class_info then
let res =
get_member_from_constraints args env class_info id reason params on_error
in
match res with
| (_, None, _, _, _) -> res
| _ ->
let err =
member_not_found
env
id_pos
~is_method:args.is_method
class_info
id_str
reason
on_error
in
let ty_nothing = MakeType.nothing Reason.none in
default ~lval_mismatch:(Error (concrete_ty, ty_nothing)) (Some err)
else if not args.is_method then
let (lval_mismatch, ty_err_opt) =
if not (SN.Members.is_special_xhp_attribute id_str) then
let err =
member_not_found
env
id_pos
~is_method:args.is_method
class_info
id_str
reason
on_error
in
let ty_nothing = MakeType.nothing Reason.none in
(Error (concrete_ty, ty_nothing), Some err)
else
(dflt_lval_mismatch, None)
in
default ~lval_mismatch ty_err_opt
else if String.equal id_str SN.Members.__clone then
(* Create a `public function __clone()[]: void {}` for classes that don't declare __clone *)
let ft =
{
ft_tparams = [];
ft_where_constraints = [];
ft_params = [];
ft_implicit_params =
{ capability = CapTy (MakeType.intersection Reason.Rnone []) };
ft_ret =
{ et_type = MakeType.void Reason.Rnone; et_enforced = Unenforced };
ft_flags = 0;
ft_ifc_decl = default_ifc_fun_decl;
ft_cross_package = None;
}
in
( env,
None,
(mk (Reason.Rnone, Tfun ft), []),
dflt_lval_mismatch,
dflt_rval_mismatch )
else if String.equal id_str SN.Members.__construct then
(* __construct is not an instance method and shouldn't be invoked directly
Note that we already raise a NAST check error in `illegal_name_check` but
we raise a related typing error here to properly keep track of failure.
We prefer a specific error here since the generic 4053 `MemberNotFound`
error, below, would be quite confusing telling us there is no instance
method `__construct` *)
let ty_err =
Typing_error.(primary @@ Primary.Construct_not_instance_method id_pos)
in
default (Some ty_err)
else
let ty_err =
member_not_found
env
id_pos
~is_method:args.is_method
class_info
id_str
reason
on_error
in
let ty_nothing = MakeType.nothing Reason.none in
default ~lval_mismatch:(Error (concrete_ty, ty_nothing)) (Some ty_err)
and nullable_obj_get
args env ety1 ((id_pos, id_str) as id) on_error ~read_context ty :
internal_result =
let (rcv_is_option, rcv_is_nothing) =
match deref ety1 with
| (_, Toption inner) ->
(match get_node inner with
| Tnonnull -> (false, true)
| _ -> (true, false))
| _ -> (false, false)
in
match args.nullsafe with
| Some r_null ->
let (env, ty_errs, (method_, tal), lval_mismatch, rval_mismatch) =
obj_get_inner args env ty id on_error
in
let (env, ty) =
match r_null with
| Reason.Rnullsafe_op p1 ->
make_nullable_member_type
~is_method:args.is_method
env
id_pos
p1
method_
| _ -> (env, method_)
in
(env, ty_errs, (ty, tal), lval_mismatch, rval_mismatch)
| None when rcv_is_option ->
(* Try to type this as though it were nullsafe *)
let (env, _ty_errs, (method_, tal), lval_mismatch, rval_mismatch) =
obj_get_inner args env ty id on_error
in
let r = get_reason ety1 in
(* If this _had_ been a nullsafe access and we would have reported no error
we special case the error and type mismatch here to get better
suggested types in holes *)
let ty_errs =
Typing_error.(
primary
@@ Primary.Null_member
{
pos = id_pos;
obj_pos_opt = Some args.obj_pos;
member_name = id_str;
reason = lazy (Reason.to_string "This can be null" r);
kind =
(if args.is_method then
`method_
else
`property);
ctxt =
(if read_context then
`read
else
`write);
})
in
let lval_mismatch =
match lval_mismatch with
| Ok _ -> Error (ety1, ty)
| Error (_, suggest) -> Error (ety1, suggest)
in
(env, Some ty_errs, (method_, tal), lval_mismatch, rval_mismatch)
| None ->
let (ty_expect, ty_err) =
let r = get_reason ety1 in
if rcv_is_nothing then
let ty_reasons =
match r with
| Reason.Ropaque_type_from_module _ ->
lazy (Reason.to_string "This type is mixed" r)
| _ -> lazy []
in
let ty_err =
Typing_error.(
primary
@@ Primary.Top_member
{
pos = id_pos;
name = id_str;
ctxt =
(if read_context then
`read
else
`write);
kind =
(if args.is_method then
`method_
else
`property);
is_nullable = true;
decl_pos = Reason.to_pos r;
ty_name = lazy (Typing_print.error env ety1);
ty_reasons;
})
in
(MakeType.nothing Reason.none, ty_err)
else
let ty_err =
Typing_error.(
primary
@@ Primary.Null_member
{
pos = id_pos;
obj_pos_opt = Some args.obj_pos;
member_name = id_str;
reason = lazy (Reason.to_string "This can be null" r);
kind =
(if args.is_method then
`method_
else
`property);
ctxt =
(if read_context then
`read
else
`write);
})
in
(MakeType.nothing Reason.none, ty_err)
in
let (env, ty) = Env.fresh_type_error env id_pos in
( env,
Some ty_err,
(ty, []),
Error (ety1, ty_expect),
Option.map ~f:(fun (_, _, ty) -> Ok ty) args.coerce_from_ty )
(* Helper method for obj_get that decomposes the type ty1.
* The additional parameter this_ty represents the type that will be substitued
* for `this` in the method signature.
*
* If ty1 is an intersection type, we distribute the member access through the
* conjuncts but maintain the intersection type for this_ty. For example,
* a call on (T & I & J) will recurse on T, I and J but with this_ty = (T & I & J),
* so that we don't "lose" information when substituting for `this`.
*
* In contrast, if ty1 is a union type, we recurse on the disjuncts but pass these
* through to this_ty, as the member access must be valid for each disjunct
* separately. Likewise for nullables (special case of union).
*)
and obj_get_inner args env receiver_ty ((id_pos, id_str) as id) on_error :
internal_result =
log_obj_get env `inner id_pos receiver_ty args.this_ty;
let (env, ety1') = Env.expand_type env receiver_ty in
let was_var = is_tyvar ety1' in
let dflt_rval_mismatch =
Option.map ~f:(fun (_, _, ty) -> Ok ty) args.coerce_from_ty
in
let ((env, expand_ty_err_opt), ety1) =
if args.is_method then
if TypecheckerOptions.method_call_inference (Env.get_tcopt env) then
let (env, ty) = Env.expand_type env receiver_ty in
((env, None), ty)
else
Typing_solver.expand_type_and_solve
env
~description_of_expected:"an object"
args.obj_pos
receiver_ty
else
Typing_solver.expand_type_and_narrow
env
~description_of_expected:"an object"
(widen_class_for_obj_get
~is_method:args.is_method
~nullsafe:args.nullsafe
id_str)
args.obj_pos
receiver_ty
in
let (env, ety1) =
if was_var then
Typing_dependent_type.ExprDepTy.make_with_dep_kind env args.dep_kind ety1
else
(env, ety1)
in
let nullable_obj_get ~read_context ty =
merge_ty_err expand_ty_err_opt
@@ nullable_obj_get
{ args with this_ty = ty; this_ty_conjunct = ty }
env
ety1
id
on_error
~read_context
ty
in
(* coerce_from_ty is used to store the source type for an assignment, so it
* is a useful marker for whether we're reading or writing *)
let read_context = Option.is_none args.coerce_from_ty in
match deref ety1 with
| (r, Tunion tyl) ->
(* Filter out null elements *)
let is_null ty =
let (_, _, ty) = TUtils.strip_supportdyn env ty in
match get_node ty with
| Tprim Tnull -> true
| _ -> false
in
let (tyl_null, tyl_nonnull) = List.partition_tf tyl ~f:is_null in
if List.is_empty tyl_null then
merge_ty_err expand_ty_err_opt
@@ obj_get_inner_union args env on_error id r tyl
else
nullable_obj_get ~read_context (MakeType.union r tyl_nonnull)
| (r, Tintersection tyl) ->
let (is_nonnull, subty_err_opt) =
if args.is_nonnull then
(true, None)
else
Typing_solver.is_sub_type env receiver_ty (MakeType.nonnull Reason.none)
in
let ty_err_opt =
Option.merge expand_ty_err_opt subty_err_opt ~f:Typing_error.both
in
merge_ty_err ty_err_opt
@@ obj_get_inner_intersection { args with is_nonnull } env on_error id r tyl
| (_, Tdependent (_, ty))
| (_, Tnewtype (_, _, ty)) ->
merge_ty_err expand_ty_err_opt @@ obj_get_inner args env ty id on_error
| (r, Tgeneric (name, _)) when not (SSet.mem name args.seen) ->
let args = { args with seen = SSet.add name args.seen } in
(match TUtils.get_concrete_supertypes ~abstract_enum:true env ety1 with
| (env, []) ->
let ctxt =
if read_context then
`read
else
`write
and kind =
if args.is_method then
`method_
else
`property
in
let ty_err =
Typing_error.(
apply ~on_error
@@ primary
@@ Primary.Non_object_member
{
pos = id_pos;
ctxt;
kind;
member_name = id_str;
ty_name = lazy (Typing_print.error env ety1);
decl_pos = Reason.to_pos r;
})
in
let ty_err_opt =
Option.merge expand_ty_err_opt (Some ty_err) ~f:Typing_error.both
in
let ty_nothing = MakeType.nothing Reason.none in
let lval_mismatch = Error (receiver_ty, ty_nothing) in
let (env, ty) = Env.fresh_type_error env id_pos in
(env, ty_err_opt, (ty, []), lval_mismatch, dflt_rval_mismatch)
| (env, tyl) ->
let (env, ty) = Inter.intersect_list env r tyl in
let (env, ty) =
if args.is_nonnull then
Typing_solver.non_null env (Pos_or_decl.of_raw_pos args.obj_pos) ty
else
(env, ty)
in
merge_ty_err expand_ty_err_opt @@ obj_get_inner args env ty id on_error)
| (_, Toption ty) -> nullable_obj_get ~read_context ty
| (r, Tprim Tnull) ->
let ty = mk (r, Tunion []) in
nullable_obj_get ~read_context ty
(* We are trying to access a member through a value of unknown type *)
| (r, Tvar _) ->
let ty_err_opt =
if TUtils.is_tyvar_error env ety1 then
None
else
Some
Typing_error.(
primary
@@ Primary.Unknown_object_member
{
elt =
(if args.is_method then
`meth
else
`prop);
member_name = id_str;
pos = id_pos;
reason = lazy (Reason.to_string "It is unknown" r);
})
in
let ty_err_opt =
Option.merge expand_ty_err_opt ty_err_opt ~f:Typing_error.both
in
let ty_nothing = MakeType.nothing Reason.none in
let (env, ty) = Env.fresh_type_error env id_pos in
( env,
ty_err_opt,
(ty, []),
Error (receiver_ty, ty_nothing),
dflt_rval_mismatch )
| (_, _) ->
merge_ty_err expand_ty_err_opt
@@ obj_get_concrete_ty args env ety1 id on_error
and obj_get_inner_union args env on_error id reason tys : internal_result =
let (env, ty_errs, resultl, lval_mismatches, rval_mismatch_opts) =
List.fold_left
tys
~init:(env, [], [], [], [])
~f:(fun (env, ty_errs, tys, lval_mismatches, rval_mismatch_opts) ty ->
let (env, ty_err, ty, lval_mismatch, rval_mismatch_opt) =
obj_get_inner
{ args with this_ty = ty; this_ty_conjunct = ty }
env
ty
id
on_error
in
( env,
ty_err :: ty_errs,
ty :: tys,
lval_mismatch :: lval_mismatches,
rval_mismatch_opt :: rval_mismatch_opts ))
in
let ty_err_opt = Typing_error.union_opt @@ List.filter_map ~f:Fn.id ty_errs in
let (env, lval_mismatch) =
mk_mismatch_union env @@ fold_mismatches lval_mismatches
in
let (env, rval_mismatch) =
Option.value_map ~default:(env, None) ~f:(fun res ->
let (env, r) = mk_mismatch_union env res in
(env, Some r))
@@ fold_mismatch_opts rval_mismatch_opts
in
(* TODO: decide what to do about methods with differing generic arity.
* See T55414751 *)
let tal =
match resultl with
| [] -> []
| (_, tal) :: _ -> tal
in
let tyl = List.map ~f:fst resultl in
let (env, ty) = Union.union_list env reason tyl in
(env, ty_err_opt, (ty, tal), lval_mismatch, rval_mismatch)
and obj_get_inner_intersection args env on_error id reason tys =
let ((env, ty_err_opt), res) =
TUtils.run_on_intersection_with_ty_err env tys ~f:(fun env ty ->
let (env, ty_err_opt, res, lval_mismatch, rval_mismatch) =
obj_get_inner { args with this_ty_conjunct = ty } env ty id on_error
in
((env, ty_err_opt), (res, lval_mismatch, rval_mismatch)))
in
let (resultl, lval_mismatches, rval_mismatch_opts) = List.unzip3 res in
let (env, lval_mismatch) =
mk_mismatch_intersection env @@ fold_mismatches lval_mismatches
in
let (env, rval_mismatch) =
Option.value_map ~default:(env, None) ~f:(fun res ->
let (env, err) = mk_mismatch_intersection env res in
(env, Some err))
@@ fold_mismatch_opts rval_mismatch_opts
in
(* TODO: decide what to do about methods with differing generic arity.
* See T55414751 *)
let tal =
match resultl with
| [] -> []
| (_, tal) :: _ -> tal
in
let tyl = List.map ~f:fst resultl in
let (env, ty) = Inter.intersect_list env reason tyl in
(env, ty_err_opt, (ty, tal), lval_mismatch, rval_mismatch)
(* Look up the type of the property or method id in the type receiver_ty of the
* receiver and use the function k to postprocess the result.
* Return any fresh type variables that were substituted for generic type
* parameters in the type of the property or method.
*
* Essentially, if receiver_ty is a concrete type, e.g., class C, then k is applied
* to the type of the property id in C; and if receiver_ty is an unresolved type,
* e.g., a union of classes (C1 | ... | Cn), then k is applied to the type
* of the property id in each Ci and the results are collected into an
* unresolved type.
*
*)
let obj_get_with_mismatches
~obj_pos
~is_method
~inst_meth
~meth_caller
~nullsafe
~coerce_from_ty
~explicit_targs
~class_id
~member_id
~on_error
?parent_ty
env
receiver_ty =
Typing_log.(
log_with_level env "obj_get" ~level:1 (fun () ->
log_types
(Pos_or_decl.of_raw_pos obj_pos)
env
[Log_head ("obj_get", [Log_type ("receiver_ty", receiver_ty)])]));
let ((env, e1), receiver_ty) =
if is_method then
Typing_solver.expand_type_and_solve
env
~description_of_expected:"an object"
obj_pos
receiver_ty
else
Typing_solver.expand_type_and_narrow
env
~description_of_expected:"an object"
(widen_class_for_obj_get ~is_method ~nullsafe (snd member_id))
obj_pos
receiver_ty
in
(* We will substitute `this` in the function signature with `this_ty`. But first,
* transform it according to the dependent kind dep_kind that was derived from the
* class_id in the original call to obj_get. See Typing_dependent_type.ml for
* more details.
*)
let dep_kind =
Typing_dependent_type.ExprDepTy.from_cid
env
(get_reason receiver_ty)
class_id
in
let (env, receiver_ty) =
Typing_dependent_type.ExprDepTy.make_with_dep_kind env dep_kind receiver_ty
in
let receiver_or_parent_ty =
match parent_ty with
| Some ty -> ty
| None -> receiver_ty
in
let is_parent_call = Nast.equal_class_id_ class_id Aast.CIparent in
let args =
{
inst_meth;
meth_caller;
is_method;
nullsafe;
obj_pos;
explicit_targs;
coerce_from_ty;
is_nonnull = false;
is_parent_call;
dep_kind;
this_ty = receiver_ty;
this_ty_conjunct = receiver_ty;
seen = SSet.empty;
}
in
let (env, e2, ty, lval_err, rval_err_opt) =
let (env, e2, ty, lvarl_err, rval_err_opt) =
obj_get_inner args env receiver_or_parent_ty member_id on_error
in
(* If we failed on a static receiver type in SDT dynamic method check, try again
* on dynamic, if the receiver type supports dynamic.
*)
if
Option.is_some e2
&& Tast.is_under_dynamic_assumptions env.Typing_env_types.checked
&& (not (is_dynamic receiver_or_parent_ty))
&& TUtils.is_sub_type
env
receiver_or_parent_ty
(MakeType.dynamic Reason.none)
then
obj_get_inner
args
env
(MakeType.dynamic (Reason.Rwitness obj_pos))
member_id
on_error
else
(env, e2, ty, lvarl_err, rval_err_opt)
in
let from_res = Result.fold ~ok:(fun _ -> None) ~error:(fun tys -> Some tys) in
let ty_err_opt = Option.merge e1 e2 ~f:Typing_error.both
and lval_err_opt = from_res lval_err
and rval_err_opt = Option.bind ~f:from_res rval_err_opt in
((env, ty_err_opt), ty, lval_err_opt, rval_err_opt)
(* Look up the type of the property or method id in the type receiver_ty of the
* receiver and use the function k to postprocess the result.
* Return any fresh type variables that were substituted for generic type
* parameters in the type of the property or method.
*
* Essentially, if receiver_ty is a concrete type, e.g., class C, then k is applied
* to the type of the property id in C; and if receiver_ty is an unresolved type,
* e.g., a union of classes (C1 | ... | Cn), then k is applied to the type
* of the property id in each Ci and the results are collected into an
* unresolved type.
*
*)
let obj_get
~obj_pos
~is_method
~inst_meth
~meth_caller
~nullsafe
~coerce_from_ty
~explicit_targs
~class_id
~member_id
~on_error
?parent_ty
env
receiver_ty =
let (env, ty, _lval_err_opt, _rval_err_opt) =
obj_get_with_mismatches
~obj_pos
~is_method
~inst_meth
~meth_caller
~nullsafe
~coerce_from_ty
~explicit_targs
~class_id
~member_id
~on_error
?parent_ty
env
receiver_ty
in
(env, ty) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_object_get.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(** Check member access, both static and instance.
* [obj_pos] is position of the object expression i.e. expr in expr->m
* [is_method] is true if this is a method invocation rather than property access
* [inst_meth] is true if this is an inst_meth expression
* [nullsafe] is Some r for null-safe calls such as expr?->m
* [parent_ty] is the type of the parent, in the case of a parent call (class_id = CIparent)
* [explicit_targs] is a list of explicit type argument expressions, if present
* [member_id] is positioned identifier for the member i.e. m in expr->m
* [on_error] is an error callback
*)
val obj_get :
obj_pos:Ast_defs.pos ->
is_method:bool ->
inst_meth:bool ->
meth_caller:bool ->
nullsafe:Typing_reason.t option ->
coerce_from_ty:
(Ast_defs.pos * Typing_reason.ureason * Typing_defs.locl_ty) option ->
explicit_targs:Nast.targ list ->
class_id:Nast.class_id_ ->
member_id:Nast.sid ->
on_error:Typing_error.Callback.t ->
?parent_ty:Typing_defs.locl_ty ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
(Typing_env_types.env * Typing_error.t option)
* (Typing_defs.locl_ty * Tast.targ list)
(** As above but also return the types at which
- we encountered an error based on the receiver's type, if at all
- coercion of `coerce_from_ty` to the object type failed, if at all *)
val obj_get_with_mismatches :
obj_pos:Ast_defs.pos ->
is_method:bool ->
inst_meth:bool ->
meth_caller:bool ->
nullsafe:Typing_reason.t option ->
coerce_from_ty:
(Ast_defs.pos * Typing_reason.ureason * Typing_defs.locl_ty) option ->
explicit_targs:Nast.targ list ->
class_id:Nast.class_id_ ->
member_id:Nast.sid ->
on_error:Typing_error.Callback.t ->
?parent_ty:Typing_defs.locl_ty ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
(Typing_env_types.env * Typing_error.t option)
* (Typing_defs.locl_ty * Tast.targ list)
* (Typing_defs.locl_ty * Typing_defs.locl_ty) option
* (Typing_defs.locl_ty * Typing_defs.locl_ty) option
val smember_not_found :
Ast_defs.pos ->
is_const:bool ->
is_method:bool ->
is_function_pointer:bool ->
Decl_provider.Class.t ->
string ->
Typing_error.Callback.t ->
Typing_error.t |
OCaml | hhvm/hphp/hack/src/typing/typing_ops.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
[@@@warning "-33"]
open Hh_prelude
[@@@warning "+33"]
open Typing_defs
module Reason = Typing_reason
(*****************************************************************************)
(* Exporting. *)
(*****************************************************************************)
let log_sub_type env p ty_sub ty_super =
let level =
if
not
(Typing_utils.is_capability_i ty_sub
|| Typing_utils.is_capability_i ty_super)
then
1
else
3
in
Typing_log.(
log_with_level env "sub" ~level (fun () ->
log_types
(Pos_or_decl.of_raw_pos p)
env
[
Log_head
( "Typing_ops.sub_type",
[
Log_type_i ("ty_sub", ty_sub);
Log_type_i ("ty_super", ty_super);
] );
]))
(* Tries to add constraint that ty_sub is subtype of ty_super in envs *)
let sub_type_i
?(is_coeffect = false)
p
ur
env
ty_sub
ty_super
(on_error : Typing_error.Callback.t) =
log_sub_type env p ty_sub ty_super;
Typing_utils.sub_type_i ~is_coeffect env ty_sub ty_super
@@ Some
(Typing_error.Reasons_callback.with_claim
on_error
~claim:(lazy (p, Reason.string_of_ureason ur)))
let sub_type p ur env ty_sub ty_super on_error =
sub_type_i p ur env (LoclType ty_sub) (LoclType ty_super) on_error
let sub_type_decl ?(is_coeffect = false) ~on_error p ur env ty_sub ty_super =
let localize_no_subst = Typing_utils.localize_no_subst ~ignore_errors:true in
let ((env, ty_err1), ty_super) = localize_no_subst env ty_super in
let ((env, ty_err2), ty_sub) = localize_no_subst env ty_sub in
let (env, ty_err3) =
Typing_utils.sub_type env ~is_coeffect ty_sub ty_super
@@ Some
(Typing_error.Reasons_callback.prepend_reason
on_error
~reason:(lazy (p, Reason.string_of_ureason ur)))
in
let ty_err_opt =
Typing_error.multiple_opt
@@ List.filter_map ~f:Fn.id [ty_err1; ty_err2; ty_err3]
in
(env, ty_err_opt)
(* Ensure that types are equivalent i.e. subtypes of each other *)
let unify_decl p ur env on_error ty1 ty2 =
let localize_no_subst = Typing_utils.localize_no_subst ~ignore_errors:true in
let ((env, ty_err1), ty1) = localize_no_subst env ty1 in
let ((env, ty_err2), ty2) = localize_no_subst env ty2 in
let reason = lazy (p, Reason.string_of_ureason ur) in
let (env, ty_err3) =
Typing_utils.sub_type env ty2 ty1
@@ Some (Typing_error.Reasons_callback.prepend_reason on_error ~reason)
in
let (env, ty_err4) =
Typing_utils.sub_type env ty1 ty2
@@ Some (Typing_error.Reasons_callback.prepend_reason on_error ~reason)
in
let ty_err_opt =
Typing_error.multiple_opt
@@ List.filter_map ~f:Fn.id [ty_err1; ty_err2; ty_err3; ty_err4]
in
(env, ty_err_opt) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_ops.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.
*
*)
(** Add constraint or check that ty_sub is subtype of ty_super in envs *)
val sub_type_i :
?is_coeffect:bool ->
Pos.t ->
Typing_reason.ureason ->
Typing_env_types.env ->
Typing_defs.internal_type ->
Typing_defs.internal_type ->
Typing_error.Callback.t ->
Typing_env_types.env * Typing_error.t option
val sub_type :
Pos.t ->
Typing_reason.ureason ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_defs.locl_ty ->
Typing_error.Callback.t ->
Typing_env_types.env * Typing_error.t option
val sub_type_decl :
?is_coeffect:bool ->
on_error:Typing_error.Reasons_callback.t ->
Pos_or_decl.t ->
Typing_reason.ureason ->
Typing_env_types.env ->
Typing_defs.decl_ty ->
Typing_defs.decl_ty ->
Typing_env_types.env * Typing_error.t option
val unify_decl :
Pos_or_decl.t ->
Typing_reason.ureason ->
Typing_env_types.env ->
Typing_error.Reasons_callback.t ->
Typing_defs.decl_ty ->
Typing_defs.decl_ty ->
Typing_env_types.env * Typing_error.t option |
OCaml | hhvm/hphp/hack/src/typing/typing_param.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
open Common
open Typing_defs
open Typing_helpers
module Reason = Typing_reason
module MakeType = Typing_make_type
module Phase = Typing_phase
module Env = Typing_env
let enforce_param_not_disposable env param ty =
if has_accept_disposable_attribute param then
None
else
Option.map
(Typing_disposable.is_disposable_type env ty)
~f:(fun class_name ->
Typing_error.Primary.Invalid_disposable_hint
{ pos = param.param_pos; class_name = Utils.strip_ns class_name })
let check_param_has_hint env param =
let prim_err_opt =
if Option.is_none (hint_of_type_hint param.param_type_hint) then
Some
(if param.param_is_variadic then
Typing_error.Primary.Expecting_type_hint_variadic param.param_pos
else
Typing_error.Primary.Expecting_type_hint param.param_pos)
else
None
in
Option.iter prim_err_opt ~f:(fun err ->
Typing_error_utils.add_typing_error ~env @@ Typing_error.primary err)
(* This function is used to determine the type of an argument.
* When we want to type-check the body of a function, we need to
* introduce the type of the arguments of the function in the environment
* Let's take an example, we want to check the code of foo:
*
* function foo(int $x): int {
* // CALL TO make_param_type on (int $x)
* // Now we know that the type of $x is int
*
* return $x; // in the environment $x is an int, the code is correct
* }
*
* When we localize, we want to resolve to "static" or "$this" depending on
* the context. Even though we are passing in CIstatic, resolve_with_class_id
* is smart enough to know what to do. Why do this? Consider the following
*
* abstract class C {
* abstract const type T;
*
* private this::T $val;
*
* final public function __construct(this::T $x) {
* $this->val = $x;
* }
*
* public static function create(this::T $x): this {
* return new static($x);
* }
* }
*
* class D extends C { const type T = int; }
*
* In __construct() we want to be able to assign $x to $this->val. The type of
* $this->val will expand to '$this::T', so we need $x to also be '$this::T'.
* We can do this soundly because when we construct a new class such as,
* 'new D(0)' we can determine the late static bound type (D) and resolve
* 'this::T' to 'D::T' which is int.
*
* A similar line of reasoning is applied for the static method create.
*)
let make_param_local_ty ~dynamic_mode ~no_auto_likes env decl_hint param =
(* Don't check (again) for existence of hint in dynamic mode *)
if not dynamic_mode then check_param_has_hint env param;
match decl_hint with
| None -> (env, None)
| Some hint ->
let ((env, ty_err_opt), ty) =
let { et_type = ty; et_enforced } =
Typing_enforceability.compute_enforced_and_pessimize_ty
~this_class:(Env.get_self_class env)
~explicitly_untrusted:param.param_is_variadic
env
hint
in
(match et_enforced with
| Unenforced ->
Typing_log.log_pessimise_param
env
~is_promoted_property:(Option.is_some param.param_visibility)
param.param_pos
param.param_callconv
param.param_name
| Enforced -> ());
(* If a non-inout parameter hint has the form ~t, where t is enforced,
* then we know that the parameter has type t after enforcement.
*)
let ty =
match (get_node ty, et_enforced, param.param_callconv) with
| (Tlike ty, Enforced, Ast_defs.Pnormal) -> ty
| _ -> ty
in
let ty =
if TypecheckerOptions.everything_sdt Typing_env_types.(env.genv.tcopt)
then
let ty =
(* For implicit pessimisation, wrap supportdyn around parameters with function types. *)
match get_node ty with
| Tfun _ ->
Typing_utils.make_supportdyn_decl_type
(get_pos ty)
(get_reason ty)
ty
| _ -> ty
in
(* For implicit pessimisation, without <<__NoAutoLikes>>, wrap like around non-enforced inout parameters *)
match (et_enforced, param.param_callconv) with
| (Unenforced, Ast_defs.Pinout _) when not no_auto_likes ->
MakeType.like (get_reason ty) ty
| _ -> ty
else
ty
in
Phase.localize_no_subst env ~ignore_errors:false ty
in
Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env);
let ty =
match get_node ty with
| t when param.param_is_variadic ->
(* when checking the body of a function with a variadic
* argument, "f(C ...$args)", $args is a vec<C> *)
let r = Reason.Rvar_param param.param_pos in
let arr_values = mk (r, t) in
MakeType.vec r arr_values
| _ -> ty
in
(* We do not permit hints to implement IDisposable or IAsyncDisposable *)
let prim_err_opt = enforce_param_not_disposable env param ty in
Option.iter prim_err_opt ~f:(fun err ->
Typing_error_utils.add_typing_error ~env @@ Typing_error.primary err);
(env, Some ty)
let make_param_local_tys ~dynamic_mode ~no_auto_likes env decl_tys params =
List.zip_exn params decl_tys
|> List.map_env env ~f:(fun env (param, hint) ->
let ty =
if dynamic_mode then
let dyn_ty =
MakeType.dynamic
(Reason.Rsupport_dynamic_type
(Pos_or_decl.of_raw_pos param.param_pos))
in
match hint with
| Some ty
when Typing_enforceability.is_enforceable
~this_class:(Env.get_self_class env)
env
ty ->
Some
(MakeType.intersection
(Reason.Rsupport_dynamic_type Pos_or_decl.none)
[ty; dyn_ty])
| _ -> Some dyn_ty
else
hint
in
make_param_local_ty ~dynamic_mode ~no_auto_likes env ty param) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_param.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val make_param_local_tys :
dynamic_mode:bool ->
no_auto_likes:bool ->
Typing_env_types.env ->
Typing_defs.decl_ty option list ->
Nast.fun_param list ->
Typing_env_types.env * Typing_defs.locl_ty option list |
OCaml | hhvm/hphp/hack/src/typing/typing_partial_enforcement.ml | (*
* Copyright (c) 2017, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Typing_defs
module Cls = Decl_provider.Class
module Env = Typing_env
module MakeType = Typing_make_type
(* For a decl type ty, return the type ety that the runtime will enforce.
* It's possible that ty </: ety because the runtime breaks through abstraction
* boundaries. For example, for enum E : int as arraykey
* we have get_enforced_type(E) = int, but E </: int.
*
* If ty=ety then we say that the type is "fully enforced"
* Resolve type parameters wrt to class_def_opt, if present
*)
let rec get_enforced_type env class_def_opt ty =
let default () = MakeType.mixed Reason.Rnone in
match get_node ty with
(* An enum type is enforced at its underlying type *)
| Tapply ((_, name), _) when Env.is_enum env name -> begin
match Env.get_class env name with
| None -> default ()
| Some tc ->
(match Cls.enum_type tc with
| None -> default ()
| Some e -> get_enforced_type env None e.te_base)
end
| Tapply ((_pos, name), tyargs) -> begin
match Env.get_class_or_typedef env name with
| Some (Env.ClassResult _class_info) ->
(* Non-generic types are fully enforced *)
if List.is_empty tyargs then
ty
(* Generic types are not enforced at their type arguments *)
else
default ()
| Some (Env.TypedefResult typedef_info) ->
(* Enforcement "sees through" type aliases and newtype, but does not instantiate generic arguments *)
(* The same is true of newtypes *)
get_enforced_type env None typedef_info.td_type
| None -> default ()
end
| Tgeneric (name, []) -> begin
match class_def_opt with
| None -> default ()
| Some cd ->
let tparams = Cls.tparams cd in
begin
match
List.find tparams ~f:(fun tp -> String.equal (snd tp.tp_name) name)
with
| None -> default ()
| Some tp ->
let bounds =
List.filter_map tp.tp_constraints ~f:(fun (cstr, ty) ->
match cstr with
| Ast_defs.Constraint_as
| Ast_defs.Constraint_eq -> begin
(* Do not follow bounds that are themselves generic parameters
* as HHVM doesn't enforce these *)
match get_node ty with
| Tgeneric _ -> None
| _ -> Some (get_enforced_type env class_def_opt ty)
end
| Ast_defs.Constraint_super -> None)
in
begin
match bounds with
| [] -> default ()
| [t] -> t
| ts -> MakeType.intersection Reason.Rnone ts
end
end
(* This is enforced but only at its class, which we can't express
* in Hack types. So we use the enclosing class as an approximation.
*)
end
| Tthis -> begin
match class_def_opt with
| None -> default ()
| Some cd ->
mk
( Reason.Rnone,
Tapply
( (Cls.pos cd, Cls.name cd),
List.map (Cls.tparams cd) ~f:(fun _ ->
(* TODO akenn *)
mk (Reason.Rnone, Tunion [])) ) )
end
| Toption t ->
let ety = get_enforced_type env class_def_opt t in
MakeType.nullable Reason.Rnone ety
| Tlike t -> get_enforced_type env class_def_opt t
(* Special case for intersections, as these are used to describe partial enforcement *)
| Tintersection tys ->
let tys = List.map tys ~f:(get_enforced_type env class_def_opt) in
MakeType.intersection (get_reason ty) tys
| Tshape _
| Ttuple _ ->
MakeType.nonnull Reason.Rnone
| Tprim _
| Tnonnull ->
ty
| _ -> default () |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_partial_enforcement.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val get_enforced_type :
Typing_env_types.env ->
Decl_provider.Class.t option ->
Typing_defs.decl_ty ->
Typing_defs.decl_ty |
OCaml | hhvm/hphp/hack/src/typing/typing_per_cont_env.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Common
module C = Typing_continuations
module CMap = C.Map
type per_cont_entry = {
(* Local types per continuation. For example, the local types of the
* break continuation correspond to the local types that there were at the
* last encountered break in the current scope. These are kept to be merged
* at the appropriate merge points. *)
local_types: Typing_local_types.t;
(* Fake members are used when we want member variables to be treated like
* locals. We want to handle the following:
* if($this->x) {
* ... $this->x ...
* }
* The trick consists in replacing $this->x with a "fake" local. So that
* all the logic that normally applies to locals is applied in cases like
* this. Hence the name: FakeMembers.
* All the fake members are thrown away at the first call.
* We keep the invalidated fake members for better error messages.
*)
fake_members: Typing_fake_members.t;
(* Type parameter environment
* Lower and upper bounds on generic type parameters and abstract types
* For constraints of the form Tu <: Tv where both Tu and Tv are type
* parameters, we store an upper bound for Tu and a lower bound for Tv.
* Contrasting with tenv and subst, bounds are *assumptions* for type
* inference, not conclusions.
*)
tpenv: Type_parameter_env.t;
}
type t = per_cont_entry C.Map.t
(*****************************************************************************)
(* Functions dealing with continuation based flow typing of local variables *)
(*****************************************************************************)
let empty_entry =
{
local_types = Typing_local_types.empty;
fake_members = Typing_fake_members.empty;
tpenv = Type_parameter_env.empty;
}
let initial_locals entry = CMap.add C.Next entry CMap.empty
let get_cont_option = CMap.find_opt
let all_continuations : t -> C.t list = C.Map.keys
(** Continuations used to typecheck the `finally` block. *)
let continuations_for_finally =
[C.Break; C.Continue; C.Catch; C.Exit; C.Finally]
(* Update an entry if it exists *)
let update_cont_entry name m f =
match CMap.find_opt name m with
| None -> m
| Some entry -> CMap.add name (f entry) m
let add_to_cont name key value m =
match CMap.find_opt name m with
| None -> m
| Some cont ->
let cont =
{ cont with local_types = Local_id.Map.add key value cont.local_types }
in
CMap.add name cont m
let remove_from_cont name key m =
match CMap.find_opt name m with
| None -> m
| Some c ->
CMap.add
name
{ c with local_types = Local_id.Map.remove key c.local_types }
m
let drop_cont = CMap.remove
let drop_conts conts map =
List.fold ~f:(fun map cont -> drop_cont cont map) ~init:map conts
let replace_cont key valueopt map =
match valueopt with
| None -> drop_cont key map
| Some value -> CMap.add key value map |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_per_cont_env.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(*****************************************************************************)
(* Functions dealing with continuation based flow typing of local variables *)
(*****************************************************************************)
module C = Typing_continuations
module CMap = C.Map
type per_cont_entry = {
(* Local types per continuation. For example, the local types of the
* break continuation correspond to the local types that there were at the
* last encountered break in the current scope. These are kept to be merged
* at the appropriate merge points. *)
local_types: Typing_local_types.t;
(* Fake members are used when we want member variables to be treated like
* locals. We want to handle the following:
* if($this->x) {
* ... $this->x ...
* }
* The trick consists in replacing $this->x with a "fake" local. So that
* all the logic that normally applies to locals is applied in cases like
* this. Hence the name: FakeMembers.
* All the fake members are thrown away at the first call.
* We keep the invalidated fake members for better error messages.
*)
fake_members: Typing_fake_members.t;
(* Type parameter environment
* Lower and upper bounds on generic type parameters and abstract types
* For constraints of the form Tu <: Tv where both Tu and Tv are type
* parameters, we store an upper bound for Tu and a lower bound for Tv.
* Contrasting with tenv and subst, bounds are *assumptions* for type
* inference, not conclusions.
*)
tpenv: Type_parameter_env.t;
}
type t = per_cont_entry Typing_continuations.Map.t
val initial_locals : per_cont_entry -> t
val empty_entry : per_cont_entry
(* Get a continuation wrapped in Some, or None if not found *)
val get_cont_option : C.t -> t -> per_cont_entry option
(** Get all continuations present in an environment *)
val all_continuations : t -> C.t list
(** Continuations used to typecheck the `finally` block. *)
val continuations_for_finally : C.t list
(* Add the key, value pair to the continuation named 'name'
* If the continuation doesn't exist, create it *)
val add_to_cont : C.t -> Local_id.t -> Typing_local_types.local -> t -> t
val update_cont_entry : C.t -> t -> (per_cont_entry -> per_cont_entry) -> t
(* remove a local from a continuation if it exists. Otherwise do nothing. *)
val remove_from_cont : C.t -> Local_id.t -> t -> t
(* Drop a continuation. If the continuation is absent, the map remains
* unchanged. *)
val drop_cont : C.t -> t -> t
val drop_conts : C.t list -> t -> t
val replace_cont : C.t -> per_cont_entry option -> t -> t |
OCaml | hhvm/hphp/hack/src/typing/typing_per_cont_ops.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Common
module C = Typing_continuations
module LMap = Local_id.Map
module LEnvC = Typing_per_cont_env
open LEnvC
type 'a locals_merge_fn =
'a ->
Typing_local_types.local ->
Typing_local_types.local ->
'a * Typing_local_types.local
(*****************************************************************************)
(* Functions dealing with continuation based flow typing of local variables *)
(*****************************************************************************)
let union union_types env context1 context2 =
let (env, local_types) =
LMap.merge_env
env
~combine:(fun env _ tyopt1 tyopt2 ->
match (tyopt1, tyopt2) with
| (Some ty1, Some ty2) ->
let (env, ty) = union_types env ty1 ty2 in
(env, Some ty)
| (Some local, None)
| (None, Some local) ->
(env, Some { local with Typing_local_types.defined = false })
| (None, None) -> (env, None))
(* TODO: we could do better here in case only in one side. *)
context1.local_types
context2.local_types
in
let (env, tpenv) =
Type_parameter_env_ops.join env context1.tpenv context2.tpenv
in
let fake_members =
Typing_fake_members.join context1.fake_members context2.fake_members
in
(env, { fake_members; local_types; tpenv })
let union_opts union_types env ctxopt1 ctxopt2 =
match (ctxopt1, ctxopt2) with
| (None, opt)
| (opt, None) ->
(env, opt)
| (Some ctx1, Some ctx2) ->
let (env, ctx) = union union_types env ctx1 ctx2 in
(env, Some ctx)
(* Does per-cont entry ctx1 entail ctx2?
* For locals, for each x:t2 in ctx2 we require x:t1 in ctx1 with t1 <: t2
* For fake member info, we delegate to Typing_fake_members.sub
* TODO: tpenv. Not clear what to do here, as we generate fresh type parameter names
* and so use of is_sub_entry for loop iteration would return false even if safe
*)
let is_sub_entry is_subtype env ctx1 ctx2 =
let open Typing_local_types in
LMap.for_all2
~f:(fun _k tyopt1 tyopt2 ->
match (tyopt1, tyopt2) with
| (None, None) -> true
| (Some local, None) -> not (Option.is_some local.bound_ty)
| (None, Some _) -> false
| ( Some { ty = ty1; defined = defined1; bound_ty = _; pos = _; eid = _ },
Some { ty = ty2; defined = defined2; bound_ty = _; pos = _; eid = _ }
) ->
(not defined2) || (defined1 && is_subtype env ty1 ty2))
ctx1.local_types
ctx2.local_types
&& Typing_fake_members.sub ctx1.fake_members ctx2.fake_members
let is_sub_opt_entry is_subtype env ctxopt1 ctxopt2 =
match (ctxopt1, ctxopt2) with
| (_, None) -> true
| (None, _) -> false
| (Some ctx1, Some ctx2) -> is_sub_entry is_subtype env ctx1 ctx2
(* Union a list of continuations *)
let union_conts env union_types local_types cont_list =
let union_two env locals cont =
union_opts union_types env locals (CMap.find_opt cont local_types)
in
List.fold_left_env env cont_list ~f:union_two ~init:None
(* Union a list of source continuations and store the result in a
* destination continuation. *)
let union_conts_and_update env union_types local_types ~from_conts ~to_cont =
let (env, unioned) = union_conts env union_types local_types from_conts in
(env, replace_cont to_cont unioned local_types)
let update_next_from_conts env union_types local_types cont_list =
union_conts_and_update
env
union_types
local_types
~from_conts:cont_list
~to_cont:C.Next
let save_and_merge_next_in_cont env union_types local_types cont =
union_conts_and_update
env
union_types
local_types
~from_conts:[C.Next; cont]
~to_cont:cont
let move_and_merge_next_in_cont env union_types local_types cont =
let (env, locals) =
save_and_merge_next_in_cont env union_types local_types cont
in
(env, drop_cont C.Next locals)
let union_by_cont env union_types locals1 locals2 =
CMap.union_env env locals1 locals2 ~combine:(fun env _ cont1 cont2 ->
let (env, ctx) = union union_types env cont1 cont2 in
(env, Some ctx))
let restore_cont_from locals ~from:source_locals cont =
let ctxopt = get_cont_option cont source_locals in
replace_cont cont ctxopt locals
let restore_conts_from locals ~from conts =
List.fold ~f:(restore_cont_from ~from) ~init:locals conts
let restore_and_merge_cont_from env union_types locals ~from cont =
let ctxfromopt = get_cont_option cont from in
let ctxtoopt = get_cont_option cont locals in
let (env, newctxopt) = union_opts union_types env ctxfromopt ctxtoopt in
(env, replace_cont cont newctxopt locals)
let restore_and_merge_conts_from env union_types locals ~from conts =
List.fold_left_env
env
~f:(fun env locals cont ->
restore_and_merge_cont_from env union_types locals ~from cont)
~init:locals
conts |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_per_cont_ops.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(*****************************************************************************)
(* Functions dealing with continuation based flow typing of local variables *)
(*****************************************************************************)
open Typing_env_types
module C = Typing_continuations
module LEnvC = Typing_per_cont_env
(* Takes two continuation maps m1 (`locals`) and m2 (`source_locals`) and
* a continuation c (`cont`) and basically perform m1[c] <= m2[c].
*
* When entering certain control flow structures, certain
* preexisting continuations must be stashed away and then _restored_
* via this function on exiting those control flow structures.
*
* For example, on entering a loop, preexisting 'break' and 'continue'
* continuations from any enclosing loops must be stashed away so as not to
* interfere with them. *)
val restore_conts_from : LEnvC.t -> from:LEnvC.t -> C.t list -> LEnvC.t
type 'a locals_merge_fn =
'a ->
Typing_local_types.local ->
Typing_local_types.local ->
'a * Typing_local_types.local
(* Same as restore_conts_from, except continuations from the 'from' locals
* are unioned with the continuations from the current environment. This is
* used after typechecking a try-catch-finally statement, as continuations
* may be used outside of this statement *)
val restore_and_merge_conts_from :
env ->
env locals_merge_fn ->
LEnvC.t ->
from:LEnvC.t ->
C.t list ->
env * LEnvC.t
(* Merge all continuations in the provided list and update the next
* continuation with the result.
*
* This is used at certain merge points in the control flow. For example,
* after a loop, we want to merge the 'break' continuation into the 'next'
* continuation, or at the beginning of a loop block, we merge the 'continue'
* continuation into the 'next' continuation. *)
val update_next_from_conts :
env -> env locals_merge_fn -> LEnvC.t -> C.Map.key list -> env * LEnvC.t
(* After this call, the provided continuation will be the union of
* itself and the next continuation.
*
* This is used at split points in the control flow.
* For example, if we encounter a function call that may throw an exception,
* we "save" the 'next' continuation by "merging" it into the 'catch'
* continuation.
*)
val save_and_merge_next_in_cont :
env -> env locals_merge_fn -> LEnvC.t -> C.Map.key -> env * LEnvC.t
(* union the provided continuation with the next continuation and store
* the result in the provided continuation. Finally, remove the next
* continuation.
*
* This is used at jump points in the control flow.
* For example, when we encounter a 'continue' statement, we "move" the 'next'
* continuation by "merging" it into the 'continue' continuation.
*)
val move_and_merge_next_in_cont :
env -> env locals_merge_fn -> LEnvC.t -> C.Map.key -> env * LEnvC.t
(* Unions two context options. We call "context" here a map from locals to
* types.
* Intersect the set of keys, and for each key in both contexts, union their
* associated types.
* More formally, the union c1 & c2 of contexts
* c1 and c2 is defined as:
* (x: T) belongs to c1 & c2 iif there exist T1, T2 such that:
* - (x: T1) belongs to c1
* - (x: T2) belongs to c2
* - T = T1 | T2
*
* Example:
* context1 = { x: A, y: B }
* context2 = { z: C, y: D }
* union context1 context2 = { y: (B|D) }
*)
val union_opts :
env locals_merge_fn ->
env ->
LEnvC.per_cont_entry option ->
LEnvC.per_cont_entry option ->
env * LEnvC.per_cont_entry option
val is_sub_opt_entry :
(env -> Typing_defs.locl_ty -> Typing_defs.locl_ty -> bool) ->
env ->
LEnvC.per_cont_entry option ->
LEnvC.per_cont_entry option ->
bool
(* union all continuations pairwise from two continuation maps.
* This is used at certain merge points in the control flow,
* typically after an `if` or a `switch` statement.
*
* Example:
* locals1 = {
* Next: { x: A, y: B },
* Continue: { x: A, y: B },
* Break: { x: A, y: B },
* }
* locals2 = {
* Next: { z: C, y: D },
* Continue: { z: C, y: D },
* Catch: { z: C, y: D },
* }
* union_by_cont locals1 locals2 = {
* Next: { y: (B|D) },
* Continue: { y: (B|D) },
* Break: { x: A, y: B },
* Catch: { z: C, y: D },
* }
*)
val union_by_cont :
env -> env locals_merge_fn -> LEnvC.t -> LEnvC.t -> env * LEnvC.t |
OCaml | hhvm/hphp/hack/src/typing/typing_phase.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Common
open Typing_defs
open Typing_env_types
module Env = Typing_env
module TUtils = Typing_utils
module TGenConstraint = Typing_generic_constraint
module Subst = Decl_subst
module MakeType = Typing_make_type
module Cls = Decl_provider.Class
module KindDefs = Typing_kinding_defs
module Kinding = Typing_kinding
module SN = Naming_special_names
(* Here is the general problem the delayed application of the phase solves.
* Let's say you have a function that you want to operate generically across
* phases. In most cases when you do this you can use the 'ty' GADT and locally
* abstract types to write code in a phase agonistic way.
*
* let yell_any: type a. a ty -> string = fun ty ->
* match ty with
* | _, Tany -> "Any"
* | _ -> ""
*
* Now let's add a function that works for all phases, but whose logic is phase
* dependent. For this we can use 'phase_ty' ADT:
*
* let yell_locl phase_ty =
* match phase_ty with
* | DeclTy ty -> ""
* | LoclTy ty -> "Locl"
*
* Let's say you want to write a function that has behavior that works across
* phases, but needs to invoke a function that is phase dependent. Our options
* are as follows.
*
* let yell_any_or_locl phase_ty =
* let ans = yell_locl phase_ty in
* match phase_ty with
* | DeclTy ty -> ans ^ (yell_any ty)
* | LoclTy ty -> ans ^ (yell_any ty)
*
* This would lead to code duplication since we can't generically operate on the
* underlying 'ty' GADT. If we want to eliminate this code duplication there are
* two options.
*
* let generic_ty: type a. phase_ty -> a ty = function
* | DeclTy ty -> ty
* | LoclTy ty -> ty
*
* let yell_any_or_locl phase_ty =
* let ans = yell_locl phase_ty in
* ans ^ (yell_any (generic_ty phase_ty))
*
* generic_ty allows us to extract a generic value which we can use. This
* approach is limiting because we lose all information about what phase 'a ty
* is.
*
* The other approach is to pass in a function that goes from 'a ty -> phase_ty'
*
* let yell_any_or_locl phase ty =
* let ans = yell_locl (phase ty) in
* ans ^ (yell_any ty)
*
* Here we can use 'ty' generically (without losing information about what phase
* 'a ty' is), and we rely on the caller passing in an appropriate function that
* converts into the 'phase_ty' when we need to hop into phase specific code.
*)
let decl ty = DeclTy ty
let locl ty = LoclTy ty
type method_instantiation = {
use_pos: Pos.t;
use_name: string;
explicit_targs: Tast.targ list;
}
(*****************************************************************************)
(* Localization caching. *)
(*****************************************************************************)
module type CACHESETTINGS = sig
val capacity : int
val node_count_threshold : int
end
module MakeTyCache (Settings : CACHESETTINGS) : sig
val add : env -> string -> locl_ty -> unit
val get : env -> string -> locl_ty option
end = struct
include
Lru.M.Make
(String)
(struct
type t = locl_ty
let weight _ = 1
end)
let cache = create Settings.capacity
let should_cache_type lty =
let exception NodeLimitReached in
let size_visitor =
object
inherit [int] Type_visitor.locl_type_visitor as super
method! on_type acc ty =
if acc >= Settings.node_count_threshold then raise NodeLimitReached;
super#on_type (acc + 1) ty
end
in
match size_visitor#on_type 0 lty with
| _count -> false
| exception NodeLimitReached -> true
let clear () =
(* The only reliable way to empty the LRU cache. *)
resize 0 cache;
trim cache;
resize Settings.capacity cache;
assert (is_empty cache)
let active_context = ref (Relative_path.default, None)
(* We invalidate the cache as soon as we are processing a new file or
* module because those affect how types are expanded (e.g., newtypes
* are unfolded only in the file that defines them). *)
let maybe_invalidate env =
let context = (Env.get_file env, Env.get_current_module env) in
let valid =
[%eq: Relative_path.t * string option] !active_context context
in
if not valid then begin
active_context := context;
clear ()
end
let add env alias lty =
let () = maybe_invalidate env in
if should_cache_type lty then begin
add alias lty cache;
trim cache
end
let get env alias =
let () = maybe_invalidate env in
promote alias cache;
find alias cache
end
(* Since the typechecker options defining the cache parameters will be
* available only when we have an environment, the add/get functions are
* stored in references initially set to stubs that update themselves
* during their first call. *)
let rec locl_cache_add =
ref (fun env ->
setup_cache env;
!locl_cache_add env)
and locl_cache_get =
ref (fun env ->
setup_cache env;
!locl_cache_get env)
and setup_cache env =
let tcopts = Env.get_tcopt env in
let module Settings = struct
let capacity = TypecheckerOptions.locl_cache_capacity tcopts
let node_count_threshold =
TypecheckerOptions.locl_cache_node_threshold tcopts
end in
let module Cache = MakeTyCache (Settings) in
locl_cache_add := Cache.add;
locl_cache_get := Cache.get
(*****************************************************************************)
(* Transforms a declaration phase type into a localized type. This performs
* common operations that are necessary for this operation, specifically:
* > Expand newtype/types
* > Resolves the "this" type
* > Instantiate generics
* > ...
*
* When keep track of additional information while localizing a type such as
* what type defs were expanded to detect potentially recursive definitions..
*)
(*****************************************************************************)
let rec localize ~(ety_env : expand_env) env (dty : decl_ty) =
(fun ((env, ty_err_opt), ty) ->
let (env, ty) = Typing_log.log_localize ~level:1 ety_env dty (env, ty) in
((env, ty_err_opt), ty))
@@
let rec find_origin dty =
match get_node dty with
| Taccess (root_ty, (_pos, id)) ->
Option.map ~f:(fun orig -> orig ^ "::" ^ id) (find_origin root_ty)
| Tapply ((_pos, cid), []) -> Some cid
| _ -> None
in
let set_origin_and_cache origin_opt final_env ty_err_opt lty =
(* When the type resulting from the localize call originates from a
* decl type with a succinct unambiguous form (e.g., Cls or Cls::T) we
* store a serialized version of the decl alias in an *origin* field
* of the locl type returned. Currently, only shape types have an
* origin field. *)
let cache_result () =
(* Under the following conditions we may cache the localized
* type:
*
* 1/ We did not encounter cycles during expansion,
* 2/ localization was error-free,
* 3/ we are expanding under regular assumptions (local
* newtypes are visible), and
* 4/ the expansion has not created new global type params.
*
* Case 4 happens when we bogusly create type params for
* abstract type constants.
* Cycles are not reported systematically as errors, so we
* track them separately with a reference in ety_env. *)
let no_new_global_type_params =
Type_parameter_env.size final_env.tpenv
<= Type_parameter_env.size env.tpenv
in
(not (Typing_defs.cyclic_expansion ety_env))
&& Option.is_none ty_err_opt
&& ety_env.expand_visible_newtype
&& no_new_global_type_params
in
match deref lty with
| ( r,
Tshape
{
s_origin = _;
s_unknown_value = shape_kind;
s_fields = shape_fields;
} ) -> begin
match origin_opt with
| None -> lty
| Some origin ->
let lty =
mk
( r,
Tshape
{
s_origin = From_alias origin;
s_unknown_value = shape_kind;
s_fields = shape_fields;
} )
in
if cache_result () then !locl_cache_add env origin lty;
lty
end
| _ -> lty
in
let push_supportdyn_into_shape lty =
let (is_supportdyn, _env, stripped_lty) = TUtils.strip_supportdyn env lty in
match deref stripped_lty with
| ( r,
Tshape
{ s_origin = origin; s_unknown_value = ty; s_fields = shape_fields }
)
when is_supportdyn ->
MakeType.supportdyn
r
(mk
( r,
Tshape
{
s_origin = origin;
s_unknown_value = MakeType.supportdyn r ty;
s_fields = shape_fields;
} ))
| _ -> lty
in
let r = get_reason dty |> Typing_reason.localize in
match get_node dty with
| Trefinement (root, cr) -> localize_refinement ~ety_env env r root cr
| (Tnonnull | Tprim _ | Tdynamic | Tany _) as x -> ((env, None), mk (r, x))
| Tmixed -> ((env, None), MakeType.mixed r)
| Tthis ->
let ty =
map_reason ety_env.this_ty ~f:(function
| Reason.Rnone -> r
| Reason.Rexpr_dep_type (_, pos, s) ->
Reason.Rexpr_dep_type (r, pos, s)
| reason -> Reason.Rinstantiate (reason, SN.Typehints.this, r))
in
((env, None), ty)
| Tvec_or_dict (tk, tv) ->
let ((env, e1), tk) = localize ~ety_env env tk in
let ((env, e2), tv) = localize ~ety_env env tv in
let ty = Tvec_or_dict (tk, tv) in
let ty_err_opt = Option.merge e1 e2 ~f:Typing_error.both in
((env, ty_err_opt), mk (r, ty))
| Tgeneric (x, targs) ->
let localize_tgeneric ?replace_with name r =
match (targs, replace_with, Env.get_pos_and_kind_of_generic env name) with
| (_, _, Some (_def_pos, kind)) ->
let arg_kinds : KindDefs.Simple.named_kind list =
KindDefs.Simple.from_full_kind kind
|> KindDefs.Simple.get_named_parameter_kinds
in
begin
match
( localize_targs_by_kind
~ety_env:{ ety_env with expand_visible_newtype = true }
env
targs
arg_kinds,
replace_with )
with
| ((env, _), Some repl_ty) -> (env, mk (r, repl_ty))
| ((env, locl_tyargs), None) ->
(env, mk (r, Tgeneric (name, locl_tyargs)))
end
| ([], None, None) ->
(* No kinding info, but also no type arguments. Just return Tgeneric *)
((env, None), mk (r, Tgeneric (x, [])))
| ([], Some repl_ty, None) -> ((env, None), mk (r, repl_ty))
| (_ :: _, _, None) ->
(* No kinding info, but type arguments given. We don't know the kinds of the arguments,
so we can't localize them. Not much we can do. *)
let (env, ty) = Env.fresh_type_error env Pos.none in
((env, None), ty)
in
begin
match SMap.find_opt x ety_env.substs with
| Some x_ty ->
let (env, x_ty) = Env.expand_type env x_ty in
let r_inst = Reason.Rinstantiate (get_reason x_ty, x, r) in
begin
match (targs, get_node x_ty) with
| (_ :: _, Tclass (((_, name) as id), _, [])) ->
let class_info = Env.get_class env name in
localize_class_instantiation ~ety_env env r_inst id targs class_info
| (_ :: _, Tnewtype (id, [], _))
| (_ :: _, Tunapplied_alias id) ->
localize_typedef_instantiation
~ety_env
env
r_inst
(get_reason dty)
id
targs
(Env.get_typedef env id)
| (_ :: _, Tgeneric (x', [])) -> localize_tgeneric x' r_inst
| (_, ty_) -> ((env, None), mk (r_inst, ty_))
end
| None -> localize_tgeneric x r
end
| Toption ty ->
let ((env, ty_err_opt), ty) = localize ~ety_env env ty in
(* Calling into the union module here would cost 2% perf regression on a full init,
* so we use this lightweight version instead. *)
let union_null env ty =
let rec null_is_subtype_of ty =
match get_node ty with
| Toption _
| Tprim Aast.Tnull ->
true
| Tunion tyl -> List.exists tyl ~f:null_is_subtype_of
| Tintersection tyl -> List.for_all tyl ~f:null_is_subtype_of
| _ -> false
in
if null_is_subtype_of ty then
(env, ty)
else
MakeType.nullable r ty |> TUtils.wrap_union_inter_ty_in_var env r
in
let (env, ty) = union_null env ty in
((env, ty_err_opt), ty)
| Tlike ty ->
let ((env, ty_err_opt), ty) = localize ~ety_env env ty in
let lty = MakeType.locl_like r ty in
((env, ty_err_opt), lty)
| Tfun ft ->
let pos = Reason.to_pos r in
let (env, ft) = localize_ft ~ety_env ~def_pos:pos env ft in
(env, mk (r, Tfun ft))
| Tapply ((_, x), [arg]) when String.equal x SN.HH.FIXME.tTanyMarker ->
if TypecheckerOptions.enable_sound_dynamic (Env.get_tcopt env) then
localize ~ety_env env arg
else
((env, None), mk (r, TUtils.tany env))
| Tapply ((_, x), [arg]) when String.equal x SN.HH.FIXME.tPoisonMarker ->
let decl_ty =
if TypecheckerOptions.enable_sound_dynamic (Env.get_tcopt env) then
mk (get_reason dty, Tlike arg)
else
arg
in
localize ~ety_env env decl_ty
| Twildcard -> begin
match ety_env.wildcard_action with
(* Generate a fresh type variable *)
| Wildcard_fresh_tyvar ->
let (env, ty) =
Env.fresh_type env (Pos_or_decl.unsafe_to_raw_pos (Reason.to_pos r))
in
((env, None), ty)
(* Produce an error: wildcard is not allowed in this position *)
| Wildcard_require_explicit tparam ->
let (decl_pos, param_name) = tparam.tp_name in
let err_opt =
Some
Typing_error.(
primary
@@ Primary.Require_generic_explicit
{
decl_pos;
param_name;
pos = Pos_or_decl.unsafe_to_raw_pos (Reason.to_pos r);
})
in
let (env, ty) =
Env.fresh_type_error
env
(Pos_or_decl.unsafe_to_raw_pos (Reason.to_pos r))
in
((env, err_opt), ty)
(* All should have been dealt with already:
* (1) Wildcard_fresh_generic and Wildcard_fresh_generic_type_argument, in localize_targ_by_kind.
* (2) Wildcard_illegal, in the naming phase.
* (3) Wildcard_higher_kinded_placeholder, in Typing_kinding.ml
*)
| Wildcard_fresh_generic
| Wildcard_fresh_generic_type_argument
| Wildcard_illegal
| Wildcard_higher_kinded_placeholder ->
let (env, ty) =
Env.fresh_type_error
env
(Pos_or_decl.unsafe_to_raw_pos (Reason.to_pos r))
in
((env, None), ty)
end
| Tapply (((_p, cid) as cls), argl) ->
let (env_err, lty) =
match Env.get_class_or_typedef env cid with
| Some (Env.ClassResult class_info) ->
localize_class_instantiation ~ety_env env r cls argl (Some class_info)
| Some (Env.TypedefResult typedef_info) ->
let origin_opt = find_origin dty in
let ((env, ty_err_opt), lty) =
match Option.bind origin_opt ~f:(!locl_cache_get env) with
| Some lty -> ((env, None), with_reason lty r)
| None ->
localize_typedef_instantiation
~ety_env
env
r
(get_reason dty)
cid
argl
(Some typedef_info)
in
let lty = set_origin_and_cache origin_opt env ty_err_opt lty in
((env, ty_err_opt), lty)
| None -> localize_class_instantiation ~ety_env env r cls argl None
in
let lty =
(* If we have supportdyn<t> then push supportdyn into open shape fields *)
if String.equal cid SN.Classes.cSupportDyn then
push_supportdyn_into_shape lty
else
lty
in
(env_err, lty)
| Ttuple tyl ->
let (env, tyl) =
List.map_env_ty_err_opt
env
tyl
~f:(localize ~ety_env)
~combine_ty_errs:Typing_error.multiple_opt
in
(env, mk (r, Ttuple tyl))
| Tunion tyl ->
let ((env, ty_err_opt), tyl) =
List.map_env_ty_err_opt
env
tyl
~f:(localize ~ety_env)
~combine_ty_errs:Typing_error.union_opt
in
let (env, ty) = Typing_union.union_list env r tyl in
((env, ty_err_opt), ty)
| Tintersection tyl ->
let ((env, ty_err_opt), tyl) =
List.map_env_ty_err_opt
env
tyl
~f:(localize ~ety_env)
~combine_ty_errs:Typing_error.multiple_opt
in
let (env, ty) = Typing_intersection.intersect_list env r tyl in
((env, ty_err_opt), ty)
| Taccess (root_ty, id) ->
let origin_opt = find_origin dty in
(match Option.bind origin_opt ~f:(!locl_cache_get env) with
| Some lty -> ((env, None), with_reason lty r)
| None ->
let rec allow_abstract_tconst ty =
match get_node ty with
| Tthis
| Tgeneric _ ->
(*
* When the root of an access is 'this', abstract type constants
* are allowed and localized as rigid type variables (Tgeneric).
* This happens when typing generic code in an abstract class
* that deals with data whose type is going to be set later in
* derived classes.
*
* In case the root is a generic, we also accept accesses to
* abstract constant to type check the dangerous and ubiquitous
* pattern:
*
* function get<TBox as Box, T>(TBox $foo) : T where T = TBox::T
* ^^^^^^^
*)
true
| Taccess (ty, _) -> allow_abstract_tconst ty
| _ -> false
in
let allow_abstract_tconst = allow_abstract_tconst root_ty in
let ((env, e1), root_ty) = localize ~ety_env env root_ty in
let ((env, e2), ty) =
TUtils.expand_typeconst ety_env env root_ty id ~allow_abstract_tconst
in
(* Elaborate reason with information about expression dependent types and
* the original location of the Taccess type
*)
let ty_err_opt = Option.merge e1 e2 ~f:Typing_error.both in
let ty = set_origin_and_cache origin_opt env ty_err_opt ty in
let elaborate_reason expand_reason =
let taccess_string =
lazy (Typing_print.full_strip_ns env root_ty ^ "::" ^ snd id)
in
(* If the root is an expression dependent type, change the primary
* reason to be for the full Taccess type to preserve the position where
* the expression dependent type was derived from.
*)
let reason =
match get_reason root_ty with
| Reason.Rexpr_dep_type (_, p, e) -> Reason.Rexpr_dep_type (r, p, e)
| _ -> r
in
Reason.Rtype_access (expand_reason, [(reason, taccess_string)])
in
let ty = map_reason ty ~f:elaborate_reason in
((env, ty_err_opt), ty))
| Tshape { s_origin = _; s_unknown_value = shape_kind; s_fields = tym } ->
let ((env, ty_err_opt1), tym) =
ShapeFieldMap.map_env_ty_err_opt
(localize ~ety_env)
env
tym
~combine_ty_errs:Typing_error.multiple_opt
in
let ((env, ty_err_opt2), shape_kind) = localize ~ety_env env shape_kind in
let ty_err_opt =
Option.merge ty_err_opt1 ty_err_opt2 ~f:Typing_error.both
in
( (env, ty_err_opt),
mk
( r,
Tshape
{
s_origin = Missing_origin;
s_unknown_value = shape_kind;
s_fields = tym;
} ) )
| Tnewtype (name, tyl, ty) ->
let td =
Utils.unsafe_opt @@ Decl_provider.get_typedef (Env.get_ctx env) name
in
let should_expand =
Env.is_typedef_visible
env
~expand_visible_newtype:ety_env.expand_visible_newtype
~name
td
in
if should_expand then
let decl_pos = Reason.to_pos r in
let (ety_env, has_cycle) =
Typing_defs.add_type_expansion_check_cycles ety_env (decl_pos, name)
in
match has_cycle with
| Some initial_taccess_pos_opt ->
let ty_err_opt =
Option.map initial_taccess_pos_opt ~f:(fun initial_taccess_pos ->
Typing_error.(
primary
@@ Primary.Cyclic_typedef
{ pos = initial_taccess_pos; decl_pos }))
in
let (env, ty) =
Env.fresh_type_error env (Pos_or_decl.unsafe_to_raw_pos decl_pos)
in
((env, ty_err_opt), ty)
| None ->
Decl_typedef_expand.expand_typedef
~force_expand:true
(Env.get_ctx env)
(get_reason dty)
name
tyl
|> localize ~ety_env env
else
let ((env, e1), ty) = localize ~ety_env env ty in
let ((env, e2), tyl) =
List.map_env_ty_err_opt
env
tyl
~f:(localize ~ety_env)
~combine_ty_errs:Typing_error.multiple_opt
in
let ty_err_opt = Option.merge e1 e2 ~f:Typing_error.both in
((env, ty_err_opt), mk (r, Tnewtype (name, tyl, ty)))
(* Localize type arguments for something whose kinds is [kind] *)
and localize_targs_by_kind
~ety_env
env
(tyargs : decl_ty list)
(nkinds : KindDefs.Simple.named_kind list) =
let exp_len = List.length nkinds in
let act_len = List.length tyargs in
let length = min exp_len act_len in
let (tyargs, nkinds) = (List.take tyargs length, List.take nkinds length) in
let ((env, ty_errs, _), tyl) =
List.map2_env
(env, [], ety_env)
tyargs
nkinds
~f:(fun (env, ty_errs, ety_env) x y ->
let ((env, ty_err_opt, ety_env), res) =
localize_targ_by_kind (env, ety_env) x y
in
let ty_errs =
Option.value_map ty_err_opt ~default:ty_errs ~f:(fun e ->
e :: ty_errs)
in
((env, ty_errs, ety_env), res))
in
let ty_err_opt = Typing_error.multiple_opt ty_errs in
(* Note that we removed superfluous type arguments, because we don't have a kind to localize
them against.
It would also be useful to fill in Terr for missing type arguments, but this breaks some
checks on built-in collections that check the number of type arguments *after* localization. *)
((env, ty_err_opt), tyl)
and localize_targ_by_kind (env, ety_env) ty (nkind : KindDefs.Simple.named_kind)
=
match (get_node ty, ety_env.wildcard_action) with
| (Twildcard, Wildcard_fresh_generic)
| (_, Wildcard_fresh_generic_type_argument) ->
let r = get_reason ty in
let pos = get_pos ty in
let r = Typing_reason.localize r in
let (name, kind) = nkind in
let is_higher_kinded = KindDefs.Simple.get_arity kind > 0 in
if is_higher_kinded then
let (env, ty) = Env.fresh_type_error env Pos.none in
(* We don't support wildcards in place of HK type arguments *)
((env, None, ety_env), ty)
else
let full_kind_without_bounds =
KindDefs.Simple.to_full_kind_without_bounds kind
in
let (env, new_name) =
(* add without bounds, because we need to substitute inside them first,
as done below *)
Env.add_fresh_generic_parameter_by_kind
env
pos
(snd name)
full_kind_without_bounds
in
let ty_fresh = mk (r, Tgeneric (new_name, [])) in
(* Substitute fresh type parameters for original formals in constraint *)
let substs = SMap.add (snd name) ty_fresh ety_env.substs in
let ety_env = { ety_env with substs } in
let subst_and_add_localized_constraints env ck cstr_tys =
Typing_set.fold
(fun cstr_ty env ->
let cstr_ty = Kinding.Locl_Inst.instantiate substs cstr_ty in
TUtils.add_constraint env ck ty_fresh cstr_ty ety_env.on_error)
cstr_tys
env
in
let (env, ty_errs) =
match KindDefs.Simple.get_wilcard_bounds kind with
| KindDefs.Simple.NonLocalized decl_cstrs ->
List.fold_left
decl_cstrs
~init:(env, [])
~f:(fun (env, ty_errs) (ck, ty) ->
let ((env, ty_err_opt), ty) = localize ~ety_env env ty in
let ty_errs =
Option.value_map
~default:ty_errs
~f:(fun e -> e :: ty_errs)
ty_err_opt
in
let env =
TUtils.add_constraint env ck ty_fresh ty ety_env.on_error
in
(env, ty_errs))
| KindDefs.Simple.Localized { wc_lower; wc_upper } ->
let env =
subst_and_add_localized_constraints
env
Ast_defs.Constraint_as
wc_upper
in
let env =
subst_and_add_localized_constraints
env
Ast_defs.Constraint_super
wc_lower
in
(env, [])
in
let ty_err_opt = Typing_error.multiple_opt ty_errs in
((env, ty_err_opt, ety_env), ty_fresh)
| _ ->
let ((env, ty_err_opt), ty) = localize_with_kind ~ety_env env ty nkind in
((env, ty_err_opt, ety_env), ty)
and localize_class_instantiation ~ety_env env r sid tyargs class_info =
let (pos, name) = sid in
match class_info with
| None ->
(* Without class info, we don't know the kinds of the arguments.
We assume they are non-HK types. *)
let (env, tyl) =
List.map_env_ty_err_opt
env
tyargs
~f:(localize ~ety_env:{ ety_env with expand_visible_newtype = true })
~combine_ty_errs:Typing_error.multiple_opt
in
(env, mk (r, Tclass (sid, nonexact, tyl)))
| Some class_info ->
if Option.is_some (Cls.enum_type class_info) then
let (ety_env, has_cycle) =
Typing_defs.add_type_expansion_check_cycles ety_env (pos, name)
in
match has_cycle with
| Some _ ->
let ty_err_opt =
Option.map
ety_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Cyclic_enum_constraint pos)
in
((env, ty_err_opt), mk (r, TUtils.tany env))
| None ->
if Ast_defs.is_c_enum_class (Cls.kind class_info) then
(* Enum classes no longer has the ambiguity between the type of
* the enum set and the type of elements, so the enum class
* itself is seen as a Tclass
*)
((env, None), mk (r, Tclass (sid, nonexact, [])))
else
let (env, cstr) =
match Env.get_enum_constraint env name with
(* If not specified, default bound is arraykey *)
| None ->
( (env, None),
MakeType.arraykey
(Reason.Rimplicit_upper_bound (pos, "arraykey")) )
| Some ty -> localize ~ety_env env ty
in
(env, mk (r, Tnewtype (name, [], cstr)))
else
let tparams = Cls.tparams class_info in
let nkinds = KindDefs.Simple.named_kinds_of_decl_tparams tparams in
let ((env, err), tyl) =
localize_targs_by_kind
~ety_env:{ ety_env with expand_visible_newtype = true }
env
tyargs
nkinds
in
(* Hide the class type if its internal and outside of the module *)
if Typing_modules.is_class_visible env class_info then
((env, err), mk (r, Tclass (sid, nonexact, tyl)))
else
let callee_module =
match Cls.get_module class_info with
| Some m -> m
| None ->
failwith
"Internal error: module must exist for class to be not visible"
in
let new_r =
Reason.Ropaque_type_from_module (Cls.pos class_info, callee_module, r)
in
let cstr = MakeType.mixed new_r in
((env, err), mk (new_r, Tnewtype (name, [], cstr)))
and localize_typedef_instantiation
~ety_env env r decl_r type_name tyargs typedef_info =
match typedef_info with
| Some typedef_info ->
if TypecheckerOptions.use_type_alias_heap (Env.get_tcopt env) then
Decl_typedef_expand.expand_typedef
(Env.get_ctx env)
decl_r
type_name
tyargs
|> localize ~ety_env env
else
let tparams = typedef_info.Typing_defs.td_tparams in
let nkinds = KindDefs.Simple.named_kinds_of_decl_tparams tparams in
let ((env, e1), tyargs) =
localize_targs_by_kind
~ety_env:{ ety_env with expand_visible_newtype = true }
env
tyargs
nkinds
in
let ((env, e2), lty) =
TUtils.expand_typedef ety_env env r type_name tyargs
in
let ty_err_opt = Option.merge e1 e2 ~f:Typing_error.both in
((env, ty_err_opt), lty)
| None ->
(* This must be unreachable. We only call localize_typedef_instantiation if we *know* that
we have a typedef with typedef info at hand. *)
failwith "Internal error: No info about typedef"
(* Localize a type with the given expected kind, which
may either indicate a higher-kinded or fully applied type.
*)
and localize_with_kind
~ety_env
env
(dty : decl_ty)
(expected_named_kind : KindDefs.Simple.named_kind) =
let expected_kind = snd expected_named_kind in
let (r, dty_) = deref dty in
let r = Typing_reason.localize r in
let arity = KindDefs.Simple.get_arity expected_kind in
if Int.( = ) arity 0 then
(* Not higher-kinded *)
localize ~ety_env env dty
else
match dty_ with
| Tapply (((_pos, name) as id), []) -> begin
match Env.get_class_or_typedef env name with
| Some (Env.ClassResult class_info) ->
let tparams = Cls.tparams class_info in
let classish_kind =
KindDefs.Simple.type_with_params_to_simple_kind tparams
in
if Kinding.Simple.is_subkind env ~sub:classish_kind ~sup:expected_kind
then
((env, None), mk (r, Tclass (id, nonexact, [])))
else
let (env, ty) = Env.fresh_type_error env Pos.none in
((env, None), ty)
| Some (Env.TypedefResult typedef) ->
if Env.is_typedef_visible env ~name typedef then
((env, None), mk (r, Tunapplied_alias name))
else
(* The bound is unused until the newtype is fully applied, thus supplying dummy Tany *)
( (env, None),
mk (r, Tnewtype (name, [], mk (Reason.none, make_tany ()))) )
| None ->
(* We are expected to localize a higher-kinded type, but are given an unknown class name.
Not much we can do. *)
let (env, ty) = Env.fresh_type_error env Pos.none in
((env, None), ty)
end
| Tgeneric (name, []) -> begin
match Env.get_pos_and_kind_of_generic env name with
| Some (_, gen_kind) ->
if
Kinding.Simple.is_subkind
env
~sub:(KindDefs.Simple.from_full_kind gen_kind)
~sup:expected_kind
then
((env, None), mk (r, Tgeneric (name, [])))
else
let (env, ty) = Env.fresh_type_error env Pos.none in
((env, None), ty)
| None ->
(* FIXME: Ideally, we would like to fail here, but sometimes we see type
parameters without an entry in the environment. *)
((env, None), mk (r, Tgeneric (name, [])))
end
| Tgeneric (_, _targs)
| Tapply (_, _targs) ->
let (env, ty) = Env.fresh_type_error env Pos.none in
((env, None), ty)
| Tany _ -> ((env, None), mk (r, make_tany ()))
| _dty_ ->
let (env, ty) = Env.fresh_type_error env Pos.none in
((env, None), ty)
(* Recursive localizations of function types do not make judgements about enforceability *)
and localize_possibly_enforced_ty ~ety_env env ety =
let (env, et_type) = localize ~ety_env env ety.et_type in
(env, { ety with et_type })
and localize_cstr_ty ~ety_env env ty tp_name =
let (env, ty) = localize ~ety_env env ty in
let ty =
map_reason ty ~f:(fun r ->
Reason.Rcstr_on_generics (Reason.to_pos r, tp_name))
in
(env, ty)
(* For the majority of cases when we localize a function type we instantiate
* the function's type parameters to Tvars. There are two cases where we do not do this.
* 1) In Typing_subtype.subtype_method. See the comment for that function for why
* this is necessary.
* 2) When the type arguments are explicitly specified, in which case we instantiate
* the type parameters to the provided types.
*)
and localize_ft
?(instantiation : method_instantiation option)
~ety_env
~def_pos
env
(ft : decl_ty fun_type) =
let ((env, arity_ty_err_opt), substs) =
match instantiation with
| Some { explicit_targs; use_name = _; use_pos } ->
let ty_err_opt =
if
(not (List.is_empty explicit_targs))
&& Int.( <> ) (List.length explicit_targs) (List.length ft.ft_tparams)
then
Some
Typing_error.(
primary
@@ Primary.Expected_tparam
{
decl_pos = def_pos;
pos = use_pos;
n = List.length ft.ft_tparams;
})
else
None
in
let tvarl = List.map ~f:fst explicit_targs in
let ft_subst = Subst.make_locl ft.ft_tparams tvarl in
((env, ty_err_opt), SMap.union ft_subst ety_env.substs)
| None -> ((env, None), ety_env.substs)
in
let ety_env = { ety_env with substs } in
(* Localize the constraints for a type parameter declaration *)
let rec localize_tparam ~nested env t =
let ((env, e1), cstrl) =
(* TODO(T70068435)
For nested type parameters (i.e., type parameters of type parameters),
we do not support constraints, yet. If nested type parameters do have
constraints, this is reported earlier. We just throw them away here. *)
if nested then
((env, None), [])
else
List.map_env_ty_err_opt
env
t.tp_constraints
~combine_ty_errs:Typing_error.multiple_opt
~f:(fun env (ck, ty) ->
let ((env, ty_err_opt), ty) =
localize_cstr_ty ~ety_env env ty t.tp_name
in
let name_str = snd t.tp_name in
(* In order to access type constants on generics on where clauses,
we need to add the constraints from the type parameters into the
environment before localizing the where clauses with them. Temporarily
add them to the environment here, and reset the environment later. *)
let env =
match ck with
| Ast_defs.Constraint_as -> Env.add_upper_bound env name_str ty
| Ast_defs.Constraint_super -> Env.add_lower_bound env name_str ty
| Ast_defs.Constraint_eq ->
Env.add_upper_bound
(Env.add_lower_bound env name_str ty)
name_str
ty
in
((env, ty_err_opt), (ck, ty)))
in
let ((env, e2), tparams) =
List.map_env_ty_err_opt
env
t.tp_tparams
~f:(localize_tparam ~nested:true)
~combine_ty_errs:Typing_error.multiple_opt
in
let ty_err_opt = Option.merge e1 e2 ~f:Typing_error.both in
((env, ty_err_opt), { t with tp_constraints = cstrl; tp_tparams = tparams })
in
let localize_where_constraint env (ty1, ck, ty2) =
let ((env, e1), ty1) = localize ~ety_env env ty1 in
let ((env, e2), ty2) = localize ~ety_env env ty2 in
let ty_err_opt = Option.merge e1 e2 ~f:Typing_error.both in
((env, ty_err_opt), (ty1, ck, ty2))
in
(* Grab and store the old tpenvs *)
let old_tpenv = Env.get_tpenv env in
let old_global_tpenv = env.tpenv in
(* Always localize tparams so they are available for later Tast check *)
let ((env, tparam_ty_err_opt), tparams) =
List.map_env_ty_err_opt
env
ft.ft_tparams
~f:(localize_tparam ~nested:false)
~combine_ty_errs:Typing_error.multiple_opt
in
(* Localize the 'where' constraints *)
let ((env, where_cstr_ty_err_opt), where_constraints) =
List.map_env_ty_err_opt
env
ft.ft_where_constraints
~f:localize_where_constraint
~combine_ty_errs:Typing_error.multiple_opt
in
(* Remove the constraints we added for localizing where constraints *)
let env = Env.env_with_tpenv env old_tpenv in
let env = Env.env_with_global_tpenv env old_global_tpenv in
(* If we're instantiating the generic parameters then add a deferred
* check that constraints are satisfied under the
* substitution [ety_env.substs].
*)
let (env, gen_param_ty_err_opt) =
match instantiation with
| Some { use_pos; _ } ->
let (env, e1) =
check_tparams_constraints ~use_pos ~ety_env env ft.ft_tparams
in
let (env, e2) =
check_where_constraints
~in_class:false
~use_pos
~definition_pos:def_pos
~ety_env
env
ft.ft_where_constraints
in
let ty_err_opt = Option.merge e1 e2 ~f:Typing_error.both in
(env, ty_err_opt)
| None -> (env, None)
in
let variadic_index =
if get_ft_variadic ft then
List.length ft.ft_params - 1
else
-1
in
let (((env, _), variadic_params_ty_err_opt), params) =
List.map_env_ty_err_opt
(env, 0)
ft.ft_params
~f:(fun (env, i) param ->
let ((env, ty_err_opt), ty) =
localize_possibly_enforced_ty ~ety_env env param.fp_type
in
(* HHVM does not enforce types on vararg parameters yet *)
let ty =
if i = variadic_index then
{ et_type = ty.et_type; et_enforced = Unenforced }
else
ty
in
(((env, i + 1), ty_err_opt), { param with fp_type = ty }))
~combine_ty_errs:Typing_error.multiple_opt
in
let ((env, implicit_params_ty_err_opt), implicit_params) =
let (env, capability) =
match ft.ft_implicit_params.capability with
| CapTy c ->
let (env, ty) = localize ~ety_env env c in
(env, CapTy ty)
| CapDefaults p -> ((env, None), CapDefaults p)
in
(env, { capability })
in
let ((env, ret_ty_err_opt), ret) =
localize_possibly_enforced_ty ~ety_env env ft.ft_ret
in
let ft =
set_ft_ftk
ft
(if Option.is_some instantiation then
FTKinstantiated_targs
else
FTKtparams)
in
let ty_err_opt =
Typing_error.multiple_opt
@@ List.filter_map
~f:Fn.id
[
arity_ty_err_opt;
tparam_ty_err_opt;
where_cstr_ty_err_opt;
gen_param_ty_err_opt;
variadic_params_ty_err_opt;
implicit_params_ty_err_opt;
ret_ty_err_opt;
]
in
( (env, ty_err_opt),
{
ft with
ft_params = params;
ft_implicit_params = implicit_params;
ft_ret = ret;
ft_tparams = tparams;
ft_where_constraints = where_constraints;
} )
(* Given a list of generic parameters [tparams] and a substitution
* in [ety_env.substs] whose domain is at least these generic parameters,
* check that the types satisfy
* the constraints on the corresponding generic parameter.
*
* Note that the constraints may contain occurrences of the generic
* parameters, but the subsitution will be applied to them. e.g. if tparams is
* <Tu as MyCovariant<Tu>, Tv super Tu>
* and ety_env.substs is
* Tu :-> C
* Tv :-> I
* with
* class C extends MyContravariant<I> implements I { ... }
* Then the constraints are satisfied, because
* C is a subtype of MyContravariant<C>
* I is a supertype of C
*)
and check_tparams_constraints ~use_pos ~ety_env env tparams =
let check_tparam_constraints (env, ty_errs) t =
match SMap.find_opt (snd t.tp_name) ety_env.substs with
| Some ty ->
List.fold_left
t.tp_constraints
~init:(env, ty_errs)
~f:(fun (env, ty_errs) (ck, cstr_ty) ->
let ((env, e1), cstr_ty) =
localize_cstr_ty ~ety_env env cstr_ty t.tp_name
in
Typing_log.(
log_with_level env "generics" ~level:1 (fun () ->
log_types
(Pos_or_decl.of_raw_pos use_pos)
env
[
Log_head
( "check_tparams_constraints: check_tparams_constraint",
[Log_type ("cstr_ty", cstr_ty); Log_type ("ty", ty)] );
]));
let (env, e2) =
TGenConstraint.check_tparams_constraint env ~use_pos ck ~cstr_ty ty
in
let ty_err_opt = Option.merge e1 e2 ~f:Typing_error.both in
let ty_errs =
Option.value_map
~default:ty_errs
~f:(fun e -> e :: ty_errs)
ty_err_opt
in
(env, ty_errs))
| None -> (env, ty_errs)
in
let (env, ty_errs) =
List.fold_left tparams ~init:(env, []) ~f:check_tparam_constraints
in
(env, Typing_error.multiple_opt ty_errs)
and check_where_constraints
~in_class ~use_pos ~ety_env ~definition_pos env cstrl =
let ety_env =
let on_error =
Some
(Typing_error.Reasons_callback.explain_where_constraint
use_pos
~in_class
~decl_pos:definition_pos)
in
{ ety_env with on_error }
in
let (env, ty_errs) =
List.fold_left
cstrl
~init:(env, [])
~f:(fun (env, ty_errs) (ty, ck, cstr_ty) ->
let ((env, e1), ty) = localize ~ety_env env ty in
let ((env, e2), cstr_ty) = localize ~ety_env env cstr_ty in
let (env, e3) =
TGenConstraint.check_where_constraint
~in_class
env
~use_pos
~definition_pos
ck
~cstr_ty
ty
in
let ty_err_opt =
Typing_error.multiple_opt @@ List.filter_map ~f:Fn.id [e1; e2; e3]
in
let ty_errs =
Option.value_map
~default:ty_errs
~f:(fun e -> e :: ty_errs)
ty_err_opt
in
(env, ty_errs))
in
(env, Typing_error.multiple_opt ty_errs)
and localize_refinement ~ety_env env r root decl_cr =
let mk_unsupported_err () =
let pos = Reason.to_pos r in
Option.map ety_env.on_error ~f:(fun on_error ->
Typing_error.(
apply_reasons ~on_error (Secondary.Unsupported_refinement pos)))
in
let ((env, ty_err_opt), root) = localize ~ety_env env root in
match get_node root with
| Tclass (cid, Nonexact cr, tyl) ->
let both_err e1 e2 = Option.merge e1 e2 ~f:Typing_error.both in
let ((env, ty_err_opt), cr) =
Class_refinement.fold_refined_consts
~f:(fun id { rc_bound; rc_is_ctx } ((env, ty_err_opt), cr) ->
let ((env, ty_err_opt'), rc_bound) =
match rc_bound with
| TRexact ty ->
let (env_err, ty) = localize ~ety_env env ty in
(env_err, TRexact ty)
| TRloose { tr_lower; tr_upper } ->
let localize_list env tyl =
List.map_env (env, None) tyl ~f:(fun (env, ty_err_opt) ty ->
let ((env, ty_err_opt'), ty) = localize ~ety_env env ty in
((env, both_err ty_err_opt ty_err_opt'), ty))
in
let ((env, ty_err_opt1), tr_lower) = localize_list env tr_lower in
let ((env, ty_err_opt2), tr_upper) = localize_list env tr_upper in
( (env, both_err ty_err_opt1 ty_err_opt2),
TRloose { tr_lower; tr_upper } )
in
let cr =
Class_refinement.add_refined_const id { rc_bound; rc_is_ctx } cr
in
((env, both_err ty_err_opt ty_err_opt'), cr))
~init:((env, ty_err_opt), cr)
decl_cr
in
((env, ty_err_opt), mk (r, Tclass (cid, Nonexact cr, tyl)))
| _ ->
let (env, ty) = Env.fresh_type_error env Pos.none in
((env, mk_unsupported_err ()), ty)
(* Like localize_no_subst, but uses the supplied kind, enabling support
for higher-kinded types *)
let localize_no_subst_and_kind env ~tparam ~on_error ty nkind =
let ety_env =
Option.value_map
~default:empty_expand_env
~f:empty_expand_env_with_on_error
on_error
in
let ety_env =
match tparam with
| Some tp
when Attributes.mem SN.UserAttributes.uaExplicit tp.tp_user_attributes ->
{ ety_env with wildcard_action = Wildcard_require_explicit tp }
| _ -> ety_env
in
localize_with_kind ~ety_env env ty nkind
(** Localize an explicit type argument to a constructor or function. We
support the use of wildcards at the top level only *)
let localize_targ_with_kind
?tparam ~check_well_kinded env hint (nkind : KindDefs.Simple.named_kind) =
(* For explicit type arguments we support a wildcard syntax `_` for which
* Hack will generate a fresh type variable *)
let kind = snd nkind in
match hint with
| (p, Aast.Hwildcard) ->
let is_higher_kinded = KindDefs.Simple.get_arity kind > 0 in
if is_higher_kinded then
let ty_err = Typing_error.(primary @@ Primary.HKT_wildcard (fst hint)) in
let (env, ty) = Env.fresh_type_error env p in
((env, Some ty_err), (ty, hint))
else
let (env, ty) = Env.fresh_type env p in
((env, None), (ty, hint))
| (hint_pos, _) ->
let ty = Decl_hint.hint env.decl_env hint in
if check_well_kinded then
Kinding.Simple.check_well_kinded ~in_signature:false env ty nkind;
let (env, ty) =
localize_no_subst_and_kind
env
~tparam
~on_error:
(Some (Typing_error.Reasons_callback.invalid_type_hint hint_pos))
ty
nkind
in
(env, (ty, hint))
let localize_targ ?tparam ~check_well_kinded env hint =
let named_kind =
KindDefs.Simple.with_dummy_name (KindDefs.Simple.fully_applied_type ())
in
localize_targ_with_kind ?tparam ~check_well_kinded env hint named_kind
(* See signature in .mli file for details *)
let localize_targs_with_kinds
~check_well_kinded
~is_method
~def_pos
~use_pos
~use_name
?(check_explicit_targs = true)
?(tparaml = [])
env
named_kinds
targl =
let targ_count = List.length targl in
let generated_tparam_count =
List.count
~f:(fun t -> SN.Coeffects.is_generated_generic (snd t.tp_name))
tparaml
in
let tparam_count =
match List.length tparaml with
| 0 -> List.length named_kinds
| n -> n
in
let explicit_tparam_count = tparam_count - generated_tparam_count in
let checking_rewritten_call () =
(* Typing_phase expands the case of targl=[] to a list of wildcards matching the
* length of tparaml, but some `if` condition checks retype already typed
* expressions, so we get the generated list instead of what the user wrote
* TODO(coeffects) attempt to remove Tast.to_nast_expr calls *)
generated_tparam_count > 0
&& targ_count = tparam_count
&& List.for_all ~f:Aast_defs.is_wildcard_hint targl
in
(* If there are explicit type arguments but too few or too many then
* report an error *)
let arity_ty_err_opt =
if
not
Int.(
targ_count = 0
|| targ_count = explicit_tparam_count
|| checking_rewritten_call ())
then
if is_method then
Some
Typing_error.(
primary
@@ Primary.Expected_tparam
{
decl_pos = def_pos;
pos = use_pos;
n = explicit_tparam_count;
})
else
Some
Typing_error.(
primary
@@ Primary.Type_arity_mismatch
{
pos = use_pos;
decl_pos = def_pos;
expected = tparam_count;
actual = targ_count;
})
else
None
in
(* Declare and localize the explicit type arguments *)
let (targ_tparaml, _) = List.zip_with_remainder targl tparaml in
let ((env, ty_errs), explicit_targs) =
List.map2_env
(env, [])
targ_tparaml
(List.take named_kinds targ_count)
~f:(fun (env, ty_errs) (targ, tparam) y ->
let ((env, ty_err_opt), res) =
localize_targ_with_kind ~tparam ~check_well_kinded env targ y
in
let ty_errs =
Option.value_map ty_err_opt ~default:ty_errs ~f:(fun e ->
e :: ty_errs)
in
((env, ty_errs), res))
in
let explicit_targ_ty_err_opt = Typing_error.multiple_opt ty_errs in
(* Generate fresh type variables for the remainder *)
let ((env, implicit_targ_ty_err_opt), implicit_targs) =
let mk_implicit_targ env (kind_name, kind) =
let wildcard_hint = (use_pos, Aast.Hwildcard) in
if
check_well_kinded
&& KindDefs.Simple.get_arity kind > 0
&& targ_count = 0
then
(* We only throw an error if the user didn't provide any type arguments at all.
Otherwise, if they provided some, but not all of them, n arity mismatch
triggers earlier in this function, independently from higher-kindedness *)
let ty_err =
Typing_error.(
primary
@@ Primary.HKT_implicit_argument
{
pos = use_pos;
decl_pos = fst kind_name;
param_name = snd kind_name;
})
in
let (env, ty) = Env.fresh_type_error env use_pos in
((env, Some ty_err), (ty, wildcard_hint))
else
let (env, tvar) =
Env.fresh_type_reason
env
use_pos
(Reason.Rtype_variable_generics (use_pos, snd kind_name, use_name))
in
Typing_log.log_tparam_instantiation env use_pos (snd kind_name) tvar;
((env, None), (tvar, wildcard_hint))
in
List.map_env_ty_err_opt
env
(List.drop named_kinds targ_count)
~f:mk_implicit_targ
~combine_ty_errs:Typing_error.multiple_opt
in
let check_for_explicit_user_attribute tparam (_, hint) =
if
Attributes.mem SN.UserAttributes.uaExplicit tparam.tp_user_attributes
&& Aast_defs.is_wildcard_hint hint
then
let (decl_pos, param_name) = tparam.tp_name in
Some
Typing_error.(
primary
@@ Primary.Require_generic_explicit
{ decl_pos; param_name; pos = fst hint })
else
None
in
let ua_ty_err_opt =
if check_explicit_targs then
Typing_error.multiple_opt
@@ List.fold2_exn
tparaml
(explicit_targs @ implicit_targs)
~init:[]
~f:(fun ty_errs tp targ ->
Option.value_map ~default:ty_errs ~f:(fun e -> e :: ty_errs)
@@ check_for_explicit_user_attribute tp targ)
else
None
in
let ty_err_opt =
Typing_error.multiple_opt
@@ List.filter_map
~f:Fn.id
[
arity_ty_err_opt;
explicit_targ_ty_err_opt;
implicit_targ_ty_err_opt;
ua_ty_err_opt;
]
in
((env, ty_err_opt), explicit_targs @ implicit_targs)
let localize_targs
~check_well_kinded
~is_method
~def_pos
~use_pos
~use_name
?(check_explicit_targs = true)
env
tparaml
targl =
let nkinds = KindDefs.Simple.named_kinds_of_decl_tparams tparaml in
localize_targs_with_kinds
~check_well_kinded
~is_method
~def_pos
~use_pos
~use_name
~tparaml
~check_explicit_targs
env
nkinds
targl
(* Performs no substitutions of generics and initializes Tthis to
* Env.get_self env
*)
let localize_no_subst_ env ~wildcard_action ~on_error ?report_cycle ty =
let ety_env =
{
empty_expand_env with
type_expansions =
Typing_defs.Type_expansions.empty_w_cycle_report ~report_cycle;
on_error;
wildcard_action;
}
in
localize env ty ~ety_env
let localize_hint_no_subst env ~ignore_errors ?report_cycle h =
let (pos, _) = h in
let h = Decl_hint.hint env.decl_env h in
localize_no_subst_
env
~on_error:
(if ignore_errors then
None
else
Some (Typing_error.Reasons_callback.invalid_type_hint pos))
~wildcard_action:Wildcard_illegal
?report_cycle
h
let localize_hint_for_refinement env h =
let (pos, _) = h in
let h = Decl_hint.hint env.decl_env h in
localize_no_subst_
env
~on_error:(Some (Typing_error.Reasons_callback.invalid_type_hint pos))
~wildcard_action:Wildcard_fresh_generic
h
let localize_hint_for_lambda env h =
let (pos, _) = h in
let h = Decl_hint.hint env.decl_env h in
localize_no_subst_
env
~on_error:(Some (Typing_error.Reasons_callback.invalid_type_hint pos))
~wildcard_action:Wildcard_fresh_tyvar
h
let localize_no_subst env ~ignore_errors ty =
localize_no_subst_
env
~on_error:
(if ignore_errors then
None
else
Some
(Typing_error.Reasons_callback.invalid_type_hint
(Pos_or_decl.unsafe_to_raw_pos @@ get_pos ty)))
~wildcard_action:Wildcard_illegal
ty
let localize_possibly_enforced_no_subst env ~ignore_errors ety =
let (env, et_type) = localize_no_subst env ~ignore_errors ety.et_type in
(env, { ety with et_type })
let localize_targs_and_check_constraints
~exact
~check_well_kinded
~def_pos
~use_pos
?(check_explicit_targs = true)
env
class_id
r
tparaml
hintl =
let ((env, e1), type_argl) =
localize_targs
~check_well_kinded
~is_method:false
~def_pos
~use_pos
~use_name:(Utils.strip_ns (snd class_id))
~check_explicit_targs
env
tparaml
hintl
in
let targs_tys = List.map ~f:fst type_argl in
let this_ty =
mk (r, Tclass (Positioned.of_raw_positioned class_id, exact, targs_tys))
in
let ety_env =
{
empty_expand_env with
this_ty;
substs = Subst.make_locl tparaml targs_tys;
on_error = Some (Typing_error.Reasons_callback.unify_error_at use_pos);
}
in
let (env, e2) = check_tparams_constraints ~use_pos ~ety_env env tparaml in
let ty_err_opt = Option.merge e1 e2 ~f:Typing_error.both in
((env, ty_err_opt), this_ty, type_argl)
(* Add generic parameters to the environment, localize their bounds, and
* transform these into a flat list of constraints of the form (ty1,ck,ty2)
* where ck is as, super or =
*)
let localize_and_add_generic_parameters_with_bounds
~ety_env (env : env) (tparams : decl_tparam list) =
let env = Env.add_generic_parameters env tparams in
let localize_bound
env ({ tp_name = (pos, name); tp_constraints = cstrl; _ } : decl_tparam) =
(* TODO(T70068435) This may have to be touched when adding support for constraints on HK
types *)
let tparam_ty = mk (Reason.Rwitness_from_decl pos, Tgeneric (name, [])) in
List.map_env_ty_err_opt
env
cstrl
~f:(fun env (ck, cstr) ->
let (env, ty) = localize env cstr ~ety_env in
(env, (tparam_ty, ck, ty)))
~combine_ty_errs:Typing_error.multiple_opt
in
let ((env, ty_err_opt), cstrss) =
List.map_env_ty_err_opt
env
tparams
~f:localize_bound
~combine_ty_errs:Typing_error.multiple_opt
in
let add_constraint env (ty1, ck, ty2) =
TUtils.add_constraint env ck ty1 ty2 ety_env.on_error
in
let env = List.fold_left (List.concat cstrss) ~f:add_constraint ~init:env in
(env, ty_err_opt)
let localize_and_add_where_constraints ~ety_env (env : env) where_constraints =
let localize_and_add_constraint (env, ty_errs) (ty1, ck, ty2) =
let ((env, e1), ty1) = localize env ty1 ~ety_env in
let ((env, e2), ty2) = localize env ty2 ~ety_env in
let env = TUtils.add_constraint env ck ty1 ty2 ety_env.on_error in
let ty_errs =
Option.(
value_map ~default:ty_errs ~f:(fun e -> e :: ty_errs)
@@ merge e1 e2 ~f:Typing_error.both)
in
(env, ty_errs)
in
let (env, ty_errs) =
List.fold_left
where_constraints
~f:localize_and_add_constraint
~init:(env, [])
in
(env, Typing_error.multiple_opt ty_errs)
(* Helper functions *)
let sub_type_decl env ty1 ty2 on_error =
let ((env, e1), ty1) = localize_no_subst env ~ignore_errors:true ty1 in
let ((env, e2), ty2) = localize_no_subst env ~ignore_errors:true ty2 in
let (env, e3) = TUtils.sub_type env ty1 ty2 on_error in
let ty_err_opt =
Typing_error.multiple_opt @@ List.filter_map ~f:Fn.id [e1; e2; e3]
in
(env, ty_err_opt)
let is_sub_type_decl ?coerce env ty1 ty2 =
let ((env, e1), ty1) = localize_no_subst env ~ignore_errors:true ty1 in
let ((env, e2), ty2) = localize_no_subst env ~ignore_errors:true ty2 in
let (_env, e3) =
TUtils.sub_type
?coerce
env
ty1
ty2
(Some (Typing_error.Reasons_callback.unify_error_at Pos.none))
in
Option.is_none e1 && Option.is_none e2 && Option.is_none e3
let localize_and_add_generic_parameters_and_where_constraints
~ety_env env tparams where_constraints =
let (env, e1) =
localize_and_add_generic_parameters_with_bounds env tparams ~ety_env
in
let (env, e2) =
localize_and_add_where_constraints env where_constraints ~ety_env
in
(env, Option.merge e1 e2 ~f:Typing_error.both)
let localize_and_add_ast_generic_parameters_and_where_constraints
env
~ignore_errors
(tparams : Nast.tparam list)
(where_constraints : Aast_defs.where_constraint_hint list) =
let tparams : decl_tparam list =
List.map tparams ~f:(Decl_hint.aast_tparam_to_decl_tparam env.decl_env)
in
let where_constraints : decl_where_constraint list =
List.map where_constraints ~f:(fun (h1, ck, h2) ->
(Decl_hint.hint env.decl_env h1, ck, Decl_hint.hint env.decl_env h2))
in
let ety_env =
if ignore_errors then
empty_expand_env
else
empty_expand_env_with_on_error
(Env.invalid_type_hint_assert_primary_pos_in_current_decl env)
in
localize_and_add_generic_parameters_and_where_constraints
~ety_env
env
tparams
where_constraints
let () = TUtils.localize_no_subst_ref := localize_no_subst
let () = TUtils.localize_ref := localize |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_phase.mli | [@@@warning "-33"]
open Hh_prelude
open Common
[@@@warning "+33"]
open Typing_defs
open Typing_env_types
type method_instantiation = {
use_pos: Pos.t;
use_name: string;
explicit_targs: Tast.targ list;
}
(**
Take a declaration phase type and use [ety_env] to transform it into a localized type.
- Desugar [Tmixed], [Toption] and [Tlike] types into unions.
- Transform [Tapply] to [Tclass] (for classish types), or [Tnewtype] (for opaque
type defs outside their defining file), else expand aliases or opaque
types within their defining file.
- Replace [Tthis] by [ety_env.this_ty].
- Replace [Tgeneric] by the type specified in [ety_env.substs], if present;
otherwise leave as generic.
- Expand [Taccess] type constant accesses through concrete classes.
Use this function to localize types outside the body of the method being
type-checked whose generic parameters and [this] type must be instantiated to
explicit types or fresh type variables. Use [localize_no_subst] instead for types
whose generic parameters and [this] type should be left as is.
The following errors are detected during localization:
- Bad type constant access e.g. [AbstractClass::T]
- Cyclic types
Errors are handled using [ety_env.on_error]. If you want to ignore errors
during localization, set this to [Errors.ignore_error]. *)
val localize :
ety_env:expand_env ->
env ->
decl_ty ->
(env * Typing_error.t option) * locl_ty
(**
Transform a declaration phase type into a localized type, with no substitution
for generic parameters and [this].
[ignore_errors] silences errors because those errors have already fired
and/or are not appropriate at the time we call localize. *)
val localize_no_subst :
env ->
ignore_errors:bool ->
decl_ty ->
(env * Typing_error.t option) * locl_ty
(**
Transform a declaration phase type with enforcement flag
into a localized type, with no substitution for generic parameters and [this].
[ignore_errors] silences errors because those errors have already fired
and/or are not appropriate at the time we call localize. *)
val localize_possibly_enforced_no_subst :
env ->
ignore_errors:bool ->
decl_possibly_enforced_ty ->
(env * Typing_error.t option) * locl_possibly_enforced_ty
(**
Transform a type hint into a localized type, with no substitution for generic
parameters and [this].
[ignore_errors] silences errors because those errors have already fired
and/or are not appropriate at the time we call localize. *)
val localize_hint_no_subst :
env ->
ignore_errors:bool ->
?report_cycle:Pos.t * string ->
Aast.hint ->
(env * Typing_error.t option) * locl_ty
val localize_hint_for_refinement :
env -> Aast.hint -> (env * Typing_error.t option) * locl_ty
val localize_hint_for_lambda :
env -> Aast.hint -> (env * Typing_error.t option) * locl_ty
val localize_ft :
?instantiation:method_instantiation ->
ety_env:expand_env ->
def_pos:Pos_or_decl.t ->
env ->
decl_fun_type ->
(env * Typing_error.t option) * locl_fun_type
(** Declare and localize the type arguments to a constructor or function, given
information about the declared type parameters in `decl_tparam list`. If no
explicit type arguments are given, generate fresh type variables in their
place; do the same for any wildcard explicit type arguments.
Report arity errors using `def_pos` (for the declared parameters), `use_pos`
(for the use-site) and `use_name` (the name of the constructor or function). *)
val localize_targs :
check_well_kinded:bool ->
is_method:bool ->
def_pos:Pos_or_decl.t ->
use_pos:Pos.t ->
use_name:string ->
?check_explicit_targs:bool ->
env ->
decl_tparam list ->
Aast.hint list ->
(env * Typing_error.t option) * Tast.targ list
(** Like [localize_targs], but acts on kinds. *)
val localize_targs_with_kinds :
check_well_kinded:bool ->
is_method:bool ->
def_pos:Pos_or_decl.t ->
use_pos:Pos.t ->
use_name:string ->
?check_explicit_targs:bool ->
?tparaml:decl_tparam list ->
env ->
Typing_kinding_defs.Simple.named_kind list ->
Aast.hint list ->
(env * Typing_error.t option) * Tast.targ list
(** Same as [localize_targs] but also check constraints on type parameters
(though not `where` constraints) *)
val localize_targs_and_check_constraints :
exact:exact ->
check_well_kinded:bool ->
def_pos:Pos_or_decl.t ->
use_pos:Pos.t ->
?check_explicit_targs:bool ->
env ->
Ast_defs.id ->
Typing_reason.t ->
decl_tparam list ->
Aast.hint list ->
(env * Typing_error.t option) * locl_ty * Tast.targ list
(** Declare and localize a single explicit type argument *)
val localize_targ :
?tparam:decl_tparam ->
check_well_kinded:bool ->
env ->
Aast.hint ->
(env * Typing_error.t option) * Tast.targ
val sub_type_decl :
env ->
decl_ty ->
decl_ty ->
Typing_error.Reasons_callback.t option ->
env * Typing_error.t option
(** Are two decl types definitely subtypes of each other? *)
val is_sub_type_decl :
?coerce:Typing_logic.coercion_direction option ->
env ->
decl_ty ->
decl_ty ->
bool
(** Add some [as] or [super] constraint to the environment.
Raise an error if any inconsistency is detected. *)
val check_tparams_constraints :
use_pos:Pos.t ->
ety_env:expand_env ->
env ->
decl_tparam list ->
env * Typing_error.t option
(** Add some [where] constraints to the environment.
Raise an error if any inconsistency is detected. *)
val check_where_constraints :
in_class:bool ->
use_pos:Pos.t ->
ety_env:expand_env ->
definition_pos:Pos_or_decl.t ->
env ->
decl_where_constraint list ->
env * Typing_error.t option
val decl : decl_ty -> phase_ty
val locl : locl_ty -> phase_ty
(** Add generic parameters to the environment, with localized bounds,
and also add any consequences of `where` constraints *)
val localize_and_add_generic_parameters_and_where_constraints :
ety_env:expand_env ->
env ->
decl_tparam list ->
decl_where_constraint list ->
env * Typing_error.t option
(** Add generic parameters to the environment, with localized bounds,
and also add any consequences of `where` constraints.
{!ignore_errors} silences errors because those errors may have already fired
during another localization and/or are not appropriate at the time we call localize. *)
val localize_and_add_ast_generic_parameters_and_where_constraints :
env ->
ignore_errors:bool ->
Nast.tparam list ->
(Aast.hint * Ast_defs.constraint_kind * Aast.hint) list ->
env * Typing_error.t option |
OCaml | hhvm/hphp/hack/src/typing/typing_print.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(*****************************************************************************)
(* Pretty printing of types *)
(*****************************************************************************)
open Hh_prelude
open Option.Monad_infix
open Typing_defs
open Typing_env_types
open Typing_logic
module SN = Naming_special_names
module Reason = Typing_reason
module TySet = Typing_set
module Cls = Decl_provider.Class
module Nast = Aast
module ITySet = Internal_type_set
(** Fuel ensures that types are curtailed while printing them. This avoids
performance regressions and increases readibility of errors overall. *)
module Fuel : sig
type t
val init : int -> t
val has_enough : t -> bool
(** [provide fuel f] consumes one unit of fuel to call f, plus fuel consumed by f itself,
provided there's enough fuel. If not, it returns the text doc "[truncated]". *)
val provide : t -> (fuel:t -> t * Doc.t) -> t * Doc.t
(** [provide_list fuel f inputs ~out_of_fuel_message] consumes fuel to call f
on each element of a list of inputs until we're out of fuel.
It consumes one unit of fuel per call to f plus the fuel consumed by f itself.
When out of fuel, it appends the text doc "[out_of_fuel_message]" to the results. *)
val provide_list :
t ->
('input -> fuel:t -> t * Doc.t) ->
'input list ->
out_of_fuel_message:string ->
t * Doc.t list
end = struct
type t = int
let init fuel = fuel
let deplete fuel = fuel - 1
let has_enough fuel = fuel >= 0
let provide_ (fuel : t) (f : fuel:t -> t * Doc.t) : t * Doc.t option =
if has_enough fuel then
let fuel = deplete fuel in
let (fuel, doc) = f ~fuel in
(fuel, Some doc)
else
(fuel, None)
let provide_list
(fuel : t)
(f : 'input -> fuel:t -> t * Doc.t)
(inputs : 'input list)
~(out_of_fuel_message : string) : t * Doc.t list =
let ((fuel, ran_out), docs) =
List.fold
inputs
~init:((fuel, false), [])
~f:(fun ((fuel, _), docs) input ->
let (fuel, doc) = provide_ fuel (f input) in
match doc with
| Some doc -> ((fuel, false), doc :: docs)
| None -> ((fuel, true), docs))
in
let docs =
if ran_out then
Doc.text (Printf.sprintf "[%s]" out_of_fuel_message) :: docs
else
docs
in
let docs = List.rev docs in
(fuel, docs)
let provide fuel f =
let (fuel, doc) = provide_ fuel f in
let doc = Option.value doc ~default:(Doc.text "[truncated]") in
(fuel, doc)
end
(** For sake of typing_print, either we wish to print a locl_ty in which case we need
the env to look up the typing environment and constraints and the like, or a decl_ty
in which case we don't need anything. [penv] stands for "printing env". *)
type penv =
| Loclenv of env
| Declenv
let split_desugared_ctx_tparams_gen ~tparams ~param_name =
let (generated_tparams, other_tparams) =
List.partition_tf tparams ~f:(fun param ->
param_name param |> SN.Coeffects.is_generated_generic)
in
let desugared_tparams =
List.map generated_tparams ~f:(fun param ->
param_name param |> SN.Coeffects.unwrap_generated_generic)
in
(desugared_tparams, other_tparams)
let strip_ns id =
id |> Utils.strip_ns |> Hh_autoimport.strip_HH_namespace_if_autoimport
let show_supportdyn env =
(not (TypecheckerOptions.everything_sdt env.genv.tcopt))
|| Typing_env_types.get_log_level env "show" >= 1
(*****************************************************************************)
(* Pretty-printer of the "full" type. *)
(* This is used in server/symbolTypeService and elsewhere *)
(* With debug_mode set it is used for hh_show_env *)
(*****************************************************************************)
module Full = struct
open Doc
let format_env = Format_env.{ default with line_width = 60 }
let text_strip_ns s = Doc.text (strip_ns s)
let text_strip_all_ns s = Doc.text (Utils.strip_all_ns s)
let ( ^^ ) a b = Concat [a; b]
let debug_mode = ref false
let show_verbose penv =
match penv with
| Loclenv env -> Typing_env_types.get_log_level env "show" > 1
| Declenv -> false
(* Until we support NoAutoDynamic, all types under everything-sdt
* support dynamic so displaying supportdyn is redundant
*)
let show_supportdyn_penv penv =
match penv with
| Loclenv env -> show_supportdyn env
| Declenv -> false
let blank_tyvars = ref false
let comma_sep = Concat [text ","; Space]
let semi_sep = Concat [text ";"; Space]
let id ~fuel x = (fuel, x)
let list_sep
~fuel
?(split = true)
(s : Doc.t)
(f : fuel:Fuel.t -> 'a -> Fuel.t * Doc.t)
(l : 'a list) : Fuel.t * Doc.t =
let split =
if split then
Split
else
Nothing
in
let max_idx = List.length l - 1 in
let (fuel, elements) =
List.fold_mapi l ~init:fuel ~f:(fun idx fuel element ->
let (fuel, d) = f ~fuel element in
if Int.equal idx max_idx then
(fuel, d)
else
(fuel, Concat [d; s; split]))
in
let d =
match elements with
| [] -> Nothing
| xs -> Nest [split; Concat xs; split]
in
(fuel, d)
let delimited_list ~fuel sep left_delimiter f l right_delimiter :
Fuel.t * Doc.t =
let (fuel, doc) = list_sep ~fuel sep f l in
let doc =
Span
[
text left_delimiter;
WithRule (Rule.Parental, Concat [doc; text right_delimiter]);
]
in
(fuel, doc)
let list
~fuel
ld
(printer : fuel:Fuel.t -> 'a -> Fuel.t * Doc.t)
(items : 'a list)
rd : Fuel.t * Doc.t =
delimited_list ~fuel comma_sep ld printer items rd
let shape_map
~fuel
(fdm : 'field TShapeMap.t)
(f_field : tshape_field_name * 'field -> fuel:Fuel.t -> Fuel.t * t) :
Fuel.t * t list =
let compare (k1, _) (k2, _) =
String.compare
(Typing_defs.TShapeField.name k1)
(Typing_defs.TShapeField.name k2)
in
let fields = List.sort ~compare (TShapeMap.bindings fdm) in
Fuel.provide_list
fuel
f_field
fields
~out_of_fuel_message:"shape was truncated"
(* Split type parameters [tparams] into normal user-denoted type
parameters, and a list of polymorphic context names that were
desugared to type parameters. *)
let split_desugared_ctx_tparams (tparams : 'a tparam list) :
string list * 'a tparam list =
let param_name { tp_name = (_, name); _ } = name in
split_desugared_ctx_tparams_gen ~tparams ~param_name
let rec is_supportdyn_mixed : type a. penv -> a ty -> bool =
fun env t ->
match get_node t with
| Tnewtype (n, _, ty)
when String.equal n SN.Classes.cSupportDyn
&& not (show_supportdyn_penv env) ->
is_supportdyn_mixed env ty
| Tapply ((_, n), [ty])
when String.equal n SN.Classes.cSupportDyn
&& not (show_supportdyn_penv env) ->
is_supportdyn_mixed env ty
| Toption t ->
(match get_node t with
| Tnonnull -> true
| _ -> false)
| _ -> false
let rec fun_type ~fuel ~ty to_doc st penv ft fun_implicit_params =
let n = List.length ft.ft_params in
let (fuel, params) =
List.fold_mapi ft.ft_params ~init:fuel ~f:(fun i fuel p ->
let (fuel, d) = fun_param ~fuel ~ty to_doc st penv p in
( fuel,
if get_ft_variadic ft && i + 1 = n then
Concat [d; text "..."]
else
d ))
in
let (_, tparams) = split_desugared_ctx_tparams ft.ft_tparams in
let (fuel, tparams_doc) =
(* only print tparams when they have been instantiated with targs
* so that they correctly express reified parameterization *)
match (tparams, get_ft_ftk ft) with
| ([], _)
| (_, FTKtparams) ->
(fuel, Nothing)
| (l, FTKinstantiated_targs) ->
list ~fuel "<" (tparam ~ty to_doc st penv) l ">"
in
let (fuel, return_doc) =
possibly_enforced_ty ~fuel ~ty to_doc st penv ft.ft_ret
in
let (fuel, capabilities_doc) =
fun_implicit_params
~fuel
to_doc
st
penv
ft.ft_tparams
ft.ft_implicit_params
in
let (fuel, params_doc) = list ~fuel "(" id params ")" in
let tparams_doc =
Span
[
tparams_doc;
params_doc;
capabilities_doc;
Space;
(if get_ft_returns_readonly ft then
text "readonly" ^^ Space
else
Nothing);
return_doc;
]
in
(fuel, tparams_doc)
and possibly_enforced_ty ~fuel ~ty to_doc st penv { et_enforced; et_type } =
let (fuel, d) = ty ~fuel to_doc st penv et_type in
let d =
Concat
[
(if show_verbose penv then
match et_enforced with
| Enforced -> text "enforced" ^^ Space
| Unenforced -> Nothing
else
Nothing);
d;
]
in
(fuel, d)
and fun_param ~fuel ~ty to_doc st penv ({ fp_name; fp_type; _ } as fp) =
let (fuel, d) = ty ~fuel to_doc st penv fp_type.et_type in
let (fuel, d) =
match (fp_name, d) with
| (None, _) -> possibly_enforced_ty ~fuel ~ty to_doc st penv fp_type
| (Some param_name, Text ("_", 1)) ->
(* Handle the case of missing a type by not printing it *)
(fuel, text param_name)
| (Some param_name, _) ->
let (fuel, d) = possibly_enforced_ty ~fuel ~ty to_doc st penv fp_type in
let d = Concat [d; Space; text param_name] in
(fuel, d)
in
let d =
Concat
[
(match get_fp_mode fp with
| FPinout -> text "inout" ^^ Space
| _ -> Nothing);
(match get_fp_readonly fp with
| true -> text "readonly" ^^ Space
| false -> Nothing);
d;
(if get_fp_has_default fp then
text " = _"
else
Nothing);
]
in
(fuel, d)
and tparam
~fuel
~ty
to_doc
st
env
{ tp_name = (_, x); tp_constraints = cstrl; tp_reified = r; _ } =
let cstrl =
List.filter cstrl ~f:(fun cstr ->
match cstr with
| (Ast_defs.Constraint_as, ty) when is_supportdyn_mixed env ty ->
false
| _ -> true)
in
let (fuel, tparam_constraints_doc) =
list_sep
~fuel
~split:false
Space
(tparam_constraint ~ty to_doc st env)
cstrl
in
let tparam_doc =
Concat
[
begin
match r with
| Nast.Erased -> Nothing
| Nast.SoftReified -> text "<<__Soft>> reify" ^^ Space
| Nast.Reified -> text "reify" ^^ Space
end;
text x;
tparam_constraints_doc;
]
in
(fuel, tparam_doc)
and tparam_constraint ~fuel ~ty to_doc st penv (ck, cty) =
let (fuel, constraint_ty_doc) = ty ~fuel to_doc st penv cty in
let constraint_doc =
Concat
[
Space;
text
(match ck with
| Ast_defs.Constraint_as -> "as"
| Ast_defs.Constraint_super -> "super"
| Ast_defs.Constraint_eq -> "=");
Space;
constraint_ty_doc;
]
in
(fuel, constraint_doc)
let tprim x = text @@ Aast_defs.string_of_tprim x
let tfun ~fuel ~ty to_doc st penv ft fun_implicit_params =
let (fuel, fun_type_doc) =
fun_type ~fuel ~ty to_doc st penv ft fun_implicit_params
in
let tfun_doc =
Concat
[
text "(";
(if get_ft_readonly_this ft then
text "readonly "
else
Nothing);
text "function";
fun_type_doc;
text ")";
]
in
(fuel, tfun_doc)
let ttuple ~fuel k tyl = list ~fuel "(" k tyl ")"
let tshape ~fuel k to_doc penv s is_open_mixed =
let { s_origin = _; s_unknown_value = shape_kind; s_fields = fdm } = s in
let open_mixed = is_open_mixed penv shape_kind in
let (fuel, fields_doc) =
let f_field (shape_map_key, { sft_optional; sft_ty }) ~fuel =
let key_delim =
match shape_map_key with
| Typing_defs.TSFlit_str _ -> text "'"
| _ -> Nothing
in
let (fuel, sft_ty_doc) = k ~fuel sft_ty in
let field_doc =
Concat
[
(if sft_optional then
text "?"
else
Nothing);
key_delim;
to_doc (Typing_defs.TShapeField.name shape_map_key);
key_delim;
Space;
text "=>";
Space;
sft_ty_doc;
]
in
(fuel, field_doc)
in
shape_map ~fuel fdm f_field
in
let (fuel, fields_doc) =
begin
if Typing_defs.is_nothing shape_kind then
(fuel, fields_doc)
else if open_mixed then
(fuel, fields_doc @ [text "..."])
else
let (fuel, ty_doc) = k ~fuel shape_kind in
( fuel,
fields_doc @ [Concat [text "_"; Space; text "=>"; Space; ty_doc]] )
end
in
list ~fuel "shape(" id fields_doc ")"
let refinement (type a) ~fuel k ({ cr_consts } : a class_refinement) =
let f_rc ~fuel (name, (rc : a refined_const)) =
let (fuel, rc_doc) =
match rc.rc_bound with
| TRexact ty ->
let (fuel, ty_doc) = k ~fuel ty in
(fuel, Concat [text "= "; ty_doc])
| TRloose { tr_lower = ls; tr_upper = us } ->
let bound kind (fuel, docs) ty =
let (fuel, ty_doc) = k ~fuel ty in
(fuel, (text (kind ^ " ") ^^ ty_doc) :: docs)
in
let (fuel, docs) = List.fold ~init:(fuel, []) ~f:(bound "super") ls in
let (fuel, docs) = List.fold ~init:(fuel, docs) ~f:(bound "as") us in
list_sep ~fuel Space id docs
in
(fuel, text (refined_const_kind_str rc ^ " " ^ name ^ " ") ^^ rc_doc)
in
delimited_list ~fuel semi_sep "{ " f_rc (SMap.bindings cr_consts) " }"
let refinements ~fuel k e =
match e with
| Exact -> (fuel, Nothing)
| Nonexact r ->
if Class_refinement.is_empty r then
(fuel, Nothing)
else
let (fuel, r_doc) = refinement ~fuel k r in
(fuel, Concat [Space; text "with"; Space; r_doc])
let thas_member ~fuel k hm =
let { hm_name = (_, name); hm_type; hm_class_id = _; hm_explicit_targs } =
hm
in
(* TODO: T71614503 print explicit type arguments appropriately *)
let printed_explicit_targs =
match hm_explicit_targs with
| None -> text "None"
| Some _ -> text "Some <targs>"
in
let (fuel, hm_ty_doc) = k ~fuel hm_type in
let has_member_doc =
Concat
[
text "has_member";
text "(";
text name;
comma_sep;
hm_ty_doc;
comma_sep;
printed_explicit_targs;
text ")";
]
in
(fuel, has_member_doc)
let tcan_index ~fuel k ci =
let (fuel, key_doc) = k ~fuel ci.ci_key in
let (fuel, val_doc) = k ~fuel ci.ci_val in
( fuel,
match ci.ci_shape with
| None ->
Concat
[text "can_index"; text "("; key_doc; comma_sep; val_doc; text ")"]
| Some _ft ->
Concat
[
text "can_index";
text "(";
key_doc;
text "(shape_field)";
comma_sep;
val_doc;
text ")";
] )
let tcan_traverse ~fuel k ct =
match ct.ct_key with
| None ->
let (fuel, val_doc) = k ~fuel ct.ct_val in
( fuel,
Concat
[
text "can_traverse";
text "(";
val_doc;
comma_sep;
text "is_await:";
text (string_of_bool ct.ct_is_await);
text ")";
] )
| Some ct_key ->
let (fuel, key_doc) = k ~fuel ct_key in
let (fuel, val_doc) = k ~fuel ct.ct_val in
( fuel,
Concat
[
text "can_traverse";
text "(";
key_doc;
comma_sep;
val_doc;
comma_sep;
text "is_await:";
text (string_of_bool ct.ct_is_await);
text ")";
] )
let tdestructure ~fuel (k : fuel:Fuel.t -> locl_ty -> Fuel.t * Doc.t) d =
let { d_required; d_optional; d_variadic; d_kind } = d in
let (fuel, e_required) =
List.fold_map d_required ~f:(fun fuel ty -> k ~fuel ty) ~init:fuel
in
let (fuel, e_optional) =
List.fold_map d_optional ~init:fuel ~f:(fun fuel v ->
let (fuel, ty_doc) = k ~fuel v in
let doc = Concat [text "=_"; ty_doc] in
(fuel, doc))
in
let (fuel, e_variadic) =
Option.value_map
~default:(fuel, [])
~f:(fun v ->
let (fuel, ty_doc) = k ~fuel v in
let doc = [Concat [text "..."; ty_doc]] in
(fuel, doc))
d_variadic
in
let prefix =
match d_kind with
| ListDestructure -> text "list"
| SplatUnpack -> text "splat"
in
let (fuel, doc) =
list ~fuel "(" id (e_required @ e_optional @ e_variadic) ")"
in
let doc = Concat [prefix; doc] in
(fuel, doc)
let rec is_open_mixed_decl penv t =
match get_node t with
| Tapply ((_, n), [ty])
when String.equal n SN.Classes.cSupportDyn
&& not (show_supportdyn_penv penv) ->
is_open_mixed_decl penv ty
| Toption t ->
(match get_node t with
| Tnonnull -> true
| _ -> false)
| _ -> false
(* Prints a decl_ty. If there isn't enough fuel, the type is omitted. Each
recursive call to print a type depletes the fuel by one. *)
let rec decl_ty ~fuel : _ -> _ -> _ -> decl_ty -> Fuel.t * Doc.t =
fun to_doc st penv x ->
Fuel.provide fuel (decl_ty_ to_doc st penv (get_node x))
and decl_ty_ ~fuel : _ -> _ -> _ -> decl_phase ty_ -> Fuel.t * Doc.t =
fun to_doc st penv x ->
let ty = decl_ty in
let k ~fuel x = ty ~fuel to_doc st penv x in
match x with
| Tany _ -> (fuel, text "_")
| Tthis -> (fuel, text SN.Typehints.this)
| Tmixed -> (fuel, text "mixed")
| Twildcard -> (fuel, text "_")
| Tdynamic -> (fuel, text "dynamic")
| Tnonnull -> (fuel, text "nonnull")
| Tvec_or_dict (x, y) -> list ~fuel "vec_or_dict<" k [x; y] ">"
| Tapply ((_, s), []) -> (fuel, to_doc s)
| Tgeneric (s, []) -> (fuel, to_doc s)
| Taccess (root_ty, id) ->
let (fuel, root_ty_doc) = k ~fuel root_ty in
let access_doc = Concat [root_ty_doc; text "::"; to_doc (snd id)] in
(fuel, access_doc)
| Trefinement (root_ty, r) ->
let (fuel, root_ty_doc) = k ~fuel root_ty in
let (fuel, rs_doc) = refinement ~fuel k r in
(fuel, root_ty_doc ^^ text " with " ^^ rs_doc)
| Toption x ->
let (fuel, ty_doc) = k ~fuel x in
let option_doc = Concat [text "?"; ty_doc] in
(fuel, option_doc)
| Tlike x ->
let (fuel, ty_doc) = k ~fuel x in
let like_doc = Concat [text "~"; ty_doc] in
(fuel, like_doc)
| Tprim x -> (fuel, tprim x)
| Tfun ft -> tfun ~fuel ~ty to_doc st penv ft fun_decl_implicit_params
| Tnewtype (n, _, ty)
when String.equal n SN.Classes.cSupportDyn
&& not (show_supportdyn_penv penv) ->
k ~fuel ty
| Tapply ((_, n), [ty])
when String.equal n SN.Classes.cSupportDyn
&& not (show_supportdyn_penv penv) ->
k ~fuel ty
(* Don't strip_ns here! We want the FULL type, including the initial slash.
*)
| Tapply ((_, s), tyl)
| Tnewtype (s, tyl, _)
| Tgeneric (s, tyl) ->
let (fuel, tys_doc) = list ~fuel "<" k tyl ">" in
let generic_doc = to_doc s ^^ tys_doc in
(fuel, generic_doc)
| Ttuple tyl -> ttuple ~fuel k tyl
| Tunion tyl ->
let (fuel, tys_doc) = ttuple ~fuel k tyl in
let union_doc = Concat [text "|"; tys_doc] in
(fuel, union_doc)
| Tintersection tyl ->
let (fuel, tys_doc) = ttuple ~fuel k tyl in
let intersection_doc = Concat [text "&"; tys_doc] in
(fuel, intersection_doc)
| Tshape s -> tshape ~fuel k to_doc penv s is_open_mixed_decl
(* TODO (T86471586): Display capabilities that are decls for functions *)
and fun_decl_implicit_params ~fuel _to_doc _st _penv _tparams _implicit_param
=
(fuel, text ":")
(* For a given type parameter, construct a list of its constraints *)
let get_constraints_on_tparam penv tparam =
let kind_opt = Typing_env_types.get_pos_and_kind_of_generic penv tparam in
match kind_opt with
| None -> []
| Some (_pos, kind) ->
(* Use the names of the parameters themselves to present bounds
depending on other parameters *)
let param_names = Type_parameter_env.get_parameter_names kind in
let params =
List.map param_names ~f:(fun name ->
Typing_make_type.generic Reason.none name)
in
let lower = Typing_env_types.get_lower_bounds penv tparam params in
let upper = Typing_env_types.get_upper_bounds penv tparam params in
let equ = Typing_env_types.get_equal_bounds penv tparam params in
let upper =
if show_supportdyn penv then
upper
else
(* Don't show "as mixed" if we're not printing supportdyn *)
TySet.remove
Typing_make_type.(supportdyn Reason.Rnone (mixed Reason.Rnone))
upper
in
(* If we have an equality we can ignore the other bounds *)
if not (TySet.is_empty equ) then
List.map (TySet.elements equ) ~f:(fun ty ->
(tparam, Ast_defs.Constraint_eq, ty))
else
List.map (TySet.elements lower) ~f:(fun ty ->
(tparam, Ast_defs.Constraint_super, ty))
@ List.map (TySet.elements upper) ~f:(fun ty ->
(tparam, Ast_defs.Constraint_as, ty))
let rec is_open_mixed env t =
match get_node t with
| Tnewtype (n, _, ty)
when String.equal n SN.Classes.cSupportDyn && not (show_supportdyn env) ->
is_open_mixed env ty
| Toption t ->
let (_, t) = Typing_inference_env.expand_type env.inference_env t in
(match get_node t with
| Tnonnull -> true
| _ -> false)
| _ -> false
(* Prints a locl_ty. If there isn't enough fuel, the type is omitted. Each
recursive call to print a type depletes the fuel by one. *)
let rec locl_ty ~fuel : _ -> _ -> _ -> locl_ty -> Fuel.t * Doc.t =
fun to_doc st penv ty ->
Fuel.provide fuel (fun ~fuel ->
let (r, x) = deref ty in
let (fuel, d) = locl_ty_ ~fuel to_doc st penv x in
let d =
match r with
| Reason.Rsolve_fail _ -> Concat [text "{suggest:"; d; text "}"]
| _ -> d
in
(fuel, d))
and locl_ty_ ~fuel : _ -> _ -> _ -> locl_phase ty_ -> Fuel.t * Doc.t =
fun to_doc st penv x ->
let ty = locl_ty in
let verbose = show_verbose penv in
let env =
match penv with
| Declenv -> failwith "must provide a locl-env here"
| Loclenv env -> env
in
let k ~fuel x = ty ~fuel to_doc st (Loclenv env) x in
match x with
| Tany _ -> (fuel, text "_")
| Tdynamic -> (fuel, text "dynamic")
| Tnonnull -> (fuel, text "nonnull")
| Tvec_or_dict (x, y) -> list ~fuel "vec_or_dict<" k [x; y] ">"
| Toption ty -> begin
match deref ty with
| (_, Tnonnull) -> (fuel, text "mixed")
| (r, Tunion tyl) when List.exists ~f:is_dynamic tyl ->
(* Unions with null become Toption, which leads to the awkward ?~...
* The Tunion case can better handle this *)
k ~fuel (mk (r, Tunion (mk (r, Tprim Nast.Tnull) :: tyl)))
| _ ->
let (fuel, d) = k ~fuel ty in
(fuel, Concat [text "?"; d])
end
| Tprim x -> (fuel, tprim x)
| Tneg (Neg_prim x) -> (fuel, Concat [text "not "; tprim x])
| Tneg (Neg_class c) -> (fuel, Concat [text "not "; to_doc (snd c)])
| Tvar n ->
let (_, ety) =
Typing_inference_env.expand_type
env.inference_env
(mk (Reason.Rnone, Tvar n))
in
begin
match deref ety with
(* For unsolved type variables, always show the type variable *)
| (_, Tvar n') ->
let tvar_doc =
if ISet.mem n' st then
text "[rec]"
else if !blank_tyvars then
text "_"
else
text ("#" ^ string_of_int n')
in
(fuel, tvar_doc)
| _ ->
let prepend =
if ISet.mem n st then
text "[rec]"
else if
(* For hh_show_env we further show the type variable number *)
show_verbose penv
then
text ("#" ^ string_of_int n)
else
Nothing
in
let st = ISet.add n st in
let (fuel, ty_doc) = ty ~fuel to_doc st penv ety in
(fuel, Concat [prepend; ty_doc])
end
| Tfun ft -> tfun ~fuel ~ty to_doc st penv ft fun_locl_implicit_params
| Tclass ((_, s), exact, tyl) ->
let (fuel, targs_doc) =
if List.is_empty tyl then
(fuel, Nothing)
else
list ~fuel "<" k tyl ">"
in
let (fuel, with_doc) = refinements ~fuel k exact in
let class_doc = to_doc s ^^ targs_doc ^^ with_doc in
let class_doc =
match exact with
| Exact when !debug_mode -> Concat [text "exact"; Space; class_doc]
| _ -> class_doc
in
(fuel, class_doc)
| Tgeneric (s, []) when SN.Coeffects.is_generated_generic s -> begin
match String.get s 2 with
| '[' ->
(* has the form T/[...] *)
(fuel, to_doc (String.sub s ~pos:3 ~len:(String.length s - 4)))
| '$' -> begin
(* Generic replacement type for parameter used for dependent context *)
match get_constraints_on_tparam env s with
| [(_, Ast_defs.Constraint_as, ty)] ->
locl_ty ~fuel to_doc st (Loclenv env) ty
| _ -> (* this case shouldn't occur *) (fuel, to_doc s)
end
| _ -> (fuel, to_doc s)
end
| Tunapplied_alias s
| Tnewtype (s, [], _)
| Tgeneric (s, []) ->
(fuel, to_doc s)
| Tnewtype (n, _, ty)
when String.equal n SN.Classes.cSupportDyn
&& not (show_supportdyn_penv penv) ->
k ~fuel ty
| Tnewtype (s, tyl, _)
| Tgeneric (s, tyl) ->
let (fuel, tys_doc) = list ~fuel "<" k tyl ">" in
let generic_doc = to_doc s ^^ tys_doc in
(fuel, generic_doc)
| Tdependent (dep, cstr) ->
let (fuel, cstr_doc) = k ~fuel cstr in
let cstr_info = Concat [Space; text "as"; Space; cstr_doc] in
let dependent_doc =
Concat [to_doc @@ DependentKind.to_string dep; cstr_info]
in
(fuel, dependent_doc)
(* Don't strip_ns here! We want the FULL type, including the initial slash.
*)
| Ttuple tyl -> ttuple ~fuel k tyl
| Tunion [] -> (fuel, text "nothing")
| Tunion tyl ->
let tyl =
List.fold_right tyl ~init:TySet.empty ~f:TySet.add |> TySet.elements
in
let (dynamic, null, nonnull) =
List.partition3_map tyl ~f:(fun t ->
match get_node t with
| Tdynamic -> `Fst t
| Tprim Nast.Tnull -> `Snd t
| _ -> `Trd t)
in
begin
match
(not @@ List.is_empty dynamic, not @@ List.is_empty null, nonnull)
with
| (false, false, []) -> (fuel, text "nothing")
(* type isn't nullable or dynamic *)
| (false, false, [ty]) ->
if verbose then
let (fuel, ty_doc) = k ~fuel ty in
let doc = Concat [text "("; ty_doc; text ")"] in
(fuel, doc)
else
k ~fuel ty
| (false, false, _ :: _) ->
delimited_list ~fuel (Space ^^ text "|" ^^ Space) "(" k nonnull ")"
(* Type only is null *)
| (false, true, []) ->
let doc =
if verbose then
text "(null)"
else
text "null"
in
(fuel, doc)
(* Type only is dynamic *)
| (true, false, []) ->
let doc =
if verbose then
text "(dynamic)"
else
text "dynamic"
in
(fuel, doc)
(* Type is nullable single type *)
| (false, true, [ty]) ->
let (fuel, ty_doc) = k ~fuel ty in
let doc =
if verbose then
Concat [text "(null |"; ty_doc; text ")"]
else
Concat [text "?"; ty_doc]
in
(fuel, doc)
(* Type is like single type *)
| (true, false, [ty]) ->
let (fuel, ty_doc) = k ~fuel ty in
let doc =
if verbose then
Concat [text "(dynamic |"; ty_doc; text ")"]
else
Concat [text "~"; ty_doc]
in
(fuel, doc)
(* Type is like null *)
| (true, true, []) ->
let doc =
if verbose then
text "(dynamic | null)"
else
text "~null"
in
(fuel, doc)
(* Type is like nullable single type *)
| (true, true, [ty]) ->
let (fuel, ty_doc) = k ~fuel ty in
let doc =
if verbose then
Concat [text "(dynamic | null |"; ty_doc; text ")"]
else
Concat [text "~?"; ty_doc]
in
(fuel, doc)
| (true, false, _ :: _) ->
let (fuel, tys_doc) =
delimited_list ~fuel (Space ^^ text "|" ^^ Space) "(" k nonnull ")"
in
let doc = Concat [text "~"; tys_doc] in
(fuel, doc)
| (false, true, _ :: _) ->
let (fuel, tys_doc) =
delimited_list ~fuel (Space ^^ text "|" ^^ Space) "(" k nonnull ")"
in
let doc = Concat [text "?"; tys_doc] in
(fuel, doc)
| (true, true, _ :: _) ->
let (fuel, tys_doc) =
delimited_list ~fuel (Space ^^ text "|" ^^ Space) "(" k nonnull ")"
in
let doc = Concat [text "~"; text "?"; tys_doc] in
(fuel, doc)
end
| Tintersection [] -> (fuel, text "mixed")
| Tintersection tyl ->
delimited_list ~fuel (Space ^^ text "&" ^^ Space) "(" k tyl ")"
| Tshape s -> tshape ~fuel k to_doc env s is_open_mixed
| Taccess (root_ty, id) ->
let (fuel, root_ty_doc) = k ~fuel root_ty in
let access_doc = Concat [root_ty_doc; text "::"; to_doc (snd id)] in
(fuel, access_doc)
and fun_locl_implicit_params ~fuel to_doc st penv tparams { capability } =
let (fuel, capabilities) =
match capability with
| CapDefaults _ -> (fuel, None)
| CapTy t ->
let default_capability : locl_ty =
Typing_make_type.default_capability Pos_or_decl.none
in
if ty_equal ~normalize_lists:true t default_capability then
(fuel, None)
else (
match get_node t with
| Tintersection [] -> (fuel, Some [])
| Toption t -> begin
match deref t with
| (_, Tnonnull) -> (fuel, Some [])
| _ ->
let (fuel, cap) = locl_ty ~fuel to_doc st penv t in
(fuel, Some [cap])
end
| _ ->
let (fuel, cap) = locl_ty ~fuel to_doc st penv t in
(fuel, Some [cap])
)
in
let (ctx_names, _) = split_desugared_ctx_tparams tparams in
let ctx_names = List.map ctx_names ~f:(fun name -> text name) in
match (capabilities, ctx_names) with
| (None, []) -> (fuel, text ":")
| (None, ctx_names) -> (fuel, Concat [text "["; Concat ctx_names; text "]:"])
| (Some capabilities, ctx_names) ->
(fuel, Concat [text "["; Concat (capabilities @ ctx_names); text "]:"])
let rec constraint_type_ ~fuel to_doc st penv x =
let k ~fuel lty = locl_ty ~fuel to_doc st penv lty in
let k' ~fuel cty = constraint_type ~fuel to_doc st penv cty in
match x with
| Thas_member hm -> thas_member ~fuel k hm
| Thas_type_member htm ->
let { htm_id = id; htm_lower = lo; htm_upper = up } = htm in
let subtype = Concat [Space; text "<:"; Space] in
let (fuel, lo_doc) = k ~fuel lo in
let (fuel, up_doc) = k ~fuel up in
let has_type_member_doc =
Concat
[
text "has_type_member(";
lo_doc;
subtype;
text id;
subtype;
up_doc;
text ")";
]
in
(fuel, has_type_member_doc)
| Tdestructure d -> tdestructure ~fuel k d
| Tcan_index ci -> tcan_index ~fuel k ci
| Tcan_traverse ct -> tcan_traverse ~fuel k ct
| TCunion (lty, cty) ->
let (fuel, lty_doc) = k ~fuel lty in
let (fuel, cty_doc) = k' ~fuel cty in
let cunion_doc =
Concat [text "("; lty_doc; text "|"; cty_doc; text ")"]
in
(fuel, cunion_doc)
| TCintersection (lty, cty) ->
let (fuel, lty_doc) = k ~fuel lty in
let (fuel, cty_doc) = k' ~fuel cty in
let cintersection_doc =
Concat [text "("; lty_doc; text "&"; cty_doc; text ")"]
in
(fuel, cintersection_doc)
and constraint_type ~fuel to_doc st penv ty =
let (r, x) = deref_constraint_type ty in
let (fuel, constraint_ty_doc) = constraint_type_ ~fuel to_doc st penv x in
let constraint_ty_doc =
match r with
| Reason.Rsolve_fail _ ->
Concat [text "{suggest:"; constraint_ty_doc; text "}"]
| _ -> constraint_ty_doc
in
(fuel, constraint_ty_doc)
let internal_type ~fuel to_doc st penv ty =
match ty with
| LoclType ty -> locl_ty ~fuel to_doc st penv ty
| ConstraintType ty -> constraint_type ~fuel to_doc st penv ty
let to_string ~fuel ~ty to_doc env x =
let (fuel, doc) = ty ~fuel to_doc ISet.empty env x in
let str = Libhackfmt.format_doc_unbroken format_env doc |> String.strip in
(fuel, str)
(* Print a suffix for type parameters in typ that have constraints
* If the type itself is a type parameter with a single constraint, just
* represent this as `as t` or `super t`, otherwise use full `where` syntax
*)
let constraints_for_type ~fuel to_doc env typ =
let tparams =
SSet.elements
(Typing_env_types.get_tparams_in_ty_and_acc env SSet.empty typ)
in
let constraints =
List.concat_map tparams ~f:(get_constraints_on_tparam env)
in
let (_, typ) = Typing_inference_env.expand_type env.inference_env typ in
let penv = Loclenv env in
match (get_node typ, constraints) with
| (_, []) -> (fuel, Nothing)
| (Tgeneric (tparam, []), [(tparam', ck, typ)])
when String.equal tparam tparam' ->
tparam_constraint ~fuel ~ty:locl_ty to_doc ISet.empty penv (ck, typ)
| _ ->
let to_tparam_constraint_doc ~fuel (tparam, ck, typ) =
let (fuel, tparam_constraint_doc) =
tparam_constraint ~fuel ~ty:locl_ty to_doc ISet.empty penv (ck, typ)
in
let doc = Concat [text tparam; tparam_constraint_doc] in
(fuel, doc)
in
let (fuel, tparam_constraints_doc) =
list_sep ~fuel comma_sep to_tparam_constraint_doc constraints
in
let doc =
Concat
[
Newline;
text "where";
Space;
WithRule (Rule.Parental, tparam_constraints_doc);
]
in
(fuel, doc)
let to_string_rec ~fuel penv n x =
let (fuel, doc) =
locl_ty ~fuel text_strip_ns (ISet.add n ISet.empty) penv x
in
let str = Libhackfmt.format_doc_unbroken format_env doc |> String.strip in
(fuel, str)
let to_string_strip_ns ~fuel ~ty env x =
to_string ~fuel ~ty text_strip_ns env x
let to_string_decl ~fuel (x : decl_ty) =
let ty = decl_ty in
to_string ~fuel ~ty Doc.text Declenv x
let fun_to_string ~fuel (x : decl_fun_type) =
let ty = decl_ty in
let (fuel, doc) =
fun_type ~fuel ~ty Doc.text ISet.empty Declenv x fun_decl_implicit_params
in
let str = Libhackfmt.format_doc_unbroken format_env doc |> String.strip in
(fuel, str)
let to_string_with_identity ~fuel env x occurrence definition_opt =
let open SymbolOccurrence in
let ty = locl_ty in
let penv = Loclenv env in
let prefix =
SymbolDefinition.(
let print_mod m = text (string_of_modifier m) ^^ Space in
match (definition_opt, occurrence.type_) with
| (None, _) -> Nothing
| (_, XhpLiteralAttr _) -> Nothing
| (Some def, _) -> begin
match def.modifiers with
| [] -> Nothing
(* It looks weird if we line break after a single modifier. *)
| [m] -> print_mod m
| ms -> Concat (List.map ms ~f:print_mod) ^^ SplitWith Cost.Base
end)
in
(* For functions and methods, interpret supportdyn as use of <<__SupportDynamicType>> attribute *)
let (prefix, x) =
match (occurrence, get_node x) with
| ({ type_ = Function | Method _; _ }, Tnewtype (name, [tyarg], _))
when String.equal name SN.Classes.cSupportDyn ->
if show_supportdyn env then
(text "<<__SupportDynamicType>>" ^^ Newline ^^ prefix, tyarg)
else
(prefix, tyarg)
| (_, _) -> (prefix, x)
in
let (fuel, body_doc) =
match (occurrence, get_node x) with
| ({ type_ = Class _; name; _ }, _) ->
let keyword =
match Decl_provider.get_class env.decl_env.Decl_env.ctx name with
| Some decl ->
(match Cls.kind decl with
| Ast_defs.Cclass _ -> "class"
| Ast_defs.Cinterface -> "interface"
| Ast_defs.Ctrait -> "trait"
| Ast_defs.Cenum -> "enum"
| Ast_defs.Cenum_class _ -> "enum class")
| None -> "class"
in
(fuel, Concat [text keyword; Space; text_strip_ns name])
| ({ type_ = Function; name; _ }, Tfun ft)
| ({ type_ = Method (_, name); _ }, Tfun ft) ->
(* Use short names for function types since they display a lot more
information to the user. *)
let (fuel, fun_ty_doc) =
fun_type
~fuel
~ty
text_strip_ns
ISet.empty
penv
ft
fun_locl_implicit_params
in
let fun_doc =
Concat [text "function"; Space; text_strip_all_ns name; fun_ty_doc]
in
(fuel, fun_doc)
| ({ type_ = Property (_, name); _ }, _) ->
let (fuel, ty_doc) = ty ~fuel text_strip_ns ISet.empty penv x in
let name =
if String.is_prefix name ~prefix:"$" then
(* Static property *)
name
else
(* Instance property *)
"$" ^ name
in
let doc = Concat [ty_doc; Space; Doc.text name] in
(fuel, doc)
| ({ type_ = XhpLiteralAttr _; name; _ }, _) ->
let (fuel, ty_doc) = ty ~fuel text_strip_ns ISet.empty penv x in
let doc =
Concat
[Doc.text "attribute"; Space; ty_doc; Space; text_strip_ns name]
in
(fuel, doc)
| ({ type_ = ClassConst (_, name); _ }, _) ->
let (fuel, ty_doc) = ty ~fuel text_strip_ns ISet.empty penv x in
let doc =
Concat [Doc.text "const"; Space; ty_doc; Space; text_strip_ns name]
in
(fuel, doc)
| ({ type_ = GConst; name; _ }, _)
| ({ type_ = EnumClassLabel _; name; _ }, _) ->
let (fuel, ty_doc) = ty ~fuel text_strip_ns ISet.empty penv x in
let doc = Concat [ty_doc; Space; text_strip_ns name] in
(fuel, doc)
| _ -> ty ~fuel text_strip_ns ISet.empty penv x
in
let (fuel, constraints) = constraints_for_type ~fuel text_strip_ns env x in
let str =
Concat [prefix; body_doc; constraints]
|> Libhackfmt.format_doc format_env
|> String.strip
in
(fuel, str)
end
let with_blank_tyvars f =
Full.blank_tyvars := true;
let res = f () in
Full.blank_tyvars := false;
res
(*****************************************************************************)
(* Computes the string representing a type in an error message. *)
(*****************************************************************************)
module ErrorString = struct
let tprim = function
| Nast.Tnull -> "null"
| Nast.Tvoid -> "void"
| Nast.Tint -> "an int"
| Nast.Tbool -> "a bool"
| Nast.Tfloat -> "a float"
| Nast.Tstring -> "a string"
| Nast.Tnum -> "a num (int | float)"
| Nast.Tresource -> "a resource"
| Nast.Tarraykey -> "an array key (int | string)"
| Nast.Tnoreturn -> "noreturn (throws or exits)"
let rec type_ ~fuel ?(ignore_dynamic = false) env ety =
let ety_to_string ety =
with_blank_tyvars (fun () ->
Full.to_string_strip_ns ~fuel ~ty:Full.locl_ty (Loclenv env) ety)
in
match get_node ety with
| Tany _ -> (fuel, "an untyped value")
| Tdynamic -> (fuel, "a dynamic value")
| Tunion l when ignore_dynamic ->
union ~fuel env (List.filter l ~f:(fun x -> not (is_dynamic x)))
| Tunion l -> union ~fuel env l
| Tintersection [] -> (fuel, "a mixed value")
| Tintersection l -> intersection ~fuel env l
| Tvec_or_dict _ -> (fuel, "a vec_or_dict")
| Ttuple l -> (fuel, "a tuple of size " ^ string_of_int (List.length l))
| Tnonnull -> (fuel, "a nonnull value")
| Toption x ->
let str =
match get_node x with
| Tnonnull -> "a mixed value"
| _ -> "a nullable type"
in
(fuel, str)
| Tprim tp -> (fuel, tprim tp)
| Tvar _ -> (fuel, "some value")
| Tfun _ -> (fuel, "a function")
| Tgeneric (s, _) when DependentKind.is_generic_dep_ty s ->
let (fuel, ty_str) = ety_to_string ety in
(fuel, "the expression dependent type " ^ ty_str)
| Tgeneric _ ->
let (fuel, ty_str) = ety_to_string ety in
(fuel, "a value of generic type " ^ ty_str)
| Tnewtype (n, _, ty)
when String.equal n SN.Classes.cSupportDyn && not (show_supportdyn env) ->
type_ ~fuel env ty
| Tnewtype (x, _, _) when String.equal x SN.Classes.cClassname ->
(fuel, "a classname string")
| Tnewtype (x, _, _) when String.equal x SN.Classes.cTypename ->
(fuel, "a typename string")
| Tnewtype _ ->
let (fuel, ty_str) = ety_to_string ety in
(fuel, "a value of type " ^ ty_str)
| Tdependent (dep, _cstr) -> (fuel, dependent dep)
| Tclass (_, e, _) ->
let (fuel, ty_str) = ety_to_string ety in
let prefix =
match e with
| Exact -> "an object of exactly the class "
| Nonexact _ -> "an object of type "
in
(fuel, prefix ^ ty_str)
| Tshape _ -> (fuel, "a shape")
| Tunapplied_alias _ ->
(* FIXME it seems like this function is only for
fully-applied types? Tunapplied_alias should only appear
in a type argument position then, which inst below
prints with a different function (namely Full.locl_ty) *)
failwith "Tunapplied_alias is not a type"
| Taccess (_ty, _id) -> (fuel, "a type constant")
| Tneg (Neg_prim p) -> (fuel, "anything but a " ^ tprim p)
| Tneg (Neg_class (_, c)) -> (fuel, "anything but a " ^ strip_ns c)
and dependent dep =
let x = strip_ns @@ DependentKind.to_string dep in
match dep with
| DTexpr _ -> "the expression dependent type " ^ x
and union ~fuel env l =
let (null, nonnull) =
List.partition_tf l ~f:(fun ty ->
equal_locl_ty_ (get_node ty) (Tprim Nast.Tnull))
in
let (fuel, l) =
List.fold_map nonnull ~init:fuel ~f:(fun fuel -> to_string ~fuel env)
in
let s = List.fold_right l ~f:SSet.add ~init:SSet.empty in
let l = SSet.elements s in
let str =
if List.is_empty null then
union_ l
else
"a nullable type"
in
(fuel, str)
and union_ = function
| [] -> "an undefined value"
| [x] -> x
| x :: rl -> x ^ " or " ^ union_ rl
and intersection ~fuel env l =
let (fuel, l) =
List.fold_map l ~init:fuel ~f:(fun fuel -> to_string ~fuel env)
in
let str = String.concat l ~sep:" and " in
(fuel, str)
and classish_kind c_kind final =
let fs =
if final then
" final"
else
""
in
match c_kind with
| Ast_defs.Cclass k ->
(match k with
| Ast_defs.Abstract -> "an abstract" ^ fs ^ " class"
| Ast_defs.Concrete -> "a" ^ fs ^ " class")
| Ast_defs.Cinterface -> "an interface"
| Ast_defs.Ctrait -> "a trait"
| Ast_defs.Cenum -> "an enum"
| Ast_defs.Cenum_class k ->
(match k with
| Ast_defs.Abstract -> "an abstract enum class"
| Ast_defs.Concrete -> "an enum class")
and to_string ~fuel ?(ignore_dynamic = false) env ty =
let (_, ety) = Typing_inference_env.expand_type env.inference_env ty in
type_ ~fuel ~ignore_dynamic env ety
end
module Json = struct
open Hh_json
let param_mode_to_string = function
| FPnormal -> "normal"
| FPinout -> "inout"
let string_to_param_mode = function
| "normal" -> Some FPnormal
| "inout" -> Some FPinout
| _ -> None
let is_like ty =
match get_node ty with
| Tunion tyl -> List.exists tyl ~f:is_dynamic
| _ -> false
let rec from_type : env -> show_like_ty:bool -> locl_ty -> json =
fun env ~show_like_ty ty ->
(* Helpers to construct fields that appear in JSON rendering of type *)
let obj x = JSON_Object x in
let kind p k = [("src_pos", Pos_or_decl.json p); ("kind", JSON_String k)] in
let args tys =
[("args", JSON_Array (List.map tys ~f:(from_type env ~show_like_ty)))]
in
let refs e =
match e with
| Exact -> []
| Nonexact r when Class_refinement.is_empty r -> []
| Nonexact { cr_consts } ->
let ref_const (id, { rc_bound; rc_is_ctx }) =
let is_ctx_json = ("is_ctx", JSON_Bool rc_is_ctx) in
match rc_bound with
| TRexact ty ->
obj
[
("type", JSON_String id);
("equal", from_type env ~show_like_ty ty);
is_ctx_json;
]
| TRloose { tr_lower; tr_upper } ->
let ty_list tys =
JSON_Array (List.map tys ~f:(from_type env ~show_like_ty))
in
obj
[
("type", JSON_String id);
("lower", ty_list tr_lower);
("upper", ty_list tr_upper);
is_ctx_json;
]
in
[("refs", JSON_Array (List.map (SMap.bindings cr_consts) ~f:ref_const))]
in
let typ ty = [("type", from_type env ~show_like_ty ty)] in
let result ty = [("result", from_type env ~show_like_ty ty)] in
let name x = [("name", JSON_String x)] in
let optional x = [("optional", JSON_Bool x)] in
let is_array x = [("is_array", JSON_Bool x)] in
let make_field (k, v) =
let shape_field_name_to_json shape_field =
(* TODO: need to update userland tooling? *)
match shape_field with
| Typing_defs.TSFlit_int (_, s) -> Hh_json.JSON_Number s
| Typing_defs.TSFlit_str (_, s) -> Hh_json.JSON_String s
| Typing_defs.TSFclass_const ((_, s1), (_, s2)) ->
Hh_json.JSON_Array [Hh_json.JSON_String s1; Hh_json.JSON_String s2]
in
obj
@@ [("name", shape_field_name_to_json k)]
@ optional v.sft_optional
@ typ v.sft_ty
in
let fields fl = [("fields", JSON_Array (List.map fl ~f:make_field))] in
let as_type ty = [("as", from_type env ~show_like_ty ty)] in
match (get_pos ty, get_node ty) with
| (_, Tvar n) ->
let (_, ty) =
Typing_inference_env.expand_type
env.inference_env
(mk (get_reason ty, Tvar n))
in
begin
match (get_pos ty, get_node ty) with
| (p, Tvar _) -> obj @@ kind p "var"
| _ -> from_type env ~show_like_ty ty
end
| (p, Ttuple tys) -> obj @@ kind p "tuple" @ is_array false @ args tys
| (p, Tany _) -> obj @@ kind p "any"
| (p, Tnonnull) -> obj @@ kind p "nonnull"
| (p, Tdynamic) -> obj @@ kind p "dynamic"
| (p, Tgeneric (s, tyargs)) ->
obj @@ kind p "generic" @ is_array true @ name s @ args tyargs
| (p, Tunapplied_alias s) -> obj @@ kind p "unapplied_alias" @ name s
| (_, Tnewtype (s, _, ty))
when String.equal s SN.Classes.cSupportDyn && not (show_supportdyn env) ->
from_type env ~show_like_ty ty
| (p, Tnewtype (s, _, ty))
when Decl_provider.get_class env.decl_env.Decl_env.ctx s
>>| Cls.enum_type
|> Option.is_some ->
obj @@ kind p "enum" @ name s @ as_type ty
| (p, Tnewtype (s, tys, ty)) ->
obj @@ kind p "newtype" @ name s @ args tys @ as_type ty
| (p, Tdependent (DTexpr _, ty)) ->
obj
@@ kind p "path"
@ [("type", obj @@ kind (get_pos ty) "expr")]
@ as_type ty
| (p, Toption ty) -> begin
match get_node ty with
| Tnonnull -> obj @@ kind p "mixed"
| _ -> obj @@ kind p "nullable" @ args [ty]
end
| (p, Tprim tp) ->
obj @@ kind p "primitive" @ name (Aast_defs.string_of_tprim tp)
| (p, Tneg (Neg_prim tp)) ->
obj @@ kind p "negation" @ name (Aast_defs.string_of_tprim tp)
| (p, Tneg (Neg_class (_, c))) -> obj @@ kind p "negation" @ name c
| (p, Tclass ((_, cid), e, tys)) ->
obj @@ kind p "class" @ name cid @ args tys @ refs e
| (p, Tshape { s_origin = _; s_unknown_value = shape_kind; s_fields = fl })
->
let fields_known = is_nothing shape_kind in
obj
@@ kind p "shape"
@ is_array false
@ [("fields_known", JSON_Bool fields_known)]
@ fields (TShapeMap.bindings fl)
| (p, Tunion []) -> obj @@ kind p "nothing"
| (_, Tunion [ty]) -> from_type env ~show_like_ty ty
| (p, Tunion tyl) ->
if show_like_ty then
obj @@ kind p "union" @ args tyl
else begin
match List.filter tyl ~f:(fun ty -> not (is_dynamic ty)) with
| [ty] -> from_type env ~show_like_ty ty
| _ -> obj @@ kind p "union" @ args tyl
end
| (p, Tintersection []) -> obj @@ kind p "mixed"
| (_, Tintersection [ty]) -> from_type env ~show_like_ty ty
| (p, Tintersection tyl) ->
if show_like_ty then
obj @@ kind p "intersection" @ args tyl
else begin
match List.find tyl ~f:is_like with
| None -> obj @@ kind p "intersection" @ args tyl
| Some ty -> from_type env ~show_like_ty ty
end
| (p, Tfun ft) ->
let fun_kind p = kind p "function" in
let callconv cc =
[("callConvention", JSON_String (param_mode_to_string cc))]
in
let readonly_param ro =
if ro then
[("readonly", JSON_Bool true)]
else
[]
in
let param fp =
obj
@@ callconv (get_fp_mode fp)
@ readonly_param (get_fp_readonly fp)
@ typ fp.fp_type.et_type
in
let readonly_this ro =
if ro then
[("readonly_this", JSON_Bool true)]
else
[]
in
let readonly_ret ro =
if ro then
[("readonly_return", JSON_Bool true)]
else
[]
in
let params fps = [("params", JSON_Array (List.map fps ~f:param))] in
obj
@@ fun_kind p
@ readonly_this (get_ft_readonly_this ft)
@ params ft.ft_params
@ readonly_ret (get_ft_returns_readonly ft)
@ result ft.ft_ret.et_type
| (p, Tvec_or_dict (ty1, ty2)) ->
obj @@ kind p "vec_or_dict" @ args [ty1; ty2]
(* TODO akenn *)
| (p, Taccess (ty, _id)) -> obj @@ kind p "type_constant" @ args [ty]
type deserialized_result = (locl_ty, deserialization_error) result
let wrap_json_accessor f x =
match f x with
| Ok value -> Ok value
| Error access_failure ->
Error
(Deserialization_error
(Hh_json.Access.access_failure_to_string access_failure))
let get_string x = wrap_json_accessor (Hh_json.Access.get_string x)
let get_bool x = wrap_json_accessor (Hh_json.Access.get_bool x)
let get_array x = wrap_json_accessor (Hh_json.Access.get_array x)
let get_val x = wrap_json_accessor (Hh_json.Access.get_val x)
let get_obj x = wrap_json_accessor (Hh_json.Access.get_obj x)
let deserialization_error ~message ~keytrace =
Error
(Deserialization_error
(message ^ Hh_json.Access.keytrace_to_string keytrace))
let not_supported ~message ~keytrace =
Error (Not_supported (message ^ Hh_json.Access.keytrace_to_string keytrace))
let wrong_phase ~message ~keytrace =
Error (Wrong_phase (message ^ Hh_json.Access.keytrace_to_string keytrace))
let to_locl_ty
?(keytrace = []) (ctx : Provider_context.t) (json : Hh_json.json) :
deserialized_result =
let reason = Reason.none in
let ty (ty : locl_phase ty_) : deserialized_result = Ok (mk (reason, ty)) in
let rec aux (json : Hh_json.json) ~(keytrace : Hh_json.Access.keytrace) :
deserialized_result =
Result.Monad_infix.(
get_string "kind" (json, keytrace) >>= fun (kind, kind_keytrace) ->
match kind with
| "this" ->
not_supported ~message:"Cannot deserialize 'this' type." ~keytrace
| "any" -> ty (Typing_defs.make_tany ())
| "mixed" -> ty (Toption (mk (reason, Tnonnull)))
| "nonnull" -> ty Tnonnull
| "dynamic" -> ty Tdynamic
| "generic" ->
get_string "name" (json, keytrace) >>= fun (name, _name_keytrace) ->
get_bool "is_array" (json, keytrace)
>>= fun (is_array, _is_array_keytrace) ->
get_array "args" (json, keytrace) >>= fun (args, args_keytrace) ->
aux_args args ~keytrace:args_keytrace >>= fun args ->
if is_array then
ty (Tgeneric (name, args))
else
wrong_phase ~message:"Tgeneric is a decl-phase type." ~keytrace
| "enum" ->
get_string "name" (json, keytrace) >>= fun (name, _name_keytrace) ->
aux_as json ~keytrace >>= fun as_ty -> ty (Tnewtype (name, [], as_ty))
| "unapplied_alias" ->
get_string "name" (json, keytrace) >>= fun (name, name_keytrace) ->
begin
match Decl_provider.get_typedef ctx name with
| Some _typedef -> ty (Tunapplied_alias name)
| None ->
deserialization_error
~message:("Unknown type alias: " ^ name)
~keytrace:name_keytrace
end
| "newtype" ->
get_string "name" (json, keytrace) >>= fun (name, name_keytrace) ->
begin
match Decl_provider.get_typedef ctx name with
| Some _typedef ->
(* We end up only needing the name of the typedef. *)
Ok name
| None ->
if String.equal name "HackSuggest" then
not_supported
~message:"HackSuggest types for lambdas are not supported"
~keytrace
else
deserialization_error
~message:("Unknown newtype: " ^ name)
~keytrace:name_keytrace
end
>>= fun typedef_name ->
get_array "args" (json, keytrace) >>= fun (args, args_keytrace) ->
aux_args args ~keytrace:args_keytrace >>= fun args ->
aux_as json ~keytrace >>= fun as_ty ->
ty (Tnewtype (typedef_name, args, as_ty))
| "path" ->
get_obj "type" (json, keytrace) >>= fun (type_json, type_keytrace) ->
get_string "kind" (type_json, type_keytrace)
>>= fun (path_kind, path_kind_keytrace) ->
get_array "path" (json, keytrace) >>= fun (ids_array, ids_keytrace) ->
let ids =
map_array
ids_array
~keytrace:ids_keytrace
~f:(fun id_str ~keytrace ->
match id_str with
| JSON_String id -> Ok id
| _ ->
deserialization_error ~message:"Expected a string" ~keytrace)
in
ids >>= fun _ids ->
begin
match path_kind with
| "expr" ->
not_supported
~message:
"Cannot deserialize path-dependent type involving an expression"
~keytrace
| "this" ->
aux_as json ~keytrace >>= fun _as_ty -> ty (Tgeneric ("this", []))
| path_kind ->
deserialization_error
~message:("Unknown path kind: " ^ path_kind)
~keytrace:path_kind_keytrace
end
| "tuple" ->
get_array "args" (json, keytrace) >>= fun (args, args_keytrace) ->
aux_args args ~keytrace:args_keytrace >>= fun args -> ty (Ttuple args)
| "nullable" ->
get_array "args" (json, keytrace) >>= fun (args, keytrace) ->
begin
match args with
| [nullable_ty] ->
aux nullable_ty ~keytrace:("0" :: keytrace) >>= fun nullable_ty ->
ty (Toption nullable_ty)
| _ ->
deserialization_error
~message:
(Printf.sprintf
"Unsupported number of args for nullable type: %d"
(List.length args))
~keytrace
end
| "primitive" ->
get_string "name" (json, keytrace) >>= fun (name, keytrace) ->
begin
match name with
| "void" -> Ok Nast.Tvoid
| "int" -> Ok Nast.Tint
| "bool" -> Ok Nast.Tbool
| "float" -> Ok Nast.Tfloat
| "string" -> Ok Nast.Tstring
| "resource" -> Ok Nast.Tresource
| "num" -> Ok Nast.Tnum
| "arraykey" -> Ok Nast.Tarraykey
| "noreturn" -> Ok Nast.Tnoreturn
| _ ->
deserialization_error
~message:("Unknown primitive type: " ^ name)
~keytrace
end
>>= fun prim_ty -> ty (Tprim prim_ty)
| "class" ->
get_string "name" (json, keytrace) >>= fun (name, _name_keytrace) ->
let class_pos =
match Decl_provider.get_class ctx name with
| Some class_ty -> Cls.pos class_ty
| None ->
(* Class may not exist (such as in non-strict modes). *)
Pos_or_decl.none
in
get_array "args" (json, keytrace) >>= fun (args, _args_keytrace) ->
aux_args args ~keytrace >>= fun tyl ->
let refs =
match get_array "refs" (json, keytrace) with
| Ok (l, _) -> l
| Error _ -> []
in
aux_refs refs ~keytrace >>= fun rs ->
(* NB: "class" could have come from either a `Tapply` or a `Tclass`.
* Right now, we always return a `Tclass`. *)
ty (Tclass ((class_pos, name), Nonexact rs, tyl))
| "shape" ->
get_array "fields" (json, keytrace)
>>= fun (fields, fields_keytrace) ->
get_bool "is_array" (json, keytrace)
>>= fun (is_array, _is_array_keytrace) ->
let unserialize_field field_json ~keytrace :
( Typing_defs.tshape_field_name
* locl_phase Typing_defs.shape_field_type,
deserialization_error )
result =
get_val "name" (field_json, keytrace)
>>= fun (name, name_keytrace) ->
(* We don't need position information for shape field names. They're
* only used for error messages and the like. *)
let dummy_pos = Pos_or_decl.none in
begin
match name with
| Hh_json.JSON_Number name ->
Ok (Typing_defs.TSFlit_int (dummy_pos, name))
| Hh_json.JSON_String name ->
Ok (Typing_defs.TSFlit_str (dummy_pos, name))
| Hh_json.JSON_Array
[Hh_json.JSON_String name1; Hh_json.JSON_String name2] ->
Ok
(Typing_defs.TSFclass_const
((dummy_pos, name1), (dummy_pos, name2)))
| _ ->
deserialization_error
~message:"Unexpected format for shape field name"
~keytrace:name_keytrace
end
>>= fun shape_field_name ->
(* Optional field may be absent for shape-like arrays. *)
begin
match get_val "optional" (field_json, keytrace) with
| Ok _ ->
get_bool "optional" (field_json, keytrace)
>>| fun (optional, _optional_keytrace) -> optional
| Error _ -> Ok false
end
>>= fun optional ->
get_obj "type" (field_json, keytrace)
>>= fun (shape_type, shape_type_keytrace) ->
aux shape_type ~keytrace:shape_type_keytrace
>>= fun shape_field_type ->
let shape_field_type =
{ sft_optional = optional; sft_ty = shape_field_type }
in
Ok (shape_field_name, shape_field_type)
in
map_array fields ~keytrace:fields_keytrace ~f:unserialize_field
>>= fun fields ->
if is_array then
(* We don't have enough information to perfectly reconstruct shape-like
* arrays. We're missing the keys in the shape map of the shape fields. *)
not_supported
~message:"Cannot deserialize shape-like array type"
~keytrace
else
get_bool "fields_known" (json, keytrace)
>>= fun (fields_known, _fields_known_keytrace) ->
let shape_kind =
if fields_known then
Typing_make_type.nothing Reason.Rnone
else
Typing_make_type.mixed Reason.Rnone
in
let fields =
List.fold fields ~init:TShapeMap.empty ~f:(fun shape_map (k, v) ->
TShapeMap.add k v shape_map)
in
ty
(Tshape
{
s_origin = Missing_origin;
s_fields = fields;
s_unknown_value = shape_kind;
})
| "union" ->
get_array "args" (json, keytrace) >>= fun (args, keytrace) ->
aux_args args ~keytrace >>= fun tyl -> ty (Tunion tyl)
| "intersection" ->
get_array "args" (json, keytrace) >>= fun (args, keytrace) ->
aux_args args ~keytrace >>= fun tyl -> ty (Tintersection tyl)
| "function" ->
get_array "params" (json, keytrace)
>>= fun (params, params_keytrace) ->
let params =
map_array
params
~keytrace:params_keytrace
~f:(fun param ~keytrace ->
get_string "callConvention" (param, keytrace)
>>= fun (callconv, callconv_keytrace) ->
begin
match string_to_param_mode callconv with
| Some callconv -> Ok callconv
| None ->
deserialization_error
~message:("Unknown calling convention: " ^ callconv)
~keytrace:callconv_keytrace
end
>>= fun callconv ->
get_obj "type" (param, keytrace)
>>= fun (param_type, param_type_keytrace) ->
aux param_type ~keytrace:param_type_keytrace
>>= fun param_type ->
Ok
{
fp_type = { et_type = param_type; et_enforced = Unenforced };
fp_flags =
make_fp_flags
~mode:callconv
~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
params >>= fun ft_params ->
get_obj "result" (json, keytrace) >>= fun (result, result_keytrace) ->
aux result ~keytrace:result_keytrace >>= fun ft_ret ->
ty
(Tfun
{
ft_params;
ft_implicit_params =
{ capability = CapDefaults Pos_or_decl.none };
ft_ret = { et_type = ft_ret; et_enforced = Unenforced };
(* 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;
})
| _ ->
deserialization_error
~message:
(Printf.sprintf
"Unknown or unsupported kind '%s' to convert to locl phase"
kind)
~keytrace:kind_keytrace)
and map_array :
type a.
Hh_json.json list ->
f:
(Hh_json.json ->
keytrace:Hh_json.Access.keytrace ->
(a, deserialization_error) result) ->
keytrace:Hh_json.Access.keytrace ->
(a list, deserialization_error) result =
fun array ~f ~keytrace ->
let array =
List.mapi array ~f:(fun i elem ->
f elem ~keytrace:(string_of_int i :: keytrace))
in
Result.all array
and aux_args
(args : Hh_json.json list) ~(keytrace : Hh_json.Access.keytrace) :
(locl_ty list, deserialization_error) result =
map_array args ~keytrace ~f:aux
and aux_refs
(refs : Hh_json.json list) ~(keytrace : Hh_json.Access.keytrace) :
(locl_class_refinement, deserialization_error) result =
let of_refined_consts consts = { cr_consts = SMap.of_list consts } in
Result.map ~f:of_refined_consts (map_array refs ~keytrace ~f:aux_ref)
and aux_ref (json : Hh_json.json) ~(keytrace : Hh_json.Access.keytrace) :
(string * locl_refined_const, deserialization_error) result =
Result.Monad_infix.(
get_bool "is_ctx" (json, keytrace) >>= fun (rc_is_ctx, _) ->
get_string "type" (json, keytrace) >>= fun (id, _) ->
match Hh_json.Access.get_obj "equal" (json, keytrace) with
| Ok (ty_json, ty_keytrace) ->
aux ty_json ~keytrace:ty_keytrace >>= fun ty ->
Ok (id, { rc_bound = TRexact ty; rc_is_ctx })
| Error (Hh_json.Access.Missing_key_error _) ->
get_array "lower" (json, keytrace) >>= fun (los_json, los_keytrace) ->
get_array "upper" (json, keytrace) >>= fun (ups_json, ups_keytrace) ->
map_array los_json ~keytrace:los_keytrace ~f:aux >>= fun tr_lower ->
map_array ups_json ~keytrace:ups_keytrace ~f:aux >>= fun tr_upper ->
Ok (id, { rc_bound = TRloose { tr_lower; tr_upper }; rc_is_ctx })
| Error _ as e -> wrap_json_accessor (fun _ -> e) ())
and aux_as (json : Hh_json.json) ~(keytrace : Hh_json.Access.keytrace) :
(locl_ty, deserialization_error) result =
Result.Monad_infix.(
(* as-constraint is optional, check to see if it exists. *)
match Hh_json.Access.get_obj "as" (json, keytrace) with
| Ok (as_json, as_keytrace) ->
aux as_json ~keytrace:as_keytrace >>= fun as_ty -> Ok as_ty
| Error (Hh_json.Access.Missing_key_error _) ->
Ok (mk (Reason.none, Toption (mk (Reason.none, Tnonnull))))
| Error access_failure ->
deserialization_error
~message:
("Invalid as-constraint: "
^ Hh_json.Access.access_failure_to_string access_failure)
~keytrace)
in
aux json ~keytrace
end
let to_json env ?(show_like_ty = false) ty = Json.from_type env ~show_like_ty ty
let json_to_locl_ty = Json.to_locl_ty
(*****************************************************************************)
(* Prints the internal type of a class, this code is meant to be used for
* debugging purposes only.
*)
(*****************************************************************************)
module PrintClass = struct
let indent = " "
let bool = string_of_bool
let sset s =
let contents = SSet.fold (fun x acc -> x ^ " " ^ acc) s "" in
Printf.sprintf "Set( %s)" contents
let pos_or_decl p =
let (line, start, end_) = Pos_or_decl.line_start_end_columns p in
Printf.sprintf "(line %d: chars %d-%d)" line start end_
let classish_kind = function
| Ast_defs.Cclass k ->
(match k with
| Ast_defs.Abstract -> "Cabstract"
| Ast_defs.Concrete -> "Cnormal")
| Ast_defs.Cinterface -> "Cinterface"
| Ast_defs.Ctrait -> "Ctrait"
| Ast_defs.Cenum -> "Cenum"
(* TODO: do we need to distinguish ? *)
| Ast_defs.Cenum_class _ -> "Cenum_class"
let constraint_ty ~fuel = function
| (Ast_defs.Constraint_as, ty) ->
let (fuel, ty_str) = Full.to_string_decl ~fuel ty in
(fuel, "as " ^ ty_str)
| (Ast_defs.Constraint_eq, ty) ->
let (fuel, ty_str) = Full.to_string_decl ~fuel ty in
(fuel, "= " ^ ty_str)
| (Ast_defs.Constraint_super, ty) ->
let (fuel, ty_str) = Full.to_string_decl ~fuel ty in
(fuel, "super " ^ ty_str)
let variance = function
| Ast_defs.Covariant -> "+"
| Ast_defs.Contravariant -> "-"
| Ast_defs.Invariant -> ""
let rec tparam
~fuel
{
tp_variance = var;
tp_name = (position, name);
tp_tparams = params;
tp_constraints = cstrl;
tp_reified = reified;
tp_user_attributes = _;
} =
let (fuel, params_string) =
if List.is_empty params then
(fuel, "")
else
let (fuel, tparam_list_str) = tparam_list ~fuel params in
(fuel, "<" ^ tparam_list_str ^ ">")
in
let (fuel, constraints_str) =
let handle_constraint x (fuel, acc) =
let (fuel, constraint_str) = constraint_ty ~fuel x in
(fuel, constraint_str ^ " " ^ acc)
in
List.fold_right cstrl ~f:handle_constraint ~init:(fuel, "")
in
let tparam_str =
variance var
^ pos_or_decl position
^ " "
^ name
^ params_string
^ " "
^ constraints_str
^
match reified with
| Nast.Erased -> ""
| Nast.SoftReified -> " soft reified"
| Nast.Reified -> " reified"
in
(fuel, tparam_str)
and tparam_list ~fuel l =
let handle_tparam x (fuel, acc) =
let (fuel, tparam_str) = tparam ~fuel x in
(fuel, tparam_str ^ ", " ^ acc)
in
let (fuel, str) = List.fold_right l ~f:handle_tparam ~init:(fuel, "") in
(fuel, str)
let class_elt ~fuel ({ ce_visibility; ce_type = (lazy ty); _ } as ce) =
let vis =
match ce_visibility with
| Vpublic -> "public"
| Vprivate _ -> "private"
| Vprotected _ -> "protected"
| Vinternal _ -> "internal"
in
let synth =
if get_ce_synthesized ce then
"synthetic "
else
""
in
let (fuel, type_str) = Full.to_string_decl ~fuel ty in
(fuel, synth ^ vis ^ " " ^ type_str)
let class_elts ~fuel m =
let handle_class_elt (fuel, acc) (field, v) =
let (fuel, class_elt_str) = class_elt ~fuel v in
let class_elt_str = "(" ^ field ^ ": " ^ class_elt_str ^ ") " ^ acc in
(fuel, class_elt_str)
in
let (fuel, class_elts_str) =
List.fold m ~init:(fuel, "") ~f:handle_class_elt
in
(fuel, class_elts_str)
let class_elts_with_breaks ~fuel m =
let handle_class_elt (fuel, acc) (field, v) =
let (fuel, class_elt_str) = class_elt ~fuel v in
let class_elt_str = "\n" ^ indent ^ field ^ ": " ^ class_elt_str ^ acc in
(fuel, class_elt_str)
in
let (fuel, elts_str) = List.fold m ~init:(fuel, "") ~f:handle_class_elt in
(fuel, elts_str)
let class_consts ~fuel m =
let handle_class_const (fuel, acc) (field, cc) =
let synth =
if cc.cc_synthesized then
"synthetic "
else
""
in
let (fuel, class_const_ty_str) = Full.to_string_decl ~fuel cc.cc_type in
let class_const_ty_str =
"(" ^ field ^ ": " ^ synth ^ class_const_ty_str ^ ") " ^ acc
in
(fuel, class_const_ty_str)
in
let (fuel, class_consts_str) =
List.fold m ~init:(fuel, "") ~f:handle_class_const
in
(fuel, class_consts_str)
let typeconst
~fuel
{
ttc_synthesized = synthetic;
ttc_name = tc_name;
ttc_kind = kind;
ttc_origin = origin;
ttc_enforceable = (_, enforceable);
ttc_reifiable = reifiable;
ttc_concretized = _;
ttc_is_ctx = _;
} =
let name = snd tc_name in
let ty ~fuel x = Full.to_string_decl ~fuel x in
let (fuel, type_info) =
match kind with
| TCConcrete { tc_type = t } ->
let (fuel, ty_str) = ty ~fuel t in
let type_info_str = Printf.sprintf " = %s" ty_str in
(fuel, type_info_str)
| TCAbstract
{ atc_as_constraint = a; atc_super_constraint = s; atc_default = d }
->
let m ~fuel printer =
Option.value_map ~default:(fuel, "") ~f:(fun x ->
let (fuel, ty_str) = ty ~fuel x in
(fuel, printer ty_str))
in
let (fuel, a) = m ~fuel (Printf.sprintf " as %s") a in
let (fuel, s) = m ~fuel (Printf.sprintf " super %s") s in
let (fuel, d) = m ~fuel (Printf.sprintf " = %s") d in
(fuel, a ^ s ^ d)
in
let typeconst_str =
name
^ type_info
^ " (origin:"
^ origin
^ ")"
^ (if synthetic then
" (synthetic)"
else
"")
^ (if enforceable then
" (enforceable)"
else
"")
^
if Option.is_some reifiable then
" (reifiable)"
else
""
in
(fuel, typeconst_str)
let typeconsts ~fuel m =
let handle_typeconst (fuel, acc) (_, v) =
let (fuel, typeconst_str) = typeconst ~fuel v in
let typeconst_str = "\n(" ^ typeconst_str ^ ")" ^ acc in
(fuel, typeconst_str)
in
let (fuel, typeconsts_str) =
List.fold m ~init:(fuel, "") ~f:handle_typeconst
in
(fuel, typeconsts_str)
let ancestors ~fuel ctx m =
(* Format is as follows:
* ParentKnownToHack
* ! ParentCompletelyUnknown
*)
let handle_ancestor (fuel, acc) (field, v) =
let (sigil, kind) =
match Decl_provider.get_class ctx field with
| None -> ("!", "")
| Some cls -> (" ", " (" ^ classish_kind (Cls.kind cls) ^ ")")
in
let (fuel, ty_str) = Full.to_string_decl ~fuel v in
(fuel, "\n" ^ indent ^ sigil ^ " " ^ ty_str ^ kind ^ acc)
in
let (fuel, str) = List.fold m ~init:(fuel, "") ~f:handle_ancestor in
(fuel, str)
let constructor ~fuel (ce_opt, (consist : consistent_kind)) =
let consist_str = Format.asprintf "(%a)" pp_consistent_kind consist in
let (fuel, ce_str) =
match ce_opt with
| None -> (fuel, "")
| Some ce -> class_elt ~fuel ce
in
(fuel, ce_str ^ consist_str)
let req_ancestors ~fuel xs =
let handle_req_ancestor (fuel, acc) (_p, x) =
let (fuel, req_ancestor_str) = Full.to_string_decl ~fuel x in
let req_ancestor_str = acc ^ req_ancestor_str ^ ", " in
(fuel, req_ancestor_str)
in
let (fuel, str) = List.fold xs ~init:(fuel, "") ~f:handle_req_ancestor in
(fuel, str)
let class_type ~fuel ctx c =
let tc_need_init = bool (Cls.need_init c) in
let tc_abstract = bool (Cls.abstract c) in
let tc_deferred_init_members = sset @@ Cls.deferred_init_members c in
let tc_kind = classish_kind (Cls.kind c) in
let tc_name = Cls.name c in
let (fuel, tc_tparams) = tparam_list ~fuel (Cls.tparams c) in
let (fuel, tc_consts) = class_consts ~fuel (Cls.consts c) in
let (fuel, tc_typeconsts) = typeconsts ~fuel (Cls.typeconsts c) in
let (fuel, tc_props) = class_elts ~fuel (Cls.props c) in
let (fuel, tc_sprops) = class_elts ~fuel (Cls.sprops c) in
let (fuel, tc_methods) = class_elts_with_breaks ~fuel (Cls.methods c) in
let (fuel, tc_smethods) = class_elts_with_breaks ~fuel (Cls.smethods c) in
let (fuel, tc_construct) = constructor ~fuel (Cls.construct c) in
let (fuel, tc_ancestors) = ancestors ~fuel ctx (Cls.all_ancestors c) in
let (fuel, tc_req_ancestors) =
req_ancestors ~fuel (Cls.all_ancestor_reqs c)
in
let tc_req_ancestors_extends =
String.concat ~sep:" " (Cls.all_ancestor_req_names c)
in
let class_ty_str =
"tc_need_init: "
^ tc_need_init
^ "\n"
^ "tc_abstract: "
^ tc_abstract
^ "\n"
^ "tc_deferred_init_members: "
^ tc_deferred_init_members
^ "\n"
^ "tc_kind: "
^ tc_kind
^ "\n"
^ "tc_name: "
^ tc_name
^ "\n"
^ "tc_tparams: "
^ tc_tparams
^ "\n"
^ "tc_consts: "
^ tc_consts
^ "\n"
^ "tc_typeconsts: "
^ tc_typeconsts
^ "\n"
^ "tc_props: "
^ tc_props
^ "\n"
^ "tc_sprops: "
^ tc_sprops
^ "\n"
^ "tc_methods: "
^ tc_methods
^ "\n"
^ "tc_smethods: "
^ tc_smethods
^ "\n"
^ "tc_construct: "
^ tc_construct
^ "\n"
^ "tc_ancestors: "
^ tc_ancestors
^ "\n"
^ "tc_req_ancestors: "
^ tc_req_ancestors
^ "\n"
^ "tc_req_ancestors_extends: "
^ tc_req_ancestors_extends
^ "\n"
^ ""
in
(fuel, class_ty_str)
end
module PrintTypedef = struct
let typedef ~fuel = function
| {
td_pos;
td_module = _;
td_vis = _;
td_attributes = _;
td_tparams;
td_as_constraint;
td_super_constraint;
td_type;
td_is_ctx;
td_internal = _;
td_docs_url = _;
} ->
let (fuel, tparaml_s) = PrintClass.tparam_list ~fuel td_tparams in
let constr_s fuel cnstr str =
match cnstr with
| None -> (fuel, str ^ " [None]")
| Some constr ->
let (fuel, res) = Full.to_string_decl ~fuel constr in
(fuel, str ^ " " ^ res)
in
let (fuel, as_constr_s) = constr_s fuel td_as_constraint "as" in
let (fuel, super_constr_s) = constr_s fuel td_super_constraint "super" in
let (fuel, ty_s) = Full.to_string_decl ~fuel td_type in
let pos_s = PrintClass.pos_or_decl td_pos in
let is_ctx_s = Bool.to_string td_is_ctx in
let typedef_str =
"ty: "
^ ty_s
^ "\n"
^ "tparaml: "
^ tparaml_s
^ "\n"
^ "constraints: "
^ as_constr_s
^ " "
^ super_constr_s
^ "\n"
^ "pos: "
^ pos_s
^ "\n"
^ "is_ctx: "
^ is_ctx_s
^ "\n"
^ ""
in
(fuel, typedef_str)
end
let supply_fuel ?(msg = true) tcopt printer =
let type_printer_fuel = TypecheckerOptions.type_printer_fuel tcopt in
let fuel = Fuel.init type_printer_fuel in
let (fuel, str) = printer ~fuel in
if Fuel.has_enough fuel || not msg then
str
else
Printf.sprintf
"%s [This type was truncated. If you need more of the type, use `hh stop; hh --config type_printer_fuel=N`. At this time, N is %d.]"
str
type_printer_fuel
(*****************************************************************************)
(* User API *)
(*****************************************************************************)
let error ?(ignore_dynamic = false) env ty =
supply_fuel env.genv.tcopt (ErrorString.to_string ~ignore_dynamic env ty)
let full env ty =
supply_fuel
env.genv.tcopt
(Full.to_string ~ty:Full.locl_ty Doc.text (Loclenv env) ty)
let full_i env ty =
supply_fuel
env.genv.tcopt
(Full.to_string ~ty:Full.internal_type Doc.text (Loclenv env) ty)
let full_rec env n ty =
supply_fuel env.genv.tcopt (Full.to_string_rec (Loclenv env) n ty)
let full_strip_ns env ty =
supply_fuel
env.genv.tcopt
(Full.to_string_strip_ns ~ty:Full.locl_ty (Loclenv env) ty)
let full_strip_ns_i env ty =
supply_fuel
env.genv.tcopt
(Full.to_string_strip_ns ~ty:Full.internal_type (Loclenv env) ty)
let full_strip_ns_decl ?(msg = true) env ty =
supply_fuel
~msg
env.genv.tcopt
(Full.to_string_strip_ns ~ty:Full.decl_ty (Loclenv env) ty)
let full_with_identity env x occurrence definition_opt =
supply_fuel
env.genv.tcopt
(Full.to_string_with_identity env x occurrence definition_opt)
let full_decl ?(msg = true) tcopt ty =
supply_fuel ~msg tcopt (Full.to_string_decl ty)
let debug env ty =
Full.debug_mode := true;
let f_str = full_strip_ns env ty in
Full.debug_mode := false;
f_str
let debug_decl env ty =
Full.debug_mode := true;
let f_str = full_strip_ns_decl env ty in
Full.debug_mode := false;
f_str
let debug_i env ty =
Full.debug_mode := true;
let f_str = full_strip_ns_i env ty in
Full.debug_mode := false;
f_str
let class_ ctx c =
supply_fuel (Provider_context.get_tcopt ctx) (PrintClass.class_type ctx c)
let gconst tcopt gc = supply_fuel tcopt (Full.to_string_decl gc.cd_type)
let fun_ tcopt { fe_type; _ } = supply_fuel tcopt (Full.to_string_decl fe_type)
let fun_type tcopt f = supply_fuel tcopt (Full.fun_to_string f)
let typedef tcopt td = supply_fuel tcopt (PrintTypedef.typedef td)
let constraints_for_type env ty =
supply_fuel env.genv.tcopt (fun ~fuel ->
let (fuel, doc) =
Full.constraints_for_type ~fuel Full.text_strip_ns env ty
in
let str =
Libhackfmt.format_doc_unbroken Full.format_env doc |> String.strip
in
(fuel, str))
let classish_kind c_kind final = ErrorString.classish_kind c_kind final
let coercion_direction cd =
match cd with
| CoerceToDynamic -> "to"
| CoerceFromDynamic -> "from"
let subtype_prop env prop =
let rec subtype_prop = function
| Conj [] -> "TRUE"
| Conj ps ->
"(" ^ String.concat ~sep:" && " (List.map ~f:subtype_prop ps) ^ ")"
| Disj (_, []) -> "FALSE"
| Disj (_, ps) ->
"(" ^ String.concat ~sep:" || " (List.map ~f:subtype_prop ps) ^ ")"
| IsSubtype (None, ty1, ty2) -> debug_i env ty1 ^ " <: " ^ debug_i env ty2
| IsSubtype (Some cd, ty1, ty2) ->
debug_i env ty1 ^ " " ^ coercion_direction cd ^ "~> " ^ debug_i env ty2
in
let p_str = subtype_prop prop in
p_str
let coeffects env ty =
supply_fuel env.genv.tcopt @@ fun ~fuel ->
let to_string ~fuel ty =
with_blank_tyvars (fun () ->
Full.to_string
~fuel
~ty:Full.locl_ty
(fun s -> Doc.text (Utils.strip_all_ns s))
(Loclenv env)
ty)
in
let exception UndesugarableCoeffect of locl_ty in
let rec desugar_simple_intersection ~fuel (ty : locl_ty) :
Fuel.t * string list =
match snd @@ deref ty with
| Tvar v ->
(* We are interested in the upper bounds because coeffects are parameters (contravariant).
* Similar to Typing_subtype.describe_ty_super, we ignore Tvars appearing in bounds *)
let upper_bounds =
ITySet.elements
(Typing_inference_env.get_tyvar_upper_bounds env.inference_env v)
|> List.filter_map ~f:(function
| LoclType lty ->
(match deref lty with
| (_, Tvar _) -> None
| _ -> Some lty)
| ConstraintType _ -> None)
in
let (fuel, tyll) =
List.fold_map
~init:fuel
~f:(fun fuel -> desugar_simple_intersection ~fuel)
upper_bounds
in
(fuel, List.concat tyll)
| Tintersection tyl ->
let (fuel, tyll) =
List.fold_map
~init:fuel
~f:(fun fuel -> desugar_simple_intersection ~fuel)
tyl
in
(fuel, List.concat tyll)
| Tunion [ty] -> desugar_simple_intersection ~fuel ty
| Tunion _
| Tnonnull
| Tdynamic ->
raise (UndesugarableCoeffect ty)
| Toption ty' -> begin
match deref ty' with
| (_, Tnonnull) -> (fuel, []) (* another special case of `mixed` *)
| _ -> raise (UndesugarableCoeffect ty)
end
| _ ->
let (fuel, str) = to_string ~fuel ty in
(fuel, [str])
in
try
let (inference_env, ty) =
Typing_inference_env.expand_type env.inference_env ty
in
let ty =
match deref ty with
| (r, Tvar v) ->
(* We are interested in the upper bounds because coeffects are parameters (contravariant).
* Similar to Typing_subtype.describe_ty_super, we ignore Tvars appearing in bounds *)
let upper_bounds =
ITySet.elements
(Typing_inference_env.get_tyvar_upper_bounds inference_env v)
|> List.filter_map ~f:(function
| LoclType lty ->
(match deref lty with
| (_, Tvar _) -> None
| _ -> Some lty)
| ConstraintType _ -> None)
in
(match upper_bounds with
| [] -> raise (UndesugarableCoeffect ty)
| _ -> Typing_make_type.intersection r upper_bounds)
| _ -> ty
in
let (fuel, tyl) = desugar_simple_intersection ~fuel ty in
let coeffect_str =
match tyl with
| [cap] -> "the capability " ^ cap
| caps ->
"the capability set {"
^ (caps
|> List.dedup_and_sort ~compare:String.compare
|> String.concat ~sep:", ")
^ "}"
in
(fuel, coeffect_str)
with
| UndesugarableCoeffect _ -> to_string ~fuel ty |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_print.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Typing_env_types
(*****************************************************************************)
(* Pretty printing of types *)
(*****************************************************************************)
val error : ?ignore_dynamic:bool -> env -> Typing_defs.locl_ty -> string
val full : env -> Typing_defs.locl_ty -> string
val full_i : env -> Typing_defs.internal_type -> string
val full_rec : env -> int -> Typing_defs.locl_ty -> string
val full_strip_ns : env -> Typing_defs.locl_ty -> string
val full_strip_ns_i : env -> Typing_defs.internal_type -> string
(* if fuel reaches 0, if msg = true, an error message is added to the
type representation. msg is true by default *)
val full_strip_ns_decl : ?msg:bool -> env -> Typing_defs.decl_ty -> string
val full_decl :
?msg:bool -> TypecheckerOptions.t -> Typing_defs.decl_ty -> string
val fun_type : TypecheckerOptions.t -> Typing_defs.decl_fun_type -> string
(** Pretty print a type and all of its associated declaration information. *)
val full_with_identity :
env ->
Typing_defs.locl_ty ->
'b SymbolOccurrence.t ->
'b SymbolDefinition.t option ->
string
val debug : env -> Typing_defs.locl_ty -> string
val debug_decl : env -> Typing_defs.decl_ty -> string
val debug_i : env -> Typing_defs.internal_type -> string
val with_blank_tyvars : (unit -> 'a) -> 'a
val class_ : Provider_context.t -> Decl_provider.class_decl -> string
val gconst : TypecheckerOptions.t -> Decl_provider.gconst_decl -> string
val fun_ : TypecheckerOptions.t -> Decl_provider.fun_decl -> string
val typedef : TypecheckerOptions.t -> Decl_provider.typedef_decl -> string
val constraints_for_type : env -> Typing_defs.locl_ty -> string
val classish_kind : Ast_defs.classish_kind -> bool -> string
val subtype_prop : env -> Typing_logic.subtype_prop -> string
val coeffects : env -> Typing_defs.locl_ty -> string
(* Convert a type to a structured JSON value, as follows:
* <prim> ::= "int" | "bool" | "float" | "string" | "num" | "arraykey"
* | "mixed" | "resource" | "void" | "noreturn"
* <array-args> ::= [ <type> ] | [ <type>, <type> ]
* <type> ::=
* mixed
* { "kind":"mixed" }
* this
* { "kind":"this" }
* any
* { "kind":"any" }
* Anonymous lambda types
* { "kind":"anon" }
* Primitives
* { "kind":"primitive", "name":<prim> }
* Arrays, with 0, 1 or 2 type arguments
* { "kind":"array", "args":<array-args> }
* Enums (with optional bound)
* { "kind":"enum", "name":<identifier> [,"as":<type>] }
* Newtype (with optional bound)
* { "kind":"newtype", "name":<identifier>, "args":<type-arguments>
* [,"as":<type>] }
* Nullable types, with singleton type argument
* { "kind":"nullable", "args":<type-arguments> }
* Classes (or interfaces, or traits) with 0 or more type arguments
* { "kind":"class", "name":<identifier>, "args":<type-arguments> }
* Generic parameters
* { "kind":"generic", "name":<identifier> }
* Tuples (and tuple-like arrays)
* { "kind":"tuple", "args":<type-arguments> }
* Shapes (and shape-like arrays) with fields
* { "kind":"shape", "fields":<fields> }
* Function types, with 0 or more arguments and possibly-void result type
* { "kind":"function", "args":<type-arguments>, "result":<type> }
* Unions of types, with 2 or more arguments
* { "kind":"union", "args":<type-arguments> }
* Type constant paths, with base type and list of identifiers
* { "kind":"path", "type":<type>, "path":<identifiers> [,"as":<type>] }
* Base type may be
* { "kind":"static" }
* { "kind":"this" }
* { "kind":"class", "name":<identifier>, "args":[]}
* Expression-dependent type
* { "kind":"expr" }
*)
val to_json : env -> ?show_like_ty:bool -> Typing_defs.locl_ty -> Hh_json.json
(* Attempt to deserialize a previously-serialized type back into a type we can
manipulate. Note that this function accesses the global state in
`Decl_provider` to verify that certain type names exist. *)
val json_to_locl_ty :
?keytrace:Hh_json.Access.keytrace ->
Provider_context.t ->
Hh_json.json ->
(Typing_defs.locl_ty, Typing_defs.deserialization_error) result
val strip_ns : string -> string
(* Split type parameters [tparams] into normal user-denoted type
parameters, and a list of polymorphic context names that were
desugared to type parameters. *)
val split_desugared_ctx_tparams_gen :
tparams:'a list -> param_name:('a -> string) -> string list * 'a list |
OCaml | hhvm/hphp/hack/src/typing/typing_reason.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
let strip_ns id =
id |> Utils.strip_ns |> Hh_autoimport.strip_HH_namespace_if_autoimport
type pos_id = Pos_or_decl.t * Ast_defs.id_ [@@deriving eq, hash, ord, show]
type arg_position =
| Aonly
| Afirst
| Asecond
[@@deriving eq, hash]
type expr_dep_type_reason =
| ERexpr of int
| ERstatic
| ERclass of string
| ERparent of string
| ERself of string
| ERpu of string
[@@deriving eq, hash]
type blame_source =
| BScall
| BSlambda
| BSassignment
| BSout_of_scope
[@@deriving eq, hash]
type blame = Blame of Pos.t * blame_source [@@deriving eq, hash]
(* create private types to represent the different type phases *)
type decl_phase = private DeclPhase [@@deriving eq, hash, show]
type locl_phase = private LoclPhase [@@deriving eq, hash, show]
(* This is to avoid a compile error with ppx_hash "Unbound value _hash_fold_phase". *)
let _hash_fold_phase hsv _ = hsv
(* The phase below helps enforce that only Pos_or_decl.t positions end up in the heap.
* To enforce that, any reason taking a Pos.t should be a locl_phase t_
* to prevent a decl ty from using it.
* Reasons used for decl types should be 'phase t_ so that they can be localized
* to be used in the localized version of the type. *)
(** The reason why something is expected to have a certain type *)
type _ t_ =
| Rnone : 'phase t_
| Rwitness : Pos.t -> locl_phase t_
| Rwitness_from_decl : Pos_or_decl.t -> 'phase t_
| Ridx : Pos.t * locl_phase t_ -> locl_phase t_
(** Used as an index into a vector-like
array or string. Position of indexing,
reason for the indexed type *)
| Ridx_vector : Pos.t -> locl_phase t_
| Ridx_vector_from_decl : Pos_or_decl.t -> 'phase t_
(** Used as an index, in the Vector case *)
| Rforeach : Pos.t -> locl_phase t_
(** Because it is iterated in a foreach loop *)
| Rasyncforeach : Pos.t -> locl_phase t_
(** Because it is iterated "await as" in foreach *)
| Rarith : Pos.t -> locl_phase t_
| Rarith_ret : Pos.t -> locl_phase t_
| Rarith_ret_float : Pos.t * locl_phase t_ * arg_position -> locl_phase t_
(** pos, arg float typing reason, arg position *)
| Rarith_ret_num : Pos.t * locl_phase t_ * arg_position -> locl_phase t_
(** pos, arg num typing reason, arg position *)
| Rarith_ret_int : Pos.t -> locl_phase t_
| Rarith_dynamic : Pos.t -> locl_phase t_
| Rbitwise_dynamic : Pos.t -> locl_phase t_
| Rincdec_dynamic : Pos.t -> locl_phase t_
| Rcomp : Pos.t -> locl_phase t_
| Rconcat_ret : Pos.t -> locl_phase t_
| Rlogic_ret : Pos.t -> locl_phase t_
| Rbitwise : Pos.t -> locl_phase t_
| Rbitwise_ret : Pos.t -> locl_phase t_
| Rno_return : Pos.t -> locl_phase t_
| Rno_return_async : Pos.t -> locl_phase t_
| Rret_fun_kind : Pos.t * Ast_defs.fun_kind -> locl_phase t_
| Rret_fun_kind_from_decl : Pos_or_decl.t * Ast_defs.fun_kind -> 'phase t_
| Rhint : Pos_or_decl.t -> 'phase t_
| Rthrow : Pos.t -> locl_phase t_
| Rplaceholder : Pos.t -> locl_phase t_
| Rret_div : Pos.t -> locl_phase t_
| Ryield_gen : Pos.t -> locl_phase t_
| Ryield_asyncgen : Pos.t -> locl_phase t_
| Ryield_asyncnull : Pos.t -> locl_phase t_
| Ryield_send : Pos.t -> locl_phase t_
| Rlost_info : string * locl_phase t_ * blame -> locl_phase t_
| Rformat : Pos.t * string * locl_phase t_ -> locl_phase t_
| Rclass_class : Pos_or_decl.t * string -> 'phase t_
| Runknown_class : Pos.t -> locl_phase t_
| Rvar_param : Pos.t -> locl_phase t_
| Rvar_param_from_decl : Pos_or_decl.t -> 'phase t_
| Runpack_param : Pos.t * Pos_or_decl.t * int -> locl_phase t_
(** splat pos, fun def pos, number of args before splat *)
| Rinout_param : Pos_or_decl.t -> 'phase t_
| Rinstantiate : 'phase t_ * string * 'phase t_ -> 'phase t_
| Rtypeconst :
'phase t_ * (Pos_or_decl.t * string) * string Lazy.t * 'phase t_
-> 'phase t_
| Rtype_access :
locl_phase t_ * (locl_phase t_ * string Lazy.t) list
-> locl_phase t_
| Rexpr_dep_type :
'phase t_ * Pos_or_decl.t * expr_dep_type_reason
-> 'phase t_
| Rnullsafe_op : Pos.t -> locl_phase t_ (** ?-> operator is used *)
| Rtconst_no_cstr : pos_id -> 'phase t_
| Rpredicated : Pos.t * string -> locl_phase t_
| Ris : Pos.t -> locl_phase t_
| Ras : Pos.t -> locl_phase t_
| Requal : Pos.t -> locl_phase t_
| Rvarray_or_darray_key : Pos_or_decl.t -> 'phase t_
| Rvec_or_dict_key : Pos_or_decl.t -> 'phase t_
| Rusing : Pos.t -> locl_phase t_
| Rdynamic_prop : Pos.t -> locl_phase t_
| Rdynamic_call : Pos.t -> locl_phase t_
| Rdynamic_construct : Pos.t -> locl_phase t_
| Ridx_dict : Pos.t -> locl_phase t_
| Rset_element : Pos.t -> locl_phase t_
| Rmissing_optional_field : Pos_or_decl.t * string -> 'phase t_
| Runset_field : Pos.t * string -> locl_phase t_
| Rcontravariant_generic : locl_phase t_ * string -> locl_phase t_
| Rinvariant_generic : locl_phase t_ * string -> locl_phase t_
| Rregex : Pos.t -> locl_phase t_
| Rimplicit_upper_bound : Pos_or_decl.t * string -> 'phase t_
| Rtype_variable : Pos.t -> locl_phase t_
| Rtype_variable_generics : Pos.t * string * string -> locl_phase t_
| Rtype_variable_error : Pos.t -> locl_phase t_
| Rglobal_type_variable_generics :
Pos_or_decl.t * string * string
-> 'phase t_
| Rsolve_fail : Pos_or_decl.t -> 'phase t_
| Rcstr_on_generics : Pos_or_decl.t * pos_id -> 'phase t_
| Rlambda_param : Pos.t * locl_phase t_ -> locl_phase t_
| Rshape : Pos.t * string -> locl_phase t_
| Rshape_literal : Pos.t -> locl_phase t_
| Renforceable : Pos_or_decl.t -> 'phase t_
| Rdestructure : Pos.t -> locl_phase t_
| Rkey_value_collection_key : Pos.t -> locl_phase t_
| Rglobal_class_prop : Pos_or_decl.t -> 'phase t_
| Rglobal_fun_param : Pos_or_decl.t -> 'phase t_
| Rglobal_fun_ret : Pos_or_decl.t -> 'phase t_
| Rsplice : Pos.t -> locl_phase t_
| Ret_boolean : Pos.t -> locl_phase t_
| Rdefault_capability : Pos_or_decl.t -> 'phase t_
| Rconcat_operand : Pos.t -> locl_phase t_
| Rinterp_operand : Pos.t -> locl_phase t_
| Rdynamic_coercion of locl_phase t_
| Rsupport_dynamic_type : Pos_or_decl.t -> 'phase t_
| Rdynamic_partial_enforcement :
Pos_or_decl.t * string * locl_phase t_
-> locl_phase t_
| Rrigid_tvar_escape :
Pos.t * string * string * locl_phase t_
-> locl_phase t_
| Ropaque_type_from_module :
Pos_or_decl.t * string * locl_phase t_
-> locl_phase t_
| Rmissing_class : Pos.t -> locl_phase t_
| Rinvalid : 'phase t_
[@@deriving hash]
type t = locl_phase t_
type decl_t = decl_phase t_
let is_none = function
| Rnone -> true
| _ -> false
let rec localize : decl_phase t_ -> locl_phase t_ = function
| Rnone -> Rnone
| Ridx_vector_from_decl p -> Ridx_vector_from_decl p
| Rinout_param p -> Rinout_param p
| Rtypeconst (r1, p, q, r2) -> Rtypeconst (localize r1, p, q, localize r2)
| Rcstr_on_generics (a, b) -> Rcstr_on_generics (a, b)
| Rwitness_from_decl p -> Rwitness_from_decl p
| Rret_fun_kind_from_decl (p, r) -> Rret_fun_kind_from_decl (p, r)
| Rclass_class (p, r) -> Rclass_class (p, r)
| Rvar_param_from_decl p -> Rvar_param_from_decl p
| Rglobal_fun_param p -> Rglobal_fun_param p
| Renforceable p -> Renforceable p
| Rimplicit_upper_bound (p, q) -> Rimplicit_upper_bound (p, q)
| Rsolve_fail p -> Rsolve_fail p
| Rmissing_optional_field (p, q) -> Rmissing_optional_field (p, q)
| Rglobal_class_prop p -> Rglobal_class_prop p
| Rhint p -> Rhint p
| Rvarray_or_darray_key p -> Rvarray_or_darray_key p
| Rvec_or_dict_key p -> Rvec_or_dict_key p
| Rglobal_fun_ret p -> Rglobal_fun_ret p
| Rinstantiate (r1, s, r2) -> Rinstantiate (localize r1, s, localize r2)
| Rexpr_dep_type (r, s, t) -> Rexpr_dep_type (localize r, s, t)
| Rtconst_no_cstr id -> Rtconst_no_cstr id
| Rdefault_capability p -> Rdefault_capability p
| Rdynamic_coercion r -> Rdynamic_coercion r
| Rsupport_dynamic_type p -> Rsupport_dynamic_type p
| Rglobal_type_variable_generics (p, tp, n) ->
Rglobal_type_variable_generics (p, tp, n)
| Rinvalid -> Rinvalid
let arg_pos_str ap =
match ap with
| Aonly -> "only"
| Afirst -> "first"
| Asecond -> "second"
(* Translate a reason to a (pos, string) list, suitable for error_l. This
* previously returned a string, however the need to return multiple lines with
* multiple locations meant that it needed to more than convert to a string *)
let rec to_string : type ph. string -> ph t_ -> (Pos_or_decl.t * string) list =
fun prefix r ->
let p = to_pos r in
match r with
| Rnone -> [(p, prefix)]
| Rinvalid -> [(p, prefix)]
| Rwitness _ -> [(p, prefix)]
| Rwitness_from_decl p -> [(p, prefix)]
| Ridx (_, r2) ->
[(p, prefix)]
@ [
( (match r2 with
| Rnone -> p
| _ -> to_pos r2),
"This can only be indexed with integers" );
]
| Ridx_vector _
| Ridx_vector_from_decl _ ->
[
( p,
prefix
^ " because only `int` can be used to index into a `Vector` or `vec`."
);
]
| Rforeach _ ->
[(p, prefix ^ " because this is used in a `foreach` statement")]
| Rasyncforeach _ ->
[
( p,
prefix
^ " because this is used in a `foreach` statement with `await as`" );
]
| Rarith _ ->
[(p, prefix ^ " because this is used in an arithmetic operation")]
| Rarith_ret _ ->
[(p, prefix ^ " because this is the result of an arithmetic operation")]
| Rarith_ret_float (_, r, s) ->
let rec find_last reason =
match reason with
| Rarith_ret_float (_, r, _) -> find_last r
| r -> r
in
let r_last = find_last r in
[
( p,
prefix
^ " because this is the result of an arithmetic operation with a `float` as the "
^ arg_pos_str s
^ " argument." );
]
@ to_string
"Here is why I think the argument is a `float`: this is a `float`"
r_last
| Rarith_ret_num (_, r, s) ->
let rec find_last reason =
match reason with
| Rarith_ret_num (_, r, _) -> find_last r
| r -> r
in
let r_last = find_last r in
[
( p,
prefix
^ " because this is the result of an arithmetic operation with a `num` as the "
^ arg_pos_str s
^ " argument, and no `float`s." );
]
@ to_string
"Here is why I think the argument is a `num`: this is a `num`"
r_last
| Rarith_ret_int _ ->
[
( p,
prefix
^ " because this is the result of an integer arithmetic operation" );
]
| Rarith_dynamic _ ->
[
( p,
prefix
^ " because this is the result of an arithmetic operation with two arguments typed `dynamic`"
);
]
| Rbitwise_dynamic _ ->
[
( p,
prefix
^ " because this is the result of a bitwise operation with all arguments typed `dynamic`"
);
]
| Rincdec_dynamic _ ->
[
( p,
prefix
^ " because this is the result of an increment/decrement of an argument typed `dynamic`"
);
]
| Rcomp _ -> [(p, prefix ^ " because this is the result of a comparison")]
| Rconcat_ret _ ->
[(p, prefix ^ " because this is the result of a concatenation")]
| Rlogic_ret _ ->
[(p, prefix ^ " because this is the result of a logical operation")]
| Rbitwise _ -> [(p, prefix ^ " because this is used in a bitwise operation")]
| Rbitwise_ret _ ->
[(p, prefix ^ " because this is the result of a bitwise operation")]
| Rno_return _ ->
[(p, prefix ^ " because this function does not always return a value")]
| Rno_return_async _ ->
[(p, prefix ^ " because this function does not always return a value")]
| Rret_fun_kind (_, kind) ->
[
( p,
match kind with
| Ast_defs.FAsyncGenerator ->
prefix ^ " (result of `async function` containing a `yield`)"
| Ast_defs.FGenerator ->
prefix ^ " (result of function containing a `yield`)"
| Ast_defs.FAsync -> prefix ^ " (result of an `async` function)"
| Ast_defs.FSync -> prefix );
]
| Rret_fun_kind_from_decl (p, kind) ->
[
( p,
match kind with
| Ast_defs.FAsyncGenerator ->
prefix ^ " (result of `async function` containing a `yield`)"
| Ast_defs.FGenerator ->
prefix ^ " (result of function containing a `yield`)"
| Ast_defs.FAsync -> prefix ^ " (result of an `async` function)"
| Ast_defs.FSync -> prefix );
]
| Rhint p -> [(p, prefix)]
| Rthrow _ -> [(p, prefix ^ " because it is used as an exception")]
| Rplaceholder _ ->
[(p, prefix ^ " (`$_` is a placeholder variable not meant to be used)")]
| Rret_div _ -> [(p, prefix ^ " because it is the result of a division `/`")]
| Ryield_gen _ ->
[(p, prefix ^ " (result of function with `yield` in the body)")]
| Ryield_asyncgen _ ->
[(p, prefix ^ " (result of `async function` with `yield` in the body)")]
| Ryield_asyncnull _ ->
[
( p,
prefix
^ " because `yield x` is equivalent to `yield null => x` in an `async` function"
);
]
| Ryield_send _ ->
[
( p,
prefix
^ " (`$generator->send()` can always send a `null` back to a `yield`)"
);
]
| Rvar_param _ -> [(p, prefix ^ " (variadic argument)")]
| Rvar_param_from_decl p -> [(p, prefix ^ " (variadic argument)")]
| Runpack_param _ -> [(p, prefix ^ " (it is unpacked with `...`)")]
| Rinout_param _ -> [(p, prefix ^ " (`inout` parameter)")]
| Rnullsafe_op _ -> [(p, prefix ^ " (use of `?->` operator)")]
| Rlost_info (s, r1, Blame (p2, source_of_loss)) ->
let s = strip_ns s in
let cause =
match source_of_loss with
| BSlambda -> "by this lambda function"
| BScall -> "during this call"
| BSassignment -> "by this assignment"
| BSout_of_scope -> "because of scope change"
in
to_string prefix r1
@ [
( p2 |> Pos_or_decl.of_raw_pos,
"All the local information about "
^ Markdown_lite.md_codify s
^ " has been invalidated "
^ cause
^ ".\nThis is a limitation of the type-checker; use a local if that's the problem."
);
]
| Rformat (_, s, t) ->
let s =
prefix
^ " because of the "
^ Markdown_lite.md_codify s
^ " format specifier"
in
(match to_string "" t with
| [(_, "")] -> [(p, s)]
| el -> [(p, s)] @ el)
| Rclass_class (_, s) ->
[
( p,
prefix
^ "; implicitly defined constant `::class` is a string that contains the fully qualified name of "
^ (strip_ns s |> Markdown_lite.md_codify) );
]
| Runknown_class _ -> [(p, prefix ^ "; this class name is unknown to Hack")]
| Rinstantiate (r_orig, generic_name, r_inst) ->
to_string prefix r_orig
@ to_string
(" via this generic " ^ Markdown_lite.md_codify generic_name)
r_inst
| Rtype_variable _ ->
[(p, prefix ^ " because a type could not be determined here")]
| Rtype_variable_error _ -> [(p, prefix ^ " because there was another error")]
| Rtype_variable_generics (_, tp_name, s)
| Rglobal_type_variable_generics (_, tp_name, s) ->
[
( p,
prefix
^ " because type parameter "
^ Markdown_lite.md_codify tp_name
^ " of "
^ Markdown_lite.md_codify s
^ " could not be determined. Please add explicit type parameters to the invocation of "
^ Markdown_lite.md_codify s );
]
| Rsolve_fail _ ->
[(p, prefix ^ " because a type could not be determined here")]
| Rtypeconst (Rnone, (pos, tconst), (lazy ty_str), r_root) ->
let prefix =
if String.equal prefix "" then
""
else
prefix ^ "\n "
in
[
( pos,
sprintf
"%sby accessing the type constant %s"
prefix
(Markdown_lite.md_codify tconst) );
]
@ to_string ("on " ^ ty_str) r_root
| Rtypeconst (r_orig, (pos, tconst), (lazy ty_str), r_root) ->
to_string prefix r_orig
@ [
(pos, sprintf " resulting from accessing the type constant '%s'" tconst);
]
@ to_string (" on " ^ ty_str) r_root
| Rtype_access (Rtypeconst (Rnone, _, _, _), (r, _) :: l) ->
to_string prefix (Rtype_access (r, l))
| Rtype_access (Rtypeconst (r, _, _, _), x) ->
to_string prefix (Rtype_access (r, x))
| Rtype_access (Rtype_access (r, expand2), expand1) ->
to_string prefix (Rtype_access (r, expand1 @ expand2))
| Rtype_access (r, []) -> to_string prefix r
| Rtype_access (r, (r_hd, (lazy tconst)) :: tail) ->
to_string prefix r
@ to_string
(" resulting from expanding the type constant "
^ Markdown_lite.md_codify tconst)
r_hd
@ List.concat_map tail ~f:(fun (r, (lazy s)) ->
to_string
(" then expanding the type constant " ^ Markdown_lite.md_codify s)
r)
| Rexpr_dep_type (r, p, e) ->
to_string prefix r @ [(p, " " ^ expr_dep_type_reason_string e)]
| Rtconst_no_cstr (_, n) ->
[(p, prefix ^ " because the type constant " ^ n ^ " lacks a constraint")]
| Rpredicated (_, f) ->
[(p, prefix ^ " from the argument to this " ^ f ^ " test")]
| Ris _ -> [(p, prefix ^ " from this `is` expression test")]
| Ras _ -> [(p, prefix ^ " from this \"as\" assertion")]
| Requal _ -> [(p, prefix ^ " from this equality test")]
| Rvarray_or_darray_key _ ->
[
( p,
"This is varray_or_darray, which requires arraykey-typed keys when used with an array (used like a hashtable)"
);
]
| Rvec_or_dict_key _ ->
[(p, "This is vec_or_dict, which requires keys that have type arraykey")]
| Rusing _ -> [(p, prefix ^ " because it was assigned in a `using` clause")]
| Rdynamic_prop _ ->
[(p, prefix ^ ", the result of accessing a property of a `dynamic` type")]
| Rdynamic_call _ ->
[(p, prefix ^ ", the result of calling a `dynamic` type as a function")]
| Rdynamic_construct _ ->
[
( p,
prefix ^ ", the result of constructing an object with a `dynamic` type"
);
]
| Ridx_dict _ ->
[
( p,
prefix
^ " because only array keys can be used to index into a `Map`, `dict`, `darray`, `Set`, or `keyset`"
);
]
| Rset_element _ ->
[
( p,
prefix
^ " because only array keys can be used as elements of `keyset` or `Set`"
);
]
| Rmissing_optional_field (_, name) ->
[
( p,
prefix
^ " because the field "
^ Markdown_lite.md_codify name
^ " may be set to any type in this shape" );
]
| Runset_field (_, name) ->
[
( p,
prefix
^ " because the field "
^ Markdown_lite.md_codify name
^ " was unset here" );
]
| Rcontravariant_generic (r_orig, class_name) ->
to_string prefix r_orig
@ [
( p,
"This type argument to "
^ (strip_ns class_name |> Markdown_lite.md_codify)
^ " only allows supertypes (it is contravariant)" );
]
| Rinvariant_generic (r_orig, class_name) ->
to_string prefix r_orig
@ [
( p,
"This type argument to "
^ (strip_ns class_name |> Markdown_lite.md_codify)
^ " must match exactly (it is invariant)" );
]
| Rregex _ -> [(p, prefix ^ " resulting from this regex pattern")]
| Rimplicit_upper_bound (_, cstr) ->
[
( p,
prefix
^ " arising from an implicit "
^ Markdown_lite.md_codify ("as " ^ cstr)
^ " constraint on this type" );
]
| Rcstr_on_generics _ -> [(p, prefix)]
(* If type originated with an unannotated lambda parameter with type variable type,
* suggested annotating the lambda parameter. Otherwise defer to original reason. *)
| Rlambda_param
( _,
( Rsolve_fail _ | Rtype_variable_generics _ | Rtype_variable _
| Rinstantiate _ ) ) ->
[
( p,
prefix
^ " because the type of the lambda parameter could not be determined. "
^ "Please add a type hint to the parameter" );
]
| Rlambda_param (_, r_orig) -> to_string prefix r_orig
| Rshape (_, fun_name) ->
[
( p,
prefix
^ " because "
^ Markdown_lite.md_codify fun_name
^ " expects a shape" );
]
| Rshape_literal _ -> [(p, prefix)]
| Renforceable _ -> [(p, prefix ^ " because it is an unenforceable type")]
| Rdestructure _ ->
[(p, prefix ^ " resulting from a list destructuring assignment or a splat")]
| Rkey_value_collection_key _ ->
[
(p, "This is a key-value collection, which requires `arraykey`-typed keys");
]
| Rglobal_class_prop p -> [(p, prefix)]
| Rglobal_fun_param p -> [(p, prefix)]
| Rglobal_fun_ret p -> [(p, prefix)]
| Rsplice _ ->
[
(p, prefix ^ " because this is being spliced into another Expression Tree");
]
| Ret_boolean _ ->
[
( p,
prefix
^ " because Expression Trees do not allow coercion of truthy values" );
]
| Rdefault_capability _ ->
[(p, prefix ^ " because the function did not have an explicit context")]
| Rconcat_operand _ -> [(p, "Expected `string` or `int`")]
| Rinterp_operand _ -> [(p, "Expected `string` or `int`")]
| Rdynamic_coercion r -> to_string prefix r
| Rsupport_dynamic_type _ ->
[(p, prefix ^ " because method must be callable in a dynamic context")]
| Rdynamic_partial_enforcement (p, cn, r_orig) ->
to_string prefix r_orig
@ [(p, "while allowing dynamic to flow into " ^ Utils.strip_all_ns cn)]
| Rrigid_tvar_escape (p, what, tvar, r_orig) ->
let tvar = Markdown_lite.md_codify tvar in
( Pos_or_decl.of_raw_pos p,
prefix ^ " because " ^ tvar ^ " escaped from " ^ what )
:: to_string (" where " ^ tvar ^ " originates from") r_orig
| Ropaque_type_from_module (p, module_, r_orig) ->
( p,
prefix
^ " because this is an internal symbol from module "
^ module_
^ ", which is opaque outside of the module." )
:: to_string "The type originated from here" r_orig
| Rmissing_class p ->
[(Pos_or_decl.of_raw_pos p, prefix ^ " because class was missing")]
and to_pos : type ph. ph t_ -> Pos_or_decl.t =
fun r ->
if !Errors.report_pos_from_reason then
Pos_or_decl.set_from_reason (to_raw_pos r)
else
to_raw_pos r
and to_raw_pos : type ph. ph t_ -> Pos_or_decl.t =
fun r ->
match r with
| Rnone
| Rinvalid ->
Pos_or_decl.none
| Rret_fun_kind_from_decl (p, _)
| Rhint p
| Rwitness_from_decl p
| Rclass_class (p, _)
| Rvar_param_from_decl p
| Rglobal_fun_param p
| Rglobal_fun_ret p
| Renforceable p
| Rimplicit_upper_bound (p, _)
| Rsolve_fail p
| Rmissing_optional_field (p, _)
| Rvarray_or_darray_key p
| Rvec_or_dict_key p
| Rdefault_capability p
| Rtconst_no_cstr (p, _)
| Rtypeconst (Rnone, (p, _), _, _)
| Rcstr_on_generics (p, _)
| Rglobal_type_variable_generics (p, _, _)
| Ridx_vector_from_decl p
| Rinout_param p
| Rsupport_dynamic_type p
| Rglobal_class_prop p ->
p
| Rwitness p
| Ridx (p, _)
| Ridx_vector p
| Rforeach p
| Rasyncforeach p
| Rarith p
| Rarith_ret p
| Rarith_dynamic p
| Rcomp p
| Rconcat_ret p
| Rlogic_ret p
| Rbitwise p
| Rbitwise_ret p
| Rno_return p
| Rno_return_async p
| Rret_fun_kind (p, _)
| Rthrow p
| Rplaceholder p
| Rret_div p
| Ryield_gen p
| Ryield_asyncgen p
| Ryield_asyncnull p
| Ryield_send p
| Rformat (p, _, _)
| Runknown_class p
| Rvar_param p
| Runpack_param (p, _, _)
| Rnullsafe_op p
| Rpredicated (p, _)
| Ris p
| Ras p
| Requal p
| Rusing p
| Rdynamic_prop p
| Rdynamic_call p
| Rdynamic_construct p
| Ridx_dict p
| Rset_element p
| Runset_field (p, _)
| Rregex p
| Rarith_ret_float (p, _, _)
| Rarith_ret_num (p, _, _)
| Rarith_ret_int p
| Rbitwise_dynamic p
| Rincdec_dynamic p
| Rtype_variable p
| Rtype_variable_generics (p, _, _)
| Rtype_variable_error p
| Rlambda_param (p, _)
| Rshape (p, _)
| Rshape_literal p
| Rdestructure p
| Rkey_value_collection_key p
| Rsplice p
| Ret_boolean p
| Rconcat_operand p
| Rinterp_operand p
| Rrigid_tvar_escape (p, _, _, _) ->
Pos_or_decl.of_raw_pos p
| Rinvariant_generic (r, _)
| Rcontravariant_generic (r, _)
| Rtype_access (r, _)
| Rlost_info (_, r, _) ->
to_raw_pos r
| Rinstantiate (_, _, r)
| Rexpr_dep_type (r, _, _)
| Rtypeconst (r, _, _, _) ->
to_raw_pos r
| Rdynamic_coercion r -> to_raw_pos r
| Rdynamic_partial_enforcement (p, _, _) -> p
| Ropaque_type_from_module (p, _, _) -> p
| Rmissing_class p -> Pos_or_decl.of_raw_pos p
(* This is a mapping from internal expression ids to a standardized int.
* Used for outputting cleaner error messages to users
*)
and expr_display_id_map = ref IMap.empty
and get_expr_display_id id =
let map = !expr_display_id_map in
match IMap.find_opt id map with
| Some n -> n
| None ->
let n = IMap.cardinal map + 1 in
expr_display_id_map := IMap.add id n map;
n
and get_expr_display_id_map () = !expr_display_id_map
and expr_dep_type_reason_string = function
| ERexpr id ->
let did = get_expr_display_id id in
"where "
^ Markdown_lite.md_codify ("<expr#" ^ string_of_int did ^ ">")
^ " is a reference to this expression"
| ERstatic ->
"where `<static>` refers to the late bound type of the enclosing class"
| ERclass c ->
"where the class "
^ (strip_ns c |> Markdown_lite.md_codify)
^ " was referenced here"
| ERparent p ->
"where the class "
^ (strip_ns p |> Markdown_lite.md_codify)
^ " (the parent of the enclosing) class was referenced here"
| ERself c ->
"where the class "
^ (strip_ns c |> Markdown_lite.md_codify)
^ " was referenced here via the keyword `self`"
| ERpu s ->
"where "
^ Markdown_lite.md_codify s
^ " is a type projected from this expression"
let to_constructor_string : type ph. ph t_ -> string = function
| Rnone -> "Rnone"
| Rwitness _ -> "Rwitness"
| Rwitness_from_decl _ -> "Rwitness_from_decl"
| Ridx _ -> "Ridx"
| Ridx_vector _ -> "Ridx_vector"
| Ridx_vector_from_decl _ -> "Ridx_vector_from_decl"
| Rforeach _ -> "Rforeach"
| Rasyncforeach _ -> "Rasyncforeach"
| Rarith _ -> "Rarith"
| Rarith_ret _ -> "Rarith_ret"
| Rcomp _ -> "Rcomp"
| Rconcat_ret _ -> "Rconcat_ret"
| Rlogic_ret _ -> "Rlogic_ret"
| Rbitwise _ -> "Rbitwise"
| Rbitwise_ret _ -> "Rbitwise_ret"
| Rno_return _ -> "Rno_return"
| Rno_return_async _ -> "Rno_return_async"
| Rret_fun_kind _ -> "Rret_fun_kind"
| Rret_fun_kind_from_decl _ -> "Rret_fun_kind_from_decl"
| Rhint _ -> "Rhint"
| Rthrow _ -> "Rthrow"
| Rplaceholder _ -> "Rplaceholder"
| Rret_div _ -> "Rret_div"
| Ryield_gen _ -> "Ryield_gen"
| Ryield_asyncgen _ -> "Ryield_asyncgen"
| Ryield_asyncnull _ -> "Ryield_asyncnull"
| Ryield_send _ -> "Ryield_send"
| Rlost_info _ -> "Rlost_info"
| Rformat _ -> "Rformat"
| Rclass_class _ -> "Rclass_class"
| Runknown_class _ -> "Runknown_class"
| Rvar_param _ -> "Rvar_param"
| Rvar_param_from_decl _ -> "Rvar_param_from_decl"
| Runpack_param _ -> "Runpack_param"
| Rinout_param _ -> "Rinout_param"
| Rinstantiate _ -> "Rinstantiate"
| Rtypeconst _ -> "Rtypeconst"
| Rtype_access _ -> "Rtype_access"
| Rexpr_dep_type _ -> "Rexpr_dep_type"
| Rnullsafe_op _ -> "Rnullsafe_op"
| Rtconst_no_cstr _ -> "Rtconst_no_cstr"
| Rpredicated _ -> "Rpredicated"
| Ris _ -> "Ris"
| Ras _ -> "Ras"
| Requal _ -> "Requal"
| Rvarray_or_darray_key _ -> "Rvarray_or_darray_key"
| Rvec_or_dict_key _ -> "Rvec_or_dict_key"
| Rusing _ -> "Rusing"
| Rdynamic_prop _ -> "Rdynamic_prop"
| Rdynamic_call _ -> "Rdynamic_call"
| Rdynamic_construct _ -> "Rdynamic_construct"
| Ridx_dict _ -> "Ridx_dict"
| Rset_element _ -> "Rset_element"
| Rmissing_optional_field _ -> "Rmissing_optional_field"
| Runset_field _ -> "Runset_field"
| Rcontravariant_generic _ -> "Rcontravariant_generic"
| Rinvariant_generic _ -> "Rinvariant_generic"
| Rregex _ -> "Rregex"
| Rimplicit_upper_bound _ -> "Rimplicit_upper_bound"
| Rarith_ret_num _ -> "Rarith_ret_num"
| Rarith_ret_float _ -> "Rarith_ret_float"
| Rarith_ret_int _ -> "Rarith_ret_int"
| Rarith_dynamic _ -> "Rarith_dynamic"
| Rbitwise_dynamic _ -> "Rbitwise_dynamic"
| Rincdec_dynamic _ -> "Rincdec_dynamic"
| Rtype_variable _ -> "Rtype_variable"
| Rtype_variable_generics _ -> "Rtype_variable_generics"
| Rtype_variable_error _ -> "Rtype_variable_error"
| Rglobal_type_variable_generics _ -> "Rglobal_type_variable_generics"
| Rsolve_fail _ -> "Rsolve_fail"
| Rcstr_on_generics _ -> "Rcstr_on_generics"
| Rlambda_param _ -> "Rlambda_param"
| Rshape _ -> "Rshape"
| Rshape_literal _ -> "Rshape_literal"
| Renforceable _ -> "Renforceable"
| Rdestructure _ -> "Rdestructure"
| Rkey_value_collection_key _ -> "Rkey_value_collection_key"
| Rglobal_class_prop _ -> "Rglobal_class_prop"
| Rglobal_fun_param _ -> "Rglobal_fun_param"
| Rglobal_fun_ret _ -> "Rglobal_fun_ret"
| Rsplice _ -> "Rsplice"
| Ret_boolean _ -> "Ret_boolean"
| Rdefault_capability _ -> "Rdefault_capability"
| Rconcat_operand _ -> "Rconcat_operand"
| Rinterp_operand _ -> "Rinterp_operand"
| Rdynamic_coercion _ -> "Rdynamic_coercion"
| Rsupport_dynamic_type _ -> "Rsupport_dynamic_type"
| Rdynamic_partial_enforcement _ -> "Rdynamic_partial_enforcement"
| Rrigid_tvar_escape _ -> "Rrigid_tvar_escape"
| Ropaque_type_from_module _ -> "Ropaque_type_from_module"
| Rmissing_class _ -> "Rmissing_class"
| Rinvalid -> "Rinvalid"
let pp fmt r =
let pos = to_raw_pos r in
Format.pp_print_string fmt
@@ Printf.sprintf "%s (%s)" (to_constructor_string r) (Pos_or_decl.show pos)
type ureason =
| URnone
| URassign
| URassign_inout
| URhint
| URreturn
| URforeach
| URthrow
| URvector
| URkey of string
| URvalue of string
| URawait
| URyield
| URxhp of string * string (** Name of XHP class, Name of XHP attribute *)
| URxhp_spread
| URindex of string
| URelement of string
| URparam
| URparam_inout
| URarray_value
| URpair_value
| URtuple_access
| URpair_access
| URnewtype_cstr
| URclass_req
| URenum
| URenum_include
| URenum_cstr
| URenum_underlying
| URenum_incompatible_cstr
| URtypeconst_cstr
| URsubsume_tconst_cstr
| URsubsume_tconst_assign
| URclone
| URusing
| URstr_concat
| URstr_interp
| URdynamic_prop
[@@deriving show]
let index_array = URindex "array"
let index_tuple = URindex "tuple"
let index_class s = URindex (strip_ns s)
let set_element s = URelement (strip_ns s)
let string_of_ureason = function
| URnone -> "Typing error"
| URreturn -> "Invalid return type"
| URhint -> "Wrong type hint"
| URassign -> "Invalid assignment"
| URassign_inout -> "Invalid assignment to an `inout` parameter"
| URforeach -> "Invalid `foreach`"
| URthrow -> "Invalid exception"
| URvector -> "Some elements in this collection are incompatible"
| URkey s -> "The keys of this `" ^ strip_ns s ^ "` are incompatible"
| URvalue s -> "The values of this `" ^ strip_ns s ^ "` are incompatible"
| URawait -> "`await` can only operate on an `Awaitable`"
| URyield -> "Invalid `yield`"
| URxhp (cls, attr) ->
"Invalid xhp value for attribute "
^ Markdown_lite.md_codify attr
^ " in "
^ (strip_ns cls |> Markdown_lite.md_codify)
| URxhp_spread -> "The attribute spread operator cannot be called on non-XHP"
| URindex s -> "Invalid index type for this " ^ strip_ns s
| URelement s -> "Invalid element type for this " ^ strip_ns s
| URparam -> "Invalid argument"
| URparam_inout -> "Invalid argument to an `inout` parameter"
| URarray_value -> "Incompatible field values"
| URpair_value -> "Incompatible pair values"
| URtuple_access ->
"Tuple elements can only be accessed with an integer literal"
| URpair_access ->
"Pair elements can only be accessed with an integer literal"
| URnewtype_cstr -> "Invalid constraint on `newtype`"
| URclass_req -> "Unable to satisfy trait/interface requirement"
| URenum -> "Constant does not match the type of the enum it is in"
| URenum_include -> "Inclusion of enum of incompatible type"
| URenum_cstr -> "Invalid constraint on enum"
| URenum_underlying -> "Invalid underlying type for enum"
| URenum_incompatible_cstr ->
"Underlying type for enum is incompatible with constraint"
| URtypeconst_cstr -> "Unable to satisfy constraint on this type constant"
| URsubsume_tconst_cstr ->
"The constraint on this type constant is inconsistent with its parent"
| URsubsume_tconst_assign ->
"The assigned type of this type constant is inconsistent with its parent"
| URclone -> "Clone cannot be called on non-object"
| URusing -> "Using cannot be used on non-disposable expression"
| URstr_concat ->
"String concatenation can only be performed on string and int arguments"
| URstr_interp ->
"Only string and int values can be used in string interpolation"
| URdynamic_prop -> "Dynamic access of property"
let compare : type phase. phase t_ -> phase t_ -> int =
fun r1 r2 ->
let get_pri : type ph. ph t_ -> int = function
| Rnone -> 0
| Rforeach _ -> 1
| Rwitness _ -> 3
| Rlost_info _ -> 5
| _ -> 2
in
let d = get_pri r2 - get_pri r1 in
if Int.( <> ) d 0 then
d
else
Pos_or_decl.compare (to_raw_pos r1) (to_raw_pos r2)
let none = Rnone |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.