language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
OCaml Interface | hhvm/hphp/hack/src/typing/typing_reason.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type pos_id = Pos_or_decl.t * Ast_defs.id_ [@@deriving eq, hash, ord, show]
type arg_position =
| Aonly
| Afirst
| Asecond
[@@deriving eq]
type expr_dep_type_reason =
| ERexpr of int
| ERstatic
| ERclass of string
| ERparent of string
| ERself of string
| ERpu of string
[@@deriving eq]
type blame_source =
| BScall
| BSlambda
| BSassignment
| BSout_of_scope
[@@deriving eq]
type blame = Blame of Pos.t * blame_source [@@deriving eq]
(* 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_phase', meaning it is a type that
was declared in user code. Phase two is 'locl_phase', meaning it is a type that is
inferred via local inference.
*)
(* 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]
(* 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_
val is_none : t -> bool
val localize : decl_phase t_ -> locl_phase t_
(** 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 *)
val to_string : string -> 'phase t_ -> (Pos_or_decl.t * string) list
val to_pos : 'phase t_ -> Pos_or_decl.t
val expr_display_id_map : int IMap.t ref
val get_expr_display_id : int -> int
val get_expr_display_id_map : unit -> int IMap.t
val to_constructor_string : 'phase t_ -> string
val pp : Format.formatter -> 'phase t_ -> unit
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]
val index_array : ureason
val index_tuple : ureason
val index_class : string -> ureason
val set_element : string -> ureason
val string_of_ureason : ureason -> string
val none : 'phase t_
val compare : 'phase t_ -> 'phase t_ -> int |
OCaml | hhvm/hphp/hack/src/typing/typing_regex.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 Aast
module Reason = Typing_reason
module MakeType = Typing_make_type
exception Empty_regex_pattern
exception Missing_delimiter
exception Invalid_global_option
let internal_error s =
failwith ("Something (internal) went wrong while typing a regex string: " ^ s)
(* bottom is non-inclusive *)
let rec int_keys p top bottom acc_i =
if top <= bottom then
acc_i
else
int_keys
p
(top - 1)
bottom
(TSFlit_int (Pos_or_decl.of_raw_pos p, string_of_int top) :: acc_i)
(* Assumes that names_numbers is sorted in DECREASING order of numbers *)
let rec keys_aux p top names_numbers acc =
match names_numbers with
| [] -> int_keys p top 0 [] @ acc
| (name, number) :: t ->
keys_aux
p
(number - 1)
t
(TSFlit_str (Pos_or_decl.of_raw_pos p, name)
:: (int_keys p top number [] @ acc))
(*
* Any shape keys for our match type except 0. For re"Hel(\D)(?'o'\D)", this is
* [ SFlit_int (p, "1"); SFlit_int (p, 'o') ].
*
*)
let keys p s ~flags =
(* Compile `re`-prefixed string for use in Pcre functions *)
let pattern = Pcre.regexp s ~flags in
(* For re"Hel(\D)(?'o'\D)", this is 2. *)
let count =
try Pcre.capturecount pattern with
| Pcre.Error (Pcre.InternalError s) -> internal_error s
in
(* For re"Hel(\D)(?'o'\D)", this is ['o']. *)
let names =
try Array.to_list (Pcre.names pattern) with
| Pcre.Error (Pcre.InternalError s) -> internal_error s
in
(* For re"Hel(\D)(?'o'\D)", this is [2] *)
let numbers =
try List.map ~f:(Pcre.get_stringnumber pattern) names with
| Invalid_argument s -> internal_error s
in
let names_numbers = List.zip_exn names numbers in
let names_numbers_sorted =
List.sort
~compare:(fun nn1 nn2 -> ~-(Int.compare (snd nn1) (snd nn2)))
names_numbers
in
keys_aux p count names_numbers_sorted []
let type_match p s ~flags =
let sft =
{ sft_optional = false; sft_ty = MakeType.string (Reason.Rregex p) }
in
let keys = keys p s ~flags in
let shape_map =
List.fold_left
~f:(fun acc key -> TShapeMap.add key sft acc)
~init:TShapeMap.empty
keys
in
(* Any Regex\Match will contain the entire matched substring at key 0 *)
let shape_map =
TShapeMap.add (TSFlit_int (Pos_or_decl.of_raw_pos p, "0")) sft shape_map
in
MakeType.closed_shape (Reason.Rregex p) shape_map
let get_global_options s =
List.fold_left (String.to_list_rev s) ~init:[] ~f:(fun acc x ->
match x with
| 'u' -> `UTF8 :: acc
| 'i' -> `CASELESS :: acc
| 'm' -> `MULTILINE :: acc
| 's' -> `DOTALL :: acc
| 'x' -> `EXTENDED :: acc
| 'A' -> `ANCHORED :: acc
| 'D' -> `DOLLAR_ENDONLY :: acc
| 'U' -> `UNGREEDY :: acc
| 'X' -> `EXTRA :: acc
| 'S' -> acc
| _ -> raise Invalid_global_option)
let complement c =
match c with
| '(' -> ')'
| '{' -> '}'
| '<' -> '>'
| '[' -> ']'
| _ -> c
(* Takes in delimiter-stripped string, checks brace-like delimiters *)
let check_balanced_delimiters s delim =
let length = String.length s in
let delim_closed = complement delim in
let rec check_acc d i =
if d < 0 then
raise Missing_delimiter
else if i < length then
let (d2, i2) =
match s.[i] with
| x when Char.equal x delim -> (d + 1, i + 1)
| x when Char.equal x delim_closed -> (d - 1, i + 1)
(* Skip escape characters *)
| '\\' -> (d, i + 2)
| _ -> (d, i + 1)
in
check_acc d2 i2
else if d > 0 then
raise Missing_delimiter
else
s
in
check_acc 0 0
(* Takes in regex string and strips outer delimiters, checks and strips
nested brace-like delimiters.
*)
let check_and_strip_delimiters s =
(* Non-alphanumeric, non-whitespace, non-backslash characters are delimiter-eligible *)
let delimiter = Str.regexp "[^a-zA-Z0-9\t\n\r\x0b\x0c \\]" in
let length = String.length s in
if Int.equal length 0 then
raise Empty_regex_pattern
else
let first = s.[0] in
if Str.string_match delimiter (String.make 1 first) 0 then
let closed_delim = complement first in
let no_first_delim = String.sub s ~pos:1 ~len:(length - 1) in
match String.rindex_from no_first_delim (length - 2) closed_delim with
| Some i ->
let flags =
get_global_options (String.sub s ~pos:(i + 2) ~len:(length - i - 2))
in
let stripped_string = String.sub s ~pos:1 ~len:i in
if not (Char.equal closed_delim first) then
(check_balanced_delimiters stripped_string first, flags)
else
(stripped_string, flags)
| None -> raise Missing_delimiter
else
raise Missing_delimiter
let type_pattern (_, p, e_) =
match e_ with
| String s ->
let (s, flags) = check_and_strip_delimiters s in
let match_type = type_match p s ~flags in
mk
( Reason.Rregex p,
Tnewtype
( Naming_special_names.Regex.tPattern,
[match_type],
MakeType.string (Reason.Rregex p) ) )
| _ -> failwith "Should have caught non-Ast_defs.String prefixed expression!" |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_regex.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.
*
*)
exception Empty_regex_pattern
exception Missing_delimiter
exception Invalid_global_option
val type_pattern : Nast.expr -> Typing_defs.locl_ty |
OCaml | hhvm/hphp/hack/src/typing/typing_reified_check.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Typing_defs
module Env = Typing_env
module SN = Naming_special_names
module UA = SN.UserAttributes
module Cls = Decl_provider.Class
module Nast = Aast
let validator =
object (this)
inherit Type_validator.type_validator as super
method! on_tapply acc r (p, h) tyl =
if String.equal h SN.Classes.cTypename then
this#invalid acc r "a typename"
else if String.equal h SN.Classes.cClassname then
this#invalid acc r "a classname"
else
super#on_tapply acc r (p, h) tyl
method! on_twildcard acc r =
if acc.Type_validator.env.Typing_env_types.allow_wildcards then
acc
else
this#invalid acc r "a wildcard"
method! on_tgeneric acc r t _tyargs =
(* Ignoring type aguments: If there were any, then this generic variable isn't allowed to be
reified anyway *)
(* TODO(T70069116) actually implement that check *)
match Env.get_reified acc.Type_validator.env t with
| Nast.Erased -> this#invalid acc r "not reified"
| Nast.SoftReified -> this#invalid acc r "soft reified"
| Nast.Reified -> acc
method! on_tfun acc r _ = this#invalid acc r "a function type"
method! on_typeconst acc class_ typeconst =
match typeconst.ttc_kind with
| TCConcrete _ -> super#on_typeconst acc class_ typeconst
| TCAbstract _ when Option.is_some typeconst.ttc_reifiable ->
super#on_typeconst acc class_ typeconst
| TCAbstract _ ->
let r = Reason.Rwitness_from_decl (fst typeconst.ttc_name) in
let kind =
"an abstract type constant without the __Reifiable attribute"
in
this#invalid acc r kind
method! on_taccess acc r (root, ids) =
let acc =
match acc.Type_validator.reification with
| Type_validator.Unresolved ->
(match get_node root with
| Tthis ->
{ acc with Type_validator.reification = Type_validator.Resolved }
| _ -> this#on_type acc root)
| Type_validator.Resolved -> acc
in
super#on_taccess acc r (root, ids)
method! on_tthis acc r =
this#invalid acc r "the late static bound this type"
method! on_trefinement acc r _ty _ = this#invalid acc r "type refinement"
end |
OCaml | hhvm/hphp/hack/src/typing/typing_requirements.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module TUtils = Typing_utils
module Env = Typing_env
module Cls = Decl_provider.Class
(* Only applied to classes. Checks that all the requirements of the traits
* and interfaces it uses are satisfied. *)
let check_fulfillment env class_pos get_impl (trait_pos, req_ty) =
match TUtils.try_unwrap_class_type req_ty with
| None -> env
| Some (_r, (_p, req_name), _paraml) ->
let req_pos = Typing_defs.get_pos req_ty in
(match get_impl req_name with
| None ->
(Typing_error_utils.add_typing_error ~env
@@ Typing_error.(
primary
@@ Primary.Unsatisfied_req
{ pos = class_pos; trait_pos; req_pos; req_name }));
env
| Some impl_ty ->
let (env, ty_err_opt) =
Typing_phase.sub_type_decl env impl_ty req_ty
@@ Some
(Typing_error.Reasons_callback.unsatisfied_req_callback
~class_pos
~trait_pos
~req_pos
req_name)
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
env)
let check_require_class env class_pos tc (trait_pos, req_ty) =
match TUtils.try_unwrap_class_type req_ty with
| None -> env
| Some (_r, (_p, req_name), _paraml) ->
(* in a `require class t;` trait constraint, t must be a non-generic class
* name. Since lowering enforces _paraml to be empty, so it is safe to
* ignore _param here. Additionally we enforce that the class that uses
* the trait with a require class constraint does not have type parameters
* and is final.
*)
if String.equal req_name (Cls.name tc) && List.is_empty (Cls.tparams tc)
then (
if Cls.final tc then
env
else
let req_pos = Typing_defs.get_pos req_ty in
(Typing_error_utils.add_typing_error ~env
@@ Typing_error.(
primary
@@ Primary.Req_class_not_final
{ pos = class_pos; trait_pos; req_pos }));
env
) else
let req_pos = Typing_defs.get_pos req_ty in
(Typing_error_utils.add_typing_error ~env
@@ Typing_error.(
primary
@@ Primary.Unsatisfied_req_class
{ pos = class_pos; trait_pos; req_pos; req_name }));
env
(* HHVM enformcement rejects conflicting require class and require extends
constraints on the same class, eg:
trait T1 { require extends C; }
trait T2 { require class C; }
trait T { use T1, T2; }
The check below, only run on traits, detects and rejects such cases,
ensuring that Hack does not accept code on which HHVM enforcement
raises an error.
*)
let get_require_class_name_pos ty =
match TUtils.try_unwrap_class_type ty with
| Some (_, (p, n), _) -> Some (n, p)
| None -> None
let check_require_class_require_extends_conflict
env trait_pos required_classes tc =
let require_extends_implements =
List.filter_map (Cls.all_ancestor_reqs tc) ~f:(fun (_, ty) ->
get_require_class_name_pos ty)
in
List.iter required_classes ~f:(fun (nc, pc) ->
match
List.find require_extends_implements ~f:(fun (ne, _) ->
String.equal nc ne)
with
| None -> ()
| Some (_, pe) ->
Typing_error_utils.add_typing_error ~env
@@ Typing_error.(
primary
@@ Primary.Incompatible_reqs
{
pos = trait_pos;
req_name = nc;
req_class_pos = pc;
req_extends_pos = pe;
}));
env
(* If a trait `T` `require class C`, but `C` does not use `T`, then Hack won't report
* any type error on the body of `T` because the intersection of `C` and `T` is empty.
* Although this behaviour is sound, it is likely to be confusing for the programmer.
* We thus eagerly emit an error if a trait `require class` a class that does not use it.
*)
let check_require_class_use env trait_pos required_classes tc =
List.iter required_classes ~f:(fun (nc, pc) ->
match Env.get_class env nc with
| None ->
(* existence of class is checked in Naming *)
()
| Some trc ->
if
(not (Cls.has_ancestor trc (Cls.name tc)))
&& Ast_defs.is_c_class (Cls.kind trc)
then
Typing_error_utils.add_typing_error ~env
@@ Typing_error.(
primary
@@ Primary.Trait_not_used
{
pos = trait_pos;
trait_name = Cls.name tc;
req_class_pos = pc;
class_pos = Cls.pos trc;
class_name = Cls.name trc;
}));
env
let check_trait_require_class env trait_pos tc =
match Cls.all_ancestor_req_class_requirements tc with
| [] -> env
| rc ->
let required_classes =
List.filter_map rc ~f:(fun (_, ty) -> get_require_class_name_pos ty)
in
let env =
check_require_class_require_extends_conflict
env
trait_pos
required_classes
tc
in
check_require_class_use env trait_pos required_classes tc
(** Check whether a class satifies all the requirements of the traits it uses,
namely [require extends] and [require implements]. *)
let check_class env class_pos tc =
match Cls.kind tc with
| Ast_defs.Cclass _ ->
let env =
List.fold
(Cls.all_ancestor_reqs tc)
~f:(fun env req ->
check_fulfillment env class_pos (Cls.get_ancestor tc) req)
~init:env
in
List.fold
(Cls.all_ancestor_req_class_requirements tc)
~f:(fun env req -> check_require_class env class_pos tc req)
~init:env
| Ast_defs.Ctrait -> check_trait_require_class env class_pos tc
| Ast_defs.Cinterface
| Ast_defs.Cenum_class _
| Ast_defs.Cenum ->
env |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_requirements.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(** Checks that all the requirements of the traits and interfaces a class uses are satisfied. *)
val check_class :
Typing_env_types.env ->
Pos.t ->
Decl_provider.class_decl ->
Typing_env_types.env |
OCaml | hhvm/hphp/hack/src/typing/typing_return.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 Typing_env_types
open Typing_env_return_info
module Env = Typing_env
module TUtils = Typing_utils
module MakeType = Typing_make_type
module SN = Naming_special_names
module Cls = Decl_provider.Class
let strip_awaitable fun_kind env et =
if not Ast_defs.(equal_fun_kind fun_kind FAsync) then
et
else
let (_env, ty) = Env.expand_type env et.et_type in
match get_node ty with
| Tclass ((_, class_name), _, [ty])
when String.equal class_name SN.Classes.cAwaitable ->
{ et with et_type = ty }
| _ -> et
let enforce_return_not_disposable ret_pos fun_kind env et =
let stripped_et = strip_awaitable fun_kind env et in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env)
@@ Option.map
(Typing_disposable.is_disposable_type env stripped_et.et_type)
~f:(fun class_name ->
let open Typing_error in
primary
@@ Primary.Invalid_disposable_return_hint
{ pos = ret_pos; class_name = Utils.strip_ns class_name })
let has_attribute attr l =
List.exists l ~f:(fun { Aast.ua_name; _ } -> String.equal attr (snd ua_name))
let has_return_disposable_attribute attrs =
has_attribute SN.UserAttributes.uaReturnDisposable attrs
let make_info ret_pos fun_kind attributes env return_type =
let return_disposable = has_return_disposable_attribute attributes in
if not return_disposable then
enforce_return_not_disposable ret_pos fun_kind env return_type;
{ return_type; return_disposable }
(* Make a fresh Awaitable<_> etc making sure that any constraints (e.g. supportdyn)
* are added to the type variable
*)
let make_wrapped_fresh_type env p r id =
let class_ = Env.get_class env id in
match class_ with
| None -> Env.fresh_type_error env p (* Shouldn't happen *)
| Some class_ ->
let ((env, _), ty, _tal) =
Typing_phase.localize_targs_and_check_constraints
~exact:nonexact
~check_well_kinded:false
~def_pos:(Cls.pos class_)
~use_pos:p
~check_explicit_targs:false
env
(p, id)
r
(Cls.tparams class_)
[]
in
(env, ty)
(* Create a return type with fresh type variables *)
let make_fresh_return_type env p =
let fun_kind = Env.get_fn_kind env in
let r = Reason.Rret_fun_kind_from_decl (Pos_or_decl.of_raw_pos p, fun_kind) in
match fun_kind with
| Ast_defs.FSync -> Env.fresh_type env p
| Ast_defs.FAsync -> make_wrapped_fresh_type env p r SN.Classes.cAwaitable
| Ast_defs.FGenerator -> make_wrapped_fresh_type env p r SN.Classes.cGenerator
| Ast_defs.FAsyncGenerator ->
make_wrapped_fresh_type env p r SN.Classes.cAsyncGenerator
(** Force the return type of a function to adhere to the fun_kind specified in
the env *)
let force_return_kind ~is_toplevel env p ety =
let fun_kind = Env.get_fn_kind env in
let (env, ty) = Env.expand_type env ety.et_type in
let (env, ty) =
match (fun_kind, get_node ty) with
(* Sync functions can return anything *)
| (Ast_defs.FSync, _) -> (env, ty)
(* Each other fun kind needs a specific return type *)
| (Ast_defs.FAsync, _) when is_toplevel ->
(* For toplevel functions, this is already checked in the parser *)
(env, ty)
| (Ast_defs.FAsync, Tclass ((_, class_name), _, _))
when String.equal class_name SN.Classes.cAwaitable ->
(* For toplevel functions, this is already checked in the parser *)
(env, ty)
| (Ast_defs.FGenerator, Tclass ((_, class_name), _, _))
when String.equal class_name SN.Classes.cGenerator ->
(env, ty)
| (Ast_defs.FAsyncGenerator, Tclass ((_, class_name), _, _))
when String.equal class_name SN.Classes.cAsyncGenerator ->
(env, ty)
| _ ->
let (env, wrapped_ty) = make_fresh_return_type env p in
let (env, ty_err_opt) =
Typing_ops.sub_type
p
Reason.URreturn
env
wrapped_ty
ty
Typing_error.Callback.unify_error
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
(env, wrapped_ty)
in
(env, { ety with et_type = ty })
let make_return_type
~ety_env
~this_class
~supportdyn
env
~hint_pos
~(explicit : decl_ty option)
~(default : locl_ty option) =
match explicit with
| None ->
let (env, ty) =
match default with
| None -> make_fresh_return_type env hint_pos
| Some ty -> (env, ty)
in
let (env, ty) =
if supportdyn then
TUtils.make_supportdyn
(Reason.Rsupport_dynamic_type (Pos_or_decl.of_raw_pos hint_pos))
env
ty
else
(env, ty)
in
(env, MakeType.unenforced ty)
| Some ty ->
let wrap_awaitable p ty =
MakeType.awaitable
(Reason.Rret_fun_kind_from_decl (p, Ast_defs.FAsync))
ty
in
let localize ~wrap (env : env) (dty : decl_ty) =
if TypecheckerOptions.everything_sdt env.genv.tcopt then (
let dty =
match get_node dty with
| Tfun _ ->
TUtils.make_supportdyn_decl_type (get_pos dty) (get_reason dty) dty
| _ -> dty
in
let ((env, ty_err_opt), ty) = Typing_phase.localize ~ety_env env dty in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
(* If type doesn't already support dynamic then wrap it if supportdyn=true *)
let (env, ty) =
if supportdyn then
TUtils.make_supportdyn
(Reason.Rsupport_dynamic_type (get_pos ty))
env
ty
else
(env, ty)
in
(* If <<__NoAutoLikes>> is specified, then add a like- to enforced returns
* so that we can return an expression of like-type.
* If <<__NoAutoLikes>> is not specified, then add a like- for the same reason,
* but add a like type even for non-enforced returns because these we pessimise anyway.
* Never pessimise void.
*)
let add_like =
if Env.get_no_auto_likes env then
match Typing_enforceability.get_enforcement ~this_class env dty with
| Unenforced -> false
| Enforced -> true
else
true
in
let et_type =
match get_node ty with
| Tprim Aast.Tvoid when not wrap -> ty
| _ ->
if add_like then
TUtils.make_like env ty
else
ty
in
let et_type =
if wrap then
wrap_awaitable (get_pos et_type) et_type
else
et_type
in
(env, { et_type; et_enforced = Unenforced })
) else
let et_enforced =
Typing_enforceability.get_enforcement ~this_class env dty
in
let et_enforced =
match et_enforced with
| Unenforced ->
if not (Env.get_no_auto_likes env) then
Typing_log.log_pessimise_return env hint_pos None;
(* Return type is not fully enforced according to the naive check
* in Typing_enforceability. Let's now ask for what type it is actually
* enforced at. If this is a subtype of the Hack type, then we can
* treat the return type as fully enforced.
* Example: return type is declared to be (~E & arraykey)
* for enum E : int as int
* get_enforced_type (~E & arraykey) is int
* Now since int <:D (~E & arraykey) it suffices to treat
* the return type as fully enforced.
*)
if not (TypecheckerOptions.enable_sound_dynamic env.genv.tcopt) then
Unenforced
else
let enforced_type =
Typing_partial_enforcement.get_enforced_type
env
(Env.get_self_class env)
dty
in
let is_sub_type =
Typing_phase.is_sub_type_decl
~coerce:(Some Typing_logic.CoerceToDynamic)
env
enforced_type
dty
in
if is_sub_type then
Enforced
else
Unenforced
| Enforced -> Enforced
in
let ((env, ty_err_opt), et_type) =
Typing_phase.localize ~ety_env env dty
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
(* If type doesn't already support dynamic then wrap it if supportdyn=true *)
let (env, et_type) =
if supportdyn then
TUtils.make_supportdyn
(Reason.Rsupport_dynamic_type (get_pos et_type))
env
et_type
else
(env, et_type)
in
(* If return type t is enforced we permit values of type ~t to be returned *)
let ety = TUtils.make_like_if_enforced env { et_enforced; et_type } in
let et_type =
if wrap then
wrap_awaitable (get_pos et_type) ety.et_type
else
ety.et_type
in
(env, { ety with et_type })
in
(match (Env.get_fn_kind env, deref ty) with
| (Ast_defs.FAsync, (_, Tapply ((_, class_name), [inner_ty])))
when String.equal class_name SN.Classes.cAwaitable ->
localize ~wrap:true env inner_ty
| (Ast_defs.FAsync, (r_like, Tlike ty_like)) -> begin
match get_node ty_like with
| Tapply ((_, class_name), [inner_ty])
when String.equal class_name SN.Classes.cAwaitable ->
let ty = mk (r_like, Tlike inner_ty) in
localize ~wrap:true env ty
| _ -> localize ~wrap:false env ty
end
| _ -> localize ~wrap:false env ty)
let make_return_type
~ety_env
~this_class
?(is_toplevel = true)
~supportdyn
env
~hint_pos
~explicit
~default =
let (env, ty) =
make_return_type
~ety_env
~this_class
env
~supportdyn
~hint_pos
~explicit
~default
in
force_return_kind ~is_toplevel env hint_pos ty
let implicit_return env pos ~expected ~actual ~hint_pos ~is_async =
let reason = Reason.URreturn in
let error =
Typing_error.Primary.(
Wellformedness (Wellformedness.Missing_return { pos; hint_pos; is_async }))
in
let (env, ty_err_opt) =
Typing_ops.sub_type pos reason env actual expected
@@ Typing_error.Callback.of_primary_error error
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
env
let check_inout_return ret_pos env =
let params = Local_id.Map.elements (Env.get_params env) in
let (env, ty_errs) =
List.fold
params
~init:(env, [])
~f:(fun (env, ty_errs) (id, (_ty, param_pos, out_ty_opt)) ->
match out_ty_opt with
| Some out_ty ->
(* Whenever the function exits normally, we require that each local
* corresponding to an inout parameter be compatible with the original
* type for the parameter (under subtyping rules). *)
let local = Env.get_local env id in
let open Typing_local_types in
let (env, ety) = Env.expand_type env local.ty in
let pos =
if not (Pos.equal Pos.none local.pos) then
local.pos
else if not (Pos.equal Pos.none ret_pos) then
ret_pos
else
param_pos
in
let param_ty =
mk (Reason.Rinout_param (get_pos out_ty), get_node out_ty)
in
let (env, ty_err_opt) =
Typing_coercion.coerce_type
pos
Reason.URassign_inout
env
ety
(MakeType.unenforced param_ty)
Typing_error.Callback.inout_return_type_mismatch
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
Option.iter ~f:(Typing_error_utils.add_typing_error ~env)
@@ Typing_error.multiple_opt ty_errs;
env
let rec remove_like_for_return env ty =
match TUtils.try_strip_dynamic env ty with
| Some ty -> ty
| None ->
(match get_node ty with
| Tclass ((p, class_name), exact, [ty])
when String.equal class_name SN.Classes.cAwaitable ->
mk
( get_reason ty,
Tclass ((p, class_name), exact, [remove_like_for_return env ty]) )
| _ -> ty)
let fun_implicit_return env pos ret =
let ret =
if TypecheckerOptions.enable_sound_dynamic env.genv.tcopt then
(* Under sound dynamic, void <D: dynamic, which means that it void <D: ~T for any T.
* However, for ergonomic reasons, it should not be the case that a function
* erroring about a missing `return` statement would stop if the return type were
* pessimised. This preserves the behavior that a function explicitly returning dynamic
* can have an implicit return, while requiring an explicit return for like types. *)
remove_like_for_return env ret
else
ret
in
let ret_pos = Some (Typing_defs_core.get_pos ret) in
function
| Ast_defs.FGenerator
| Ast_defs.FAsyncGenerator ->
env
| Ast_defs.FSync ->
(* A function without a terminal block has an implicit return; the
* "void" type *)
let env = check_inout_return Pos.none env in
let r = Reason.Rno_return pos in
let rty = MakeType.void r in
implicit_return
env
pos
~expected:ret
~actual:rty
~hint_pos:ret_pos
~is_async:false
| Ast_defs.FAsync ->
(* An async function without a terminal block has an implicit return;
* the Awaitable<void> type *)
let r = Reason.Rno_return_async pos in
let rty = MakeType.awaitable r (MakeType.void r) in
implicit_return
env
pos
~expected:ret
~actual:rty
~hint_pos:ret_pos
~is_async:true |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_return.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
(** Typing code concerned with return types. *)
val make_info :
Pos.t ->
Ast_defs.fun_kind ->
Nast.user_attribute list ->
env ->
Typing_defs.locl_possibly_enforced_ty ->
Typing_env_return_info.t
val implicit_return :
env ->
Ast_defs.pos ->
expected:Typing_defs.locl_ty ->
actual:Typing_defs.locl_ty ->
hint_pos:Pos_or_decl.t option ->
is_async:bool ->
env
val make_return_type :
ety_env:Typing_defs.expand_env ->
this_class:Decl_provider.Class.t option ->
?is_toplevel:bool ->
(* Wrap return type with supportdyn, used when checking SDT functions and methods *)
supportdyn:bool ->
env ->
(* Position of return type hint, or function name, if absent *)
hint_pos:Ast_defs.pos ->
(* Explicit type from source code *)
explicit:Typing_defs.decl_ty option ->
(* A type to use if the explicit type isn't present.
* e.g. implicit void (for constructors), or contextual type (for lambdas)
*)
default:Typing_defs.locl_ty option ->
env * Typing_defs.locl_possibly_enforced_ty
(** For async functions, strip Awaitable<_> from the return type *)
val strip_awaitable :
Ast_defs.fun_kind ->
env ->
Typing_defs.locl_possibly_enforced_ty ->
Typing_defs.locl_possibly_enforced_ty
val fun_implicit_return :
env -> Ast_defs.pos -> Typing_defs.locl_ty -> Ast_defs.fun_kind -> env
val check_inout_return : Ast_defs.pos -> env -> env |
OCaml | hhvm/hphp/hack/src/typing/typing_sequencing.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.
*
*)
(* Pass to check for unsequenced modifications to local variables.
*
* PHP has a somewhat weird evaluation order (technically unspecified,
* but...) that can cause us trouble. Evaluation is *usually*
* left-to-right except that for certain operators, if the left hand side
* is a variable, it is right-to-left.
*
* If we didn't handle this in some way, the typechecker would be unsound,
* since code like '$x + f($x = array())' typechecks if you assume
* left-to-right evaluation but will fail at runtime.
*
* We deal with this by outlawing unsequenced modification and access
* to local variables. We consider certain operations to be "sequencing";
* (that is, they sequence their subexpressions)
* two expressions are unsequenced if their least common
* ancestor in the syntax tree is *not* sequencing.
*
* Basically everything is sequencing except:
* all binops except && and ||, array/object accesses,
* array field specifiers, list(...),
* assignment (sort of; '$x = $x+1' is OK, '$x = $x++' is not)
* (The first three correspond to when eval order can get reversed;
* the others just correspond to bad code.)
*
* This all solves the unsoundness problem without needing to commit the
* typechecker to exactly understanding the evaluation order and also
* closes off most of the ways a strict Hack program can observe unusual
* evaluation order (side-effectful __toString methods can observe it;
* maybe other ways also).
*
*)
open Hh_prelude
open Aast
type env = {
(* tracking will be set when we are under an unsequenced operation
* that requires us to be tracking variable accesses *)
tracking: bool;
(* We should maybe use a better data structure than lists. *)
used: (Pos.t * Local_id.t) list;
assigned: (Pos.t * Local_id.t) list;
}
let empty_env = { tracking = false; used = []; assigned = [] }
let tracking_env = { empty_env with tracking = true }
let add_id map px = px :: map
let assign_local env id =
if env.tracking then
{ env with assigned = add_id env.assigned id }
else
env
let use_local env id =
if env.tracking then
{ env with used = add_id env.used id }
else
env
(* Traverse down through list(...) destructuring to find all
* the "atomic" lvals that are being assigned to. *)
let unpack_lvals e =
let rec unpack acc = function
| (_, _, List es) -> List.fold_left ~f:unpack ~init:acc es
| e -> e :: acc
in
List.rev (unpack [] e)
let get_lvar = function
| (_, _, Lvar id) -> First id
| e -> Second e
(* Pass that just collects all the variables used (and not just written to)
* in fragments of code.
* We need this because a common idiom is to assign to unused variables
* as a form of documentation, and we want to ignore those variables
* when doing our sequencing checks. *)
let used_variables_visitor =
object (this)
inherit [Local_id.Set.t] Nast.Visitor_DEPRECATED.visitor as parent
method! on_lvar acc (_, id) = Local_id.Set.add id acc
(* We have to handle expressions just enough to avoid counting
* assignments as uses of variables.
* (We do still count operator-assignments) *)
method! on_expr acc ((_, _, e_) as e) =
match e_ with
| Binop Aast.{ bop = Ast_defs.Eq None; lhs = e1; rhs = e2 } ->
let (_, not_vars) = List.partition_map (unpack_lvals e1) ~f:get_lvar in
let acc = List.fold_left ~f:this#on_expr ~init:acc not_vars in
this#on_expr acc e2
| _ -> parent#on_expr acc e
end
(* Actual sequence checking pass *)
let sequence_visitor ~require_used used_vars =
(* First declare some helpers that don't need to be in the object *)
(* Merge a separately checked environment into the current one *)
let merge env new_env =
if env.tracking then
{
used = new_env.used @ env.used;
assigned = new_env.assigned @ env.assigned;
tracking = true;
}
else
empty_env
in
(* Check the used/assigned sets from two unsequenced expressions and report
* errors if they conflict.
* N.B that the sets are only checked for conflicts against the other
* environment and not for other accesses in itself. There may well be
* multiple writes to the same location in one env; these will either
* have been properly sequenced or an error would already have been reported.
*)
let check_unsequenced env1 env2 =
let id_matches (_p1, x1) (_p2, x2) = Local_id.equal x1 x2 in
let check_write_conflicts reads writes ((p, _) as id) =
let conflicting_reads = List.filter reads ~f:(id_matches id) in
let conflicting_writes = List.filter writes ~f:(id_matches id) in
(* Ignore conflicts when writing to variables that are never read
* in order to support the idiom where pointless variable
* assignments are used as documentation. *)
let conflicting_writes =
if not require_used then
conflicting_writes
else
List.filter conflicting_writes ~f:(fun (_, x) ->
Local_id.Set.mem x used_vars)
in
let cleanup = List.map ~f:fst in
if not (List.is_empty conflicting_reads) then
Errors.add_error
Nast_check_error.(
to_user_error
@@ Local_variable_modified_and_used
{ pos = p; pos_useds = cleanup conflicting_reads });
if not (List.is_empty conflicting_writes) then
Errors.add_error
Nast_check_error.(
to_user_error
@@ Local_variable_modified_twice
{ pos = p; pos_modifieds = cleanup conflicting_writes })
in
(* reversing the lists makes things sorted more naturally in the output *)
let (reads1, writes1) = (List.rev env1.used, List.rev env1.assigned) in
let (reads2, writes2) = (List.rev env2.used, List.rev env2.assigned) in
List.iter writes1 ~f:(check_write_conflicts reads2 writes2);
(* Only check writes2 for conflicts with the reads from env1,
* since we've already checked for write/write conflicts. *)
List.iter writes2 ~f:(check_write_conflicts reads1 [])
in
let merge_unsequenced env env1 env2 =
check_unsequenced env1 env2;
let env = merge env env1 in
let env = merge env env2 in
env
in
let merge_unsequenced_list envs =
List.fold_left
envs
~f:
begin
fun env1 env2 ->
check_unsequenced env1 env2;
merge env1 env2
end
~init:tracking_env
in
(* And now the actual visitor object *)
object (this)
inherit [env] Nast.Visitor_DEPRECATED.visitor as parent
method check_unsequenced_exprs env e1 e2 =
let env1 = this#on_expr tracking_env e1 in
let env2 = this#on_expr tracking_env e2 in
merge_unsequenced env env1 env2
method! on_expr env ((_, _, e_) as e) =
match e_ with
| Lvar id -> use_local env id
| Unop
( (Ast_defs.Uincr | Ast_defs.Udecr | Ast_defs.Upincr | Ast_defs.Updecr),
(_, _, Lvar id) ) ->
assign_local env id
(* Assignment. This is pretty hairy because of list(...)
* destructuring and the treatment necessary to allow
* code like '$x = $x + 1'. *)
| Binop Aast.{ bop = Ast_defs.Eq _; lhs = e1; rhs = e2 } ->
(* Unpack any list(...) destructuring and separate out locals
* we are assigning to from other lvals. *)
let (lvars, lval_exprs) =
List.partition_map (unpack_lvals e1) ~f:get_lvar
in
(* Build separate envs for the direct variable assignments and
* for the other lvals assigned to. We treat all these lvals
* as unsequenced. *)
let lvar_envs = List.map lvars ~f:(assign_local tracking_env) in
let lhs_var_env = merge_unsequenced_list lvar_envs in
let lval_expr_envs =
List.map lval_exprs ~f:(this#on_expr tracking_env)
in
let lval_expr_env = merge_unsequenced_list lval_expr_envs in
let rhs_env = this#on_expr tracking_env e2 in
(* Our lhs local var writes only conflict with other *writes* on
* the rhs, not with reads (need to allow '$x = $x + 1' but
* disallow '$x = $x++'), so we do a check_unsequenced against
* a version of env2 containing only the writes and then merge
* with the real thing. *)
let rhs_writes = { empty_env with assigned = rhs_env.assigned } in
check_unsequenced lhs_var_env rhs_writes;
(* Also check local assignments against the other lvalues *)
check_unsequenced lhs_var_env lval_expr_env;
(* We've manually handled everything relating to the lhs locals,
* so merge them into the env and then do a regular unsequenced
* merge of the non local lhs stuff against the rhs. *)
let env = merge env lhs_var_env in
merge_unsequenced env lval_expr_env rhs_env
(* leave && and || sequenced before making all
* the other binops unsequenced *)
| Binop
Aast.
{
bop =
Ast_defs.Ampamp | Ast_defs.Barbar | Ast_defs.QuestionQuestion;
_;
} ->
parent#on_expr env e
(* These operations have unsequenced subexpressions. *)
| Binop Aast.{ lhs = e1; rhs = e2; _ }
| Obj_get (e1, e2, _, _)
| Array_get (e1, Some e2) ->
this#check_unsequenced_exprs env e1 e2
| Efun { ef_fun = f; ef_use = idl; _ }
| Lfun (f, idl) ->
let nb = f.f_body in
(* Ignore the current environment and start fresh. *)
let _acc = this#on_block empty_env nb.fb_ast in
(* we use all the variables we are capturing *)
List.fold_left ~f:(fun acc (_, id) -> use_local acc id) ~init:env idl
| _ -> parent#on_expr env e
method! on_field env (e1, e2) = this#check_unsequenced_exprs env e1 e2
method! on_afield env =
function
| AFvalue e -> this#on_expr env e
| AFkvalue (e1, e2) -> this#check_unsequenced_exprs env e1 e2
(* Handle case to disallow assigning to vars inside case labels. *)
method! on_case acc (e, b) =
let env = this#on_expr tracking_env e in
List.iter env.assigned ~f:(fun (p, _) ->
Errors.add_error
Nast_check_error.(to_user_error @@ Assign_during_case p));
let acc = this#on_block acc b in
acc
end
let sequence_check_block block =
let used_vars = used_variables_visitor#on_block Local_id.Set.empty block in
let visitor = sequence_visitor ~require_used:true used_vars in
let _ = visitor#on_block empty_env block in
()
let sequence_check_expr expr =
let visitor = sequence_visitor ~require_used:false Local_id.Set.empty in
let _ = visitor#on_expr empty_env expr in
() |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_sequencing.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 sequence_check_block : Nast.block -> unit
val sequence_check_expr : Nast.expr -> unit |
OCaml | hhvm/hphp/hack/src/typing/typing_set.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.
*
*)
(* An implementation of a set of types, using compare_locl_ty for a total order.
* Typing-rule-equivalent types may get duplicated, as the equality induced
* by compare_locl_ty does not expand Tvars and type aliases.
*)
open Hh_prelude
open Typing_defs
module Ty_ = struct
type t = locl_ty [@@deriving show]
let compare r1 r2 = Typing_defs.compare_locl_ty r1 r2
end
include Caml.Set.Make (Ty_)
let pp fmt t =
Format.fprintf fmt "@[<hv 2>{";
ignore
(List.fold_left
~f:(fun sep ty ->
if sep then Format.fprintf fmt ";@ ";
Ty_.pp fmt ty;
true)
~init:false
(elements t));
Format.fprintf fmt "@,}@]"
let show = Format.asprintf "%a" pp |
OCaml | hhvm/hphp/hack/src/typing/typing_shapes.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 Common
open Typing_defs
module Env = Typing_env
module Reason = Typing_reason
module TUtils = Typing_utils
module Type = Typing_ops
module MakeType = Typing_make_type
let widen_for_refine_shape ~expr_pos field_name env ty =
Typing_log.(
log_with_level env "typing" ~level:1 (fun () ->
log_types
(Pos_or_decl.of_raw_pos expr_pos)
env
[Log_head ("widen_for_refine_shape", [Log_type ("ty", ty)])]));
match deref ty with
| (r, Tshape { s_origin = _; s_unknown_value = shape_kind; s_fields = fields })
-> begin
match TShapeMap.find_opt field_name fields with
| None ->
let (env, element_ty) = Env.fresh_type_invariant env expr_pos in
let sft = { sft_optional = true; sft_ty = element_ty } in
( (env, None),
Some
(mk
( r,
Tshape
{
s_origin = Missing_origin;
s_unknown_value = shape_kind;
s_fields = TShapeMap.add field_name sft fields;
} )) )
| Some _ -> ((env, None), Some ty)
end
| _ -> ((env, None), None)
(* Refine a shape with the knowledge that field_name
* exists. We do this by intersecting with
* shape(field_name => mixed, ...)
*)
let refine_shape field_name pos env shape =
let ((env, e1), shape) =
Typing_solver.expand_type_and_narrow
~description_of_expected:"a shape"
env
(widen_for_refine_shape ~expr_pos:pos field_name)
pos
shape
in
let r =
Reason.Rmissing_optional_field
(get_pos shape, TUtils.get_printable_shape_field_name field_name)
in
let sft_ty = MakeType.mixed r in
let sft_ty =
if
TUtils.is_dynamic env shape
&& TypecheckerOptions.enable_sound_dynamic (Env.get_tcopt env)
then
MakeType.supportdyn r sft_ty
else
sft_ty
in
let sft = { sft_optional = false; sft_ty } in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) e1;
Typing_intersection.intersect
env
~r:(Reason.Rwitness pos)
shape
(MakeType.open_shape Reason.Rnone (TShapeMap.singleton field_name sft))
let make_locl_like_type env ty =
if TypecheckerOptions.enable_sound_dynamic (Env.get_tcopt env) then
let dyn = MakeType.dynamic (Reason.Renforceable (get_pos ty)) in
Typing_union.union env dyn ty
else
(env, ty)
(*****************************************************************************)
(* Remove a field from all the shapes found in a given type.
* The function leaves all the other types (non-shapes) unchanged.
*)
(*****************************************************************************)
let rec shrink_shape pos ~supportdyn field_name env shape =
(* Make sure we have a shape type in our hands.
* Note that we don't want to freshen any types inside the shape
* e.g. turn shape('a' => C) into shape('a' => #1) with a subtype constraint on #1,
* because we know that the types of the fields don't change
*)
let ((env, e1), shape) =
Typing_solver.expand_type_and_solve
~freshen:false
~description_of_expected:"a shape"
env
pos
shape
in
let (supportdyn2, env, stripped_shape) = TUtils.strip_supportdyn env shape in
let supportdyn = supportdyn || supportdyn2 in
match get_node stripped_shape with
| Tshape { s_origin = _; s_unknown_value = shape_kind; s_fields = fields } ->
let fields =
if is_nothing shape_kind then
TShapeMap.remove field_name fields
(* TODO akenn: check this *)
else
let printable_name = TUtils.get_printable_shape_field_name field_name in
let nothing =
MakeType.nothing (Reason.Runset_field (pos, printable_name))
in
TShapeMap.add
field_name
{ sft_ty = nothing; sft_optional = true }
fields
in
let result =
mk
( Reason.Rwitness pos,
Tshape
{
s_origin = Missing_origin;
s_unknown_value = shape_kind;
s_fields = fields;
} )
in
( (env, e1),
if supportdyn then
let r = get_reason result in
MakeType.supportdyn r result
else
result )
| Tunion tyl ->
let ((env, e2), tyl) =
List.map_env_ty_err_opt
env
tyl
~combine_ty_errs:Typing_error.multiple_opt
~f:(shrink_shape pos ~supportdyn field_name)
in
let result = mk (Reason.Rwitness pos, Tunion tyl) in
((env, Option.merge e1 e2 ~f:Typing_error.both), result)
| _ ->
( (env, e1),
if supportdyn then
let r = get_reason shape in
MakeType.supportdyn r shape
else
shape )
(* Refine the type of a shape knowing that a call to Shapes::idx is not null.
* This means that the shape now has the field, and that the type for this
* field is not nullable.
* We stay quite liberal here: we add the field to the shape type regardless
* of whether this field can be here at all. Errors will anyway be raised
* elsewhere when typechecking the call to Shapes::idx. This allows for more
* useful typechecking of incomplete code (code in the process of being
* written). *)
let shapes_idx_not_null_with_ty_err env shape_ty (ty, p, field) =
let (fld_opt, ty_err_opt) =
TUtils.shape_field_name_with_ty_err env (ty, p, field)
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
match fld_opt with
| None -> ((env, None), shape_ty)
| Some field ->
let field = TShapeField.of_ast Pos_or_decl.of_raw_pos field in
let ((env, e1), shape_ty) =
Typing_solver.expand_type_and_narrow
~description_of_expected:"a shape"
env
(widen_for_refine_shape ~expr_pos:p field)
p
shape_ty
in
let rec refine_type env shape_ty =
let (env, shape_ty) = Env.expand_type env shape_ty in
match deref shape_ty with
| (r, Tnewtype (n, _, ty))
when String.equal n Naming_special_names.Classes.cSupportDyn ->
let (env, ty) = refine_type env ty in
TUtils.make_supportdyn r env ty
| ( r,
Tshape { s_origin = _; s_fields = ftm; s_unknown_value = shape_kind }
) ->
let (env, field_type) =
let sft_ty =
match TShapeMap.find_opt field ftm with
| Some { sft_ty; _ } -> sft_ty
| None -> shape_kind
in
let (env, sft_ty) =
Typing_solver.non_null env (Pos_or_decl.of_raw_pos p) sft_ty
in
(env, { sft_optional = false; sft_ty })
in
let ftm = TShapeMap.add field field_type ftm in
( env,
mk
( r,
Tshape
{
s_origin = Missing_origin;
s_fields = ftm;
s_unknown_value = shape_kind;
} ) )
| _ ->
(* This should be an error, but it is already raised when
typechecking the call to Shapes::idx *)
(env, shape_ty)
in
(match deref shape_ty with
| (r, Tunion tyl) ->
let (env, tyl) = List.map_env env tyl ~f:refine_type in
let (env, ty) = Typing_union.union_list env r tyl in
((env, e1), ty)
| _ ->
let (env, ty) = refine_type env shape_ty in
((env, None), ty))
let shapes_idx_not_null env shape_ty fld =
let ((env, ty_err_opt), res) =
shapes_idx_not_null_with_ty_err env shape_ty fld
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
(env, res)
let make_idx_fake_super_shape shape_pos fun_name field_name field_ty =
MakeType.open_shape
(Reason.Rshape (shape_pos, fun_name))
(TShapeMap.singleton field_name field_ty)
(* Typing rules for Shapes::idx
*
* e : ?shape(?sfn => t, ...)
* ----------------------------
* Shapes::idx(e, sfn) : ?t
*
* Typing rules when the shape has a like type:
*
* e : ~?shape(?sfn => t, ...)
* ----------------------------
* Shapes::idx(e, sfn) : ~?t
*)
let idx_without_default env ~expr_pos ~shape_pos shape_ty field_name =
let (env, shape_ty) = Env.expand_type env shape_ty in
let (env, res) = Env.fresh_type env expr_pos in
let ((env, ty_err_opt), res) =
let fake_super_shape_ty =
make_idx_fake_super_shape
shape_pos
"Shapes::idx"
field_name
{ sft_optional = true; sft_ty = res }
in
let nullable_super_shape = mk (Reason.Rnone, Toption fake_super_shape_ty) in
let super_shape =
if TypecheckerOptions.enable_sound_dynamic (Env.get_tcopt env) then
let like_nullable_super_shape =
MakeType.locl_like (Reason.Rwitness shape_pos) nullable_super_shape
in
like_nullable_super_shape
else
nullable_super_shape
in
let (env, ty_err_opt) =
Typing_coercion.coerce_type
shape_pos
Reason.URparam
env
shape_ty
{ et_type = super_shape; et_enforced = Unenforced }
Typing_error.Callback.unify_error
in
let (env, res) = TUtils.union env res (MakeType.null Reason.Rnone) in
((env, ty_err_opt), res)
in
let (env, res) =
match get_node (TUtils.strip_dynamic env shape_ty) with
| Tnewtype (n, _, _)
when String.equal n Naming_special_names.Classes.cSupportDyn ->
let r = get_reason shape_ty in
TUtils.make_supportdyn r env res
| _ -> (env, res)
in
Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env);
make_locl_like_type env res
let remove_key_with_ty_err p env shape_ty ((_, field_p, _) as field) =
let (fld_opt, ty_err_opt) = TUtils.shape_field_name_with_ty_err env field in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
match fld_opt with
| None ->
let (env, ty) = Env.fresh_type_error env field_p in
((env, None), ty)
| Some field_name ->
let field_name = TShapeField.of_ast Pos_or_decl.of_raw_pos field_name in
shrink_shape ~supportdyn:false p field_name env shape_ty
let remove_key p env shape_ty field =
let ((env, ty_err_opt), res) = remove_key_with_ty_err p env shape_ty field in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
(env, res)
let to_collection env pos shape_ty res return_type =
let mapper =
object (self)
inherit Type_mapper.shallow_type_mapper as super
inherit! Type_mapper.tunion_type_mapper
inherit! Type_mapper.tvar_expanding_type_mapper
method! on_tshape env r s =
let { s_origin = _; s_unknown_value = shape_kind; s_fields = fdm } =
s
in
(* The key type is the union of the types of the known fields,
* or arraykey if there may be unknown fields (open shape)
*)
let (env, key) =
if not (TUtils.is_nothing env shape_kind) then
(env, MakeType.arraykey r)
else
let keys = TShapeMap.keys fdm in
let (env, keys) =
List.map_env env keys ~f:(fun env key ->
match key with
| Typing_defs.TSFlit_int (p, _) ->
(env, MakeType.int (Reason.Rwitness_from_decl p))
| Typing_defs.TSFlit_str (p, _) ->
(env, MakeType.string (Reason.Rwitness_from_decl p))
| Typing_defs.TSFclass_const ((_, cid), (_, mid)) -> begin
match Env.get_class env cid with
| Some class_ -> begin
match Env.get_const env class_ mid with
| Some const ->
let ((env, ty_err_opt), lty) =
Typing_phase.localize_no_subst
env
~ignore_errors:true
const.cc_type
in
Option.iter
~f:(Typing_error_utils.add_typing_error ~env)
ty_err_opt;
(env, lty)
| None -> Env.fresh_type_error env pos
end
| None -> Env.fresh_type_error env pos
end)
in
Typing_union.union_list env r keys
in
(* The value type is the union of the types of the known fields together
* with the type of the unknown fields (open shape, typically mixed or supportdyn<mixed>)
*)
let (env, value) =
(* If the unknown fields have type mixed then that's the type of values: no need for union *)
if TUtils.is_mixed env shape_kind then
(env, shape_kind)
else
(* Otherwise first filter out subtypes (common case,
* as unknown fields are likely supportdyn<mixed>)
* and then construct the union.
*)
let values = TShapeMap.values fdm in
let values =
List.filter_map
~f:(fun { sft_ty; _ } ->
if TUtils.is_sub_type env sft_ty shape_kind then
None
else
Some sft_ty)
values
in
Typing_union.union_list env r (shape_kind :: values)
in
return_type env (get_reason res) key value
method! on_tunion env r tyl =
let (env, tyl) = List.fold_map tyl ~init:env ~f:self#on_type in
Typing_union.union_list env r tyl
method! on_tintersection env r tyl =
let (env, tyl) = List.fold_map tyl ~init:env ~f:self#on_type in
Typing_intersection.intersect_list env r tyl
method! on_type env ty =
match get_node ty with
| Tdynamic ->
(* This makes it so that to_collection on a dynamic value returns a dynamic
* value instead of the standard dict<arraykey, mixed> declared in the HHI,
* which would otherwise subsume any other inferred type due to covariance. *)
(env, ty)
| Tvar _
| Tshape _
| Tunion _
| Tintersection _ ->
super#on_type env ty
(* Look through bound on newtype, including supportdyn. We assume that
* supportdyn has already been pushed into the type of unknown fields *)
| Tnewtype (_, _, ty) -> super#on_type env ty
| _ -> (env, res)
end
in
mapper#on_type (Type_mapper.fresh_env env) shape_ty
let to_dict env pos shape_ty res =
let ((env, e1), shape_ty) =
Typing_solver.expand_type_and_solve
~description_of_expected:"a shape"
env
pos
shape_ty
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) e1;
let shape_ty = TUtils.get_base_type ~expand_supportdyn:true env shape_ty in
to_collection env pos shape_ty res (fun env r key value ->
(env, MakeType.dict r key value))
let shape_field_pos = function
| Ast_defs.SFlit_int (p, _)
| Ast_defs.SFlit_str (p, _) ->
p
| Ast_defs.SFclass_const ((cls_pos, _), (mem_pos, _)) ->
Pos.btw cls_pos mem_pos
let check_shape_keys_validity env keys =
(* If the key is a class constant, get its class name and type. *)
let get_field_info env key =
let key_pos = shape_field_pos key in
(* Empty strings or literals that start with numbers are not
permitted as shape field names. *)
match key with
| Ast_defs.SFlit_int _ -> (env, key_pos, None)
| Ast_defs.SFlit_str (_, key_name) ->
(if Int.equal 0 (String.length key_name) then
Typing_error_utils.add_typing_error ~env
@@ Typing_error.(
shape
@@ Primary.Shape.Invalid_shape_field_name
{ pos = key_pos; is_empty = true }));
(env, key_pos, None)
| Ast_defs.SFclass_const ((_p, cls), (p, y)) -> begin
match Env.get_class env cls with
| None ->
let (env, ty) = Env.fresh_type_error env p in
(env, key_pos, Some (cls, ty))
| Some cd ->
(match Env.get_const env cd y with
| None ->
Typing_error_utils.add_typing_error ~env
@@ Typing_object_get.smember_not_found
p
~is_const:true
~is_method:false
~is_function_pointer:false
cd
y
Typing_error.Callback.unify_error;
let (env, ty) = Env.fresh_type_error env p in
(env, key_pos, Some (cls, ty))
| Some { cc_type; _ } ->
let ((env, ty_err_opt), ty) =
Typing_phase.localize_no_subst ~ignore_errors:true env cc_type
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
let r = Reason.Rwitness key_pos in
let (env, e2) =
Type.sub_type key_pos Reason.URnone env ty (MakeType.arraykey r)
@@ Typing_error.(
Callback.always
Primary.(
Shape
(Shape.Invalid_shape_field_type
{
pos = key_pos;
ty_pos = get_pos ty;
ty_name = lazy (Typing_print.error env ty);
trail = [];
})))
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) e2;
(env, key_pos, Some (cls, ty)))
end
in
let check_field witness_pos witness_info env key =
let (env, key_pos, key_info) = get_field_info env key in
let ty_errs =
let open Typing_error in
match (witness_info, key_info) with
| (Some _, None) ->
[
shape
@@ Primary.Shape.Invalid_shape_field_literal
{ pos = key_pos; witness_pos };
]
| (None, Some _) ->
[
shape
@@ Primary.Shape.Invalid_shape_field_const
{ pos = key_pos; witness_pos };
]
| (None, None) -> []
| (Some (cls1, ty1), Some (cls2, ty2)) ->
List.filter_map
~f:Fn.id
[
(if TUtils.is_tyvar_error env ty1 || TUtils.is_tyvar_error env ty2
then
None
else if String.( <> ) cls1 cls2 then
Some
(shape
(Primary.Shape.Shape_field_class_mismatch
{
pos = key_pos;
witness_pos;
class_name = Utils.strip_ns cls2;
witness_class_name = Utils.strip_ns cls1;
}))
else
None);
(if TUtils.is_tyvar_error env ty1 || TUtils.is_tyvar_error env ty2
then
None
else
let (ty1_sub_ty2, e1) = Typing_solver.is_sub_type env ty1 ty2
and (ty2_sub_ty1, e2) = Typing_solver.is_sub_type env ty2 ty1 in
let e3 =
if not (ty1_sub_ty2 && ty2_sub_ty1) then
Some
(shape
(Primary.Shape.Shape_field_type_mismatch
{
pos = key_pos;
witness_pos;
ty_name = lazy (Typing_print.error env ty2);
witness_ty_name = lazy (Typing_print.error env ty1);
}))
else
None
in
Typing_error.multiple_opt @@ List.filter_map ~f:Fn.id [e1; e2; e3]);
]
in
let ty_err_opt = Typing_error.multiple_opt ty_errs in
(env, ty_err_opt)
in
(* Sort the keys by their positions since the error messages will make
* more sense if we take the one that appears first as canonical and if
* they are processed in source order. *)
let cmp_keys x y = Pos.compare (shape_field_pos x) (shape_field_pos y) in
let keys = List.sort ~compare:cmp_keys keys in
match keys with
| [] -> env
| witness :: rest_keys ->
let (env, pos, info) = get_field_info env witness in
let (env, ty_errs) =
List.fold_left rest_keys ~init:(env, []) ~f:(fun (env, ty_errs) k ->
match check_field pos info env k with
| (env, Some ty_err) -> (env, ty_err :: ty_errs)
| (env, _) -> (env, ty_errs))
in
let ty_err_opt = Typing_error.multiple_opt ty_errs in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
env
let update_param : decl_fun_param -> decl_ty -> decl_fun_param =
(fun param ty -> { param with fp_type = { param.fp_type with et_type = ty } })
(* For function Shapes::idx called with a literal
* field name, transform the decl function type from the hhi file
* into a type that is specific to the field.
*
* In the hhi file, the function has type
* Shapes::idx<Tv>(
* ?shape(...) $shape,
* arraykey $index,
* ?Tv,
* )[]: ?Tv;
*
* If there are two arguments, transform it to
* Shapes::idx<Tv>(
* ?shape('field_name' => Tv, ...) $shape,
* arraykey $index,
* )[]: ?Tv;
*
* If there are three arguments, transform it to
* Shapes::idx<Tv>(
* ?shape('field_name' => Tv, ...) $shape,
* arraykey $index,
* Tv $default,
* )[]: Tv;
*)
let transform_idx_fun_ty (field_name : tshape_field_name) nargs fty =
let (param1, param2, param3) =
match fty.ft_params with
| [param1; param2; param3] -> (param1, param2, param3)
| _ -> failwith "Expected 3 parameters for Shapes::idx in hhi file"
in
let rret = get_reason fty.ft_ret.et_type in
let field_ty : decl_ty =
MakeType.generic (Reason.Rwitness_from_decl param1.fp_pos) "Tv"
in
let (params, ret) =
let param1 =
update_param
param1
(mk
( Reason.Rnone,
Toption
(MakeType.open_shape
(Reason.Rwitness_from_decl param1.fp_pos)
(TShapeMap.singleton
field_name
{ sft_optional = true; sft_ty = field_ty })) ))
in
match nargs with
| 2 ->
(* Return type should be ?Tv *)
let ret = MakeType.nullable rret (MakeType.generic rret "Tv") in
([param1; param2], ret)
| 3 ->
(* Third parameter should have type Tv *)
let param3 =
let r3 = get_reason param1.fp_type.et_type in
update_param param3 (MakeType.generic r3 "Tv")
in
(* Return type should be Tv *)
let ret = MakeType.generic rret "Tv" in
([param1; param2; param3], ret)
(* Shouldn't happen! *)
| _ -> (fty.ft_params, fty.ft_ret.et_type)
in
{ fty with ft_params = params; ft_ret = { fty.ft_ret with et_type = ret } }
(* For function Shapes::at called with a literal
* field name, transform the decl function type from the hhi file
* into a type that is specific to the field.
*
* In the hhi file, the function has type
* Shapes::at<Tv>(
* shape(...) $shape,
* arraykey $index,
* )[]: Tv;
*
* Transform it to
* Shapes::at<Tv>(
* shape('field_name' => Tv, ...) $shape,
* arraykey $index,
* )[]: Tv;
*)
let transform_at_fun_ty (field_name : tshape_field_name) fty =
let (param1, param2) =
match fty.ft_params with
| [param1; param2] -> (param1, param2)
| _ -> failwith "Expected 2 parameters for Shapes::at in hhi file"
in
let params =
(* Return type should be Tv already, but first parameter is just shape(...) *)
let field_ty : decl_ty =
MakeType.generic (Reason.Rwitness_from_decl param1.fp_pos) "Tv"
in
let param1 =
update_param
param1
(MakeType.open_shape
(Reason.Rwitness_from_decl param1.fp_pos)
(TShapeMap.singleton
field_name
{ sft_optional = true; sft_ty = field_ty }))
in
[param1; param2]
in
{ fty with ft_params = params }
(* For functions Shapes::idx or Shapes::at called with a literal
* field name, transform the decl function type from the hhi file
* into a type that is specific to the field.
*)
let transform_special_shapes_fun_ty field_name id nargs fty =
if String.equal (snd id) Naming_special_names.Shapes.at then
transform_at_fun_ty field_name fty
else if String.equal (snd id) Naming_special_names.Shapes.idx then
transform_idx_fun_ty field_name nargs fty
else
fty |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_shapes.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 refine_shape :
Typing_defs.TShapeMap.key ->
Pos.t ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty
val idx_without_default :
Typing_env_types.env ->
expr_pos:Pos.t ->
shape_pos:Pos.t ->
Typing_defs.locl_ty ->
Typing_defs.tshape_field_name ->
Typing_env_types.env * Typing_defs.locl_ty
val shapes_idx_not_null :
Typing_env_types.env ->
Typing_defs.locl_ty ->
Nast.expr ->
Typing_env_types.env * Typing_defs.locl_ty
val remove_key :
Pos.t ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
('a, 'b) Aast.expr ->
Typing_env_types.env * Typing_reason.locl_phase Typing_defs.ty
val to_dict :
Typing_env_types.env ->
Pos.t ->
Typing_defs.locl_ty ->
Typing_defs.locl_phase Typing_defs.ty ->
Type_mapper.result
val check_shape_keys_validity :
Typing_env_types.env -> Ast_defs.shape_field_name list -> Typing_env_types.env
val transform_special_shapes_fun_ty :
Typing_defs.tshape_field_name ->
Aast.sid ->
int ->
Typing_defs.decl_fun_type ->
Typing_defs.decl_fun_type |
OCaml | hhvm/hphp/hack/src/typing/typing_skeleton.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.
*
*)
(* Generate method skeletons based on the known type.*)
open Hh_prelude
open Typing_defs
(* Given a type declaration, return user-denotable syntax that
represents it. This is lossy: we use mixed if there's no better
syntax. *)
let rec strip_supportdyn ty =
match get_node ty with
| Tapply (name, [ty])
when String.equal (snd name) Naming_special_names.Classes.cSupportDyn ->
strip_supportdyn ty
| _ -> ty
let rec of_decl_ty (ty : decl_ty) : string =
(* TODO: when we start supporting NoAutoDynamic, revisit this *)
let ty = strip_supportdyn ty in
match get_node ty with
| Tprim p -> Aast_defs.string_of_tprim p
| Tmixed
| Twildcard
| Tany _ ->
"mixed"
| Tnewtype (name, tyl, ty) ->
let name = Utils.strip_all_ns name in
(match tyl with
| [] -> name
| args ->
let args = List.map args ~f:of_decl_ty in
Printf.sprintf
"%s<%s> %s"
name
(String.concat ~sep:", " args)
(of_decl_ty ty))
| Tnonnull -> "nonnull"
| Tdynamic -> "dynamic"
| Tthis -> "this"
| Toption ty ->
(* TODO: when we start supporting NoAutoDynamic, revisit this *)
(match get_node (strip_supportdyn ty) with
| Typing_defs.Tnonnull -> "mixed"
| _ -> "?" ^ of_decl_ty ty)
| Tfun f ->
let params = List.map f.ft_params ~f:of_fun_param in
let params =
if get_ft_variadic f then
params @ ["..."]
else
params
in
Printf.sprintf
"(function(%s): %s)"
(String.concat ~sep:", " params)
(of_enforced_ty f.ft_ret)
| Tgeneric (name, args)
| Tapply ((_, name), args) ->
let name = Utils.strip_all_ns name in
(match args with
| [] -> name
| args ->
let args = List.map args ~f:of_decl_ty in
Printf.sprintf "%s<%s>" name (String.concat ~sep:", " args))
| Ttuple args ->
let args = List.map args ~f:of_decl_ty in
Printf.sprintf "(%s)" (String.concat ~sep:", " args)
| Tshape { s_origin = _; s_fields = fields; s_unknown_value = kind } ->
let fields =
TShapeMap.fold (fun key ty acc -> of_shape_field key ty :: acc) fields []
in
let fields_with_ellipsis =
if is_nothing kind (* Closed shape *) then
fields
(* Open shape TODO akenn non-mixed open *)
else
fields @ ["..."]
in
Printf.sprintf "shape(%s)" (String.concat ~sep:", " fields_with_ellipsis)
| Tunion [] -> "nothing"
| Tunion _ -> "mixed"
| Tintersection _ -> "mixed"
| Tvec_or_dict (key_ty, val_ty) ->
Printf.sprintf "vec_or_dict<%s, %s>" (of_decl_ty key_ty) (of_decl_ty val_ty)
| Tlike ty -> of_decl_ty ty
| Taccess (ty, (_, name)) -> Printf.sprintf "%s::%s" (of_decl_ty ty) name
| Trefinement (ty, rs) ->
Printf.sprintf
"%s with %s"
(of_decl_ty ty)
(Class_refinement.to_string of_decl_ty rs)
and of_enforced_ty et : string = of_decl_ty et.et_type
and of_fun_param fp : string = of_enforced_ty fp.fp_type
and of_shape_field (name : tshape_field_name) sft : string =
let name_s =
match name with
| TSFlit_int (_, s) -> s
| TSFlit_str (_, s) -> Printf.sprintf "\"%s\"" s
| TSFclass_const ((_, c_name), (_, const_name)) ->
Printf.sprintf "%s::%s" c_name const_name
in
let name_s =
if sft.sft_optional then
"?" ^ name_s
else
name_s
in
Printf.sprintf "%s => %s" name_s (of_decl_ty sft.sft_ty)
let param_source (param : decl_ty fun_param) ~(variadic : bool) : string =
let name = Option.value param.fp_name ~default:"$_" in
let ty_s = of_decl_ty param.fp_type.et_type in
Printf.sprintf
"%s %s%s"
ty_s
(if variadic then
"..."
else
"")
name
(* Is this type of the form Awaitable<something> ? *)
let rec is_awaitable (ty : decl_ty) : bool =
match get_node ty with
| Tapply ((_, name), _)
when String.equal name Naming_special_names.Classes.cAwaitable ->
true
| Tlike ty -> is_awaitable ty
| _ -> false
let params_source ~variadic (params : decl_ty fun_params) : string =
let n = List.length params in
let explicit_params =
List.mapi params ~f:(fun i p ->
param_source ~variadic:(variadic && i + 1 = n) p)
in
String.concat ~sep:", " explicit_params
let of_implicit_params (impl_params : decl_ty fun_implicit_params) : string =
match impl_params.capability with
| CapDefaults _ -> ""
| CapTy t ->
(match get_node t with
| Tintersection tys ->
let contexts = List.map tys ~f:of_decl_ty in
Printf.sprintf "[%s]" (String.concat ~sep:", " contexts)
| _ -> "")
let of_method (name : string) (meth : class_elt) ~is_static ~is_override :
string =
(* TODO: when we start supporting NoAutoDynamic, revisit this *)
let (_, ty_) = deref (strip_supportdyn (Lazy.force meth.ce_type)) in
let (params, return_ty, async_modifier, capabilities) =
match ty_ with
| Tfun ft ->
( params_source ~variadic:(get_ft_variadic ft) ft.ft_params,
of_decl_ty ft.ft_ret.et_type,
(if is_awaitable ft.ft_ret.et_type then
"async "
else
""),
of_implicit_params ft.ft_implicit_params )
| _ -> ("", "mixed", "", "")
in
Printf.sprintf
"\n%s %s %s%sfunction %s(%s)%s: %s {}\n"
(if is_override then
" <<__Override>>\n"
else
"")
(Typing_defs.string_of_visibility meth.ce_visibility)
(if is_static then
"static "
else
"")
async_modifier
name
params
capabilities
return_ty |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_skeleton.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.
*
*)
(** Generates source code for a method skeleton that matches [meth],
with the appropriate static modifier and override attribute.*)
val of_method :
string ->
Typing_defs.class_elt ->
is_static:bool ->
is_override:bool ->
string |
OCaml | hhvm/hphp/hack/src/typing/typing_solver.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Common
open Typing_defs
open Typing_env_types
module Reason = Typing_reason
module Env = Typing_env
module Inter = Typing_intersection
module ITySet = Internal_type_set
module TL = Typing_logic
module TUtils = Typing_utils
module Utils = Typing_solver_utils
module Cls = Decl_provider.Class
module TySet = Typing_set
module MakeType = Typing_make_type
let log_remaining_prop env =
let filename = Pos.filename env.genv.callable_pos in
if not (Relative_path.is_hhi (Relative_path.prefix filename)) then (
let prop =
Typing_inference_env.get_nongraph_subtype_prop env.inference_env
in
(if TypecheckerOptions.log_inference_constraints (Env.get_tcopt env) then
let p_as_string = Typing_print.subtype_prop env prop in
let pos = Pos.string (Pos.to_absolute env.genv.callable_pos) in
let size = TL.size prop in
let n_disj = TL.n_disj prop in
let n_conj = TL.n_conj prop in
TypingLogger.InferenceCnstr.log p_as_string ~pos ~size ~n_disj ~n_conj);
if (not (Errors.currently_has_errors ())) && not (TL.is_valid prop) then
Typing_log.log_prop
1
(Pos_or_decl.of_raw_pos env.genv.callable_pos)
"There are remaining unsolved constraints!"
env
prop
)
(* Given a type ty, replace any covariant or contravariant components of the type
* with fresh type variables. Components replaced include
* covariant key and element types for tuples, arrays, and shapes
* covariant return type and contravariant parameter types for function types
* co- and contra-variant parameters to classish types and newtypes
* Note that the variance of type variables is set explicitly to be invariant
* because we only use this function on the lower or upper bounds of an invariant
* type variable.
*
* Also note that freshening lifts through unions and nullables.
*
* Example 1: the type
* ?dict<t1,t2>
* will be transformed to
* ?dict<#1,#2>
*
* Example 2: the contravariant/invariant type
* ContraInv<t1,t2>
* will be transformed to
* Contra<#1,t2>
* leaving the invariant component alone.
*)
let rec freshen_inside_ty env ty =
let default () = (env, ty) in
let (env, ty) = Env.expand_type env ty in
let (r, ty_) = deref ty in
match ty_ with
| Tany _
| Tnonnull
| Tdynamic
| Tprim _
| Tneg _ ->
default ()
| Tgeneric (name, tyl) ->
if List.is_empty tyl then
default ()
else
(* TODO(T69931993) Replace Invariant here once we support arbitrary variances
on HK generics *)
let variancel =
List.replicate ~num:(List.length tyl) Ast_defs.Invariant
in
let (env, tyl) = freshen_tparams env variancel tyl in
(env, mk (r, Tnewtype (name, tyl, ty)))
| Tdependent _ -> default ()
(* Nullable is covariant *)
| Toption ty ->
let (env, ty) = freshen_inside_ty env ty in
(env, mk (r, Toption ty))
| Tunion tyl ->
let (env, tyl) = List.map_env env tyl ~f:freshen_inside_ty in
(env, mk (r, Tunion tyl))
| Tintersection tyl ->
let (env, tyl) = List.map_env env tyl ~f:freshen_inside_ty in
Inter.intersect_list env r tyl
(* Tuples are covariant *)
| Ttuple tyl ->
let (env, tyl) = List.map_env env tyl ~f:freshen_ty in
(env, mk (r, Ttuple tyl))
(* Shape data is covariant *)
| Tshape { s_origin = _; s_unknown_value = shape_kind; s_fields = fdm } ->
let (env, fdm) = ShapeFieldMap.map_env freshen_ty env fdm in
(* TODO(shapes) should freshening impact unknown type? *)
( env,
mk
( r,
Tshape
{
s_origin = Missing_origin;
s_unknown_value = shape_kind;
s_fields = fdm;
} ) )
(* Functions are covariant in return type, contravariant in parameter types *)
| Tfun ft ->
let (env, ft_ret) = freshen_possibly_enforced_ty env ft.ft_ret in
let (env, ft_params) =
List.map_env env ft.ft_params ~f:(fun env p ->
let (env, fp_type) = freshen_possibly_enforced_ty env p.fp_type in
(env, { p with fp_type }))
in
(env, mk (r, Tfun { ft with ft_ret; ft_params }))
| Tnewtype (name, _, ty)
when String.equal name Naming_special_names.Classes.cSupportDyn ->
let (env, ty) = freshen_inside_ty env ty in
(env, MakeType.supportdyn r ty)
| Tnewtype (name, tyl, ty) ->
if List.is_empty tyl then
default ()
else begin
match Env.get_typedef env name with
| None -> default ()
| Some td ->
let variancel = List.map td.td_tparams ~f:(fun t -> t.tp_variance) in
let (env, tyl) = freshen_tparams env variancel tyl in
(env, mk (r, Tnewtype (name, tyl, ty)))
end
| Tclass ((p, cid), e, tyl) ->
if List.is_empty tyl then
default ()
else begin
match Env.get_class env cid with
| None -> default ()
| Some cls ->
let variancel =
List.map (Cls.tparams cls) ~f:(fun t -> t.tp_variance)
in
let (env, tyl) = freshen_tparams env variancel tyl in
(env, mk (r, Tclass ((p, cid), e, tyl)))
end
| Tvec_or_dict (ty1, ty2) ->
let (env, ty1) = freshen_ty env ty1 in
let (env, ty2) = freshen_ty env ty2 in
(env, mk (r, Tvec_or_dict (ty1, ty2)))
| Tvar _ -> default ()
| Taccess (ty, ids) ->
let (env, ty) = freshen_ty env ty in
(env, mk (r, Taccess (ty, ids)))
| Tunapplied_alias _ -> default ()
and freshen_ty env ty =
if TUtils.is_tyvar_error env ty then
Env.fresh_type_error env (get_pos ty |> Pos_or_decl.unsafe_to_raw_pos)
else
Env.fresh_type_invariant env (get_pos ty |> Pos_or_decl.unsafe_to_raw_pos)
and freshen_possibly_enforced_ty env ety =
let (env, et_type) = freshen_ty env ety.et_type in
(env, { ety with et_type })
and freshen_tparams env variancel tyl =
match (variancel, tyl) with
| ([], []) -> (env, [])
| (variance :: variancel, ty :: tyl) ->
let (env, tyl) = freshen_tparams env variancel tyl in
let (env, ty) =
if Ast_defs.(equal_variance variance Invariant) then
(env, ty)
else
freshen_ty env ty
in
(env, ty :: tyl)
| _ -> (env, tyl)
let bind env var (ty : locl_ty) =
let old_env = env in
(* If there has been a use of this type variable that led to an "unknown type"
* error (e.g. method invocation), then record this in the reason info. We
* can make use of this for linters and code mods that suggest annotations *)
let ty =
map_reason ty ~f:(fun r ->
if Env.get_tyvar_eager_solve_fail env var then
Reason.Rsolve_fail (Reason.to_pos r)
else
r)
in
(* Remember the T::Tx involving this variable before we erase that from
* the env.
*)
let tconsts = Env.get_tyvar_type_consts env var in
(* Update the variance *)
let env = Env.update_variance_after_bind env var ty in
(* Unify the variable *)
let (ty, var_in_ty_err_opt) = Utils.err_if_var_in_ty_pure env var ty in
let env = Env.add env var ty in
(* Make sure we don't project from this variable if it is bound to
* nothing, as it will lead to type holes.
*)
let proj_ty_err_opt =
if TUtils.is_tyvar_error env ty then
None
else if TUtils.is_nothing env ty && not (SMap.is_empty tconsts) then
let (_, ((proj_pos, tconst_name), _)) = SMap.choose tconsts
and pos = Env.get_tyvar_pos env var in
Some
Typing_error.(
primary
@@ Primary.Unresolved_tyvar_projection { pos; tconst_name; proj_pos })
else
None
in
let ty_err_opt =
Option.merge var_in_ty_err_opt proj_ty_err_opt ~f:Typing_error.both
in
(Env.log_env_change "bind" old_env env, ty_err_opt)
(* Solve type variable var by assigning it to the union of its lower bounds.
* If freshen=true, first freshen the covariant and contravariant components of
* the bounds.
*)
let bind_to_lower_bound ~freshen env r var lower_bounds =
let old_env = env in
let (env, ty_err_opt) =
if ITySet.exists is_constraint_type lower_bounds then
(env, None)
else
let (env, lower_bounds) =
Utils.remove_tyvar_from_lower_bounds env var lower_bounds
in
let lower_bounds = Utils.filter_locl_types lower_bounds in
let (env, ty) = TUtils.union_list env r (TySet.elements lower_bounds) in
(* Freshen components of the types in the union wrt their variance.
* For example, if we have
* Cov<C>, Contra<D> <: v
* then we actually construct the union
* Cov<#1> | Contra<#2> with C <: #1 and #2 <: D
*)
let (env, freshen_ty_err, ty) =
if freshen then
let (env, newty) = freshen_inside_ty env ty in
(* In theory, the following subtype would only fail if the lower bound
* was already in conflict with another bound. However we don't
* add such conflicting bounds to avoid cascading errors, so in theory,
* the following subtype calls should not fail, and the error callback
* should not matter. *)
let on_error =
Some
(Typing_error.Reasons_callback.unify_error_at
@@ Env.get_tyvar_pos env var)
in
let (env, ty_err_opt) = TUtils.sub_type env ty newty on_error in
(env, ty_err_opt, newty)
else
(env, None, ty)
in
(* If any of the components of the union are type variables, then remove
* var from their upper bounds. Why? Because if we construct
* v1 , ... , vn , t <: var
* for type variables v1, ..., vn and non-type variable t
* then necessarily we must have var as an upper bound on each of vi
* so after binding var we end up with redundant bounds
* vi <: v1 | ... | vn | t
*)
let env =
TySet.fold
(fun ty env ->
let (env, ty) = Env.expand_type env ty in
match get_node ty with
| Tvar v -> Env.remove_tyvar_upper_bound env v var
| _ -> env)
lower_bounds
env
in
(* In autocomplete mode, we do not solve to nothing, as it makes a lot
* of checks in the autocompletion fail for bad reasons (especially
* around invariant generics. Leave them be to try to get leave more
* flexibility to type filers *)
let autocomplete_mode =
TypecheckerOptions.tco_autocomplete_mode env.genv.tcopt
in
if autocomplete_mode && TUtils.is_nothing env ty then
(env, freshen_ty_err)
else
(* Now actually make the assignment var := ty, and remove var from tvenv *)
let (env, bind_ty_err) = bind env var ty in
let ty_err_opt =
Option.merge freshen_ty_err bind_ty_err ~f:Typing_error.both
in
(env, ty_err_opt)
in
(Env.log_env_change "bind_to_lower_bound" old_env env, ty_err_opt)
let bind_to_upper_bound env r var upper_bounds =
let old_env = env in
let (env, ty_err_opt) =
if ITySet.exists is_constraint_type upper_bounds then
(env, None)
else
let (env, upper_bounds) =
Utils.remove_tyvar_from_upper_bounds env var upper_bounds
in
let upper_bounds = Utils.filter_locl_types upper_bounds in
let (env, ty) =
Inter.intersect_list env r (TySet.elements upper_bounds)
in
(* If ty is a variable (in future, if any of the types in the list are variables),
* then remove var from their lower bounds. Why? Because if we construct
* var <: v1 , ... , vn , t
* for type variables v1 , ... , vn and non-type variable t
* then necessarily we must have var as a lower bound on each of vi
* so after binding var we end up with redundant bounds
* v1 & ... & vn & t <: vi
*)
let (env, ty) = Env.expand_type env ty in
let env =
match get_node ty with
| Tvar v -> Env.remove_tyvar_lower_bound env v var
| _ -> env
in
bind env var ty
in
(Env.log_env_change "bind_to_upper_bound" old_env env, ty_err_opt)
(* Is the outer skeleton of the types the same (everything that isn't a nested type)?
* e.g. C<string> same as C<int>,
* dict<string,bool> same as dict<int,string>
* shape('a' => int) same as shape('a' => bool)
* but shape('a' => int) not same as shape('b' => int)
* shape(?'a' => int) not same as shape('a' => int)
*
* Expected invariant:
* if ty_equal_shallow ty1 ty2
* then freshen_inside_ty ty1 is identical to freshen_inside_ty ty2
* up to a choice of fresh type variables.
* (Or: there is some instantiation of the fresh type variables that
* makes freshen_inside_ty ty1 and freshen_inside_ty ty2 the same.)
*)
let ty_equal_shallow env ty1 ty2 =
let (env, ty1) = Env.expand_type env ty1 in
let (_env, ty2) = Env.expand_type env ty2 in
if TUtils.is_tyvar_error env ty1 && TUtils.is_tyvar_error env ty2 then
true
else
match (get_node ty1, get_node ty2) with
| (Tany _, Tany _)
| (Tnonnull, Tnonnull)
| (Tdynamic, Tdynamic)
| (Ttuple _, Ttuple _) ->
true
| (Tprim p1, Tprim p2) -> Aast_defs.equal_tprim p1 p2
| (Tclass (x_sub, exact_sub, _), Tclass (x_super, exact_super, _)) ->
String.equal (snd x_sub) (snd x_super)
&& equal_exact exact_sub exact_super
| (Tfun fty1, Tfun fty2) -> Int.equal fty1.ft_flags fty2.ft_flags
| ( Tshape { s_origin = _; s_unknown_value = shape_kind1; s_fields = fdm1 },
Tshape { s_origin = _; s_unknown_value = shape_kind2; s_fields = fdm2 }
) ->
Bool.equal
(TUtils.is_nothing env shape_kind1)
(TUtils.is_nothing env shape_kind2)
&& List.equal
(fun (k1, v1) (k2, v2) ->
TShapeField.equal k1 k2
&& Bool.equal v1.sft_optional v2.sft_optional)
(ShapeFieldMap.elements fdm1)
(ShapeFieldMap.elements fdm2)
| (Tnewtype (n1, _, _), Tnewtype (n2, _, _)) -> String.equal n1 n2
| (Tdependent (dep1, _), Tdependent (dep2, _)) ->
equal_dependent_type dep1 dep2
| _ -> false
let try_bind_to_equal_bound ~freshen env r var =
if Env.tyvar_is_solved env var then
(env, None)
else
let old_env = env in
let env = Utils.remove_tyvar_from_bounds env var in
let is_null ity =
match ity with
| LoclType ty -> begin
match get_node ty with
| Tprim Aast_defs.Tnull -> true
| _ -> false
end
| _ -> false
in
let lower_bounds = Env.get_tyvar_lower_bounds env var in
let has_null_lower_bound = ITySet.exists is_null lower_bounds in
let expand_all ~strip_supportdyn env tyset =
ITySet.fold
(fun ty (env, res, sd_res) ->
let (env, ty) = Env.expand_internal_type env ty in
match ty with
| LoclType ty when strip_supportdyn ->
let (_, env, stripped_ty) = TUtils.strip_supportdyn env ty in
let res = ITySet.add (LoclType stripped_ty) res in
let sd_res = ITySet.add (LoclType ty) sd_res in
let res =
if has_null_lower_bound then
ITySet.add (LoclType (MakeType.nullable r stripped_ty)) res
else
res
in
(env, res, sd_res)
| _ -> (env, ITySet.add ty res, sd_res))
tyset
(env, ITySet.empty, ITySet.empty)
in
let (env, lower_bounds, sd_lower_bounds) =
expand_all ~strip_supportdyn:true env lower_bounds
in
let (env, upper_bounds, _) =
expand_all
~strip_supportdyn:false
env
(Env.get_tyvar_upper_bounds env var)
in
let equal_bounds = ITySet.inter lower_bounds upper_bounds in
let equal_bounds =
if ITySet.is_empty equal_bounds then
ITySet.inter sd_lower_bounds upper_bounds
else
equal_bounds
in
let (env, ty_err_opt) =
match ITySet.choose_opt equal_bounds with
| Some (LoclType ty) -> bind env var ty
| Some (ConstraintType _)
| None ->
if not freshen then
(env, None)
else
(* Search for lower bound and upper bound pair that shallowly match.
* Then freshen the inner types on the matched type. We then want
* to make var equal to the matched type so we add the constraints
* var <: matched_ty and matched_ty <: var
* Finally we bind var to matched_ty
*)
let shallow_match =
ITySet.find_first_opt
(fun lower_bound ->
ITySet.exists
(fun upper_bound ->
match (lower_bound, upper_bound) with
| (LoclType lower_bound, LoclType upper_bound) ->
ty_equal_shallow env lower_bound upper_bound
| _ -> false)
upper_bounds)
lower_bounds
in
(match shallow_match with
| Some (LoclType shallow_match) ->
let (env, ty) = freshen_inside_ty env shallow_match in
let var_ty = mk (r, Tvar var) in
(* In theory, the following subtype would only fail if the shallow match
* we've found was already in conflict with another bound. However we don't
* add such conflicting bounds to avoid cascading errors, so in theory,
* the following subtype calls should not fail, and the error callback
* should not matter. *)
let on_error =
Some
(Typing_error.Reasons_callback.unify_error_at
@@ Env.get_tyvar_pos env var)
in
let (env, ty_sub_err_opt) =
TUtils.sub_type env ty var_ty on_error
in
let (env, ty_sup_err_opt) =
TUtils.sub_type env var_ty ty on_error
in
let (env, bind_err_opt) = bind env var ty in
let ty_err_opt =
Typing_error.multiple_opt
@@ List.filter_map
~f:Fn.id
[ty_sub_err_opt; ty_sup_err_opt; bind_err_opt]
in
(env, ty_err_opt)
| _ -> (env, None))
in
(Env.log_env_change "bind_to_equal_bound" old_env env, ty_err_opt)
(* Always solve a type variable.
We are here because we eagerly solve a type variable to see
whether certain operations are allowed on the type (e.g. a method call).
Therefore, we always force to the lower bounds (even contravariant variables),
because it produces a "more specific" type, which is more likely to support
the operation which we eagerly solved for in the first place.
During autocompletion, if the set of lower bounds is empty and the
variable appears contravariantly, try an upper bound.
*)
let rec always_solve_tyvar_down ~freshen env r var =
let autocomplete_mode =
TypecheckerOptions.tco_autocomplete_mode env.genv.tcopt
in
(* If there is a type that is both a lower and upper bound, force to that type *)
let (env, ty_err_opt1) = try_bind_to_equal_bound ~freshen env r var in
if Env.tyvar_is_solved env var then
(env, ty_err_opt1)
else
let r =
if Reason.is_none r then
Reason.Rwitness (Env.get_tyvar_pos env var)
else
r
in
let (env, ty_err_opt2) =
let (to_lower, bounds) =
let lower_bounds = Env.get_tyvar_lower_bounds env var in
if autocomplete_mode then
let upper_bounds = Env.get_tyvar_upper_bounds env var in
if
Env.get_tyvar_appears_contravariantly env var
&& ITySet.is_empty lower_bounds
&& not (ITySet.is_empty upper_bounds)
then
(false, upper_bounds)
else
(true, lower_bounds)
else
(true, lower_bounds)
in
(* We cannot do more on (<expr#1> as C) than on simply C,
* so replace expression-dependent types with their bound.
* This avoids solving to a type so specific that it ends
* up hurting completeness. *)
if to_lower then
let bounds =
ITySet.map
(function
| LoclType lty as ity ->
let (_env, lty) = Env.expand_type env lty in
(match get_node lty with
| Tdependent (_, bnd) -> LoclType bnd
| _ -> ity)
| ity -> ity)
bounds
in
bind_to_lower_bound ~freshen env r var bounds
else
bind_to_upper_bound env r var bounds
in
let (env, ety) = Env.expand_var env r var in
match get_node ety with
| Tvar var' when not (Ident.equal var var') ->
let (env, ty_err_opt3) = always_solve_tyvar_down ~freshen env r var in
let ty_err_opt =
Typing_error.multiple_opt
@@ List.filter_map ~f:Fn.id [ty_err_opt1; ty_err_opt2; ty_err_opt3]
in
(env, ty_err_opt)
| _ ->
let ty_err_opt =
Option.merge ty_err_opt1 ty_err_opt2 ~f:Typing_error.both
in
(env, ty_err_opt)
(* Use the variance information about a type variable to force a solution.
* (1) If the type variable is bounded by t1, ..., tn <: v and it appears only
* covariantly or not at all in the expression type then
* we can minimize it i.e. set v := t1 | ... | tn.
* (2) If the type variable is bounded by v <: t1, ..., tn and it appears only
* contravariantly in the expression type then we can maximize it. Ideally we
* would use an intersection v := t1 & ... & tn so for now we only solve
* if there is a single upper bound.
* (3) If the type variable is bounded by t1, ..., tm <: v <: u1, ..., un and
* u1 & ... & un == t1 | ... | tm then we can set v to either of these
* equivalent types. Because we don't have intersections, for now we check if
* there exist i, j such that uj <: ti, which implies ti == uj and allows
* us to set v := ti.
*)
let solve_tyvar_wrt_variance env r var =
if Env.tyvar_is_solved env var then
(env, None)
else
let r =
if Reason.is_none r then
Reason.Rwitness (Env.get_tyvar_pos env var)
else
r
in
let lower_bounds = Env.get_tyvar_lower_bounds env var
and upper_bounds = Env.get_tyvar_upper_bounds env var
and appears_covariantly = Env.get_tyvar_appears_covariantly env var
and appears_contravariantly =
Env.get_tyvar_appears_contravariantly env var
in
match (appears_covariantly, appears_contravariantly) with
| (true, false)
| (false, false) ->
(* As in Local Type Inference by Pierce & Turner, if type variable does
* not appear at all, or only appears covariantly, solve to lower bound.
* If there are no lower bounds, and we've got type constant projections
* on the type variable, then solve to the upper bound anyway, hoping that
* this resolves the projections.
*)
if
ITySet.is_empty lower_bounds
&& not (SMap.is_empty (Env.get_tyvar_type_consts env var))
then
bind_to_upper_bound env r var upper_bounds
else
bind_to_lower_bound ~freshen:false env r var lower_bounds
| (false, true) ->
(* As in Local Type Inference by Pierce & Turner, if type variable
* appears only contravariantly, solve to upper bound
*)
bind_to_upper_bound env r var upper_bounds
| (true, true) ->
(* Not ready to solve yet! *)
(env, None)
let solve_to_equal_bound_or_wrt_variance env r var =
Typing_log.(
log_with_level env "prop" ~level:2 (fun () ->
log_types
(Reason.to_pos r)
env
[
Log_head
( Printf.sprintf
"Typing_subtype.solve_to_equal_bound_or_wrt_variance #%d"
var,
[] );
]));
(* If there is a type that is both a lower and upper bound, force to that type *)
let (env, ty_err_opt1) = try_bind_to_equal_bound ~freshen:false env r var in
let (env, ty_err_opt2) = solve_tyvar_wrt_variance env r var in
let ty_err_opt = Option.merge ty_err_opt1 ty_err_opt2 ~f:Typing_error.both in
(env, ty_err_opt)
let solve_to_equal_bound_or_wrt_variance env r var =
let rec solve_until_concrete_ty env ty_errs v =
let (env, ty_errs) =
match solve_to_equal_bound_or_wrt_variance env r v with
| (env, Some ty_err) -> (env, ty_err :: ty_errs)
| (env, _) -> (env, ty_errs)
in
let (env, ety) = Env.expand_var env r v in
match get_node ety with
| Tvar v' when not (Ident.equal v v') ->
solve_until_concrete_ty env ty_errs v'
| _ ->
let ty_err_opt = Typing_error.multiple_opt ty_errs in
(env, ty_err_opt)
in
solve_until_concrete_ty env [] var
let always_solve_tyvar env r var =
let (env, ty_err_opt1) = solve_to_equal_bound_or_wrt_variance env r var in
let (env, ty_err_opt2) = always_solve_tyvar_down ~freshen:false env r var in
let ty_err_opt = Option.merge ty_err_opt1 ty_err_opt2 ~f:Typing_error.both in
(env, ty_err_opt)
(* Force solve all type variables in the environment *)
let solve_all_unsolved_tyvars env =
let old_env = env in
let (env, ty_errs) =
List.fold
(Env.get_all_tyvars env)
~init:(env, [])
~f:(fun (env, ty_errs) var ->
match always_solve_tyvar env Reason.Rnone var with
| (env, Some ty_err) -> (env, ty_err :: ty_errs)
| (env, _) -> (env, ty_errs))
in
let env = Env.log_env_change "solve_all_unsolved_tyvars" old_env env in
log_remaining_prop env;
let ty_err_opt = Typing_error.multiple_opt ty_errs in
(env, ty_err_opt)
(* Expand an already-solved type variable, and solve an unsolved type variable
* by binding it to the union of its lower bounds, with covariant and contravariant
* components of the type suitably "freshened". For example,
* vec<C> <: #1
* will be solved by
* #1 := vec<#2> where C <: #2
* The optional `default` parameter is used to solve a type variable
* if `widen_concrete_type` does not produce a result.
*)
let expand_type_and_solve
env ?default ?(freshen = true) ~description_of_expected p ty =
(* If we're checking an SDT method or function under dynamic assumptions,
* then attempt to solve to dynamic if we're left with a type variable *)
let default =
if Option.is_some default then
default
else if Tast.is_under_dynamic_assumptions env.Typing_env_types.checked then
Some (MakeType.dynamic (Reason.Rwitness p))
else
None
in
(* TODO: rather than writing to a ref cell from inside the `on_tyvar`
function, modify `simplify_unions` to return the accumulated result
from this function, if it is provided *)
let vars_solved_to_nothing = ref [] in
let ty_errs = ref [] in
let (env', ety) =
TUtils.simplify_unions env ty ~on_tyvar:(fun env r v ->
let (env, ty_err_opt) = always_solve_tyvar_down ~freshen env r v in
Option.iter ty_err_opt ~f:(fun ty_err -> ty_errs := ty_err :: !ty_errs);
let (env, ety) = Env.expand_var env r v in
(match get_node ety with
| Tunion [] ->
vars_solved_to_nothing := (r, v) :: !vars_solved_to_nothing
| _ -> ());
(env, ety))
in
let (env', ety) = Env.expand_type env' ety in
match (!vars_solved_to_nothing, get_node ety) with
| (_ :: _, Tunion []) -> begin
match default with
| Some default_ty ->
let res =
TUtils.sub_type env ety default_ty
@@ Some (Typing_error.Reasons_callback.unify_error_at p)
in
(res, default_ty)
| None ->
let env =
List.fold !vars_solved_to_nothing ~init:env ~f:(fun env (r, v) ->
match r with
| Reason.Rtype_variable_error _ -> env
| _ ->
let ty_err =
Typing_error.(
primary
@@ Primary.Unknown_type
{
expected = description_of_expected;
pos = p;
reason = lazy (Reason.to_string "It is unknown" r);
})
in
ty_errs := ty_err :: !ty_errs;
Env.set_tyvar_eager_solve_fail env v)
in
let ty_err_opt = Typing_error.multiple_opt !ty_errs in
let (env, ty) = Env.fresh_type_error env p in
((env, ty_err_opt), ty)
end
| _ ->
let ty_err_opt = Typing_error.multiple_opt !ty_errs in
((env', ty_err_opt), ety)
let expand_type_and_solve_eq env ty =
let ty_err_opts = ref [] in
let (env, ty) =
TUtils.simplify_unions env ty ~on_tyvar:(fun env r v ->
let (env, ty_err_opt) = try_bind_to_equal_bound ~freshen:true env r v in
ty_err_opts := ty_err_opt :: !ty_err_opts;
Env.expand_var env r v)
in
let (env, ty) = Env.expand_type env ty in
let ty_err_opt =
Typing_error.multiple_opt @@ List.filter_map ~f:Fn.id !ty_err_opts
in
((env, ty_err_opt), ty)
(* When applied to concrete types (typically classes), the `widen_concrete_type`
* function should produce the largest supertype that is valid for an operation.
* For example, if we have an expression $x->f for $x:v and exact C <: v, then
* we widen `exact C` to `B`, if `B` is the base class from which `C` inherits
* field f.
*
* The `widen` function extends this to nullables and abstract types.
* General unions have been dealt with already.
*)
let widen env widen_concrete_type ty =
let ty_nothing = MakeType.nothing Reason.none in
let rec widen env ty =
let (env, ty) = Env.expand_type env ty in
match deref ty with
| (r, Tunion tyl) -> widen_all env r tyl
| (r, Toption ty) -> widen_all env r [MakeType.null r; ty]
(* Don't widen the `this` type, because the field type changes up the hierarchy
* so we lose precision
*)
| (_, Tgeneric ("this", [])) -> ((env, None), ty)
(* For other abstract types, just widen to the bound, if possible *)
| (r, Tnewtype (name, [ty], _))
when String.equal name Naming_special_names.Classes.cSupportDyn ->
let ((env, err), ty) = widen env ty in
let (env, ty) = TUtils.make_supportdyn r env ty in
((env, err), ty)
| (_, Tdependent (_, ty))
| (_, Tnewtype (_, _, ty)) ->
widen env ty
| _ ->
let ((env, ty_err_opt), ty_opt) = widen_concrete_type env ty in
let ty = Option.value ~default:ty_nothing ty_opt in
((env, ty_err_opt), ty)
and widen_all env r tyl =
let (env, ty_errs, rev_tyl) =
List.fold tyl ~init:(env, [], []) ~f:(fun (env, ty_errs, tys) ty ->
match widen env ty with
| ((env, Some ty_err), ty) -> (env, ty_err :: ty_errs, ty :: tys)
| ((env, _), ty) -> (env, ty_errs, ty :: tys))
in
let (env, ty) = Typing_union.union_list env r @@ List.rev rev_tyl in
((env, Typing_error.union_opt ty_errs), ty)
in
widen env ty
let is_nothing env ty =
TUtils.is_sub_type_ignore_generic_params env ty (MakeType.nothing Reason.none)
(* Using the `widen_concrete_type` function to compute an upper bound,
* narrow the constraints on a type that are valid for an operation.
* For example, if we have an expression $x->f for $x:#1 and exact C <: #1, then
* we can add #1 <: B if C inherits the property f from base class B.
* Likewise, if we have an expression $x[3] for $x:#2 and vec<string> <: #2, then
* we can add #2 <: KeyedCollection<int,#3> because that is the largest type
* consistent with vec for which indexing is valid.
*
* Note that if further information arises on the type variable, then
* this approach is not complete. For example, we might have an unrelated
* exact A <: #1, for which A does not inherit from base class B.
*
* But in general, narrowing is a useful technique for delaying the complete
* solving of a constraint whilst supporting checking of operations such as
* member access and array indexing.
*
* The optional `default` parameter is used to solve a type variable
* if `widen_concrete_type` does not produce a result.
*)
let expand_type_and_narrow
env
?default
?(allow_nothing = false)
?(force_solve = true)
~description_of_expected
widen_concrete_type
p
ty =
(* If we're checking an SDT method or function under dynamic assumptions,
* then attempt to solve to dynamic if we're left with a type variable *)
let default =
if Option.is_some default then
default
else if Tast.is_under_dynamic_assumptions env.Typing_env_types.checked then
Some (MakeType.dynamic (Reason.Rwitness p))
else
None
in
let ((env, ty_err_opt), ty) =
let ((env, ty_err_opt1), ty) = expand_type_and_solve_eq env ty in
(* Deconstruct the type into union elements (if it's a union). For variables,
* take the lower bounds. If there are no variables, then we have a concrete
* type so just return expanded type
*)
let has_tyvar = ref false in
let seen_tyvars = ref ISet.empty in
(* Simplify unions in ty, but when we encounter a type variable in the process,
recursively replace it with the union of its lower bounds, effectively getting
rid of all unsolved type variables in the union. *)
let (env, concretized_ty) =
Typing_union.simplify_unions env ty ~on_tyvar:(fun env r v ->
has_tyvar := true;
if ISet.mem v !seen_tyvars then
(env, MakeType.nothing r)
else
let () = seen_tyvars := ISet.add v !seen_tyvars in
let lower_bounds =
TySet.elements
@@ Utils.filter_locl_types
@@ Env.get_tyvar_lower_bounds env v
in
Typing_union.union_list env r lower_bounds)
in
if not !has_tyvar then
((env, ty_err_opt1), ty)
else
let ((env, ty_err_opt2), widened_ty) =
widen env widen_concrete_type concretized_ty
in
let ((env, ty_err_opt3), ty) =
match
((not allow_nothing) && is_nothing env widened_ty, default, widened_ty)
with
| (true, None, _) ->
if force_solve then
expand_type_and_solve env ~description_of_expected p ty
else
((env, None), ty)
| (true, Some widened_ty, _)
| (false, _, widened_ty) ->
(* We really don't want to just guess `nothing` if none of the types can be widened *)
let res =
TUtils.sub_type env ty widened_ty
@@ Some (Typing_error.Reasons_callback.unify_error_at p)
in
(match res with
| (env, None) ->
let supportdyn = Typing_utils.is_supportdyn env ty in
let res2 =
if supportdyn then begin
TUtils.sub_type
env
widened_ty
(MakeType.supportdyn_mixed (Reason.Rwitness p))
@@ Some (Typing_error.Reasons_callback.unify_error_at p)
end else
(env, None)
in
(res2, widened_ty)
| _ ->
if force_solve then
expand_type_and_solve env ~description_of_expected p ty
else
((env, None), ty))
in
let ty_err_opt =
Typing_error.union_opt
@@ List.filter_map ~f:Fn.id [ty_err_opt1; ty_err_opt2; ty_err_opt3]
in
((env, ty_err_opt), ty)
in
let (env, ty) = Env.expand_type env ty in
((env, ty_err_opt), ty)
(* Solve type variables on top of stack, without losing completeness (by using
* their variance), and pop variables off the stack
*)
let close_tyvars_and_solve env =
let old_env = env in
let tyvars = Env.get_current_tyvars env in
let env = Env.close_tyvars env in
let (env, ty_errs) =
List.fold_left tyvars ~init:(env, []) ~f:(fun (env, ty_errs) tyvar ->
match solve_to_equal_bound_or_wrt_variance env Reason.Rnone tyvar with
| (env, Some ty_err) -> (env, ty_err :: ty_errs)
| (env, _) -> (env, ty_errs))
in
let ty_err_opt = Typing_error.multiple_opt ty_errs in
(Env.log_env_change "close_tyvars_and_solve" old_env env, ty_err_opt)
(* Currently, simplify_subtype doesn't look at bounds on type variables.
* Let's at least notice when these bounds imply an equality.
*)
let is_sub_type env ty1 ty2 =
let ((env, ty_err_opt1), ty1) = expand_type_and_solve_eq env ty1 in
let ((env, ty_err_opt2), ty2) = expand_type_and_solve_eq env ty2 in
let ty_err_opt = Option.merge ty_err_opt1 ty_err_opt2 ~f:Typing_error.both in
(TUtils.is_sub_type env ty1 ty2, ty_err_opt)
(**
* Strips away all Toption that we possible can in a type, expanding type
* variables along the way, turning ?T -> T. This exists to avoid ??T when
* we wrap a type in Toption while typechecking.
*)
let rec non_null env pos ty =
(* This is to mimic the previous behaviour of non_null on Tabstract, but
is hacky. We basically non_nullify the concrete supertypes of abstract
types. *)
let make_concrete_super_types_nonnull =
object
inherit Type_mapper.union_inter_type_mapper as super
method! on_tdependent env r dep cstr =
let ty = mk (r, Tdependent (dep, cstr)) in
match TUtils.get_concrete_supertypes ~abstract_enum:true env ty with
| (env, [ty'])
when TUtils.is_sub_type_for_union env (MakeType.null Reason.none) ty'
->
let (env, ty') = non_null env pos ty' in
(env, mk (r, Tdependent (dep, ty')))
| (env, _) -> super#on_tdependent env r dep cstr
method! on_tnewtype env r x tyl cstr =
let ty = mk (r, Tnewtype (x, tyl, cstr)) in
match TUtils.get_concrete_supertypes ~abstract_enum:true env ty with
| (env, [ty'])
when TUtils.is_sub_type_for_union env (MakeType.null Reason.none) ty'
->
let (env, ty') = non_null env pos ty' in
(env, mk (r, Tnewtype (x, tyl, ty')))
| (env, _) -> super#on_tnewtype env r x tyl cstr
end
in
let (env, ty) = make_concrete_super_types_nonnull#on_type env ty in
let r = Reason.Rwitness_from_decl pos in
Inter.intersect env ~r ty (MakeType.nonnull r)
let try_bind_to_equal_bound env v =
(* The reason we pass here doesn't matter since it's used only when `freshen` is true. *)
try_bind_to_equal_bound ~freshen:false env Reason.none v |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_solver.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 Env = Typing_env
open Typing_defs
open Typing_env_types
(* Non-side-effecting test for subtypes.
result = true implies ty1 <: ty2
result = false implies NOT ty1 <: ty2 OR we don't know
*)
val is_sub_type : env -> locl_ty -> locl_ty -> bool * Typing_error.t option
val non_null : env -> Pos_or_decl.t -> locl_ty -> env * locl_ty
(* Force solve all remaining unsolved type variables *)
val solve_all_unsolved_tyvars : env -> env * Typing_error.t option
val expand_type_and_solve :
env ->
?default:locl_ty ->
?freshen:bool ->
description_of_expected:string ->
Pos.t ->
locl_ty ->
(env * Typing_error.t option) * locl_ty
val expand_type_and_solve_eq :
env -> locl_ty -> (env * Typing_error.t option) * locl_ty
val expand_type_and_narrow :
env ->
?default:locl_ty ->
?allow_nothing:bool ->
?force_solve:bool ->
description_of_expected:string ->
(env -> locl_ty -> (env * Typing_error.t option) * locl_ty option) ->
Pos.t ->
locl_ty ->
(env * Typing_error.t option) * locl_ty
val solve_to_equal_bound_or_wrt_variance :
env -> Reason.t -> int -> env * Typing_error.t option
val close_tyvars_and_solve : env -> env * Typing_error.t option
val bind : env -> Ident.t -> locl_ty -> env * Typing_error.t option
val try_bind_to_equal_bound : env -> Ident.t -> env * Typing_error.t option |
OCaml | hhvm/hphp/hack/src/typing/typing_solver_utils.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Typing_defs
open Typing_env_types
module Env = Typing_env
module ITySet = Internal_type_set
module MakeType = Typing_make_type
module TUtils = Typing_utils
module TySet = Typing_set
let filter_locl_types types =
ITySet.fold
(fun ty types ->
match ty with
| LoclType ty -> TySet.add ty types
| _ -> types)
types
TySet.empty
(** If a type variable appear in one of its own lower bounds under a combination
of unions and intersections, it can be simplified away from this lower bound by
replacing any of its occurences with nothing.
E.g.
- if #1 has lower bound (#1 | A), the lower bound can be simplified to
(nothing | A) = A.
- if #1 has lower bound (#1 & A), the lower bound can be simplified to
(nothing & A) = nothing.
*)
let remove_tyvar_from_lower_bound env var lower_bound =
let is_nothing = ty_equal (MakeType.nothing Reason.none) in
let rec remove env ty =
let (env, ty) = Env.expand_type env ty in
match deref ty with
| (_, Tvar v) when Ident.equal v var -> (env, MakeType.nothing Reason.none)
| (r, Toption ty) ->
let (env, ty) = remove env ty in
(env, MakeType.nullable r ty)
| (r, Tunion tyl) ->
let (env, tyl) = List.fold_map tyl ~init:env ~f:remove in
let tyl = List.filter tyl ~f:(fun ty -> not (is_nothing ty)) in
(env, MakeType.union r tyl)
| (r, Tintersection tyl) ->
let (env, tyl) = List.fold_map tyl ~init:env ~f:remove in
let ty =
if List.exists tyl ~f:is_nothing then
MakeType.nothing r
else
MakeType.intersection r tyl
in
(env, ty)
| (r, Tnewtype (name, [tyarg], _))
when String.equal name Naming_special_names.Classes.cSupportDyn ->
let (env, ty) = remove env tyarg in
if is_nothing ty then
(env, MakeType.nothing r)
else
(env, MakeType.supportdyn r ty)
| _ -> (env, ty)
and remove_i env ty =
match ty with
| LoclType ty ->
let (env, ty) = remove env ty in
(env, LoclType ty)
| _ -> (env, ty)
in
remove_i env lower_bound
let remove_tyvar_from_lower_bounds env var lower_bounds =
let (env, lower_bounds) =
ITySet.fold
(fun lower_bound (env, acc) ->
let (env, lower_bound) =
remove_tyvar_from_lower_bound env var lower_bound
in
(env, ITySet.add lower_bound acc))
lower_bounds
(env, ITySet.empty)
in
let is_not_nothing ty = not @@ TUtils.is_nothing_i env ty in
let lower_bounds = ITySet.filter is_not_nothing lower_bounds in
(env, lower_bounds)
(** If a type variable appear in one of its own upper bounds under a combination
of unions and intersections, it can be simplified away from this upper bound by
replacing any of its occurences with mixed.
E.g.
- if #1 has upper bound (#1 & A), the upper bound can be simplified to
(mixed & A) = A.
- if #1 has upper bound (#1 | A), the upper bound can be simplified to
(mixed | A) = mixed
*)
let remove_tyvar_from_upper_bound env var upper_bound =
let is_mixed ty =
ty_equal ty (MakeType.mixed Reason.none)
|| ty_equal ty (MakeType.intersection Reason.none [])
in
let rec remove env ty =
let (env, ty) = Env.expand_type env ty in
match deref ty with
| (_, Tvar v) when Ident.equal v var -> (env, MakeType.mixed Reason.none)
| (r, Toption ty) ->
let (env, ty) = remove env ty in
(env, MakeType.nullable r ty)
| (r, Tunion tyl) ->
let (env, tyl) = List.fold_map tyl ~init:env ~f:remove in
let ty =
if List.exists tyl ~f:is_mixed then
MakeType.mixed r
else
MakeType.union r tyl
in
(env, ty)
| (r, Tnewtype (name, [tyarg], _))
when String.equal name Naming_special_names.Classes.cSupportDyn ->
let (env, ty) = remove env tyarg in
(env, MakeType.supportdyn r ty)
| (r, Tintersection tyl) ->
let (env, tyl) = List.fold_map tyl ~init:env ~f:remove in
let tyl = List.filter tyl ~f:(fun ty -> not (is_mixed ty)) in
(env, MakeType.intersection r tyl)
| _ -> (env, ty)
and remove_i env ty =
match ty with
| LoclType ty ->
let (env, ty) = remove env ty in
(env, LoclType ty)
| _ -> (env, ty)
in
remove_i env upper_bound
let remove_tyvar_from_upper_bounds env var upper_bounds =
let (env, upper_bounds) =
ITySet.fold
(fun upper_bound (env, acc) ->
let (env, upper_bound) =
remove_tyvar_from_upper_bound env var upper_bound
in
(env, ITySet.add upper_bound acc))
upper_bounds
(env, ITySet.empty)
in
let is_not_mixed ty = not @@ TUtils.is_mixed_i env ty in
let upper_bounds = ITySet.filter is_not_mixed upper_bounds in
(env, upper_bounds)
(** Remove a type variable from its upper and lower bounds. More precisely,
if a type variable appears in one of its bounds under any combination of unions
and intersections, it can be simplified away from the bound.
For example,
- if #1 has lower bound (#1 | A), the lower bound can be simplified to A
- if #1 has upper bound (#1 | B), the upper bound can be simplified to mixed
and dually for intersections.
*)
let remove_tyvar_from_bounds env var =
Env.log_env_change "remove_tyvar_from_bounds" ~level:3 env
@@
let lower_bounds = Env.get_tyvar_lower_bounds env var in
let upper_bounds = Env.get_tyvar_upper_bounds env var in
let (env, lower_bounds) =
remove_tyvar_from_lower_bounds env var lower_bounds
in
let (env, upper_bounds) =
remove_tyvar_from_upper_bounds env var upper_bounds
in
let env = Env.set_tyvar_lower_bounds env var lower_bounds in
let env = Env.set_tyvar_upper_bounds env var upper_bounds in
env
let var_occurs_in_ty env var ty =
let finder =
object (this)
inherit [env * bool] Type_visitor.locl_type_visitor as super
method! on_tvar (env, occurs) r v =
let (env, ety) = Env.expand_var env r v in
match get_node ety with
| Tvar v -> (env, Ident.equal v var)
| _ -> this#on_type (env, occurs) ety
method! on_type (env, occurs) ty =
if occurs then
(env, occurs)
else
super#on_type (env, occurs) ty
end
in
finder#on_type (env, false) ty
let err_if_var_in_ty_pure env var ty =
let (env, var_occurs_in_ty) = var_occurs_in_ty env var ty in
if var_occurs_in_ty then
let ty_err =
Typing_error.(
primary
@@ Primary.Unification_cycle
{
pos = Env.get_tyvar_pos env var;
ty_name =
lazy
Typing_print.(
with_blank_tyvars (fun () -> full_rec env var ty));
})
in
(MakeType.union (get_reason ty) [], Some ty_err)
else
(ty, None)
let err_if_var_in_ty env var ty =
match err_if_var_in_ty_pure env var ty with
| (ty, Some err) ->
Typing_error_utils.add_typing_error ~env err;
ty
| (ty, _) -> ty |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_solver_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.
*
*)
open Typing_defs
open Typing_env_types
val filter_locl_types : Internal_type_set.t -> Typing_set.t
val remove_tyvar_from_lower_bound :
env -> Ident.t -> internal_type -> env * internal_type
val remove_tyvar_from_lower_bounds :
env -> Ident.t -> Internal_type_set.t -> env * Internal_type_set.t
val remove_tyvar_from_upper_bound :
env -> Ident.t -> internal_type -> env * internal_type
val remove_tyvar_from_upper_bounds :
env -> Ident.t -> Internal_type_set.t -> env * Internal_type_set.t
val remove_tyvar_from_bounds : env -> Ident.t -> env
val err_if_var_in_ty : env -> Ident.t -> locl_ty -> locl_ty
val err_if_var_in_ty_pure :
env -> Ident.t -> locl_ty -> locl_ty * Typing_error.t option |
OCaml | hhvm/hphp/hack/src/typing/typing_special_fun.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 SN = Naming_special_names
module MakeType = Typing_make_type
let update_param : decl_fun_param -> decl_ty -> decl_fun_param =
(fun param ty -> { param with fp_type = { param.fp_type with et_type = ty } })
let wrap_with_like_type (pessimise : bool) (ty : decl_ty) =
if pessimise then
MakeType.like (Reason.Renforceable (get_pos ty)) ty
else
ty
(** Transform the special function `idx` according to the number
of arguments actually passed to the function
The idx function has two signatures, depending on number of arguments
actually passed:
idx<Tk as arraykey, Tv>(?KeyedContainer<Tk, Tv> $collection, ?Tk $index): ?Tv
idx<Tk as arraykey, Tv>(?KeyedContainer<Tk, Tv> $collection, ?Tk $index, Tv $default): Tv
In the hhi file, it has signature
function idx<Tk as arraykey, Tv>
(?KeyedContainer<Tk, Tv> $collection, ?Tk $index, $default = null)
so this needs to be munged into the above. *)
let transform_idx_fun_ty :
pessimise:bool -> decl_fun_type -> int -> decl_fun_type =
fun ~pessimise fty nargs ->
let (param1, param2, param3) =
match fty.ft_params with
| [param1; param2; param3] -> (param1, param2, param3)
| _ -> failwith "Expected 3 parameters for idx in hhi file"
in
let rret = get_reason fty.ft_ret.et_type in
let (params, ret) =
match nargs with
| 2 ->
(* Return type should be ?Tv *)
let ret = MakeType.nullable rret (MakeType.generic rret "Tv") in
let ret = wrap_with_like_type pessimise ret in
([param1; param2], ret)
| 3 ->
(* Third parameter should have type Tv *)
let param3 =
let r3 = get_reason param1.fp_type.et_type in
update_param param3 (MakeType.generic r3 "Tv")
in
(* Return type should be Tv *)
let ret = MakeType.generic rret "Tv" in
let ret = wrap_with_like_type pessimise ret in
([param1; param2; param3], ret)
(* Shouldn't happen! *)
| _ -> (fty.ft_params, fty.ft_ret.et_type)
in
{ fty with ft_params = params; ft_ret = { fty.ft_ret with et_type = ret } }
(** Transform the types of special functions whose type is not denotable in hack, e.g. idx *)
let transform_special_fun_ty :
pessimise:bool -> decl_fun_type -> Aast.sid -> int -> decl_fun_type =
fun ~pessimise fty id nargs ->
if String.equal (snd id) SN.FB.idx || String.equal (snd id) SN.Readonly.idx
then
transform_idx_fun_ty ~pessimise fty nargs
else
fty |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_special_fun.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.
*
*)
(** Transform the types of special functions whose type is not denotable in hack, e.g. idx *)
val transform_special_fun_ty :
pessimise:bool ->
Typing_defs.decl_fun_type ->
Aast.sid ->
int ->
Typing_defs.decl_fun_type |
OCaml | hhvm/hphp/hack/src/typing/typing_structure.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 MakeType = Typing_make_type
module Phase = Typing_phase
module Reason = Typing_reason
module SN = Naming_special_names
module Subst = Decl_subst
module TUtils = Typing_utils
(** This module implements the typing for type_structure. *)
let make_ts : Typing_env_types.env -> locl_ty -> Typing_env_types.env * locl_ty
=
fun env ty ->
let r = get_reason ty in
match Env.get_typedef env SN.FB.cTypeStructure with
| Some { td_tparams; _ } ->
(* Typedef parameters can not have constraints *)
let params =
List.map
~f:
begin
fun { tp_name = (p, x); _ } ->
mk (Reason.Rwitness_from_decl p, Tgeneric (x, []))
end
td_tparams
in
let ts =
mk
(Reason.Rnone, Tapply ((Pos_or_decl.none, SN.FB.cTypeStructure), params))
in
let ety_env =
{
(empty_expand_env_with_on_error
(Typing_error.Reasons_callback.invalid_type_hint
(Reason.to_pos r |> Pos_or_decl.unsafe_to_raw_pos)))
with
substs = Subst.make_locl td_tparams [ty];
}
in
let ((env, ty_err), ty) = Phase.localize ~ety_env env ts in
let ty = with_reason ty r in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err;
(env, ty)
| _ ->
(* Should not hit this because TypeStructure should always be defined *)
(env, MakeType.dynamic r)
let rec transform_shapemap ?(nullable = false) env pos ty shape =
let ((env, ty_err_opt), ty) =
Typing_solver.expand_type_and_solve
~description_of_expected:"a shape"
env
pos
ty
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
(* If there are Tanys, be conservative and don't try to represent the
* type more precisely
*)
if TUtils.HasTany.check ty then
(env, shape)
else
let (env, ty) = Env.expand_type env ty in
match get_node ty with
| Toption ty -> transform_shapemap ~nullable:true env pos ty shape
| _ ->
let base_type = TUtils.get_base_type env ty in
(* If the abstract type is unbounded we do not specialize at all *)
let is_unbound =
match get_node base_type with
| Tgeneric _ -> true
| _ -> false
in
let is_generic =
match get_node ty with
| Tgeneric _ -> true
| _ -> false
in
let (supportdyn, env, ty) = TUtils.strip_supportdyn env ty in
let base_type = TUtils.get_base_type ~expand_supportdyn:false env ty in
let (supportdyn_bound, env, base_type) =
TUtils.strip_supportdyn env base_type
in
let base_type =
if is_unbound then
MakeType.mixed (get_reason base_type)
else
base_type
in
(* Does this type contain only enum or object instances?
* These are the types that can be represented using classname
*)
let rec is_enum_or_classish ty =
match get_node ty with
| Tnewtype (cid, _, _) when Env.is_enum env cid -> true
| Tintersection tys -> List.exists tys ~f:is_enum_or_classish
| Tunion tys -> List.for_all tys ~f:is_enum_or_classish
| Tclass ((_, x), _, _)
when not
(String.equal x SN.Collections.cVec
|| String.equal x SN.Collections.cDict
|| String.equal x SN.Collections.cKeyset) ->
true
| Tgeneric _ ->
let (_env, tyl) =
TUtils.get_concrete_supertypes
~expand_supportdyn:true
~abstract_enum:false
env
ty
in
List.exists tyl ~f:is_enum_or_classish
| _ -> false
in
let supportdyn = supportdyn || supportdyn_bound in
let transform_shape_field field { sft_ty; _ } (env, shape) =
(* Accumulates the provided type for this iteration of the fold, adding
it to the accumulation ShapeMap for the current field. Since the
field must have been explicitly set, we set sft_optional to true. *)
let acc_field_with_type sft_ty =
TShapeMap.add field { sft_optional = false; sft_ty } shape
in
let (env, sft_ty) = Env.expand_type env sft_ty in
match (field, deref sft_ty, deref base_type) with
| (TSFlit_str (_, "nullable"), (_, Toption fty), _) when nullable ->
(env, acc_field_with_type fty)
| (TSFlit_str (_, "nullable"), (_, Toption fty), (_, Toption _)) ->
(env, acc_field_with_type fty)
| (TSFlit_str (_, "classname"), (_, Toption fty), _)
when is_enum_or_classish ty ->
(env, acc_field_with_type fty)
| (TSFlit_str (_, "elem_types"), _, (r, Ttuple tyl)) ->
let (env, tyl) = List.map_env env tyl ~f:make_ts in
(env, acc_field_with_type (mk (r, Ttuple tyl)))
| (TSFlit_str (_, "param_types"), _, (r, Tfun funty)) ->
let tyl = List.map funty.ft_params ~f:(fun x -> x.fp_type.et_type) in
let (env, tyl) = List.map_env env tyl ~f:make_ts in
(env, acc_field_with_type (mk (r, Ttuple tyl)))
| (TSFlit_str (_, "return_type"), _, (r, Tfun funty)) ->
let (env, ty) = make_ts env funty.ft_ret.et_type in
(env, acc_field_with_type (mk (r, Ttuple [ty])))
| ( TSFlit_str (_, "fields"),
_,
( r,
Tshape
{
s_origin = _;
s_unknown_value = shape_kind;
s_fields = fields;
} ) ) ->
let (env, fields) = ShapeFieldMap.map_env make_ts env fields in
let ty =
mk
( r,
Tshape
{
s_origin = Missing_origin;
s_unknown_value = shape_kind;
s_fields = fields;
} )
in
let ty =
if supportdyn then
MakeType.supportdyn r ty
else
ty
in
(env, acc_field_with_type ty)
(* For generics we cannot specialize the generic_types field. Consider:
*
* class C<T> {}
* class D extends C<int> {}
*
* function test<T as C<int>>(TypeStructure<T> $ts): TypeStructure<int> {
* return $ts['generic_types'][0];
* }
*
* For test(TypeStructure<D>) there will not be a generic_types field
*)
| (TSFlit_str (_, "generic_types"), _, _) when is_generic ->
(env, acc_field_with_type sft_ty)
| (TSFlit_str (_, "generic_types"), _, (r, Tclass (_, _, tyl)))
when List.length tyl > 0 ->
let (env, tyl) = List.map_env env tyl ~f:make_ts in
(env, acc_field_with_type (mk (r, Ttuple tyl)))
| (TSFlit_str (_, ("kind" | "name" | "alias")), _, _) ->
(env, acc_field_with_type sft_ty)
| (_, _, _) -> (env, shape)
in
TShapeMap.fold transform_shape_field shape (env, TShapeMap.empty) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_structure.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 transform_shapemap :
?nullable:bool ->
Typing_env_types.env ->
Pos.t ->
Typing_defs.locl_ty ->
Typing_defs.locl_phase Typing_defs.shape_field_type Typing_defs.TShapeMap.t ->
Typing_env_types.env
* Typing_defs.locl_phase Typing_defs.shape_field_type Typing_defs.TShapeMap.t |
OCaml | hhvm/hphp/hack/src/typing/typing_substring.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 Typing_env_types
module Reason = Typing_reason
module Env = Typing_env
module MakeType = Typing_make_type
module SN = Naming_special_names
let sub_string_err (p : Pos.t) (env : env) (ty : locl_ty) :
env * (locl_ty * locl_ty) option =
(* Under constraint-based inference, we implement sub_string as a subtype test.
* All the cases in the legacy implementation just fall out from subtyping rules.
* We test against ?(arraykey | bool | float | resource | dynamic |
* HH\FormatString<T>).
*)
let r = Reason.Rwitness p in
let (env, formatter_tyvar) = Env.fresh_type_invariant env p in
let tyl =
[
MakeType.arraykey r;
MakeType.bool r;
MakeType.float r;
MakeType.resource r;
MakeType.dynamic r;
MakeType.hh_formatstring r formatter_tyvar;
]
in
let stringish = MakeType.class_type r SN.Classes.cStringish [] in
let stringlike = MakeType.nullable r (MakeType.union r tyl) in
let (is_sub_stringish, e1) = Typing_solver.is_sub_type env ty stringish in
let err =
Typing_error.(
primary
@@
if is_sub_stringish then
Primary.Object_string_deprecated p
else
Primary.Invalid_substring
{ pos = p; ty_name = lazy (Typing_print.error env ty) })
in
let (env, e2) =
Typing_subtype.sub_type_or_fail env ty stringlike @@ Some err
in
let ty_mismatch = Option.map e2 ~f:(Fn.const (ty, stringlike)) 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, ty_mismatch)
let sub_string (p : Pos.t) (env : env) (ty : locl_ty) : env =
fst @@ sub_string_err p env ty |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_substring.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 sub_string_err :
Pos.t ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_env_types.env * (Typing_defs.locl_ty * Typing_defs.locl_ty) option
val sub_string :
Pos.t -> Typing_env_types.env -> Typing_defs.locl_ty -> Typing_env_types.env |
OCaml | hhvm/hphp/hack/src/typing/typing_subtype.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 Utils
open Typing_defs
open Typing_env_types
open Typing_logic_helpers
module Reason = Typing_reason
module Env = Typing_env
module Inter = Typing_intersection
module TUtils = Typing_utils
module SN = Naming_special_names
module Phase = Typing_phase
module TL = Typing_logic
module Cls = Decl_provider.Class
module ITySet = Internal_type_set
module MakeType = Typing_make_type
module Nast = Aast
(* We maintain a "visited" set for subtype goals. We do this only
* for goals of the form T <: t or t <: T where T is a generic parameter,
* as this is the more common case.
* T83096774: work out how to do this *efficiently* for all subtype goals.
*
* Here's a non-trivial example (assuming a contravariant type Contra).
* Under assumption T <: Contra<Contra<T>> show T <: Contra<T>.
* This leads to cycle of implications
* T <: Contra<T> =>
* Contra<Contra<T>> <: Contra<T> =>
* T <: Contra<T>
* at which point we are back at the original goal.
*
* Note that it's not enough to just keep a set of visited generic parameters,
* else we would reject good code e.g. consider
* class C extends B implements Contra<B>
* Now under assumption T <: C show T <: Contra<T>
* This leads to cycle of implications
* T <: Contra<T> =>
* C <: Contra<T> =>
* Contra<B> <: Contra<T> =>
* T <: B => // DO NOT REJECT here just because we've visited T before!
* C <: B => done.
*
* We represent the visited set as a map from generic parameters
* to pairs of sets of types, such that an entry T := ({t1,...,tm},{u1,...,un})
* represents a set of goals
* T <: u1, ..., t <: un , t1 <: T, ..., tn <: T
*)
module VisitedGoals = struct
type t = (ITySet.t * ITySet.t) SMap.t
let empty : t = SMap.empty
(* Return None if (name <: ty) is already present, otherwise return Some v'
* where v' has the pair added
*)
let try_add_visited_generic_sub v name ty =
match SMap.find_opt name v with
| None -> Some (SMap.add name (ITySet.empty, ITySet.singleton ty) v)
| Some (lower, upper) ->
if ITySet.mem ty upper then
None
else
Some (SMap.add name (lower, ITySet.add ty upper) v)
(* Return None if (ty <: name) is already present, otherwise return Some v'
* where v' has the pair added
*)
let try_add_visited_generic_super v ty name =
match SMap.find_opt name v with
| None -> Some (SMap.add name (ITySet.singleton ty, ITySet.empty) v)
| Some (lower, upper) ->
if ITySet.mem ty lower then
None
else
Some (SMap.add name (ITySet.add ty lower, upper) v)
end
type subtype_env = {
require_soundness: bool;
(** If set, requires the simplification of subtype constraints to be sound,
meaning that the simplified constraint must imply the original one. *)
require_completeness: bool;
(** If set, requires the simplification of subtype constraints to be complete,
meaning that the original constraint must imply the simplified one.
If set, we also finish as soon as we see a goal of the form T <: t or
t <: T for generic parameter T *)
visited: VisitedGoals.t;
(** If above is not set, maintain a visited goal set *)
no_top_bottom: bool;
coerce: TL.coercion_direction option;
(** Coerce indicates whether subtyping should allow
coercion to or from dynamic. For coercion to dynamic, types that implement
dynamic are considered sub-types of dynamic. For coercion from dynamic,
dynamic is treated as a sub-type of all types. *)
on_error: Typing_error.Reasons_callback.t option;
tparam_constraints: (Pos_or_decl.t * Typing_defs.pos_id) list;
(** This is used for better error reporting to flag violated
constraints on type parameters, if any. *)
is_coeffect: bool;
(** A flag which, if set, indicates that coeffects are being subtyped.
Note: this is a short-term solution to provide coeffects.pretty-printing of
`locl_ty`s that represent coeffects, since there is no good way to
tell apart coeffects from regular types *)
log_level: int;
(** Which level the recursive calls to simplify_subtype should be logged at *)
}
let coercing_from_dynamic se =
match se.coerce with
| Some TL.CoerceFromDynamic -> true
| _ -> false
let coercing_to_dynamic se =
match se.coerce with
| Some TL.CoerceToDynamic -> true
| _ -> false
let make_subtype_env
?(require_soundness = true)
?(require_completeness = false)
?(no_top_bottom = false)
?(coerce = None)
?(is_coeffect = false)
~(log_level : int)
on_error =
{
require_soundness;
require_completeness;
visited = VisitedGoals.empty;
no_top_bottom;
coerce;
is_coeffect;
on_error;
tparam_constraints = [];
log_level;
}
let possibly_add_violated_constraint subtype_env ~r_sub ~r_super =
{
subtype_env with
tparam_constraints =
(match (r_super, r_sub) with
| (Reason.Rcstr_on_generics (p, tparam), _)
| (_, Reason.Rcstr_on_generics (p, tparam)) ->
(match subtype_env.tparam_constraints with
| (p_prev, tparam_prev) :: _
when Pos_or_decl.equal p p_prev
&& Typing_defs.equal_pos_id tparam tparam_prev ->
(* since tparam_constraints is used for error reporting, it's
* unnecessary to add duplicates. *)
subtype_env.tparam_constraints
| _ -> (p, tparam) :: subtype_env.tparam_constraints)
| _ -> subtype_env.tparam_constraints);
}
(* Given a pair of types `ty_sub` and `ty_super` attempt to apply simplifications
* and add to the accumulated constraints in `constraints` any necessary and
* sufficient [(t1,ck1,u1);...;(tn,ckn,un)] such that
* ty_sub <: ty_super iff t1 ck1 u1, ..., tn ckn un
* where ck is `as` or `=`. Essentially we are making solution-preserving
* simplifications to the subtype assertion, for now, also generating equalities
* as well as subtype assertions, for backwards compatibility with use of
* unification.
*
* If `constraints = []` is returned then the subtype assertion is valid.
*
* If the subtype assertion is unsatisfiable then return `failed = Some f`
* where `f` is a `unit-> unit` function that records an error message.
* (Sometimes we don't want to call this function e.g. when just checking if
* a subtype holds)
*
* Elide singleton unions, treat invariant generics as both-ways
* subtypes, and actually chase hierarchy for extends and implements.
*
* Annoyingly, we need to pass env back too, because Typing_phase.localize
* expands type constants. (TODO: work out a better way of handling this)
*
* Special cases:
* If assertion is valid (e.g. string <: arraykey) then
* result can be the empty list (i.e. nothing is added to the result)
* If assertion is unsatisfiable (e.g. arraykey <: string) then
* we record this in the failed field of the result.
*)
let log_subtype_i ~level ~this_ty ~function_name env ty_sub ty_super =
Typing_log.(
log_with_level env "sub" ~level (fun () ->
let types =
[Log_type_i ("ty_sub", ty_sub); Log_type_i ("ty_super", ty_super)]
in
let types =
Option.value_map this_ty ~default:types ~f:(fun ty ->
Log_type ("this_ty", ty) :: types)
in
if
level >= 3
|| not
(TUtils.is_capability_i ty_sub || TUtils.is_capability_i ty_super)
then
log_types
(Reason.to_pos (reason ty_sub))
env
[Log_head (function_name, types)]
else
()))
let log_subtype ~this_ty ~function_name env ty_sub ty_super =
log_subtype_i
~this_ty
~function_name
env
(LoclType ty_sub)
(LoclType ty_super)
let is_final_and_invariant env id =
let class_def = Env.get_class env id in
match class_def with
| Some class_ty -> TUtils.class_is_final_and_invariant class_ty
| None -> false
let is_tprim_disjoint tp1 tp2 =
let one_side tp1 tp2 =
Aast_defs.(
match (tp1, tp2) with
| (Tnum, Tint)
| (Tnum, Tfloat)
| (Tarraykey, Tint)
| (Tarraykey, Tstring)
| (Tarraykey, Tnum) ->
false
| ( _,
( Tnum | Tint | Tvoid | Tbool | Tarraykey | Tfloat | Tstring | Tnull
| Tresource | Tnoreturn ) ) ->
true)
in
(not (Aast_defs.equal_tprim tp1 tp2)) && one_side tp1 tp2 && one_side tp2 tp1
(* Two classes c1 and c2 are disjoint iff there exists no c3 such that
c3 <: c1 and c3 <: c2. *)
let is_class_disjoint env c1 c2 =
let is_interface_or_trait c_def =
Ast_defs.(
match Cls.kind c_def with
| Cinterface
| Ctrait ->
true
| Cclass _
| Cenum_class _
| Cenum ->
false)
in
if String.equal c1 c2 then
false
else
match (Env.get_class env c1, Env.get_class env c2) with
| (Some c1_def, Some c2_def) ->
if Cls.final c1_def then
(* if c1 is final, then c3 would have to be equal to c1 *)
not (Cls.has_ancestor c1_def c2)
else if Cls.final c2_def then
(* if c2 is final, then c3 would have to be equal to c2 *)
not (Cls.has_ancestor c2_def c1)
else
(* Given two non-final classes, if either is an interface or trait, then
there could be a c3, and so we consider the classes to not be disjoint.
However, if they are both classes, then c3 must be either c1 or c2 since
we don't have multiple inheritance. *)
(not (is_interface_or_trait c1_def))
&& (not (is_interface_or_trait c2_def))
&& (not (Cls.has_ancestor c2_def c1))
&& not (Cls.has_ancestor c1_def c2)
| _ ->
(* This is a decl error that should have already been caught *)
false
(** [negate_ak_null_type env r ty] performs type negation similar to
TUtils.negate_type, but restricted to arraykey and null (and their
negations). *)
let negate_ak_null_type env r ty =
let (env, ty) = Env.expand_type env ty in
let neg_ty =
match get_node ty with
| Tprim Aast.Tnull -> Some (MakeType.nonnull r)
| Tprim Aast.Tarraykey -> Some (MakeType.neg r (Neg_prim Aast.Tarraykey))
| Tneg (Neg_prim Aast.Tarraykey) ->
Some (MakeType.prim_type r Aast.Tarraykey)
| Tnonnull -> Some (MakeType.null r)
| _ -> None
in
(env, neg_ty)
let find_type_with_exact_negation env tyl =
let rec find env tyl acc_tyl =
match tyl with
| [] -> (env, None, acc_tyl)
| ty :: tyl' ->
let (env, neg_ty) = negate_ak_null_type env (get_reason ty) ty in
(match neg_ty with
| None -> find env tyl' (ty :: acc_tyl)
| Some neg_ty -> (env, Some neg_ty, tyl' @ acc_tyl))
in
find env tyl []
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 : env -> internal_type -> string =
(* 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
| LoclType ty -> Lazy.force @@ Typing_coeffects.pretty env ty
| ty -> describe_ty_default env ty
let rec describe_ty_super ~is_coeffect env ty =
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) = Env.expand_type env ty in
(match get_node ty with
| Tvar v ->
let upper_bounds = ITySet.elements (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 (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: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 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:TUtils.is_nothing lo)
(bound_desc ~prefix:" as " ~is_trivial:TUtils.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 simplify_subtype_by_physical_equality env ty_sub ty_super simplify_subtype =
match (ty_sub, ty_super) with
| (LoclType ty1, LoclType ty2) when phys_equal ty1 ty2 -> (env, TL.valid)
| _ -> simplify_subtype ()
(* If it's clear from the syntax of the type that null isn't in ty, return true.
*)
let rec null_not_subtype ty =
match get_node ty with
| Tprim (Aast_defs.Tnull | Aast_defs.Tvoid)
| Tgeneric _
| Tdynamic
| Tany _
| Toption _
| Tvar _
| Taccess _
| Tunapplied_alias _
| Tneg _
| Tintersection _ ->
false
| Tunion tys -> List.for_all tys ~f:null_not_subtype
| Tclass _
| Tprim _
| Tnonnull
| Tfun _
| Ttuple _
| Tshape _
| Tvec_or_dict _ ->
true
| Tdependent (_, bound)
| Tnewtype (_, _, bound) ->
null_not_subtype bound
let get_tyvar_opt t =
match t with
| LoclType lt -> begin
match get_node lt with
| Tvar var -> Some var
| _ -> None
end
| _ -> None
(* build the interface corresponding to the can_traverse constraint *)
let can_traverse_to_iface ct =
match (ct.ct_key, ct.ct_is_await) with
| (None, false) -> MakeType.traversable ct.ct_reason ct.ct_val
| (None, true) -> MakeType.async_iterator ct.ct_reason ct.ct_val
| (Some ct_key, false) ->
MakeType.keyed_traversable ct.ct_reason ct_key ct.ct_val
| (Some ct_key, true) ->
MakeType.async_keyed_iterator ct.ct_reason ct_key ct.ct_val
let liken ~super_like env ty =
if super_like then
TUtils.make_like env ty
else
ty
(* At present, we don't distinguish between coercions (<:D) and subtyping (<:) in the
* type variable and type parameter environments. When closing the environment we use subtyping (<:).
* To mitigate against this, when adding a dynamic upper bound wrt coercion,
* transform it first into supportdyn<mixed>,
* as t <:D dynamic iff t <: supportdyn<mixed>.
*)
let transform_dynamic_upper_bound ~coerce env ty =
if Tast.is_under_dynamic_assumptions env.checked then
ty
else
match (coerce, get_node ty) with
| (Some TL.CoerceToDynamic, Tdynamic) ->
let r = get_reason ty in
MakeType.supportdyn_mixed ~mixed_reason:r r
| (Some TL.CoerceToDynamic, _) -> ty
| _ -> ty
let mk_issubtype_prop ~sub_supportdyn ~coerce env ty1 ty2 =
let (env, ty1) =
match sub_supportdyn with
| None -> (env, ty1)
| Some r ->
let (env, ty1) = Env.expand_internal_type env ty1 in
( env,
(match ty1 with
| LoclType ty ->
if is_tyvar ty then
ty1
else
let ty = MakeType.supportdyn r ty in
LoclType ty
| _ -> ty1) )
in
( env,
match ty2 with
| LoclType ty2 ->
let (coerce, ty2) =
(* If we are in dynamic-aware subtyping mode, that fact will be lost when ty2
ends up on the upper bound of a type variable. Here we find if ty2 contains
dynamic and replace it with supportdyn<mixed> which is equivalent, but does not
require dynamic-aware subtyping mode to be a supertype of types that support dynamic. *)
match (coerce, TUtils.try_strip_dynamic env ty2) with
| (Some TL.CoerceToDynamic, Some non_dyn_ty) ->
let r = get_reason ty2 in
( None,
MakeType.union
r
[non_dyn_ty; MakeType.supportdyn_mixed ~mixed_reason:r r] )
| _ -> (coerce, ty2)
in
TL.IsSubtype (coerce, ty1, LoclType ty2)
| _ -> TL.IsSubtype (coerce, ty1, ty2) )
(* This is a duplicate of logic in Typing_error_utils, due to conversion of primary errors to secondary errors
on some code paths for Typing_object_get, which throws out quickfix information (unsafe for secondary errors). *)
let add_obj_get_quickfixes
ty_err (on_error : Typing_error.Reasons_callback.t option) :
Typing_error.Reasons_callback.t option =
match ty_err with
| Typing_error.(Error.Primary (Primary.Null_member { pos; obj_pos_opt; _ }))
->
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
Option.map
~f:(fun cb -> Typing_error.Reasons_callback.add_quickfixes cb quickfixes)
on_error
| _ -> on_error
(** Given types ty_sub and ty_super, attempt to
* reduce the subtyping proposition ty_sub <: ty_super to
* a logical proposition whose primitive assertions are of the form v <: t or t <: v
* where v is a type variable.
*
* If super_like=true, then we have already reduced ty_sub <: ~ty_super to ty_sub <: ty_super
* with ty_super known to support dynamic (i.e. ty_super <: supportdyn<mixed>). In this case,
* when "going under" a constructor (for example, we had C<t> <: ~C<u>),
* we can apply "like pushing" on the components (in this example, t <: ~u).
* The parameter defaults to false to guard against incorrectly propagating the option. When
* simplifying ty_sub only (e.g. reducing t|u <: v to t<:v && u<:v) it is correct to
* propagate it.
**)
let rec simplify_subtype
~(subtype_env : subtype_env)
~(sub_supportdyn : Reason.t option)
?(this_ty : locl_ty option = None)
?(super_like = false)
?(super_supportdyn = false)
ty_sub
ty_super =
simplify_subtype_i
~subtype_env
~this_ty
~super_like
~sub_supportdyn
~super_supportdyn
(LoclType ty_sub)
(LoclType ty_super)
and simplify_dynamic_aware_subtype ~subtype_env =
simplify_subtype
~subtype_env:{ subtype_env with coerce = Some TL.CoerceToDynamic }
and default_subtype
~subtype_env
~(this_ty : locl_ty option)
?(super_like = false)
~sub_supportdyn
~fail
env
ty_sub
ty_super =
let default ~sub_supportdyn env =
mk_issubtype_prop
~sub_supportdyn
~coerce:subtype_env.coerce
env
ty_sub
ty_super
in
let ( ||| ) = ( ||| ) ~fail in
let (env, ty_super) = Env.expand_internal_type env ty_super in
let (env, ty_sub) = Env.expand_internal_type env ty_sub in
let default_subtype_inner env ty_sub ty_super =
(* This inner function contains typing rules that are based solely on the subtype
* if you need to pattern match on the super type it should NOT be included
* here
*)
match ty_sub with
| ConstraintType cty_sub -> begin
match deref_constraint_type cty_sub with
| (_, TCunion (lty_sub, cty_sub)) ->
env
|> simplify_subtype_i
~subtype_env
~sub_supportdyn
(LoclType lty_sub)
ty_super
&&& simplify_subtype_i
~subtype_env
~sub_supportdyn
(ConstraintType cty_sub)
ty_super
| (_, TCintersection (lty_sub, cty_sub)) ->
env
|> simplify_subtype_i
~subtype_env
~sub_supportdyn
(LoclType lty_sub)
ty_super
||| simplify_subtype_i
~subtype_env
~sub_supportdyn
(ConstraintType cty_sub)
ty_super
| _ -> invalid ~fail env
end
| LoclType lty_sub -> begin
match deref lty_sub with
| (_, Tunion tyl) ->
(*
* t1 | ... | tn <: t
* if and only if
* t1 <: t /\ ... /\ tn <: t
* We want this even if t is a type variable e.g. consider
* int | v <: v
*
* Prioritize types that aren't dynamic or intersections with dynamic
* to get better error messages
*)
let rec f ty =
Typing_defs.is_dynamic ty
||
match get_node ty with
| Tintersection tyl -> List.exists ~f tyl
| _ -> false
in
let (last_tyl, first_tyl) = TUtils.partition_union ~f tyl in
let subtype_list env prop tyl =
List.fold_left tyl ~init:(env, prop) ~f:(fun res ty_sub ->
res
&&& simplify_subtype_i
~subtype_env
~sub_supportdyn
~super_like
(LoclType ty_sub)
ty_super)
in
let (env, prop) = subtype_list env TL.valid first_tyl in
subtype_list env prop last_tyl
(*| (_, Terr) ->
if subtype_env.no_top_bottom then
default env
else
valid env*)
| (_, Tvar id) ->
(* For subtyping queries of the form
*
* Tvar #id <: (Tvar #id | ...)
*
* `remove_tyvar_from_upper_bound` simplifies the union to
* `mixed`. This indicates that the query is discharged. If we find
* any other upper bound, we leave the subtyping query as it is.
*)
let (env, simplified_super_ty) =
Typing_solver_utils.remove_tyvar_from_upper_bound env id ty_super
in
(* If the type is already in the upper bounds of the type variable,
* then we already know that this subtype assertion is valid
*)
if ITySet.mem simplified_super_ty (Env.get_tyvar_upper_bounds env id)
then
valid env
else
let mixed = MakeType.mixed Reason.none in
(match simplified_super_ty with
| LoclType simplified_super_ty when ty_equal simplified_super_ty mixed
->
valid env
| _ -> default ~sub_supportdyn env)
(* Special case if Tany is in an intersection on the left:
* t1 & ... & _ & ... & tn <: u
* simplifies to
* _ <: u
*)
| (r, Tintersection tyl) when List.exists tyl ~f:is_any ->
simplify_subtype_i
~this_ty
~sub_supportdyn:None
~subtype_env
(LoclType (mk (r, Typing_defs.make_tany ())))
ty_super
env
| (r_sub, Tintersection tyl) ->
(* A & B <: C iif A <: C | !B *)
(match find_type_with_exact_negation env tyl with
| (env, Some non_ty, tyl) ->
let (env, ty_super) =
TUtils.union_i env (get_reason non_ty) ty_super non_ty
in
let ty_sub = MakeType.intersection r_sub tyl in
simplify_subtype_i
~subtype_env
~sub_supportdyn
(LoclType ty_sub)
ty_super
env
| _ ->
(* It's sound to reduce t1 & t2 <: t to (t1 <: t) || (t2 <: t), but
* not complete.
* TODO(T120921930): Don't do this if require_completeness is set.
*)
List.fold_left
tyl
~init:(env, TL.invalid ~fail)
~f:(fun res ty_sub ->
let ty_sub = LoclType ty_sub in
res
||| simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
ty_sub
ty_super))
| (_, Tgeneric (name_sub, tyargs)) ->
(* TODO(T69551141) handle type arguments. right now, just passing
* tyargs to Env.get_upper_bounds *)
(if subtype_env.require_completeness then
default ~sub_supportdyn env
else
(* If we've seen this type parameter before then we must have gone
* round a cycle so we fail
*)
match
VisitedGoals.try_add_visited_generic_sub
subtype_env.visited
name_sub
ty_super
with
| None -> invalid ~fail env
| Some new_visited ->
let subtype_env = { subtype_env with visited = new_visited } in
(* If the generic is actually an expression dependent type,
we need to update this_ty
*)
let this_ty =
if
DependentKind.is_generic_dep_ty name_sub
&& Option.is_none this_ty
then
Some lty_sub
else
this_ty
in
(* Otherwise, we collect all the upper bounds ("as" constraints) on
the generic parameter, and check each of these in turn against
ty_super until one of them succeeds
*)
let rec try_bounds tyl env =
match tyl with
| [] ->
(* Try an implicit mixed = ?nonnull bound before giving up.
This can be useful when checking T <: t, where type t is
equivalent to but syntactically different from ?nonnull.
E.g., if t is a generic type parameter T with nonnull as
a lower bound.
*)
let r =
Reason.Rimplicit_upper_bound (get_pos lty_sub, "?nonnull")
in
let tmixed = LoclType (MakeType.mixed r) in
env
|> simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
tmixed
ty_super
| [ty] ->
simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
~super_like
(LoclType ty)
ty_super
env
| ty :: tyl ->
env
|> try_bounds tyl
||| simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
~super_like
(LoclType ty)
ty_super
in
let bounds =
Typing_set.elements (Env.get_upper_bounds env name_sub tyargs)
in
env |> try_bounds bounds)
|> (* Turn error into a generic error about the type parameter *)
if_unsat (invalid ~fail)
| (_, Tdynamic) when coercing_from_dynamic subtype_env -> valid env
| (_, Taccess _) -> invalid ~fail env
| (r, Tnewtype (n, _, ty)) ->
let sub_supportdyn =
match sub_supportdyn with
| None ->
if String.equal n SN.Classes.cSupportDyn then
Some r
else
None
| _ -> sub_supportdyn
in
simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
~super_like
(LoclType ty)
ty_super
env
| (_, Tdependent (_, ty)) ->
let this_ty = Option.first_some this_ty (Some lty_sub) in
simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
~super_like
(LoclType ty)
ty_super
env
| _ -> invalid ~fail env
end
in
(* We further refine the default subtype case for rules that apply to all
* LoclTypes but not to ConstraintTypes
*)
match ty_super with
| LoclType lty_super ->
(match ty_sub with
| ConstraintType _ -> default_subtype_inner env ty_sub ty_super
| LoclType lty_sub -> begin
match deref lty_sub with
| (_, Tvar _) -> begin
match (subtype_env.coerce, get_node lty_super) with
| (Some TL.CoerceToDynamic, Tdynamic) ->
let r = get_reason lty_super in
let ty_super = MakeType.supportdyn_mixed ~mixed_reason:r r in
default_subtype_inner env ty_sub (LoclType ty_super)
| (Some cd, _) ->
mk_issubtype_prop
~sub_supportdyn
~coerce:(Some cd)
env
(LoclType lty_sub)
(LoclType lty_super)
| (None, _) -> default_subtype_inner env ty_sub ty_super
end
| (r_sub, Tprim Nast.Tvoid) ->
let r =
Reason.Rimplicit_upper_bound (Reason.to_pos r_sub, "?nonnull")
in
simplify_subtype
~subtype_env
~sub_supportdyn:None
~this_ty
(MakeType.mixed r)
lty_super
env
|> if_unsat (invalid ~fail)
| (_, Tany _) ->
if subtype_env.no_top_bottom then
default ~sub_supportdyn env
else
valid env
| _ -> default_subtype_inner env ty_sub ty_super
end)
| ConstraintType _ -> default_subtype_inner env ty_sub ty_super
(* Attempt to "solve" a subtype assertion ty_sub <: ty_super.
* Return a proposition that is logically stronger and simpler than
* the original assertion
* The logical relationship between the original and returned proposition
* depends on the flags require_soundness and require_completeness.
* Fail with Unsat error_function if
* the assertion is unsatisfiable. Some examples:
* string <: arraykey ==> True (represented as Conj [])
* (For covariant C and a type variable v)
* C<string> <: C<v> ==> string <: v
* (Assuming that C does *not* implement interface J)
* C <: J ==> Unsat _
* (Assuming we have T <: D in tpenv, and class D implements I)
* vec<T> <: vec<I> ==> True
* This last one would be left as T <: I if subtype_env.require_completeness=true
*)
and simplify_subtype_i
~(subtype_env : subtype_env)
~(sub_supportdyn : Reason.t option)
?(this_ty : locl_ty option = None)
?(super_like : bool = false)
?(super_supportdyn : bool = false)
(ty_sub : internal_type)
(ty_super : internal_type)
env : env * TL.subtype_prop =
log_subtype_i
~level:subtype_env.log_level
~this_ty
~function_name:
("simplify_subtype"
^ (match subtype_env.coerce with
| None -> ""
| Some TL.CoerceToDynamic -> " <:D"
| Some TL.CoerceFromDynamic -> " D<:")
^
let flag str = function
| true -> str
| false -> ""
in
flag " sub_supportdyn" (Option.is_some sub_supportdyn)
^ flag " super_like" super_like
^ flag " require_soundness" subtype_env.require_soundness
^ flag " require_completeness" subtype_env.require_completeness)
env
ty_sub
ty_super;
simplify_subtype_by_physical_equality env ty_sub ty_super @@ fun () ->
let (env, ety_super) = Env.expand_internal_type env ty_super in
let (env, ety_sub) = Env.expand_internal_type env ty_sub in
simplify_subtype_by_physical_equality env ety_sub ety_super @@ fun () ->
let subtype_env =
possibly_add_violated_constraint
subtype_env
~r_sub:(reason ety_sub)
~r_super:(reason ety_super)
in
let fail_snd_err =
match subtype_env.tparam_constraints with
| [] ->
Typing_error.Secondary.Subtyping_error
{
ty_sub = ety_sub;
ty_sup = ety_super;
is_coeffect = subtype_env.is_coeffect;
}
| cstrs ->
Typing_error.Secondary.Violated_constraint
{
cstrs;
ty_sub = ety_sub;
ty_sup = ety_super;
is_coeffect = subtype_env.is_coeffect;
}
in
let fail_with_suffix snd_err_opt =
let open Typing_error in
let maybe_retain_code =
match subtype_env.tparam_constraints with
| [] -> Reasons_callback.retain_code
| _ -> Fn.id
in
match snd_err_opt with
| Some snd_err ->
Option.map subtype_env.on_error ~f:(fun on_error ->
apply_reasons
~on_error:
Reasons_callback.(
prepend_on_apply (maybe_retain_code on_error) fail_snd_err)
snd_err)
| _ ->
Option.map subtype_env.on_error ~f:(fun on_error ->
apply_reasons ~on_error:(maybe_retain_code on_error) fail_snd_err)
in
let fail = fail_with_suffix None in
let ( ||| ) = ( ||| ) ~fail in
(* We *know* that the assertion is unsatisfiable *)
let invalid_env env = invalid ~fail env in
let invalid_env_with env f = invalid ~fail:f env in
(* We don't know whether the assertion is valid or not *)
let default env =
mk_issubtype_prop
~sub_supportdyn
~coerce:subtype_env.coerce
env
ety_sub
ety_super
in
let default_subtype env =
default_subtype
~subtype_env
~sub_supportdyn
~this_ty
~super_like
~fail
env
ety_sub
ety_super
in
match ety_super with
(* First deal with internal constraint types *)
| ConstraintType cty_super ->
let using_new_method_call_inference =
TypecheckerOptions.method_call_inference (Env.get_tcopt env)
in
begin
match deref_constraint_type cty_super with
| (_, TCintersection (lty, cty)) ->
(match ety_sub with
| LoclType t when is_union t -> default_subtype env
| ConstraintType t when is_constraint_type_union t ->
default_subtype env
| _ ->
env
|> simplify_subtype_i
~subtype_env
~sub_supportdyn
ty_sub
(LoclType lty)
&&& simplify_subtype_i
~subtype_env
~sub_supportdyn
ty_sub
(ConstraintType cty))
| (_, TCunion (maybe_null, maybe_has_member))
when using_new_method_call_inference
&& is_has_member maybe_has_member
&&
let (_, maybe_null) = Env.expand_type env maybe_null in
is_prim Aast.Tnull maybe_null ->
(* `LHS <: Thas_member(...) | null` is morally a null-safe object access *)
let (env, null_ty) = Env.expand_type env maybe_null in
let r_null = get_reason null_ty in
let (r, has_member_ty) = deref_constraint_type maybe_has_member in
(match has_member_ty with
| Thas_member has_member_ty ->
simplify_subtype_has_member
~subtype_env
~sub_supportdyn
~this_ty
~nullsafe:r_null
~fail
ety_sub
(r, has_member_ty)
env
| _ -> invalid_env env (* Not possible due to guard in parent match *))
| (_, TCunion (lty_super, cty_super)) ->
(match ety_sub with
| ConstraintType cty when is_constraint_type_union cty ->
default_subtype env
| ConstraintType _ ->
env
|> simplify_subtype_i
~subtype_env
~sub_supportdyn
ty_sub
(ConstraintType cty_super)
||| simplify_subtype_i
~subtype_env
~sub_supportdyn
ty_sub
(LoclType lty_super)
||| default_subtype
| LoclType lty ->
(match deref lty with
| (r, Toption ty) ->
let ty_null = MakeType.null r in
if_unsat
invalid_env
(simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
(LoclType ty_null)
ty_super
env)
&&& simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
(LoclType ty)
ty_super
| (_, (Tintersection _ | Tunion _ | Tvar _)) -> default_subtype env
| _ ->
env
|> simplify_subtype_i
~subtype_env
~sub_supportdyn
ty_sub
(ConstraintType cty_super)
||| simplify_subtype_i
~subtype_env
~sub_supportdyn
ty_sub
(LoclType lty_super)
||| default_subtype))
| (r_super, Tdestructure { d_required; d_optional; d_variadic; d_kind })
->
(* List destructuring *)
let destructure_array ~sub_supportdyn t env =
(* If this is a splat, there must be a variadic box to receive the elements
* but for list(...) destructuring this is not required. Example:
*
* function f(int $i): void {}
* function g(vec<int> $v): void {
* list($a) = $v; // ok (but may throw)
* f(...$v); // error
* } *)
let fpos =
match r_super with
| Reason.Runpack_param (_, fpos, _) -> fpos
| _ -> Reason.to_pos r_super
in
match (d_kind, d_required, d_variadic) with
| (SplatUnpack, _ :: _, _) ->
(* return the env so as not to discard the type variable that might
have been created for the Traversable type created below. *)
invalid_env_with
env
(Option.map subtype_env.on_error ~f:(fun on_error ->
Typing_error.(
apply_reasons ~on_error
@@ Secondary.Unpack_array_required_argument
{ pos = Reason.to_pos r_super; decl_pos = fpos })))
| (SplatUnpack, [], None) ->
invalid_env_with
env
(Option.map subtype_env.on_error ~f:(fun on_error ->
Typing_error.(
apply_reasons ~on_error
@@ Secondary.Unpack_array_variadic_argument
{ pos = Reason.to_pos r_super; decl_pos = fpos })))
| (SplatUnpack, [], Some _)
| (ListDestructure, _, _) ->
List.fold d_required ~init:(env, TL.valid) ~f:(fun res ty_dest ->
res
&&& simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
t
ty_dest)
&&& fun env ->
List.fold d_optional ~init:(env, TL.valid) ~f:(fun res ty_dest ->
res
&&& simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
t
ty_dest)
&&& fun env ->
Option.value_map ~default:(env, TL.valid) d_variadic ~f:(fun vty ->
simplify_subtype ~subtype_env ~sub_supportdyn ~this_ty t vty env)
in
let destructure_tuple r ts env =
(* First fill the required elements. If there are insufficient elements, an error is reported.
* Fill as many of the optional elements as possible, and the remainder are unioned into the
* variadic element. Example:
*
* (float, bool, string, int) <: Tdestructure(#1, opt#2, ...#3) =>
* float <: #1 /\ bool <: #2 /\ string <: #3 /\ int <: #3
*
* (float, bool) <: Tdestructure(#1, #2, opt#3) =>
* float <: #1 /\ bool <: #2
*)
let len_ts = List.length ts in
let len_required = List.length d_required in
let arity_error f =
let (epos, fpos, prefix) =
match r_super with
| Reason.Runpack_param (epos, fpos, c) ->
(Pos_or_decl.of_raw_pos epos, fpos, c)
| _ -> (Reason.to_pos r_super, Reason.to_pos r, 0)
in
invalid_env_with
env
(f
(prefix + len_required)
(prefix + len_ts)
epos
fpos
subtype_env.on_error)
in
if len_ts < len_required then
arity_error (fun expected actual pos decl_pos on_error_opt ->
Option.map on_error_opt ~f:(fun on_error ->
let base_err =
Typing_error.Secondary.Typing_too_few_args
{ pos; decl_pos; expected; actual }
in
Typing_error.(apply_reasons ~on_error base_err)))
else
let len_optional = List.length d_optional in
let (ts_required, remain) = List.split_n ts len_required in
let (ts_optional, ts_variadic) = List.split_n remain len_optional in
List.fold2_exn
ts_required
d_required
~init:(env, TL.valid)
~f:(fun res ty ty_dest ->
res
&&& simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
ty
ty_dest)
&&& fun env ->
let len_ts_opt = List.length ts_optional in
let d_optional_part =
if len_ts_opt < len_optional then
List.take d_optional len_ts_opt
else
d_optional
in
List.fold2_exn
ts_optional
d_optional_part
~init:(env, TL.valid)
~f:(fun res ty ty_dest ->
res
&&& simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
ty
ty_dest)
&&& fun env ->
match (ts_variadic, d_variadic) with
| (vars, Some vty) ->
List.fold vars ~init:(env, TL.valid) ~f:(fun res ty ->
res
&&& simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
ty
vty)
| ([], None) -> valid env
| (_, None) ->
(* Elements remain but we have nowhere to put them *)
arity_error (fun expected actual pos decl_pos on_error_opt ->
Option.map on_error_opt ~f:(fun on_error ->
Typing_error.(
apply_reasons ~on_error
@@ Secondary.Typing_too_many_args
{ pos; decl_pos; expected; actual })))
in
let destructure_dynamic t env =
if TypecheckerOptions.enable_sound_dynamic (Env.get_tcopt env) then
List.fold d_required ~init:(env, TL.valid) ~f:(fun res ty_dest ->
res
&&& simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
t
ty_dest)
&&& fun env ->
List.fold d_optional ~init:(env, TL.valid) ~f:(fun res ty_dest ->
res
&&& simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
t
ty_dest)
&&& fun env ->
Option.value_map ~default:(env, TL.valid) d_variadic ~f:(fun vty ->
simplify_subtype ~subtype_env ~sub_supportdyn ~this_ty t vty env)
else
env |> destructure_array ~sub_supportdyn t
in
begin
match ety_sub with
| ConstraintType _ -> default_subtype env
| LoclType ty_sub ->
(match deref ty_sub with
| (r, Ttuple tyl) -> env |> destructure_tuple r tyl
| (r, Tclass ((_, x), _, tyl))
when String.equal x SN.Collections.cPair ->
env |> destructure_tuple r tyl
| (_, Tclass ((_, x), _, [elt_type]))
when String.equal x SN.Collections.cVector
|| String.equal x SN.Collections.cImmVector
|| String.equal x SN.Collections.cVec
|| String.equal x SN.Collections.cConstVector ->
env |> destructure_array ~sub_supportdyn elt_type
| (_, Tdynamic) -> env |> destructure_dynamic ty_sub
(* TODO: should remove these any cases *)
| (r, Tany _) ->
let any = mk (r, Typing_defs.make_tany ()) in
env |> destructure_array ~sub_supportdyn any
| (_, (Tunion _ | Tintersection _ | Tgeneric _ | Tvar _)) ->
(* TODO(T69551141) handle type arguments of Tgeneric? *)
default_subtype env
| _ -> begin
match d_kind with
| SplatUnpack ->
(* Allow splatting of arbitrary Traversables *)
let (env, ty_inner) = Env.fresh_type env Pos.none in
let traversable = MakeType.traversable r_super ty_inner in
env
|> simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
ty_sub
traversable
&&& destructure_array ~sub_supportdyn:None ty_inner
| ListDestructure ->
let ty_sub_descr =
lazy
(Typing_print.with_blank_tyvars (fun () ->
Typing_print.full_strip_ns env ty_sub))
in
default_subtype env
|> if_unsat @@ fun env ->
invalid_env_with
env
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Invalid_destructure
{
pos = Reason.to_pos r_super;
decl_pos = get_pos ty_sub;
ty_name = ty_sub_descr;
}))
end)
end
| (r, Tcan_index ci) ->
simplify_subtype_can_index
~subtype_env
~sub_supportdyn
~this_ty
~fail
ety_sub
ety_super
(r, ci)
env
| (r, Tcan_traverse ct) ->
simplify_subtype_can_traverse
~subtype_env
~sub_supportdyn
~this_ty
~fail
ety_sub
ety_super
(r, ct)
env
| (r, Thas_member has_member_ty) ->
simplify_subtype_has_member
~subtype_env
~sub_supportdyn
~this_ty
~fail
ety_sub
(r, has_member_ty)
env
| (r, Thas_type_member htm) ->
(* Contextualize errors that may be generated when
* checking refinement bounds. *)
let on_error =
Option.map subtype_env.on_error ~f:(fun on_error ->
let open Typing_error.Reasons_callback in
prepend_on_apply on_error fail_snd_err)
in
let subtype_env = { subtype_env with on_error } in
simplify_subtype_has_type_member
~subtype_env
~sub_supportdyn
~this_ty
~fail
ety_sub
(r, htm)
env
end
(* Next deal with all locl types *)
| LoclType ty_super ->
(match deref ty_super with
| (_, Tvar var_super) ->
(match ety_sub with
| ConstraintType cty when is_constraint_type_union cty ->
default_subtype env
| ConstraintType _ -> default env
| LoclType ty_sub ->
(match deref ty_sub with
| (_, Tunion _) -> default_subtype env
| (_, Tdynamic) when coercing_from_dynamic subtype_env ->
default_subtype env
(* We want to treat nullable as a union with the same rule as above.
* This is only needed for Tvar on right; other cases are dealt with specially as
* derived rules.
*)
| (r, Toption t) ->
let (env, t) = Env.expand_type env t in
(match get_node t with
(* We special case on `mixed <: Tvar _`, adding the entire `mixed` type
as a lower bound. This enables clearer error messages when upper bounds
are added to the type variable: transitive closure picks up the
entire `mixed` type, and not separately consider `null` and `nonnull` *)
| Tnonnull -> default env
| _ ->
let ty_null = MakeType.null r in
env
|> simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
~super_like
t
ty_super
&&& simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
ty_null
ty_super)
| (_, Tvar var_sub) when Ident.equal var_sub var_super -> valid env
| _ -> begin
match subtype_env.coerce with
| Some cd ->
mk_issubtype_prop
~sub_supportdyn
~coerce:(Some cd)
env
(LoclType ty_sub)
(LoclType ty_super)
| None ->
if super_like then
let (env, ty_sub) =
Typing_dynamic.strip_covariant_like env ty_sub
in
env
|> simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
~super_like:false
(LoclType ty_sub)
(LoclType ty_super)
else
default env
end))
| (_, Tintersection tyl) ->
(match ety_sub with
| ConstraintType cty when is_constraint_type_union cty ->
default_subtype env
| LoclType lty when is_union lty -> default_subtype env
(* t <: (t1 & ... & tn)
* if and only if
* t <: t1 /\ ... /\ t <: tn
*)
| _ ->
List.fold_left tyl ~init:(env, TL.valid) ~f:(fun res ty_super ->
let ty_super = LoclType ty_super in
res
&&& simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
ty_sub
ty_super))
(* Empty union encodes the bottom type nothing *)
| (_, Tunion []) -> default_subtype env
(* ty_sub <: union{ty_super'} iff ty_sub <: ty_super' *)
| (_, Tunion [ty_super']) ->
simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
~super_like
ty_sub
(LoclType ty_super')
env
| (r, Tunion (_ :: _ as tyl_super)) ->
let simplify_sub_union env ty_sub tyl_super =
(* Identify cases heuristically where we just want to reduce t <: ~u to
t <: u with super-like set, and not also try t <: dynamic or run finish *)
let avoid_disjunctions env ty =
let (env, ty) = Env.expand_type env ty in
match (ty_sub, get_node ty) with
| (LoclType lty, Tnewtype (n2, _, _)) ->
(match get_node lty with
| Tnewtype (n1, _, _)
when String.equal n1 n2
&& not (String.equal n1 SN.Classes.cSupportDyn) ->
(env, true)
| _ -> (env, false))
| _ -> (env, false)
in
let finish env =
match ty_sub with
| LoclType lty -> begin
match get_node lty with
| Tnewtype _
| Tdependent _
| Tgeneric _ ->
default_subtype env
| _ -> invalid_env env
end
| _ -> invalid_env env
in
let simplify_subtype_of_dynamic env =
simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
ty_sub
(LoclType (MakeType.dynamic r))
env
in
let dyn_finish ty env =
let (env, avoid) = avoid_disjunctions env ty in
if avoid then
invalid_env env
else
simplify_subtype_of_dynamic env ||| fun env ->
if Typing_utils.is_tyvar env ty then
invalid_env env
else
finish env
in
let stripped_dynamic =
if TypecheckerOptions.enable_sound_dynamic env.genv.tcopt then
TUtils.try_strip_dynamic_from_union env tyl_super
else
None
in
match stripped_dynamic with
| Some tyl ->
let ty = MakeType.union r tyl in
let (env, ty) = Env.expand_type env ty in
let delay_push =
is_sub_type_for_union_i
env
(LoclType ty)
(LoclType (MakeType.supportdyn_mixed ~mixed_reason:r r))
in
(* This is Typing_logic_helpers.( ||| ) except with a bias towards p1 *)
let ( ||| ) (env, p1) (f : env -> env * TL.subtype_prop) =
if TL.is_valid p1 then
(env, p1)
else
let (env, p2) = f env in
if TL.is_unsat p2 then
(env, p1)
else if TL.is_unsat p1 then
(env, p2)
else
(env, TL.disj ~fail p1 p2)
in
(* Implement the declarative subtyping rule C<~t1,...,~tn> <: ~C<t1,...,tn>
* for a type C<t1,...,tn> that supports dynamic. Algorithmically,
* t <: ~C<t1,...,tn> iff
* t <: C<~t1,...,~tn> /\ C<~t1,...,~tn> <:D dynamic.
* An SDT class C generalizes to other SDT constructors such as tuples and shapes.
*)
let try_push env =
if delay_push then
dyn_finish ty env
else
(* "Solve" type variables that are bounded from above and below by the same type.
* Push this through nullables. This addresses common completeness issues that
* bedevil like-pushing because of the disjunction that is generated.
*)
let rec solve_eq_tyvar env ty =
let (env, ty) = Env.expand_type env ty in
match get_node ty with
| Tvar v ->
let lower_bounds = Env.get_tyvar_lower_bounds env v in
let upper_bounds = Env.get_tyvar_upper_bounds env v in
let bounds = ITySet.inter lower_bounds upper_bounds in
let bounds_list = ITySet.elements bounds in
begin
match bounds_list with
| [LoclType lty] -> (env, lty)
| _ -> (env, ty)
end
| Toption ty1 ->
let (env, ty1) = solve_eq_tyvar env ty1 in
(env, mk (get_reason ty, Toption ty1))
| _ -> (env, ty)
in
let (env, ty) = solve_eq_tyvar env ty in
(* For generic parameters with lower bounds, try like-pushing wrt
* these lower bounds. For example, we want
* vec<~int> <: ~T if vec<int> <: T
*)
let ty =
match get_node ty with
| Tgeneric (name, targs) ->
let bounds = Env.get_lower_bounds env name targs in
MakeType.union (get_reason ty) (Typing_set.elements bounds)
| _ -> ty
in
let (env, opt_ty) = Typing_dynamic.try_push_like env ty in
match opt_ty with
| None ->
let istyvar =
match get_node ty with
| Tvar _ -> true
| Toption ty ->
let (_, ty) = Env.expand_type env ty in
is_tyvar ty
| _ -> false
in
if istyvar then
env
|> simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
~super_like:true
ty_sub
(LoclType ty)
||| dyn_finish ty
else
dyn_finish ty env
| Some ty ->
let simplify_pushed_like env =
env
|> simplify_dynamic_aware_subtype
~subtype_env
~sub_supportdyn:None
~this_ty
ty
(MakeType.dynamic Reason.Rnone)
&&& simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
ty_sub
(LoclType ty)
in
env |> simplify_pushed_like ||| dyn_finish ty
in
simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
~super_like:delay_push
ty_sub
(LoclType ty)
env
||| try_push
| _ ->
(* It's sound to reduce t <: t1 | t2 to (t <: t1) || (t <: t2). But
* not complete e.g. consider (t1 | t3) <: (t1 | t2) | (t2 | t3).
* But we deal with unions on the left first (see case above), so this
* particular situation won't arise.
* TODO: identify under what circumstances this reduction is complete.
* TODO(T120921930): Don't do this if require_completeness is set.
*)
let rec try_disjuncts tys env =
match tys with
| [] -> invalid_env env
| ty :: tys ->
let ty = LoclType ty in
env
|> simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
~super_like
ty_sub
ty
||| try_disjuncts tys
in
env |> try_disjuncts tyl_super
in
(match ety_sub with
| ConstraintType cty when is_constraint_type_union cty ->
default_subtype env
| ConstraintType _ -> simplify_sub_union env ety_sub tyl_super
| LoclType lty_sub ->
(match
simplify_subtype_arraykey_union
~sub_supportdyn
~this_ty
~subtype_env
env
lty_sub
tyl_super
with
| (env, Some props) -> (env, props)
| (env, None) ->
(match deref lty_sub with
| (_, (Tunion _ | Tvar _)) -> default_subtype env
| (_, Tgeneric _) when subtype_env.require_completeness ->
default_subtype env
(* Num is not atomic: it is equivalent to int|float. The rule below relies
* on ty_sub not being a union e.g. consider num <: arraykey | float, so
* we break out num first.
*)
| (r, Tprim Nast.Tnum) ->
let ty_float = MakeType.float r and ty_int = MakeType.int r in
env
|> simplify_subtype
~subtype_env
~sub_supportdyn:None
~this_ty
ty_float
ty_super
&&& simplify_subtype
~subtype_env
~sub_supportdyn:None
~this_ty
ty_int
ty_super
(* Likewise, reduce nullable on left to a union *)
| (r, Toption ty) ->
let ty_null = MakeType.null r in
if_unsat
invalid_env
(simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
(LoclType ty_null)
ety_super
env)
&&& simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
(LoclType ty)
ety_super
| (_, Tintersection tyl)
when let (_, non_ty_opt, _) =
find_type_with_exact_negation env tyl
in
Option.is_some non_ty_opt ->
default_subtype env
| (_, Tintersection tyl_sub) ->
let simplify_super_intersection env tyl_sub ty_super =
(* It's sound to reduce t1 & t2 <: t to (t1 <: t) || (t2 <: t), but
* not complete.
* TODO(T120921930): Don't do this if require_completeness is set.
*)
List.fold_left
tyl_sub
~init:(env, TL.invalid ~fail)
~f:(fun res ty_sub ->
let ty_sub = LoclType ty_sub in
res
||| simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
ty_sub
ty_super)
in
(* Heuristicky logic to decide whether to "break" the intersection
or the union first, based on observing that the following cases often occur:
- A & B <: (A & B) | C
In which case we want to "break" the union on the right first
in order to have the following recursive calls :
A & B <: A & B
A & B <: C
- A & (B | C) <: B | C
In which case we want to "break" the intersection on the left first
in order to have the following recursive calls:
A <: B | C
B | C <: B | C
If there is a type variable in the union, then generally it's helpful to
break the union apart.
*)
if
List.exists tyl_super ~f:(fun t ->
TUtils.is_tintersection env t
|| TUtils.is_opt_tyvar env t
|| TUtils.is_tyvar env t)
then
simplify_sub_union env ety_sub tyl_super
else if List.exists tyl_sub ~f:(TUtils.is_tunion env) then
simplify_super_intersection env tyl_sub (LoclType ty_super)
else
simplify_sub_union env ety_sub tyl_super
| _ -> simplify_sub_union env ety_sub tyl_super)))
| (r_super, Toption arg_ty_super) ->
let (env, ety) = Env.expand_type env arg_ty_super in
(* Toption(Tnonnull) encodes mixed, which is our top type.
* Everything subtypes mixed *)
if is_nonnull ety then
valid env
else (
match ety_sub with
| ConstraintType _ -> default_subtype env
| LoclType lty_sub ->
(match (deref lty_sub, get_node ety) with
(* ?supportdyn<t> is equivalent to supportdyn<?t> *)
| (_, Tnewtype (name, [tyarg], _))
when String.equal name SN.Classes.cSupportDyn ->
let tyarg = MakeType.nullable r_super tyarg in
simplify_subtype
~subtype_env
~sub_supportdyn
~super_like
lty_sub
(MakeType.supportdyn r_super tyarg)
env
(* supportdyn<t> <: ?u iff
* nonnull & supportdyn<t> <: u iff
* supportdyn<nonnull & t> <: u
*)
| ((r, Tnewtype (name, [tyarg1], _)), _)
when String.equal name SN.Classes.cSupportDyn ->
let (env, ty_sub') =
Inter.intersect env ~r:r_super tyarg1 (MakeType.nonnull r_super)
in
simplify_subtype
~subtype_env
~sub_supportdyn:(Some r)
~super_like
ty_sub'
ety
env
(* A <: ?B iff A & nonnull <: B
Only apply if B is a type variable or an intersection, to avoid oscillating
forever between this case and the previous one. *)
| ((_, Tintersection tyl), (Tintersection _ | Tvar _))
when let (_, non_ty_opt, _) =
find_type_with_exact_negation env tyl
in
Option.is_none non_ty_opt ->
let (env, ty_sub') =
Inter.intersect_i env r_super ty_sub (MakeType.nonnull r_super)
in
simplify_subtype_i
~subtype_env
~sub_supportdyn
~super_like
ty_sub'
(LoclType arg_ty_super)
env
(* null is the type of null and is a subtype of any option type. *)
| ((_, Tprim Nast.Tnull), _) -> valid env
(* ?ty_sub' <: ?ty_super' iff ty_sub' <: ?ty_super'. Reasoning:
* If ?ty_sub' <: ?ty_super', then from ty_sub' <: ?ty_sub' (widening) and transitivity
* of <: it follows that ty_sub' <: ?ty_super'. Conversely, if ty_sub' <: ?ty_super', then
* by covariance and idempotence of ?, we have ?ty_sub' <: ??ty_sub' <: ?ty_super'.
* Therefore, this step preserves the set of solutions.
*)
| ((_, Toption ty_sub'), _) ->
simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
~super_like
ty_sub'
ty_super
env
(* If the type on the left is disjoint from null, then the Toption on the right is not
doing anything helpful. *)
| ((_, (Tintersection _ | Tunion _)), _)
when TUtils.is_type_disjoint
env
lty_sub
(MakeType.null Reason.Rnone) ->
simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
~super_like
lty_sub
ety
env
(* We do not want to decompose Toption for these cases *)
| ((_, (Tvar _ | Tunion _ | Tintersection _)), _) ->
default_subtype env
| ((_, Tgeneric _), _) when subtype_env.require_completeness ->
(* TODO(T69551141) handle type arguments ? *)
default_subtype env
(* If t1 <: ?t2 and t1 is an abstract type constrained as t1',
* then t1 <: t2 or t1' <: ?t2. The converse is obviously
* true as well. We can fold the case where t1 is unconstrained
* into the case analysis below.
*
* In the case where it's easy to determine that null isn't in t1,
* we need only check t1 <: t2.
*)
| ((_, (Tnewtype _ | Tdependent _ | Tgeneric _ | Tprim Nast.Tvoid)), _)
->
(* TODO(T69551141) handle type arguments? *)
if null_not_subtype lty_sub then
env
|> simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
~super_like
lty_sub
arg_ty_super
else
env
|> simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
~super_like
lty_sub
arg_ty_super
||| default_subtype
(* If ty_sub <: ?ty_super' and ty_sub does not contain null then we
* must also have ty_sub <: ty_super'. The converse follows by
* widening and transitivity. Therefore, this step preserves the set
* of solutions.
*)
| ((_, Tunapplied_alias _), _) ->
Typing_defs.error_Tunapplied_alias_in_illegal_context ()
| ( ( _,
( Tdynamic | Tprim _ | Tnonnull | Tfun _ | Ttuple _ | Tshape _
| Tclass _ | Tvec_or_dict _ | Tany _ | Taccess _ ) ),
_ ) ->
simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
~super_like
lty_sub
arg_ty_super
env
(* This is treating the option as a union, and using the sound, but incomplete,
t <: t1 | t2 to (t <: t1) || (t <: t2) reduction
TODO(T120921930): Don't do this if require_completeness is set.
*)
| ((_, Tneg _), _) ->
simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
~super_like
lty_sub
arg_ty_super
env)
)
| (_r_super, Tdependent (d_sup, bound_sup)) ->
let (env, bound_sup) = Env.expand_type env bound_sup in
(match ety_sub with
| ConstraintType _ -> default_subtype env
| LoclType ty_sub ->
(match (deref ty_sub, get_node bound_sup) with
| ((_, Tclass _), Tclass ((_, x), _, _))
when is_final_and_invariant env x ->
(* For final class C, there is no difference between `this as X` and `X`,
* and `expr<#n> as X` and `X`.
* But we need to take care with variant classes, since we can't
* statically guarantee their runtime type.
*)
simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
ty_sub
bound_sup
env
| ( (r_sub, Tclass ((_, y), _, _)),
Tclass (((_, x) as id), _, _tyl_super) ) ->
let fail =
if String.equal x y then
let p = Reason.to_pos r_sub in
let (pos_super, class_name) = id in
fail_with_suffix
(Some
(Typing_error.Secondary.This_final
{ pos_super; class_name; pos_sub = p }))
else
fail
in
invalid_env_with env fail
| ((_, Tdependent (d_sub, bound_sub)), _) ->
let this_ty = Option.first_some this_ty (Some ty_sub) in
(* Dependent types are identical but bound might be different *)
if equal_dependent_type d_sub d_sup then
simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
bound_sub
bound_sup
env
else
simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
bound_sub
ty_super
env
| _ -> default_subtype env))
| (_, Taccess _) -> invalid_env env
| (_, Tgeneric (name_super, tyargs_super)) ->
(* TODO(T69551141) handle type arguments. Right now, only passing tyargs_super to
Env.get_lower_bounds *)
(match ety_sub with
| ConstraintType _ -> default_subtype env
(* If subtype and supertype are the same generic parameter, we're done *)
| LoclType ty_sub ->
let (generic_lower_bounds, other_lower_bounds) =
let rec fixpoint new_set bounds_set =
if Typing_set.is_empty new_set then
bounds_set
else
let add_set =
Typing_set.fold
(fun ty add_set ->
match get_node ty with
| Tgeneric (name, targs) ->
let gen_bounds = Env.get_lower_bounds env name targs in
Typing_set.union add_set gen_bounds
| _ -> add_set)
new_set
Typing_set.empty
in
let bounds_set = Typing_set.union new_set bounds_set in
let new_set = Typing_set.diff add_set bounds_set in
fixpoint new_set bounds_set
in
let lower_bounds =
fixpoint (Typing_set.singleton ty_super) Typing_set.empty
in
Typing_set.fold
(fun bound_ty (g_set, o_set) ->
match get_node bound_ty with
| Tgeneric (name, []) -> (SSet.add name g_set, o_set)
| _ -> (g_set, Typing_set.add bound_ty o_set))
lower_bounds
(SSet.empty, Typing_set.empty)
in
(match get_node ty_sub with
| Tgeneric (name_sub, []) when SSet.mem name_sub generic_lower_bounds ->
valid env
| Tgeneric (name_sub, tyargs_sub) when String.equal name_sub name_super
->
if List.is_empty tyargs_super then
valid env
else
(* TODO(T69931993) Type parameter env must carry variance information *)
let variance_reifiedl =
List.map tyargs_sub ~f:(fun _ ->
(Ast_defs.Invariant, Aast.Erased))
in
simplify_subtype_variance_for_non_injective
~subtype_env
~sub_supportdyn
~super_like
name_sub
None
variance_reifiedl
tyargs_sub
tyargs_super
ety_sub
ety_super
env
(* When decomposing subtypes for the purpose of adding bounds on generic
* parameters to the context, (so seen_generic_params = None), leave
* subtype so that the bounds get added *)
| Tvar _
| Tunion _ ->
default_subtype env
| _ ->
if subtype_env.require_completeness then
default env
else (
(* If we've seen this type parameter before then we must have gone
* round a cycle so we fail
*)
match
VisitedGoals.try_add_visited_generic_super
subtype_env.visited
ety_sub
name_super
with
| None -> invalid_env env
| Some new_visited ->
let subtype_env = { subtype_env with visited = new_visited } in
(* Collect all the lower bounds ("super" constraints) on the
* generic parameter, and check ty_sub against each of them in turn
* until one of them succeeds *)
let rec try_bounds tyl env =
match tyl with
| [] -> default_subtype env
| ty :: tyl ->
env
|> simplify_subtype
~subtype_env
~sub_supportdyn
~super_like
~this_ty
ty_sub
ty
||| try_bounds tyl
in
(* Turn error into a generic error about the type parameter *)
let bounds = Typing_set.elements other_lower_bounds in
env |> try_bounds bounds |> if_unsat invalid_env
)))
| (_, Tnonnull) ->
(match ety_sub with
| ConstraintType cty -> begin
match deref_constraint_type cty with
| (_, (Thas_member _ | Tdestructure _)) -> valid env
| _ -> default_subtype env
end
| LoclType lty ->
(match deref lty with
| ( _,
( Tprim
Nast.(
( Tint | Tbool | Tfloat | Tstring | Tresource | Tnum
| Tarraykey | Tnoreturn ))
| Tnonnull | Tfun _ | Ttuple _ | Tshape _ | Tclass _
| Tvec_or_dict _ | Taccess _ ) ) ->
valid env
(* supportdyn<t> <: nonnull iff t <: nonnull *)
| (r, Tnewtype (name, [tyarg], _))
when String.equal name SN.Classes.cSupportDyn ->
env
|> simplify_subtype
~subtype_env
~sub_supportdyn:(Some r)
~this_ty
tyarg
ty_super
(* negations always contain null *)
| (_, Tneg _) -> invalid_env env
| _ -> default_subtype env))
| (r_dynamic, Tdynamic)
when TypecheckerOptions.enable_sound_dynamic env.genv.tcopt
&& (coercing_to_dynamic subtype_env
|| Tast.is_under_dynamic_assumptions env.checked) ->
let open Ast_defs in
(match ety_sub with
| ConstraintType _cty ->
(* TODO *)
default_subtype env
| LoclType lty_sub ->
let dyn = lazy (describe_ty_super ~is_coeffect:false env ety_super) in
let dynamic_part =
Lazy.map dyn ~f:(fun dyn ->
Reason.to_string ("Expected " ^ dyn) r_dynamic)
and ty_name = lazy (describe_ty_default env ety_sub)
and pos = Reason.to_pos (get_reason lty_sub) in
let postprocess =
if_unsat
(invalid
~fail:
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Not_sub_dynamic
{ pos; ty_name; dynamic_part })))
in
postprocess
@@
if Option.is_some sub_supportdyn then
valid env
else (
match deref lty_sub with
| (_, Tany _)
| ( _,
Tprim
( Tint | Tbool | Tfloat | Tstring | Tnum | Tarraykey | Tvoid
| Tnoreturn | Tresource ) ) ->
valid env
| (_, Tnewtype (name_sub, [_tyarg_sub], _))
when String.equal name_sub SN.Classes.cSupportDyn ->
valid env
| (_, Tnewtype (name_sub, _, _))
when String.equal name_sub SN.Classes.cEnumClassLabel ->
valid env
| (_, Toption ty) ->
(match deref ty with
(* Special case mixed <: dynamic for better error message *)
| (_, Tnonnull) -> invalid_env env
| _ -> simplify_subtype ~subtype_env ~sub_supportdyn ty ty_super env)
| (_, (Tdynamic | Tprim Tnull)) -> valid env
| (_, Tnonnull)
| (_, Tvar _)
| (_, Tunapplied_alias _)
| (_, Tnewtype _)
| (_, Tdependent _)
| (_, Taccess _)
| (_, Tunion _)
| (_, Tintersection _)
| (_, Tgeneric _)
| (_, Tneg _) ->
default_subtype env
| (_, Tvec_or_dict (_, ty)) ->
simplify_subtype ~subtype_env ~sub_supportdyn ty ty_super env
| (_, Tfun ft_sub) ->
if get_ft_support_dynamic_type ft_sub then
valid env
else
(* Special case of function type subtype dynamic.
* (function(ty1,...,tyn):ty <: supportdyn<nonnull>)
* iff
* dynamic <D: ty1 & ... & dynamic <D: tyn & ty <D: dynamic
*)
let ty_dyn_enf =
{ et_enforced = Unenforced; et_type = ty_super }
in
env
(* Contravariant subtyping on parameters *)
|> simplify_supertype_params_with_variadic
~subtype_env
ft_sub.ft_params
ty_dyn_enf
&&& (* Finally do covariant subtryping on return type *)
simplify_subtype
~subtype_env
~sub_supportdyn
ft_sub.ft_ret.et_type
ty_super
| (_, Ttuple tyl) ->
List.fold_left
~init:(env, TL.valid)
~f:(fun res ty_sub ->
res
&&& simplify_subtype
~subtype_env
~sub_supportdyn
ty_sub
ty_super)
tyl
| ( _,
Tshape
{
s_origin = _;
s_unknown_value = unknown_fields_type;
s_fields = sftl;
} ) ->
List.fold_left
~init:(env, TL.valid)
~f:(fun res sft ->
res
&&& simplify_subtype
~subtype_env
~sub_supportdyn
sft.sft_ty
ty_super)
(TShapeMap.values sftl)
&&& simplify_subtype
~subtype_env
~sub_supportdyn
unknown_fields_type
ty_super
| (_, Tclass ((_, class_id), _exact, tyargs)) ->
let class_def_sub = Env.get_class env class_id in
(match class_def_sub with
| None ->
(* This should have been caught already in the naming phase *)
valid env
| Some class_sub ->
if
Cls.get_support_dynamic_type class_sub
|| Env.is_enum env class_id
then
(* If a class has the __SupportDynamicType annotation, then
a type formed from it is a dynamic-aware subtype of dynamic if
the type arguments are correctly supplied, which depends on the
variance of the parameter, and whether the __RequireDynamic
is on the parameter.
*)
let rec subtype_args tparams tyargs env =
match (tparams, tyargs) with
| ([], _) -> valid env
| (_, []) ->
(* If there are missing type arguments, we don't know that they are subtypes of dynamic, unless the bounds enforce that *)
invalid_env env
| (tp :: tparams, tyarg :: tyargs) ->
let has_require_dynamic =
Attributes.mem
SN.UserAttributes.uaRequireDynamic
tp.tp_user_attributes
in
(if
has_require_dynamic
(* Implicit pessimisation should ignore the RequireDynamic attribute
because everything should be pessimised enough that it isn't necessary. *)
&& not (TypecheckerOptions.everything_sdt env.genv.tcopt)
then
(* If the class is marked <<__SupportDynamicType>> then for any
* type parameters marked <<__RequireDynamic>> then the class does not
* unconditionally implement dynamic, but rather we must check that
* it is a subtype of the same type whose corresponding type arguments
* are replaced by dynamic, intersected with the parameter's upper bounds.
*
* For example, to check dict<int,float> <: supportdyn<nonnull>
* we check dict<int,float> <D: dict<arraykey,dynamic>
* which in turn requires int <D: arraykey and float <D: dynamic.
*)
let upper_bounds =
List.filter_map tp.tp_constraints ~f:(fun (c, ty) ->
match c with
| Ast_defs.Constraint_as ->
let (_env, ty) =
Phase.localize_no_subst
env
~ignore_errors:true
ty
in
Some ty
| _ -> None)
in
let super =
MakeType.intersection
r_dynamic
(ty_super :: upper_bounds)
in
match tp.tp_variance with
| Ast_defs.Covariant ->
simplify_subtype
~subtype_env
~sub_supportdyn:None
tyarg
super
env
| Ast_defs.Contravariant ->
simplify_subtype
~subtype_env
~sub_supportdyn:None
super
tyarg
env
| Ast_defs.Invariant ->
simplify_subtype
~subtype_env
~sub_supportdyn:None
tyarg
super
env
&&& simplify_subtype
~subtype_env
~sub_supportdyn:None
super
tyarg
else
(* If the class is marked <<__SupportDynamicType>> then for any
* type parameters not marked <<__RequireDynamic>> then the class is a
* subtype of dynamic only when the arguments are also subtypes of dynamic.
*)
match tp.tp_variance with
| Ast_defs.Covariant
| Ast_defs.Invariant ->
simplify_subtype
~subtype_env
~sub_supportdyn:None
tyarg
ty_super
env
| Ast_defs.Contravariant ->
(* If the parameter is contra-variant, then we only need to
check that the lower bounds (if present) are subtypes of
dynamic. For example, given <<__SDT>> class C<-T> {...},
then for any t, C<t> <: C<nothing>, and since
`nothing <D: dynamic`, `C<nothing> <D: dynamic` and so
`C<t> <D: dynamic`. If there are lower bounds, we can't
push the argument below them. It suffices to check only
them because if one of them is not <D: dynamic, then
none of their supertypes are either.
*)
let lower_bounds =
List.filter_map tp.tp_constraints ~f:(fun (c, ty) ->
match c with
| Ast_defs.Constraint_super ->
let (_env, ty) =
Phase.localize_no_subst
env
~ignore_errors:true
ty
in
Some ty
| _ -> None)
in
(match lower_bounds with
| [] -> valid env
| _ ->
let sub = MakeType.union r_dynamic lower_bounds in
simplify_subtype
~subtype_env
~sub_supportdyn:None
sub
ty_super
env))
&&& subtype_args tparams tyargs
in
subtype_args (Cls.tparams class_sub) tyargs env
else (
match Cls.kind class_sub with
| Ast_defs.Cenum_class _ ->
(match Cls.enum_type class_sub with
| Some enum_type ->
let ((env, _ty_err_opt), subtype) =
TUtils.localize_no_subst
~ignore_errors:true
env
enum_type.te_base
in
simplify_subtype
~subtype_env
~sub_supportdyn:None
subtype
ty_super
env
| None -> default_subtype env)
| _ -> default_subtype env
))
))
| (_, Tdynamic) ->
(match ety_sub with
| LoclType lty when is_dynamic lty -> valid env
| ConstraintType _
| LoclType _ ->
default_subtype env)
| (_, Tprim prim_ty) ->
(match ety_sub with
| ConstraintType _ -> default_subtype env
| LoclType lty ->
(match (deref lty, prim_ty) with
| ((_, Tprim (Nast.Tint | Nast.Tfloat)), Nast.Tnum) -> valid env
| ((_, Tprim (Nast.Tint | Nast.Tstring)), Nast.Tarraykey) -> valid env
| ((_, Tprim prim_sub), _) when Aast.equal_tprim prim_sub prim_ty ->
valid env
| ((_, Toption arg_ty_sub), Nast.Tnull) ->
simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
arg_ty_sub
ty_super
env
| (_, _) -> default_subtype env))
| (_, Tany _) ->
(match ety_sub with
| ConstraintType cty -> begin
match deref_constraint_type cty with
| (_, (TCunion _ | TCintersection _)) -> default_subtype env
| _ -> valid env
end
| LoclType ty_sub ->
(match deref ty_sub with
| (_, Tany _) -> valid env
| (_, (Tunion _ | Tintersection _ | Tvar _)) -> default_subtype env
| _ when subtype_env.no_top_bottom -> default env
| _ -> valid env))
| (r_super, Tfun ft_super) ->
(match ety_sub with
| ConstraintType _ -> default_subtype env
| LoclType lty ->
(match deref lty with
| (r_sub, Tfun ft_sub) ->
simplify_subtype_funs
~subtype_env
~check_return:true
~for_override:false
~super_like
r_sub
ft_sub
r_super
ft_super
env
| _ -> default_subtype env))
| (_, Ttuple tyl_super) ->
(match ety_sub with
| ConstraintType _ -> default_subtype env
(* (t1,...,tn) <: (u1,...,un) iff t1<:u1, ... , tn <: un *)
| LoclType lty ->
(match get_node lty with
| Ttuple tyl_sub
when Int.equal (List.length tyl_super) (List.length tyl_sub) ->
wfold_left2
(fun res ty_sub ty_super ->
let ty_super = liken ~super_like env ty_super in
res
&&& simplify_subtype ~subtype_env ~sub_supportdyn ty_sub ty_super)
(env, TL.valid)
tyl_sub
tyl_super
| _ -> default_subtype env))
| ( r_super,
Tshape
{
s_origin = origin_super;
s_unknown_value = shape_kind_super;
s_fields = fdm_super;
} ) ->
(match ety_sub with
| ConstraintType _ -> default_subtype env
| LoclType lty ->
let (sub_supportdyn', env, lty) = TUtils.strip_supportdyn env lty in
let sub_supportdyn = Option.is_some sub_supportdyn || sub_supportdyn' in
(match deref lty with
| ( r_sub,
Tshape
{
s_origin = origin_sub;
s_unknown_value = shape_kind_sub;
s_fields = fdm_sub;
} ) ->
if same_type_origin origin_super origin_sub then
(* Fast path for shape types: if they have the same origin,
* they are equal type. *)
valid env
else
simplify_subtype_shape
~subtype_env
~env
~this_ty
~super_like
(sub_supportdyn, r_sub, shape_kind_sub, fdm_sub)
(super_supportdyn, r_super, shape_kind_super, fdm_super)
| _ -> default_subtype env))
| (_, Tvec_or_dict _) ->
(match ety_sub with
| ConstraintType _ -> default_subtype env
| LoclType lty ->
(match (get_node lty, get_node ty_super) with
| (Tvec_or_dict (tk_sub, tv_sub), Tvec_or_dict (tk_super, tv_super)) ->
let tv_super = liken ~super_like env tv_super in
let tk_super = liken ~super_like env tk_super in
env
|> simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
tk_sub
tk_super
&&& simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
tv_sub
tv_super
| ( Tclass ((_, n), _, [tk_sub; tv_sub]),
Tvec_or_dict (tk_super, tv_super) )
when String.equal n SN.Collections.cDict ->
let tv_super = liken ~super_like env tv_super in
let tk_super = liken ~super_like env tk_super in
env
|> simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
tk_sub
tk_super
&&& simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
tv_sub
tv_super
| (Tclass ((_, n), _, [tv_sub]), Tvec_or_dict (tk_super, tv_super))
when String.equal n SN.Collections.cVec ->
let pos = get_pos lty in
let tk_sub = MakeType.int (Reason.Ridx_vector_from_decl pos) in
let tv_super = liken ~super_like env tv_super in
let tk_super = liken ~super_like env tk_super in
env
|> simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
tk_sub
tk_super
&&& simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
tv_sub
tv_super
| _ -> default_subtype env))
(* If t supports dynamic, and t <: u, then t <: supportdyn<u> *)
| (r_supportdyn, Tnewtype (name_super, [tyarg_super], _))
when String.equal name_super SN.Classes.cSupportDyn ->
(match ety_sub with
| ConstraintType _cty ->
(* TODO *)
default_subtype env
| LoclType lty_sub ->
(match deref lty_sub with
| (r, Tnewtype (name_sub, [tyarg_sub], _))
when String.equal name_sub SN.Classes.cSupportDyn ->
env
|> simplify_subtype
~subtype_env
~this_ty
~super_like
~super_supportdyn:true
~sub_supportdyn:(Some r)
tyarg_sub
tyarg_super
| (_, (Tgeneric _ | Tvar _)) -> default_subtype env
| _ ->
let ty_dyn = MakeType.dynamic r_supportdyn in
env
|> simplify_subtype
~subtype_env
~this_ty
~sub_supportdyn
~super_like
~super_supportdyn:true
lty_sub
tyarg_super
&&& simplify_dynamic_aware_subtype
~subtype_env
~this_ty
~sub_supportdyn
lty_sub
ty_dyn))
| (_, Tnewtype (name_super, tyl_super, _)) ->
(match ety_sub with
| ConstraintType _ -> default_subtype env
| LoclType lty ->
(match deref lty with
| (_, Tclass ((_, name_sub), _, _))
when String.equal name_sub name_super && Env.is_enum env name_super ->
valid env
| (_, Tnewtype (name_sub, tyl_sub, _))
when String.equal name_sub name_super ->
if List.is_empty tyl_sub then
valid env
else if Env.is_enum env name_super && Env.is_enum env name_sub then
valid env
else
let td = Env.get_typedef env name_super in
begin
match td with
| Some { td_tparams; _ } ->
let variance_reifiedl =
List.map td_tparams ~f:(fun t ->
(t.tp_variance, t.tp_reified))
in
simplify_subtype_variance_for_non_injective
~subtype_env
~sub_supportdyn
~super_like
name_sub
None
variance_reifiedl
tyl_sub
tyl_super
ety_sub
ety_super
env
| None -> invalid_env env
end
| (r, Toption ty_sub) ->
let ty_null = MakeType.null r in
(* Errors due to `null` should refer to full option type *)
if_unsat
invalid_env
(simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
ty_null
ty_super
env)
&&& simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
ty_sub
ty_super
| (r, Tprim Aast.Tarraykey) ->
let ty_string = MakeType.string r and ty_int = MakeType.int r in
(* Use `if_unsat` so we report arraykey in the error *)
if_unsat
invalid_env
begin
env
|> simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
ty_string
ty_super
&&& simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
ty_int
ty_super
end
| (_, Tgeneric _) when subtype_env.require_completeness ->
default_subtype env
| _ ->
(match Env.get_typedef env name_super with
| Some { td_type = lower; td_vis = Aast.CaseType; td_tparams; _ }
| Some { td_super_constraint = Some lower; td_tparams; _ } ->
let try_lower_bound env =
let ((env, _ty_err_opt), lower_bound) =
(* The this_ty cannot does not need to be set because newtypes
* & case types cannot appear within classes thus cannot us
* the this type. If we ever change that this could needs to
* be changed *)
Phase.localize
~ety_env:
{
empty_expand_env with
substs =
(if List.is_empty tyl_super then
SMap.empty
else
Decl_subst.make_locl td_tparams tyl_super);
}
env
lower
in
simplify_subtype
~subtype_env
~sub_supportdyn:None
lty
lower_bound
env
in
default_subtype env ||| try_lower_bound
| _ -> default_subtype env)))
| (_, Tunapplied_alias n_sup) ->
(match ety_sub with
| ConstraintType _ -> default_subtype env
| LoclType lty ->
(match deref lty with
| (_, Tunapplied_alias n_sub) when String.equal n_sub n_sup -> valid env
| _ -> default_subtype env))
| (r_super, Tneg (Neg_prim tprim_super)) ->
(match ety_sub with
| ConstraintType _ -> default_subtype env
| LoclType ty_sub ->
(match deref ty_sub with
| (r_sub, Tneg (Neg_prim tprim_sub)) ->
simplify_subtype
~subtype_env
~sub_supportdyn:None
~this_ty
(MakeType.prim_type r_super tprim_super)
(MakeType.prim_type r_sub tprim_sub)
env
| (_, Tneg (Neg_class _)) ->
(* not C contains all primitive types, and so can't be a subtype of
not p, which doesn't contain primitive type p *)
invalid_env env
| (_, Tprim tprim_sub) ->
if is_tprim_disjoint tprim_sub tprim_super then
valid env
else
invalid_env env
| (_, Tclass ((_, cname), ex, _))
when String.equal cname SN.Classes.cStringish
&& is_nonexact ex
&& Aast.(
equal_tprim tprim_super Tstring
|| equal_tprim tprim_super Tarraykey) ->
invalid_env env
(* All of these are definitely disjoint from primitive types *)
| (_, (Tfun _ | Ttuple _ | Tshape _ | Tclass _)) -> valid env
| _ -> default_subtype env))
| (_, Tneg (Neg_class (_, c_super))) ->
(match ety_sub with
| ConstraintType _ -> default_subtype env
| LoclType ty_sub ->
(match deref ty_sub with
| (_, Tneg (Neg_class (_, c_sub))) ->
if TUtils.is_sub_class_refl env c_super c_sub then
valid env
else
invalid_env env
| (_, Tneg (Neg_prim _)) ->
(* not p, for any primitive type p contains all class types, and so
can't be a subtype of not c, which doesn't contain class types c *)
invalid_env env
| (_, Tclass ((_, c_sub), _, _)) ->
if is_class_disjoint env c_sub c_super then
valid env
else
invalid_env env
(* All of these are definitely disjoint from class types *)
| (_, (Tfun _ | Ttuple _ | Tshape _ | Tprim _)) -> valid env
| _ -> default_subtype env))
| (r_super, Tclass (x_super, Nonexact cr_super, tyl_super))
when (not (Class_refinement.is_empty cr_super))
&& (subtype_env.require_soundness
|| (* To deal with refinements, the code below generates a
* constraint type. That is currently not supported when
* require_soundness is not set (see below in the function
* decompose_subtype_add_prop). Consequently, if soundness
* is not required, we treat the refinement information
* only if we know for sure that we can discharge it on
* the spot; e.g., when ety_sub is a class-ish. This
* limits the information lost by skipping refinements. *)
TUtils.is_class_i ety_sub) ->
(* We discharge class refinements before anything
* else ... *)
Class_refinement.fold_refined_consts
cr_super
~init:(valid env)
~f:(fun type_id { rc_bound; _ } (env, prop) ->
(env, prop)
&&&
let (htm_lower, htm_upper) =
match rc_bound with
| TRexact ty -> (ty, ty)
| TRloose { tr_lower; tr_upper } ->
let loty = MakeType.union r_super tr_lower in
let upty = MakeType.intersection r_super tr_upper in
(loty, upty)
in
let htm_ty =
let htm = { htm_id = type_id; htm_lower; htm_upper } in
mk_constraint_type (r_super, Thas_type_member htm)
in
simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
~super_like
ety_sub
(ConstraintType htm_ty))
&&&
(* ... then recursively check the class with all the
* refinements dropped. *)
let ty_super = mk (r_super, Tclass (x_super, nonexact, tyl_super)) in
simplify_subtype_i
~subtype_env
~sub_supportdyn
~this_ty
~super_like
ety_sub
(LoclType ty_super)
| (_, Tclass ((_, class_name), exact_super, tyl_super)) ->
(match ety_sub with
| ConstraintType _ -> default_subtype env
| LoclType ty_sub ->
(match deref ty_sub with
| (_, Tnewtype (enum_name, _, _))
when String.equal enum_name class_name
&& is_nonexact exact_super
&& Env.is_enum env enum_name ->
valid env
| (_, Tnewtype (cid, _, _))
when String.equal class_name SN.Classes.cHH_BuiltinEnum
&& Env.is_enum env cid ->
(match tyl_super with
| [ty_super'] ->
env
|> simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
ty_sub
ty_super'
| _ -> default_subtype env)
| (_, Tnewtype (enum_name, _, _))
when String.equal enum_name class_name && Env.is_enum env enum_name ->
valid env
| (_, Tnewtype (enum_name, _, _))
when Env.is_enum env enum_name
&& String.equal class_name SN.Classes.cXHPChild ->
valid env
| (_, Tprim Nast.(Tstring | Tarraykey | Tint | Tfloat | Tnum))
when String.equal class_name SN.Classes.cXHPChild
&& is_nonexact exact_super ->
valid env
| (_, Tprim Nast.Tstring)
when String.equal class_name SN.Classes.cStringish
&& is_nonexact exact_super ->
valid env
(* Match what's done in unify for non-strict code *)
| (_, Tclass _) ->
simplify_subtype_classes
~fail
~subtype_env
~sub_supportdyn
~this_ty
~super_like
ty_sub
ty_super
env
| (_r_sub, Tvec_or_dict (_, tv)) ->
(match (exact_super, tyl_super) with
| (Nonexact _, [tv_super])
when String.equal class_name SN.Collections.cTraversable
|| String.equal class_name SN.Collections.cContainer ->
(* vec<tv> <: Traversable<tv_super>
* iff tv <: tv_super
* Likewise for vec<tv> <: Container<tv_super>
* and map<_,tv> <: Traversable<tv_super>
* and map<_,tv> <: Container<tv_super>
*)
simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
tv
tv_super
env
| (Nonexact _, [tk_super; tv_super])
when String.equal class_name SN.Collections.cKeyedTraversable
|| String.equal class_name SN.Collections.cKeyedContainer
|| String.equal class_name SN.Collections.cAnyArray ->
(match get_node ty_sub with
| Tvec_or_dict (tk, _) ->
env
|> simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
tk
tk_super
&&& simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
tv
tv_super
| _ -> default_subtype env)
| (Nonexact _, [])
when String.equal class_name SN.Collections.cKeyedTraversable
|| String.equal class_name SN.Collections.cKeyedContainer
|| String.equal class_name SN.Collections.cAnyArray ->
(* All arrays are subtypes of the untyped KeyedContainer / Traversables *)
valid env
| (_, _) -> default_subtype env)
| _ -> default_subtype env)))
and simplify_subtype_shape
~(subtype_env : subtype_env)
~(env : env)
~(this_ty : locl_ty option)
?(super_like = false)
(supportdyn_sub, r_sub, shape_kind_sub, fdm_sub)
(supportdyn_super, r_super, shape_kind_super, fdm_super) =
(*
Shape projection for shape type `s` and field `f` (`s |_ f`) is defined as:
- if `f` appears in `s` as `f => ty` then `s |_ f` = `Required ty`
- if `f` appears in `s` as `?f => ty` then `s |_ f` = `Optional ty`
- if `f` does not appear in `s` and `s` is closed, then `s |_ f` = `Absent`
- if `f` does not appear in `s` and `s` is open, then `s |_ f` = `Optional mixed`
EXCEPT
- `?f => nothing` should be ignored, and treated as `Absent`.
Such a field cannot be given a value, and so is effectively not present.
*)
let shape_projection ~supportdyn field_name shape_kind shape_map r =
let make_supportdyn ty =
if
supportdyn
&& not
(is_sub_type_for_union_i
env
(LoclType ty)
(LoclType (MakeType.supportdyn_mixed ~mixed_reason:r r)))
then
MakeType.supportdyn r ty
else
ty
in
match TShapeMap.find_opt field_name shape_map with
| Some { sft_ty; sft_optional } ->
(match (deref sft_ty, sft_optional) with
| ((_, Tunion []), true) -> `Absent
| (_, true) -> `Optional (make_supportdyn sft_ty)
| (_, false) -> `Required (make_supportdyn sft_ty))
| None ->
if TUtils.is_nothing env shape_kind then
`Absent
else
let printable_name = TUtils.get_printable_shape_field_name field_name in
let ty =
with_reason
shape_kind
(Reason.Rmissing_optional_field (Reason.to_pos r, printable_name))
in
`Optional (make_supportdyn ty)
in
(*
For two particular projections `p1` and `p2`, `p1` <: `p2` iff:
- `p1` = `Required ty1`, `p2` = `Required ty2`, and `ty1` <: `ty2`
- `p1` = `Required ty1`, `p2` = `Optional ty2`, and `ty1` <: `ty2`
- `p1` = `Optional ty1`, `p2` = `Optional ty2`, and `ty1` <: `ty2`
- `p1` = `Absent`, `p2` = `Optional ty2`
- `p1` = `Absent`, `p2` = `Absent`
We therefore need to handle all other cases appropriately.
*)
let simplify_subtype_shape_projection
(r_sub, proj_sub) (r_super, proj_super) field_name res =
let field_pos = TShapeField.pos field_name in
let printable_name = TUtils.get_printable_shape_field_name field_name in
match (proj_sub, proj_super) with
(***** "Successful" cases - 5 / 9 total cases *****)
| (`Required sub_ty, `Required super_ty)
| (`Required sub_ty, `Optional super_ty)
| (`Optional sub_ty, `Optional super_ty) ->
let super_ty = liken ~super_like env super_ty in
res
&&& simplify_subtype
~subtype_env
~sub_supportdyn:
(if supportdyn_sub then
Some r_sub
else
None)
~this_ty
sub_ty
super_ty
| (`Absent, `Optional _)
| (`Absent, `Absent) ->
res
(***** Error cases - 4 / 9 total cases *****)
| (`Required _, `Absent)
| (`Optional _, `Absent) ->
let ty_err_opt =
Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Missing_field
{
pos = Reason.to_pos r_super;
decl_pos = field_pos;
name = printable_name;
})
in
with_error ty_err_opt res
| (`Optional _, `Required super_ty) ->
let ty_err_opt =
Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Required_field_is_optional
{
pos = Reason.to_pos r_sub;
decl_pos = Reason.to_pos r_super;
name = printable_name;
def_pos = get_pos super_ty;
})
in
with_error ty_err_opt res
| (`Absent, `Required _) ->
let quickfixes_opt =
match r_sub with
| Reason.Rshape_literal p ->
let fix_pos =
Pos.shrink_to_end (Pos.shrink_by_one_char_both_sides p)
in
Some
[
Quickfix.make
~title:("Add field " ^ Markdown_lite.md_codify printable_name)
~new_text:(Printf.sprintf ", '%s' => TODO" printable_name)
fix_pos;
]
| _ -> None
in
let ty_err_opt =
Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
let on_error =
Option.value_map
~default:on_error
~f:(Reasons_callback.add_quickfixes on_error)
quickfixes_opt
in
apply_reasons ~on_error
@@ Secondary.Missing_field
{
decl_pos = field_pos;
pos = Reason.to_pos r_sub;
name = printable_name;
})
in
with_error ty_err_opt res
in
(* Helper function to project out a field and then simplify subtype *)
let shape_project_and_simplify_subtype
(supportdyn_sub, r_sub, shape_kind_sub, shape_map_sub)
(supportdyn_super, r_super, shape_kind_super, shape_map_super)
field_name
res =
let proj_sub =
shape_projection
~supportdyn:supportdyn_sub
field_name
shape_kind_sub
shape_map_sub
r_sub
in
let proj_super =
shape_projection
~supportdyn:supportdyn_super
field_name
shape_kind_super
shape_map_super
r_super
in
simplify_subtype_shape_projection
(r_sub, proj_sub)
(r_super, proj_super)
field_name
res
in
match
( TUtils.is_nothing env shape_kind_sub,
TUtils.is_nothing env shape_kind_super )
with
(* An open shape cannot subtype a closed shape *)
| (false, true) ->
let fail =
Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Shape_fields_unknown
{
pos = Reason.to_pos r_sub;
decl_pos = Reason.to_pos r_super;
})
in
invalid ~fail env
(* Otherwise, all projections must subtype *)
| _ ->
TShapeSet.fold
(shape_project_and_simplify_subtype
(supportdyn_sub, r_sub, shape_kind_sub, fdm_sub)
(supportdyn_super, r_super, shape_kind_super, fdm_super))
(TShapeSet.of_list (TShapeMap.keys fdm_sub @ TShapeMap.keys fdm_super))
(env, TL.valid)
(* Suptyping when the two types are classish *)
and simplify_subtype_classes
~fail
~(subtype_env : subtype_env)
~(sub_supportdyn : Reason.t option)
~(this_ty : locl_ty option)
~(super_like : bool)
ty_sub
ty_super
env : env * TL.subtype_prop =
let invalid_env = invalid ~fail in
let ( ||| ) = ( ||| ) ~fail in
match (deref ty_sub, deref ty_super) with
| ( (r_sub, Tclass (x_sub, exact_sub, tyl_sub)),
(_r_super, Tclass (x_super, exact_super, tyl_super)) ) ->
let (cid_super, cid_sub) = (snd x_super, snd x_sub) in
let (exact_match, both_exact) =
match (exact_sub, exact_super) with
| (Nonexact _, Exact) -> (false, false)
| (Exact, Exact) -> (true, true)
| (_, _) -> (true, false)
in
if String.equal cid_super cid_sub then
if List.is_empty tyl_sub && List.is_empty tyl_super && exact_match then
valid env
else
(* This is side-effecting as it registers a dependency *)
let class_def_sub = Env.get_class env cid_sub in
(* If class is final then exactness is superfluous *)
let (has_generics, is_final) =
match class_def_sub with
| Some tc -> (not (List.is_empty (Cls.tparams tc)), Cls.final tc)
| None -> (false, false)
in
if not (exact_match || is_final) then
invalid_env env
else if has_generics && List.is_empty tyl_super then
(* C<t> <: C where C represents all possible instantiations of C's generics *)
valid env
else if has_generics && List.is_empty tyl_sub then
(* C </: C<t>, since C's generic can be instantiated to other things than t *)
invalid_env env
else
let variance_reifiedl =
if List.is_empty tyl_sub then
[]
else if both_exact then
(* Subtyping exact class types following variance
* annotations is unsound in general (see T142810099).
* When the class is exact, we must treat all generic
* parameters as invariant.
*)
List.map tyl_sub ~f:(fun _ -> (Ast_defs.Invariant, Aast.Erased))
else
match class_def_sub with
| None ->
List.map tyl_sub ~f:(fun _ -> (Ast_defs.Invariant, Aast.Erased))
| Some class_sub ->
List.map (Cls.tparams class_sub) ~f:(fun t ->
(t.tp_variance, t.tp_reified))
in
simplify_subtype_variance_for_injective
~subtype_env
~sub_supportdyn
~super_like
cid_sub
class_def_sub
variance_reifiedl
tyl_sub
tyl_super
env
else if not exact_match then
invalid_env env
else
let class_def_sub = Env.get_class env cid_sub in
(match class_def_sub with
| None ->
(* This should have been caught already in the naming phase *)
valid env
| Some class_sub ->
(* We handle the case where a generic A<T> is used as A for the sub-class.
This works because there will be no locls to substitute for type parameters
T in the type build by get_ancestor. If T does show up in that type, then
the call to simplify subtype will fail. This is what we expect since we
would need it to be a sub-type of the super-type for all T. If T is not there,
then simplify_subtype should succeed. *)
let ety_env =
{
empty_expand_env with
substs = TUtils.make_locl_subst_for_class_tparams class_sub tyl_sub;
(* FIXME(T59448452): Unsound in general *)
this_ty = Option.value this_ty ~default:ty_sub;
}
in
let up_obj = Cls.get_ancestor class_sub cid_super in
(match up_obj with
| Some up_obj ->
(* Since we have provided no `Typing_error.Reasons_callback.t`
* in the `expand_env`, this will not generate any errors *)
let ((env, _ty_err_opt), up_obj) =
Phase.localize ~ety_env env up_obj
in
simplify_subtype_classes
~fail
~subtype_env
~sub_supportdyn
~this_ty
~super_like
up_obj
ty_super
env
| None ->
if
Ast_defs.is_c_trait (Cls.kind class_sub)
|| Ast_defs.is_c_interface (Cls.kind class_sub)
then
let reqs_class =
List.map
(Cls.all_ancestor_req_class_requirements class_sub)
~f:snd
in
let rec try_upper_bounds_on_this up_objs env =
match up_objs with
| [] ->
(* It's crucial that we don't lose updates to tpenv in
* env that were introduced by Phase.localize.
* TODO: avoid this requirement *)
invalid_env env
| ub_obj_typ :: up_objs
when List.mem reqs_class ub_obj_typ ~equal:equal_decl_ty ->
(* `require class` constraints do not induce subtyping,
* so skipping them *)
try_upper_bounds_on_this up_objs env
| ub_obj_typ :: up_objs ->
(* A trait is never the runtime type, but it can be used
* as a constraint if it has requirements or where
* constraints for its using classes *)
(* Since we have provided no `Typing_error.Reasons_callback.t`
* in the `expand_env`, this will not generate any errors *)
let ((env, _ty_err_opt), ub_obj_typ) =
Phase.localize ~ety_env env ub_obj_typ
in
env
|> simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
(mk (r_sub, get_node ub_obj_typ))
ty_super
||| try_upper_bounds_on_this up_objs
in
try_upper_bounds_on_this (Cls.upper_bounds_on_this class_sub) env
else
invalid_env env))
| (_, _) -> invalid_env env
and simplify_subtype_can_index
~subtype_env ~sub_supportdyn ~this_ty ~fail ty_sub ty_super (_r, _ci) env =
(* TODO: implement *)
default_subtype
~subtype_env
~sub_supportdyn
~this_ty
~fail
env
ty_sub
ty_super
and simplify_subtype_can_traverse
~subtype_env
~sub_supportdyn
~this_ty
~fail
ty_sub
ty_super
((_r : Reason.t), ct)
env =
log_subtype_i
~level:2
~this_ty
~function_name:"simplify_subtype_can_traverse"
env
ty_sub
ty_super;
match ty_sub with
| ConstraintType _ ->
default_subtype
~subtype_env
~sub_supportdyn
~this_ty
~fail
env
ty_sub
ty_super
| LoclType lty_sub ->
if TUtils.is_tyvar_error env lty_sub then
let trav_ty = can_traverse_to_iface ct in
simplify_subtype ~subtype_env ~sub_supportdyn ~this_ty lty_sub trav_ty env
else
let subtype_with_dynamic () =
simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
lty_sub
ct.ct_val
env
&&&
match ct.ct_key with
| None -> valid
| Some ct_key ->
simplify_subtype ~subtype_env ~sub_supportdyn ~this_ty lty_sub ct_key
in
(match get_node lty_sub with
| Tdynamic -> subtype_with_dynamic ()
| _
when Option.is_some sub_supportdyn
&& TypecheckerOptions.enable_sound_dynamic env.genv.tcopt
&& Tast.is_under_dynamic_assumptions env.checked ->
subtype_with_dynamic ()
| Tclass _
| Tvec_or_dict _
| Tany _ ->
let trav_ty = can_traverse_to_iface ct in
simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
lty_sub
trav_ty
env
| _ ->
default_subtype
~subtype_env
~sub_supportdyn
~this_ty
~fail
env
ty_sub
ty_super)
and simplify_subtype_has_type_member
~subtype_env ~sub_supportdyn ~this_ty ~fail ty_sub (r, htm) env =
let { htm_id = memid; htm_lower = memloty; htm_upper = memupty } = htm in
let htmty = ConstraintType (mk_constraint_type (r, Thas_type_member htm)) in
log_subtype_i
~level:2
~this_ty
~function_name:"simplify_subtype_has_type_member"
env
ty_sub
htmty;
let (env, ety_sub) = Env.expand_internal_type env ty_sub in
let default_subtype env =
default_subtype
~subtype_env
~sub_supportdyn
~this_ty
~fail
env
ety_sub
htmty
in
let simplify_subtype_bound kind ~bound ty env =
let on_error =
Option.map subtype_env.on_error ~f:(fun on_error ->
let open Typing_error in
let pos = Reason.to_pos (get_reason bound) in
Reasons_callback.prepend_on_apply
on_error
(Secondary.Violated_refinement_constraint { cstr = (kind, pos) }))
in
let subtype_env = { subtype_env with on_error } in
let this_ty = None in
match kind with
| `As ->
simplify_subtype ~subtype_env ~sub_supportdyn:None ~this_ty ty bound env
| `Super ->
simplify_subtype ~subtype_env ~sub_supportdyn:None ~this_ty bound ty env
in
match ety_sub with
| ConstraintType _ -> invalid ~fail env
| LoclType ty_sub ->
let concrete_rigid_tvar_access env ucckind bndtys =
(* First, we try to discharge the subtype query on the bound; if
* that fails, we mint a fresh rigid type variable to represent
* the concrete type constant and try to solve the query using it *)
let ( ||| ) = ( ||| ) ~fail in
let bndty = MakeType.intersection (get_reason ty_sub) bndtys in
simplify_subtype_i
~subtype_env
~sub_supportdyn:None
~this_ty
(LoclType bndty)
htmty
env
||| fun env ->
(* TODO(refinements): The treatment of `this_ty` below is
* no good; see below. *)
let (env, dtmemty) =
Typing_type_member.make_type_member
env
~this_ty:(Option.value this_ty ~default:ty_sub)
~on_error:subtype_env.on_error
ucckind
bndtys
(Reason.to_pos r, memid)
in
simplify_subtype_bound `As dtmemty ~bound:memupty env
&&& simplify_subtype_bound `Super ~bound:memloty dtmemty
in
(match deref ty_sub with
| (_r_sub, Tclass (x_sub, exact_sub, _tyl_sub)) ->
let (env, type_member) =
(* TODO(refinements): The treatment of `this_ty` below is
* no good; we should not default to `ty_sub`. `this_ty`
* will be used when a type constant refers to another
* constant either in its def or in its bounds.
* See related FIXME(T59448452) above. *)
Typing_type_member.lookup_class_type_member
env
~this_ty:(Option.value this_ty ~default:ty_sub)
~on_error:subtype_env.on_error
(x_sub, exact_sub)
(Reason.to_pos r, memid)
in
(match type_member with
| Typing_type_member.Error err -> invalid ~fail:err env
| Typing_type_member.Exact ty ->
simplify_subtype_bound `As ty ~bound:memupty env
&&& simplify_subtype_bound `Super ~bound:memloty ty
| Typing_type_member.Abstract { name; lower = loty; upper = upty } ->
let r_bnd = Reason.Rtconst_no_cstr name in
let loty = Option.value ~default:(MakeType.nothing r_bnd) loty in
let upty = Option.value ~default:(MakeType.mixed r_bnd) upty in
(* In case the refinement is exact we check that upty <: loty;
* doing the check early gives us a better chance at generating
* good error messages. The unification errors we get when
* doing this check are usually unhelpful, so we drop them. *)
let is_exact = phys_equal memloty memupty in
(if is_exact then
let drop_sub_reasons =
Option.map
subtype_env.on_error
~f:Typing_error.Reasons_callback.drop_reasons_on_apply
in
let subtype_env = { subtype_env with on_error = drop_sub_reasons } in
simplify_subtype
~subtype_env
~sub_supportdyn:None
~this_ty
upty
loty
env
else
valid env)
&&& simplify_subtype_bound `As upty ~bound:memupty
&&& simplify_subtype_bound `Super ~bound:memloty loty)
| (_r_sub, Tdependent (DTexpr eid, bndty)) ->
concrete_rigid_tvar_access env (Typing_type_member.EDT eid) [bndty]
| (_r_sub, Tgeneric (s, ty_args)) when String.equal s SN.Typehints.this ->
let bnd_tys = Typing_set.elements (Env.get_upper_bounds env s ty_args) in
concrete_rigid_tvar_access env Typing_type_member.This bnd_tys
| (_, (Tvar _ | Tgeneric _ | Tunion _ | Tintersection _)) ->
default_subtype env
| _ -> invalid ~fail env)
and simplify_subtype_has_member
~subtype_env
~sub_supportdyn
~this_ty
~fail
?(nullsafe : Reason.t option)
ty_sub
(r, has_member_ty)
env =
let using_new_method_call_inference =
TypecheckerOptions.method_call_inference (Env.get_tcopt env)
in
let {
hm_name = (name_pos, name_) as name;
hm_type = member_ty;
hm_class_id = class_id;
hm_explicit_targs = explicit_targs;
} =
has_member_ty
in
let is_method = Option.is_some explicit_targs in
(* If `nullsafe` is `Some _`, we are allowing the object type on LHS to be nullable. *)
let mk_maybe_nullable env ty =
match nullsafe with
| None -> (env, ty)
| Some r_null ->
let null_ty = MakeType.null r_null in
Typing_union.union_i env r_null ty null_ty
in
let (env, maybe_nullable_ty_super) =
let ty_super = mk_constraint_type (r, Thas_member has_member_ty) in
mk_maybe_nullable env (ConstraintType ty_super)
in
log_subtype_i
~level:2
~this_ty
~function_name:"simplify_subtype_has_member"
env
ty_sub
maybe_nullable_ty_super;
let (env, ety_sub) = Env.expand_internal_type env ty_sub in
let default_subtype env =
default_subtype
~subtype_env
~sub_supportdyn
~this_ty
~fail
env
ety_sub
maybe_nullable_ty_super
in
match ety_sub with
| ConstraintType cty ->
(match deref_constraint_type cty with
| ( _,
Thas_member
{
hm_name = name_sub;
hm_type = ty_sub;
hm_class_id = cid_sub;
hm_explicit_targs = explicit_targs_sub;
} ) ->
if
let targ_equal (_, (_, hint1)) (_, (_, hint2)) =
Aast_defs.equal_hint_ hint1 hint2
in
String.equal (snd name_sub) name_
&& class_id_equal cid_sub class_id
&& Option.equal
(List.equal targ_equal)
explicit_targs_sub
explicit_targs
then
simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
ty_sub
member_ty
env
else
invalid ~fail env
| _ -> default_subtype env)
| LoclType ty_sub ->
(match deref ty_sub with
| (_, (Tvar _ | Tunion _)) -> default_subtype env
| (r_null, Tprim Aast.Tnull) when using_new_method_call_inference ->
if Option.is_some nullsafe then
valid env
else
invalid
env
~fail:
(Some
Typing_error.(
primary
@@ Primary.Null_member
{
pos = name_pos;
obj_pos_opt = None;
member_name = name_;
reason =
lazy (Reason.to_string "This can be null" r_null);
kind =
(if is_method then
`method_
else
`property);
ctxt = `read;
}))
| (r_option, Toption option_ty) when using_new_method_call_inference ->
if Option.is_some nullsafe then
simplify_subtype_has_member
~subtype_env
~sub_supportdyn
~this_ty
~fail
?nullsafe
(LoclType option_ty)
(r, has_member_ty)
env
else
let (env, option_ty) = Env.expand_type env option_ty in
(match get_node option_ty with
| Tnonnull ->
invalid
env
~fail:
(Some
Typing_error.(
primary
@@ Primary.Top_member
{
pos = name_pos;
name = name_;
ctxt = `read;
kind =
(if is_method then
`method_
else
`property);
is_nullable = true;
decl_pos = Reason.to_pos r_option;
ty_name = lazy (Typing_print.error env ty_sub);
(* Subtyping already gives these reasons *)
ty_reasons = lazy [];
}))
| _ ->
invalid
env
~fail:
(Some
Typing_error.(
primary
@@ Primary.Null_member
{
pos = name_pos;
obj_pos_opt = None;
member_name = name_;
reason =
lazy (Reason.to_string "This can be null" r_option);
kind =
(if is_method then
`method_
else
`property);
ctxt = `read;
})))
| (_, Tintersection tyl)
when let (_, non_ty_opt, _) = find_type_with_exact_negation env tyl in
Option.is_some non_ty_opt ->
(* use default_subtype to perform: A & B <: C <=> A <: C | !B *)
default_subtype env
| (r_inter, Tintersection []) ->
(* Tintersection [] = mixed *)
invalid
env
~fail:
(Some
Typing_error.(
primary
@@ Primary.Top_member
{
pos = name_pos;
name = name_;
is_nullable = true;
kind =
(if is_method then
`method_
else
`property);
ctxt = `read;
decl_pos = Reason.to_pos r_inter;
ty_name = lazy (Typing_print.error env ty_sub);
(* Subtyping already gives these reasons *)
ty_reasons = lazy [];
}))
| (r_inter, Tintersection tyl) when using_new_method_call_inference ->
let (env, tyl) = List.map_env ~f:Env.expand_type env tyl in
let subtype_fresh_has_member_ty env ty_sub =
let (env, fresh_tyvar) = Env.fresh_type env name_pos in
let env = Env.set_tyvar_variance env fresh_tyvar in
let fresh_has_member_ty =
mk_constraint_type
(r, Thas_member { has_member_ty with hm_type = fresh_tyvar })
in
let (env, maybe_nullable_fresh_has_member_ty) =
mk_maybe_nullable env (ConstraintType fresh_has_member_ty)
in
let (env, ty_err_opt) =
sub_type_inner
env
~subtype_env
~sub_supportdyn
~this_ty
(LoclType ty_sub)
maybe_nullable_fresh_has_member_ty
in
match ty_err_opt with
| None ->
let (env, _ty_err_opt) =
match get_var fresh_tyvar with
| Some var ->
(* TODO: can this actually generate an error? *)
Typing_solver.solve_to_equal_bound_or_wrt_variance
env
Reason.Rnone
var
| None -> (env, None)
in
((env, None), Some fresh_tyvar)
| Some _ -> ((env, ty_err_opt), None)
in
let ((env, ty_err_opt), fresh_tyvar_opts) =
TUtils.run_on_intersection_with_ty_err
env
tyl
~f:subtype_fresh_has_member_ty
in
let fresh_tyvars = List.filter_map ~f:Fn.id fresh_tyvar_opts in
if List.is_empty fresh_tyvars then
invalid ~fail:ty_err_opt env
else
let (env, intersection_ty) =
Inter.intersect_list env r_inter fresh_tyvars
in
simplify_subtype
~subtype_env
~sub_supportdyn
~this_ty
intersection_ty
member_ty
env
| (r1, Tnewtype (n, _, newtype_ty)) ->
let sub_supportdyn =
match sub_supportdyn with
| None ->
if String.equal n SN.Classes.cSupportDyn then
Some r1
else
None
| _ -> sub_supportdyn
in
simplify_subtype_has_member
~subtype_env
~sub_supportdyn
~this_ty
~fail
?nullsafe
(LoclType newtype_ty)
(r, has_member_ty)
env
(* TODO
| (_, Tdependent _) ->
| (_, Tgeneric _) ->
*)
| _ ->
let explicit_targs =
match explicit_targs with
| None -> []
| Some targs -> targs
in
let (res, (obj_get_ty, _tal)) =
Typing_object_get.obj_get
~obj_pos:name_pos
(* `~obj_pos:name_pos` is a lie: `name_pos` is the rhs of `->` or `?->` *)
~is_method
~inst_meth:false
~meth_caller:false
~coerce_from_ty:None
~nullsafe
~explicit_targs
~class_id
~member_id:name
~on_error:Typing_error.Callback.unify_error
env
ty_sub
in
let prop =
match res with
| (env, None) -> valid env
| (env, Some ty_err) ->
let on_error = add_obj_get_quickfixes ty_err subtype_env.on_error in
(* TODO - this needs to somehow(?) account for the fact that the old
code considered FIXMEs in this position *)
let fail =
Option.map
on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error @@ Secondary.Of_error ty_err)
in
invalid env ~fail
in
prop
&&& simplify_subtype
~subtype_env
~sub_supportdyn:None
~this_ty
obj_get_ty
member_ty)
(* Given an injective type constructor C (e.g., a class)
* C<t1, .., tn> <: C<u1, .., un> iff
* t1 <:v1> u1 /\ ... /\ tn <:vn> un
* where vi is the variance of the i'th generic parameter of C,
* and <:v denotes the appropriate direction of subtyping for variance v *)
and simplify_subtype_variance_for_injective
~(subtype_env : subtype_env)
~(sub_supportdyn : Reason.t option)
?(super_like = false)
(cid : string)
(class_sub : Cls.t option) =
(* Before looping through the generic arguments, check to see if we should push
supportdyn onto them. This depends on the generic class itself. *)
let sub_supportdyn =
match (sub_supportdyn, class_sub) with
| (None, _)
| (_, None) ->
None
| (Some _, Some class_sub) ->
if
String.equal cid SN.Collections.cTraversable
|| String.equal cid SN.Collections.cKeyedTraversable
|| String.equal cid SN.Collections.cContainer
|| Cls.has_ancestor class_sub SN.Collections.cContainer
then
sub_supportdyn
else
None
in
simplify_subtype_variance_for_injective_loop
~subtype_env
~sub_supportdyn
~super_like
cid
and simplify_subtype_variance_for_injective_loop
~(subtype_env : subtype_env)
~(sub_supportdyn : Reason.t option)
?(super_like = false)
(cid : string)
(variance_reifiedl : (Ast_defs.variance * Aast.reify_kind) list)
(children_tyl : locl_ty list)
(super_tyl : locl_ty list) : env -> env * TL.subtype_prop =
fun env ->
let simplify_subtype reify_kind =
(* When doing coercions from dynamic we treat dynamic as a bottom type. This is generally
correct, except for the case when the generic isn't erased. When a generic is
reified it is enforced as if it is it's own separate class in the runtime. i.e.
In the code:
class Box<reify T> {}
function box_int(): Box<int> { return new Box<~int>(); }
If is enforced like:
class Box<reify T> {}
class Box_int extends Box<int> {}
class Box_like_int extends Box<~int> {}
function box_int(): Box_int { return new Box_like_int(); }
Thus we cannot push the like type to the outside of generic like we can
we erased generics.
*)
let subtype_env =
if
(not Aast.(equal_reify_kind reify_kind Erased))
&& coercing_from_dynamic subtype_env
then
{ subtype_env with coerce = None }
else
subtype_env
in
simplify_subtype ~subtype_env ~this_ty:None
in
let simplify_subtype_variance_for_injective =
simplify_subtype_variance_for_injective_loop
~subtype_env
~sub_supportdyn
~super_like
in
match (variance_reifiedl, children_tyl, super_tyl) with
| ([], _, _)
| (_, [], _)
| (_, _, []) ->
valid env
| ( (variance, reify_kind) :: variance_reifiedl,
child :: childrenl,
super :: superl ) ->
let simplify_subtype = simplify_subtype reify_kind in
begin
match variance with
| Ast_defs.Covariant ->
let super = liken ~super_like env super in
simplify_subtype ~sub_supportdyn child super env
| Ast_defs.Contravariant ->
let super =
mk
( Reason.Rcontravariant_generic (get_reason super, cid),
get_node super )
in
simplify_subtype ~sub_supportdyn super child env
| Ast_defs.Invariant ->
let super' =
mk (Reason.Rinvariant_generic (get_reason super, cid), get_node super)
in
env
|> simplify_subtype ~sub_supportdyn child (liken ~super_like env super')
&&& simplify_subtype
~sub_supportdyn
super'
(if is_tyvar super' then
child
else
liken ~super_like env child)
end
&&& simplify_subtype_variance_for_injective
cid
variance_reifiedl
childrenl
superl
(* Given a type constructor N that may not be injective (e.g., a newtype)
* t1 <:v1> u1 /\ ... /\ tn <:vn> un
* implies
* N<t1, .., tn> <: N<u1, .., un>
* where vi is the variance of the i'th generic parameter of N,
* and <:v denotes the appropriate direction of subtyping for variance v.
* However, the reverse direction does not hold. *)
and simplify_subtype_variance_for_non_injective
~(subtype_env : subtype_env)
~sub_supportdyn
~super_like
(cid : string)
class_sub
(variance_reifiedl : (Ast_defs.variance * Aast.reify_kind) list)
(children_tyl : locl_ty list)
(super_tyl : locl_ty list)
ty_sub
ty_super
env =
let ((env, p) as res) =
simplify_subtype_variance_for_injective
~subtype_env
~sub_supportdyn
~super_like
cid
class_sub
variance_reifiedl
children_tyl
super_tyl
env
in
if subtype_env.require_completeness && not (TL.is_valid p) then
(* If we require completeness, then we can still use the incomplete
* N<t1, .., tn> <: N<u1, .., un> to t1 <:v1> u1 /\ ... /\ tn <:vn> un
* simplification if all of the latter constraints already hold.
* If they don't already hold, there is nothing we can (soundly) simplify. *)
if subtype_env.require_soundness then
mk_issubtype_prop
~sub_supportdyn
~coerce:subtype_env.coerce
env
ty_sub
ty_super
else
(env, TL.valid)
else
res
and simplify_subtype_params
~(subtype_env : subtype_env)
~for_override
?(check_params_ifc = false)
(subl : locl_fun_param list)
(superl : locl_fun_param list)
(variadic_sub_ty : bool)
(variadic_super_ty : bool)
env =
let simplify_subtype_params =
simplify_subtype_params ~subtype_env ~for_override
in
let simplify_subtype_params_with_variadic =
simplify_subtype_params_with_variadic ~subtype_env
in
let simplify_supertype_params_with_variadic =
simplify_supertype_params_with_variadic ~subtype_env
in
match (subl, superl) with
(* When either list runs out, we still have to typecheck that
the remaining portion sub/super types with the other's variadic.
For example, if
ChildClass {
public function a(int $x = 0, string ... $args) // superl = [int], super_var = string
}
overrides
ParentClass {
public function a(string ... $args) // subl = [], sub_var = string
}
, there should be an error because the first argument will be checked against
int, not string that is, ChildClass::a("hello") would crash,
but ParentClass::a("hello") wouldn't.
Similarly, if the other list is longer, aka
ChildClass extends ParentClass {
public function a(mixed ... $args) // superl = [], super_var = mixed
}
overrides
ParentClass {
//subl = [string], sub_var = string
public function a(string $x = 0, string ... $args)
}
It should also check that string is a subtype of mixed.
*)
| ([fp], _) when variadic_sub_ty ->
simplify_supertype_params_with_variadic superl fp.fp_type env
| (_, [fp]) when variadic_super_ty ->
simplify_subtype_params_with_variadic subl fp.fp_type env
| ([], _) -> valid env
| (_, []) -> valid env
| (sub :: subl, super :: superl) ->
let { fp_type = ty_sub; _ } = sub in
let { fp_type = ty_super; _ } = super in
let subtype_env_for_param =
(* When overriding in Sound Dynamic, we treat any dynamic-aware subtype of dynamic as a
* subtype of the dynamic type itself
*)
match get_node ty_super.et_type with
| Tdynamic
when TypecheckerOptions.enable_sound_dynamic env.genv.tcopt
&& for_override ->
{ subtype_env with coerce = Some TL.CoerceToDynamic }
| _ -> subtype_env
in
let simplify_subtype_possibly_enforced =
simplify_subtype_possibly_enforced
~subtype_env:subtype_env_for_param
~sub_supportdyn:None
in
(* Check that the calling conventions of the params are compatible. *)
env
|> simplify_param_modes ~subtype_env sub super
&&& simplify_param_readonly ~subtype_env sub super
&&& simplify_param_accept_disposable ~subtype_env sub super
&&& begin
if check_params_ifc then
simplify_param_ifc ~subtype_env sub super
else
valid
end
&&& begin
fun env ->
match (get_fp_mode sub, get_fp_mode super) with
| (FPinout, FPinout) ->
(* Inout parameters are invariant wrt subtyping for function types. *)
env
|> simplify_subtype_possibly_enforced ty_super ty_sub
&&& simplify_subtype_possibly_enforced ty_sub ty_super
| _ -> env |> simplify_subtype_possibly_enforced ty_sub ty_super
end
&&& simplify_subtype_params subl superl variadic_sub_ty variadic_super_ty
and simplify_subtype_params_with_variadic
~(subtype_env : subtype_env)
(subl : locl_fun_param list)
(variadic_ty : locl_possibly_enforced_ty)
env =
let simplify_subtype_possibly_enforced =
simplify_subtype_possibly_enforced ~subtype_env
in
let simplify_subtype_params_with_variadic =
simplify_subtype_params_with_variadic ~subtype_env
in
match subl with
| [] -> valid env
| { fp_type = sub; _ } :: subl ->
env
|> simplify_subtype_possibly_enforced ~sub_supportdyn:None sub variadic_ty
&&& simplify_subtype_params_with_variadic subl variadic_ty
and simplify_subtype_implicit_params
~subtype_env { capability = sub_cap } { capability = super_cap } env =
if TypecheckerOptions.any_coeffects (Env.get_tcopt env) then
let expected = Typing_coeffects.get_type sub_cap in
let got = Typing_coeffects.get_type super_cap in
let reasons =
Typing_error.Secondary.Coeffect_subtyping
{
pos = get_pos got;
cap = Typing_coeffects.pretty env got;
pos_expected = get_pos expected;
cap_expected = Typing_coeffects.pretty env expected;
}
in
let on_error =
Option.map subtype_env.on_error ~f:(fun on_error ->
let err = Typing_error.apply_reasons ~on_error reasons in
Typing_error.(Reasons_callback.always err))
in
let subtype_env = { subtype_env with on_error } in
match (sub_cap, super_cap) with
| (CapTy sub, CapTy super) ->
simplify_subtype ~subtype_env ~sub_supportdyn:None sub super env
| (CapTy sub, CapDefaults _p) ->
simplify_subtype ~subtype_env ~sub_supportdyn:None sub got env
| (CapDefaults _p, CapTy super) ->
simplify_subtype ~subtype_env ~sub_supportdyn:None expected super env
| (CapDefaults _p1, CapDefaults _p2) -> valid env
else
valid env
and simplify_supertype_params_with_variadic
~(subtype_env : subtype_env)
(superl : locl_fun_param list)
(variadic_ty : locl_possibly_enforced_ty)
env =
let simplify_subtype_possibly_enforced =
simplify_subtype_possibly_enforced ~subtype_env
in
let simplify_supertype_params_with_variadic =
simplify_supertype_params_with_variadic ~subtype_env
in
match superl with
| [] -> valid env
| { fp_type = super; _ } :: superl ->
env
|> simplify_subtype_possibly_enforced ~sub_supportdyn:None variadic_ty super
&&& simplify_supertype_params_with_variadic superl variadic_ty
and simplify_param_modes ~subtype_env param1 param2 env =
let { fp_pos = pos1; _ } = param1 in
let { fp_pos = pos2; _ } = param2 in
match (get_fp_mode param1, get_fp_mode param2) with
| (FPnormal, FPnormal)
| (FPinout, FPinout) ->
valid env
| (FPnormal, FPinout) ->
invalid
~fail:
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Inoutness_mismatch { pos = pos2; decl_pos = pos1 }))
env
| (FPinout, FPnormal) ->
invalid
~fail:
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Inoutness_mismatch { pos = pos1; decl_pos = pos2 }))
env
and simplify_param_accept_disposable ~subtype_env param1 param2 env =
let { fp_pos = pos1; _ } = param1 in
let { fp_pos = pos2; _ } = param2 in
match (get_fp_accept_disposable param1, get_fp_accept_disposable param2) with
| (true, false) ->
invalid
~fail:
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Accept_disposable_invariant
{ pos = pos1; decl_pos = pos2 }))
env
| (false, true) ->
invalid
~fail:
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Accept_disposable_invariant
{ pos = pos2; decl_pos = pos1 }))
env
| (_, _) -> valid env
and simplify_param_ifc ~subtype_env sub super env =
let { fp_pos = pos_sub; _ } = sub in
let { fp_pos = pos_super; _ } = super in
(* TODO: also handle <<CanCall>> *)
match (get_fp_ifc_external sub, get_fp_ifc_external super) with
| (true, false) ->
invalid
~fail:
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Ifc_external_contravariant { pos_super; pos_sub }))
env
| _ -> valid env
and simplify_param_readonly ~subtype_env sub super env =
(* The sub param here (as with all simplify_param_* functions)
is actually the parameter on ft_super, since params are contravariant *)
(* Thus we check readonly subtyping covariantly *)
let { fp_pos = pos1; _ } = sub in
let { fp_pos = pos2; _ } = super in
if not (readonly_subtype (get_fp_readonly sub) (get_fp_readonly super)) then
invalid
~fail:
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Readonly_mismatch
{
pos = pos1;
kind = `param;
reason_sub = lazy [(pos2, "This parameter is mutable")];
reason_super =
lazy [(pos1, "But this parameter is readonly")];
}))
env
else
valid env
and ifc_policy_matches (ifc1 : ifc_fun_decl) (ifc2 : ifc_fun_decl) =
match (ifc1, ifc2) with
| (FDPolicied (Some s1), FDPolicied (Some s2)) when String.equal s1 s2 -> true
| (FDPolicied None, FDPolicied None) -> true
(* TODO(T79510128): IFC needs to check that the constraints inferred by the parent entail those by the subtype *)
| (FDInferFlows, FDInferFlows) -> true
| _ -> false
and readonly_subtype (r_sub : bool) (r_super : bool) =
match (r_sub, r_super) with
| (true, false) ->
false (* A readonly value is a supertype of a mutable one *)
| _ -> true
and cross_package_subtype (c_sub : string option) (c_super : string option) =
match (c_sub, c_super) with
| (Some s, Some t) -> String.equal s t
| (Some _, None) -> false
| (None, Some _) -> true
| (None, None) -> true
(* Helper function for subtyping on function types: performs all checks that
* don't involve actual types:
* <<__ReturnDisposable>> attribute
* variadic arity
* <<__Policied>> attribute
* Readonlyness
* <<__CrossPackage>> attribute
*)
and simplify_subtype_funs_attributes
~subtype_env
(r_sub : Reason.t)
(ft_sub : locl_fun_type)
(r_super : Reason.t)
(ft_super : locl_fun_type)
env =
let p_sub = Reason.to_pos r_sub in
let p_super = Reason.to_pos r_super in
let ifc_policy_err_str = function
| FDPolicied (Some s) -> s
| FDPolicied None -> "the existential policy"
| FDInferFlows -> "an inferred policy"
in
let print_cross_pkg_reason (c : string option) (is_sub : bool) =
match c with
| Some s when is_sub ->
Printf.sprintf
"This function is marked `<<__CrossPackage(%s)>>`, so it's only compatible with other functions marked `<<__CrossPackage(%s)>>`"
s
s
| Some s ->
Printf.sprintf "This function is marked <<__CrossPackage(%s)>>" s
| None -> "This function is not cross package"
in
(env, TL.valid)
|> check_with
(ifc_policy_matches ft_sub.ft_ifc_decl ft_super.ft_ifc_decl)
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Ifc_policy_mismatch
{
pos = p_sub;
policy = ifc_policy_err_str ft_sub.ft_ifc_decl;
pos_super = p_super;
policy_super = ifc_policy_err_str ft_super.ft_ifc_decl;
}))
|> check_with
(readonly_subtype
(* Readonly this is contravariant, so check ft_super_ro <: ft_sub_ro *)
(get_ft_readonly_this ft_super)
(get_ft_readonly_this ft_sub))
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Readonly_mismatch
{
pos = p_sub;
kind = `fn;
reason_sub =
lazy [(p_sub, "This function is not marked readonly")];
reason_super =
lazy [(p_super, "This function is marked readonly")];
}))
|> check_with
(readonly_subtype
(* Readonly return is covariant, so check ft_sub <: ft_super *)
(get_ft_returns_readonly ft_sub)
(get_ft_returns_readonly ft_super))
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Readonly_mismatch
{
pos = p_sub;
kind = `fn_return;
reason_sub =
lazy
[(p_sub, "This function returns a readonly value")];
reason_super =
lazy
[
( p_super,
"This function does not return a readonly value"
);
];
}))
|> check_with
(cross_package_subtype ft_sub.ft_cross_package ft_super.ft_cross_package)
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Cross_package_mismatch
{
pos = p_sub;
reason_sub =
lazy
[
( p_sub,
print_cross_pkg_reason
ft_sub.ft_cross_package
true );
];
reason_super =
lazy
[
( p_super,
print_cross_pkg_reason
ft_super.ft_cross_package
false );
];
}))
|> check_with
(Bool.equal
(get_ft_return_disposable ft_sub)
(get_ft_return_disposable ft_super))
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Return_disposable_mismatch
{
pos_super = p_super;
pos_sub = p_sub;
is_marked_return_disposable =
get_ft_return_disposable ft_super;
}))
|> check_with
(arity_min ft_sub <= arity_min ft_super)
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Fun_too_many_args
{
expected = arity_min ft_super;
actual = arity_min ft_sub;
pos = p_sub;
decl_pos = p_super;
}))
|> fun res ->
let ft_sub_variadic =
if get_ft_variadic ft_sub then
List.last ft_sub.ft_params
else
None
in
let ft_super_variadic =
if get_ft_variadic ft_super then
List.last ft_super.ft_params
else
None
in
match (ft_sub_variadic, ft_super_variadic) with
| (Some { fp_name = None; _ }, Some { fp_name = Some _; _ }) ->
(* The HHVM runtime ignores "..." entirely, but knows about
* "...$args"; for contexts for which the runtime enforces method
* compatibility (currently, inheritance from abstract/interface
* methods), letting "..." override "...$args" would result in method
* compatibility errors at runtime. *)
with_error
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Fun_variadicity_hh_vs_php56
{ pos = p_sub; decl_pos = p_super }))
res
| (None, None) ->
let sub_max = List.length ft_sub.ft_params in
let super_max = List.length ft_super.ft_params in
if sub_max < super_max then
with_error
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Fun_too_few_args
{
pos = p_sub;
decl_pos = p_super;
expected = super_max;
actual = sub_max;
}))
res
else
res
| (None, Some _) ->
with_error
(Option.map
subtype_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Fun_unexpected_nonvariadic
{ pos = p_sub; decl_pos = p_super }))
res
| (_, _) -> res
and simplify_subtype_possibly_enforced
~(subtype_env : subtype_env) ~sub_supportdyn et_sub et_super =
simplify_subtype ~subtype_env ~sub_supportdyn et_sub.et_type et_super.et_type
(* This implements basic subtyping on non-generic function types:
* (1) return type behaves covariantly
* (2) parameter types behave contravariantly
* (3) special casing for variadics
*)
and simplify_subtype_funs
~(subtype_env : subtype_env)
~(check_return : bool)
~(for_override : bool)
?(super_like = false)
(r_sub : Reason.t)
(ft_sub : locl_fun_type)
(r_super : Reason.t)
(ft_super : locl_fun_type)
env : env * TL.subtype_prop =
(* First apply checks on attributes and variadic arity *)
let simplify_subtype_implicit_params =
simplify_subtype_implicit_params ~subtype_env
in
env
|> simplify_subtype_funs_attributes ~subtype_env r_sub ft_sub r_super ft_super
&&& (* Now do contravariant subtyping on parameters *)
begin
(* If both fun policies are IFC public, there's no need to check for inheritance issues *)
(* There is the chance that the super function has an <<__External>> argument and the sub function does not,
but <<__External>> on a public policied function literally just means the argument must be governed by the public policy,
so should be an error in any case.
*)
let check_params_ifc =
non_public_ifc ft_super.ft_ifc_decl || non_public_ifc ft_sub.ft_ifc_decl
in
simplify_subtype_params
~subtype_env
~for_override
~check_params_ifc
ft_super.ft_params
ft_sub.ft_params
(get_ft_variadic ft_super)
(get_ft_variadic ft_sub)
end
&&& simplify_subtype_implicit_params
ft_super.ft_implicit_params
ft_sub.ft_implicit_params
&&&
(* Finally do covariant subtyping on return type *)
if check_return then
let super_ty = liken ~super_like env ft_super.ft_ret.et_type in
let subtype_env =
if TypecheckerOptions.enable_sound_dynamic env.genv.tcopt && for_override
then
(* When overriding in Sound Dynamic, we allow t to override dynamic if
* t is a dynamic-aware subtype of dynamic. We also allow Awaitable<t>
* to override Awaitable<dynamic> and and Awaitable<t> to
* override ~Awaitable<dynamic>.
*)
let super_ty = TUtils.strip_dynamic env super_ty in
match get_node super_ty with
| Tdynamic -> { subtype_env with coerce = Some TL.CoerceToDynamic }
| Tclass ((_, class_name), _, [ty])
when String.equal class_name SN.Classes.cAwaitable && is_dynamic ty ->
{ subtype_env with coerce = Some TL.CoerceToDynamic }
| _ -> subtype_env
else
subtype_env
in
simplify_subtype
~subtype_env
~sub_supportdyn:None
ft_sub.ft_ret.et_type
super_ty
else
valid
(* Add a new upper bound ty on var. Apply transitivity of sutyping,
* so if we already have tyl <: var, then check that for each ty_sub
* in tyl we have ty_sub <: ty.
*)
and add_tyvar_upper_bound_and_close
~coerce
(env, prop)
var
ty
(on_error : Typing_error.Reasons_callback.t option) =
let ty =
match ty with
| LoclType ty -> LoclType (transform_dynamic_upper_bound ~coerce env ty)
| cty -> cty
in
let upper_bounds_before = Env.get_tyvar_upper_bounds env var in
let env =
Env.add_tyvar_upper_bound_and_update_variances
~intersect:(try_intersect_i ~ignore_tyvars:true env)
env
var
ty
in
let upper_bounds_after = Env.get_tyvar_upper_bounds env var in
let added_upper_bounds = ITySet.diff upper_bounds_after upper_bounds_before in
let lower_bounds = Env.get_tyvar_lower_bounds env var in
let (env, prop) =
ITySet.fold
(fun upper_bound (env, prop) ->
let (env, ty_err_opt) =
Typing_subtype_tconst.make_all_type_consts_equal
env
var
upper_bound
~on_error
~as_tyvar_with_cnstr:true
in
let (env, prop) =
Option.value_map
~default:(env, prop)
~f:(fun ty_err -> invalid ~fail:(Some ty_err) env)
ty_err_opt
in
ITySet.fold
(fun lower_bound (env, prop1) ->
let (env, prop2) =
simplify_subtype_i
~subtype_env:(make_subtype_env ~coerce ~log_level:2 on_error)
~sub_supportdyn:None
lower_bound
upper_bound
env
in
(env, TL.conj prop1 prop2))
lower_bounds
(env, prop))
added_upper_bounds
(env, prop)
in
(env, prop)
(* Add a new lower bound ty on var. Apply transitivity of subtyping
* (so if var <: ty1,...,tyn then assert ty <: tyi for each tyi), using
* simplify_subtype to produce a subtype proposition.
*)
and add_tyvar_lower_bound_and_close
~coerce
(env, prop)
var
ty
(on_error : Typing_error.Reasons_callback.t option) =
let lower_bounds_before = Env.get_tyvar_lower_bounds env var in
let env =
Env.add_tyvar_lower_bound_and_update_variances
~union:(try_union_i env)
env
var
ty
in
let lower_bounds_after = Env.get_tyvar_lower_bounds env var in
let added_lower_bounds = ITySet.diff lower_bounds_after lower_bounds_before in
let upper_bounds = Env.get_tyvar_upper_bounds env var in
let (env, prop) =
ITySet.fold
(fun lower_bound (env, prop) ->
let (env, ty_err_opt) =
Typing_subtype_tconst.make_all_type_consts_equal
env
var
lower_bound
~on_error
~as_tyvar_with_cnstr:false
in
let (env, prop) =
Option.value_map
~default:(env, prop)
~f:(fun err -> invalid ~fail:(Some err) env)
ty_err_opt
in
ITySet.fold
(fun upper_bound (env, prop1) ->
let (env, prop2) =
simplify_subtype_i
~subtype_env:(make_subtype_env ~coerce ~log_level:2 on_error)
~sub_supportdyn:None
lower_bound
upper_bound
env
in
(env, TL.conj prop1 prop2))
upper_bounds
(env, prop))
added_lower_bounds
(env, prop)
in
(env, prop)
(** [simplify_subtype_arraykey_union env ty_sub tyl_super] implements a special purpose typing
rule for t <: arraykey | tvar by checking t & not arraykey <: tvar. It also works for
not arraykey | tvar. By only applying if B is a type variable, we avoid oscillating
forever between this rule and the generic one that moves from t1 & arraykey <: t2.
to t1 <: t2 | not arraykey. This is similar to our treatment of A <: ?B iff
A & nonnull <: B. This returns a subtyp_prop if the pattern this rule looks for matched,
and returns None if it did not, so that this rule does not apply. ) *)
and simplify_subtype_arraykey_union
~this_ty ~sub_supportdyn ~subtype_env env ty_sub tyl_super =
match tyl_super with
| [ty_super1; ty_super2] ->
let (env, ty_super1) = Env.expand_type env ty_super1 in
let (env, ty_super2) = Env.expand_type env ty_super2 in
(match (deref ty_super1, deref ty_super2) with
| ( ((_, Tvar _) as tvar_ty),
((_, (Tprim Aast.Tarraykey | Tneg (Neg_prim Aast.Tarraykey))) as ak_ty)
)
| ( ((_, (Tprim Aast.Tarraykey | Tneg (Neg_prim Aast.Tarraykey))) as ak_ty),
((_, Tvar _) as tvar_ty) ) ->
let (env, neg_ty) =
Inter.negate_type
env
(get_reason (mk ak_ty))
~approx:Inter.Utils.ApproxDown
(mk ak_ty)
in
let (env, inter_ty) =
Inter.intersect env ~r:(get_reason ty_sub) neg_ty ty_sub
in
let (env, props) =
simplify_subtype_i
~this_ty
~sub_supportdyn
~subtype_env
(LoclType inter_ty)
(LoclType (mk tvar_ty))
env
in
(env, Some props)
| _ -> (env, None))
| _ -> (env, None)
(* Traverse a list of disjuncts and remove obviously redundant ones.
t1 <: #1 is considered redundant if t2 <: #1 is also a disjunct and t2 <: t1.
Dually,
#1 <: t1 is considered redundant if #1 <: t2 is also a disjunct and t1 <: t2.
It does not preserve the ordering.
*)
and simplify_disj env disj =
(* even if sub_ty is not a supertype of super_ty, still consider super_ty redunant *)
let additional_heuristic ~coerce env _sub_ty super_ty =
let nonnull =
if TypecheckerOptions.enable_sound_dynamic (Env.get_tcopt env) then
MakeType.supportdyn_nonnull Reason.none
else
MakeType.nonnull Reason.none
in
is_sub_type_for_union_i ~coerce env (LoclType nonnull) super_ty
in
let rec add_new_bound ~is_lower ~coerce ~constr ty bounds =
match bounds with
| [] -> [(is_lower, ty, constr)]
| ((is_lower', bound_ty, _) as b) :: bounds ->
if is_lower && is_lower' then
if is_sub_type_for_union_i ~coerce env bound_ty ty then
b :: bounds
else if is_sub_type_for_union_i ~coerce env ty bound_ty then
add_new_bound ~is_lower ~coerce ~constr ty bounds
else if additional_heuristic ~coerce env bound_ty ty then
b :: bounds
else if additional_heuristic ~coerce env ty bound_ty then
add_new_bound ~is_lower ~coerce ~constr ty bounds
else
b :: add_new_bound ~is_lower ~coerce ~constr ty bounds
else if
(not is_lower)
&& (not is_lower')
&& is_sub_type_for_union_i ~coerce env ty bound_ty
then
b :: bounds
else if
(not is_lower)
&& (not is_lower')
&& is_sub_type_for_union_i ~coerce env bound_ty ty
then
add_new_bound ~is_lower ~coerce ~constr ty bounds
else
b :: add_new_bound ~is_lower ~coerce ~constr ty bounds
in
(* Map a type variable to a list of lower and upper bound types. For any two types
t1 and t2 both lower or upper in the list, it is not the case that t1 <: t2 or t2 <: t1.
*)
let bound_map = ref IMap.empty in
let process_bound ~is_lower ~coerce ~constr ty var =
let ty =
match ty with
| LoclType ty when not is_lower ->
LoclType (transform_dynamic_upper_bound ~coerce env ty)
| _ -> ty
in
match IMap.find_opt var !bound_map with
| None -> bound_map := IMap.add var [(is_lower, ty, constr)] !bound_map
| Some bounds ->
let new_bounds = add_new_bound ~is_lower ~coerce ~constr ty bounds in
bound_map := IMap.add var new_bounds !bound_map
in
let rec fill_bound_map disj =
match disj with
| [] -> []
| d :: disj ->
(match d with
| TL.Conj _ -> d :: fill_bound_map disj
| TL.Disj (_, props) -> fill_bound_map (props @ disj)
| TL.IsSubtype (coerce, ty_sub, ty_super) ->
(match get_tyvar_opt ty_super with
| Some var_super ->
process_bound ~is_lower:true ~coerce ~constr:d ty_sub var_super;
fill_bound_map disj
| None ->
(match get_tyvar_opt ty_sub with
| Some var_sub ->
process_bound ~is_lower:false ~coerce ~constr:d ty_super var_sub;
fill_bound_map disj
| None -> d :: fill_bound_map disj)))
in
(* Get the constraints from the table that were not removed, and add them to
the remaining constraints that were not of the form we were looking for. *)
let rec rebuild_disj remaining to_process =
match to_process with
| [] -> remaining
| (_, bounds) :: to_process ->
List.map ~f:(fun (_, _, c) -> c) bounds
@ rebuild_disj remaining to_process
in
let remaining = fill_bound_map disj in
let bounds = IMap.elements !bound_map in
rebuild_disj remaining bounds
and props_to_env
ty_sub
ty_super
env
ty_errs
remain
props
(on_error : Typing_error.Reasons_callback.t option) =
let props_to_env = props_to_env ty_sub ty_super in
match props with
| [] -> (env, List.rev ty_errs, List.rev remain)
| prop :: props ->
(match prop with
| TL.Conj props' ->
props_to_env env ty_errs remain (props' @ props) on_error
| TL.Disj (ty_err_opt, disj_props) ->
(* For now, just find the first prop in the disjunction that works *)
let rec try_disj disj_props =
match disj_props with
| [] ->
(* For now let it fail later when calling
process_simplify_subtype_result on the remaining constraints. *)
props_to_env env (ty_err_opt :: ty_errs) remain props on_error
| prop :: disj_props' ->
let (env', ty_errs', other) =
props_to_env env [] remain [prop] on_error
in
if List.is_empty ty_errs' || List.for_all ty_errs' ~f:Option.is_none
then
props_to_env env' ty_errs (remain @ other) props on_error
else
try_disj disj_props'
in
let rec log_non_singleton_disj msg props =
match props with
| [] -> ()
| [TL.Disj (_, props)] -> log_non_singleton_disj msg props
| [_] -> ()
| _ ->
Typing_log.log_prop
1
(Reason.to_pos (get_reason_i ty_sub))
("non-singleton disjunction "
^ msg
^ " of "
^ Typing_print.full_i env ty_sub
^ " <: "
^ Typing_print.full_i env ty_super)
env
prop
in
let simplified_disj_props = simplify_disj env disj_props in
log_non_singleton_disj "before simplification" disj_props;
log_non_singleton_disj "after simplification" simplified_disj_props;
try_disj simplified_disj_props
| TL.IsSubtype (coerce, ty_sub, ty_super) ->
let (env, ty_sub) = Env.expand_internal_type env ty_sub in
let (env, ty_super) = Env.expand_internal_type env ty_super in
(match (get_tyvar_opt ty_sub, get_tyvar_opt ty_super) with
| (Some var_sub, Some var_super) ->
let (env, prop1) =
add_tyvar_upper_bound_and_close
~coerce
(valid env)
var_sub
ty_super
on_error
in
let (env, prop2) =
add_tyvar_lower_bound_and_close
~coerce
(valid env)
var_super
ty_sub
on_error
in
props_to_env env ty_errs remain (prop1 :: prop2 :: props) on_error
| (Some var, _) ->
let (env, prop) =
add_tyvar_upper_bound_and_close
~coerce
(valid env)
var
ty_super
on_error
in
props_to_env env ty_errs remain (prop :: props) on_error
| (_, Some var) ->
let (env, prop) =
add_tyvar_lower_bound_and_close
~coerce
(valid env)
var
ty_sub
on_error
in
props_to_env env ty_errs remain (prop :: props) on_error
| _ -> props_to_env env ty_errs (prop :: remain) props on_error))
(* Given a subtype proposition, resolve conjunctions of subtype assertions
* of the form #v <: t or t <: #v by adding bounds to #v in env. Close env
* wrt transitivity i.e. if t <: #v and #v <: u then resolve t <: u which
* may in turn produce more bounds in env.
* For disjunctions, arbitrarily pick the first disjunct that is not
* unsatisfiable. If any unsatisfiable disjunct remains, return it.
*)
and prop_to_env ty_sub ty_super env prop on_error =
let (env, ty_errs, props') =
props_to_env ty_sub ty_super env [] [] [prop] on_error
in
let ty_err_opt = Typing_error.union_opt @@ List.filter_map ~f:Fn.id ty_errs in
let env = Env.add_subtype_prop env (TL.conj_list props') in
(env, ty_err_opt)
and sub_type_inner
(env : env)
~(subtype_env : subtype_env)
~(sub_supportdyn : Reason.t option)
~(this_ty : locl_ty option)
(ty_sub : internal_type)
(ty_super : internal_type) : env * Typing_error.t option =
log_subtype_i
~level:1
~this_ty
~function_name:
("sub_type_inner"
^
match subtype_env.coerce with
| Some TL.CoerceToDynamic -> " (dynamic aware)"
| Some TL.CoerceFromDynamic -> " (treat dynamic as bottom)"
| None -> "")
env
ty_sub
ty_super;
let (env, prop) =
simplify_subtype_i ~subtype_env ~sub_supportdyn ~this_ty ty_sub ty_super env
in
if not (TL.is_valid prop) then
Typing_log.log_prop
1
(Reason.to_pos (reason ty_sub))
"sub_type_inner"
env
prop;
prop_to_env ty_sub ty_super env prop subtype_env.on_error
and is_sub_type_alt_i
~require_completeness ~no_top_bottom ~coerce ~sub_supportdyn env ty1 ty2 =
let this_ty =
match ty1 with
| LoclType ty1 -> Some ty1
| ConstraintType _ -> None
in
let (_env, prop) =
simplify_subtype_i
~subtype_env:
(make_subtype_env
~require_completeness
~no_top_bottom
~coerce
~log_level:3
None)
~sub_supportdyn
~this_ty
(* It is weird that this can cause errors, but I am wary to discard them.
* Using the generic unify_error to maintain current behavior. *)
ty1
ty2
env
in
if TL.is_valid prop then
Some true
else if TL.is_unsat prop then
Some false
else
None
and is_sub_type_for_union_i env ?(coerce = None) ty1 ty2 =
let ( = ) = Option.equal Bool.equal in
is_sub_type_alt_i
~require_completeness:false
~no_top_bottom:true
~coerce
~sub_supportdyn:None
env
ty1
ty2
= Some true
and is_sub_type_ignore_generic_params_i env ty1 ty2 =
let ( = ) = Option.equal Bool.equal in
is_sub_type_alt_i
(* TODO(T121047839): Should this set a dedicated ignore_generic_param flag instead? *)
~require_completeness:true
~no_top_bottom:true
~coerce:None
~sub_supportdyn:None
env
ty1
ty2
= Some true
(* Attempt to compute the intersection of a type with an existing list intersection.
* If try_intersect env t [t1;...;tn] = [u1; ...; um]
* then u1&...&um must be the greatest lower bound of t and t1&...&tn wrt subtyping.
* For example:
* try_intersect nonnull [?C] = [C]
* try_intersect t1 [t2] = [t1] if t1 <: t2
* Note: it's acceptable to return [t;t1;...;tn] but the intention is that
* we simplify (as above) wherever practical.
* It can be assumed that the original list contains no redundancy.
*)
and try_intersect_i ?(ignore_tyvars = false) env ty tyl =
match tyl with
| [] -> [ty]
| ty' :: tyl' ->
let (env, ty) = Env.expand_internal_type env ty in
let (env, ty') = Env.expand_internal_type env ty' in
let default env = ty' :: try_intersect_i env ~ignore_tyvars ty tyl' in
(* Do not attempt to simplify intersection of type variables, as we use
* intersection simplification when transitively closing through type variable
* upper bounds and this would result in a type failing to be added.
*)
if ignore_tyvars && (is_tyvar_i ty || is_tyvar_i ty') then
default env
else if is_sub_type_ignore_generic_params_i env ty ty' then
try_intersect_i ~ignore_tyvars env ty tyl'
else if is_sub_type_ignore_generic_params_i env ty' ty then
tyl
else
let nonnull_ty = LoclType (MakeType.nonnull (reason ty)) in
(match (ty, ty') with
| (LoclType lty, _)
when is_sub_type_ignore_generic_params_i env ty' nonnull_ty -> begin
match get_node lty with
| Toption t ->
try_intersect_i ~ignore_tyvars env (LoclType t) (ty' :: tyl')
| _ -> default env
end
| (_, LoclType lty)
when is_sub_type_ignore_generic_params_i env ty nonnull_ty -> begin
match get_node lty with
| Toption t ->
try_intersect_i ~ignore_tyvars env (LoclType t) (ty :: tyl')
| _ -> default env
end
| (_, _) -> default env)
and try_intersect ?(ignore_tyvars = false) env ty tyl =
List.map
(try_intersect_i
~ignore_tyvars
env
(LoclType ty)
(List.map tyl ~f:(fun ty -> LoclType ty)))
~f:(function
| LoclType ty -> ty
| _ ->
failwith
"The intersection of two locl type should always be a locl type.")
(* Attempt to compute the union of a type with an existing list union.
* If try_union env t [t1;...;tn] = [u1;...;um]
* then u1|...|um must be the least upper bound of t and t1|...|tn wrt subtyping.
* For example:
* try_union int [float] = [num]
* try_union t1 [t2] = [t1] if t2 <: t1
*
* Notes:
* 1. It's acceptable to return [t;t1;...;tn] but the intention is that
* we simplify (as above) wherever practical.
* 2. Do not use Tunion for a syntactic union - the caller can do that.
* 3. It can be assumed that the original list contains no redundancy.
* TODO: there are many more unions to implement yet.
*)
and try_union_i env ty tyl =
match tyl with
| [] -> [ty]
| ty' :: tyl' ->
if is_sub_type_for_union_i env ty ty' then
tyl
else if is_sub_type_for_union_i env ty' ty then
try_union_i env ty tyl'
else
let (env, ty) = Env.expand_internal_type env ty in
let (env, ty') = Env.expand_internal_type env ty' in
(match (ty, ty') with
| (LoclType t1, LoclType t2)
when (is_prim Nast.Tfloat t1 && is_prim Nast.Tint t2)
|| (is_prim Nast.Tint t1 && is_prim Nast.Tfloat t2) ->
let num = LoclType (MakeType.num (reason ty)) in
try_union_i env num tyl'
| (_, _) -> ty' :: try_union_i env ty tyl')
and try_union env ty tyl =
List.map
(try_union_i env (LoclType ty) (List.map tyl ~f:(fun ty -> LoclType ty)))
~f:(function
| LoclType ty -> ty
| _ -> failwith "The union of two locl type should always be a locl type.")
(* Determines whether the types are definitely disjoint, or whether they might
overlap (i.e., both contain some particular value). *)
(* One of the main entry points to this module *)
let sub_type_i ~subtype_env env ty_sub ty_super =
let old_env = env in
match
sub_type_inner
~subtype_env
~sub_supportdyn:None
env
~this_ty:None
ty_sub
ty_super
with
| (env, None) -> (Env.log_env_change "sub_type" old_env env, None)
| (_, ty_err_opt) ->
(Env.log_env_change "sub_type" old_env old_env, ty_err_opt)
let sub_type
env
?(coerce = None)
?(is_coeffect = false)
(ty_sub : locl_ty)
(ty_super : locl_ty)
on_error =
sub_type_i
~subtype_env:(make_subtype_env ~is_coeffect ~coerce ~log_level:2 on_error)
env
(LoclType ty_sub)
(LoclType ty_super)
let is_sub_type_alt ~require_completeness ~no_top_bottom env ty1 ty2 =
is_sub_type_alt_i
~require_completeness
~no_top_bottom
env
(LoclType ty1)
(LoclType ty2)
let is_sub_type env ty1 ty2 =
let ( = ) = Option.equal Bool.equal in
is_sub_type_alt
~require_completeness:false
~no_top_bottom:false
~coerce:None
~sub_supportdyn:None
env
ty1
ty2
= Some true
let is_dynamic_aware_sub_type env ty1 ty2 =
let ( = ) = Option.equal Bool.equal in
is_sub_type_alt
~require_completeness:false
~no_top_bottom:false
~coerce:(Some TL.CoerceToDynamic)
~sub_supportdyn:None
env
ty1
ty2
= Some true
let is_sub_type_for_union env ?(coerce = None) ty1 ty2 =
let ( = ) = Option.equal Bool.equal in
is_sub_type_alt
~require_completeness:false
~no_top_bottom:true
~coerce
~sub_supportdyn:None
env
ty1
ty2
= Some true
let is_sub_type_ignore_generic_params env ty1 ty2 =
let ( = ) = Option.equal Bool.equal in
is_sub_type_alt
(* TODO(T121047839): Should this set a dedicated ignore_generic_param flag instead? *)
~require_completeness:true
~no_top_bottom:true
~coerce:None
~sub_supportdyn:None
env
ty1
ty2
= Some true
let can_sub_type env ty1 ty2 =
let ( <> ) a b = not (Option.equal Bool.equal a b) in
is_sub_type_alt
~require_completeness:false
~no_top_bottom:true
~coerce:None
~sub_supportdyn:None
env
ty1
ty2
<> Some false
let is_type_disjoint env ty1 ty2 =
(* visited record which type variables & generics we've seen, to cut off cycles. *)
let rec is_type_disjoint visited env ty1 ty2 =
let (env, ty1) = Env.expand_type env ty1 in
let (env, ty2) = Env.expand_type env ty2 in
match (get_node ty1, get_node ty2) with
| (_, (Tany _ | Tdynamic | Taccess _ | Tunapplied_alias _))
| ((Tany _ | Tdynamic | Taccess _ | Tunapplied_alias _), _) ->
false
| (Tshape _, Tshape _) ->
(* This could be more precise, e.g., if we have two closed shapes with different fields.
However, intersection already detects this and simplifies to nothing, so it's not
so important here. *)
false
| (Tshape _, _) ->
(* Treat shapes as dict<arraykey, mixed> because that implementation detail
leaks through when doing is dict<_, _> on them, and they are also
Traversable, KeyedContainer, etc. (along with darrays).
We could translate darray to a more precise dict type with the same
type arguments, but it doesn't matter since disjointness doesn't ever
look at them. *)
let r = get_reason ty1 in
is_type_disjoint visited env MakeType.(dict r (arraykey r) (mixed r)) ty2
| (_, Tshape _) ->
let r = get_reason ty2 in
is_type_disjoint visited env ty1 MakeType.(dict r (arraykey r) (mixed r))
| (Ttuple tyl1, Ttuple tyl2) ->
(match List.exists2 ~f:(is_type_disjoint visited env) tyl1 tyl2 with
| List.Or_unequal_lengths.Ok res -> res
| List.Or_unequal_lengths.Unequal_lengths -> true)
| (Ttuple _, _) ->
(* Treat tuples as vec<mixed> because that implementation detail
leaks through when doing is vec<_> on them, and they are also
Traversable, Container, etc. along with varrays.
We could translate varray to a more precise vec type with the same
type argument, but it doesn't matter since disjointness doesn't ever
look at it. *)
let r = get_reason ty1 in
is_type_disjoint visited env MakeType.(vec r (mixed r)) ty2
| (_, Ttuple _) ->
let r = get_reason ty2 in
is_type_disjoint visited env ty1 MakeType.(vec r (mixed r))
| (Tvec_or_dict (tyk, tyv), _) ->
let r = get_reason ty1 in
is_type_disjoint
visited
env
MakeType.(union r [vec r tyv; dict r tyk tyv])
ty2
| (_, Tvec_or_dict (tyk, tyv)) ->
let r = get_reason ty2 in
is_type_disjoint
visited
env
ty1
MakeType.(union r [vec r tyv; dict r tyk tyv])
| (Tgeneric (name, []), _) -> is_generic_disjoint visited env name ty1 ty2
| (_, Tgeneric (name, [])) -> is_generic_disjoint visited env name ty2 ty1
| ((Tgeneric _ | Tnewtype _ | Tdependent _ | Tintersection _), _) ->
let (env, bounds) =
TUtils.get_concrete_supertypes ~abstract_enum:false env ty1
in
is_intersection_type_disjoint visited env bounds ty2
| (_, (Tgeneric _ | Tnewtype _ | Tdependent _ | Tintersection _)) ->
let (env, bounds) =
TUtils.get_concrete_supertypes ~abstract_enum:false env ty2
in
is_intersection_type_disjoint visited env bounds ty1
| (Tvar tv, _) -> is_tyvar_disjoint visited env tv ty2
| (_, Tvar tv) -> is_tyvar_disjoint visited env tv ty1
| (Tunion tyl, _) -> List.for_all ~f:(is_type_disjoint visited env ty2) tyl
| (_, Tunion tyl) -> List.for_all ~f:(is_type_disjoint visited env ty1) tyl
| (Toption ty1, _) ->
is_type_disjoint visited env ty1 ty2
&& is_type_disjoint visited env (MakeType.null Reason.Rnone) ty2
| (_, Toption ty2) ->
is_type_disjoint visited env ty1 ty2
&& is_type_disjoint visited env ty1 (MakeType.null Reason.Rnone)
| (Tnonnull, _) ->
is_sub_type_for_union env ty2 (MakeType.null Reason.Rnone)
| (_, Tnonnull) ->
is_sub_type_for_union env ty1 (MakeType.null Reason.Rnone)
| (Tneg (Neg_prim tp1), _) ->
is_sub_type_for_union env ty2 (MakeType.prim_type Reason.Rnone tp1)
| (_, Tneg (Neg_prim tp2)) ->
is_sub_type_for_union env ty1 (MakeType.prim_type Reason.Rnone tp2)
| (Tneg (Neg_class (_, c1)), Tclass ((_, c2), _, _tyl))
| (Tclass ((_, c2), _, _tyl), Tneg (Neg_class (_, c1))) ->
(* These are disjoint iff for all objects o, o in c2<_tyl> implies that
o notin (complement (Union tyl'. c1<tyl'>)), which is just that
c2<_tyl> subset Union tyl'. c1<tyl'>. If c2 is a subclass of c1, then
whatever _tyl is, we can chase up the hierarchy to find an instantiation
for tyl'. If c2 is not a subclass of c1, then no matter what the tyl' are
the subset realtionship cannot hold, since either c1 and c2 are disjoint tags,
or c1 is a non-equal subclass of c2, and so objects that are exact c2,
can't inhabit c1. NB, we aren't allowing abstractness of a class to cause
types to be considered disjoint.
e.g., in abstract class C {}; class D extends C {}, we wouldn't consider
neg D and C to be disjoint.
*)
TUtils.is_sub_class_refl env c2 c1
| (Tneg _, _)
| (_, Tneg _) ->
false
| (Tprim tp1, Tprim tp2) -> is_tprim_disjoint tp1 tp2
| (Tclass ((_, cname), ex, _), Tprim (Aast.Tarraykey | Aast.Tstring))
| (Tprim (Aast.Tarraykey | Aast.Tstring), Tclass ((_, cname), ex, _))
when String.equal cname SN.Classes.cStringish && is_nonexact ex ->
false
| (Tprim _, (Tfun _ | Tclass _))
| ((Tfun _ | Tclass _), Tprim _) ->
true
| (Tfun _, Tfun _) -> false
| (Tfun _, Tclass _)
| (Tclass _, Tfun _) ->
true
| (Tclass ((_, c1), _, _), Tclass ((_, c2), _, _)) ->
is_class_disjoint env c1 c2
(* incomplete, e.g., is_intersection_type_disjoint (?int & ?float) num *)
and is_intersection_type_disjoint visited_tvyars env inter_tyl ty =
List.exists ~f:(is_type_disjoint visited_tvyars env ty) inter_tyl
and is_intersection_itype_set_disjoint visited_tvyars env inter_ty_set ty =
ITySet.exists (is_itype_disjoint visited_tvyars env ty) inter_ty_set
and is_itype_disjoint
visited_tvyars env (lty1 : locl_ty) (ity : internal_type) =
match ity with
| LoclType lty2 -> is_type_disjoint visited_tvyars env lty1 lty2
| ConstraintType _ -> false
and is_tyvar_disjoint visited env (tyvar : int) ty =
let (visited_tyvars, visited_generics) = visited in
if ISet.mem tyvar visited_tyvars then
(* There is a cyclic type variable bound, this will lead to a type error *)
false
else
let bounds = Env.get_tyvar_upper_bounds env tyvar in
is_intersection_itype_set_disjoint
(ISet.add tyvar visited_tyvars, visited_generics)
env
bounds
ty
and is_generic_disjoint visited env (name : string) gen_ty ty =
let (visited_tyvars, visited_generics) = visited in
if SSet.mem name visited_generics then
false
else
let (env, bounds) =
TUtils.get_concrete_supertypes ~abstract_enum:false env gen_ty
in
is_intersection_type_disjoint
(visited_tyvars, SSet.add name visited_generics)
env
bounds
ty
in
is_type_disjoint (ISet.empty, SSet.empty) env ty1 ty2
let decompose_subtype_add_bound
~coerce (env : env) (ty_sub : locl_ty) (ty_super : locl_ty) : env =
let (env, ty_super) = Env.expand_type env ty_super in
let (env, ty_sub) = Env.expand_type env ty_sub in
match (get_node ty_sub, get_node ty_super) with
| (_, Tany _) -> env
(* name_sub <: ty_super so add an upper bound on name_sub *)
| (Tgeneric (name_sub, targs), _) when not (phys_equal ty_sub ty_super) ->
let ty_super = transform_dynamic_upper_bound ~coerce env ty_super in
(* TODO(T69551141) handle type arguments. Passing targs to get_lower_bounds,
but the add_upper_bound call must be adapted *)
log_subtype
~level:2
~this_ty:None
~function_name:"decompose_subtype_add_bound"
env
ty_sub
ty_super;
let tys = Env.get_upper_bounds env name_sub targs in
(* Don't add the same type twice! *)
if Typing_set.mem ty_super tys then
env
else
Env.add_upper_bound ~intersect:(try_intersect env) env name_sub ty_super
(* ty_sub <: name_super so add a lower bound on name_super *)
| (_, Tgeneric (name_super, targs)) when not (phys_equal ty_sub ty_super) ->
(* TODO(T69551141) handle type arguments. Passing targs to get_lower_bounds,
but the add_lower_bound call must be adapted *)
log_subtype
~level:2
~this_ty:None
~function_name:"decompose_subtype_add_bound"
env
ty_sub
ty_super;
let tys = Env.get_lower_bounds env name_super targs in
(* Don't add the same type twice! *)
if Typing_set.mem ty_sub tys then
env
else
Env.add_lower_bound ~union:(try_union env) env name_super ty_sub
| (_, _) -> env
(* Given two types that we know are in a subtype relationship
* ty_sub <: ty_super
* add to env.tpenv any bounds on generic type parameters that must
* hold for ty_sub <: ty_super to be valid.
*
* For example, suppose we know Cov<T> <: Cov<D> for a covariant class Cov.
* Then it must be the case that T <: D so we add an upper bound D to the
* bounds for T.
*
* Although some of this code is similar to that for sub_type_inner, its
* purpose is different. sub_type_inner takes two types t and u and makes
* updates to the substitution of type variables (through unification) to
* make t <: u true.
*
* decompose_subtype takes two types t and u for which t <: u is *assumed* to
* hold, and makes updates to bounds on generic parameters that *necessarily*
* hold in order for t <: u.
*)
let rec decompose_subtype
(env : env)
(ty_sub : locl_ty)
(ty_super : locl_ty)
(on_error : Typing_error.Reasons_callback.t option) : env =
log_subtype
~level:2
~this_ty:None
~function_name:"decompose_subtype"
env
ty_sub
ty_super;
let (env, prop) =
simplify_subtype
~subtype_env:
(make_subtype_env
~require_soundness:false
~require_completeness:true
~log_level:2
on_error)
~sub_supportdyn:None
~this_ty:None
ty_sub
ty_super
env
in
decompose_subtype_add_prop env prop
and decompose_subtype_add_prop env prop =
match prop with
| TL.Conj props ->
List.fold_left ~f:decompose_subtype_add_prop ~init:env props
| TL.Disj (_, []) -> Env.mark_inconsistent env
| TL.Disj (_, [prop']) -> decompose_subtype_add_prop env prop'
| TL.Disj _ ->
let callable_pos = env.genv.callable_pos in
Typing_log.log_prop
2
(Pos_or_decl.of_raw_pos callable_pos)
"decompose_subtype_add_prop"
env
prop;
env
| TL.IsSubtype (coerce, LoclType ty1, LoclType ty2) ->
decompose_subtype_add_bound ~coerce env ty1 ty2
| TL.IsSubtype _ ->
(* Subtyping queries between locl types are not creating
constraint types only if require_soundness is unset.
Otherwise type refinement subtyping queries may create
Thas_type_member() constraint types. *)
failwith
("Subtyping locl types in completeness mode should yield "
^ "propositions involving locl types only.")
(* Decompose a general constraint *)
and decompose_constraint
(env : env)
(ck : Ast_defs.constraint_kind)
(ty_sub : locl_ty)
(ty_super : locl_ty)
on_error : env =
(* constraints are caught based on reason, not error callback. Using unify_error *)
match ck with
| Ast_defs.Constraint_as -> decompose_subtype env ty_sub ty_super on_error
| Ast_defs.Constraint_super -> decompose_subtype env ty_super ty_sub on_error
| Ast_defs.Constraint_eq ->
let env = decompose_subtype env ty_sub ty_super on_error in
decompose_subtype env ty_super ty_sub on_error
(* Given a constraint ty1 ck ty2 where ck is AS, SUPER or =,
* add bounds to type parameters in the environment that necessarily
* must hold in order for ty1 ck ty2.
*
* First, we invoke decompose_constraint to add initial bounds to
* the environment. Then we iterate, decomposing constraints that
* arise through transitivity across bounds.
*
* For example, suppose that env already contains
* C<T1> <: T2
* for some covariant class C. Now suppose we add the
* constraint "T2 as C<T3>" i.e. we end up with
* C<T1> <: T2 <: C<T3>
* Then by transitivity we know that T1 <: T3 so we add this to the
* environment too.
*
* We repeat this process until no further bounds are added to the
* environment, or some limit is reached. (It's possible to construct
* types that expand forever under inheritance.)
*)
let constraint_iteration_limit = 20
let add_constraint
(env : env)
(ck : Ast_defs.constraint_kind)
(ty_sub : locl_ty)
(ty_super : locl_ty)
on_error : env =
log_subtype
~level:1
~this_ty:None
~function_name:"add_constraint"
env
ty_sub
ty_super;
let oldsize = Env.get_tpenv_size env in
let env = decompose_constraint env ck ty_sub ty_super on_error in
let ( = ) = Int.equal in
if Env.get_tpenv_size env = oldsize then
env
else
let rec iter n env =
if n > constraint_iteration_limit then
env
else
let oldsize = Env.get_tpenv_size env in
let env =
List.fold_left
(Env.get_generic_parameters env)
~init:env
~f:(fun env x ->
List.fold_left
(* TODO(T70068435) always using [] as args for now *)
(Typing_set.elements (Env.get_lower_bounds env x []))
~init:env
~f:(fun env ty_sub' ->
List.fold_left
(* TODO(T70068435) always using [] as args for now *)
(Typing_set.elements (Env.get_upper_bounds env x []))
~init:env
~f:(fun env ty_super' ->
decompose_subtype env ty_sub' ty_super' on_error)))
in
if Int.equal (Env.get_tpenv_size env) oldsize then
env
else
iter (n + 1) env
in
iter 0 env
let add_constraints p env constraints =
let add_constraint env (ty1, ck, ty2) =
add_constraint env ck ty1 ty2
@@ Some (Typing_error.Reasons_callback.unify_error_at p)
in
List.fold_left constraints ~f:add_constraint ~init:env
let sub_type_with_dynamic_as_bottom env ty_sub ty_super on_error =
log_subtype
~level:1
~this_ty:None
~function_name:"coercion"
env
ty_sub
ty_super;
let old_env = env in
let (env, prop) =
simplify_subtype
~subtype_env:
(make_subtype_env
~coerce:(Some TL.CoerceFromDynamic)
~log_level:2
on_error)
~sub_supportdyn:None
~this_ty:None
ty_sub
ty_super
env
in
let (env, ty_err) =
prop_to_env (LoclType ty_sub) (LoclType ty_super) env prop on_error
in
( (if Option.is_some ty_err then
old_env
else
env),
ty_err )
let simplify_subtype_i ?(is_coeffect = false) env ty_sub ty_super ~on_error =
simplify_subtype_i
~subtype_env:
(make_subtype_env ~is_coeffect ~no_top_bottom:true ~log_level:2 on_error)
~sub_supportdyn:None
ty_sub
ty_super
env
(*****************************************************************************)
(* Exporting *)
(*****************************************************************************)
let sub_type_i env ?(is_coeffect = false) ty1 ty2 on_error =
sub_type_i
~subtype_env:
(make_subtype_env ~log_level:2 ~is_coeffect ~coerce:None on_error)
env
ty1
ty2
let subtype_funs
~(check_return : bool)
~for_override
~on_error
(r_sub : Reason.t)
(ft_sub : locl_fun_type)
(r_super : Reason.t)
(ft_super : locl_fun_type)
env =
(* This is used for checking subtyping of function types for method override
* (see Typing_subtype_method) so types are fully-explicit and therefore we
* permit subtyping to dynamic when --enable-sound-dynamic-type is true
*)
let old_env = env in
let (env, prop) =
simplify_subtype_funs
~subtype_env:(make_subtype_env ~log_level:2 ~coerce:None on_error)
~check_return
~for_override
r_sub
ft_sub
r_super
ft_super
env
in
let (env, ty_err) =
prop_to_env
(LoclType (mk (r_sub, Tfun ft_sub)))
(LoclType (mk (r_super, Tfun ft_super)))
env
prop
on_error
in
( (if Option.is_some ty_err then
old_env
else
env),
ty_err )
let sub_type_or_fail env ty1 ty2 err_opt =
sub_type env ty1 ty2
@@ Option.map ~f:Typing_error.Reasons_callback.always err_opt
let is_sub_type_for_union = is_sub_type_for_union ~coerce:None
let is_sub_type_for_union_i = is_sub_type_for_union_i ~coerce:None
let set_fun_refs () =
TUtils.sub_type_ref := sub_type;
TUtils.sub_type_i_ref := sub_type_i;
TUtils.sub_type_with_dynamic_as_bottom_ref := sub_type_with_dynamic_as_bottom;
TUtils.add_constraint_ref := add_constraint;
TUtils.is_sub_type_ref := is_sub_type;
TUtils.is_sub_type_for_union_ref := is_sub_type_for_union;
TUtils.is_sub_type_for_union_i_ref := is_sub_type_for_union_i;
TUtils.is_sub_type_ignore_generic_params_ref :=
is_sub_type_ignore_generic_params;
TUtils.is_type_disjoint_ref := is_type_disjoint;
TUtils.can_sub_type_ref := can_sub_type
let () = set_fun_refs () |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_subtype.mli | open Typing_defs
open Typing_env_types
(** Non-side-effecting test for subtypes.
result = true implies ty1 <: ty2
result = false implies NOT ty1 <: ty2 OR we don't know
*)
val is_sub_type : env -> locl_ty -> locl_ty -> bool
val is_dynamic_aware_sub_type : env -> locl_ty -> locl_ty -> bool
val is_sub_type_ignore_generic_params : env -> locl_ty -> locl_ty -> bool
val is_sub_type_for_union : env -> locl_ty -> locl_ty -> bool
(** Determines whether the types are definitely disjoint, or whether they might
overlap. *)
val is_type_disjoint : env -> locl_ty -> locl_ty -> bool
val can_sub_type : env -> locl_ty -> locl_ty -> bool
(**
* [sub_type env t u on_error] asserts that [t] is a subtype of [u],
* adding constraints to [env.tvenv] that are necessary to ensure this, or
* calling [on_error ?code msgl] with (optional) error code and a list of
* (position, message) pairs if the assertion is unsatisfiable.
*
* Note that the [on_error] callback must prefix this list with a top-level
* position and message identifying the primary source of the error (e.g.
* an expression or statement).
* If the optional [coerce] argument indicates whether subtyping should allow
* coercion to or from dynamic. For coercion to dynamic, types that implement
* dynamic are considered sub-types of dynamic. For coercion from dynamic,
* dynamic is treated as a sub-type of all types.
*)
val sub_type :
env ->
?coerce:Typing_logic.coercion_direction option ->
?is_coeffect:bool ->
locl_ty ->
locl_ty ->
Typing_error.Reasons_callback.t option ->
env * Typing_error.t option
(**
* As above, but with a simpler error handler that doesn't make use of the
* code and message list provided by subtyping.
*)
val sub_type_or_fail :
env ->
locl_ty ->
locl_ty ->
Typing_error.Error.t option ->
env * Typing_error.t option
val sub_type_with_dynamic_as_bottom :
env ->
locl_ty ->
locl_ty ->
Typing_error.Reasons_callback.t option ->
env * Typing_error.t option
val sub_type_i :
env ->
?is_coeffect:bool ->
internal_type ->
internal_type ->
Typing_error.Reasons_callback.t option ->
env * Typing_error.t option
val add_constraint :
env ->
Ast_defs.constraint_kind ->
locl_ty ->
locl_ty ->
Typing_error.Reasons_callback.t option ->
env
val add_constraints :
Pos.t -> env -> (locl_ty * Ast_defs.constraint_kind * locl_ty) list -> env
(** Hack to allow for circular dependencies between Ocaml modules. *)
val set_fun_refs : unit -> unit
val simplify_subtype_i :
?is_coeffect:bool ->
env ->
internal_type ->
internal_type ->
on_error:Typing_error.Reasons_callback.t option ->
env * Typing_logic.subtype_prop
val subtype_funs :
check_return:bool ->
for_override:bool ->
on_error:Typing_error.Reasons_callback.t option ->
Reason.t ->
locl_fun_type ->
Reason.t ->
locl_fun_type ->
env ->
env * Typing_error.t option
val can_traverse_to_iface : can_traverse -> locl_ty |
OCaml | hhvm/hphp/hack/src/typing/typing_subtype_method.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
open Typing_subtype
module Reason = Typing_reason
module Env = Typing_env
module Phase = Typing_phase
(** Check that the method decl with signature ft_sub can be used to override
* (is a subtype of) method decl with signature ft_super.
*
* This goes beyond subtyping on function types because methods can have
* generic parameters with bounds, and `where` constraints.
*
* Suppose ft_super is of the form
* <T1 csuper1, ..., Tn csupern>(tsuper1, ..., tsuperm) : tsuper where wsuper
* and ft_sub is of the form
* <T1 csub1, ..., Tn csubn>(tsub1, ..., tsubm) : tsub where wsub
* where csuperX and csubX are constraints on type parameters and wsuper and
* wsub are 'where' constraints. Note that all types in the superclass,
* including constraints (so csuperX, tsuperX, tsuper and wsuper) have had
* any class type parameters instantiated appropriately according to
* the actual arguments of the superclass. For example, suppose we have
*
* class Super<T> {
* function foo<Tu as A<T>>(T $x) : B<T> where T super C<T>
* }
* class Sub extends Super<D> {
* ...override of foo...
* }
* then the actual signature in the superclass that we need to check is
* function foo<Tu as A<D>>(D $x) : B<D> where D super C<D>
* Note in particular the general form of the 'where' constraint.
*
* (Currently, this instantiation happens in
* Typing_extends.check_class_implements which in turn calls
* Decl_instantiate.instantiate_ce)
*
* Then for ft_sub to be a subtype of ft_super it must be the case that
* (1) tsuper1 <: tsub1, ..., tsupern <: tsubn (under constraints
* T1 csuper1, ..., Tn csupern and wsuper).
*
* This is contravariant subtyping on parameter types.
*
* (2) tsub <: tsuper (under constraints T1 csuper1, ..., Tn csupern and wsuper)
* This is covariant subtyping on result type. For constraints consider
* e.g. consider ft_super = <T super I>(): T
* and ft_sub = <T>(): I
*
* (3) The constraints for ft_super entail the constraints for ft_sub, because
* we might be calling the function having checked that csuperX are
* satisfied but the definition of the function (e.g. consider an override)
* has been checked under csubX.
* More precisely, we must assume constraints T1 csuper1, ..., Tn csupern
* and wsuper, and check that T1 satisfies csub1, ..., Tn satisfies csubn
* and that wsub holds under those assumptions.
*)
let subtype_method_decl
~(check_return : bool)
(env : env)
(r_sub : Reason.t)
(ft_sub : decl_fun_type)
(r_super : Reason.t)
(ft_super : decl_fun_type)
(on_error : Typing_error.Reasons_callback.t) : env =
let p_sub = Reason.to_pos r_sub in
let p_super = Reason.to_pos r_super in
let ety_env = empty_expand_env in
(* We check constraint entailment and contravariant parameter/covariant result
* subtyping in the context of the ft_super constraints. But we'd better
* restore tpenv afterwards *)
let old_tpenv = Env.get_tpenv env in
let old_global_tpenv = Env.get_global_tpenv env in
let env = Env.open_tyvars env Pos.none in
(* First extend the environment with the type parameters from the supertype, along
* with their bounds and the function's where constraints
*)
let (env, ty_err1) =
Phase.localize_and_add_generic_parameters_and_where_constraints
~ety_env
env
ft_super.ft_tparams
ft_super.ft_where_constraints
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err1;
(* Reified type parameters should match those in the overridden method (TODO).
* For non-reified parameters, we allow a generic method to override
* a method whose signature is an instance of the generic type. For example,
* foo(int):int
* can be overridden by
* foo<T>(T):T
* To implement this, we use localize_targs to generate fresh type variables for the
* generic parameters, and add bounds and where constraints.
* A more complex example is the following:
* interface I { abstract const type TC as num; }
* Now consider
* class B {
* function foo(num):void;
* }
* overridden by
* class C<T as I> extends B {
* function foo<TF>(TF):void where TF super T::TC;
* }
* We need to find type variable #1 with T::TC <: #1 such that
* (by contravariance of parameter types) num <: #1.
* Clearly #1:=num is a solution, as T::TC <: num from the type constant bound.
* Dually, suppose we have
* class C<T as I> extends B {
* function foo<TF>(TF):void where TF as T::TC;
* }
* This time, we need to find type variable #1 with #1 <: T::TC
* such that num <: #1.
* There is no solution, as by transitivity we need num <: T::TC which does not hold.
*)
let non_reified_tparams =
List.filter ft_sub.ft_tparams ~f:(fun tp ->
match tp.tp_reified with
| Aast.Erased -> true
| _ -> false)
in
let ((env, ty_err2), explicit_targs) =
Phase.localize_targs
~check_well_kinded:true
~is_method:true
~def_pos:p_sub
~use_pos:Pos.none
~use_name:"overriding"
~check_explicit_targs:false
env
non_reified_tparams
[]
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err2;
let tvarl = List.map ~f:fst explicit_targs in
let substs = Decl_subst.make_locl non_reified_tparams tvarl in
let (env, ty_err3) =
Phase.check_tparams_constraints
~use_pos:Pos.none
~ety_env:{ ety_env with substs }
env
ft_sub.ft_tparams
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err3;
(* Localize the function type for the method in the subtype.
* Non-reified generic method parameters will be replaced by the type
* variables generated by localize_targs *)
let ((env, ty_err4), locl_ft_sub) =
Phase.localize_ft ~ety_env:{ ety_env with substs } ~def_pos:p_sub env ft_sub
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err4;
(* Localize the function type for the method in the supertype.
* Generic method parameters will be left alone.
*)
let ((env, ty_err5), locl_ft_super) =
Phase.localize_ft ~ety_env ~def_pos:p_super env ft_super
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err5;
let add_where_constraints env (cstrl : locl_where_constraint list) =
List.fold_left cstrl ~init:env ~f:(fun env (ty1, ck, ty2) ->
Typing_subtype.add_constraint env ck ty1 ty2 (Some on_error))
in
(* Now extend the environment with `where` constraints from the supertype *)
let env = add_where_constraints env locl_ft_super.ft_where_constraints in
(* Check the where constraints from the subtype. *)
(* Localize the where constraints here rather than using locl_ft_sub.ft_where_constraints,
* as localize_ft loses changes to tpenv (see comments in code for localize_ft) *)
let check_where_constraints ~ety_env env cstrl =
let (env, ty_errs) =
List.fold_left
cstrl
~init:(env, [])
~f:(fun (env, ty_errs) (ty, ck, cstr_ty) ->
let ((env, e1), ty) = Phase.localize ~ety_env env ty in
let ((env, e2), cstr_ty) = Phase.localize ~ety_env env cstr_ty in
let (env, e3) =
Typing_generic_constraint.check_constraint env ck ~cstr_ty ty
@@ Some on_error
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)
in
let (env, ty_err6) =
check_where_constraints
~ety_env:{ ety_env with substs }
env
ft_sub.ft_where_constraints
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err6;
(* Finally apply ordinary contra/co subtyping on the function types *)
let (env, ty_err7) =
subtype_funs
~on_error:(Some on_error)
~for_override:true
~check_return
r_sub
locl_ft_sub
r_super
locl_ft_super
env
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err7;
let (env, ty_err8) = Typing_solver.close_tyvars_and_solve env in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err8;
(* Restore the type parameter environment *)
Env.env_with_tpenv (Env.env_with_global_tpenv env old_global_tpenv) old_tpenv |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_subtype_method.mli | open Typing_defs
open Typing_env_types
(** Check that the method with signature ft_sub can be used to override
(is a subtype of) method with signature ft_super. *)
val subtype_method_decl :
check_return:bool ->
env ->
Reason.t ->
decl_fun_type ->
Reason.t ->
decl_fun_type ->
Typing_error.Reasons_callback.t ->
env |
OCaml | hhvm/hphp/hack/src/typing/typing_subtype_tconst.ml | open Hh_prelude
open Typing_defs
module Env = Typing_env
module ITySet = Internal_type_set
module Utils = Typing_utils
(** Make `tvar` equal to `ty::tconstid`. The locl type `tvar` is a
type variable that represents the the type constant ::tconstid of
another variable v. See get_tyvar_type_const below, where such type
variables are created. *)
let make_type_const_equal
env
tvar
(ty : internal_type)
tconstid
~(on_error : Typing_error.Reasons_callback.t option)
~as_tyvar_with_cnstr =
let subtype_error =
Option.map ~f:Typing_error.Reasons_callback.type_constant_mismatch on_error
in
let rec make_equal env ty =
match ty with
| LoclType ty ->
let ety_env = empty_expand_env in
let ((env, e1), tytconst) =
Utils.expand_typeconst
ety_env
env
~as_tyvar_with_cnstr
ty
tconstid
~allow_abstract_tconst:true
~ignore_errors:(Option.is_some as_tyvar_with_cnstr)
in
let (env, e2) = Utils.sub_type env tytconst tvar subtype_error in
let (env, e3) = Utils.sub_type env tvar tytconst subtype_error in
(env, Typing_error.multiple_opt @@ List.filter_map ~f:Fn.id [e1; e2; e3])
| ConstraintType ty ->
(match deref_constraint_type ty with
| (r, Thas_type_member { htm_id; htm_upper = up_ty; htm_lower = lo_ty })
when String.equal htm_id (snd tconstid) ->
let (env, e) = Utils.sub_type env up_ty lo_ty on_error in
(match e with
| Some _ ->
let err_opt =
Option.map
~f:(fun on_error ->
Typing_error.(
apply_reasons
~on_error
(Secondary.Inexact_tconst_access (Reason.to_pos r, tconstid))))
on_error
in
(env, err_opt)
| None ->
(* We constrain the upper and lower bounds to be equal
* between themselves and with the type variable. *)
let (env, e1) = Utils.sub_type env up_ty tvar subtype_error in
let (env, e2) = Utils.sub_type env tvar lo_ty subtype_error in
(env, Option.merge ~f:Typing_error.both e1 e2))
| (_, Thas_type_member _)
| (_, Thas_member _)
| (_, Tcan_index _)
| (_, Tcan_traverse _)
| (_, Tdestructure _) ->
(env, None)
| (_, TCunion (lty, cty)) ->
let (env, e1) = make_equal env (LoclType lty) in
let (env, e2) = make_equal env (ConstraintType cty) in
(env, Option.merge e1 e2 ~f:(fun e1 e2 -> Typing_error.union [e1; e2]))
| (_, TCintersection (lty, cty)) ->
let (env, e1) = make_equal env (LoclType lty) in
let (env, e2) = make_equal env (ConstraintType cty) in
(* TODO: should we be taking the intersection of the errors? *)
(env, Option.merge ~f:Typing_error.both e1 e2))
in
make_equal env ty
(** Add a type constant with id `tyconstid` and type `ty` to a type variable,
and propagate constraints to all type constants `tyconstid` of upper bounds and
lower bounds. *)
let add_tyvar_type_const env var tconstid ty ~on_error =
let env = Env.set_tyvar_type_const env var tconstid ty in
let var_pos = Env.get_tyvar_pos env var in
let upper_bounds = Env.get_tyvar_upper_bounds env var in
let (env, upper_ty_errs) =
ITySet.fold
(fun bound (env, ty_errs) ->
match
make_type_const_equal
env
ty
bound
tconstid
~on_error
~as_tyvar_with_cnstr:(Some var_pos)
with
| (env, Some ty_err) -> (env, ty_err :: ty_errs)
| (env, _) -> (env, ty_errs))
upper_bounds
(env, [])
in
let lower_bounds = Env.get_tyvar_lower_bounds env var in
let (env, ty_errs) =
ITySet.fold
(fun bound (env, ty_errs) ->
match
make_type_const_equal
env
ty
bound
tconstid
~on_error
~as_tyvar_with_cnstr:None
with
| (env, Some ty_err) -> (env, ty_err :: ty_errs)
| (env, _) -> (env, ty_errs))
lower_bounds
(env, upper_ty_errs)
in
(env, Typing_error.multiple_opt ty_errs)
(** For all type constants T of var, make its type equal to ty::T *)
let make_all_type_consts_equal
env var (ty : internal_type) ~on_error ~as_tyvar_with_cnstr =
let is_mixed =
match ty with
| LoclType lty ->
let (_is_supportdyn, env, lty) = Utils.strip_supportdyn env lty in
Utils.is_mixed env lty
| _ -> false
in
if is_mixed then
(env, None)
else
let var_pos = Env.get_tyvar_pos env var in
let as_tyvar_with_cnstr =
if as_tyvar_with_cnstr then
Some var_pos
else
None
in
let (env, ty_errs) =
SMap.fold
(fun _ (tconstid, tconstty) (env, ty_errs) ->
match
make_type_const_equal
env
tconstty
ty
tconstid
~on_error
~as_tyvar_with_cnstr
with
| (env, Some ty_err) -> (env, ty_err :: ty_errs)
| (env, _) -> (env, ty_errs))
(Env.get_tyvar_type_consts env var)
(env, [])
in
(env, Typing_error.multiple_opt ty_errs)
(** `p` is the position where var::tconstid was encountered. *)
let get_tyvar_type_const env var tconstid ~on_error =
match Env.get_tyvar_type_const env var tconstid with
| Some (_pos, ty) -> ((env, None), ty)
| None ->
let var_pos = Env.get_tyvar_pos env var in
let (env, tvar) = Env.fresh_type_invariant env var_pos in
Typing_log.log_new_tvar_for_tconst env (var_pos, var) tconstid tvar;
let env = add_tyvar_type_const env var tconstid tvar ~on_error in
(env, tvar) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_subtype_tconst.mli | open Typing_defs
open Typing_env_types
module Env = Typing_env
(** For all type constant T of type variable, make its type equal to `ty`::T *)
val make_all_type_consts_equal :
env ->
Ident.t ->
internal_type ->
on_error:Typing_error.Reasons_callback.t option ->
as_tyvar_with_cnstr:bool ->
env * Typing_error.t option
(** Get the type of a type constant of a type variable by looking it up in the
environment.
If that type constant is not present, make a fresh invariant
type variable and add it as the type of the type constant in the environment.
*)
val get_tyvar_type_const :
env ->
Ident.t ->
pos_id ->
on_error:Typing_error.Reasons_callback.t option ->
(env * Typing_error.t option) * locl_ty |
OCaml | hhvm/hphp/hack/src/typing/typing_taccess.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 Reason = Typing_reason
module Env = Typing_env
module Log = Typing_log
module Phase = Typing_phase
module TySet = Typing_set
module Cls = Decl_provider.Class
module MakeType = Typing_make_type
(* A guiding principle when expanding a type access C::T is that if C <: D and
we know that D::T = X (represented by an Exact result below), then C::T is
also X. So Exact is propagated down the <: relation, see `update_class_name`
below where this behavior is encoded. *)
(** When the access code is going to return a `Tgeneric "Foo::Bar"`,
we use the following type to tell the difference between legit
accesses from known concrete types (`this`, or expression-
dependent types), and unsound accesses from arbitrary generic
variables. *)
type root_kind =
| ConcreteClass
| GenericType
type context = {
id: pos_id; (** The T in the type access C::T *)
ety_env: expand_env;
(** The expand environment as passed in by Phase.localize *)
generics_seen: TySet.t;
(** A set of visited types used to avoid infinite loops during expansion. *)
allow_abstract: bool;
(** Whether or not an abstract type constant is allowed as the result. In the
future, this boolean should disappear and abstract type constants should
appear only in the class where they are defined. *)
abstract_as_tyvar_at_pos: Pos.t option;
(** If set, abstract type constants will be expanded as type variables. This
is a hack which should naturally go away when the semantics of abstract
type constants is cleaned up. *)
base: locl_ty option;
(** The origin of the extension. For example if TC is a generic parameter
subject to the constraint TC as C and we would like to expand TC::T we
will expand C::T with base set to `Some (Tgeneric "TC")` (and root set
to C). If it is None the base is exactly the current root. *)
root_kind: root_kind; (** See documentation for the [root_kind] type. *)
}
(** The result of an expansion
- Missing err means that the type constant is not present, with error function
to be called if we need to report this
- Exact ty means that the expansion results precisely in 'ty'
- Abstract (n0, [n1, n2, n3], lower_bound, upper_bound) means that the result is a
generic with name n0::T such that:
n0::T as n1::T as n2::T as n3::T as upper_bound super lower_bound *)
type result =
| Missing of Typing_error.t option
| Exact of locl_ty
| Abstract of abstract
and abstract = {
name: string;
names: string list;
lower_bounds: TySet.t;
upper_bounds: TySet.t;
}
let make_reason env id root r =
Reason.Rtypeconst (r, id, lazy (Typing_print.error env root), get_reason root)
(* FIXME: It is bogus to use strings here and put them in Tgeneric; one
possible problem is when a type parameter has a name which conflicts
with a class name *)
let tp_name class_name id = class_name ^ "::" ^ snd id
(** A smart constructor for Abstract that also checks if the type we are
creating is known to be equal to some other type *)
let abstract_or_exact env id ({ name; _ } as abstr) =
let tp_name = tp_name name id in
if not (TySet.is_empty (Env.get_equal_bounds env tp_name [])) then
(* If the resulting abstract type is exactly equal to something,
mark the result as exact.
For example, if we have the following
abstract class Box {
abstract const type T;
}
function addFiveToValue<T1 as Box>(T1 $x) : int where T1::T = int {
return $x->get() + 5;
}
Here, $x->get() has type expr#1::T as T1::T (as Box::T).
But T1::T is exactly equal to int, so $x->get() no longer needs
to be expression dependent. Thus, $x->get() typechecks. *)
Exact (MakeType.generic Reason.Rnone tp_name)
else
Abstract abstr
(** Lookup a type constant in a class and return a result. A type constant has
both a constraint type and assigned type. Which one we choose depends if
the current root is the base (origin) of the expansion, or if it is an
upper bound of the base. *)
let create_root_from_type_constant ctx env root (_class_pos, class_name) class_
=
let { id = (id_pos, id_name) as id; _ } = ctx in
match Env.get_typeconst env class_ id_name with
| None ->
( (env, None),
Missing
(Option.map
ctx.ety_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Smember_not_found
{
pos = id_pos;
kind = `class_typeconst;
class_name;
class_pos = Cls.pos class_;
member_name = id_name;
hint = None;
})) )
| Some typeconst ->
let name = tp_name class_name id in
let (ety_env, has_cycle) =
Typing_defs.add_type_expansion_check_cycles ctx.ety_env (id_pos, name)
in
let ctx = { ctx with ety_env } 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 ->
let seen =
Typing_defs.Type_expansions.ids ctx.ety_env.type_expansions
in
Typing_error.(
primary
@@ Primary.Cyclic_typeconst
{ pos = initial_taccess_pos; tyconst_names = seen }))
in
(* This is a cycle through a type constant that we are using *)
((env, ty_err_opt), Missing None)
| None ->
let drop_exact ty =
(* Legacy behavior is to preserve exactness only on `this` and not
through `this::T` *)
map_ty ty ~f:(function
| Tclass (cid, _, tyl) -> Tclass (cid, nonexact, tyl)
| ty -> ty)
in
let ety_env =
{
ctx.ety_env with
this_ty = drop_exact (Option.value ctx.base ~default:root);
}
in
let abstract_or_exact env ~lower_bounds ~upper_bounds =
let ty_err_opt =
if not ctx.allow_abstract then
let tc_pos = fst typeconst.ttc_name in
Option.map
ctx.ety_env.on_error
~f:
Typing_error.(
fun on_error ->
apply_reasons ~on_error
@@ Secondary.Abstract_tconst_not_allowed
{
pos = id_pos;
decl_pos = tc_pos;
tconst_name = id_name;
})
else
None
in
(* TODO(T59448452): this treatment of abstract type constants is unsound *)
( abstract_or_exact
env
id
{ name = class_name; names = []; lower_bounds; upper_bounds },
ty_err_opt )
in
let to_tys env = function
| Some ty ->
let (env, ty) = Phase.localize ~ety_env env ty in
(env, TySet.singleton ty)
| None -> ((env, None), TySet.empty)
in
(* Don't report errors in expanded definition or constraint.
* These will have been reported at the definition site already. *)
let ety_env = { ety_env with on_error = None } in
(match typeconst.ttc_kind with
(* Concrete type constants *)
| TCConcrete { tc_type = ty } ->
let ((env, ty_err_opt), ty) = Phase.localize ~ety_env env ty in
let ty = map_reason ty ~f:(make_reason env id root) in
((env, ty_err_opt), Exact ty)
(* Abstract type constants *)
| TCAbstract
{ atc_as_constraint = upper; atc_super_constraint = lower; _ } ->
let ((env, e1), lower_bounds) = to_tys env lower in
let ((env, e2), upper_bounds) = to_tys env upper in
let (res, e3) = abstract_or_exact env ~lower_bounds ~upper_bounds in
let ty_err_opt =
Typing_error.multiple_opt @@ List.filter_map ~f:Fn.id [e1; e2; e3]
in
((env, ty_err_opt), res)))
(* Cheap intersection operation. Do not call Typing_intersection.intersect
* as this calls into subtype which in turn calls into expand_with_env below
*)
let intersect ty1 ty2 =
if equal_locl_ty ty1 ty2 then
ty1
else
MakeType.intersection (get_reason ty1) [ty1; ty2]
(* Cheap union operation. Do not call Typing_union.union
* as this calls into subtype which in turn calls into expand_with_env below
*)
let union ty1 ty2 =
if equal_locl_ty ty1 ty2 then
ty1
else
MakeType.union (get_reason ty1) [ty1; ty2]
(* Given the results of projecting a type constant from types t1 , ... , tn,
* determine the result of projecting a type constant from type (t1 | ... | tn).
* If the type constant is missing from any of the disjuncts, then it's treated
* as missing from the union.
*)
let rec union_results err rl =
match rl with
| [] -> Missing err
| [r] -> r
| r1 :: rl ->
let r2 = union_results err rl in
(* Union is defined iff both are defined concretely *)
(match (r1, r2) with
| (Missing err, _)
| (_, Missing err) ->
Missing err
(* In essence, this says (C | D)::TP = (C::TP) | (D::TP) *)
| (Exact ty1, Exact ty2) -> Exact (union ty1 ty2)
(* We don't support projecting through any other kind of union *)
| _ -> Missing err)
(* Given the results of projecting a type constant from types t1, ..., tn,
* determine the result of projecting a type constant from type (t1 & ... & tn).
*)
let rec intersect_results err rl =
match rl with
(* Essentially, this is `mixed`. *)
| [] -> Missing err
| [r] -> r
| r1 :: rs ->
let r2 = intersect_results err rs in
(match (r1, r2) with
| (Missing _, r)
| (r, Missing _) ->
r
(* In essence, we're saying (C & D)::TP = (C::TP) & (D::TP) *)
| (Exact ty1, Exact ty2) -> Exact (intersect ty1 ty2)
(* Here, we merge the bounds on abstract type constants. Effectively this is intersection. *)
| ( Abstract { name; names; lower_bounds = lowerl1; upper_bounds = upperl1 },
Abstract { lower_bounds = lowerl2; upper_bounds = upperl2; _ } ) ->
Abstract
{
name;
names;
lower_bounds = TySet.union lowerl1 lowerl2;
upper_bounds = TySet.union upperl1 upperl2;
}
(* Exact type overrides abstract type: the bound on abstract type will be checked
* against the exact type at implementation site. *)
| (Abstract _, Exact ty)
| (Exact ty, Abstract _) ->
Exact ty)
let rec type_of_result ~ignore_errors ctx env root res =
let type_with_bound env as_tyvar name ~lower_bounds ~upper_bounds =
match as_tyvar with
| Some tyvar_pos ->
let (env, tvar) = Env.fresh_type_invariant env tyvar_pos in
Log.log_new_tvar_for_tconst_access env tyvar_pos tvar name ctx.id;
(env, tvar)
| None ->
let generic_name = tp_name name ctx.id in
let reason = make_reason env ctx.id root Reason.Rnone in
let ty = MakeType.generic reason generic_name in
let env =
TySet.fold
(fun bnd env ->
(* TODO(T59317869): play well with flow sensitivity *)
Env.add_upper_bound_global env generic_name bnd)
upper_bounds
env
in
let env =
TySet.fold
(fun bnd env ->
(* TODO(T59317869): play well with flow sensitivity *)
Env.add_lower_bound_global env generic_name bnd)
lower_bounds
env
in
(env, ty)
in
match res with
| Exact ty -> ((env, None), ty)
| Abstract { name; names = name' :: namel; lower_bounds; upper_bounds } ->
let res' =
Abstract { name = name'; names = namel; lower_bounds; upper_bounds }
in
let ((env, ty_err_opt), ty) =
type_of_result ~ignore_errors ctx env root res'
in
let (env, ty) =
type_with_bound
env
None
name
~lower_bounds
~upper_bounds:(TySet.singleton ty)
in
((env, ty_err_opt), ty)
| Abstract { name; names = []; lower_bounds; upper_bounds } ->
let (env, ty) =
type_with_bound
env
ctx.abstract_as_tyvar_at_pos
name
~lower_bounds
~upper_bounds
in
((env, None), ty)
| Missing err ->
let ty_err_opt =
if not ignore_errors then
err
else
None
in
(* TODO akenn: this is a source of unsoundness *)
let ty =
Typing_utils.mk_tany env (Pos_or_decl.unsafe_to_raw_pos (get_pos root))
in
((env, ty_err_opt), ty)
let update_class_name env id new_name = function
| (Exact _ | Missing _) as res -> res
| Abstract ({ name; names; _ } as abstr) ->
abstract_or_exact
env
id
{ abstr with name = new_name; names = name :: names }
let rec expand ctx env root =
let (env, root) = Env.expand_type env root in
let err =
let (pos, tconst) = ctx.id in
let ty_name = lazy (Typing_print.error env root) in
let reason =
Typing_error.Secondary.Non_object_member
{
pos;
ctxt = `read;
kind = `class_typeconst;
member_name = tconst;
ty_name;
decl_pos = get_pos root;
}
in
Option.map ctx.ety_env.on_error ~f:(fun on_error ->
Typing_error.apply_reasons ~on_error reason)
in
if Typing_utils.is_tyvar_error env root then
((env, None), Missing None)
else
match get_node root with
| Tany _ -> ((env, None), Exact root)
| Tnewtype (name, _, ty) ->
let ctx =
let base = Some (Option.value ctx.base ~default:root) in
let allow_abstract = true in
{ ctx with base; allow_abstract }
in
let ((env, ty_err_opt), res) = expand ctx env ty in
let name = Printf.sprintf "<cls#%s>" name in
((env, ty_err_opt), update_class_name env ctx.id name res)
| Tclass (cid, Nonexact cr, targs)
when Class_refinement.has_refined_const ctx.id cr -> begin
match Class_refinement.get_refined_const ctx.id cr with
| Some { rc_bound = TRexact ty; _ } -> ((env, None), Exact ty)
| Some { rc_bound = TRloose { tr_lower; tr_upper }; _ } ->
let alt_root = mk (get_reason root, Tclass (cid, nonexact, targs)) in
let ((env, ty_err_opt), result) = expand ctx env alt_root in
(match result with
| Exact _
| Missing _ ->
((env, ty_err_opt), result)
| Abstract abstr ->
(* Flag an error if the root is not a concrete class type. *)
let ty_err_opt' =
match ctx.root_kind with
| ConcreteClass -> None
| GenericType ->
let pos = Reason.to_pos (get_reason root) in
Option.map ctx.ety_env.on_error ~f:(fun on_error ->
Typing_error.apply_reasons
~on_error
(Typing_error.Secondary.Inexact_tconst_access (pos, ctx.id)))
in
let ty_err_opt = Option.first_some ty_err_opt' ty_err_opt in
let add_bounds tyset bnds =
List.fold bnds ~init:tyset ~f:(fun tyset t -> TySet.add t tyset)
in
let abstr =
{
abstr with
lower_bounds = add_bounds abstr.lower_bounds tr_lower;
upper_bounds = add_bounds abstr.upper_bounds tr_upper;
}
in
((env, ty_err_opt), Abstract abstr))
| None -> (* unreachable *) ((env, None), Missing None)
end
| Tclass (cls, _, _) -> begin
match Env.get_class env (snd cls) with
| None -> ((env, None), Missing None)
| Some ci ->
(* Hack: `self` in a trait is mistakenly replaced by the trait instead
of the class using the trait, so if a trait is the root, it is
likely because originally there was `self::T` written.
TODO(T54081153): fix `self` in traits and clean this up *)
let allow_abstract =
Ast_defs.is_c_trait (Cls.kind ci) || ctx.allow_abstract
in
let ctx = { ctx with allow_abstract } in
create_root_from_type_constant ctx env root cls ci
end
| Tgeneric (s, tyargs) ->
let ctx =
let root_kind =
let this_name = Naming_special_names.SpecialIdents.this in
(* The `this` type stands for a concrete class. *)
if String.equal s this_name then
ConcreteClass
else
ctx.root_kind
in
let generics_seen = TySet.add root ctx.generics_seen in
let base = Some (Option.value ctx.base ~default:root) in
let allow_abstract = true in
let abstract_as_tyvar_at_pos = None in
{
ctx with
generics_seen;
base;
allow_abstract;
abstract_as_tyvar_at_pos;
root_kind;
}
in
let is_supportdyn_mixed t =
let (is_supportdyn, _, t) = Typing_utils.strip_supportdyn env t in
is_supportdyn && Typing_utils.is_mixed env t
in
(* Ignore seen bounds to avoid infinite loops *)
let upper_bounds =
let ub = Env.get_upper_bounds env s tyargs in
TySet.filter
(fun ty ->
(not (is_supportdyn_mixed ty))
&& (* Also ignore ~T if we've seen T *)
not
(TySet.mem (Typing_utils.strip_dynamic env ty) ctx.generics_seen))
ub
|> TySet.elements
in
(* TODO: should we be taking the intersection of the errors? *)
let ((env, ty_err_opt), resl) =
List.map_env_ty_err_opt
env
upper_bounds
~f:(expand ctx)
~combine_ty_errs:Typing_error.multiple_opt
in
let res = intersect_results err resl in
((env, ty_err_opt), update_class_name env ctx.id s res)
| Tdependent (dep_ty, ty) ->
let ctx =
let root_kind = ConcreteClass in
let base = Some (Option.value ctx.base ~default:root) in
let allow_abstract = true in
let abstract_as_tyvar_at_pos = None in
{ ctx with base; allow_abstract; abstract_as_tyvar_at_pos; root_kind }
in
let ((env, ty_err_opt), res) = expand ctx env ty in
( (env, ty_err_opt),
update_class_name env ctx.id (DependentKind.to_string dep_ty) res )
| Tintersection tyl ->
(* Terrible hack (compatible with previous behaviour) that first attempts to project off the
* non-type-variable conjunects. If this doesn't succeed, then try the type variable
* conjunects, which will cause type-const constraints to be added to the type variables.
*)
let (tyl_vars, tyl_nonvars) =
List.partition_tf tyl ~f:(fun t ->
let (_env, t) = Env.expand_type env t in
is_tyvar t)
in
(* TODO: should we be taking the intersection of the errors? *)
let ((env, e1), resl) =
List.map_env_ty_err_opt
env
tyl_nonvars
~f:(expand ctx)
~combine_ty_errs:Typing_error.multiple_opt
in
let result = intersect_results err resl in
(match result with
| Missing _ ->
(* TODO: should we be taking the intersection of the errors? *)
let ((env, e2), resl) =
List.map_env_ty_err_opt
env
tyl_vars
~f:(expand ctx)
~combine_ty_errs:Typing_error.multiple_opt
in
(* TODO: should we be taking the intersection of the errors? *)
let ty_err_opt =
Option.merge e1 e2 ~f:(fun e1 e2 -> Typing_error.multiple [e1; e2])
in
((env, ty_err_opt), intersect_results err resl)
| _ -> ((env, e1), result))
| Tunion tyl ->
let ((env, ty_err_opt), resl) =
List.map_env_ty_err_opt
env
tyl
~f:(expand ctx)
~combine_ty_errs:Typing_error.union_opt
in
let result = union_results err resl in
((env, ty_err_opt), result)
| Tvar n ->
let (env, ty) =
Typing_subtype_tconst.get_tyvar_type_const
env
n
ctx.id
~on_error:ctx.ety_env.on_error
in
(env, Exact ty)
| Tunapplied_alias _ ->
Typing_defs.error_Tunapplied_alias_in_illegal_context ()
| Taccess _
| Tnonnull
| Tprim _
| Tshape _
| Ttuple _
| Tvec_or_dict _
| Tfun _
| Tdynamic
| Toption _
| Tneg _ ->
((env, None), Missing err)
(** Expands a type constant access like A::T to its definition. *)
let expand_with_env
(ety_env : expand_env)
env
?(ignore_errors = false)
?(as_tyvar_with_cnstr = None)
root
(id : pos_id)
~allow_abstract_tconst =
let ((env, ty_err_opt), ty) =
let ctx =
{
id;
ety_env;
base = None;
generics_seen = TySet.empty;
allow_abstract = allow_abstract_tconst;
abstract_as_tyvar_at_pos = as_tyvar_with_cnstr;
root_kind =
GenericType
(* Worst-case assumption; may be refined during [expand]. *);
}
in
let ((env, e1), res) = expand ctx env root in
let ((env, e2), ty) = type_of_result ~ignore_errors ctx env root res in
let ty_err_opt = Option.merge e1 e2 ~f:Typing_error.both in
((env, ty_err_opt), ty)
in
let (env, ty) = Log.log_type_access ~level:1 root id (env, ty) in
((env, ty_err_opt), ty)
(* This is called with non-nested type accesses e.g. this::T1::T2 is
* represented by (this, [T1; T2])
*)
let referenced_typeconsts env ety_env (root, ids) =
let ((env, e1), root) = Phase.localize ~ety_env env root in
let (((_env, ty_errs), _ty), res) =
List.fold
ids
~init:(((env, Option.to_list e1), root), [])
~f:(fun (((env, ty_errs), root), acc) (pos, tconst) ->
let (env, tyl) =
Typing_utils.get_concrete_supertypes ~abstract_enum:true env root
in
let acc =
List.fold tyl ~init:acc ~f:(fun acc ty ->
let (env, ty) = Env.expand_type env ty in
match get_node ty with
| Tclass ((_, class_name), _, _) ->
let ( >>= ) = Option.( >>= ) in
Option.value
~default:acc
( Env.get_class env class_name >>= fun class_ ->
Env.get_typeconst env class_ tconst >>= fun typeconst ->
Some ((typeconst.Typing_defs.ttc_origin, tconst, pos) :: acc)
)
| _ -> acc)
in
let ((env, ty_err_opt), root) =
expand_with_env
ety_env
env
~as_tyvar_with_cnstr:None
root
(Pos_or_decl.of_raw_pos pos, tconst)
~allow_abstract_tconst:true
in
let ty_errs =
Option.value_map
~default:ty_errs
~f:(fun e -> e :: ty_errs)
ty_err_opt
in
(((env, ty_errs), root), acc))
in
(res, Typing_error.multiple_opt ty_errs)
(*****************************************************************************)
(* Exporting *)
(*****************************************************************************)
let () = Typing_utils.expand_typeconst_ref := expand_with_env |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_taccess.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
(** Returns (class_name, tconst_name, tconst_reference_position) for each type
constant referenced in a type access. *)
val referenced_typeconsts :
env ->
expand_env ->
decl_ty * Aast.sid list ->
(string * string * Pos.t) list * Typing_error.t option |
OCaml | hhvm/hphp/hack/src/typing/typing_tdef.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 Utils
module Reason = Typing_reason
module Env = Typing_env
module SN = Naming_special_names
module Subst = Decl_subst
module TUtils = Typing_utils
module Phase = Typing_phase
module MakeType = Typing_make_type
(*****************************************************************************)
(* Expanding type definition *)
(*****************************************************************************)
let expand_typedef_ ?(force_expand = false) ety_env env r (x : string) argl =
let pos = Reason.to_pos r in
let td = unsafe_opt @@ Env.get_typedef env x in
let {
td_pos;
td_module = _;
td_vis = _;
td_tparams;
td_type;
td_as_constraint;
td_super_constraint = _;
td_is_ctx = _;
td_attributes = _;
td_internal = _;
td_docs_url = _;
} =
td
in
let (ety_env, has_cycle) =
Typing_defs.add_type_expansion_check_cycles ety_env (td_pos, x)
in
match has_cycle with
| Some initial_taccess_pos_opt ->
(* Only report a cycle if it's through the specified definition *)
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 = pos }))
in
let (env, ty) =
Env.fresh_type_error env (Pos_or_decl.unsafe_to_raw_pos pos)
in
((env, ty_err_opt), (ety_env, ty))
| None ->
let should_expand =
force_expand
|| Env.is_typedef_visible
env
~expand_visible_newtype:ety_env.expand_visible_newtype
~name:x
td
in
let ety_env =
{
ety_env with
substs = Subst.make_locl td_tparams argl;
on_error =
(* Don't report errors in expanded definition.
* These will have been reported at the definition site already. *)
None;
}
in
let (env, expanded_ty) =
if should_expand then
Phase.localize ~ety_env env td_type
else
let (env, td_as_constraint) =
match td_as_constraint with
| None ->
let r_cstr =
Reason.Rimplicit_upper_bound (Reason.to_pos r, "?nonnull")
in
let cstr = MakeType.mixed r_cstr in
((env, None), cstr)
| Some cstr ->
(* Special case for supportdyn<T> defined with "as T" in order to
* avoid supportdynamic.hhi appearing in reason *)
if String.equal x SN.Classes.cSupportDyn then
((env, None), List.hd_exn argl)
else
Phase.localize ~ety_env env cstr
in
(* TODO: update Tnewtype and pass in super constraint as well *)
(env, mk (r, Tnewtype (x, argl, td_as_constraint)))
in
(env, (ety_env, with_reason expanded_ty r))
let expand_typedef ety_env env r type_name argl =
let (env, (_ety_env, ty)) = expand_typedef_ ety_env env r type_name argl in
(env, ty)
(* Expand a typedef, smashing abstraction and collecting a trail
* of where the typedefs come from. *)
let force_expand_typedef ~ety_env env (t : locl_ty) =
let rec aux e1 ety_env env t =
let default () =
( (env, e1),
t,
Typing_defs.Type_expansions.positions ety_env.type_expansions )
in
match deref t with
| (_, Tnewtype (x, _, _)) when String.equal SN.Classes.cEnumClassLabel x ->
(* Labels are Resources at runtime, so we don't want to force them
* to string. MemberOf on the other hand are "typed alias" on the
* underlying type so it's ok to force them. So we only special case
* Labels here *)
default ()
| (r, Tnewtype (x, argl, _))
when not (Env.is_enum env x || Env.is_enum_class env x) ->
let ((env, e2), (ety_env, ty)) =
expand_typedef_ ~force_expand:true ety_env env r x argl
in
aux (Option.merge e1 e2 ~f:Typing_error.both) ety_env env ty
| _ -> default ()
in
aux None ety_env env t
let () = TUtils.expand_typedef_ref := expand_typedef |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_tdef.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.
*
*)
(** Expand a typedef, smashing abstraction and collecting a trail
of where the typedefs come from. *)
val force_expand_typedef :
ety_env:Typing_defs.expand_env ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
(Typing_env_types.env * Typing_error.t option)
* Typing_defs.locl_ty
* Pos_or_decl.t list |
OCaml | hhvm/hphp/hack/src/typing/typing_toplevel.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 Aast
open Typing_defs
open Typing_env_types
open Typing_helpers
module Reason = Typing_reason
module Env = Typing_env
module MakeType = Typing_make_type
module Phase = Typing_phase
module EnvFromDef = Typing_env_from_def
module TCO = TypecheckerOptions
module SN = Naming_special_names
module Profile = Typing_toplevel_profile
let is_literal_with_trivially_inferable_type (_, _, e) =
Option.is_some @@ Decl_utils.infer_const e
let check_if_this_def_is_the_winner ctx name_type (pos, name) : bool =
if String.is_empty name || String.equal name "\\" then
(* In case of some parse errors, the AST contains definitions with empty names.
There's no useful duplicate-name-check we can do here.
Return [false] because there's no such thing as the winner for the empty name. *)
false
else
match Decl_provider.is_this_def_the_winner ctx name_type (pos, name) with
| Decl_provider.Winner -> true
| Decl_provider.Loser_to prev_pos ->
Errors.add_error
Naming_error.(
to_user_error @@ Error_name_already_bound { name; pos; prev_pos });
false
| Decl_provider.Not_found ->
(* This is impossible! The fact that we have an AST def for [name] implies
that Decl_provider should be able to find at least one decl with this name.
Only explanations are (1) weirdness with Provider_context.entry which
gives slightly different answers from what direct-decl-parser provides
e.g. in case of incorrect parse trees, or order of winner; (2) disk race
where the file on disk has changed but we haven't yet updated naming table. *)
HackEventLogger.decl_consistency_bug
"Decl consistency: Ast definition but no decl"
~data:name
~pos:(Pos.to_relative_string pos |> Pos.string);
false
let fun_def ctx fd : Tast.fun_def Tast_with_dynamic.t option =
let f = fd.fd_fun in
let tcopt = Provider_context.get_tcopt ctx in
Profile.measure_elapsed_time_and_report tcopt None fd.fd_name @@ fun () ->
Counters.count Counters.Category.Typecheck @@ fun () ->
Errors.run_with_span f.f_span @@ fun () ->
let (_ : bool) =
check_if_this_def_is_the_winner ctx FileInfo.Fun fd.fd_name
in
let env = EnvFromDef.fun_env ~origin:Decl_counters.TopLevel ctx fd in
with_timeout env fd.fd_name @@ fun env ->
(* reset the expression dependent display ids for each function body *)
Reason.expr_display_id_map := IMap.empty;
let pos = fst fd.fd_name in
let env = Env.open_tyvars env (fst fd.fd_name) in
let env = Env.set_env_callable_pos env pos in
let (env, user_attributes) =
Typing.attributes_check_def env SN.AttributeKinds.fn f.f_user_attributes
in
let (env, file_attrs) = Typing.file_attributes env fd.fd_file_attributes in
let (env, cap_ty, unsafe_cap_ty) =
Typing_coeffects.type_capability
env
f.f_ctxs
f.f_unsafe_ctxs
(fst fd.fd_name)
in
let env = Env.set_current_module env fd.fd_module in
let env = Env.set_internal env fd.fd_internal in
let env =
if
Naming_attributes.mem
SN.UserAttributes.uaSupportDynamicType
f.f_user_attributes
then
Env.set_support_dynamic_type env true
else
env
in
let no_auto_likes =
Naming_attributes.mem SN.UserAttributes.uaNoAutoLikes f.f_user_attributes
in
let env =
if no_auto_likes then
Env.set_no_auto_likes env true
else
env
in
let env = Env.load_cross_packages_from_attr env f.f_user_attributes in
(* Is sound dynamic enabled, and the function marked <<__SupportDynamicType>> explicitly or implicitly? *)
let sdt_function =
TCO.enable_sound_dynamic (Provider_context.get_tcopt (Env.get_ctx env))
&& Env.get_support_dynamic_type env
in
List.iter ~f:(Typing_error_utils.add_typing_error ~env)
@@ Typing_type_wellformedness.fun_def env fd;
Env.make_depend_on_current_module env;
let (env, ty_err_opt) =
Phase.localize_and_add_ast_generic_parameters_and_where_constraints
env
~ignore_errors:false
fd.fd_tparams
fd.fd_where_constraints
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
let env = Env.set_fn_kind env f.f_fun_kind in
let (return_decl_ty, params_decl_ty) =
hint_fun_decl ~params:f.f_params ~ret:f.f_ret env
in
let hint_pos =
match f.f_ret with
| (_, None) -> fst fd.fd_name
| (_, Some (pos, _)) -> pos
in
(* Do we need to check the body of the function again, under dynamic assumptions? *)
let sdt_dynamic_check_required =
sdt_function
&& not
(Typing_dynamic.function_parameters_safe_for_dynamic
~this_class:None
env
params_decl_ty)
in
let ety_env =
empty_expand_env_with_on_error
(Typing_error.Reasons_callback.invalid_type_hint hint_pos)
in
let (env, return_ty) =
Typing_return.make_return_type
~ety_env
~this_class:None
env
~supportdyn:(sdt_function && not sdt_dynamic_check_required)
~hint_pos
~explicit:return_decl_ty
~default:None
in
let return =
Typing_return.make_info
hint_pos
f.f_fun_kind
f.f_user_attributes
env
return_ty
in
let (env, _) =
Typing_coeffects.register_capabilities env cap_ty unsafe_cap_ty
in
let sound_dynamic_check_saved_env = env in
let (env, param_tys) =
Typing_param.make_param_local_tys
~dynamic_mode:false
~no_auto_likes
env
params_decl_ty
f.f_params
in
let can_read_globals =
Typing_subtype.is_sub_type
env
cap_ty
(MakeType.capability (get_reason cap_ty) SN.Capabilities.accessGlobals)
in
let (env, typed_params) =
Typing.bind_params
env
~can_read_globals
~no_auto_likes
f.f_ctxs
param_tys
f.f_params
in
let env = set_tyvars_variance_in_callable env return_ty.et_type param_tys in
let local_tpenv = Env.get_tpenv env in
let disable =
Naming_attributes.mem
SN.UserAttributes.uaDisableTypecheckerInternal
f.f_user_attributes
in
Typing_memoize.check_function env f;
let ((env, tb), had_errors) =
Errors.run_and_check_for_errors (fun () ->
Typing.fun_
~native:(Typing_native.is_native_fun ~env f)
~disable
env
return
pos
f.f_body
f.f_fun_kind)
in
begin
match hint_of_type_hint f.f_ret with
| None ->
Typing_error_utils.add_typing_error
~env
Typing_error.(primary @@ Primary.Expecting_return_type_hint pos)
| Some _ -> ()
end;
let (env, tparams) = List.map_env env fd.fd_tparams ~f:Typing.type_param in
let (env, e1) = Typing_solver.close_tyvars_and_solve env in
let (env, e2) = Typing_solver.solve_all_unsolved_tyvars env in
let ret_hint = hint_of_type_hint f.f_ret in
let fun_ =
{
Aast.f_annotation = Env.save local_tpenv env;
Aast.f_readonly_this = f.f_readonly_this;
Aast.f_span = f.f_span;
Aast.f_readonly_ret = f.f_readonly_ret;
Aast.f_ret = (return_ty.et_type, ret_hint);
Aast.f_params = typed_params;
Aast.f_ctxs = f.f_ctxs;
Aast.f_unsafe_ctxs = f.f_unsafe_ctxs;
Aast.f_fun_kind = f.f_fun_kind;
Aast.f_user_attributes = user_attributes;
Aast.f_body = { Aast.fb_ast = tb };
Aast.f_external = f.f_external;
Aast.f_doc_comment = f.f_doc_comment;
}
in
let under_normal_assumptions =
{
Aast.fd_mode = fd.fd_mode;
Aast.fd_name = fd.fd_name;
Aast.fd_fun = fun_;
Aast.fd_file_attributes = file_attrs;
Aast.fd_namespace = fd.fd_namespace;
Aast.fd_internal = fd.fd_internal;
Aast.fd_module = fd.fd_module;
Aast.fd_tparams = tparams;
Aast.fd_where_constraints = fd.fd_where_constraints;
}
in
let fundef_of_dynamic
(dynamic_env, dynamic_params, dynamic_body, dynamic_return_ty) =
let open Aast in
{
under_normal_assumptions with
fd_fun =
{
under_normal_assumptions.fd_fun with
f_annotation = Env.save local_tpenv dynamic_env;
f_ret = (dynamic_return_ty, ret_hint);
f_params = dynamic_params;
f_body = { fb_ast = dynamic_body };
};
}
in
let (under_normal_assumptions, under_dynamic_assumptions) =
if
sdt_dynamic_check_required
&& (not had_errors)
&& not (TCO.skip_check_under_dynamic tcopt)
then
let env = { env with checked = Tast.CUnderNormalAssumptions } in
let under_normal_assumptions =
let f_annotation = Env.save local_tpenv env in
Aast.
{
under_normal_assumptions with
fd_fun = { under_normal_assumptions.fd_fun with f_annotation };
}
in
let dynamic_components =
Typing.check_function_dynamically_callable
~this_class:None
sound_dynamic_check_saved_env
(Some fd.fd_name)
f
params_decl_ty
return_ty.et_type
in
(under_normal_assumptions, Some (fundef_of_dynamic dynamic_components))
else
(under_normal_assumptions, None)
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;
{ Tast_with_dynamic.under_normal_assumptions; under_dynamic_assumptions }
let class_def ctx class_ =
Counters.count Counters.Category.Typecheck @@ fun () ->
Errors.run_with_span class_.c_span @@ fun () ->
if check_if_this_def_is_the_winner ctx FileInfo.Class class_.c_name then
(* [Typing_class.class_def] is unusual in that it can't work properly
unless it's the winner and has the same capitalization.
If either isn't met, it will report to telemetry and return None. *)
Typing_class.class_def ctx class_
else
None
let typedef_def ctx typedef =
let tcopt = Provider_context.get_tcopt ctx in
Profile.measure_elapsed_time_and_report tcopt None typedef.t_name @@ fun () ->
Errors.run_with_span typedef.t_span @@ fun () ->
let (_ : bool) =
check_if_this_def_is_the_winner ctx FileInfo.Typedef typedef.t_name
in
Typing_typedef.typedef_def ctx typedef
let gconst_def ctx cst =
let tcopt = Provider_context.get_tcopt ctx in
Profile.measure_elapsed_time_and_report tcopt None cst.cst_name @@ fun () ->
Counters.count Counters.Category.Typecheck @@ fun () ->
Errors.run_with_span cst.cst_span @@ fun () ->
let (_ : bool) =
check_if_this_def_is_the_winner ctx FileInfo.Const cst.cst_name
in
let env = EnvFromDef.gconst_env ~origin:Decl_counters.TopLevel ctx cst in
List.iter ~f:(Typing_error_utils.add_typing_error ~env)
@@ Typing_type_wellformedness.global_constant env cst;
let (typed_cst_value, (env, ty_err_opt)) =
let ((_, _, init) as value) = cst.cst_value in
match (cst.cst_type, init) with
| (Some _, Omitted) when Env.is_hhi env ->
(* We don't require global consts to have a value set for decl purposes
* in HHI files so it may just be a placeholder, therefore we don't care
* about checking the value and simply pass it through *)
let (env, te, _ty) = Typing.expr env value in
(te, (env, None))
| (Some hint, _) ->
let ty = Decl_hint.hint env.decl_env hint in
let ty =
Typing_enforceability.compute_enforced_ty ~this_class:None env ty
in
let ((env, ty_err_opt1), dty) =
Phase.localize_possibly_enforced_no_subst env ~ignore_errors:false ty
in
let (env, te, value_type) =
let expected =
ExpectedTy.make_and_allow_coercion (fst hint) Reason.URhint dty
in
Typing.expr_with_pure_coeffects env ~expected value
in
let (env, ty_err_opt2) =
Typing_coercion.coerce_type
(fst hint)
Reason.URhint
env
value_type
dty
Typing_error.Callback.unify_error
in
let ty_err_opt =
Option.merge ~f:Typing_error.both ty_err_opt1 ty_err_opt2
in
(te, (env, ty_err_opt))
| (None, _) ->
if
(not (is_literal_with_trivially_inferable_type value))
&& not (Env.is_hhi env)
then
Errors.add_error
Naming_error.(to_user_error @@ Missing_typehint (fst cst.cst_name));
let (env, te, _value_type) = Typing.expr_with_pure_coeffects env value in
(te, (env, None))
in
Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env);
{
Aast.cst_annotation = Env.save (Env.get_tpenv env) env;
Aast.cst_mode = cst.cst_mode;
Aast.cst_name = cst.cst_name;
Aast.cst_type = cst.cst_type;
Aast.cst_value = typed_cst_value;
Aast.cst_namespace = cst.cst_namespace;
Aast.cst_span = cst.cst_span;
Aast.cst_emit_id = cst.cst_emit_id;
}
let module_def ctx md =
Counters.count Counters.Category.Typecheck @@ fun () ->
Errors.run_with_span md.md_span @@ fun () ->
let (_ : bool) =
check_if_this_def_is_the_winner ctx FileInfo.Module md.md_name
in
let env = EnvFromDef.module_env ~origin:Decl_counters.TopLevel ctx md in
let (env, file_attributes) =
Typing.file_attributes env md.md_file_attributes
in
let (env, user_attributes) =
Typing.attributes_check_def
env
SN.AttributeKinds.module_
md.md_user_attributes
in
{
md with
Aast.md_annotation = Env.save (Env.get_tpenv env) env;
Aast.md_user_attributes = user_attributes;
Aast.md_file_attributes = file_attributes;
}
let nast_to_tast ~(do_tast_checks : bool) ctx nast :
Tast.program Tast_with_dynamic.t =
let convert_def = function
(* Sometimes typing will just return `None` but that should only be the case
* if an error had already been registered e.g. in naming
*)
| Fun f -> begin
match fun_def ctx f with
| Some fs -> Some (Tast_with_dynamic.map ~f:(fun f -> Aast.Fun f) fs)
| None -> None
end
| Constant gc ->
Some
(Tast_with_dynamic.mk_without_dynamic
@@ Aast.Constant (gconst_def ctx gc))
| Typedef td ->
Some
(Tast_with_dynamic.mk_without_dynamic
@@ Aast.Typedef (typedef_def ctx td))
| Class c -> begin
match class_def ctx c with
| Some cs -> Some (Tast_with_dynamic.map ~f:(fun c -> Aast.Class c) cs)
| None -> None
end
(* We don't typecheck top level statements:
* https://docs.hhvm.com/hack/unsupported/top-level
* so just create the minimal env for us to construct a Stmt.
*)
| Stmt s ->
let env = Typing_env_types.empty ctx Relative_path.default ~droot:None in
Some
(Tast_with_dynamic.mk_without_dynamic
@@ Aast.Stmt (snd (Typing.stmt env s)))
| Module md ->
Some
(Tast_with_dynamic.mk_without_dynamic @@ Aast.Module (module_def ctx md))
| SetModule sm ->
Some (Tast_with_dynamic.mk_without_dynamic @@ Aast.SetModule sm)
| Namespace _
| NamespaceUse _
| SetNamespaceEnv _
| FileAttributes _ ->
failwith
"Invalid nodes in NAST. These nodes should be removed during naming."
in
if do_tast_checks then Nast_check.program ctx nast;
let tast = List.filter_map nast ~f:convert_def |> Tast_with_dynamic.collect in
(* We only do TAST checks for non-dynamic components *)
if do_tast_checks then
Tast_check.program ctx tast.Tast_with_dynamic.under_normal_assumptions;
tast |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_toplevel.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.
*
*)
(** If the input is the winning definition of its symbol,
returns [Some t] and as a side effect populates errors encountered
during typechecking. If not the winning definition, returns None
and emits a "duplicate name" error. (We're not able to check
a class that isn't the winning declaration, because we use both
the AST and the folded-decl in the work of checking, and the only
folded-decl available is that of the winner, so we can't proceed
if this definition isn't the winner.
If any method within the class took longer than `--config timeout=<secs>`
to typecheck (default infinite) then it's omitted from the resulting Tast. *)
val class_def :
Provider_context.t -> Nast.class_ -> Tast.class_ Tast_with_dynamic.t option
val typedef_def : Provider_context.t -> Nast.typedef -> Tast.typedef
(** If it takes longer than `--config timeout=<secs>` then produces None.
Otherwise, it returns either 1 or 2 tasts, depending on whether sound-dynamic is enabled. *)
val fun_def :
Provider_context.t -> Nast.fun_def -> Tast.fun_def Tast_with_dynamic.t option
val gconst_def : Provider_context.t -> Nast.gconst -> Tast.gconst
val module_def : Provider_context.t -> Nast.module_def -> Tast.module_def
(** Run typing on the given named AST (NAST) to produced a typed AST (TAST).
Set [do_tast_checks] to [false] to skip running TAST checks on the resulting
TAST. This means that the associated list of errors may be incomplete. This is
useful for performance in cases where we want the TAST, but don't need a correct
list of errors.
It is unfortunate that this routine exists alongside [Typing_check_job.calc_errors_and_tast]
which does almost exactly the same thing, except it also does [Naming], and
there are minor differences in treatment of some toplevel nodes. *)
val nast_to_tast :
do_tast_checks:bool ->
Provider_context.t ->
Nast.program ->
Tast.program Tast_with_dynamic.t |
OCaml | hhvm/hphp/hack/src/typing/typing_toplevel_profile.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module Env = Typing_env
let measure_elapsed_time_and_report tcopt env_opt id f =
if TypecheckerOptions.profile_top_level_definitions tcopt then (
let start_time = Unix.gettimeofday () in
let result = f () in
let end_time = Unix.gettimeofday () in
let elapsed_time_ms = (end_time -. start_time) *. 1000. in
let id =
match Option.(env_opt >>= Env.get_self_id) with
| Some class_name -> class_name ^ "::" ^ snd id
| None -> snd id
in
Printf.printf "%s: %0.2fms\n" id elapsed_time_ms;
result
) else
f () |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_toplevel_profile.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(** Measure the time it takes to evaluate the last argument and write the
result to console along with the given identifier. *)
val measure_elapsed_time_and_report :
TypecheckerOptions.t ->
Typing_env_types.env option ->
'a * string ->
(unit -> 'b) ->
'b |
OCaml | hhvm/hphp/hack/src/typing/typing_try.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the "hack" directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*)
[@@@warning "-33"] (* in OCaml 4.06.0, this can be inlined *)
open Hh_prelude
open Common
[@@@warning "+33"]
module C = Typing_continuations
module CMap = C.Map
(* See the type system specs for try for what's going on here *)
type ('env, 'continuation) union_function =
'env ->
C.t ->
'continuation option ->
'continuation option ->
'env * 'continuation option
let get_cont_cont (cont_cont_map : 'a CMap.t CMap.t) (cont1 : C.t) (cont2 : C.t)
: 'a option =
match CMap.find_opt cont1 cont_cont_map with
| None -> None
| Some cont_map -> CMap.find_opt cont2 cont_map
let make_new_cont
(union : ('env, 'continuation) union_function)
(locals_map : 'continuation CMap.t CMap.t)
(env : 'env)
(cont : C.t) : 'env * 'continuation option =
let ctx_cont_next = get_cont_cont locals_map cont C.Next in
let ctxs_x_cont = CMap.map (CMap.find_opt cont) locals_map in
CMap.fold_env env union ctxs_x_cont ctx_cont_next
let finally_merge
(union : ('env, 'continuation) union_function)
(env : 'env)
(locals_map : 'continuation CMap.t CMap.t) : 'env * 'continuation CMap.t =
let make_and_add_new_cont env locals cont =
let (env, ctxopt) = make_new_cont union locals_map env cont in
let locals =
match ctxopt with
| None -> CMap.remove cont locals
| Some ctx -> CMap.add cont ctx locals
in
(env, locals)
in
List.fold_left_env
env
~f:make_and_add_new_cont
~init:CMap.empty
Typing_cont_key.all |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_try.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 CMap = Typing_continuations.Map
val finally_merge :
(Typing_env_types.env ->
CMap.key ->
Typing_per_cont_env.per_cont_entry option ->
Typing_per_cont_env.per_cont_entry option ->
Typing_env_types.env * Typing_per_cont_env.per_cont_entry option) ->
Typing_env_types.env ->
Typing_per_cont_env.t CMap.t ->
Typing_env_types.env * Typing_per_cont_env.t |
OCaml | hhvm/hphp/hack/src/typing/typing_typedef.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 Aast
open Tast
module Reason = Typing_reason
module Env = Typing_env
module SN = Naming_special_names
module Phase = Typing_phase
module EnvFromDef = Typing_env_from_def
module DTMap = Typing_case_types.DataType.Map
let get_cnstr_errs env tcstr reverse t_pos ty =
match tcstr with
| Some tcstr ->
let ((env, ty_err_opt1), cstr) =
Phase.localize_hint_no_subst env ~ignore_errors:false tcstr
in
let (env, ty_err_opt2) =
Typing_ops.sub_type
t_pos
Reason.URnewtype_cstr
env
(if reverse then
cstr
else
ty)
(if reverse then
ty
else
cstr)
Typing_error.Callback.newtype_alias_must_satisfy_constraint
in
(env, Option.merge ~f:Typing_error.both ty_err_opt1 ty_err_opt2)
| _ -> (env, None)
let create_err_from_cycles cycles pos name =
let relevant_cycles =
List.filter
~f:(fun Decl_typedef_expand.{ td_name; _ } -> String.equal name td_name)
cycles
in
let cycle_to_error Decl_typedef_expand.{ decl_pos; _ } =
Typing_error.(primary @@ Primary.Cyclic_typedef { pos; decl_pos })
in
let err =
match List.map relevant_cycles ~f:cycle_to_error with
| [] -> None
| head :: tail -> Some (List.fold_left tail ~init:head ~f:Typing_error.both)
in
err
let casetype_def env typedef =
let {
t_annotation = ();
t_name = (t_pos, t_name);
t_tparams = _;
t_as_constraint = _;
t_super_constraint = _;
t_kind = varaints;
t_user_attributes = _;
t_vis;
t_mode = _;
t_namespace = _;
t_span = _;
t_emit_id = _;
t_is_ctx = _;
t_file_attributes = _;
t_internal = _;
t_module = _;
t_docs_url = _;
t_doc_comment = _;
} =
typedef
in
match (t_vis, varaints) with
| (Aast.CaseType, (_, Hunion hints)) ->
let data_type_map = Typing_case_types.mk_data_type_mapping env hints in
let errs =
DTMap.filter_map
begin
fun tag hints ->
if List.length hints > 1 then
let err =
Typing_error.Primary.CaseType.Overlapping_variant_types
{
pos = t_pos;
name = t_name;
tag = Typing_case_types.DataType.Tag.name tag;
why =
lazy
begin
List.map hints ~f:(fun (p, h) ->
let h =
Decl_hint.hint
env.Typing_env_types.decl_env
(p, h)
in
( Pos_or_decl.of_raw_pos p,
Typing_print.full_strip_ns_decl env h ))
end;
}
in
Some (Typing_error.casetype err)
else
None
end
data_type_map
in
let err1 = Typing_error.multiple_opt @@ DTMap.values errs in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) err1;
env
| _ -> env
let typedef_def ctx typedef =
let env = EnvFromDef.typedef_env ~origin:Decl_counters.TopLevel ctx typedef in
let env = Env.set_current_module env typedef.t_module in
let env = Env.set_internal env typedef.t_internal in
let (env, ty_err_opt1) =
Phase.localize_and_add_ast_generic_parameters_and_where_constraints
env
~ignore_errors:false
typedef.t_tparams
[]
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt1;
List.iter ~f:(Typing_error_utils.add_typing_error ~env)
@@ Typing_type_wellformedness.typedef env typedef;
Env.make_depend_on_current_module env;
Typing_variance.typedef env typedef;
let {
t_annotation = ();
t_name = (t_pos, t_name);
t_tparams = _;
t_as_constraint = tascstr;
t_super_constraint = tsupercstr;
t_kind = hint;
t_user_attributes = _;
t_vis = vis;
t_mode = _;
t_namespace = _;
t_span = _;
t_emit_id = _;
t_is_ctx = _;
t_file_attributes = _;
t_internal = _;
t_module = _;
t_docs_url = _;
t_doc_comment = _;
} =
typedef
in
let (env, ty_opt) =
if TypecheckerOptions.use_type_alias_heap (Env.get_tcopt env) then
match Decl_provider.get_typedef ctx t_name with
| Some _ ->
let (ty, ty_err_opt2) =
let ty = Decl_hint.hint env.Typing_env_types.decl_env hint in
let ctx = Env.get_ctx env in
let r = Typing_defs_core.get_reason ty in
let (ty, cycles) =
Decl_typedef_expand.expand_typedef_with_error
~force_expand:true
ctx
r
t_name
in
let err = create_err_from_cycles cycles t_pos t_name in
(ty, err)
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt2;
let ety_env = Typing_defs.empty_expand_env in
let ((env, ty_err_opt3), ty) = Phase.localize ~ety_env env ty in
let env = casetype_def env typedef in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt3;
let (env, ty_err_opt3) = get_cnstr_errs env tascstr false t_pos ty in
let (env, ty_err_opt4) = get_cnstr_errs env tsupercstr true t_pos ty in
Option.iter
~f:(Typing_error_utils.add_typing_error ~env)
(Option.merge ~f:Typing_error.both ty_err_opt3 ty_err_opt4);
(env, Some ty)
| None ->
(* We get here if there's a "Name already bound" error. *)
(env, None)
else
let ((env, ty_err_opt2), ty) =
Phase.localize_hint_no_subst
env
~ignore_errors:false
~report_cycle:(t_pos, t_name)
hint
in
let env = casetype_def env typedef in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt2;
let (env, ty_err_opt3) = get_cnstr_errs env tascstr false t_pos ty in
let (env, ty_err_opt4) = get_cnstr_errs env tsupercstr true t_pos ty in
Option.iter
~f:(Typing_error_utils.add_typing_error ~env)
(Option.merge ~f:Typing_error.both ty_err_opt3 ty_err_opt4);
(env, Some ty)
in
let env =
match (vis, hint, ty_opt) with
| (Aast.CaseType, (pos, Hunion hints), Some ty) ->
let unrecoverable_hint env hint =
let ((env, _), hint_ty) =
Phase.localize_hint_no_subst env ~ignore_errors:false hint
in
let (env, refined_ty) =
Typing.refine_hint
~pos
~reason:(Typing_reason.Rwitness (fst hint))
env
ty
hint
in
not @@ Typing_utils.is_sub_type env refined_ty hint_ty
in
let hints = List.filter hints ~f:(unrecoverable_hint env) in
let _ =
match hints with
| [] -> ()
| _ ->
let err =
Typing_error.Primary.CaseType.Unrecoverable_variant_type
{
pos = t_pos;
name = Utils.strip_ns t_name;
hints =
List.map hints ~f:(fun (p, h) ->
let h =
Decl_hint.hint env.Typing_env_types.decl_env (p, h)
in
(p, Typing_print.full_strip_ns_decl env h));
}
in
Typing_error_utils.add_typing_error ~env @@ Typing_error.casetype err
in
env
| _ -> env
in
let env =
match hint with
| (_pos, Hshape { nsi_allows_unknown_fields = _; nsi_field_map }) ->
let get_name sfi = sfi.sfi_name in
Typing_shapes.check_shape_keys_validity
env
(List.map ~f:get_name nsi_field_map)
| _ -> env
in
let (env, user_attributes) =
Typing.attributes_check_def
env
SN.AttributeKinds.typealias
typedef.t_user_attributes
in
let (env, tparams) =
List.map_env env typedef.t_tparams ~f:Typing.type_param
in
let (env, file_attributes) =
Typing.file_attributes env typedef.t_file_attributes
in
{
Aast.t_annotation = Env.save (Env.get_tpenv env) env;
Aast.t_name = typedef.t_name;
Aast.t_mode = typedef.t_mode;
Aast.t_vis = typedef.t_vis;
Aast.t_user_attributes = user_attributes;
Aast.t_as_constraint = typedef.t_as_constraint;
Aast.t_super_constraint = typedef.t_super_constraint;
Aast.t_kind = typedef.t_kind;
Aast.t_tparams = tparams;
Aast.t_namespace = typedef.t_namespace;
Aast.t_span = typedef.t_span;
Aast.t_emit_id = typedef.t_emit_id;
Aast.t_is_ctx = typedef.t_is_ctx;
Aast.t_file_attributes = file_attributes;
Aast.t_internal = typedef.t_internal;
Aast.t_module = typedef.t_module;
Aast.t_docs_url = typedef.t_docs_url;
Aast.t_doc_comment = typedef.t_doc_comment;
} |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_typedef.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(** This is a helper for [Typing_toplevel.typedef_def]. Call that instead. *)
val typedef_def : Provider_context.t -> Nast.typedef -> Tast.typedef |
OCaml | hhvm/hphp/hack/src/typing/typing_type_member.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 TySet = Typing_set
type type_member =
| Error of Typing_error.t option
| Exact of locl_ty
| Abstract of {
name: pos_id;
(* The bounds are optional: None for lower is equivalent
* to nothing and None for upper is equivalent to mixed.
* Having them optional ensures that [collect_bounds] below
* does not pick up trivial bounds and clutter the tpenv. *)
lower: locl_ty option;
upper: locl_ty option;
}
type unknown_concrete_class_kind =
| EDT of Ident.t
| This
let make_missing_err ~on_error cls_id const_name =
match on_error with
| Some on_error ->
Some
Typing_error.(
apply_reasons ~on_error
@@ Secondary.Missing_class_constant
{ pos = fst cls_id; class_name = snd cls_id; const_name })
| None -> None
(* Lookups a type member from the class decl of `cls_id`. *)
let lookup_class_decl_type_member env ~on_error ~this_ty cls_id type_id =
let ety_env = { empty_expand_env with this_ty; on_error } in
(* Things are not perfect here, localize may itself call into
* Typing_taccess, leading to legacy behavior. *)
let localize env decl_ty = Typing_utils.localize ~ety_env env decl_ty in
match Env.get_class env (snd cls_id) with
| None -> (env, Error (make_missing_err ~on_error cls_id (snd type_id)))
| Some cls -> begin
match Env.get_typeconst env cls (snd type_id) with
| None -> (env, Error (make_missing_err ~on_error cls_id (snd type_id)))
| Some { ttc_kind = TCConcrete tcc; _ } ->
let ((env, err_opt), lty) = localize env tcc.tc_type in
( env,
(match err_opt with
| Some _ -> Error err_opt
| None -> Exact lty) )
| Some { ttc_kind = TCAbstract tca; ttc_name = name; _ } ->
let ((env, err_opt_1), lty_as) =
match tca.atc_as_constraint with
| Some decl_ty ->
let ((env, err_opt), lty) = localize env decl_ty in
((env, err_opt), Some lty)
| None -> ((env, None), None)
in
let ((env, err_opt_2), lty_super) =
match tca.atc_super_constraint with
| Some decl_ty ->
let ((env, err_opt), lty) = localize env decl_ty in
((env, err_opt), Some lty)
| None -> ((env, None), None)
in
( env,
(match Option.first_some err_opt_1 err_opt_2 with
| Some _ as err_opt -> Error err_opt
| None -> Abstract { name; lower = lty_super; upper = lty_as }) )
end
let lookup_class_type_member env ~on_error ~this_ty (cls_id, exact) type_id =
let (combine_lower, combine_upper) =
let dedup_then ~f tys =
let ts = TySet.of_list tys in
if TySet.is_empty ts then
None
else
Some (f (TySet.elements ts))
in
( dedup_then ~f:(Typing_make_type.union Reason.Rnone),
dedup_then ~f:(Typing_make_type.intersection Reason.Rnone) )
in
let refined_type_member =
match exact with
| Nonexact cr -> begin
match Class_refinement.get_refined_const type_id cr with
| Some { rc_bound = TRexact ty; _ } -> Exact ty
| Some { rc_bound = TRloose { tr_lower; tr_upper }; _ } ->
let lower = combine_lower tr_lower in
let upper = combine_upper tr_upper in
(* FIXME(refinements): The position is pointing at
* the class when we would like to point in the
* refinement. *)
let name = (fst cls_id, snd type_id) in
Abstract { name; lower; upper }
| None -> Error None
end
| _ -> Error None
in
match refined_type_member with
| Exact _ -> (env, refined_type_member)
| Abstract { name = _; lower = mem_lower; upper = mem_upper } ->
(* In this case, we still lookup the class decl to potentially
* obtain more information on the type member. *)
(match
lookup_class_decl_type_member env ~on_error ~this_ty cls_id type_id
with
| (env, Error _) -> (env, refined_type_member)
| (_env, Exact _) as result -> result
| (env, Abstract { name = cls_name; lower = cls_lower; upper = cls_upper })
->
let to_list b1 b2 = List.filter_map ~f:Fn.id [b1; b2] in
let lower = combine_lower (to_list mem_lower cls_lower) in
let upper = combine_upper (to_list mem_upper cls_upper) in
(env, Abstract { name = cls_name; lower; upper }))
| _ -> lookup_class_decl_type_member env ~on_error ~this_ty cls_id type_id
let make_type_member env ~on_error ~this_ty ucc_kind bnd_tys type_id =
let rec collect_bounds env lo_bnds up_bnds = function
| bnd_ty :: bnd_tys ->
let (env, bnd_ty) = Env.expand_type env bnd_ty in
(match deref bnd_ty with
| (_, Tclass (x_bnd, exact_bnd, _tyl_bnd)) ->
let (env, type_member) =
lookup_class_type_member
env
~on_error
~this_ty
(x_bnd, exact_bnd)
type_id
in
let (lo_bnds, up_bnds) =
match type_member with
| Error _ -> (lo_bnds, up_bnds)
| Exact ty -> (ty :: lo_bnds, ty :: up_bnds)
| Abstract { name = _; lower; upper } ->
let maybe_add bnds =
Option.fold ~init:bnds ~f:(Fun.flip List.cons)
in
(maybe_add lo_bnds lower, maybe_add up_bnds upper)
in
collect_bounds env lo_bnds up_bnds bnd_tys
| (_, Tintersection tyl) ->
collect_bounds env lo_bnds up_bnds (tyl @ bnd_tys)
| (_, _) -> collect_bounds env lo_bnds up_bnds bnd_tys)
| [] -> (env, lo_bnds, up_bnds)
in
let rigid_tvar_name =
let ucc_string_id =
match ucc_kind with
| This -> "this"
| EDT eid -> DependentKind.to_string (DTexpr eid)
in
ucc_string_id ^ "::" ^ snd type_id
in
let reason = Reason.Rnone in
let ty = Typing_make_type.generic reason rigid_tvar_name in
let (env, lower_bounds, upper_bounds) = collect_bounds env [] [] bnd_tys in
let add_bounds bounds add env =
List.fold bounds ~init:env ~f:(fun env bnd -> add env rigid_tvar_name bnd)
in
let env = add_bounds lower_bounds Env.add_lower_bound env in
let env = add_bounds upper_bounds Env.add_upper_bound env in
(env, ty) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_type_member.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
(** This module is meant to eventually replace Typing_taccess,
with drastically simpler logic. The idea here is to only
have *lookup* logic on class types, unlike Typing_taccess
that aims to work on any locl type. *)
(** The localized result of a type member lookup; in case it is
[Abstract] existing lower and upper bounds are also returned. *)
type type_member =
| Error of Typing_error.t option
| Exact of locl_ty
| Abstract of {
name: pos_id;
lower: locl_ty option;
upper: locl_ty option;
}
(** Locl types are able to describe unknown concrete class types.
Either via expression-dependent types (those represent the
runtime class type of an object resulting from an expression
evaluation). Or via the this type in a possibly abstract class
(meant to represent the concrete class type of the object that
will be the receiver when the method is invoked). *)
type unknown_concrete_class_kind =
| EDT of Ident.t
| This
(** Lookups a type member in a class definition, or in the exact
refinement information available. *)
val lookup_class_type_member :
env ->
on_error:Typing_error.Reasons_callback.t option ->
this_ty:locl_ty ->
pos_id * exact ->
pos_id ->
env * type_member
(** Given an unknown concrete class ([Tdependent(_)] or
[Tgeneric("this")]) and its bounds, creates a rigid type
variable that stands for the type constant found in the
concrete class. *)
val make_type_member :
env ->
on_error:Typing_error.Reasons_callback.t option ->
this_ty:locl_ty ->
unknown_concrete_class_kind ->
locl_ty list ->
pos_id ->
env * locl_ty |
OCaml | hhvm/hphp/hack/src/typing/typing_type_wellformedness.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
open Typing_env_types
open Utils
module Env = Typing_env
module FunUtils = Decl_fun_utils
module Inst = Decl_instantiate
module Phase = Typing_phase
module Subst = Decl_subst
module Cls = Decl_provider.Class
(** This module checks well-formedness of type hints. See .mli file for more. *)
type env = {
typedef_tparams: Nast.tparam list;
tenv: Typing_env_types.env;
}
let check_tparams_constraints env use_pos tparams targs =
let ety_env : expand_env =
{ empty_expand_env with substs = Subst.make_locl tparams targs }
in
Phase.check_tparams_constraints ~use_pos ~ety_env env tparams
let loclty_of_hint unchecked_tparams env h =
let hint_pos = fst h in
let decl_ty = Decl_hint.hint env.decl_env h in
let unchecked_tparams =
List.map
unchecked_tparams
~f:(Decl_hint.aast_tparam_to_decl_tparam env.decl_env)
in
let tyl =
List.map unchecked_tparams ~f:(fun t ->
mk (Reason.Rwitness_from_decl (fst t.tp_name), Typing_defs.make_tany ()))
in
let subst = Inst.make_subst unchecked_tparams tyl in
let decl_ty = Inst.instantiate subst decl_ty in
let ety_env =
if TypecheckerOptions.strict_wellformedness (Env.get_tcopt env) > 1 then
empty_expand_env_with_on_error
(Typing_error.Reasons_callback.invalid_type_hint hint_pos)
else
empty_expand_env
in
let ety_env = { ety_env with expand_visible_newtype = false } in
let ((env, ty_err_opt), locl_ty) = Phase.localize env ~ety_env decl_ty in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
(env, hint_pos, locl_ty)
let check_hrefinement unchecked_tparams env h rl =
let (env, _, locl_ty) = loclty_of_hint unchecked_tparams env h in
match get_node locl_ty with
| Tclass (cls_id, _, _) ->
let get_class_const =
match Env.get_class env (snd cls_id) with
| Some cls -> begin
fun const_sid ->
match Env.get_typeconst env cls (snd const_sid) with
| Some ttc -> `Found ttc
| None -> `Missing
end
| _ -> (fun _ -> `Skip)
in
let check_ref r =
let (const_sid, is_ctx) =
match r with
| Rctx (sid, _) -> (sid, true)
| Rtype (sid, _) -> (sid, false)
in
let on_error =
Typing_error.Reasons_callback.invalid_class_refinement (fst const_sid)
in
match get_class_const const_sid with
| `Skip -> None
| `Found ttc when Bool.(ttc.ttc_is_ctx = is_ctx) -> None
| `Missing ->
Some
Typing_error.(
apply_reasons ~on_error
@@ Secondary.Missing_class_constant
{
pos = fst cls_id;
class_name = snd cls_id;
const_name = snd const_sid;
})
| `Found ttc ->
let kind_str is_ctx =
if is_ctx then
"ctx"
else
"type"
in
let correct_kind = kind_str ttc.ttc_is_ctx in
let wrong_kind = kind_str is_ctx in
Some
Typing_error.(
apply_reasons ~on_error
@@ Secondary.Invalid_refined_const_kind
{
pos = fst cls_id;
class_name = snd cls_id;
const_name = snd const_sid;
correct_kind;
wrong_kind;
})
in
List.iter rl ~f:(fun r ->
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) (check_ref r))
| _ -> ()
(** Mostly check constraints on type parameters. *)
let check_happly unchecked_tparams env h =
let (env, hint_pos, locl_ty) = loclty_of_hint unchecked_tparams env h in
let (env, ty_err_opt) =
match get_node locl_ty with
| Tnewtype (type_name, targs, _cstr_ty) ->
(match Env.get_typedef env type_name with
| None -> (env, None)
| Some typedef ->
check_tparams_constraints env hint_pos typedef.td_tparams targs)
| Tclass (cls, _, targs) ->
(match Env.get_class env (snd cls) with
| Some cls ->
check_tparams_constraints env hint_pos (Cls.tparams cls) targs
| None -> (env, None))
| _ -> (env, None)
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
env
let rec context_hint ?(in_signature = true) env (p, h) =
Typing_kinding.Simple.check_well_kinded_context_hint
~in_signature
env.tenv
(p, h);
hint_ ~in_signature env p h
and hint_ ~in_signature env p h_ =
let hint env (p, h) = hint_ ~in_signature env p h in
let hint_opt env = Option.value_map ~f:(hint env) ~default:[] in
let hints env xs = List.concat_map xs ~f:(hint env) in
match h_ with
| Hany
| Herr
| Hmixed
| Hwildcard
| Hnonnull
| Hprim _
| Hthis
| Haccess _
| Habstr _
| Hdynamic
| Hnothing ->
[]
| Hoption (_, Hprim Tnull) ->
Lint.option_null p;
[]
| Hoption (_, Hprim Tvoid) ->
[
Typing_error.(
primary @@ Primary.Option_return_only_typehint { pos = p; kind = `void });
]
| Hoption (_, Hprim Tnoreturn) ->
[
Typing_error.(
primary
@@ Primary.Option_return_only_typehint { pos = p; kind = `noreturn });
]
| Hoption (_, Hmixed) ->
Lint.option_mixed p;
[]
| Hvec_or_dict (ty1, ty2) -> hint_opt env ty1 @ hint env ty2
| Htuple hl
| Hunion hl
| Hintersection hl ->
hints env hl
| Hoption h
| Hsoft h
| Hlike h ->
hint env h
| Hfun
{
hf_is_readonly = _;
hf_param_tys = hl;
hf_param_info = _;
hf_variadic_ty = variadic_hint;
hf_ctxs;
hf_return_ty = h;
hf_is_readonly_return = _;
} ->
hints env hl
@ hint env h
@ hint_opt env variadic_hint
@ contexts_opt env hf_ctxs
| Happly ((p, "\\Tuple"), _)
| Happly ((p, "\\tuple"), _) ->
[Typing_error.(wellformedness @@ Primary.Wellformedness.Tuple_syntax p)]
| Happly ((_, x), hl) as h -> begin
match Env.get_class_or_typedef env.tenv x with
| None -> []
| Some (Env.TypedefResult _) ->
let (_ : Typing_env_types.env) =
check_happly env.typedef_tparams env.tenv (p, h)
in
hints env hl
| Some (Env.ClassResult _) ->
let (_ : Typing_env_types.env) =
check_happly env.typedef_tparams env.tenv (p, h)
in
hints env hl
end
| Hrefinement (hr, rl) as h ->
check_hrefinement env.typedef_tparams env.tenv (p, h) rl;
let refinement_hints =
List.fold rl ~init:[] ~f:(fun rl r ->
match r with
| Rctx (_, CRexact h) -> h :: rl
| Rctx (_, CRloose { cr_lower = hl; cr_upper = hr }) ->
Option.to_list hl @ Option.to_list hr @ rl
| Rtype (_, TRexact h) -> h :: rl
| Rtype (_, TRloose { tr_lower = hl; tr_upper = hr }) -> hl @ hr @ rl)
in
hints env (hr :: refinement_hints)
| Hshape { nsi_allows_unknown_fields = _; nsi_field_map } ->
let compute_hint_for_shape_field_info { sfi_hint; _ } = hint env sfi_hint in
List.concat_map ~f:compute_hint_for_shape_field_info nsi_field_map
| Hfun_context _ ->
(* TODO(coeffects): check if arg is a function type in the locals? *)
[]
| Hvar _ ->
(* TODO(coeffects) *)
[]
and contexts env (_, hl) = List.concat_map ~f:(context_hint env) hl
and contexts_opt env = Option.value_map ~default:[] ~f:(contexts env)
let hint ?(in_signature = true) env (p, h) =
(* Do not use this one recursively to avoid quadratic runtime! *)
Typing_kinding.Simple.check_well_kinded_hint ~in_signature env.tenv (p, h);
hint_ ~in_signature env p h
let hint_opt ?in_signature env =
Option.value_map ~default:[] ~f:(hint ?in_signature env)
let hints ?in_signature env = List.concat_map ~f:(hint ?in_signature env)
let type_hint env th =
Option.value_map ~default:[] ~f:(hint env) (hint_of_type_hint th)
let fun_param env param = type_hint env param.param_type_hint
let fun_params env = List.concat_map ~f:(fun_param env)
let tparam env t =
List.concat_map t.Aast.tp_constraints ~f:(fun (_, h) -> hint env h)
let tparams env = List.concat_map ~f:(tparam env)
let where_constr env (h1, _, h2) = hint env h1 @ hint env h2
let where_constrs env = List.concat_map ~f:(where_constr env)
let requirements env = List.concat_map ~f:(fun (h, _kind) -> hint env h)
let fun_ tenv f =
let env = { typedef_tparams = []; tenv } in
let err_opt = FunUtils.check_params f.f_params in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env:tenv) err_opt;
type_hint env f.f_ret @ fun_params env f.f_params
let fun_def tenv fd =
(* Add type parameters to typing environment and localize the bounds
and where constraints *)
let (tenv, ty_err_opt) =
Phase.localize_and_add_ast_generic_parameters_and_where_constraints
tenv
~ignore_errors:true
fd.fd_tparams
fd.fd_where_constraints
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env:tenv) ty_err_opt;
let env = { typedef_tparams = []; tenv } in
tparams env fd.fd_tparams
@ fun_ tenv fd.fd_fun
@ where_constrs env fd.fd_where_constraints
let enum_opt env =
let f { e_base; e_constraint; _ } =
hint env e_base @ hint_opt env e_constraint
in
Option.value_map ~default:[] ~f
let const env { Aast.cc_type; _ } = hint_opt env cc_type
let consts env cs = List.concat_map ~f:(const env) cs
let typeconsts env tcs =
let f tconst =
match tconst.c_tconst_kind with
| TCAbstract { c_atc_as_constraint; c_atc_super_constraint; c_atc_default }
->
hint_opt env c_atc_as_constraint
@ hint_opt env c_atc_super_constraint
@ hint_opt env c_atc_default
| TCConcrete { c_tc_type } -> hint env c_tc_type
in
List.concat_map ~f tcs
(* Treat private or internal class members as internal *)
let at_least_internal = function
| Internal
| Private ->
true
| Protected
| Public ->
false
let class_vars env cvs =
let f cv =
let tenv = Env.set_internal env.tenv (at_least_internal cv.cv_visibility) in
let env = { env with tenv } in
type_hint env cv.cv_type
in
List.concat_map ~f cvs
let method_ env m =
(* Add method type parameters to environment and localize the bounds
and where constraints *)
let (tenv, ty_err_opt) =
Phase.localize_and_add_ast_generic_parameters_and_where_constraints
env.tenv
~ignore_errors:true
m.m_tparams
m.m_where_constraints
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env:tenv) ty_err_opt;
(* Only throw hack error if class and method are both public *)
let tenv =
Env.set_internal
tenv
(at_least_internal m.m_visibility || Env.get_internal tenv)
in
let env = { env with tenv } in
fun_params env m.m_params
@ tparams env m.m_tparams
@ where_constrs env m.m_where_constraints
@ type_hint env m.m_ret
let methods env = List.concat_map ~f:(method_ env)
let method_opt env = Option.value_map ~default:[] ~f:(method_ env)
let hint_no_kind_check env (p, h) = hint_ ~in_signature:true env p h
let class_ tenv c =
let env = { typedef_tparams = []; tenv } in
let {
c_span = _;
c_annotation = _;
c_mode = _;
c_final = _;
c_is_xhp = _;
c_has_xhp_keyword = _;
c_kind;
c_name = _;
c_tparams;
c_extends;
c_uses;
c_xhp_category = _;
c_reqs;
c_implements;
c_where_constraints;
c_consts;
c_typeconsts;
c_vars;
c_methods;
c_xhp_children = _;
c_xhp_attrs = _;
(* Collapsed into c_vars during Naming *)
c_xhp_attr_uses = _;
(* These represent `attribute :a;` declarations, and it is a parse error
* to write `attribute :a<string>` *)
c_namespace = _;
c_user_attributes = _;
c_file_attributes = _;
c_enum;
c_doc_comment = _;
c_emit_id = _;
c_internal = _;
c_module = _;
c_docs_url = _;
} =
c
in
(* Add type parameters to typing environment and localize the bounds *)
let (tenv, ty_err_opt) =
let req_class_constraints =
List.filter_map c_reqs ~f:(fun req ->
match req with
| (t, RequireClass) ->
let pos = fst t in
Some ((pos, Hthis), Ast_defs.Constraint_eq, t)
| _ -> None)
in
Phase.localize_and_add_ast_generic_parameters_and_where_constraints
tenv
~ignore_errors:true
c_tparams
(req_class_constraints @ c_where_constraints)
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env:tenv) ty_err_opt;
let env = { env with tenv } in
let (c_constructor, c_statics, c_methods) = split_methods c_methods in
let (c_static_vars, c_vars) = split_vars c_vars in
List.concat
[
(if not Ast_defs.(is_c_interface c_kind) then
method_opt env c_constructor
else
[]);
tparams env c_tparams;
where_constrs env c_where_constraints;
(* Classes inherited are not signatures from the point of view of modules because the trait
being use'd does not need to be seen by users of the class *)
hints ~in_signature:false env c_extends;
hints ~in_signature:false env c_implements;
hints ~in_signature:false env c_uses;
(if TypecheckerOptions.strict_wellformedness (Env.get_tcopt env.tenv) > 0
then
requirements env c_reqs
else
[]);
typeconsts env c_typeconsts;
class_vars env c_static_vars;
class_vars env c_vars;
consts env c_consts;
methods env c_statics;
methods env c_methods;
enum_opt env c_enum;
]
let typedef tenv t =
let {
t_tparams;
t_annotation = _;
t_name = _;
t_as_constraint;
t_super_constraint;
t_kind;
t_mode = _;
t_vis;
t_namespace = _;
t_user_attributes = _;
t_span = _;
t_emit_id = _;
t_is_ctx = _;
t_file_attributes = _;
t_internal = _;
t_module = _;
t_docs_url = _;
t_doc_comment = _;
} =
t
in
(* We don't allow constraints on typdef parameters, but we still
need to record their kinds in the generic var environment *)
let where_constraints = [] in
let tenv_with_typedef_tparams =
let (env, ty_err_opt) =
Phase.localize_and_add_ast_generic_parameters_and_where_constraints
tenv
~ignore_errors:true
t_tparams
where_constraints
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
env
in
(* We only need to check that the type alias as a public API if it's transparent, since
an opaque type alias is inherently internal *)
let should_check_internal_signature =
Aast.equal_typedef_visibility t_vis Transparent
in
(* For typdefs, we do want to do the simple kind checks on the body
(e.g., arities match up), but no constraint checks. We need to check the
kinds of typedefs separately, because check_happly replaces all the generic
parameters of typedefs by Tany, which makes the kind check moot *)
maybe
(* We always check the constraints for internal types, so treat in_signature:true *)
(Typing_kinding.Simple.check_well_kinded_hint ~in_signature:true)
tenv_with_typedef_tparams
t_as_constraint;
maybe
(Typing_kinding.Simple.check_well_kinded_hint ~in_signature:true)
tenv_with_typedef_tparams
t_super_constraint;
Typing_kinding.Simple.check_well_kinded_hint
~in_signature:should_check_internal_signature
tenv_with_typedef_tparams
t_kind;
let env =
{
typedef_tparams =
(match t_vis with
| Transparent ->
(* Since type aliases cannot have constraints we shouldn't check
* if its type params satisfy the constraints of any tapply it
* references.
*)
t.t_tparams
| CaseType
| Opaque
| OpaqueModule ->
[]);
tenv;
}
in
(* We checked the kinds already above. *)
Option.value_map ~default:[] ~f:(hint_no_kind_check env) t.t_as_constraint
@ Option.value_map
~default:[]
~f:(hint_no_kind_check env)
t.t_super_constraint
@ hint_no_kind_check env t_kind
let global_constant tenv gconst =
let env = { typedef_tparams = []; tenv } in
let {
cst_annotation = _;
cst_mode = _;
cst_name = _;
cst_type;
cst_value = _;
cst_namespace = _;
cst_span = _;
cst_emit_id = _;
} =
gconst
in
hint_opt env cst_type
let hint tenv h =
let env = { typedef_tparams = []; tenv } in
hint ~in_signature:false env h
(** Check well-formedness of type hints. See .mli file for more. *)
let expr tenv ((), _p, e) =
(* We don't recurse on expressions here because this is called by Typing.expr *)
match e with
| ExpressionTree
{
et_hint = h;
et_splices = _;
et_function_pointers = _;
et_virtualized_expr = _;
et_runtime_expr = _;
et_dollardollar_pos = _;
}
| Is (_, h)
| As (_, h, _)
| Upcast (_, h)
| Cast (h, _) ->
hint tenv h
| New (_, hl, _, _, _)
| Call { targs = hl; _ } ->
List.concat_map hl ~f:(fun (_, h) -> hint tenv h)
| Lfun (f, _)
| Efun { ef_fun = f; _ } ->
fun_ tenv f
| Invalid _
| Darray _
| Varray _
| Shape _
| ValCollection _
| KeyValCollection _
| Null
| This
| True
| False
| Omitted
| Id _
| Lvar _
| Dollardollar _
| Clone _
| Array_get _
| Obj_get _
| Class_get _
| Class_const _
| FunctionPointer _
| Int _
| Float _
| String _
| String2 _
| PrefixedString _
| Yield _
| Await _
| ReadonlyExpr _
| Tuple _
| List _
| Unop _
| Binop _
| Pipe _
| Eif _
| Xml _
| Import _
| Collection _
| Lplaceholder _
| Method_caller _
| Pair _
| EnumClassLabel _
| ET_Splice _
| Hole _
| Package _ ->
[]
(** Check well-formedness of type hints. See .mli file for more. *)
let _toplevel_def tenv = function
(* This function is not used but ensures we don't forget to
* extend this module for future top-level definitions we may add. *)
| Fun f ->
let {
fd_namespace = _;
fd_mode = _;
fd_file_attributes = _;
fd_fun;
fd_name = _;
fd_internal = _;
fd_module = _;
fd_tparams = _;
fd_where_constraints = _;
} =
f
in
fun_ tenv fd_fun
| Constant gc -> global_constant tenv gc
| Typedef td -> typedef tenv td
| Class c -> class_ tenv c
| Stmt _
| Namespace _
| NamespaceUse _
| SetNamespaceEnv _
| FileAttributes _
| SetModule _
(* TODO(T108206307) *)
| Module _ ->
[] |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_type_wellformedness.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(** This module checks wellformedness of type hints in the decls and bodies.
Wellformedness checks include:
- constraints on type parameters (e.g. C<string> where C requires T as arraykey)
- hint well-kinded-ness
- trivial syntactic errors:
- writing ?nonnull instead of mixed
- ?void, ?noreturn, ?mixed
- Tuple<X, Y> instead of (X, Y))
NB: this is akin to well-formedness in e.g.
"Featherweight Java: A Minimal Core Calculus for Java and GJ", 2002,
Igarashi, Pierce, Wadler. *)
val fun_def : Typing_env_types.env -> Nast.fun_def -> Typing_error.t list
val class_ : Typing_env_types.env -> Nast.class_ -> Typing_error.t list
val typedef : Typing_env_types.env -> Nast.typedef -> Typing_error.t list
val global_constant : Typing_env_types.env -> Nast.gconst -> Typing_error.t list
(** Check type wellformedness of any hint appearing in this
expression, e.g. parameter type hints of lambda expressions,
hints in `is` and `as` expressions, etc. *)
val expr : Typing_env_types.env -> Nast.expr -> Typing_error.t list |
OCaml | hhvm/hphp/hack/src/typing/typing_tyvar_occurrences.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type t = {
tyvar_occurrences: ISet.t IMap.t;
(** A map to track where each type variable occurs,
more precisely in the type of which other type variables.
E.g. if #1 is bound to (#2 | int), then this map contains the entry
#2 -> { #1 }
This is based on shallow binding, i.e. in the example above, if #2
is mapped to #3, then tyvar_occurrences would be:
#2 -> { #1 }
#3 -> { #2 }
but we would not record that #3 occurs in #1.
When a type variable v gets solved or the type bound to it gets simplified,
we simplify the unions and intersections of the types bound to the
type variables associated to v in this map.
So in our example, if #2 gets solved to int,
we simplify #1 to (int | int) = int.
There are only entries for variables that are unsolved or contain
other unsolved type variables. Variables that are solved and contain
no other unsolved type variables get removed from this map. *)
tyvars_in_tyvar: ISet.t IMap.t;
(** Mapping of type variables to the type variables contained in their
types which are either unsolved or themselves contain unsolved type
variables.
This is the dual of tyvar_occurrences. *)
}
module Log = struct
open Typing_log_value
let iset_imap_as_value map =
Map
(IMap.fold
(fun i vars m -> SMap.add (var_as_string i) (varset_as_value vars) m)
map
SMap.empty)
let tyvar_occurrences_as_value = iset_imap_as_value
let tyvars_in_tyvar_as_value = iset_imap_as_value
let as_value x =
let { tyvar_occurrences; tyvars_in_tyvar } = x in
make_map
[
("tyvar_occurrences", tyvar_occurrences_as_value tyvar_occurrences);
("tyvars_in_tyvar", tyvars_in_tyvar_as_value tyvars_in_tyvar);
]
end
let init = { tyvar_occurrences = IMap.empty; tyvars_in_tyvar = IMap.empty }
let get_tyvar_occurrences x v =
Option.value (IMap.find_opt v x.tyvar_occurrences) ~default:ISet.empty
let get_tyvars_in_tyvar x v =
Option.value (IMap.find_opt v x.tyvars_in_tyvar) ~default:ISet.empty
let set_tyvar_occurrences x v vars =
{ x with tyvar_occurrences = IMap.add v vars x.tyvar_occurrences }
(** Make v occur in v', i.e. add v' to the occurrences of v. *)
let add_tyvar_occurrence x v ~occurs_in:v' =
let vars = get_tyvar_occurrences x v in
let vars = ISet.add v' vars in
let x = set_tyvar_occurrences x v vars in
x
let add_tyvar_occurrences x vars ~occur_in:v =
ISet.fold (fun v' x -> add_tyvar_occurrence x v' ~occurs_in:v) vars x
let set_tyvars_in_tyvar x v vars =
{ x with tyvars_in_tyvar = IMap.add v vars x.tyvars_in_tyvar }
let make_tyvars_occur_in_tyvar x vars ~occur_in:v =
let x = add_tyvar_occurrences x vars ~occur_in:v in
let x = set_tyvars_in_tyvar x v vars in
x
let remove_tyvar_occurrence x v ~no_more_occurs_in:v' =
let vars = get_tyvar_occurrences x v in
let vars = ISet.remove v' vars in
let x = set_tyvar_occurrences x v vars in
x
let remove_tyvar_from_tyvar x ~from:v v' =
let vars = get_tyvars_in_tyvar x v in
let vars = ISet.remove v' vars in
let x = set_tyvars_in_tyvar x v vars in
x
let make_tyvar_no_more_occur_in_tyvar x v ~no_more_in:v' =
let x = remove_tyvar_occurrence x v ~no_more_occurs_in:v' in
let x = remove_tyvar_from_tyvar x ~from:v' v in
x
let contains_unsolved_tyvars x v =
not @@ ISet.is_empty (get_tyvars_in_tyvar x v)
(** Update the tyvar occurrences after unbinding a type variable. *)
let unbind_tyvar x v =
let vars_in_v = get_tyvars_in_tyvar x v in
(* update tyvar_occurrences. *)
let x =
ISet.fold
(fun v' x -> remove_tyvar_occurrence x v' ~no_more_occurs_in:v)
vars_in_v
x
in
(* update tyvars_in_tyvar *)
let x = set_tyvars_in_tyvar x v ISet.empty in
x
let occurs_in x occuring_tv ~in_:containing_tv =
let occurs = ISet.mem containing_tv (get_tyvar_occurrences x occuring_tv) in
let contains = ISet.mem occuring_tv (get_tyvars_in_tyvar x containing_tv) in
assert (Bool.equal occurs contains);
occurs
let remove_var x v =
let occurrences = get_tyvar_occurrences x v in
let x =
ISet.fold
(fun occ x -> make_tyvar_no_more_occur_in_tyvar x v ~no_more_in:occ)
occurrences
x
in
let x = { x with tyvar_occurrences = IMap.remove v x.tyvar_occurrences } in
let vars_in_v = get_tyvars_in_tyvar x v in
let x =
ISet.fold
(fun var_in_v x ->
make_tyvar_no_more_occur_in_tyvar x var_in_v ~no_more_in:v)
vars_in_v
x
in
let x = { x with tyvars_in_tyvar = IMap.remove v x.tyvars_in_tyvar } in
x |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_tyvar_occurrences.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type t
module Log : sig
val as_value : t -> Typing_log_value.value
end
val init : t
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_tyvars_occur_in_tyvar : t -> ISet.t -> occur_in:Ident.t -> t
val make_tyvar_no_more_occur_in_tyvar : t -> Ident.t -> no_more_in:int -> t
(** Update the tyvar occurrences after unbinding a type variable. *)
val unbind_tyvar : t -> Ident.t -> t
val occurs_in : t -> Ident.t -> in_:Ident.t -> bool
(** remove variable from the occurrence structure.
Does not try and be clever, especially does not perform any
type simplification. *)
val remove_var : t -> Ident.t -> t |
OCaml | hhvm/hphp/hack/src/typing/typing_union.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 Reason = Typing_reason
module TySet = Typing_set
module Utils = Typing_utils
module MakeType = Typing_make_type
module Nast = Aast
module Cls = Decl_provider.Class
exception Dont_simplify
module Log = struct
let log_union r ty1 ty2 (env, result) =
Typing_log.(
log_with_level env "union" ~level:1 (fun () ->
log_types
(Reason.to_pos r)
env
[
Log_head
( "Typing_union.union",
[
Log_type ("ty1", ty1);
Log_type ("ty2", ty2);
Log_type ("result", result);
] );
]));
(env, result)
let log_simplify_union r ty1 ty2 (env, result) =
Typing_log.(
log_with_level env "union" ~level:2 (fun () ->
log_types
(Reason.to_pos r)
env
[
Log_head
( "Typing_union.simplify_union",
[
Log_type ("ty1", ty1);
Log_type ("ty2", ty2);
(match result with
| None -> Log_head ("result: None", [])
| Some ty -> Log_type ("result: Some", ty));
] );
]));
(env, result)
let log_union_list r tyl (env, result) =
Typing_log.(
log_with_level env "union" ~level:1 (fun () ->
log_types
(Reason.to_pos r)
env
[
Log_head
( "Typing_union.union_list",
List.map tyl ~f:(fun ty -> Log_type ("ty", ty))
@ [Log_type ("result", result)] );
]));
(env, result)
let log_simplify_unions r ty (env, result) =
Typing_log.(
log_with_level env "union" ~level:1 (fun () ->
log_types
(Reason.to_pos r)
env
[
Log_head
( "Typing_union.simplify_unions",
[Log_type ("ty", ty); Log_type ("result", result)] );
]));
(env, result)
end
(* Two types are "equivalent" if when expanded they are equal.
* If they are equivalent, this function returns a type which is equivalent to
* both, otherwise returns None.
*
* We need this instead of simply ty_equal, otherwise a lot of things aren't
* unioned properly - e.g. we get things like `array<^(int)> | array<^(int)>` -
* which potentially creates huge unresolved types, damaging perf.
*
* Furthermore, when unioning classes with type parameters, we allow
* A<Unresolved[]> | A<B> = A<B>
* This is because collections are often initialized like
* $myvec = get_int_vec() ?? vec[]
* If we don't do this simplification, this potentially produces exponentially
* growing Unresolved, like in test map_corner_case.php.
*)
let ty_equiv env ty1 ty2 ~are_ty_param =
let (env, ety1) = Env.expand_type env ty1 in
let (env, ety2) = Env.expand_type env ty2 in
let ty =
match ((get_node ety1, ty1), (get_node ety2, ty2)) with
| ((Tunion [], _), (_, ty))
| ((_, ty), (Tunion [], _))
when are_ty_param ->
Some ty
| _ when ty_equal ety1 ety2 -> begin
match get_node ty1 with
| Tvar _ -> Some ty1
| _ -> Some ty2
end
| _ -> None
in
(env, ty)
(* Destructure a union into a list of its sub-types, decending into sub-unions,
and also pulling out null and dynamic.
*)
let dest_union_list env tyl =
let orr r_opt r = Some (Option.value r_opt ~default:r) in
let rec dest_union env ty tyl tyl_res r_null r_union r_dyn =
let (env, ty) = Env.expand_type env ty in
match deref ty with
| (r, Tunion tyl') ->
dest_union_list env (tyl' @ tyl) tyl_res r_null (orr r_union r) r_dyn
| (r, Toption ty) ->
dest_union env ty tyl tyl_res (orr r_null r) r_union r_dyn
| (r, Tprim Aast.Tnull) ->
dest_union_list env tyl tyl_res (orr r_null r) r_union r_dyn
| (r, Tdynamic) ->
dest_union_list env tyl tyl_res r_null r_union (orr r_dyn r)
| _ -> dest_union_list env tyl (ty :: tyl_res) r_null r_union r_dyn
and dest_union_list env tyl tyl_res r_null r_union r_dyn =
match tyl with
| [] -> (env, (tyl_res, r_null, r_union, r_dyn))
| ty :: tyl -> dest_union env ty tyl tyl_res r_null r_union r_dyn
in
dest_union_list env tyl [] None None None
(** Constructor for unions and options, taking a list of types and whether the
result should be nullable. Simplify things like singleton unions or nullable nothing.
This allows the result of any unioning function from this module to be flattened and normalized,
with options being "pushed out" of the union (e.g. we return ?(A|B) instead of (A | ?B)
or (A | null | B), and similarly with like types). *)
let make_union env r tyl reason_nullable_opt reason_dyn_opt =
let ty =
match tyl with
| [ty] -> ty
| tyl -> MakeType.union r tyl
in
(* Given that unions with null are encoded specially in the type system - as options -
we still need to simplify unions of null and nonnull here.
For example, we may have to construct ?(nonnull | any) which should result in mixed.
For something more complex like ?(A | (B & nonnull)), one can
distribute the option to give (?A | (?B & ?nonnull)) which then simplifies to ?(A | B).
This function performs those simplifications. *)
let simplify_nonnull env ty =
let is_nonnull ty = ty_equal ty (MakeType.nonnull r) in
let rec simplify env ty =
let (env, ty) = Env.expand_type env ty in
match deref ty with
| (_, Toption ty) ->
(* ok to remove the Toption since we'll re-add it at the end. *)
simplify env ty
| (r, Tunion tyl) ->
let (env, tyl) = List.map_env env tyl ~f:simplify in
if List.exists tyl ~f:is_nonnull then
(env, MakeType.nonnull r)
else
(env, MakeType.union r tyl)
| (r, Tintersection tyl) ->
let (env, tyl) = List.map_env env tyl ~f:simplify in
let tyl = List.filter tyl ~f:(fun ty -> not (is_nonnull ty)) in
(env, MakeType.intersection r tyl)
| _ -> (env, ty)
in
simplify env ty
in
let (env, ty) =
if Option.is_some reason_nullable_opt then
simplify_nonnull env ty
else
(env, ty)
in
let like_ty dyn_r ty = MakeType.union dyn_r [MakeType.dynamic dyn_r; ty] in
(* Some code is sensitive to dynamic appearing first in the union. *)
let ty =
match (reason_nullable_opt, reason_dyn_opt, deref ty) with
| (None, Some dyn_r, (_, Tunion [])) -> MakeType.dynamic dyn_r
| (Some null_r, None, (_, Tunion [])) -> MakeType.null null_r
| (Some null_r, Some dyn_r, (_, Tunion [])) ->
like_ty dyn_r (MakeType.null null_r)
| (None, None, _) -> ty
| (None, Some dyn_r, (r, Tunion tyl)) ->
MakeType.union r (MakeType.dynamic dyn_r :: tyl)
| (None, Some dyn_r, _) -> like_ty dyn_r ty
| (Some null_r, None, _) -> MakeType.nullable null_r ty
| (Some null_r, Some dyn_r, _) ->
like_ty dyn_r (MakeType.nullable null_r ty)
in
let (env, ty) = Utils.wrap_union_inter_ty_in_var env r ty in
(env, ty)
let exact_least_upper_bound e1 e2 =
match (e1, e2) with
| (Exact, Exact) -> Exact
| (_, _) -> nonexact
let rec union env ?(approx_cancel_neg = false) ty1 ty2 =
let r1 = get_reason ty1 in
let r2 = get_reason ty2 in
Log.log_union r2 ty1 ty2
@@
if ty_equal ty1 ty2 then
(env, ty1)
else if Utils.is_sub_type_for_union env ty1 ty2 then
(env, ty2)
else if Utils.is_sub_type_for_union env ty2 ty1 then
(env, ty1)
else
let r = union_reason r1 r2 in
let (env, non_ty2) =
Typing_intersection.negate_type env Reason.none ty2 ~approx:Utils.ApproxUp
in
if Utils.is_sub_type_for_union env non_ty2 ty1 then
(env, MakeType.mixed r)
else
let (env, non_ty1) =
Typing_intersection.negate_type
env
Reason.none
ty1
~approx:Utils.ApproxUp
in
if Utils.is_sub_type_for_union env non_ty1 ty2 then
(env, MakeType.mixed r)
else
union_ ~approx_cancel_neg env ty1 ty2 r
and union_ ~approx_cancel_neg env ty1 ty2 r =
union_lists ~approx_cancel_neg env [ty1] [ty2] r
(** Simplify the union of two types, for example (int|float) as num.
Returns None if there is no simplification.
Does not deal with null, options, unions and intersections, which are dealt with by union_lists.
If approx_cancel_neg is true, then some unions with negations are treated over-approximately:
C<t> | not C simplifies to mixed.*)
and simplify_union ~approx_cancel_neg env ty1 ty2 r =
Log.log_simplify_union r ty1 ty2
@@
if ty_equal ty1 ty2 then
(env, Some ty1)
else if Utils.is_sub_type_for_union env ty1 ty2 then
(env, Some ty2)
else if Utils.is_sub_type_for_union env ty2 ty1 then
(env, Some ty1)
else
simplify_union_ ~approx_cancel_neg env ty1 ty2 r
and simplify_union_ ~approx_cancel_neg env ty1 ty2 r =
let (env, ty1) = Env.expand_type env ty1 in
let (env, ty2) = Env.expand_type env ty2 in
try
match (deref ty1, deref ty2) with
| ((r1, Tprim Nast.Tint), (r2, Tprim Nast.Tfloat))
| ((r1, Tprim Nast.Tfloat), (r2, Tprim Nast.Tint)) ->
let r = union_reason r1 r2 in
(env, Some (MakeType.num r))
| ((_, Tclass ((p, id1), e1, tyl1)), (_, Tclass ((_, id2), e2, tyl2)))
when String.equal id1 id2 ->
let e = exact_least_upper_bound e1 e2 in
if List.is_empty tyl1 then
(env, Some (mk (r, Tclass ((p, id1), e, tyl1))))
else
let (env, tyl) = union_class ~approx_cancel_neg env id1 tyl1 tyl2 in
(env, Some (mk (r, Tclass ((p, id1), e, tyl))))
| ((_, Tgeneric (name1, [])), (_, Tgeneric (name2, [])))
when String.equal name1 name2 ->
(* TODO(T69551141) handle type arguments above and below properly *)
(env, Some (mk (r, Tgeneric (name1, []))))
| ((_, Tvec_or_dict (tk1, tv1)), (_, Tvec_or_dict (tk2, tv2))) ->
let (env, tk) = union ~approx_cancel_neg env tk1 tk2 in
let (env, tv) = union ~approx_cancel_neg env tv1 tv2 in
(env, Some (mk (r, Tvec_or_dict (tk, tv))))
| ((_, Tdependent (dep1, tcstr1)), (_, Tdependent (dep2, tcstr2)))
when equal_dependent_type dep1 dep2 ->
let (env, tcstr) = union ~approx_cancel_neg env tcstr1 tcstr2 in
(env, Some (mk (r, Tdependent (dep1, tcstr))))
| ((_, Tdependent (_, ty1)), _) when Utils.is_class ty1 ->
ty_equiv env ty1 ty2 ~are_ty_param:false
| (_, (_, Tdependent (_, ty2))) when Utils.is_class ty2 ->
ty_equiv env ty2 ty1 ~are_ty_param:false
| ((r1, Tnewtype (id1, [tyl1], _)), (r2, Tnewtype (id2, [tyl2], _)))
when String.equal id1 id2
&& String.equal id1 Naming_special_names.Classes.cSupportDyn ->
let r = union_reason r1 r2 in
let (env, try_union) =
simplify_union ~approx_cancel_neg env tyl1 tyl2 r
in
(env, Option.map ~f:(MakeType.supportdyn r) try_union)
| ((_, Tnewtype (id1, tyl1, tcstr1)), (_, Tnewtype (id2, tyl2, tcstr2)))
when String.equal id1 id2
&& not (String.equal id1 Naming_special_names.Classes.cSupportDyn) ->
if List.is_empty tyl1 then
(env, Some ty1)
else
let (env, tyl) = union_newtype ~approx_cancel_neg env id1 tyl1 tyl2 in
let (env, tcstr) = union ~approx_cancel_neg env tcstr1 tcstr2 in
(env, Some (mk (r, Tnewtype (id1, tyl, tcstr))))
| ((_, Ttuple tyl1), (_, Ttuple tyl2)) ->
if Int.equal (List.length tyl1) (List.length tyl2) then
let (env, tyl) =
List.map2_env env tyl1 tyl2 ~f:(union ~approx_cancel_neg)
in
(env, Some (mk (r, Ttuple tyl)))
else
(env, None)
| ( ( r1,
Tshape
{ s_origin = _; s_unknown_value = shape_kind1; s_fields = fdm1 } ),
( r2,
Tshape
{ s_origin = _; s_unknown_value = shape_kind2; s_fields = fdm2 } )
) ->
let (env, ty) =
union_shapes
~approx_cancel_neg
env
(shape_kind1, fdm1, r1)
(shape_kind2, fdm2, r2)
in
(env, Some (mk (r, ty)))
| ((_, Tfun ft1), (_, Tfun ft2)) ->
let (env, ft) = union_funs ~approx_cancel_neg env ft1 ft2 in
(env, Some (mk (r, Tfun ft)))
| ((_, Tunapplied_alias _), _) ->
Typing_defs.error_Tunapplied_alias_in_illegal_context ()
| ((_, Tneg (Neg_class (_, c1))), (_, Tclass ((_, c2), Exact, [])))
| ((_, Tclass ((_, c2), Exact, [])), (_, Tneg (Neg_class (_, c1))))
when String.equal c1 c2 ->
(env, Some (MakeType.mixed r))
| ((_, Tneg (Neg_class (_, c1))), (_, Tclass ((_, c2), Nonexact _, [])))
| ((_, Tclass ((_, c2), Nonexact _, [])), (_, Tneg (Neg_class (_, c1))))
when Utils.is_sub_class_refl env c1 c2 ->
(* This union is mixed iff for all objects o,
o not in complement (union tyl. c1<tyl>) implies o in c2,
which is equivalent to
(union tyl. c1<tyl>) subset c2.
This is certainly the case when c1 is a sub-class of c2, since
c2 has no type parameters.
*)
(env, Some (MakeType.mixed r))
| ((_, Tneg (Neg_class (_, c1))), (_, Tclass ((_, c2), Nonexact _, _ :: _)))
| ((_, Tclass ((_, c2), Nonexact _, _ :: _)), (_, Tneg (Neg_class (_, c1))))
when approx_cancel_neg && Utils.is_sub_class_refl env c1 c2 ->
(* Unlike the case where c2 has no parameters, here we can get a situation
where c1 is a sub-class of c2, but they don't union to mixed. For example,
Vector<int> | not Vector, which doesn't include Vector<string>, etc. However,
we can still approximate up to mixed when it would be both sound and convenient,
as controlled by the approx_cancel_neg flag. *)
(env, Some (MakeType.mixed r))
| ((_, Tneg (Neg_class (_, c1))), (_, Tclass ((_, c2), Exact, _ :: _)))
| ((_, Tclass ((_, c2), Exact, _ :: _)), (_, Tneg (Neg_class (_, c1))))
when approx_cancel_neg && String.equal c1 c2 ->
(env, Some (MakeType.mixed r))
| ((_, Tneg (Neg_prim tp1)), (_, Tprim tp2))
| ((_, Tprim tp1), (_, Tneg (Neg_prim tp2)))
when Aast_defs.equal_tprim tp1 tp2 ->
(env, Some (MakeType.mixed r))
| ((_, Tneg (Neg_prim Aast.Tnum)), (_, Tprim Aast.Tarraykey))
| ((_, Tprim Aast.Tarraykey), (_, Tneg (Neg_prim Aast.Tnum))) ->
(env, Some (MakeType.neg r (Neg_prim Aast.Tfloat)))
| ((_, Tneg (Neg_prim Aast.Tarraykey)), (_, Tprim Aast.Tnum))
| ((_, Tprim Aast.Tnum), (_, Tneg (Neg_prim Aast.Tarraykey))) ->
(env, Some (MakeType.neg r (Neg_prim Aast.Tstring)))
| ((r1, Tintersection tyl1), (r2, Tintersection tyl2)) ->
(match Typing_algebra.factorize_common_types tyl1 tyl2 with
| ([], _, _) ->
(* No common types, fall back to default case *)
ty_equiv env ty1 ty2 ~are_ty_param:false
| (common_tyl, tyl1', tyl2') ->
(match (tyl1', tyl2') with
| ([], _)
| (_, []) ->
(* If one of the intersections is now empty, then the union is mixed,
and we just return the common types from the intersetion *)
(env, Some (MakeType.intersection r common_tyl))
| _ ->
let (env, union_ty) =
match (tyl1', tyl2') with
| ([ty1], [ty2]) ->
(* It seems like it is wasteful to simplify with the main union function which checks
subtyping. If there was a subtype relationship between these two, there
would have been one with the common types in, and we wouldn't get here.
However, in some cases, that is not the case. E.g., ?#1 & t <: #1 & t will
not pass the initial sub-type check, but will here *)
union ~approx_cancel_neg env ty1 ty2
| ([ty], tyl)
| (tyl, [ty]) ->
union_lists
~approx_cancel_neg
env
[ty]
[MakeType.intersection r1 tyl]
r
| _ ->
( env,
MakeType.union
r
[
MakeType.intersection r1 tyl1';
MakeType.intersection r2 tyl2';
] )
in
(match common_tyl with
| [common_ty] ->
let (env, inter_ty) =
Typing_intersection.intersect env ~r common_ty union_ty
in
(env, Some inter_ty)
| _ -> (env, Some (MakeType.intersection r (union_ty :: common_tyl))))))
(* TODO with Tclass, union type arguments if covariant *)
| ( ( _,
( Tprim _ | Tdynamic | Tgeneric _ | Tnewtype _ | Tdependent _
| Tclass _ | Ttuple _ | Tfun _ | Tshape _ | Tvar _ | Tvec_or_dict _
(* If T cannot be null, `union T nonnull = nonnull`. However, it's hard
* to say whether a given T can be null - e.g. opaque newtypes, dependent
* types, etc. - so for now we leave it here.
* TODO improve that. *)
| Tnonnull | Tany _ | Tintersection _ | Toption _ | Tunion _
| Taccess _ | Tneg _ ) ),
(_, _) ) ->
ty_equiv env ty1 ty2 ~are_ty_param:false
with
| Dont_simplify -> (env, None)
(* Recognise a pattern t1 | t2 | t3 | (t4 & t5 & t6) which happens frequently
at control flow join points, and check for types that drop out of the intersection
because they union to mixed with types in the union. Assume that all of the types
in tyl1 and tyl2 are not unions, having been processed by decompose in the
union_lists function. The semantics are that tyl1 and tyl2 are the union of their
elements, and we are building the union of the two lists. Instead of just appending,
we look for the special case where one of the elements of tyl1 or tyl2 is itself
an intersection, and try to cancel things out. We return the simplified
lists for further processing.
For example if tyl1 = [bool; int; string] represents bool | int | string, and
tyl2 = [float; (dynamic & not int & not string)],
then to union tyl1 and tyl2, we can remove the not int and not string conjuncts
from tyl2 because they union to mixed with elements of tyl1. Thus we end up with
a result [bool; int; string], [float; dynamic]
*)
and try_special_union_of_intersection ~approx_cancel_neg env tyl1 tyl2 r :
Typing_env_types.env * locl_ty list * locl_ty list =
(* Assume that inter_ty is an intersection type and look for a pairs of a conjunct in
inter_ty and an element of tyl that union to mixed. Remove these from the intersection,
and return the remaining elements of the intersection,
or return None indicating that no pairs were found. *)
let simplify_inter env inter_ty tyl : Typing_env_types.env * locl_ty option =
let changed = ref false in
let (env, (inter_tyl, inter_r)) =
Typing_intersection.destruct_inter_list env [inter_ty]
in
let inter_r = Option.value inter_r ~default:r in
let (env, new_inter_tyl) =
List.filter_map_env env inter_tyl ~f:(fun env inter_ty ->
match
List.exists_env env tyl ~f:(fun env ty ->
match simplify_union_ ~approx_cancel_neg env inter_ty ty r with
| (env, None) -> (env, false)
| (env, Some ty) -> (env, Utils.is_mixed env ty))
with
| (env, true) ->
changed := true;
(env, None)
| (env, false) -> (env, Some inter_ty))
in
( env,
if !changed then
Some (MakeType.intersection inter_r new_inter_tyl)
else
None )
in
let (inter_tyl1, not_inter_tyl1) =
List.partition_tf tyl1 ~f:(Utils.is_tintersection env)
in
let (inter_tyl2, not_inter_tyl2) =
List.partition_tf tyl2 ~f:(Utils.is_tintersection env)
in
let (env, res_tyl1) =
match inter_tyl1 with
| [inter_ty1] ->
(match simplify_inter env inter_ty1 not_inter_tyl2 with
| (env, None) -> (env, tyl1)
| (env, Some new_inter1) -> (env, new_inter1 :: not_inter_tyl1))
| _ -> (env, tyl1)
in
let (env, res_tyl2) =
match inter_tyl2 with
| [inter_ty2] ->
(match simplify_inter env inter_ty2 not_inter_tyl1 with
| (env, None) -> (env, tyl2)
| (env, Some new_inter1) -> (env, new_inter1 :: not_inter_tyl2))
| _ -> (env, tyl2)
in
(env, res_tyl1, res_tyl2)
(** Union two lists of types together.
This has complexity N*M where N, M are the sized of the two lists.
The two lists are first flattened and null and dynamic are extracted from them,
then we attempt to simplify each pair of types. *)
and union_lists ~approx_cancel_neg env tyl1 tyl2 r =
let product_ty_tyl env ty1 tyl2 =
let rec product_ty_tyl env ty1 tyl2 tyl_res =
match tyl2 with
| [] -> (env, ty1 :: tyl_res)
| ty2 :: tyl2 ->
let (env, ty_opt) = simplify_union ~approx_cancel_neg env ty1 ty2 r in
(match ty_opt with
| None -> product_ty_tyl env ty1 tyl2 (ty2 :: tyl_res)
| Some ty -> product_ty_tyl env ty tyl2 tyl_res)
in
product_ty_tyl env ty1 tyl2 []
in
let rec product env tyl1 tyl2 =
match (tyl1, tyl2) with
| ([], tyl)
| (tyl, []) ->
(env, tyl)
| (ty1 :: tyl1, tyl2) ->
let (env, tyl2) = product_ty_tyl env ty1 tyl2 in
product env tyl1 tyl2
in
let (env, (tyl1, r_null1, _r_union1, r_dyn1)) = dest_union_list env tyl1 in
let (env, (tyl2, r_null2, _r_union2, r_dyn2)) = dest_union_list env tyl2 in
let (env, tyl1, tyl2) =
try_special_union_of_intersection ~approx_cancel_neg env tyl1 tyl2 r
in
let (env, tyl) = product env tyl1 tyl2 in
let r_null = Option.first_some r_null1 r_null2 in
let r_dyn = Option.first_some r_dyn1 r_dyn2 in
make_union env r tyl r_null r_dyn
and union_funs ~approx_cancel_neg env fty1 fty2 =
(* TODO: If we later add fields to ft, they will be forgotten here. *)
if
Int.equal fty1.ft_flags fty2.ft_flags
&& Int.equal (ft_params_compare fty1.ft_params fty2.ft_params) 0
then
let (env, ft_ret) =
union_possibly_enforced_tys ~approx_cancel_neg env fty1.ft_ret fty2.ft_ret
in
(env, { fty1 with ft_ret })
else
raise Dont_simplify
and union_possibly_enforced_tys ~approx_cancel_neg env ety1 ety2 =
let (env, et_type) = union ~approx_cancel_neg env ety1.et_type ety2.et_type in
(env, { ety1 with et_type })
and union_class ~approx_cancel_neg env name tyl1 tyl2 =
let tparams =
match Env.get_class env name with
| None -> []
| Some c -> Cls.tparams c
in
union_tylists_w_variances ~approx_cancel_neg env tparams tyl1 tyl2
and union_newtype ~approx_cancel_neg env typename tyl1 tyl2 =
let tparams =
match Env.get_typedef env typename with
| None -> []
| Some t -> t.td_tparams
in
union_tylists_w_variances ~approx_cancel_neg env tparams tyl1 tyl2
and union_tylists_w_variances ~approx_cancel_neg env tparams tyl1 tyl2 =
let variances = List.map tparams ~f:(fun t -> t.tp_variance) in
let variances =
let adjust_list_length l newlen filler =
let len = List.length l in
if len < newlen then
l @ List.init (newlen - len) ~f:(fun _ -> filler)
else
List.sub l ~pos:0 ~len:newlen
in
adjust_list_length variances (List.length tyl1) Ast_defs.Invariant
in
let merge_ty_params env ty1 ty2 variance =
match variance with
| Ast_defs.Covariant -> union ~approx_cancel_neg env ty1 ty2
| _ ->
let (env, ty_opt) = ty_equiv env ty1 ty2 ~are_ty_param:true in
(match ty_opt with
| Some ty -> (env, ty)
| None -> raise Dont_simplify)
in
let (env, tyl) =
try List.map3_env env tyl1 tyl2 variances ~f:merge_ty_params with
| Invalid_argument _ -> raise Dont_simplify
in
(env, tyl)
and union_shapes
~approx_cancel_neg env (shape_kind1, fdm1, r1) (shape_kind2, fdm2, r2) =
let (env, shape_kind) =
union_shape_kind ~approx_cancel_neg env shape_kind1 shape_kind2
in
let ((env, shape_kind), fdm) =
TShapeMap.merge_env
(env, shape_kind)
fdm1
fdm2
~combine:(fun (env, shape_kind) k fieldopt1 fieldopt2 ->
match ((shape_kind1, fieldopt1, r1), (shape_kind2, fieldopt2, r2)) with
| ((_, None, _), (_, None, _)) -> ((env, shape_kind), None)
(* key is present on one side but not the other *)
| ((_, Some { sft_ty; _ }, _), (shape_kind_other, None, r))
| ((shape_kind_other, None, r), (_, Some { sft_ty; _ }, _)) ->
let sft_ty =
if is_nothing shape_kind_other then
sft_ty
else
let r =
Reason.Rmissing_optional_field
(Reason.to_pos r, Utils.get_printable_shape_field_name k)
in
with_reason shape_kind_other r
in
((env, shape_kind), Some { sft_optional = true; sft_ty })
(* key is present on both sides *)
| ( (_, Some { sft_optional = optional1; sft_ty = ty1 }, _),
(_, Some { sft_optional = optional2; sft_ty = ty2 }, _) ) ->
let sft_optional = optional1 || optional2 in
let (env, sft_ty) = union ~approx_cancel_neg env ty1 ty2 in
((env, shape_kind), Some { sft_optional; sft_ty }))
in
( env,
Tshape
{
s_origin = Missing_origin;
s_unknown_value = shape_kind;
s_fields = fdm;
} )
and union_shape_kind ~approx_cancel_neg env shape_kind1 shape_kind2 =
union ~approx_cancel_neg env shape_kind1 shape_kind2
(* TODO: add a new reason with positions of merge point and possibly merged
* envs.*)
and union_reason r1 r2 =
if Reason.is_none r1 then
r2
else if Reason.is_none r2 then
r1
else if Reason.compare r1 r2 <= 0 then
r1
else
r2
(** Takes a list of types, possibly including unions, and flattens it.
Returns a set of types.
If null is encountered (possibly in an option), get its reason and return it
in a separate optional reason (do not add null in the resulting set of types).
Do the same if dynamic is encountered.
This is because options and dynamic have to be "pushed out" of the resulting union. *)
let normalize_union env ?on_tyvar tyl :
Typing_env_types.env
* Reason.t option
* Reason.t option
* Reason.t option
* TySet.t =
let orr r_opt r = Some (Option.value r_opt ~default:r) in
let rec normalize_union env tyl r_null r_union r_dyn =
match tyl with
| [] -> (env, r_null, r_union, r_dyn, TySet.empty)
| ty :: tyl ->
let (env, ty) = Env.expand_type env ty in
let proceed env ty = (env, r_null, r_union, r_dyn, TySet.singleton ty) in
let (env, r_null, r_union, r_dyn, tys') =
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_union env [ty'] r_null r_union r_dyn
| ((r, Tprim Nast.Tnull), _) ->
normalize_union env [] (orr r_null r) r_union r_dyn
| ((r, Toption ty), _) ->
normalize_union env [ty] (orr r_null r) r_union r_dyn
| ((r, Tunion tyl'), _) ->
normalize_union env tyl' r_null (orr r_union r) r_dyn
| ((r, Tdynamic), _) ->
normalize_union env [] r_null r_union (orr r_dyn r)
| ((r, Tnewtype (n, [ty], _)), _)
when String.equal n Naming_special_names.Classes.cSupportDyn ->
let (_, env, ty) = Utils.strip_supportdyn env ty in
let (env, ty) = Utils.simplify_intersections env ty ?on_tyvar in
let (env, ty) = Utils.simple_make_supportdyn r env ty in
proceed env ty
| ((_, Tintersection _), _) ->
let (env, ty) = Utils.simplify_intersections env ty ?on_tyvar in
let (env, ety) = Env.expand_type env ty in
begin
match deref ety with
| (_, Tintersection _) -> proceed env ty
| _ -> normalize_union env [ty] r_null r_union r_dyn
end
| _ -> proceed env ty
in
let (env, r_null, r_union, r_dyn, tys) =
normalize_union env tyl r_null r_union r_dyn
in
(env, r_null, r_union, r_dyn, TySet.union tys' tys)
in
normalize_union env tyl None None None
(* Is this type minimal with respect to the ground subtype ordering, if we ignore the nothing type?
* Examples are exact or final non-generic classes.
* Non-examples (surprisingly) are int or string (because an enum can be a subtype).
*
* Another example is classname<C>, if C is minimal, and this pattern occurs
* frequently e.g. vec[C::class, D::class].
*
* Note that doesn't work for general covariant classes or built-ins e.g. vec<exact C> is not
* minimal because vec<nothing> <: vec<exact C>. But classname<nothing> is uninhabited so it's
* ok to suppose that it is equivalent to nothing.
*
* Finally note that if we did treat string, int, and float as minimal, then the code in
* union_list_2_by_2 would not simplify int|float to num or string|classname<C> to string.
*)
let rec is_minimal env ty =
match get_node ty with
| Tclass (_, Exact, []) -> true
| Tclass ((_, name), _, []) -> begin
match Env.get_class env name with
| Some cd -> Cls.final cd
| None -> false
end
| Tnewtype (name, [ty], _)
when String.equal name Naming_special_names.Classes.cClassname ->
is_minimal env ty
| Tdependent _ -> true
| _ -> false
(** Construct union of a list of types by applying binary union pairwise.
* This uses a quadratic number of subtype tests so we apply the following
* optimization that's particularly useful for the common pattern of vec[C1::class,...,Cn::class].
*
* First split the list of types into "final" types (those known to have no non-empty subtypes)
* and non-final types (that might have a non-empty subtype).
* For the non-final types, we apply binary union pointwise, which is quadratic in the number
* of types. Then for each of the final types we drop those that subtype any of the types
* in the result.
*
* If m is the number of final types, and n is the number of non-final types, the first
* stage uses O(n^2) subtype tests and the second stage uses O(mn) subtype tests.
* One common pattern is a union of exact classnames: constructing this will involve no
* subtype tests at all.
*)
let union_list_2_by_2 ~approx_cancel_neg env r tyl =
let (tyl_final, tyl_nonfinal) = List.partition_tf tyl ~f:(is_minimal env) in
let (env, reduced_nonfinal) =
List.fold tyl_nonfinal ~init:(env, []) ~f:(fun (env, res_tyl) ty ->
let rec union_ty_w_tyl env ty tyl tyl_acc =
match tyl with
| [] -> (env, ty :: tyl_acc)
| ty' :: tyl ->
let (env, union_opt) =
simplify_union ~approx_cancel_neg env ty ty' r
in
(match union_opt with
| None -> union_ty_w_tyl env ty tyl (ty' :: tyl_acc)
| Some union -> (env, tyl @ (union :: tyl_acc)))
in
union_ty_w_tyl env ty res_tyl [])
in
let reduced_final =
List.filter tyl_final ~f:(fun fty ->
not
(List.exists
reduced_nonfinal
~f:(Utils.is_sub_type_for_union env fty)))
in
(env, reduced_final @ reduced_nonfinal)
let union_list env ?(approx_cancel_neg = false) r tyl =
Log.log_union_list r tyl
@@
let (env, r_null, _r_union, r_dyn, tys) = normalize_union env tyl in
let (env, tyl) =
union_list_2_by_2 ~approx_cancel_neg env r (TySet.elements tys)
in
make_union env r tyl r_null r_dyn
let fold_union env ?(approx_cancel_neg = false) r tyl =
List.fold_left_env
env
tyl
~init:(MakeType.nothing r)
~f:(union ~approx_cancel_neg)
(* See documentation in mli file *)
let simplify_unions env ?(approx_cancel_neg = false) ?on_tyvar ty =
let r = get_reason ty in
Log.log_simplify_unions r ty
@@
let (env, r_null, r_union, r_dyn, tys) = normalize_union env [ty] ?on_tyvar in
let (env, tyl) =
union_list_2_by_2 ~approx_cancel_neg env r (TySet.elements tys)
in
let r = Option.value r_union ~default:r in
make_union env r tyl r_null r_dyn
let rec union_i env ?(approx_cancel_neg = false) r ty1 lty2 =
let ty2 = LoclType lty2 in
if Utils.is_sub_type_for_union_i env ty1 ty2 then
(env, ty2)
else if Utils.is_sub_type_for_union_i env ty2 ty1 then
(env, ty1)
else
let (env, ty) =
match ty1 with
| LoclType lty1 ->
let (env, ty) = union ~approx_cancel_neg env lty1 lty2 in
(env, LoclType ty)
| ConstraintType cty1 ->
(match deref_constraint_type cty1 with
| (_, TCunion (lty1, cty1)) ->
let (env, lty) = union ~approx_cancel_neg env lty1 lty2 in
(env, ConstraintType (mk_constraint_type (r, TCunion (lty, cty1))))
| (r', TCintersection (lty1, cty1)) ->
(* Distribute union over intersection.
At the moment local types in TCintersection can only be
unions or intersections involving only null and nonnull,
so applying distributivity allows for simplifying the types. *)
let (env, lty) = union ~approx_cancel_neg env lty1 lty2 in
let (env, ty) =
union_i ~approx_cancel_neg env r (ConstraintType cty1) lty2
in
(match ty with
| LoclType ty ->
let (env, ty) = Typing_intersection.intersect env ~r:r' lty ty in
(env, LoclType ty)
| ConstraintType cty ->
( env,
ConstraintType
(mk_constraint_type (r', TCintersection (lty, cty))) ))
| (_, Thas_member _)
| (_, Thas_type_member _)
| (_, Tcan_index _)
| (_, Tcan_traverse _)
| (_, Tdestructure _) ->
(env, ConstraintType (mk_constraint_type (r, TCunion (lty2, cty1)))))
in
match ty with
| LoclType _ -> (env, ty)
| ConstraintType ty -> Utils.simplify_constraint_type env ty
let () = Utils.union_ref := union
let () = Utils.union_i_ref := union_i
let () = Utils.union_list_ref := union_list
let () = Utils.fold_union_ref := fold_union
let () = Utils.simplify_unions_ref := simplify_unions
let () = Utils.make_union_ref := make_union
let () =
(* discard optional parameters. *)
let simplify_unions env ty = simplify_unions env ty in
Env.simplify_unions_ref := simplify_unions |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_union.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 Env = Typing_env
(** Performs the union of two types.
The union is the least upper bound of the subtyping relation.
There is however one approximation: if type A is covariant,
then
A<T1> | A<T2> = A<T1|T2>
This approximation is necessary to avoid type growing exponentially in size.
We have seen cases where it would otherwise generate unions involving all
the subsets of a set of types.
If approx_cancel_neg is true, then some unions with negations are treated over-approximately:
C<t> | not C simplifies to mixed. *)
val union :
env -> ?approx_cancel_neg:bool -> locl_ty -> locl_ty -> env * locl_ty
(** Computes the union of a list of types by unioning types two by two.
This has quadratic complexity, but in practice we benefit from aggressively
simplified unions. *)
val union_list :
env -> ?approx_cancel_neg:bool -> Reason.t -> locl_ty list -> env * locl_ty
(** Simplify the unions within a type.
Return the result in a flattened, "normalized" form, with options and like types being
"pushed out" of the result.
E.g. transforms `(int | (int | null | X))` into `?(int | X)`
This has quadratic complexity, but in practice we benefit from aggressively
simplified unions. *)
val simplify_unions :
env ->
?approx_cancel_neg:bool ->
?on_tyvar:(env -> Reason.t -> Ident.t -> env * locl_ty) ->
locl_ty ->
env * locl_ty
val union_i :
env ->
?approx_cancel_neg:bool ->
Typing_reason.t ->
internal_type ->
locl_ty ->
env * internal_type |
OCaml | hhvm/hphp/hack/src/typing/typing_utils.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Common
open Typing_defs
open Typing_env_types
module SN = Naming_special_names
module Reason = Typing_reason
module Env = Typing_env
module TySet = Typing_set
module Cls = Decl_provider.Class
module MakeType = Typing_make_type
(*****************************************************************************)
(* Importing what is necessary *)
(*****************************************************************************)
let not_implemented s _ =
failwith (Printf.sprintf "Function %s not implemented" s)
type expand_typedef =
expand_env ->
env ->
Reason.t ->
string ->
locl_ty list ->
(env * Typing_error.t option) * locl_ty
let (expand_typedef_ref : expand_typedef ref) =
ref (not_implemented "expand_typedef")
let expand_typedef x = !expand_typedef_ref x
type sub_type =
env ->
?coerce:Typing_logic.coercion_direction option ->
?is_coeffect:bool ->
locl_ty ->
locl_ty ->
Typing_error.Reasons_callback.t option ->
env * Typing_error.t option
let (sub_type_ref : sub_type ref) = ref (not_implemented "sub_type")
let sub_type x = !sub_type_ref x
type sub_type_i =
env ->
?is_coeffect:bool ->
internal_type ->
internal_type ->
Typing_error.Reasons_callback.t option ->
env * Typing_error.t option
let (sub_type_i_ref : sub_type_i ref) = ref (not_implemented "sub_type_i")
let sub_type_i env ?(is_coeffect = false) x = !sub_type_i_ref env ~is_coeffect x
type sub_type_with_dynamic_as_bottom =
env ->
locl_ty ->
locl_ty ->
Typing_error.Reasons_callback.t option ->
env * Typing_error.t option
let (sub_type_with_dynamic_as_bottom_ref : sub_type_with_dynamic_as_bottom ref)
=
ref (not_implemented "sub_type_with_dynamic_as_bottom")
let sub_type_with_dynamic_as_bottom x = !sub_type_with_dynamic_as_bottom_ref x
type is_sub_type_type = env -> locl_ty -> locl_ty -> bool
let (is_sub_type_ref : is_sub_type_type ref) =
ref (not_implemented "is_sub_type")
let is_sub_type x = !is_sub_type_ref x
let (is_sub_type_for_union_ref : (env -> locl_ty -> locl_ty -> bool) ref) =
ref (not_implemented "is_sub_type_for_union")
let is_sub_type_for_union x = !is_sub_type_for_union_ref x
let (is_sub_type_for_union_i_ref :
(env -> internal_type -> internal_type -> bool) ref) =
ref (not_implemented "is_sub_type_for_union_i")
let is_sub_type_for_union_i x = !is_sub_type_for_union_i_ref x
let (is_type_disjoint_ref : (env -> locl_ty -> locl_ty -> bool) ref) =
ref (not_implemented "is_type_disjoint")
let is_type_disjoint x = !is_type_disjoint_ref x
let (is_sub_type_ignore_generic_params_ref : is_sub_type_type ref) =
ref (not_implemented "is_sub_type_ignore_generic_params")
let is_sub_type_ignore_generic_params x =
!is_sub_type_ignore_generic_params_ref x
type add_constraint =
env ->
Ast_defs.constraint_kind ->
locl_ty ->
locl_ty ->
Typing_error.Reasons_callback.t option ->
env
let (add_constraint_ref : add_constraint ref) =
ref (not_implemented "add_constraint")
let add_constraint x = !add_constraint_ref x
let (can_sub_type_ref : is_sub_type_type ref) =
ref (not_implemented "can_sub_type_ref")
let can_sub_type x = !can_sub_type_ref x
type expand_typeconst =
expand_env ->
env ->
?ignore_errors:bool ->
?as_tyvar_with_cnstr:Pos.t option ->
locl_ty ->
pos_id ->
allow_abstract_tconst:bool ->
(env * Typing_error.t option) * locl_ty
let (expand_typeconst_ref : expand_typeconst ref) =
ref (not_implemented "expand_typeconst")
let expand_typeconst x = !expand_typeconst_ref x
type union =
env -> ?approx_cancel_neg:bool -> locl_ty -> locl_ty -> env * locl_ty
let (union_ref : union ref) = ref (not_implemented "union")
let union x = !union_ref x
type make_union =
env ->
Reason.t ->
locl_ty list ->
Reason.t option ->
Reason.t option ->
env * locl_ty
let (make_union_ref : make_union ref) = ref (not_implemented "make_union")
let make_union env = !make_union_ref env
type union_i =
env ->
?approx_cancel_neg:bool ->
Reason.t ->
internal_type ->
locl_ty ->
env * internal_type
let (union_i_ref : union_i ref) = ref (not_implemented "union")
let union_i x = !union_i_ref x
type union_list =
env -> ?approx_cancel_neg:bool -> Reason.t -> locl_ty list -> env * locl_ty
let (union_list_ref : union_list ref) = ref (not_implemented "union_list")
let union_list x = !union_list_ref x
type fold_union =
env -> ?approx_cancel_neg:bool -> Reason.t -> locl_ty list -> env * locl_ty
let (fold_union_ref : fold_union ref) = ref (not_implemented "fold_union")
type simplify_unions =
env ->
?approx_cancel_neg:bool ->
?on_tyvar:(env -> Reason.t -> Ident.t -> env * locl_ty) ->
locl_ty ->
env * locl_ty
let (simplify_unions_ref : simplify_unions ref) =
ref (not_implemented "simplify_unions")
let simplify_unions x = !simplify_unions_ref x
type intersect_list = env -> Reason.t -> locl_ty list -> env * locl_ty
let (intersect_list_ref : intersect_list ref) =
ref (not_implemented "intersect_list")
let intersect_list x = !intersect_list_ref x
type approx =
| ApproxUp
| ApproxDown
[@@deriving eq]
type negate_type = env -> Reason.t -> locl_ty -> approx:approx -> env * locl_ty
let (negate_type_ref : negate_type ref) = ref (not_implemented "negate_type")
let negate_type x = !negate_type_ref x
type simplify_intersections =
env ->
?on_tyvar:(env -> Reason.t -> int -> env * locl_ty) ->
locl_ty ->
env * locl_ty
let (simplify_intersections_ref : simplify_intersections ref) =
ref (not_implemented "simplify_intersections")
let simplify_intersections x = !simplify_intersections_ref x
type localize_no_subst =
env ->
ignore_errors:bool ->
decl_ty ->
(env * Typing_error.t option) * locl_ty
let (localize_no_subst_ref : localize_no_subst ref) =
ref (not_implemented "localize_no_subst")
let localize_no_subst x = !localize_no_subst_ref x
type localize =
ety_env:expand_env ->
env ->
decl_ty ->
(env * Typing_error.t option) * locl_ty
let (localize_ref : localize ref) =
ref (fun ~ety_env:_ -> not_implemented "localize")
let localize x = !localize_ref x
(*****************************************************************************)
(* Checking properties of types *)
(*****************************************************************************)
let is_class ty =
match get_node ty with
| Tclass _ -> true
| _ -> false
let is_class_i ty =
match ty with
| ConstraintType _ -> false
| LoclType ty -> is_class ty
let is_mixed_i env ty =
let mixed = LoclType (MakeType.mixed Reason.Rnone) in
is_sub_type_for_union_i env mixed ty
let is_mixed env ty = is_mixed_i env (LoclType ty)
let is_nothing_i env ty =
let nothing = LoclType (MakeType.nothing Reason.Rnone) in
is_sub_type_for_union_i env ty nothing
let is_nothing env ty = is_nothing_i env (LoclType ty)
let is_dynamic env ty =
let dynamic = MakeType.dynamic Reason.Rnone in
(is_sub_type_for_union env dynamic ty && not (is_mixed env ty))
|| (is_sub_type_for_union env ty dynamic && not (is_nothing env ty))
let rec is_any env ty =
let (env, ty) = Env.expand_type env ty in
match get_node ty with
| Tany _ -> true
| Tunion tyl -> List.for_all tyl ~f:(is_any env)
| Tintersection tyl -> List.exists tyl ~f:(is_any env)
| _ -> false
let is_tunion env ty =
let (_env, ty) = Env.expand_type env ty in
match get_node ty with
| Tunion _ -> true
| _ -> false
let is_tintersection env ty =
let (_env, ty) = Env.expand_type env ty in
match get_node ty with
| Tintersection _ -> true
| _ -> false
let is_tyvar env ty =
let (_env, ty) = Env.expand_type env ty in
match get_node ty with
| Tvar _ -> true
| _ -> false
let is_opt_tyvar env ty =
let (env, ty) = Env.expand_type env ty in
match get_node ty with
| Toption ty -> is_tyvar env ty
| _ -> false
let is_tyvar_error env ty =
let (_env, ty) = Env.expand_type env ty in
let rec is_tyvar_error_reason r =
match r with
| Reason.Rtype_variable_error _ -> true
| Reason.Rtype_access (r, _) -> is_tyvar_error_reason r
| Reason.Rtypeconst (r, _, _, _) -> is_tyvar_error_reason r
| _ -> false
in
match deref ty with
| (r, Tvar _) -> is_tyvar_error_reason r
| _ -> false
(** Simplify unions and intersections of constraint
types which involve mixed or nothing. *)
let simplify_constraint_type env ty =
match deref_constraint_type ty with
| (_, TCunion (lty, cty)) ->
if is_nothing env lty then
(env, ConstraintType cty)
else if is_mixed env lty then
(env, LoclType lty)
else
(env, ConstraintType ty)
| (_, TCintersection (lty, cty)) ->
if is_nothing env lty then
(env, LoclType lty)
else if is_mixed env lty then
(env, ConstraintType cty)
else
(env, ConstraintType ty)
| (_, Thas_member _)
| (_, Thas_type_member _)
| (_, Tcan_index _)
| (_, Tcan_traverse _)
| (_, Tdestructure _) ->
(env, ConstraintType ty)
let contains_unresolved_tyvars env ty =
let finder =
object (this)
inherit [env * bool] Type_visitor.locl_type_visitor as super
method! on_tvar (env, occurs) r v =
let (env, ty) = Env.expand_var env r v in
if Typing_defs.is_tyvar ty then
(env, true)
else
this#on_type (env, occurs) ty
method! on_type (env, occurs) ty =
if occurs then
(env, occurs)
else
super#on_type (env, occurs) ty
end
in
finder#on_type (env, false) ty
let contains_tvar_decl (t : decl_ty) =
let finder =
object
inherit [bool] Type_visitor.decl_type_visitor as parent
method! on_tvar _found _r _v = true
method! on_type found ty =
if found then
true
else
parent#on_type found ty
end
in
finder#on_type false t
exception FoundGeneric of Pos_or_decl.t
let contains_generic_decl : Typing_defs.decl_ty -> Pos_or_decl.t option =
fun ty ->
let visitor =
object
inherit [_] Type_visitor.decl_type_visitor as super
method! on_type env ty =
match get_node ty with
| Tgeneric _ -> raise (FoundGeneric (get_pos ty))
| _ -> super#on_type env ty
end
in
try
visitor#on_type () ty;
None
with
| FoundGeneric p -> Some p
let wrap_union_inter_ty_in_var env r ty =
if is_union_or_inter_type ty then
let (env, contains_unresolved_tyvars) = contains_unresolved_tyvars env ty in
if contains_unresolved_tyvars then
Env.wrap_ty_in_var env r ty
else
(env, ty)
else
(env, ty)
(*****************************************************************************
* Get the "as" constraints from an abstract type or generic parameter, or
* return the type itself if there is no "as" constraint.
* In the case of a generic parameter whose "as" constraint is another
* generic parameter, repeat the process until a type is reached that is not
* a generic parameter. Don't loop on cycles.
* (For example, function foo<Tu as Tv, Tv as Tu>(...))
* Also breaks apart intersections.
*****************************************************************************)
let get_concrete_supertypes
?(expand_supportdyn = true)
?(include_case_types = false)
~abstract_enum
env
ty =
let rec iter seen env acc tyl =
match tyl with
| [] -> (env, acc)
| ty :: tyl ->
let (env, ty) = Env.expand_type env ty in
(match get_node ty with
(* Enums with arraykey upper bound are treated as "abstract" *)
| Tnewtype (cid, _, bound_ty)
when abstract_enum
&& is_prim Aast.Tarraykey bound_ty
&& Env.is_enum env cid ->
iter seen env acc tyl
(* Don't expand enums or newtype; just return the type itself *)
| Tnewtype (n, _, as_ty)
when expand_supportdyn || not (String.equal n SN.Classes.cSupportDyn) ->
let acc = TySet.add as_ty acc in
let acc =
if include_case_types then
TySet.add ty acc
else
acc
in
iter seen env acc tyl
| Tdependent (_, ty) -> iter seen env (TySet.add ty acc) tyl
| Tgeneric (n, targs) ->
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 targs) @ tyl)
| Tintersection tyl' -> iter seen env acc (tyl' @ 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)
(** Run a function on an intersection represented by a list of types.
We stay liberal with errors:
discard the result of any run which has produced an error.
If all runs have produced an error, gather all errors and results and add errors. *)
let run_on_intersection :
'env -> f:('env -> locl_ty -> 'env * 'a) -> locl_ty list -> 'env * 'a list =
fun env ~f tyl ->
let (env, resl_errors) =
List.map_env env tyl ~f:(fun env ty ->
let (errors, (env, result)) = Errors.do_ @@ fun () -> f env ty in
(env, (result, errors)))
in
let valid_resl =
List.filter resl_errors ~f:(fun (_, err) -> Errors.is_empty err)
|> List.map ~f:fst
in
let resl =
if not (List.is_empty valid_resl) then
valid_resl
else (
List.iter resl_errors ~f:(fun (_, err) -> Errors.merge_into_current err);
List.map ~f:fst resl_errors
)
in
(env, resl)
let run_on_intersection_with_ty_err env ~f tys =
let (env, resl) =
List.map_env env tys ~f:(fun env ty ->
let ((env, ty_err_opt), res) = f env ty in
(env, (res, ty_err_opt)))
in
(* Partition the results into those with and without errors *)
let res =
List.partition_map resl ~f:(function
| (res, None) -> Either.first res
| (res, Some err) -> Either.second (res, err))
in
match res with
| ([], with_err) ->
(* We have no element of the intersection without error
Take the intersection of the errors so we remember where they came from
when applying error suppression
*)
let (res, errs) = List.unzip with_err in
((env, Typing_error.intersect_opt errs), res)
| (without_err, _) ->
(* We have at least one that is without error so return the elements without
error and indicate there is no error for the intersection *)
((env, None), without_err)
(** As above but allow functions which also return subtyping/coercion error
information *)
let run_on_intersection_res env ~f tyl =
let g env ty =
let (env, a, b) = f env ty in
(env, (a, b))
in
let (env, pairs) = run_on_intersection env ~f:g tyl in
let (res, errs) = List.unzip pairs in
(env, res, errs)
let run_on_intersection_key_value_res env ~f tyl =
let g env ty =
let (env, a, b, c) = f env ty in
(env, (a, b, c))
in
let (env, triples) = run_on_intersection env ~f:g tyl in
let (res, key_errs, errs) = List.unzip3 triples in
(env, res, key_errs, errs)
let run_on_intersection_array_key_value_res env ~f tyl =
let g env ty =
let (env, a, b, c, d) = f env ty in
(env, (a, b, c, d))
in
let (env, quads) = run_on_intersection env ~f:g tyl in
let (res, arr_errs, key_errs, val_errs) = List.unzip4 quads in
(env, res, arr_errs, key_errs, val_errs)
let rec strip_supportdyn env ty =
let (env, ty) = Env.expand_type env ty in
match get_node ty with
| Tnewtype (name, [tyarg], _) when String.equal name SN.Classes.cSupportDyn ->
let (_, env, ty) = strip_supportdyn env tyarg in
(true, env, ty)
| _ -> (false, env, ty)
(* The list of types should not be considered to be a bound if it is all mixed
or supportdyn<mixed> (when include_sd_mixed is set *)
let no_upper_bound ~include_sd_mixed env tyl =
List.for_all_env env tyl ~f:(fun env ty ->
if is_mixed env ty then
(env, true)
else if include_sd_mixed then
let (stripped, env, ty) = strip_supportdyn env ty in
(env, stripped && is_mixed env ty)
else
(env, false))
(* Gets the base type of an abstract type *)
let get_base_type ?(expand_supportdyn = true) env ty =
let rec loop seen_generics ty =
let (env, ty) = Env.expand_type env ty in
let r = get_reason ty in
match get_node ty with
| Tnewtype (classname, _, _)
when String.equal classname SN.Classes.cClassname ->
ty
| Tnewtype (n, _, ty) when String.equal n SN.Classes.cSupportDyn ->
let ty = loop seen_generics ty in
if expand_supportdyn then
ty
else
MakeType.supportdyn r ty
(* If we have an expression dependent type and it only has one super
type, we can treat it similarly to AKdependent _, Some ty *)
| Tgeneric (n, targs) when DependentKind.is_generic_dep_ty n -> begin
match TySet.elements (Env.get_upper_bounds env n targs) with
| ty2 :: _ when ty_equal ty ty2 -> ty
(* If it's exactly equal, then the base ty is just this one *)
| ty :: _ ->
if TySet.mem ty (Env.get_lower_bounds env n targs) then
ty
else if SSet.mem n seen_generics then
ty
else
loop (SSet.add n seen_generics) ty
| [] -> ty
end
| Tnewtype (cid, _, bound_ty)
when is_prim Aast.Tarraykey bound_ty && Env.is_enum env cid ->
ty
| Tgeneric _
| Tnewtype _
| Tdependent _ ->
let (env, tys) =
get_concrete_supertypes ~expand_supportdyn ~abstract_enum:true env ty
in
let (_env, has_no_bounds) =
no_upper_bound ~include_sd_mixed:expand_supportdyn env tys
in
(match tys with
| [ty] when not has_no_bounds -> loop seen_generics ty
| _ -> ty)
| _ -> ty
in
loop SSet.empty ty
let get_printable_shape_field_name = Typing_defs.TShapeField.name
let shape_field_name_with_ty_err env (_, p, field) =
match field with
| Aast.Int name -> (Some (Ast_defs.SFlit_int (p, name)), None)
| Aast.String name -> (Some (Ast_defs.SFlit_str (p, name)), None)
| Aast.Class_const ((_, _, Aast.CI x), y) ->
(Some (Ast_defs.SFclass_const (x, y)), None)
| Aast.Class_const ((_, _, Aast.CIself), y) ->
let this =
match Env.get_self_ty env with
| None -> None
| Some c_ty ->
(match get_node c_ty with
| Tclass (sid, _, _) -> Some (Positioned.unsafe_to_raw_positioned sid)
| _ -> None)
in
(match this with
| Some sid -> (Some (Ast_defs.SFclass_const (sid, y)), None)
| None ->
( None,
Some
Typing_error.(
primary @@ Primary.Expected_class { pos = p; suffix = None }) ))
| _ ->
let err =
Typing_error.Primary.Shape.(
Invalid_shape_field_name { pos = p; is_empty = false })
in
(None, Some (Typing_error.shape err))
(*****************************************************************************)
(* Class types *)
(*****************************************************************************)
let unwrap_class_type ty =
match deref ty with
| (r, Tapply (name, tparaml)) -> (r, name, tparaml)
| _ -> raise @@ Invalid_argument "unwrap_class_type got non-class"
let try_unwrap_class_type x = Option.try_with (fun () -> unwrap_class_type x)
let class_is_final_and_invariant class_ty =
Cls.final class_ty
&& List.for_all (Cls.tparams class_ty) ~f:(function
| { tp_variance = Ast_defs.Invariant; _ } -> true
| _ -> false)
(*****************************************************************************)
(* Check if a type is not fully constrained *)
(*****************************************************************************)
module HasTany : sig
val check : locl_ty -> bool
val check_why : locl_ty -> Reason.t option
end = struct
let visitor =
object (_this)
inherit [Reason.t option] Type_visitor.locl_type_visitor
method! on_tany _ r = Some r
end
let check_why ty = visitor#on_type None ty
let check ty = Option.is_some (check_why ty)
end
(*****************************************************************************)
(* Function parameters *)
(*****************************************************************************)
let default_fun_param ?(pos = Pos_or_decl.none) ty : 'a fun_param =
{
fp_pos = pos;
fp_name = None;
fp_type = { et_type = ty; et_enforced = Unenforced };
fp_flags =
make_fp_flags
~mode:FPnormal
~accept_disposable:false
~has_default:false
~ifc_external:false
~ifc_can_call:false
~readonly:false;
}
let tany = Env.tany
let mk_tany env p = mk (Reason.Rwitness p, tany env)
let collect_enum_class_upper_bounds env name =
(* the boolean ok is here to see if we find anything at all,
* and prevents us to return the initial mixed value if nothing
* is to be found.
*)
let rec collect seen ok result name =
let upper_bounds = Env.get_upper_bounds env name [] in
TySet.fold
(fun lty (seen, ok, result) ->
match get_node lty with
| Tclass ((_, name), _, _) when Env.is_enum_class env name ->
let result =
(* We build an intersection, but only care about the result
* if it is simplified to a singleton type, so the following
* reason is not useful. We could add a dedicated reason
* for more precise error reporting.
*)
let r = Reason.Rnone in
mk (r, Tintersection [result; lty])
in
(seen, true, result)
| Tgeneric (name, _) when not (SSet.mem name seen) ->
collect (SSet.add name seen) ok result name
| _ -> (seen, ok, result))
upper_bounds
(seen, ok, result)
in
let mixed = MakeType.mixed Reason.Rnone in
let (_, ok, upper_bound) = collect SSet.empty false mixed name in
if ok then
let (env, upper_bound) = simplify_intersections env upper_bound in
(env, Some upper_bound)
else
(env, None)
let make_locl_subst_for_class_tparams classdef tyl =
if List.is_empty tyl then
SMap.empty
else
Decl_subst.make_locl (Cls.tparams classdef) tyl
let is_sub_class_refl env c_sub c_super =
String.equal c_sub c_super
||
match Env.get_class env c_sub with
| None -> false
| Some cls_sub -> Cls.has_ancestor cls_sub c_super
let class_has_no_params env c =
match Env.get_class env c with
| Some cls -> List.is_empty (Cls.tparams cls)
| None -> false
(* Is super_id an ancestor of sub_id, including through requires steps?
* Maintain a visited set to catch cycles (these are rejected in folding but
* the definitions survive).
*)
let rec has_ancestor_including_req ~visited env cls super_id =
Cls.has_ancestor cls super_id
||
let kind = Cls.kind cls in
(Ast_defs.is_c_trait kind || Ast_defs.is_c_interface kind)
&& (Cls.requires_ancestor cls super_id
||
let bounds = Cls.upper_bounds_on_this cls in
List.exists bounds ~f:(fun ty ->
match get_node ty with
| Tapply ((_, name), _) ->
has_ancestor_including_req_refl ~visited env name super_id
| _ -> false))
and has_ancestor_including_req_refl ~visited env sub_id super_id =
(not (SSet.mem sub_id visited))
&& (String.equal sub_id super_id
||
match Env.get_class env sub_id with
| None -> false
| Some cls ->
has_ancestor_including_req
~visited:(SSet.add sub_id visited)
env
cls
super_id)
let has_ancestor_including_req = has_ancestor_including_req ~visited:SSet.empty
let has_ancestor_including_req_refl =
has_ancestor_including_req_refl ~visited:SSet.empty
(* search through tyl, and any unions directly-recursively contained in tyl,
and return those that satisfy f, and those that do not, separately.*)
let rec partition_union ~f tyl =
match tyl with
| [] -> ([], [])
| t :: tyl ->
let (dyns, nondyns) = partition_union ~f tyl in
if f t then
(t :: dyns, nondyns)
else (
match get_node t with
| Tunion tyl ->
(match strip_union ~f tyl with
| Some (sub_dyns, sub_nondyns) ->
(sub_dyns @ dyns, MakeType.union (get_reason t) sub_nondyns :: nondyns)
| None -> (dyns, t :: nondyns))
| _ -> (dyns, t :: nondyns)
)
and strip_union tyl ~f =
let (dyns, nondyns) = partition_union ~f tyl in
match (dyns, nondyns) with
| ([], _) -> None
| (_, _) -> Some (dyns, nondyns)
let rec try_strip_dynamic_from_union _env tyl =
match strip_union ~f:Typing_defs.is_dynamic tyl with
| None -> None
| Some (_, tyl) -> Some tyl
and try_strip_dynamic env ty =
let (env, ty) = Env.expand_type env ty in
match get_node ty with
| Tunion tyl ->
(match try_strip_dynamic_from_union env tyl with
| None -> None
| Some tyl -> Some (MakeType.union (get_reason ty) tyl))
| _ -> None
and strip_dynamic env ty =
match try_strip_dynamic env ty with
| None -> ty
| Some ty -> ty
let is_supportdyn env ty =
is_sub_type_for_union env ty (MakeType.supportdyn_mixed Reason.Rnone)
let rec make_supportdyn r env ty =
let (env, ty) = Env.expand_type env ty in
match deref ty with
| (r', Tintersection tyl) ->
let (env, tyl) = List.map_env env tyl ~f:(make_supportdyn r) in
(env, mk (r', Tintersection tyl))
| (r', Tunion tyl) ->
let (env, tyl) = List.map_env env tyl ~f:(make_supportdyn r) in
(env, mk (r', Tunion tyl))
| _ ->
if is_supportdyn env ty then
(env, ty)
else
(env, MakeType.supportdyn r ty)
let simple_make_supportdyn r env ty =
let (env, ty) = Env.expand_type env ty in
( env,
match get_node ty with
| Tnewtype (n, _, _) when String.equal n SN.Classes.cSupportDyn -> ty
| _ -> MakeType.supportdyn r ty )
let make_supportdyn_decl_type p r ty =
mk (r, Tapply ((p, SN.Classes.cSupportDyn), [ty]))
let make_like env ty =
if Typing_defs.is_dynamic ty || Option.is_some (try_strip_dynamic env ty) then
ty
else
let r = get_reason ty in
MakeType.locl_like r ty
let make_like_if_enforced env ety =
match ety.et_enforced with
| Enforced
when TypecheckerOptions.enable_sound_dynamic (Env.get_tcopt env)
&& Env.get_support_dynamic_type env ->
{ ety with et_type = make_like env ety.et_type }
| _ -> ety
let rec is_capability ty =
match get_node ty with
| Tclass ((_, name), _, _)
when String.is_prefix ~prefix:SN.Capabilities.prefix name ->
true
| Tintersection [] -> false
| Tintersection tyl -> List.for_all ~f:is_capability tyl
| Tgeneric (s, []) when SN.Coeffects.is_generated_generic s -> true
| _ -> false
let is_capability_i ty =
match ty with
| LoclType ty -> is_capability ty
| ConstraintType _ -> false
let supports_dynamic env ty =
let r = get_reason ty in
sub_type env ty (MakeType.supportdyn_mixed r)
let is_inter_dyn env ty =
let (env, ty) = Env.expand_type env ty in
match get_node ty with
| Tintersection [ty1; ty2]
when Typing_defs.is_dynamic ty1 || Typing_defs.is_dynamic ty2 ->
(env, Some (ty1, ty2))
| _ -> (env, None)
let rec find_inter_dyn env acc tyl =
match tyl with
| [] -> (env, None)
| ty :: tyl ->
(match is_inter_dyn env ty with
| (env, None) -> find_inter_dyn env (ty :: acc) tyl
| (env, Some ty_inter) -> (env, Some (ty_inter, acc @ tyl)))
(* Detect types that look like (t1 & dynamic) | t2 and convert to
~t2 & (t1 | t2). Also in function returns.
*)
let rec recompose_like_type env orig_ty =
let (env, ty) = Env.expand_type env orig_ty in
match get_node ty with
| Tunion tys ->
(match find_inter_dyn env [] tys with
| (env, Some ((ty1, ty2), [ty_sub])) ->
let (env, ty_union1) = union env ty1 ty_sub in
let (env, ty_union2) = union env ty2 ty_sub in
(env, MakeType.intersection (get_reason ty) [ty_union1; ty_union2])
| (env, _) ->
(match try_strip_dynamic env ty with
| None -> (env, ty)
| Some ty1 ->
let (env, ty2) = recompose_like_type env ty1 in
(env, MakeType.locl_like (get_reason ty) ty2)))
| Tfun ft ->
let (env, et_type) = recompose_like_type env ft.ft_ret.et_type in
let ft_ret = { ft.ft_ret with et_type } in
(env, mk (get_reason ty, Tfun { ft with ft_ret }))
| Tnewtype (n, _, ty1) when String.equal n SN.Classes.cSupportDyn ->
let (env, ty1) = recompose_like_type env ty1 in
simple_make_supportdyn (get_reason ty) env ty1
| _ -> (env, orig_ty)
let make_simplify_typed_expr env p ty te =
let (env, ty) =
if TypecheckerOptions.enable_sound_dynamic (Env.get_tcopt env) then
recompose_like_type env ty
else
(env, ty)
in
(env, Tast.make_typed_expr p ty te) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_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.
*
*)
type expand_typedef =
Typing_defs.expand_env ->
Typing_env_types.env ->
Typing_reason.t ->
string ->
Typing_defs.locl_ty list ->
(Typing_env_types.env * Typing_error.t option) * Typing_defs.locl_ty
val expand_typedef_ref : expand_typedef ref
val expand_typedef : expand_typedef
type sub_type =
Typing_env_types.env ->
?coerce:Typing_logic.coercion_direction option ->
?is_coeffect:bool ->
Typing_defs.locl_ty ->
Typing_defs.locl_ty ->
Typing_error.Reasons_callback.t option ->
Typing_env_types.env * Typing_error.t option
val sub_type_ref : sub_type ref
val sub_type : sub_type
type sub_type_i =
Typing_env_types.env ->
?is_coeffect:bool ->
Typing_defs.internal_type ->
Typing_defs.internal_type ->
Typing_error.Reasons_callback.t option ->
Typing_env_types.env * Typing_error.t option
val sub_type_i_ref : sub_type_i ref
val sub_type_i : sub_type_i
type sub_type_with_dynamic_as_bottom =
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_defs.locl_ty ->
Typing_error.Reasons_callback.t option ->
Typing_env_types.env * Typing_error.t option
val sub_type_with_dynamic_as_bottom_ref : sub_type_with_dynamic_as_bottom ref
val sub_type_with_dynamic_as_bottom : sub_type_with_dynamic_as_bottom
type is_sub_type_type =
Typing_env_types.env -> Typing_defs.locl_ty -> Typing_defs.locl_ty -> bool
val is_sub_type_ref : is_sub_type_type ref
val is_sub_type :
Typing_env_types.env -> Typing_defs.locl_ty -> Typing_defs.locl_ty -> bool
val is_sub_type_for_union_ref :
(Typing_env_types.env -> Typing_defs.locl_ty -> Typing_defs.locl_ty -> bool)
ref
val is_sub_type_for_union_i_ref :
(Typing_env_types.env ->
Typing_defs.internal_type ->
Typing_defs.internal_type ->
bool)
ref
val is_sub_type_for_union :
Typing_env_types.env -> Typing_defs.locl_ty -> Typing_defs.locl_ty -> bool
val is_sub_type_for_union_i :
Typing_env_types.env ->
Typing_defs.internal_type ->
Typing_defs.internal_type ->
bool
val is_sub_type_ignore_generic_params_ref : is_sub_type_type ref
val is_sub_type_ignore_generic_params :
Typing_env_types.env -> Typing_defs.locl_ty -> Typing_defs.locl_ty -> bool
val can_sub_type_ref : is_sub_type_type ref
val can_sub_type :
Typing_env_types.env -> Typing_defs.locl_ty -> Typing_defs.locl_ty -> bool
val unwrap_class_type :
Typing_defs.decl_phase Typing_defs.ty ->
Typing_defs.decl_phase Typing_defs.Reason.t_
* Typing_defs.pos_id
* Typing_defs.decl_ty list
val try_unwrap_class_type :
Typing_defs.decl_phase Typing_defs.ty ->
(Typing_defs.decl_phase Typing_defs.Reason.t_
* Typing_defs.pos_id
* Typing_defs.decl_ty list)
option
val class_is_final_and_invariant : Decl_provider.Class.t -> bool
module HasTany : sig
val check : Typing_defs.locl_ty -> bool
val check_why : Typing_defs.locl_ty -> Typing_reason.t option
end
type localize_no_subst =
Typing_env_types.env ->
ignore_errors:bool ->
Typing_defs.decl_ty ->
(Typing_env_types.env * Typing_error.t option) * Typing_defs.locl_ty
val localize_no_subst_ref : localize_no_subst ref
val localize_no_subst :
Typing_env_types.env ->
ignore_errors:bool ->
Typing_defs.decl_ty ->
(Typing_env_types.env * Typing_error.t option) * Typing_defs.locl_ty
type localize =
ety_env:Typing_defs.expand_env ->
Typing_env_types.env ->
Typing_defs.decl_ty ->
(Typing_env_types.env * Typing_error.t option) * Typing_defs.locl_ty
val localize_ref : localize ref
val localize :
Typing_env_types.env ->
ety_env:Typing_defs.expand_env ->
Typing_defs.decl_ty ->
(Typing_env_types.env * Typing_error.t option) * Typing_defs.locl_ty
val is_class_i : Typing_defs.internal_type -> bool
val is_class : Typing_defs.locl_ty -> bool
val is_mixed_i : Typing_env_types.env -> Typing_defs.internal_type -> bool
val is_mixed : Typing_env_types.env -> Typing_defs.locl_ty -> bool
val is_nothing_i : Typing_env_types.env -> Typing_defs.internal_type -> bool
val is_nothing : Typing_env_types.env -> Typing_defs.locl_ty -> bool
val run_on_intersection :
'env ->
f:('env -> Typing_defs.locl_ty -> 'env * 'a) ->
Typing_defs.locl_ty list ->
'env * 'a list
val run_on_intersection_with_ty_err :
'env ->
f:('env -> Typing_defs.locl_ty -> ('env * Typing_error.t option) * 'a) ->
Typing_defs.locl_ty list ->
('env * Typing_error.t option) * 'a list
val run_on_intersection_res :
'a ->
f:('a -> Typing_defs.locl_ty -> 'a * 'b * 'c) ->
Typing_defs.locl_ty list ->
'a * 'b list * 'c list
val run_on_intersection_key_value_res :
'a ->
f:('a -> Typing_defs.locl_ty -> 'a * 'b * 'c * 'd) ->
Typing_defs.locl_ty list ->
'a * 'b list * 'c list * 'd list
val run_on_intersection_array_key_value_res :
'a ->
f:('a -> Typing_defs.locl_ty -> 'a * 'b * 'c * 'd * 'e) ->
Typing_defs.locl_ty list ->
'a * 'b list * 'c list * 'd list * 'e list
val is_dynamic : Typing_env_types.env -> Typing_defs.locl_ty -> bool
val is_any : Typing_env_types.env -> Typing_defs.locl_ty -> bool
val is_tunion : Typing_env_types.env -> Typing_defs.locl_ty -> bool
val is_tintersection : Typing_env_types.env -> Typing_defs.locl_ty -> bool
val is_tyvar : Typing_env_types.env -> Typing_defs.locl_ty -> bool
val is_opt_tyvar : Typing_env_types.env -> Typing_defs.locl_ty -> bool
val is_tyvar_error : Typing_env_types.env -> Typing_defs.locl_ty -> bool
val get_base_type :
?expand_supportdyn:bool ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_defs.locl_ty
val get_printable_shape_field_name : Typing_defs.tshape_field_name -> string
val shape_field_name_with_ty_err :
Typing_env_types.env ->
('a, 'b) Aast.expr ->
Ast_defs.shape_field_name option * Typing_error.t option
val simplify_constraint_type :
Typing_env_types.env ->
Typing_defs.constraint_type ->
Typing_env_types.env * Typing_defs.internal_type
type add_constraint =
Typing_env_types.env ->
Ast_defs.constraint_kind ->
Typing_defs.locl_ty ->
Typing_defs.locl_ty ->
Typing_error.Reasons_callback.t option ->
Typing_env_types.env
val add_constraint_ref : add_constraint ref
val add_constraint : add_constraint
type expand_typeconst =
Typing_defs.expand_env ->
Typing_env_types.env ->
?ignore_errors:bool ->
?as_tyvar_with_cnstr:Pos.t option ->
Typing_defs.locl_ty ->
Typing_defs.pos_id ->
allow_abstract_tconst:bool ->
(Typing_env_types.env * Typing_error.t option) * Typing_defs.locl_ty
val expand_typeconst_ref : expand_typeconst ref
val expand_typeconst :
Typing_defs.expand_env ->
Typing_env_types.env ->
?ignore_errors:bool ->
?as_tyvar_with_cnstr:Pos.t option ->
Typing_defs.locl_ty ->
Typing_defs.pos_id ->
allow_abstract_tconst:bool ->
(Typing_env_types.env * Typing_error.t option) * Typing_defs.locl_ty
type union =
Typing_env_types.env ->
?approx_cancel_neg:bool ->
Typing_defs.locl_ty ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty
val union_ref : union ref
val union :
Typing_env_types.env ->
?approx_cancel_neg:bool ->
Typing_defs.locl_ty ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty
type make_union =
Typing_env_types.env ->
Typing_reason.t ->
Typing_defs.locl_ty list ->
Typing_reason.t option ->
Typing_reason.t option ->
Typing_env_types.env * Typing_defs.locl_ty
val make_union_ref : make_union ref
val make_union :
Typing_env_types.env ->
Typing_reason.t ->
Typing_defs.locl_ty list ->
Typing_reason.t option ->
Typing_reason.t option ->
Typing_env_types.env * Typing_defs.locl_ty
type union_i =
Typing_env_types.env ->
?approx_cancel_neg:bool ->
Typing_reason.t ->
Typing_defs.internal_type ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.internal_type
val union_i_ref : union_i ref
val union_i :
Typing_env_types.env ->
?approx_cancel_neg:bool ->
Typing_reason.t ->
Typing_defs.internal_type ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.internal_type
type union_list =
Typing_env_types.env ->
?approx_cancel_neg:bool ->
Typing_reason.t ->
Typing_defs.locl_ty list ->
Typing_env_types.env * Typing_defs.locl_ty
val union_list_ref : union_list ref
val union_list :
Typing_env_types.env ->
?approx_cancel_neg:bool ->
Typing_reason.t ->
Typing_defs.locl_ty list ->
Typing_env_types.env * Typing_defs.locl_ty
type fold_union =
Typing_env_types.env ->
?approx_cancel_neg:bool ->
Typing_reason.t ->
Typing_defs.locl_ty list ->
Typing_env_types.env * Typing_defs.locl_ty
val fold_union_ref : fold_union ref
type simplify_unions =
Typing_env_types.env ->
?approx_cancel_neg:bool ->
?on_tyvar:
(Typing_env_types.env ->
Typing_reason.t ->
Ident.t ->
Typing_env_types.env * Typing_defs.locl_ty) ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty
val simplify_unions_ref : simplify_unions ref
type intersect_list =
Typing_env_types.env ->
Typing_reason.t ->
Typing_defs.locl_ty list ->
Typing_env_types.env * Typing_defs.locl_ty
val intersect_list_ref : intersect_list ref
val intersect_list : intersect_list
val contains_tvar_decl : Typing_defs.decl_ty -> bool
val contains_generic_decl : Typing_defs.decl_ty -> Pos_or_decl.t option
(** [wrap_union_inter_ty_in_var env r ty] wraps [ty] in a type variable
if [ty] is a union, intersection or option containing an unsolved type variable.
Wrapping in a type variable means a new type variable is created and mapped to [ty].
This is a way to mark [ty] as needing simplification when the unsolved type variable
later gets solved. *)
val wrap_union_inter_ty_in_var :
Typing_env_types.env ->
Typing_defs.Reason.t ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty
val get_concrete_supertypes :
?expand_supportdyn:bool ->
?include_case_types:bool ->
abstract_enum:bool ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_set.elt list
val simplify_unions :
Typing_env_types.env ->
?approx_cancel_neg:bool ->
?on_tyvar:
(Typing_env_types.env ->
Typing_reason.t ->
Ident.t ->
Typing_env_types.env * Typing_defs.locl_ty) ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty
type approx =
| ApproxUp
| ApproxDown
[@@deriving eq]
type negate_type =
Typing_env_types.env ->
Typing_reason.t ->
Typing_defs.locl_ty ->
approx:approx ->
Typing_env_types.env * Typing_defs.locl_ty
val negate_type_ref : negate_type ref
val negate_type :
Typing_env_types.env ->
Typing_reason.t ->
Typing_defs.locl_ty ->
approx:approx ->
Typing_env_types.env * Typing_defs.locl_ty
val simplify_intersections :
Typing_env_types.env ->
?on_tyvar:
(Typing_env_types.env ->
Typing_reason.t ->
int ->
Typing_env_types.env * Typing_defs.locl_ty) ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty
type simplify_intersections =
Typing_env_types.env ->
?on_tyvar:
(Typing_env_types.env ->
Typing_reason.t ->
int ->
Typing_env_types.env * Typing_defs.locl_ty) ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty
val simplify_intersections_ref : simplify_intersections ref
val is_type_disjoint :
Typing_env_types.env -> Typing_defs.locl_ty -> Typing_defs.locl_ty -> bool
val is_type_disjoint_ref :
(Typing_env_types.env -> Typing_defs.locl_ty -> Typing_defs.locl_ty -> bool)
ref
val collect_enum_class_upper_bounds :
Typing_env_types.env ->
string ->
Typing_env_types.env * Typing_defs.locl_ty option
val default_fun_param : ?pos:Pos_or_decl.t -> 'a -> 'a Typing_defs.fun_param
val tany : Typing_env_types.env -> Typing_defs.locl_phase Typing_defs.ty_
val mk_tany :
Typing_env_types.env -> Pos.t -> Typing_reason.locl_phase Typing_defs.ty
val make_locl_subst_for_class_tparams :
Decl_provider.Class.t ->
Typing_defs.locl_ty list ->
Typing_defs.locl_ty SMap.t
val is_sub_class_refl : Typing_env_types.env -> string -> string -> bool
val class_has_no_params : Typing_env_types.env -> string -> bool
val has_ancestor_including_req_refl :
Typing_env_types.env -> string -> string -> bool
val has_ancestor_including_req :
Typing_env_types.env -> Decl_provider.Class.t -> string -> bool
(* If input is dynamic | t or t | dynamic then return Some t.
* Otherwise return None.
*)
val try_strip_dynamic :
Typing_env_types.env -> Typing_defs.locl_ty -> Typing_defs.locl_ty option
val try_strip_dynamic_from_union :
Typing_env_types.env ->
Typing_defs.locl_ty list ->
Typing_defs.locl_ty list option
(* If input is dynamic | t or t | dynamic then return t,
* otherwise return type unchanged. *)
val strip_dynamic :
Typing_env_types.env -> Typing_defs.locl_ty -> Typing_defs.locl_ty
(* Wrap supportdyn<_> around a type. Push through intersections
* and unions, and leave type alone if it is a subtype of dynamic.
*)
val make_supportdyn :
Typing_reason.t ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty
val simple_make_supportdyn :
Typing_reason.t ->
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty
val make_supportdyn_decl_type :
Pos_or_decl.t ->
Typing_defs.Reason.decl_t ->
Typing_defs.decl_ty ->
Typing_defs.decl_ty
(* Wrap ~ around a type, unless it is already a dynamic or a like type *)
val make_like :
Typing_env_types.env -> Typing_defs.locl_ty -> Typing_defs.locl_ty
(* Wrap ~ around a type if it is enforced. This is used for returns, property
* assignment, and default expression typing
*)
val make_like_if_enforced :
Typing_env_types.env ->
Typing_defs.locl_possibly_enforced_ty ->
Typing_defs.locl_possibly_enforced_ty
val is_capability : Typing_defs.locl_ty -> bool
val is_capability_i : Typing_defs.internal_type -> bool
val supports_dynamic :
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_error.Reasons_callback.t option ->
Typing_env_types.env * Typing_error.t option
(* Return true if type definitely is a subtype of supportdyn<mixed> *)
val is_supportdyn : Typing_env_types.env -> Typing_defs.locl_ty -> bool
val strip_supportdyn :
Typing_env_types.env ->
Typing_defs.locl_ty ->
bool * Typing_env_types.env * Typing_defs.locl_ty
val no_upper_bound :
include_sd_mixed:bool ->
Typing_env_types.env ->
Typing_defs.locl_ty list ->
Typing_env_types.env * bool
val recompose_like_type :
Typing_env_types.env ->
Typing_defs.locl_ty ->
Typing_env_types.env * Typing_defs.locl_ty
val make_simplify_typed_expr :
Typing_env_types.env ->
Pos.t ->
Typing_defs.locl_ty ->
(Typing_defs.locl_ty, Tast.saved_env) Aast_defs.expr_ ->
Typing_env_types.env * Tast.expr
val partition_union :
f:('a Typing_defs.ty -> bool) ->
'a Typing_defs.ty list ->
'a Typing_defs.ty list * 'a Typing_defs.ty list |
OCaml | hhvm/hphp/hack/src/typing/typing_variance.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 Utils
module SN = Naming_special_names
module Cls = Decl_provider.Class
(*****************************************************************************)
(* Module checking the (co/contra)variance annotations (+/-).
*
* The algorithm works by tracking the variance of *uses* of a type parameter,
* and checks that the variance *declaration* on that type parameter is
* consistent with its uses.
*
* For every type parameter use, we keep a witness (a position in the source),
* that tells us where the covariance (or contravariance) was deduced.
* This way, when we find an error, we can point to the place that was
* problematic (as usual).
*)
(*****************************************************************************)
(* Type describing the kind of position we are dealing with.
* Pos.t gives us the position in the source, it doesn't tell us the kind
* of position we are dealing with. This type keeps track of that.
*)
type position_descr =
| Rtypedef
| Rproperty (* Instance variable *)
| Rtype_parameter (* The declaration site of a type-parameter *)
| Rfun_parameter
| Rfun_return
| Rtype_argument of string
(* The argument of a parametric class or
* typedef:
* A<T1, ..>, T1 is (Rtype_argument "A")
*)
| Rconstraint_as
| Rconstraint_eq
| Rconstraint_super
| Rrefinement_eq
| Rrefinement_as
| Rrefinement_super
| Rwhere_as
| Rwhere_super
| Rwhere_eq
| Rfun_inout_parameter
type position_variance =
| Pcovariant
| Pcontravariant
| Pinvariant
type reason = Pos.t * position_descr * position_variance
(* The variance that we have inferred for a given use of a type-parameter. We keep
* a stack of reasons that made us infer the variance of a position.
* For example:
* T appears in foo(...): (function(...): T)
* T is inferred as covariant + a stack made of two elements:
* -) The first one points to the position of T
* -) The second one points to the position of (function(...): T)
* We can, thanks to this stack, detail why we think something is covariant
* in the error message.
*)
type variance =
(* The type parameter appeared in covariant position. *)
| Vcovariant of reason list
(* The type parameter appeared in contravariant position. *)
| Vcontravariant of reason list
(* The type parameter appeared in both covariant and contravariant position.
* We keep a stack for each side: the left hand side is proof for covariance,
* while the right hand side is proof for contravariance.
*)
| Vinvariant of reason list * reason list
(* The type parameter is not used, or is a method type parameter.
*)
| Vboth
module Env = struct
(** The set of type parameters which are in scope, with their variances. *)
type type_parameter_env = variance SMap.t
type t = {
tpenv: type_parameter_env;
enclosing_class: Nast.class_ option;
env: Typing_env_types.env;
}
let remove_type_parameter : t -> string -> t =
(fun env name -> { env with tpenv = SMap.remove name env.tpenv })
end
(*****************************************************************************)
(* Reason pretty-printing *)
(*****************************************************************************)
let variance_to_string = function
| Pcovariant -> "covariant (+)"
| Pcontravariant -> "contravariant (-)"
| Pinvariant -> "invariant"
let variance_to_sign = function
| Pcovariant -> "(+)"
| Pcontravariant -> "(-)"
| Pinvariant -> "(I)"
let reason_stack_to_string variance reason_stack =
Printf.sprintf
"This position is %s because it is the composition of %s\nThe rest of the error messages decomposes the inference of the variance.\nCheck out this link if you don't understand what this is about:\nhttp://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)"
variance
(List.fold_right
reason_stack
~f:
begin
(fun (_, _, pvariance) acc -> variance_to_sign pvariance ^ acc)
end
~init:"")
let reason_to_string ~sign (_, descr, variance) =
(if sign then
variance_to_sign variance ^ " "
else
"")
^
match descr with
| Rtypedef -> "Aliased types are covariant"
| Rproperty -> "A non private class property is always invariant"
| Rtype_parameter ->
"The type parameter was declared as " ^ variance_to_string variance
| Rfun_parameter -> "Function parameters are contravariant"
| Rfun_return -> "Function return types are covariant"
| Rtype_argument name ->
Printf.sprintf
"This type parameter was declared as %s (cf '%s')"
(variance_to_string variance)
name
| Rconstraint_super ->
"`super` constraints on method type parameters are covariant"
| Rconstraint_as ->
"`as` constraints on method type parameters are contravariant"
| Rconstraint_eq -> "`=` constraints on method type parameters are invariant"
| Rwhere_as ->
"`where _ as _` constraints are covariant on the left, contravariant on the right"
| Rwhere_eq -> "`where _ = _` constraints are invariant on the left and right"
| Rwhere_super ->
"`where _ super _` constraints are contravariant on the left, covariant on the right"
| Rfun_inout_parameter ->
"Inout/ref function parameters are both covariant and contravariant"
| Rrefinement_eq -> "exact refinements are invariant"
| Rrefinement_as -> "`as` refinement bounds are covariant"
| Rrefinement_super -> "`super` refinement bounds are contravariant"
let detailed_message variance pos stack =
match stack with
| [] -> []
| [((p, _, _) as r)] -> [(p, reason_to_string ~sign:false r)]
| _ ->
(pos, reason_stack_to_string variance stack)
:: List.map stack ~f:(fun ((p, _, _) as r) ->
(p, reason_to_string ~sign:true r))
(*****************************************************************************)
(* Converts an annotation (+/-) to a type. *)
(*****************************************************************************)
let make_variance reason pos = function
| Ast_defs.Covariant -> Vcovariant [(pos, reason, Pcovariant)]
| Ast_defs.Contravariant -> Vcontravariant [(pos, reason, Pcontravariant)]
| Ast_defs.Invariant ->
Vinvariant ([(pos, reason, Pinvariant)], [(pos, reason, Pinvariant)])
(*****************************************************************************)
(* Used when we want to compose with the variance coming from another class.
* Let's assume: A<-T>
* public function foo(A<T> $x): void;
* A<T> is in contravariant position so we process -A<T>.
* because A is annotated with a minus: we deduce --T (which becomes T).
*)
(*****************************************************************************)
let compose (pos, param_descr) from to_ =
(* We don't really care how we deduced the variance that we are composing
* with (_stack_to). That's because the decomposition could be in a different
* file and would be too hard to follow anyway.
* Let's consider the following return type: A<T>.
* Turns out A is declared as A<-T>.
* It's not a good idea for us to point to what made us deduce that the
* position was contravariant (the declaration side). Because the user will
* wonder where it comes from.
* It's better to point to the return type (more precisely, point to the T
* in the return type) and explain that this position is contravariant.
* Later on, the user can go and check the definition of A for herself.
*)
match (from, to_) with
| (Vcovariant stack_from, Vcovariant _stack_to) ->
let reason = (pos, param_descr, Pcovariant) in
Vcovariant (reason :: stack_from)
| (Vcontravariant stack_from, Vcontravariant _stack_to) ->
let reason = (pos, param_descr, Pcontravariant) in
Vcovariant (reason :: stack_from)
| (Vcovariant stack_from, Vcontravariant _stack_to) ->
let reason = (pos, param_descr, Pcontravariant) in
Vcontravariant (reason :: stack_from)
| (Vcontravariant stack_from, Vcovariant _stack_to) ->
let reason = (pos, param_descr, Pcovariant) in
Vcontravariant (reason :: stack_from)
| ((Vinvariant _ as x), _) -> x
| (_, Vinvariant (_co, _contra)) ->
let reason = (pos, param_descr, Pinvariant) in
Vinvariant ([reason], [reason])
| (Vboth, x)
| (x, Vboth) ->
x
(*****************************************************************************)
(* Given a type parameter, returns the declared variance. *)
(*****************************************************************************)
let get_tparam_variance env name =
match SMap.find_opt name env with
| None -> Vboth
| Some x -> x
(*****************************************************************************)
(* Given a type parameter, returns the variance declared. *)
(*****************************************************************************)
let get_declared_variance : Pos.t -> Ast_defs.variance -> variance =
make_variance Rtype_parameter
let make_decl_tparam_variance : Typing_defs.decl_tparam -> variance =
fun t ->
get_declared_variance
(fst t.tp_name |> Pos_or_decl.unsafe_to_raw_pos)
t.tp_variance
let get_declared_variance : Nast.tparam -> variance =
(fun t -> get_declared_variance (fst t.Aast.tp_name) t.Aast.tp_variance)
(******************************************************************************)
(* Checks that a 'this' type is correctly used at a given contravariant *)
(* position in a final class. *)
(******************************************************************************)
let check_final_this_pos_variance :
Typing_env_types.env -> variance -> Pos.t -> Nast.class_ -> unit =
fun env env_variance rpos class_ ->
if class_.Aast.c_final then
List.iter class_.Aast.c_tparams ~f:(fun t ->
match (env_variance, t.Aast.tp_variance) with
| (Vcontravariant _, (Ast_defs.Covariant | Ast_defs.Contravariant)) ->
Typing_error_utils.add_typing_error
~env
Typing_error.(
primary
@@ Primary.Contravariant_this
{
pos = rpos;
class_name =
Utils.strip_ns (Ast_defs.get_id class_.Aast.c_name);
typaram_name = snd t.Aast.tp_name;
})
| _ -> ())
(*****************************************************************************)
(* Returns the list of type parameter variance for a given class.
*
* N.B.: this function works both with classes and typedefs.
*)
(*****************************************************************************)
let get_class_variance : Typing_env_types.env -> Ast_defs.id -> _ =
fun env (pos, class_name) ->
match class_name with
| name when String.equal name SN.Classes.cAwaitable ->
[Vcovariant [(pos, Rtype_argument (Utils.strip_ns name), Pcovariant)]]
| _ ->
let tparams =
match Typing_env.get_class_or_typedef env class_name with
| Some (Typing_env.TypedefResult { td_tparams; _ }) -> td_tparams
| Some (Typing_env.ClassResult cls) -> Cls.tparams cls
| None -> []
in
List.map tparams ~f:make_decl_tparam_variance
let union (pos1, neg1) (pos2, neg2) =
( SMap.union ~combine:(fun _ x y -> Some (x @ y)) pos1 pos2,
SMap.union ~combine:(fun _ x y -> Some (x @ y)) neg1 neg2 )
let flip (pos, neg) = (neg, pos)
let rec get_typarams_union ~tracked tenv acc (ty : decl_ty) =
union acc (get_typarams ~tracked tenv ty)
and get_typarams ~tracked tenv (ty : decl_ty) =
let empty = (SMap.empty, SMap.empty) in
let get_typarams_union = get_typarams_union ~tracked tenv in
let get_typarams_list tyl =
List.fold_left tyl ~init:empty ~f:get_typarams_union
in
let get_typarams = get_typarams ~tracked tenv in
let single id pos = (SMap.singleton id [pos], SMap.empty) in
let rec get_typarams_variance_list acc variancel tyl =
match (variancel, tyl) with
| (variance :: variancel, ty :: tyl) ->
let param = get_typarams ty in
let param =
match variance with
| Vcovariant _ -> param
| Vcontravariant _ -> flip param
| _ -> union param (flip param)
in
get_typarams_variance_list (union acc param) variancel tyl
| _ -> acc
in
match get_node ty with
| Tgeneric (id, _tyargs) ->
(* TODO(T69551141) handle type arguments *)
(* Only count tracked generic parameters *)
if SSet.mem id tracked then
single id (get_reason ty)
else
empty
| Tnonnull
| Tdynamic
| Tprim _
| Tany _
| Tthis
| Tmixed
| Twildcard ->
empty
| Toption ty
| Tlike ty
| Taccess (ty, _) ->
get_typarams ty
| Trefinement (ty, rs) ->
SMap.fold
(fun _ { rc_bound; _ } acc ->
match rc_bound with
| TRexact bnd ->
let tp = get_typarams bnd in
union acc @@ union (flip tp) tp
| TRloose bnds ->
(* Lower bounds on type members are contravariant
* while upper bounds are covariant. Interestingly,
* this differs from where constraints because,
* logically, those sit on the LHS of an
* implication while refinements are on the RHS.
* (A => B) |- (A' => B ) if A' |- A
* (A => B) |- (A => B') if B |- B'
*)
union
(flip (get_typarams_list bnds.tr_lower))
(get_typarams_list bnds.tr_upper))
rs.cr_consts
(get_typarams ty)
| Tunion tyl
| Tintersection tyl
| Ttuple tyl ->
get_typarams_list tyl
| Tshape { s_fields = m; _ } ->
TShapeMap.fold
(fun _ { sft_ty; _ } res -> get_typarams_union res sft_ty)
m
empty
| Tfun ft ->
let get_typarams_param acc fp =
let tp = get_typarams fp.fp_type.et_type in
let tp =
match get_fp_mode fp with
(* Parameters behave contravariantly *)
| FPnormal -> flip tp
(* Inout parameters behave both co- and contra-variantly *)
| FPinout -> union tp (flip tp)
in
union acc tp
in
let params =
List.fold_left ft.ft_params ~init:empty ~f:get_typarams_param
in
let implicit_params =
let { capability } = ft.ft_implicit_params in
match capability with
| CapDefaults _ -> empty
| CapTy ty -> get_typarams ty
in
let ret = get_typarams ft.ft_ret.et_type in
let get_typarams_constraint acc (ck, ty) =
union
acc
(match ck with
| Ast_defs.Constraint_as -> get_typarams ty
| Ast_defs.Constraint_eq ->
let tp = get_typarams ty in
union (flip tp) tp
| Ast_defs.Constraint_super -> flip (get_typarams ty))
in
let get_typarams_tparam acc tp =
List.fold_left tp.tp_constraints ~init:acc ~f:get_typarams_constraint
in
let bounds =
List.fold_left ft.ft_tparams ~init:empty ~f:get_typarams_tparam
in
let get_typarams_where_constraint acc (ty1, ck, ty2) =
union
acc
(match ck with
| Ast_defs.Constraint_super ->
union (flip (get_typarams ty1)) (get_typarams ty2)
| Ast_defs.Constraint_as ->
union (get_typarams ty1) (flip (get_typarams ty2))
| Ast_defs.Constraint_eq ->
let tp = union (get_typarams ty1) (get_typarams ty2) in
union tp (flip tp))
in
let constrs =
List.fold_left
ft.ft_where_constraints
~init:empty
~f:get_typarams_where_constraint
in
(* Result so far: bounds, constraints, return, parameters *)
let result =
params
|> union implicit_params
|> union ret
|> union constrs
|> union bounds
in
(* Get the lower bounds of a type parameter, including where constraints
* of the form `where t as T` or `where T super t`
*)
let get_lower_bounds tp =
let name = snd tp.tp_name in
List.filter_map
~f:(fun (ck, ty) ->
match ck with
| Ast_defs.Constraint_super
| Ast_defs.Constraint_eq ->
Some ty
| _ -> None)
tp.tp_constraints
@ List.filter_map
~f:(fun (ty1, ck, ty2) ->
match ck with
| Ast_defs.Constraint_as
| Ast_defs.Constraint_eq
when is_generic_equal_to name ty2 ->
Some ty1
| Ast_defs.Constraint_super
| Ast_defs.Constraint_eq
when is_generic_equal_to name ty1 ->
Some ty2
| _ -> None)
ft.ft_where_constraints
in
(* Get the upper bounds of a type parameter, including where constraints
* of the form `where T as t` or `where t super T`
*)
let get_upper_bounds tp =
let name = snd tp.tp_name in
List.filter_map
~f:(fun (ck, ty) ->
match ck with
| Ast_defs.Constraint_as
| Ast_defs.Constraint_eq ->
Some ty
| _ -> None)
tp.tp_constraints
@ List.filter_map
~f:(fun (ty1, ck, ty2) ->
match ck with
| Ast_defs.Constraint_as
| Ast_defs.Constraint_eq
when is_generic_equal_to name ty1 ->
Some ty2
| Ast_defs.Constraint_super
| Ast_defs.Constraint_eq
when is_generic_equal_to name ty2 ->
Some ty1
| _ -> None)
ft.ft_where_constraints
in
(* If a type parameter appears covariantly, then treat its lower bounds as covariant *)
let propagate_covariant_to_lower_bounds tp =
get_typarams_list (get_lower_bounds tp)
in
(* If a type parameter appears contravariantly, then treat its upper bounds as contravariant *)
let propagate_contravariant_to_upper_bounds tp =
flip (get_typarams_list (get_upper_bounds tp))
in
(* Given a type parameter, propagate its variance (co and/or contra) to lower and upper bounds
* as appropriate. See Typing_env.set_tyvar_appears_covariantly_and_propagate etc for an
* analagous calculation for type variables.
*)
let propagate_typarams_tparam acc tp =
let acc =
if SMap.mem (snd tp.tp_name) (fst result) then
union acc (propagate_covariant_to_lower_bounds tp)
else
acc
in
let acc =
if SMap.mem (snd tp.tp_name) (snd result) then
union acc (propagate_contravariant_to_upper_bounds tp)
else
acc
in
acc
in
List.fold_left ft.ft_tparams ~init:result ~f:propagate_typarams_tparam
| Tapply (pos_name, tyl) ->
let variancel =
get_class_variance tenv (Positioned.unsafe_to_raw_positioned pos_name)
in
get_typarams_variance_list empty variancel tyl
| Tnewtype (name, tyl, _) ->
let variancel =
let tparams =
match Typing_env.get_typedef tenv name with
| Some { td_tparams; _ } -> td_tparams
| None -> []
in
List.map tparams ~f:make_decl_tparam_variance
in
get_typarams_variance_list empty variancel tyl
| Tvec_or_dict (ty1, ty2) -> union (get_typarams ty1) (get_typarams ty2)
let get_positive_negative_generics ~tracked ~is_mutable env acc ty =
let r = get_typarams ~tracked env ty in
if is_mutable then
union acc (union r (flip r))
else
union acc r
let generic_ :
Typing_env_types.env ->
Env.type_parameter_env ->
variance ->
string ->
_ ->
unit =
fun tyenv env variance name _targs ->
(* TODO(T69931993) Once we support variance for higher-kinded generics, we have to update this.
For now, having type arguments implies that the declared must be invariant *)
let declared_variance = get_tparam_variance env name in
match (declared_variance, variance) with
(* Happens if type parameter isn't from class *)
| (Vboth, _)
| (_, Vboth) ->
()
| (Vinvariant _, _)
| (Vcovariant _, Vcovariant _)
| (Vcontravariant _, Vcontravariant _) ->
()
| (Vcovariant stack1, (Vcontravariant stack2 | Vinvariant (_, stack2))) ->
let (pos1, _, _) = List.hd_exn stack1 in
let (pos2, _, _) = List.hd_exn stack2 in
let emsg = lazy (detailed_message "contravariant (-)" pos2 stack2) in
Typing_error_utils.add_typing_error
~env:tyenv
Typing_error.(
primary
@@ Primary.Declared_covariant
{ param_pos = pos1; pos = pos2; msgs = emsg })
| (Vcontravariant stack1, (Vcovariant stack2 | Vinvariant (stack2, _))) ->
let (pos1, _, _) = List.hd_exn stack1 in
let (pos2, _, _) = List.hd_exn stack2 in
let emsg = lazy (detailed_message "covariant (+)" pos2 stack2) in
Typing_error_utils.add_typing_error
~env:tyenv
Typing_error.(
primary
@@ Primary.Declared_contravariant
{ param_pos = pos2; pos = pos1; msgs = emsg })
(*****************************************************************************)
(* Used for the arguments of function. *)
(*****************************************************************************)
let flip reason = function
| Vcovariant stack -> Vcontravariant (reason :: stack)
| Vcontravariant stack -> Vcovariant (reason :: stack)
| Vinvariant _ as x -> x
| Vboth -> Vboth
let detail reason = function
| Vcovariant stack -> Vcovariant (reason :: stack)
| Vcontravariant stack -> Vcontravariant (reason :: stack)
| variance -> variance
let rec hint : Env.t -> variance -> Aast_defs.hint -> unit =
fun env variance (pos, h) ->
let open Aast_defs in
match h with
| Habstr (name, targs) ->
(* This section makes the position more precise.
* Say we find a return type that is a tuple (int, int, T).
* The whole tuple is in covariant position, and so the position
* is going to include the entire tuple.
* That can make things pretty unreadable when the type is long.
* Here we replace the position with the exact position of the generic
* that was problematic. *)
let variance =
match variance with
| Vcovariant ((pos', x, y) :: rest) when not (Pos.equal pos pos') ->
Vcovariant ((pos, x, y) :: rest)
| Vcontravariant ((pos', x, y) :: rest) when not (Pos.equal pos pos') ->
Vcontravariant ((pos, x, y) :: rest)
| x -> x
in
generic_ env.Env.env env.Env.tpenv variance name targs
| Hany
| Herr
| Hmixed
| Hwildcard
| Hnonnull
| Hdynamic
| Hnothing
| Hvar _
| Hfun_context _
| Hprim _ ->
()
| Hvec_or_dict (hk, hv) ->
Option.iter hk ~f:(hint env variance);
hint env variance hv
| Hthis ->
(* Check that 'this' isn't being improperly referenced in a contravariant
* position.
* With the exception of that check, `this` constraints are bivariant
* (otherwise any class that used the `this` type would not be able to use
* covariant type params). *)
Option.value_map
env.Env.enclosing_class
~default:()
~f:(check_final_this_pos_variance env.Env.env variance pos)
| Hoption h
| Hlike h
| Hsoft h
| Haccess (h, _) ->
hint env variance h
| Hunion tyl
| Hintersection tyl
| Htuple tyl ->
hint_list env variance tyl
| Hshape { nsi_allows_unknown_fields = _; nsi_field_map } ->
List.iter
nsi_field_map
~f:(fun { sfi_hint; sfi_optional = _; sfi_name = _ } ->
hint env variance sfi_hint)
| Hrefinement (h, members) ->
List.iter members ~f:(refinement_member env variance);
hint env variance h
| Hfun hfun ->
let {
hf_is_readonly = _;
hf_param_tys;
hf_param_info;
hf_variadic_ty;
hf_return_ty;
hf_ctxs = _;
hf_is_readonly_return = _;
} =
hfun
in
List.iter2_exn hf_param_info hf_param_tys ~f:(hfun_param env variance);
fun_arity env variance hf_variadic_ty;
fun_ret env variance hf_return_ty
| Happly (_, []) -> ()
| Happly (name, hl) ->
let variancel = get_class_variance env.Env.env name in
iter2_shortest
begin
fun tparam_variance h ->
let pos = Ast_defs.get_pos h in
let reason =
Rtype_argument (Utils.strip_ns @@ Ast_defs.get_id name)
in
let variance = compose (pos, reason) variance tparam_variance in
hint env variance h
end
variancel
hl
and hint_list env variance tyl = List.iter tyl ~f:(hint env variance)
and hfun_param env variance info h =
let pos = Ast_defs.get_pos h in
match Option.map info ~f:(fun x -> x.Aast.hfparam_kind) with
| None
| Some Ast_defs.Pnormal ->
let reason = (pos, Rfun_parameter, Pcontravariant) in
let variance = flip reason variance in
hint env variance h
| Some (Ast_defs.Pinout _) ->
let variance = make_variance Rfun_inout_parameter pos Ast_defs.Invariant in
hint env variance h
and fun_ret env variance h =
let pos = Ast_defs.get_pos h in
let reason_covariant = (pos, Rfun_return, Pcovariant) in
let variance = detail reason_covariant variance in
hint env variance h
and fun_arity env variance h =
let empty_param_info = None in
Option.iter h ~f:(hfun_param env variance empty_param_info)
and refinement_member env variance member =
let check_exact h =
let pos = Ast_defs.get_pos h in
let reason = [(pos, Rrefinement_eq, Pinvariant)] in
let var = Vinvariant (reason, reason) in
hint env var h
in
let check_loose (lower, upper) =
List.iter lower ~f:(fun h ->
let pos = Ast_defs.get_pos h in
let reason = (pos, Rrefinement_super, Pcontravariant) in
let var = flip reason variance in
hint env var h);
List.iter upper ~f:(fun h ->
let pos = Ast_defs.get_pos h in
let reason = (pos, Rrefinement_as, Pcovariant) in
let var = detail reason variance in
hint env var h)
in
match member with
| Aast.Rtype (_, ref) ->
(match ref with
| Aast.TRexact h -> check_exact h
| Aast.TRloose { Aast.tr_lower = lb; tr_upper = ub } -> check_loose (lb, ub))
| Aast.Rctx (_, ref) ->
(match ref with
| Aast.CRexact h -> check_exact h
| Aast.CRloose { Aast.cr_lower = lb; cr_upper = ub } ->
check_loose (Option.to_list lb, Option.to_list ub))
let fun_param : Env.t -> variance -> Nast.fun_param -> unit =
fun env variance param ->
let {
Aast.param_type_hint = (_, h);
param_is_variadic = _;
param_pos = _;
param_name = _;
param_annotation = _;
param_expr = _;
param_readonly = _;
param_callconv;
param_user_attributes = _;
param_visibility = _;
} =
param
in
Option.iter
h
~f:
(hfun_param
env
variance
(Some
Aast.{ hfparam_kind = param_callconv; hfparam_readonlyness = None }))
let fun_where_constraint : Env.t -> Aast.where_constraint_hint -> unit =
fun env (h1, ck, h2) ->
let pos1 = Ast_defs.get_pos h1 in
let pos2 = Ast_defs.get_pos h2 in
match ck with
| Ast_defs.Constraint_super ->
let var1 = Vcontravariant [(pos1, Rwhere_super, Pcontravariant)] in
let var2 = Vcovariant [(pos2, Rwhere_super, Pcovariant)] in
hint env var1 h1;
hint env var2 h2
| Ast_defs.Constraint_eq ->
let reason1 = [(pos1, Rwhere_eq, Pinvariant)] in
let reason2 = [(pos2, Rwhere_eq, Pinvariant)] in
let var = Vinvariant (reason1, reason2) in
hint env var h1;
hint env var h2
| Ast_defs.Constraint_as ->
let var1 = Vcovariant [(pos1, Rwhere_as, Pcovariant)] in
let var2 = Vcontravariant [(pos2, Rwhere_as, Pcontravariant)] in
hint env var1 h1;
hint env var2 h2
(* `as` constraints on method type parameters must be contravariant
* and `super` constraints on method type parameters are covariant. To
* see why, suppose that we allow the wrong variance:
*
* class Foo<+T> {
* public function bar<Tu as T>(Tu $x) {}
* }
*
* Let A and B be classes, with B a subtype of A. Then
*
* function f(Foo<A> $x) {
* $x->(new A());
* }
*
* typechecks. However, covariance means that we could call `f()` with an
* instance of B. However, B::bar would expect its argument $x to be a subtype
* of B, but we would be passing an instance of A to it, which should be a type
* error. In other words, `as` constraints are upper type bounds, and since
* subtypes must have more relaxed constraints than their supertypes, `as`
* constraints must be contravariant. (Reversing this argument shows that
* `super` constraints must be covariant.)
*
* The preceding discussion might lead one to think that the constraints should
* have the same variance as the class parameter types, i.e. that `as`
* constraints used in the return type should be covariant. In particular,
* suppose
*
* class Foo<-T> {
* public function bar<Tu as T>(Tu $x): Tu { ... }
* public function baz<Tu as T>(): Tu { ... }
* }
*
* class A {}
* class B extends A {
* public function qux() {}
* }
*
* function f(Foo<B> $x) {
* $x->baz()->qux();
* }
*
* Now `f($x)` could be a runtime error if `$x` was an instance of Foo<A>, and
* it seems like we should enforce covariance on Tu. However, the real problem
* is that constraints apply to _instantiation_, not usage. As far as Hack
* knows, $x->bar() could be of any type, since we have not provided any clues
* about how `Tu` should be instantiated. In fact `$x->bar()->whatever()`
* succeeds as well, because `Tu` is of type Tany -- though in an ideal world
* we would make it Tmixed in order to ensure soundness. Also, the signature
* of `baz()` doesn't entirely make sense -- why constrain Tu if it it's only
* getting used in one place?
*
* Thus, if one wants type safety, how `$x` _should_ be used is
*
* function f(Foo<B> $x) {
* $x->bar(new B()))->qux();
* }
*
* Thus we can see that, if `$x` is used correctly (or if we enforced correct
* use by returning Tmixed for uninstantiated type variables), we would always
* know the exact type of Tu, and Tu can be validly used in both co- and
* contravariant positions.
*
* Remark: This is far more intuitive if you think about how Vector::concat is
* typed with its `Tu super T` type in both the parameter and return type
* positions. Uninstantiated `super` types are less likely to cause confusion,
* however -- you can't imagine doing very much with a returned value that is
* some (unspecified) supertype of a class.
*)
let tparam_constraint : Env.t -> Ast_defs.constraint_kind * Aast.hint -> unit =
fun env (ck, h) ->
let pos = Ast_defs.get_pos h in
let var =
match ck with
| Ast_defs.Constraint_as ->
Vcontravariant [(pos, Rconstraint_as, Pcontravariant)]
| Ast_defs.Constraint_eq ->
let reasons = [(pos, Rconstraint_eq, Pinvariant)] in
Vinvariant (reasons, reasons)
| Ast_defs.Constraint_super ->
Vcovariant [(pos, Rconstraint_super, Pcovariant)]
in
hint env var h
let method_tparam : Env.t -> Nast.tparam -> Env.t =
fun env tparam ->
let {
Aast.tp_variance = _;
tp_name;
tp_parameters = (* TODO high-kinded generics? T69931993 *) _;
tp_constraints;
tp_reified = _;
tp_user_attributes = _;
} =
tparam
in
List.iter tp_constraints ~f:(tparam_constraint env);
let env = Env.remove_type_parameter env (Ast_defs.get_id tp_name) in
env
let class_property : Env.t -> Nast.class_var -> unit =
fun env prop ->
Option.iter (snd prop.Aast.cv_type) ~f:(fun h ->
if prop.Aast.cv_is_static then
(* Static properties should not be generic at all. This is checked in
* Typing_toplevel.check_no_generic_static_property on the class decl,
* Since we need properties imported from traits as well. *)
()
else
match prop.Aast.cv_visibility with
| Aast.Private -> ()
| Aast.Public
| Aast.Protected
| Aast.Internal ->
let variance =
make_variance Rproperty (Ast_defs.get_pos h) Ast_defs.Invariant
in
hint env variance h)
let class_method : Env.t -> Nast.class_ -> Nast.method_ -> unit =
fun env class_ method_ ->
let {
Aast.m_visibility;
m_final;
m_static;
m_tparams;
m_params;
m_readonly_this = _;
m_ret = (_, m_ret);
m_name = (_, m_name);
m_where_constraints;
m_ctxs = _;
m_unsafe_ctxs = _;
m_span = _;
m_annotation = _;
m_abstract = _;
m_body = _;
m_fun_kind = _;
m_user_attributes = _;
m_readonly_ret = _;
m_external = _;
m_doc_comment = _;
} =
method_
in
if String.equal m_name SN.Members.__construct then
()
else
match m_visibility with
| Aast.Private ->
(* Final methods can't be overridden, so it's ok to use covariant
and contravariant type parameters in any position in the type *)
()
| Aast.Public
| Aast.Protected
| Aast.Internal ->
if (class_.Aast.c_final || m_final) && m_static then
()
else
let env = List.fold m_tparams ~f:method_tparam ~init:env in
let variance = Vcovariant [] in
List.iter m_params ~f:(fun_param env variance);
Option.iter m_ret ~f:(fun_ret env variance);
List.iter m_where_constraints ~f:(fun_where_constraint env);
()
(*****************************************************************************)
(* The entry point (for classes). *)
(*****************************************************************************)
let props_from_constructors : Nast.method_ list -> Nast.class_var list =
fun methods ->
let constructors =
List.filter methods ~f:(fun m ->
Ast_defs.get_id m.Aast.m_name |> String.equal SN.Members.__construct)
in
List.map constructors ~f:(fun m ->
m.Aast.m_params
|> List.filter_map ~f:(fun param ->
let {
Aast.param_type_hint;
param_is_variadic;
param_pos;
param_name;
param_annotation = ();
param_expr;
param_readonly;
param_callconv = _;
param_user_attributes;
param_visibility;
} =
param
in
Option.(
param_visibility >>| fun cv_visibility ->
{
Aast.cv_final = false;
cv_xhp_attr = None;
cv_abstract = false;
cv_visibility;
cv_readonly = Option.is_some param_readonly;
cv_type = param_type_hint;
cv_id = (param_pos, param_name);
cv_expr = param_expr;
cv_user_attributes = param_user_attributes;
cv_doc_comment = None;
cv_is_promoted_variadic = param_is_variadic;
cv_is_static = false;
cv_span = param_pos;
})))
|> List.concat
let class_def : Typing_env_types.env -> Nast.class_ -> unit =
fun env class_ ->
let {
Aast.c_tparams;
c_extends;
c_uses;
c_implements;
c_vars;
c_methods;
c_final = _;
c_where_constraints = (* TODO *) _;
c_typeconsts = (* TODO *) _;
c_kind = _;
c_span = _;
c_annotation = _;
c_mode = _;
c_is_xhp = _;
c_has_xhp_keyword = _;
c_name = _;
c_xhp_attr_uses = _;
c_xhp_category = _;
c_reqs = _;
c_consts = _;
c_xhp_children = _;
c_xhp_attrs = _;
c_namespace = _;
c_user_attributes = _;
c_file_attributes = _;
c_module = _;
c_enum = _;
c_doc_comment = _;
c_emit_id = _;
c_internal = _;
c_docs_url = _;
} =
class_
in
let env =
{
Env.tpenv =
List.fold c_tparams ~init:SMap.empty ~f:(fun env tp ->
SMap.add (snd tp.Aast.tp_name) (get_declared_variance tp) env);
enclosing_class = Some class_;
env;
}
in
let parents = c_extends @ c_implements @ c_uses in
List.iter parents ~f:(hint env Vboth);
let c_vars = c_vars @ props_from_constructors c_methods in
List.iter c_vars ~f:(class_property env);
List.iter c_methods ~f:(class_method env class_);
()
(*****************************************************************************)
(* The entry point (for typedefs). *)
(*****************************************************************************)
let typedef : Typing_env_types.env -> Nast.typedef -> unit =
fun env typedef ->
let {
Aast.t_tparams;
t_kind;
t_annotation = _;
t_name = _;
t_as_constraint = _;
t_super_constraint = _;
t_user_attributes = _;
t_mode = _;
t_vis = _;
t_namespace = _;
t_span = _;
t_emit_id = _;
t_is_ctx = _;
t_file_attributes = _;
t_internal = _;
t_module = _;
t_docs_url = _;
t_doc_comment = _;
} =
typedef
in
let env =
{
Env.tpenv =
List.fold t_tparams ~init:SMap.empty ~f:(fun env tp ->
SMap.add (snd tp.Aast.tp_name) (get_declared_variance tp) env);
enclosing_class = None;
env;
}
in
let reason_covariant = [(Ast_defs.get_pos t_kind, Rtypedef, Pcovariant)] in
hint env (Vcovariant reason_covariant) t_kind |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_variance.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 a class definition for correct usage of variant generic parameters *)
val class_def : Typing_env_types.env -> Nast.class_ -> unit
(** Check a type definition for correct usage of variant generic parameters *)
val typedef : Typing_env_types.env -> Nast.typedef -> unit
(** Get (positive,negative) occurrences of generic parameters in a type.
* Only collect those present in tracked. If is_mutable is true, treat the
* type as invariant, i.e. all type parameters appear both positively and negatively.
*)
val get_positive_negative_generics :
tracked:SSet.t ->
is_mutable:bool ->
Typing_env_types.env ->
Typing_reason.decl_t list SMap.t * Typing_reason.decl_t list SMap.t ->
Typing_defs.decl_ty ->
Typing_reason.decl_t list SMap.t * Typing_reason.decl_t list SMap.t |
OCaml | hhvm/hphp/hack/src/typing/typing_visibility.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
open Utils
open Typing_error.Primary.Modules
module Env = Typing_env
module TUtils = Typing_utils
module Cls = Decl_provider.Class
(* Is a private member defined on class/trait [origin_id] visible
* from code in class/trait [self_id]?
*
* For almost all circumstances, this is just a case of checking
* that they are the same, *except* for the special case of
* where-constraints on the this type defined on a trait, for example:
*
* class C { private static function foo():void { } }
* trait TR where this = C {
* ...C::foo...
* }
*
* Using `require_class` also allows a trait to access the private
* method from the class it requires
*)
let is_private_visible ~is_static env origin_id self_id =
if String.equal origin_id self_id then
None
else
let in_bounds bounds =
List.exists bounds ~f:(fun t ->
match get_node t with
| Tapply ((_, name), _) -> String.equal origin_id name
| _ -> false)
in
match Env.get_class env self_id with
| Some cls when Ast_defs.is_c_trait (Cls.kind cls) ->
let bounds_from_require_class_constraints =
List.map (Cls.all_ancestor_req_class_requirements cls) ~f:snd
in
(* If the right class is required, give access *)
if (not is_static) && in_bounds bounds_from_require_class_constraints then
None
else
let upper = Cls.upper_bounds_on_this_from_constraints cls in
let lower = Cls.lower_bounds_on_this_from_constraints cls in
(* Otherwise check the where constraints on `this` (experimental) *)
if in_bounds upper && in_bounds lower then
None
else
Some "You cannot access this member"
| _ -> Some "You cannot access this member"
let is_protected_visible env origin_id self_id =
if TUtils.has_ancestor_including_req_refl env self_id origin_id then
None
else
match Env.get_class env origin_id with
| None -> None
| Some origin_class ->
(* Parents can call direct children's protected methods
* (like a constructor)
*)
if Cls.has_ancestor origin_class self_id then
None
else
Some
("Cannot access this protected member, you don't extend "
^ strip_ns origin_id)
let is_private_visible_for_class env x self_id cid class_ =
match cid with
| CIstatic ->
let my_class = Env.get_class env self_id in
(match my_class with
| Some cls when Cls.final cls -> None
| _ ->
Some
"Private members cannot be accessed with static:: since a child class may also have an identically named private member")
| CIparent -> Some "You cannot access a private member with parent::"
| CIself -> is_private_visible ~is_static:true env x self_id
| CI (_, called_ci) ->
(match is_private_visible ~is_static:true env x self_id with
| None -> None
| Some _ -> begin
match Env.get_class env called_ci with
| Some cls when Ast_defs.is_c_trait (Cls.kind cls) ->
Some
"You cannot access private members using the trait's name (did you mean to use self::?)"
| _ -> Some "You cannot access this member"
end)
| CIexpr _ ->
if Cls.final class_ then
None
else
Some
"Private members cannot be accessed dynamically. Did you mean to use 'self::'?"
let is_internal_visible env target =
match
Typing_modules.can_access_internal
~env
~current:(Env.get_current_module env)
~target:(Some target)
with
| `Yes -> None
| `Disjoint (current, target) ->
Some
(Printf.sprintf
"You cannot access internal members from module `%s` in module `%s`"
target
current)
| `Outside _ -> Some "You cannot access internal members outside of a module"
| `OutsideViaTrait _ ->
Some "You cannot access internal members inside a public trait"
let check_internal_access ~in_signature env target pos decl_pos =
let module_err_opt =
match
Typing_modules.can_access_internal
~env
~current:(Env.get_current_module env)
~target
with
| `Yes when in_signature && not (Env.get_internal env) ->
Some (Module_hint { pos; decl_pos })
| `Yes -> None
| `Disjoint (current, target) ->
Some
(Module_mismatch
{
pos;
decl_pos;
current_module_opt = Some current;
target_module = target;
})
| `Outside target ->
Some
(Module_mismatch
{ pos; decl_pos; current_module_opt = None; target_module = target })
| `OutsideViaTrait trait_pos ->
Some (Module_unsafe_trait_access { access_pos = pos; trait_pos })
in
Option.map ~f:Typing_error.modules module_err_opt
let check_public_access env use_pos def_pos target =
match
Typing_modules.can_access_public
~env
~current:(Env.get_current_module env)
~target
with
| `Yes -> None
| `ImportsNotSatisfied (module_name, module_pos) ->
Some
(Typing_error.modules
(Module_missing_import
{
pos = use_pos;
decl_pos = def_pos;
module_pos;
current_module = module_name;
target_module_opt = target;
}))
| `ExportsNotSatisfied (module_name, module_pos) ->
Some
(Typing_error.modules
(Module_missing_export
{
pos = use_pos;
decl_pos = def_pos;
module_pos;
current_module_opt = Env.get_current_module env;
target_module = module_name;
}))
| `PackageNotSatisfied (package_pos, module_pos) ->
let current_module = Env.get_current_module env in
Some
(Typing_error.modules
(Module_cross_pkg_access
{
pos = use_pos;
decl_pos = def_pos;
module_pos;
package_pos;
current_module_opt = current_module;
target_module_opt = target;
current_package_opt =
Option.bind current_module ~f:(fun md ->
Env.get_package_for_module env md
|> Option.map ~f:Package.get_package_name);
target_package_opt =
Option.bind target ~f:(fun md ->
Env.get_package_for_module env md
|> Option.map ~f:Package.get_package_name);
}))
| `PackageSoftIncludes (package_pos, module_pos) ->
let current_module = Env.get_current_module env in
Some
(Typing_error.modules
(Module_soft_included_access
{
pos = use_pos;
decl_pos = def_pos;
module_pos;
package_pos;
current_module_opt = current_module;
target_module_opt = target;
current_package_opt =
Option.bind current_module ~f:(fun md ->
Env.get_package_for_module env md
|> Option.map ~f:Package.get_package_name);
target_package_opt =
Option.bind target ~f:(fun md ->
Env.get_package_for_module env md
|> Option.map ~f:Package.get_package_name);
}))
let is_visible_for_obj ~is_method env vis =
let member_ty =
if is_method then
"method"
else
"property"
in
match vis with
| Vpublic -> None
| Vprivate x ->
(match Env.get_self_id env with
| None -> Some ("You cannot access this " ^ member_ty)
| Some self_id -> is_private_visible ~is_static:false env x self_id)
| Vprotected x ->
(match Env.get_self_id env with
| None -> Some ("You cannot access this " ^ member_ty)
| Some self_id -> is_protected_visible env x self_id)
| Vinternal m -> is_internal_visible env m
(* The only permitted way to access an LSB property is via
static::, ClassName::, or $class_name:: *)
let is_lsb_permitted cid =
match cid with
| CIself -> Some "__LSB properties cannot be accessed with self::"
| CIparent -> Some "__LSB properties cannot be accessed with parent::"
| _ -> None
(* LSB property accessibility is relative to the defining class *)
let is_lsb_accessible env vis =
match vis with
| Vpublic -> None
| Vprivate x ->
(match Env.get_self_id env with
| None -> Some "You cannot access this property"
| Some self_id -> is_private_visible ~is_static:false env x self_id)
| Vprotected x ->
(match Env.get_self_id env with
| None -> Some "You cannot access this property"
| Some self_id -> is_protected_visible env x self_id)
| Vinternal m -> is_internal_visible env m
let is_lsb_visible_for_class env vis cid =
match is_lsb_permitted cid with
| Some x -> Some x
| None -> is_lsb_accessible env vis
let is_visible_for_class ~is_method env (vis, lsb) cid cty =
if lsb then
is_lsb_visible_for_class env vis cid
else
let member_ty =
if is_method then
"method"
else
"property"
in
match vis with
| Vpublic -> None
| Vprivate x ->
(match Env.get_self_id env with
| None -> Some ("You cannot access this " ^ member_ty)
| Some self_id -> is_private_visible_for_class env x self_id cid cty)
| Vprotected x ->
(match Env.get_self_id env with
| None -> Some ("You cannot access this " ^ member_ty)
| Some self_id ->
let their_class = Env.get_class env x in
(match (cid, their_class) with
| (CI _, Some cls) when Ast_defs.is_c_trait (Cls.kind cls) ->
Some
"You cannot access protected members using the trait's name (did you mean to use static:: or self::?)"
| _ -> is_protected_visible env x self_id))
| Vinternal m -> is_internal_visible env m
let is_visible_for_top_level
~in_signature env is_internal target_module pos decl_pos =
if is_internal then
check_internal_access ~in_signature env target_module pos decl_pos
else
check_public_access env pos decl_pos target_module
let is_visible ~is_method env (vis, lsb) cid class_ =
let msg_opt =
match cid with
| Some cid -> is_visible_for_class ~is_method env (vis, lsb) cid class_
| None -> is_visible_for_obj ~is_method env vis
in
Option.is_none msg_opt
let visibility_error p msg (p_vis, vis) =
let s = Typing_defs.string_of_visibility vis in
let msg_vis = "This member is " ^ s in
Typing_error.(
primary
@@ Primary.Visibility
{ pos = p; msg; decl_pos = p_vis; reason_msg = msg_vis })
let check_obj_access ~is_method ~use_pos ~def_pos env vis =
Option.map (is_visible_for_obj ~is_method env vis) ~f:(fun msg ->
visibility_error use_pos msg (def_pos, vis))
let check_top_level_access
~in_signature ~use_pos ~def_pos env is_internal target_module =
is_visible_for_top_level
~in_signature
env
is_internal
target_module
use_pos
def_pos
let check_expression_tree_vis ~use_pos ~def_pos env vis =
let open Typing_error in
if Env.is_in_expr_tree env then
match vis with
| Vpublic -> None
| _ ->
Some
(expr_tree
@@ Primary.Expr_tree.Expression_tree_non_public_member
{ pos = use_pos; decl_pos = def_pos })
else
None
let check_inst_meth_access ~use_pos ~def_pos vis =
let open Typing_error in
match vis with
| Vprivate _ ->
Some
(primary
@@ Primary.Private_inst_meth { decl_pos = def_pos; pos = use_pos })
| Vprotected _ ->
Some
(primary
@@ Primary.Protected_inst_meth { decl_pos = def_pos; pos = use_pos })
| _ -> None
let check_meth_caller_access ~use_pos ~def_pos vis =
let open Typing_error in
match vis with
| Vprivate _ ->
Some
(primary
@@ Primary.Private_meth_caller { decl_pos = def_pos; pos = use_pos })
| Vprotected _ ->
Some
(primary
@@ Primary.Protected_meth_caller { decl_pos = def_pos; pos = use_pos })
| _ -> None
let check_class_access ~is_method ~use_pos ~def_pos env (vis, lsb) cid class_ =
Option.map
(is_visible_for_class ~is_method env (vis, lsb) cid class_)
~f:(fun msg -> visibility_error use_pos msg (def_pos, vis))
let check_cross_package ~use_pos ~def_pos env (cross_package : string option) =
match cross_package with
| Some target ->
let current_module = Env.get_current_module env in
let current_pkg =
Option.bind ~f:(Env.get_package_for_module env) current_module
in
let target_pkg = Env.get_package_by_name env target in
(match Typing_modules.satisfies_package_deps env current_pkg target_pkg with
| Some _ ->
Some
(Typing_error.modules
(Module_cross_pkg_call
{
pos = use_pos;
decl_pos = def_pos;
current_package_opt =
Option.map ~f:Package.get_package_name current_pkg;
target_package_opt = cross_package;
}))
| _ -> None)
| None -> None
let check_deprecated ~use_pos ~def_pos env deprecated =
if Tast.is_under_dynamic_assumptions env.Typing_env_types.checked then
None
else
Option.map deprecated ~f:(fun s ->
Typing_error.(
primary
@@ Primary.Deprecated_use
{ pos = use_pos; decl_pos_opt = Some def_pos; msg = s })) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_visibility.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
val check_class_access :
is_method:bool ->
use_pos:Pos.t ->
def_pos:Pos_or_decl.t ->
env ->
ce_visibility * bool ->
Nast.class_id_ ->
Decl_provider.class_decl ->
Typing_error.t option
val check_obj_access :
is_method:bool ->
use_pos:Pos.t ->
def_pos:Pos_or_decl.t ->
env ->
ce_visibility ->
Typing_error.t option
val check_top_level_access :
in_signature:bool ->
use_pos:Pos.t ->
def_pos:Pos_or_decl.t ->
env ->
bool ->
string option ->
Typing_error.t option
val check_inst_meth_access :
use_pos:Pos.t ->
def_pos:Pos_or_decl.t ->
ce_visibility ->
Typing_error.t option
val check_meth_caller_access :
use_pos:Pos.t ->
def_pos:Pos_or_decl.t ->
ce_visibility ->
Typing_error.t option
val check_deprecated :
use_pos:Pos.t ->
def_pos:Pos_or_decl.t ->
env ->
string option ->
Typing_error.t option
(* Expression Trees can only access publicly accessible properties *)
val check_expression_tree_vis :
use_pos:Pos.t ->
def_pos:Pos_or_decl.t ->
env ->
ce_visibility ->
Typing_error.t option
val is_visible :
is_method:bool ->
env ->
ce_visibility * bool ->
Nast.class_id_ option ->
Decl_provider.class_decl ->
bool
val check_cross_package :
use_pos:Pos.t ->
def_pos:Pos_or_decl.t ->
env ->
string option ->
Typing_error.t option |
OCaml | hhvm/hphp/hack/src/typing/typing_xhp.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 Common
open Typing_defs
module Env = Typing_env
module Phase = Typing_phase
module Reason = Typing_reason
module TUtils = Typing_utils
module MakeType = Typing_make_type
module Cls = Decl_provider.Class
module SN = Naming_special_names
let raise_xhp_required env pos ureason ty =
let ty_str = lazy (Typing_print.error env ty) in
let msgl =
Lazy.map ty_str ~f:(fun ty_str ->
Reason.to_string ("This is " ^ ty_str) (get_reason ty))
in
Typing_error.(
xhp
@@ Primary.Xhp.Xhp_required
{
pos;
why_xhp = Reason.string_of_ureason ureason;
ty_reason_msg = msgl;
})
(**
* Given class info, produces the subset of props that are XHP attributes
*)
let xhp_attributes_for_class info : (string * class_elt) list =
Cls.props info
|> List.filter ~f:(fun (_, elt_) -> Option.is_some (get_ce_xhp_attr elt_))
(**
* Walks a type and gathers all the XHP, adding an error when we encounter a
* type that is not XHP.
*)
let rec walk_and_gather_xhp_ ~env ~pos cty =
let ((env, ty_err_opt), cty) =
Typing_solver.expand_type_and_solve
~description_of_expected:"an XHP instance"
env
pos
cty
in
Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt;
match get_node cty with
| Tany _
| Tdynamic ->
(env, [], [])
| Tunion tyl ->
(* If it's a union, make sure it can only be XHP and add every
* possible class. *)
walk_list_and_gather_xhp env pos tyl
| Tintersection tyl ->
(* If any conjunct is dynamic then we let it pass *)
if List.exists tyl ~f:is_dynamic then
(env, [], [])
else
let (env, xhp, non_xhp) = walk_list_and_gather_xhp env pos tyl in
(* ok to have non_xhp if there are some xhp *)
let non_xhp =
match xhp with
| _ :: _ -> []
| _ -> non_xhp
in
(env, xhp, non_xhp)
| Tgeneric ("this", []) -> begin
(* This is unsound, but we want to do best-effort checking
* of attribute spreads even on XHP classes not marked `final`. We should
* implement <<__ConsistentAttributes>> as a way to make this hacky
* inference sound and check it before doing this conversion. *)
match Env.get_self_ty env with
| None -> (env, [], [])
| Some ty -> walk_and_gather_xhp_ ~env ~pos ty
end
| Tgeneric _
| Tdependent _
| Tnewtype _ ->
let (env, tyl) =
TUtils.get_concrete_supertypes ~abstract_enum:true env cty
in
walk_list_and_gather_xhp env pos tyl
| Tclass ((_, c), _, tyl) -> begin
(* Here's where we actually check the declaration *)
match Env.get_class env c with
| Some class_ when Cls.is_xhp class_ -> (env, [(cty, tyl, class_)], [])
| _ -> (env, [], [cty])
end
| Tnonnull
| Tvec_or_dict _
| Toption _
| Tprim _
| Tvar _
| Tfun _
| Ttuple _
| Tshape _
| Tneg _ ->
(env, [], [cty])
| Taccess _
| Tunapplied_alias _ ->
(env, [], [cty])
and walk_list_and_gather_xhp env pos tyl =
List.fold ~init:(env, [], []) tyl ~f:(fun (env, xhp_acc, non_xhp_acc) ty ->
let (env, xhp_acc', non_xhp_acc') = walk_and_gather_xhp_ ~env ~pos ty in
(env, xhp_acc' @ xhp_acc, non_xhp_acc' @ non_xhp_acc))
(**
* For a given type, enforce that we have an XHP class and return the complete
* list of possible attributes for typechecking the spread operator.
*)
and get_spread_attributes env pos onto_xhp cty =
let onto_attrs =
xhp_attributes_for_class onto_xhp
|> List.fold ~init:SSet.empty ~f:(fun acc (k, _) -> SSet.add k acc)
in
let (env, possible_xhp, non_xhp) = walk_and_gather_xhp_ ~env ~pos cty in
let xhp_required_err_opt =
Typing_error.multiple_opt
@@ List.map non_xhp ~f:(raise_xhp_required env pos Reason.URxhp_spread)
in
let xhp_to_attrs env (xhp_ty, tparams, xhp_info) =
let attrs = xhp_attributes_for_class xhp_info in
(* Compute the intersection and then localize the types *)
let attrs = List.filter attrs ~f:(fun (k, _) -> SSet.mem k onto_attrs) in
(* XHP does not allow generics in the class declaration, so
* we don't need to perform any substitutions *)
let ety_env =
{
empty_expand_env with
this_ty = xhp_ty;
substs = TUtils.make_locl_subst_for_class_tparams xhp_info tparams;
}
in
List.map_env_ty_err_opt
~combine_ty_errs:Typing_error.multiple_opt
~f:
begin
fun env (k, ce) ->
let (lazy ty) = ce.ce_type in
let (env, ty) = Phase.localize ~ety_env env ty in
(env, ((pos, k), (pos, ty)))
end
env
attrs
in
let ((env, locl_ty_err_opt), attrs) =
List.map_env_ty_err_opt
~f:xhp_to_attrs
env
possible_xhp
~combine_ty_errs:Typing_error.multiple_opt
in
let ty_err_opt =
Option.merge ~f:Typing_error.both xhp_required_err_opt locl_ty_err_opt
in
((env, ty_err_opt), List.concat attrs)
(**
* Typing rules for the body expressions of an XHP literal.
*)
let is_xhp_child env pos ty =
let r = Reason.Rwitness pos in
(* XHPChild *)
let ty_child = MakeType.class_type r SN.Classes.cXHPChild [] in
(* Any Traversable *)
let ty_traversable = MakeType.traversable r (MakeType.mixed r) in
Typing_solver.is_sub_type
env
ty
(MakeType.nullable
r
(MakeType.union r [MakeType.dynamic r; ty_child; ty_traversable]))
let rewrite_xml_into_new pos sid attributes children =
let cid = CI sid in
let mk_attribute ix = function
| Xhp_simple { xs_name = (attr_pos, attr_key); xs_expr = exp; _ } ->
let attr_aux = attr_pos in
let key = ((), attr_aux, Aast.String attr_key) in
(key, exp)
| Xhp_spread exp ->
let attr_key = Format.asprintf "...$%s" (string_of_int ix) in
let attr_key_ann = pos in
let key = ((), attr_key_ann, Aast.String attr_key) in
(key, exp)
in
let attributes =
let attributes = List.mapi ~f:mk_attribute attributes in
((), pos, Darray (None, attributes))
in
let children = ((), pos, Varray (None, children)) in
let file = ((), pos, Aast.String "") in
let line = ((), pos, Aast.Int "1") in
let args = [attributes; children; file; line] in
let sid_ann = fst sid in
((), sid_ann, New (((), sid_ann, cid), [], args, None, ()))
let rewrite_attribute_access_into_call pos exp nullflavor =
let obj_get_exp =
( (),
pos,
Aast.Obj_get
(exp, ((), pos, Id (pos, "getAttribute")), nullflavor, Is_method) )
in
( (),
pos,
Aast.Call
{
func = obj_get_exp;
targs = [];
args = [(Ast_defs.Pnormal, ((), pos, Aast.String ""))];
unpacked_arg = None;
} ) |
OCaml Interface | hhvm/hphp/hack/src/typing/typing_xhp.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.
*
*)
open Aast
open Typing_env_types
(**
* This is used in computing all possible attributes for XHP spreads.
*
* Given a type `cty` that should represent an XHP instance, gather all the
* XHP attributes and their localized types to verify compatibility with the
* XHP onto which we are spreading.
*)
val get_spread_attributes :
env ->
Pos.t ->
Decl_provider.class_decl ->
Typing_defs.locl_ty ->
(env * Typing_error.t option)
* (Aast.pstring * (Pos.t * Typing_defs.locl_ty)) list
(**
* Verify that an XHP body expression is legal.
*)
val is_xhp_child :
env -> Pos.t -> Typing_defs.locl_ty -> bool * Typing_error.t option
(* Rewrites an Xml node into a New node. The resulting New expression has
* four arguments. This mimics the rewrite undergone before the emitter is
* run.
*
* For example,
* `<p colour='blue'>Hi</p>;`
* becomes
* `new :p(darray['colour' => 'blue'], varray['Hi'],"",1);`
*
* The first two arguments are for the attributes and children. The last two
* arguments are for the filename and line number. These are irrelevant from a
* typing perspective, so they are set to arbitrary defaults.
*)
val rewrite_xml_into_new :
Pos.t -> sid -> Nast.xhp_attribute list -> Nast.expr list -> Nast.expr
(* Rewrites an Xml attribute access into a call to getAttribute. The
* resulting Call expression has one argument fake string argument to match the
* expected parameter of getAttribute.
*
* For example,
* `$xml->:attr;`
* becomes
* `$xml->getAttribute('');`
*
* The null flavor argument is indicates an expression of the form
* `$xml?->:attr`
*)
val rewrite_attribute_access_into_call :
Pos.t -> Nast.expr -> og_null_flavor -> Nast.expr |
OCaml | hhvm/hphp/hack/src/typing/xhp_attribute.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type tag =
| Required
| LateInit
[@@deriving eq, show { with_path = false }]
type t = {
xa_tag: tag option;
xa_has_default: bool;
}
[@@deriving eq, show { with_path = false }]
let init : t = { xa_tag = None; xa_has_default = false }
let map_tag attr ~f = { attr with xa_tag = f attr.xa_tag }
let is_required attr =
match attr.xa_tag with
| None
| Some LateInit ->
false
| Some Required -> true
let opt_is_required (attr : t option) : bool =
match attr with
| None -> false
| Some attr -> is_required attr |
OCaml Interface | hhvm/hphp/hack/src/typing/xhp_attribute.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type tag =
| Required
| LateInit
[@@deriving eq, show]
type t = {
xa_tag: tag option;
xa_has_default: bool;
}
[@@deriving eq, show]
val init : t
val map_tag : t -> f:(tag option -> tag option) -> t
val is_required : t -> bool
val opt_is_required : t option -> bool |
TOML | hhvm/hphp/hack/src/typing/cargo/hh_distc_types/Cargo.toml | # @generated by autocargo
[package]
name = "hh_distc_types_rs"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../hh_distc_types/lib.rs"
[dependencies]
eq_modulo_pos = { version = "0.0.0", path = "../../../utils/eq_modulo_pos" }
errors = { package = "errors_rs", version = "0.0.0", path = "../../../errors/cargo/errors" }
no_pos_hash = { version = "0.0.0", path = "../../../utils/no_pos_hash" }
ocamlrep = { version = "0.1.0", git = "https://github.com/facebook/ocamlrep/", branch = "main" }
serde = { version = "1.0.176", features = ["derive", "rc"] } |
OCaml | hhvm/hphp/hack/src/typing/env/deps.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module Cls = Decl_provider.Class
module Dep = Typing_deps.Dep
let get_current_decl env =
Option.map
env.Typing_env_types.decl_env.Decl_env.droot
~f:Dep.to_decl_reference
let add_fine_dep_if_enabled env dependency =
let open Option.Let_syntax in
let decl_env = env.Typing_env_types.decl_env in
let ctx = decl_env.Decl_env.ctx in
(* We resolve the dependency to its origin. See
* [Typing_extends.add_pessimisation_dependency] for details. *)
let dependency_on_origin () =
match dependency with
| Dep.Method (class_name, method_name) ->
let origin_name =
let* cls = Decl_provider.get_class ctx class_name in
let* elt = Cls.get_method cls method_name in
Some elt.Typing_defs.ce_origin
in
let origin_name = Option.value origin_name ~default:class_name in
Dep.Method (origin_name, method_name)
| Dep.SMethod (class_name, method_name) ->
let origin_name =
let* cls = Decl_provider.get_class ctx class_name in
let* elt = Cls.get_smethod cls method_name in
Some elt.Typing_defs.ce_origin
in
let origin_name = Option.value origin_name ~default:class_name in
Dep.SMethod (origin_name, method_name)
| _ -> dependency
in
if
TypecheckerOptions.record_fine_grained_dependencies
@@ Typing_env_types.(env.genv.tcopt)
then
let dependency = dependency_on_origin () in
Typing_pessimisation_deps.try_add_fine_dep
(Provider_context.get_deps_mode ctx)
decl_env.Decl_env.droot
decl_env.Decl_env.droot_member
dependency
let add_dependency_edge (env : Typing_env_types.env) dep : unit =
let decl_env = env.Typing_env_types.decl_env in
Option.iter decl_env.Decl_env.droot ~f:(fun root ->
let ctx = decl_env.Decl_env.ctx in
let deps_mode = Provider_context.get_deps_mode ctx in
Typing_deps.add_idep deps_mode root dep);
add_fine_dep_if_enabled env dep
let make_depend_on_gconst env name def =
match def with
| Some cst when Pos_or_decl.is_hhi cst.Typing_defs.cd_pos -> ()
| _ -> add_dependency_edge env (Dep.GConst name)
let make_depend_on_fun env name fd =
match fd with
| Some fd when Pos_or_decl.is_hhi fd.Typing_defs.fe_pos -> ()
| _ -> add_dependency_edge env (Dep.Fun name)
let make_depend_on_class_name env class_name =
add_dependency_edge env (Dep.Type class_name)
let make_depend_on_class env x cd =
match cd with
| Some cd when Pos_or_decl.is_hhi (Cls.pos cd) -> ()
| _ -> make_depend_on_class_name env x
let make_depend_on_constructor_name env class_name =
make_depend_on_class_name env class_name;
add_dependency_edge env (Dep.Constructor class_name);
()
let make_depend_on_constructor env class_ =
if not (Pos_or_decl.is_hhi (Cls.pos class_)) then (
make_depend_on_constructor_name env (Cls.name class_);
Option.iter
(fst (Cls.construct class_))
~f:(fun ce ->
make_depend_on_constructor_name env ce.Typing_defs.ce_origin)
)
let make_depend_on_module_name env module_name =
add_dependency_edge env (Dep.Module module_name)
let make_depend_on_module env name md =
match md with
| Some md when Pos_or_decl.is_hhi md.Typing_defs.mdt_pos -> ()
| _ -> make_depend_on_module_name env name
let make_depend_on_ancestors (env : Typing_env_types.env) (cls : Cls.t) : unit =
List.iter (Cls.all_ancestor_names cls) ~f:(fun ancestor ->
add_dependency_edge env (Dep.Type ancestor))
let make_depend_on_parent env ~skip_constructor_dep name class_ =
match class_ with
| Some cd when Pos_or_decl.is_hhi (Cls.pos cd) -> ()
| _ ->
if not skip_constructor_dep then make_depend_on_constructor_name env name;
add_dependency_edge env (Dep.Extends name)
let add_member_dep ~is_method ~is_static env (class_ : Cls.t) mid class_elt_opt
=
let add_dep cid =
let dep =
match (is_method, is_static) with
| (true, true) -> Dep.SMethod (cid, mid)
| (true, false) -> Dep.Method (cid, mid)
| (false, true) -> Dep.SProp (cid, mid)
| (false, false) -> Dep.Prop (cid, mid)
in
add_dependency_edge env dep
in
if not (Pos_or_decl.is_hhi (Cls.pos class_)) then (
make_depend_on_class_name env (Cls.name class_);
add_dep (Cls.name class_);
Option.iter class_elt_opt ~f:(fun ce -> add_dep ce.Typing_defs.ce_origin)
);
()
let make_depend_on_class_const env class_ name =
if not (Pos_or_decl.is_hhi (Cls.pos class_)) then (
make_depend_on_class_name env (Cls.name class_);
add_dependency_edge env (Dep.Const (Cls.name class_, name))
)
let make_depend_on_typedef env name td =
match td with
| Some td when Pos_or_decl.is_hhi td.Typing_defs.td_pos -> ()
| _ -> make_depend_on_class_name env name |
OCaml Interface | hhvm/hphp/hack/src/typing/env/deps.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val get_current_decl : Typing_env_types.env -> Decl_reference.t option
val make_depend_on_gconst :
Typing_env_types.env -> string -> Typing_defs.const_decl option -> unit
val make_depend_on_fun :
Typing_env_types.env -> string -> Typing_defs.fun_elt option -> unit
val make_depend_on_class :
Typing_env_types.env -> string -> Decl_provider.Class.t option -> unit
val make_depend_on_module :
Typing_env_types.env -> string -> Typing_defs.module_def_type option -> unit
val make_depend_on_module_name : Typing_env_types.env -> string -> unit
val make_depend_on_typedef :
Typing_env_types.env -> string -> Typing_defs.typedef_type option -> unit
val make_depend_on_constructor :
Typing_env_types.env -> Decl_provider.Class.t -> unit
val make_depend_on_class_const :
Typing_env_types.env -> Decl_provider.Class.t -> string -> unit
val add_member_dep :
is_method:bool ->
is_static:bool ->
Typing_env_types.env ->
Decl_provider.Class.t ->
string ->
Typing_defs.class_elt option ->
unit
(** Register the droot as being dependent on all of the ancestor classes,
interfaces, and traits of the given class (i.e., the recursive ancestors
returned by [Typing_classes_heap.Api.all_ancestor_names] and stored in
[Decl_defs.dc_ancestors]). Should be invoked once when typechecking the
given class (after [droot] has been set to correspond to the given class). *)
val make_depend_on_ancestors :
Typing_env_types.env -> Decl_provider.Class.t -> unit
val make_depend_on_parent :
Typing_env_types.env ->
skip_constructor_dep:bool ->
string ->
Decl_provider.Class.t option ->
unit |
hhvm/hphp/hack/src/typing/env/dune | (library
(name typing_env)
(libraries
decl_provider
provider_context
typing_env_types
typing_log
typing_pessimisation_deps)
(preprocess
(pps ppx_deriving.std))) |
|
OCaml | hhvm/hphp/hack/src/typing/env/typing_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 Common
open Decl_env
open Typing_env_types
open Typing_defs
open Aast
module Inf = Typing_inference_env
module LID = Local_id
module LEnvC = Typing_per_cont_env
module C = Typing_continuations
module Cls = Decl_provider.Class
module Fake = Typing_fake_members
module ITySet = Internal_type_set
module TPEnv = Type_parameter_env
module KDefs = Typing_kinding_defs
module TySet = Typing_set
type 'a class_or_typedef_result =
'a Decl_enforceability.class_or_typedef_result =
| ClassResult of 'a
| TypedefResult of Typing_defs.typedef_type
let show_env _ = "<env>"
let pp_env _ _ = Printf.printf "%s\n" "<env>"
let get_tcopt env = env.genv.tcopt
let map_tcopt env ~f =
let tcopt = f env.genv.tcopt in
let genv = { env.genv with tcopt } in
{ env with genv }
let get_deps_mode env = Provider_context.get_deps_mode env.decl_env.Decl_env.ctx
let get_ctx env = env.decl_env.Decl_env.ctx
let get_file env = env.genv.file
let get_current_decl_and_file env : Pos_or_decl.ctx =
{ Pos_or_decl.file = get_file env; decl = Deps.get_current_decl env }
let fill_in_pos_filename_if_in_current_decl env pos =
Pos_or_decl.fill_in_filename_if_in_current_decl
~current_decl_and_file:(get_current_decl_and_file env)
pos
let unify_error_assert_primary_pos_in_current_decl env =
Typing_error.Reasons_callback.unify_error_assert_primary_pos_in_current_decl
(get_current_decl_and_file env)
let invalid_type_hint_assert_primary_pos_in_current_decl env =
Typing_error.Reasons_callback
.invalid_type_hint_assert_primary_pos_in_current_decl
(get_current_decl_and_file env)
let get_tracing_info env = env.tracing_info
let set_log_level env key log_level =
{ env with log_levels = SMap.add key log_level env.log_levels }
let get_log_level = Typing_env_types.get_log_level
let log_env_change_ :
type res. string -> ?level:int -> env -> env * res -> env * res =
fun function_name ?(level = 1) old_env (new_env, res) ->
(if
get_log_level new_env function_name >= 1
|| get_log_level new_env "env" >= level
then
let pos =
Option.value
(Inf.get_current_pos_from_tyvar_stack old_env.inference_env)
~default:old_env.genv.callable_pos
in
Typing_log.log_env_diff pos ~function_name old_env new_env);
(new_env, res)
let log_env_change name ?(level = 1) old_env new_env =
let (env, ()) = log_env_change_ name ~level old_env (new_env, ()) in
env
let expand_var env r v =
let (inference_env, ty) = Inf.expand_var env.inference_env r v in
({ env with inference_env }, ty)
let fresh_type_reason ?variance env p r =
log_env_change_ "fresh_type_reason" env
@@
let (inference_env, res) =
Inf.fresh_type_reason ?variance env.inference_env p r
in
({ env with inference_env }, res)
let fresh_type env p =
log_env_change_ "fresh_type" env
@@
let (inference_env, res) = Inf.fresh_type env.inference_env p in
({ env with inference_env }, res)
let fresh_type_invariant env p =
log_env_change_ "fresh_type_invariant" env
@@
let (inference_env, res) = Inf.fresh_type_invariant env.inference_env p in
({ env with inference_env }, res)
let fresh_type_error env p =
log_env_change_ "fresh_type_error" env
@@
let (inference_env, res) =
Inf.fresh_type_reason
~variance:Ast_defs.Invariant
env.inference_env
p
(Reason.Rtype_variable_error p)
in
({ env with inference_env }, res)
let fresh_type_error_contravariant env p =
log_env_change_ "fresh_type_error_contravariant" env
@@
let (inference_env, res) =
Inf.fresh_type_reason
~variance:Ast_defs.Contravariant
env.inference_env
p
(Reason.Rtype_variable_error p)
in
({ env with inference_env }, res)
let add_subtype_prop env prop =
log_env_change "add_subtype_prop" env
@@ { env with inference_env = Inf.add_subtype_prop env.inference_env prop }
let empty_bounds = TySet.empty
let tyvar_is_solved env var = Inf.tyvar_is_solved env.inference_env var
let make_tyvar_no_more_occur_in_tyvar env v ~no_more_in:v' =
{
env with
inference_env =
Inf.make_tyvar_no_more_occur_in_tyvar env.inference_env v ~no_more_in:v';
}
let not_implemented s _ =
failwith (Printf.sprintf "Function %s not implemented" s)
type simplify_unions = env -> locl_ty -> env * locl_ty
let (simplify_unions_ref : simplify_unions ref) =
ref (not_implemented "simplify_unions")
let simplify_unions x = !simplify_unions_ref x
let bind env v ty = { env with inference_env = Inf.bind env.inference_env v ty }
(** Unions and intersections containing unsolved type variables may remain
in an unsimplified form once those type variables get solved.
For example, consider the union (#1 | int) where #1 is an unsolved type variable.
If #1 gets solved to int, then this union will remain in the unsimplified form
(int | int) which compromise the robustness of some of our logic and might
cause performance issues (by creating big unsimplified unions).
To solve this problem, we wrap each union and intersection in a type var,
so we'd get `#2 -> (#1 | int)` (This is done in Typing_union and
Typing_intersection), and register that #1 occurs in #2 in
[env.tyvar_occurrences]. Then when #1 gets solved, we simplify #2.
This function deals with this simplification.
The simplification is recursive: simplifying a type variable will
trigger simplification of its own occurrences. *)
let simplify_occurrences env v =
let rec simplify_occurrences env v ~seen_tyvars =
let vars = Inf.get_tyvar_occurrences env.inference_env v in
let (env, seen_tyvars) =
ISet.fold
(fun v' (env, seen_tyvars) ->
(* This type variable is now solved and does not contain any unsolved
type variable, so we can remove it from its occurrences. *)
let env = make_tyvar_no_more_occur_in_tyvar env v ~no_more_in:v' in
(* Only simplify when the type of v' does not contain any more
unsolved type variables. *)
if not @@ Inf.contains_unsolved_tyvars env.inference_env v' then
simplify_type_of_var env v' ~seen_tyvars
else
(env, seen_tyvars))
vars
(env, seen_tyvars)
in
(env, seen_tyvars)
and simplify_type_of_var env v ~seen_tyvars =
if ISet.mem v seen_tyvars then
(* TODO raise exception. *)
(env, seen_tyvars)
else
let seen_tyvars = ISet.add v seen_tyvars in
match Inf.get_direct_binding env.inference_env v with
| None -> failwith "Can only simplify type of bounded variables"
| Some ty ->
(* Only simplify the type of variables which are bound directly to a
concrete type to preserve the variable aliasings and save some memory. *)
let env =
match get_node ty with
| Tvar _ -> env
| _ ->
let (env, ty) = simplify_unions env ty in
(* we only call this function when v does not recursively contain unsolved
type variables, so ty here should not contain unsolved type variables and
it is safe to simply bind it without reupdating the type var occurrences. *)
let env = bind env v ty in
env
in
simplify_occurrences env v ~seen_tyvars
in
if not @@ Inf.contains_unsolved_tyvars env.inference_env v then
fst @@ simplify_occurrences env v ~seen_tyvars:ISet.empty
else
env
let add env ?(tyvar_pos = Pos.none) v ty =
let env =
{ env with inference_env = Inf.add env.inference_env ~tyvar_pos v ty }
in
let env = simplify_occurrences env v in
env
let get_type env r var =
let (inference_env, res) = Inf.get_type env.inference_env r var in
({ env with inference_env }, res)
let expand_type env ty =
let (inference_env, res) = Inf.expand_type env.inference_env ty in
({ env with inference_env }, res)
let expand_internal_type env ty =
let (inference_env, res) = Inf.expand_internal_type env.inference_env ty in
({ env with inference_env }, res)
let get_tyvar_pos env var = Inf.get_tyvar_pos env.inference_env var
let get_tyvar_lower_bounds env var =
Inf.get_tyvar_lower_bounds env.inference_env var
let set_tyvar_lower_bounds env var tys =
{
env with
inference_env = Inf.set_tyvar_lower_bounds env.inference_env var tys;
}
let get_tyvar_upper_bounds env var =
Inf.get_tyvar_upper_bounds env.inference_env var
let set_tyvar_upper_bounds env var tys =
{
env with
inference_env = Inf.set_tyvar_upper_bounds env.inference_env var tys;
}
let get_tyvar_appears_covariantly env var =
Inf.get_tyvar_appears_covariantly env.inference_env var
let set_tyvar_appears_covariantly env var =
{
env with
inference_env = Inf.set_tyvar_appears_covariantly env.inference_env var;
}
let get_tyvar_appears_contravariantly env var =
Inf.get_tyvar_appears_contravariantly env.inference_env var
let set_tyvar_appears_contravariantly env var =
{
env with
inference_env = Inf.set_tyvar_appears_contravariantly env.inference_env var;
}
let get_tyvar_appears_invariantly env var =
Inf.get_tyvar_appears_invariantly env.inference_env var
let get_tyvar_eager_solve_fail env var =
Inf.get_tyvar_eager_solve_fail env.inference_env var
let set_tyvar_eager_solve_fail env var =
{
env with
inference_env = Inf.set_tyvar_eager_solve_fail env.inference_env var;
}
let get_tyvar_type_consts env var =
Inf.get_tyvar_type_consts env.inference_env var
let get_tyvar_type_const env var tid =
Inf.get_tyvar_type_const env.inference_env var tid
let set_tyvar_type_const env var tconstid ty =
{
env with
inference_env = Inf.set_tyvar_type_const env.inference_env var tconstid ty;
}
let get_current_tyvars env = Inf.get_current_tyvars env.inference_env
let open_tyvars env p =
{ env with inference_env = Inf.open_tyvars env.inference_env p }
let close_tyvars env =
{ env with inference_env = Inf.close_tyvars env.inference_env }
let wrap_ty_in_var env r ty =
let (inference_env, res) = Inf.wrap_ty_in_var env.inference_env r ty in
({ env with inference_env }, res)
let next_cont_opt = Typing_env_types.next_cont_opt
let all_continuations env = LEnvC.all_continuations env.lenv.per_cont_env
let get_tpenv = Typing_env_types.get_tpenv
let get_global_tpenv env = env.tpenv
let get_pos_and_kind_of_generic = Typing_env_types.get_pos_and_kind_of_generic
let get_lower_bounds = Typing_env_types.get_lower_bounds
let get_upper_bounds = Typing_env_types.get_upper_bounds
(* Get bounds that are both an upper and lower of a given generic *)
let get_equal_bounds = Typing_env_types.get_equal_bounds
let get_reified env name =
let tpenv = get_tpenv env in
let local = TPEnv.get_reified tpenv name in
let global = TPEnv.get_reified env.tpenv name in
match (local, global) with
| (Reified, _)
| (_, Reified) ->
Reified
| (SoftReified, _)
| (_, SoftReified) ->
SoftReified
| _ -> Erased
let get_enforceable env name =
let tpenv = get_tpenv env in
let local = TPEnv.get_enforceable tpenv name in
let global = TPEnv.get_enforceable env.tpenv name in
local || global
let get_newable env name =
let tpenv = get_tpenv env in
let local = TPEnv.get_newable tpenv name in
let global = TPEnv.get_newable env.tpenv name in
local || global
let get_require_dynamic env name =
let tpenv = get_tpenv env in
let local = TPEnv.get_require_dynamic tpenv name in
let global = TPEnv.get_require_dynamic env.tpenv name in
local || global
let env_with_tpenv env tpenv =
{
env with
lenv =
{
env.lenv with
per_cont_env =
LEnvC.(
update_cont_entry C.Next env.lenv.per_cont_env (fun entry ->
{ entry with tpenv }));
};
}
let env_with_global_tpenv env tpenv = { env with tpenv }
let add_upper_bound_global env name ty =
let tpenv =
let (env, ty) = expand_type env ty in
match deref ty with
| (r, Tgeneric (formal_super, [])) ->
TPEnv.add_lower_bound env.tpenv formal_super (mk (r, Tgeneric (name, [])))
| (_r, Tgeneric (_formal_super, _targs)) ->
(* TODO(T70068435) Revisit this when implementing bounds on HK generic vars *)
env.tpenv
| _ -> env.tpenv
in
{ env with tpenv = TPEnv.add_upper_bound tpenv name ty }
let add_lower_bound_global env name ty =
let tpenv =
let (env, ty) = expand_type env ty in
match deref ty with
| (r, Tgeneric (formal_super, [])) ->
TPEnv.add_upper_bound env.tpenv formal_super (mk (r, Tgeneric (name, [])))
| (_r, Tgeneric (_formal_super, _targs)) ->
(* TODO(T70068435) Revisit this when implementing bounds on HK generic vars *)
env.tpenv
| _ -> env.tpenv
in
{ env with tpenv = TPEnv.add_lower_bound tpenv name ty }
(* Add a single new upper bound [ty] to generic parameter [name] in the local
* type parameter environment of [env].
* 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
* (T <: t1) /\ ... /\ (T <: tn)
* is equivalent to a single upper bound
* T <: (t1 & ... & tn)
*)
let add_upper_bound ?intersect env name ty =
env_with_tpenv env (TPEnv.add_upper_bound ?intersect (get_tpenv env) name ty)
(* Add a single new upper lower [ty] to generic parameter [name] in the
* local type parameter environment [env].
* 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 <: T) /\ ... /\ (tn <: T)
* is equivalent to a single lower bound
* (t1 | ... | tn) <: T
*)
let add_lower_bound ?union env name ty =
env_with_tpenv env (TPEnv.add_lower_bound ?union (get_tpenv env) name ty)
(* Add type parameters to environment, initially with no bounds.
* Existing type parameters with the same name will be overridden. *)
let add_generic_parameters env tparaml =
env_with_tpenv env (TPEnv.add_generic_parameters (get_tpenv env) tparaml)
let is_generic_parameter env name =
TPEnv.mem name (get_tpenv env) || SSet.mem name env.fresh_typarams
let get_generic_parameters env =
TPEnv.get_tparam_names (TPEnv.union (get_tpenv env) env.tpenv)
let get_tpenv_size env = TPEnv.size (get_tpenv env) + TPEnv.size env.tpenv
let is_consistent env = TPEnv.is_consistent (get_tpenv env)
let mark_inconsistent env =
env_with_tpenv env (TPEnv.mark_inconsistent (get_tpenv env))
let fresh_param_name env prefix : env * string =
let rec iterate i =
let name = Printf.sprintf "%s#%d" prefix i in
if is_generic_parameter env name then
iterate (i + 1)
else
name
in
let name = iterate 1 in
let env = { env with fresh_typarams = SSet.add name env.fresh_typarams } in
(env, name)
(* Generate a fresh generic parameter with a specified prefix but distinct
* from all generic parameters in the environment *)
let add_fresh_generic_parameter_by_kind env pos prefix kind =
let (env, name) = fresh_param_name env prefix in
let env =
env_with_tpenv env (TPEnv.add ~def_pos:pos name kind (get_tpenv env))
in
(env, name)
let add_fresh_generic_parameter env pos prefix ~reified ~enforceable ~newable =
let kind =
KDefs.
{
lower_bounds = empty_bounds;
upper_bounds = empty_bounds;
reified;
enforceable;
newable;
require_dynamic = true;
parameters = [];
}
in
add_fresh_generic_parameter_by_kind env pos prefix kind
let is_fresh_generic_parameter name =
String.contains name '#' && not (DependentKind.is_generic_dep_ty name)
let get_tparams_in_ty_and_acc = Typing_env_types.get_tparams_in_ty_and_acc
let get_tparams env ty = get_tparams_in_ty_and_acc env SSet.empty ty
let get_tpenv_tparams env =
TPEnv.fold
begin
fun _x
KDefs.
{
lower_bounds;
upper_bounds;
reified = _;
enforceable = _;
newable = _;
require_dynamic = _;
(* FIXME what to do here? it seems dangerous to just traverse *)
parameters = _;
}
acc ->
let folder ty acc =
let (_env, ty) = expand_type env ty in
match get_node ty with
| Tgeneric _ -> acc
| _ -> get_tparams_in_ty_and_acc env acc ty
in
TySet.fold folder lower_bounds @@ TySet.fold folder upper_bounds acc
end
(get_tpenv env)
SSet.empty
(* Replace types for locals with empty environment *)
let env_with_locals env locals =
{ env with lenv = { env.lenv with per_cont_env = locals } }
(* This is used whenever we start checking a method. Retain tpenv from the class type parameters *)
let reinitialize_locals env =
env_with_locals
env
LEnvC.(initial_locals { empty_entry with tpenv = get_tpenv env })
let set_env_callable_pos env callable_pos =
{ env with genv = { env.genv with callable_pos } }
let set_fun_tast_info env fun_tast_info =
{ env with fun_tast_info = Some fun_tast_info }
let set_condition_type env n ty =
{
env with
genv =
{ env.genv with condition_types = SMap.add n ty env.genv.condition_types };
}
let get_condition_type env n = SMap.find_opt n env.genv.condition_types
let fun_is_constructor env = env.genv.fun_is_ctor
let set_fun_is_constructor env is_ctor =
{ env with genv = { env.genv with fun_is_ctor = is_ctor } }
let env_with_method_droot_member env m ~static =
let child =
if static then
Typing_pessimisation_deps.SMethod m
else
Typing_pessimisation_deps.Method m
in
let decl_env = { env.decl_env with droot_member = Some child } in
{ env with decl_env }
let env_with_constructor_droot_member env =
let member = Typing_pessimisation_deps.Constructor in
let decl_env = { env.decl_env with droot_member = Some member } in
{ env with decl_env }
let get_module (env : env) (name : Decl_provider.module_key) :
module_def_type option =
let res =
Decl_provider.get_module
?tracing_info:(get_tracing_info env)
(get_ctx env)
name
in
Deps.make_depend_on_module env name res;
res
let set_current_module env m =
{ env with genv = { env.genv with current_module = m } }
let get_current_module env = Option.map env.genv.current_module ~f:snd
let make_depend_on_current_module env =
Option.iter
Typing_env_types.(env.genv.current_module)
~f:(fun (_, mid) -> Deps.make_depend_on_module_name env mid)
let make_depend_on_ancestors = Deps.make_depend_on_ancestors
let set_internal env b = { env with genv = { env.genv with this_internal = b } }
let get_internal env = env.genv.this_internal
let get_package_for_module env md =
let info = get_tcopt env |> TypecheckerOptions.package_info in
PackageInfo.get_package_for_module info md
let get_package_by_name env pkg_name =
let info = get_tcopt env |> TypecheckerOptions.package_info in
PackageInfo.get_package info pkg_name
let is_package_loaded env package = SSet.mem package env.loaded_packages
let load_packages env packages =
{ env with loaded_packages = SSet.union env.loaded_packages packages }
let load_cross_packages_from_attr env attr =
match
Naming_attributes.find
Naming_special_names.UserAttributes.uaCrossPackage
attr
with
| Some attr ->
let pkgs_to_load =
List.fold
~init:SSet.empty
~f:
(fun acc -> function
| (_, _, Aast.String pkg) -> SSet.add pkg acc
| _ -> acc)
attr.ua_params
in
load_packages env pkgs_to_load
| _ -> env
let with_packages env packages f =
let old_loaded_packages = env.loaded_packages in
let env = load_packages env packages in
let (env, result) = f env in
let env = { env with loaded_packages = old_loaded_packages } in
(env, result)
let get_typedef env x =
let td =
Decl_provider.get_typedef
?tracing_info:(get_tracing_info env)
(get_ctx env)
x
in
Deps.make_depend_on_typedef env x td;
td
let is_typedef env x =
match Naming_provider.get_type_kind (get_ctx env) x with
| Some Naming_types.TTypedef -> true
| _ -> false
let is_typedef_visible env ?(expand_visible_newtype = true) ~name td =
let { Typing_defs.td_vis; td_module; _ } = td in
match td_vis with
| Aast.Opaque ->
expand_visible_newtype
&&
let td_path = Naming_provider.get_typedef_path (get_ctx env) name in
(match td_path with
| Some s -> Relative_path.equal s (get_file env)
| None -> (* Not the right place to raise an error *) false)
| Aast.OpaqueModule ->
expand_visible_newtype
&& Option.equal
String.equal
(get_current_module env)
(Option.map td_module ~f:snd)
| Aast.Transparent -> true
| Aast.CaseType -> false
let get_class (env : env) (name : Decl_provider.type_key) : Cls.t option =
let res =
Decl_provider.get_class
?tracing_info:(get_tracing_info env)
(get_ctx env)
name
in
Deps.make_depend_on_class env name res;
res
let get_parent env ~skip_constructor_dep name : Cls.t option =
let res = get_class env name in
Deps.make_depend_on_parent env ~skip_constructor_dep name res;
res
let add_parent_dep env ~skip_constructor_dep name : unit =
let _ = get_parent env ~skip_constructor_dep name in
()
let get_class_or_typedef env x =
if is_typedef env x then
match get_typedef env x with
| None -> None
| Some td -> Some (TypedefResult td)
else
match get_class env x with
| None -> None
| Some cd -> Some (ClassResult cd)
let get_fun env x =
let res =
Decl_provider.get_fun ?tracing_info:(get_tracing_info env) (get_ctx env) x
in
Deps.make_depend_on_fun env x res;
res
let get_enum_constraint env x =
match get_class env x with
| None -> None
| Some tc ->
(match Cls.enum_type tc with
| None -> None
| Some e -> e.te_constraint)
(* TODO: do we want to introduce a Cls.enum_class_type ? *)
let get_enum env x =
match get_class env x with
| Some tc when Option.is_some (Cls.enum_type tc) -> Some tc
| _ -> None
let is_enum env x =
match get_enum env x with
| Some cls -> Ast_defs.is_c_enum (Cls.kind cls)
| None -> false
let is_enum_class env x =
match get_enum env x with
| Some cls -> Ast_defs.is_c_enum_class (Cls.kind cls)
| None -> false
let get_typeconst env class_ mid =
Deps.make_depend_on_class_const env class_ mid;
Cls.get_typeconst class_ mid
(* Used to access class constants. *)
let get_const env class_ mid =
Deps.make_depend_on_class_const env class_ mid;
Cls.get_const class_ mid
let consts env class_ =
Deps.make_depend_on_class env (Cls.name class_) (Some class_);
Cls.consts class_
(* Used to access "global constants". That is constants that were
* introduced with "const X = ...;" at topelevel, or "define('X', ...);"
*)
let get_gconst env cst_name =
let res =
Decl_provider.get_gconst
?tracing_info:(get_tracing_info env)
(get_ctx env)
cst_name
in
Deps.make_depend_on_gconst env cst_name res;
res
let get_static_member is_method env class_ mid =
(* The type of a member is stored separately in the heap. This means that
* any user of the member also has a dependency on the class where the member
* originated.
*)
let ce_opt =
if is_method then
Cls.get_smethod class_ mid
else
Cls.get_sprop class_ mid
in
Deps.add_member_dep ~is_method ~is_static:true env class_ mid ce_opt;
ce_opt
(* Given a list of [possibilities] whose name we can extract with [f], return
the item whose name is closest to [name]. *)
let most_similar (name : string) (possibilities : 'a list) (f : 'a -> string) :
'a option =
(* Compare strings case-insensitively. *)
let name = String.lowercase name in
let f x = String.lowercase (f x) in
let distance upper_bound = String_utils.levenshtein_distance ~upper_bound in
let choose_closest ~best:(best, best_distance) candidate =
let candidate_distance = distance (best_distance + 1) (f candidate) name in
if best_distance <= candidate_distance then
(best, best_distance)
else
(candidate, candidate_distance)
in
match possibilities with
| [] -> None
| [x] -> Some x
| x :: xs ->
(* The initial distance upper bound here is chosen practically. It reduces
the amount of work we do while computing the Levenshtein distance, but
does not regress any of the suggestions in the test suite. *)
let init = (x, distance 10 (f x) name) in
Some
(fst
@@ List.fold xs ~init ~f:(fun (current_best, best_distance) possibility ->
let (new_best, new_best_distance) =
choose_closest ~best:(current_best, best_distance) possibility
in
(new_best, new_best_distance)))
let suggest_member members mid =
let pairs =
List.map members ~f:(fun (x, { ce_type = (lazy ty); _ }) -> (get_pos ty, x))
in
most_similar mid pairs snd
let suggest_static_member is_method class_ mid =
let mid = String.lowercase mid in
let members =
if is_method then
Cls.smethods class_
else
Cls.sprops class_
in
suggest_member members mid
let get_member is_method env (class_ : Cls.t) mid =
(* The type of a member is stored separately in the heap. This means that
* any user of the member also has a dependency on the class where the member
* originated.
*)
let ce_opt =
if is_method then
Cls.get_method class_ mid
else
Cls.get_prop class_ mid
in
Deps.add_member_dep ~is_method ~is_static:false env class_ mid ce_opt;
ce_opt
let suggest_member is_method class_ mid =
let mid = String.lowercase mid in
let members =
if is_method then
Cls.methods class_
else
Cls.props class_
in
suggest_member members mid
let get_construct env class_ =
Deps.make_depend_on_constructor env class_;
Cls.construct class_
let get_return env = env.genv.return
let set_return env x =
let genv = env.genv in
let genv = { genv with return = x } in
{ env with genv }
let get_readonly env = env.genv.readonly
let set_readonly env x =
let genv = env.genv in
let genv = { genv with readonly = x } in
{ env with genv }
let get_params env = env.genv.params
let set_params env params = { env with genv = { env.genv with params } }
let set_param env x param =
let params = get_params env in
let params = LID.Map.add x param params in
set_params env params
let clear_params env = set_params env LID.Map.empty
let with_env env f =
let ret = get_return env in
let params = get_params env in
let (env, result) = f env in
let env = set_params env params in
let env = set_return env ret in
(env, result)
let with_origin env origin f =
let ti1 = env.tracing_info in
let ti2 = Option.map ti1 ~f:(fun ti -> { ti with Decl_counters.origin }) in
let env = { env with tracing_info = ti2 } in
let (env, result) = f env in
let env = { env with tracing_info = ti1 } in
(env, result)
let with_origin2 env origin f =
let ti1 = env.tracing_info in
let ti2 = Option.map ti1 ~f:(fun ti -> { ti with Decl_counters.origin }) in
let env = { env with tracing_info = ti2 } in
let (env, r1, r2) = f env in
let env = { env with tracing_info = ti1 } in
(env, r1, r2)
let inside_expr_tree env expr_tree_hint =
let outer_locals =
match next_cont_opt env with
| None -> LID.Map.empty
| Some cont -> cont.LEnvC.local_types
in
{ env with in_expr_tree = Some { dsl = expr_tree_hint; outer_locals } }
let outside_expr_tree env = { env with in_expr_tree = None }
let with_inside_expr_tree env expr_tree_hint f =
let old_in_expr_tree = env.in_expr_tree in
let env = inside_expr_tree env expr_tree_hint in
let (env, r1, r2) = f env in
let env = { env with in_expr_tree = old_in_expr_tree } in
(env, r1, r2)
let with_outside_expr_tree env f =
let old_in_expr_tree = env.in_expr_tree in
let dsl =
match old_in_expr_tree with
| Some { dsl = (_, Happly (cls, _)); outer_locals = _ } -> Some cls
| _ -> None
in
let env = outside_expr_tree env in
let (env, r1, r2) = f env dsl in
let env = { env with in_expr_tree = old_in_expr_tree } in
(env, r1, r2)
let is_in_expr_tree env = Option.is_some env.in_expr_tree
let is_static env = env.genv.static
let get_val_kind env = env.genv.val_kind
let get_self_ty env = Option.map env.genv.self ~f:snd
let get_self_class_type env =
match get_self_ty env with
| Some self -> begin
match get_node self with
| Tclass (id, exact, tys) -> Some (id, exact, tys)
| _ -> None
end
| None -> None
let get_self_id env = Option.map env.genv.self ~f:fst
let get_self_class env =
let open Option in
get_self_id env >>= get_class env
let get_parent_ty env = Option.map env.genv.parent ~f:snd
let get_parent_id env = Option.map env.genv.parent ~f:fst
let get_parent_class env =
let open Option in
get_parent_id env >>= get_class env
let get_fn_kind env = env.genv.fun_kind
let set_fn_kind env fn_type =
let genv = env.genv in
let genv = { genv with fun_kind = fn_type } in
{ env with genv }
let set_support_dynamic_type env b =
{ env with genv = { env.genv with this_support_dynamic_type = b } }
let set_no_auto_likes env b =
{ env with genv = { env.genv with no_auto_likes = b } }
let set_everything_sdt env b =
map_tcopt
~f:(fun tcopt -> { tcopt with GlobalOptions.tco_everything_sdt = b })
env
let get_support_dynamic_type env = env.genv.this_support_dynamic_type
let get_no_auto_likes env = env.genv.no_auto_likes
let set_self env self_id self_ty =
let genv = env.genv in
let genv = { genv with self = Some (self_id, self_ty) } in
{ env with genv }
let run_with_no_self env f =
let self = env.genv.self in
let genv = { env.genv with self = None } in
let (env, result) = f { env with genv } in
let genv = { env.genv with self } in
({ env with genv }, result)
let set_parent env parent_id parent_ty =
let genv = env.genv in
let genv = { genv with parent = Some (parent_id, parent_ty) } in
{ env with genv }
let set_static env =
let genv = env.genv in
let genv = { genv with static = true } in
{ env with genv }
let set_val_kind env x =
let genv = env.genv in
let genv = { genv with val_kind = x } in
{ env with genv }
let set_mode env mode =
let decl_env = env.decl_env in
let decl_env = { decl_env with mode } in
{ env with decl_env }
let get_mode env = env.decl_env.mode
let is_strict env = FileInfo.is_strict (get_mode env)
let is_hhi env = FileInfo.is_hhi (get_mode env)
(*****************************************************************************)
(* Locals *)
(*****************************************************************************)
let set_local_ env x ty =
let per_cont_env = LEnvC.add_to_cont C.Next x ty env.lenv.per_cont_env in
{ env with lenv = { env.lenv with per_cont_env } }
(* We maintain 2 states for a local: the type
* that the local currently has, and an expression_id generated from
* the last assignment to this local.
*)
let set_local ?(immutable = false) ~is_defined ~bound_ty env x new_type pos =
let new_type =
match get_node new_type with
| Tunion [ty] -> ty
| _ -> new_type
in
match next_cont_opt env with
| None -> env
| Some next_cont ->
let expr_id =
match LID.Map.find_opt x next_cont.LEnvC.local_types with
| None -> Ident.tmp ()
| Some local -> local.Typing_local_types.eid
in
let expr_id =
if immutable then
Ident.make_immutable expr_id
else
expr_id
in
let local =
Typing_local_types.
{ ty = new_type; defined = is_defined; bound_ty; pos; eid = expr_id }
in
set_local_ env x local
let is_using_var env x = LID.Set.mem x env.lenv.local_using_vars
let set_using_var env x =
{
env with
lenv =
{
env.lenv with
local_using_vars = LID.Set.add x env.lenv.local_using_vars;
};
}
let unset_local env local =
let { per_cont_env; local_using_vars } = env.lenv in
let per_cont_env =
LEnvC.remove_from_cont C.Next local
@@ LEnvC.remove_from_cont C.Catch local
@@ per_cont_env
in
let local_using_vars = LID.Set.remove local local_using_vars in
let env = { env with lenv = { per_cont_env; local_using_vars } } in
env
let tany _env = Typing_defs.make_tany ()
let local_undefined_error ~env p x ctx =
let open Option.Let_syntax in
(* When inside an expression tree, the user may forget to splice in a
variable. If that happens we want to suggest splicing in that
variable. *)
let all_outer_locals () =
Option.value ~default:[]
@@ let* { outer_locals; dsl } = env.in_expr_tree in
let locals =
LID.Map.fold
(fun k v acc ->
(* $this doesn't have a position. In general best to avoid
suggestions that lack positions. *)
if
LID.is_user_denotable k
&& (not @@ Pos.equal v.Typing_local_types.pos Pos.none)
then
(k, v, Some dsl) :: acc
else
acc)
outer_locals
[]
in
return locals
in
match p with
| Some p ->
let lid = LID.to_string x in
let suggest_most_similar lid =
(* Ignore fake locals *)
let all_locals =
LID.Map.fold
(fun k v acc ->
if LID.is_user_denotable k && v.Typing_local_types.defined then
(k, v, None) :: acc
else
acc)
ctx.LEnvC.local_types
(* Prefer suggesting variables within the current scope *)
(all_outer_locals ())
in
let var_name (k, _, _) = LID.to_string k in
match most_similar lid all_locals var_name with
| Some (k, local, dsl) ->
(Some (LID.to_string k, local.Typing_local_types.pos), dsl)
| None -> (None, None)
in
let (most_similar, in_dsl) = suggest_most_similar lid in
let error =
match in_dsl with
| None ->
Naming_error.Undefined
{ pos = p; var_name = lid; did_you_mean = most_similar }
| Some dsl ->
let dsl =
match dsl with
| (_, Happly ((_, cls), _)) -> Some cls
| _ -> None
in
Naming_error.Undefined_in_expr_tree
{ pos = p; var_name = lid; dsl; did_you_mean = most_similar }
in
Errors.add_error (Naming_error.to_user_error error)
| None -> ()
let get_local_in_ctx ~undefined_err_fun x ctx_opt =
let not_found_is_ok x ctx = Fake.is_valid ctx.LEnvC.fake_members x in
match ctx_opt with
| None ->
(* If the continuation is absent, we are in dead code so the variable should
have type nothing. *)
Some
Typing_local_types.
{
ty = Typing_make_type.nothing Reason.Rnone;
defined = false;
bound_ty = None;
pos = Pos.none;
eid = 0;
}
| Some ctx ->
let lcl = LID.Map.find_opt x ctx.LEnvC.local_types in
let error () =
if not_found_is_ok x ctx then
()
else
undefined_err_fun x ctx
in
begin
match lcl with
| None -> error ()
| Some local ->
if local.Typing_local_types.defined then
()
else
error ()
end;
lcl
let get_local_ty_in_ctx ~undefined_err_fun x ctx_opt =
match get_local_in_ctx ~undefined_err_fun x ctx_opt with
| None ->
( false,
Typing_local_types.
{
ty = Typing_make_type.nothing Reason.Rnone;
defined = false;
bound_ty = None;
pos = Pos.none;
eid = 0;
} )
| Some local ->
let open Typing_local_types in
let ty =
if local.defined then
local.ty
else
Typing_make_type.nothing Reason.Rnone
in
(true, { local with ty })
let get_local_in_next_continuation ?error_if_undef_at_pos:p env x =
let undefined_err_fun = local_undefined_error ~env p in
let next_cont = next_cont_opt env in
get_local_ty_in_ctx ~undefined_err_fun x next_cont
let get_local_ ?error_if_undef_at_pos:p env x =
get_local_in_next_continuation ?error_if_undef_at_pos:p env x
let get_local env x = snd (get_local_ env x)
let get_locals ?(quiet = false) env plids =
let next_cont = next_cont_opt env in
List.fold plids ~init:LID.Map.empty ~f:(fun locals (_, (p, lid)) ->
let error_if_undef_at_pos =
if quiet then
None
else
Some p
in
let undefined_err_fun =
local_undefined_error ~env error_if_undef_at_pos
in
match get_local_in_ctx ~undefined_err_fun lid next_cont with
| None -> locals
| Some ty_eid -> LID.Map.add lid ty_eid locals)
let set_locals env locals =
LID.Map.fold (fun lid ty env -> set_local_ env lid ty) locals env
(* If the local is present in the local environment. It might be defined, or
it might have a bound (or both). *)
let is_local_present env x =
let next_cont = next_cont_opt env in
Option.is_some next_cont && fst (get_local_ env x)
let get_local_check_defined env (p, x) =
snd (get_local_ ~error_if_undef_at_pos:p env x)
let set_local_expr_id env x new_eid =
let per_cont_env = env.lenv.per_cont_env in
match LEnvC.get_cont_option C.Next per_cont_env with
| None -> Ok env
| Some next_cont -> begin
let open Typing_local_types in
match LID.Map.find_opt x next_cont.LEnvC.local_types with
| Some Typing_local_types.{ ty; defined; bound_ty; pos; eid }
when not (equal_expression_id eid new_eid) ->
let local = { ty; defined; bound_ty; pos; eid = new_eid } in
let per_cont_env = LEnvC.add_to_cont C.Next x local per_cont_env in
let env = { env with lenv = { env.lenv with per_cont_env } } in
if Ident.is_immutable eid then
Error (env, Typing_error.(primary @@ Primary.Immutable_local pos))
else
Ok env
| _ -> Ok env
end
let get_local_expr_id env x =
match next_cont_opt env with
| None -> (* dead code *) None
| Some next_cont ->
let lcl = LID.Map.find_opt x next_cont.LEnvC.local_types in
Option.map lcl ~f:(fun x -> x.Typing_local_types.eid)
let set_fake_members env fake_members =
let per_cont_env =
LEnvC.update_cont_entry C.Next env.lenv.per_cont_env (fun entry ->
{ entry with LEnvC.fake_members })
in
{ env with lenv = { env.lenv with per_cont_env } }
let get_fake_members env =
match LEnvC.get_cont_option C.Next env.lenv.per_cont_env with
| None -> Fake.empty
| Some next_cont -> next_cont.LEnvC.fake_members
let update_lost_info name blame env ty =
let info r = Reason.Rlost_info (name, r, blame) in
let rec update_ty (env, seen_tyvars) ty =
let (env, ty) = expand_type env ty in
match deref ty with
| (_, Tvar v) ->
if ISet.mem v seen_tyvars then
((env, seen_tyvars), ty)
else
let seen_tyvars = ISet.add v seen_tyvars in
let bs = get_tyvar_lower_bounds env v in
let ((env, seen_tyvars), bs) =
ITySet.fold_map bs ~init:(env, seen_tyvars) ~f:update_ty_i
in
let env = set_tyvar_lower_bounds env v bs in
let bs = get_tyvar_upper_bounds env v in
let ((env, seen_tyvars), bs) =
ITySet.fold_map bs ~init:(env, seen_tyvars) ~f:update_ty_i
in
let env = set_tyvar_upper_bounds env v bs in
((env, seen_tyvars), ty)
| (r, Toption ty) ->
let ((env, seen_tyvars), ty) = update_ty (env, seen_tyvars) ty in
((env, seen_tyvars), mk (info r, Toption ty))
| (r, Tunion tyl) ->
let ((env, seen_tyvars), tyl) =
List.fold_map tyl ~init:(env, seen_tyvars) ~f:update_ty
in
((env, seen_tyvars), mk (info r, Tunion tyl))
| _ -> ((env, seen_tyvars), map_reason ty ~f:info)
and update_ty_i (env, seen_tyvars) ty =
match ty with
| LoclType ty ->
let ((env, seen_tyvars), ty) = update_ty (env, seen_tyvars) ty in
((env, seen_tyvars), LoclType ty)
| ConstraintType ty ->
let (r, ty) = deref_constraint_type ty in
((env, seen_tyvars), ConstraintType (mk_constraint_type (info r, ty)))
in
let ((env, _seen_tyvars), ty) = update_ty (env, ISet.empty) ty in
(env, ty)
let forget_generic forget env blame =
let fake_members = get_fake_members env in
let fake_members = forget fake_members blame in
set_fake_members env fake_members
let forget_members = forget_generic Fake.forget
let forget_prefixed_members env lid =
forget_generic (fun fake_members -> Fake.forget_prefixed fake_members lid) env
let forget_suffixed_members env suffix =
forget_generic
(fun fake_members -> Fake.forget_suffixed fake_members suffix)
env
module FakeMembers = struct
let update_fake_members env fake_members =
let per_cont_env =
LEnvC.update_cont_entry C.Next env.lenv.per_cont_env (fun entry ->
LEnvC.{ entry with fake_members })
in
{ env with lenv = { env.lenv with per_cont_env } }
let is_valid env obj member_name =
match obj with
| (_, _, This)
| (_, _, Lvar _) ->
let fake_members = get_fake_members env in
let id = Fake.make_id obj member_name in
Fake.is_valid fake_members id
| _ -> false
let is_valid_static env cid member_name =
let name = Fake.make_static_id cid member_name in
let fake_members = get_fake_members env in
Fake.is_valid fake_members name
let check_static_invalid env cid member_name ty =
let fake_members = get_fake_members env in
let fake_id = Fake.make_static_id cid member_name in
match Fake.is_invalid fake_members fake_id with
| None -> (env, ty)
| Some blame -> update_lost_info (LID.to_string fake_id) blame env ty
let check_instance_invalid env obj member_name ty =
match obj with
| (_, _, This)
| (_, _, Lvar _) ->
let fake_members = get_fake_members env in
let fake_id = Fake.make_id obj member_name in
begin
match Fake.is_invalid fake_members fake_id with
| None -> (env, ty)
| Some blame -> update_lost_info (LID.to_string fake_id) blame env ty
end
| _ -> (env, ty)
let add_member env fake_id pos =
let fake_members = get_fake_members env in
let fake_members = Fake.add fake_members fake_id pos in
set_fake_members env fake_members
let make env obj_name member_name pos =
let my_fake_local_id = Fake.make_id obj_name member_name in
let env = add_member env my_fake_local_id pos in
(env, my_fake_local_id)
let make_static env class_name member_name pos =
let my_fake_local_id = Fake.make_static_id class_name member_name in
let env = add_member env my_fake_local_id pos in
(env, my_fake_local_id)
end
(*****************************************************************************)
(* Sets up/cleans up the environment when typing anonymous function / lambda *)
(*****************************************************************************)
let closure env f =
(* Remember parts of the environment specific to the enclosing function
that will be overwritten when typing a lambda *)
let old_lenv = env.lenv in
let old_return = get_return env in
let old_params = get_params env in
let outer_fun_kind = get_fn_kind env in
let outer_check_status = env.checked in
(* Typing *)
let (env, ret) = f env in
(* Restore the environment fields that were clobbered *)
let env = { env with lenv = old_lenv } in
let env = set_params env old_params in
let env = set_return env old_return in
let env = set_fn_kind env outer_fun_kind in
let env = { env with checked = outer_check_status } in
(env, ret)
let in_try env f =
let old_in_try = env.in_try in
let env = { env with in_try = true } in
let (env, result) = f env in
({ env with in_try = old_in_try }, result)
(* Return the subset of env which is saved in the Typed AST's EnvAnnotation. *)
let save local_tpenv env =
{
Tast.tcopt = get_tcopt env;
Tast.inference_env = env.inference_env;
Tast.tpenv = TPEnv.union local_tpenv env.tpenv;
Tast.condition_types = env.genv.condition_types;
Tast.fun_tast_info = env.fun_tast_info;
Tast.checked = env.checked;
}
(* Compute the type variables appearing covariantly (positively)
* resp. contravariantly (negatively) in a given type ty.
* Return a pair of sets of positive and negative type variables
* (as well as an updated environment).
*)
let rec get_tyvars env (ty : locl_ty) = get_tyvars_i env (LoclType ty)
and get_tyvars_i env (ty : internal_type) =
let get_tyvars_union (env, acc_positive, acc_negative) ty =
let (env, positive, negative) = get_tyvars env ty in
(env, ISet.union acc_positive positive, ISet.union acc_negative negative)
in
let get_tyvars_param (env, acc_positive, acc_negative) fp =
let (env, positive, negative) = get_tyvars env fp.fp_type.et_type in
match get_fp_mode fp with
(* Parameters are treated contravariantly *)
| FPnormal ->
(env, ISet.union negative acc_positive, ISet.union positive acc_negative)
(* Inout parameters are both co- and contra-variant *)
| FPinout ->
let tyvars = ISet.union negative positive in
(env, ISet.union tyvars acc_positive, ISet.union tyvars acc_negative)
in
let (env, ety) = expand_internal_type env ty in
match ety with
| LoclType ety ->
(match get_node ety with
| Tvar v -> (env, ISet.singleton v, ISet.empty)
| Tany _
| Tnonnull
| Tdynamic
| Tprim _
| Tneg _ ->
(env, ISet.empty, ISet.empty)
| Toption ty -> get_tyvars env ty
| Ttuple tyl
| Tunion tyl
| Tintersection tyl ->
List.fold_left tyl ~init:(env, ISet.empty, ISet.empty) ~f:get_tyvars_union
| Tshape { s_fields = m; _ } ->
TShapeMap.fold
(fun _ { sft_ty; _ } res -> get_tyvars_union res sft_ty)
m
(env, ISet.empty, ISet.empty)
| Tfun ft ->
let (env, params_positive, params_negative) =
List.fold_left
ft.ft_params
~init:(env, ISet.empty, ISet.empty)
~f:get_tyvars_param
in
let (env, implicit_params_positive, implicit_params_negative) =
match ft.ft_implicit_params.capability with
| CapDefaults _ -> (env, ISet.empty, ISet.empty)
| CapTy ty -> get_tyvars env ty
in
let (env, ret_positive, ret_negative) =
get_tyvars env ft.ft_ret.et_type
in
( env,
ISet.union
implicit_params_positive
(ISet.union ret_positive params_positive),
ISet.union
implicit_params_negative
(ISet.union ret_negative params_negative) )
| Tnewtype (name, tyl, _) ->
if List.is_empty tyl then
(env, ISet.empty, ISet.empty)
else begin
match get_typedef env name with
| Some { td_tparams; _ } ->
let variancel = List.map td_tparams ~f:(fun t -> t.tp_variance) in
get_tyvars_variance_list (env, ISet.empty, ISet.empty) variancel tyl
| None -> (env, ISet.empty, ISet.empty)
end
| Tdependent (_, ty) -> get_tyvars env ty
| Tgeneric (_, tyl) ->
(* TODO(T69931993) Once implementing variance support for HK types, query
tyvar env here for list of variances *)
let variancel =
List.replicate ~num:(List.length tyl) Ast_defs.Invariant
in
get_tyvars_variance_list (env, ISet.empty, ISet.empty) variancel tyl
| Tclass ((_, cid), _, tyl) ->
if List.is_empty tyl then
(env, ISet.empty, ISet.empty)
else begin
match get_class env cid with
| Some cls ->
let variancel =
List.map (Cls.tparams cls) ~f:(fun t -> t.tp_variance)
in
get_tyvars_variance_list (env, ISet.empty, ISet.empty) variancel tyl
| None -> (env, ISet.empty, ISet.empty)
end
| Tvec_or_dict (ty1, ty2) ->
let (env, positive1, negative1) = get_tyvars env ty1 in
let (env, positive2, negative2) = get_tyvars env ty2 in
(env, ISet.union positive1 positive2, ISet.union negative1 negative2)
| Tunapplied_alias _ -> (env, ISet.empty, ISet.empty)
| Taccess (ty, _ids) -> get_tyvars env ty)
| ConstraintType ty ->
(match deref_constraint_type ty with
| (_, Tdestructure { d_required; d_optional; d_variadic; d_kind = _ }) ->
let (env, positive1, negative1) =
List.fold_left
d_required
~init:(env, ISet.empty, ISet.empty)
~f:get_tyvars_union
in
let (env, positive2, negative2) =
List.fold_left
d_optional
~init:(env, ISet.empty, ISet.empty)
~f:get_tyvars_union
in
let (env, positive3, negative3) =
match d_variadic with
| Some ty -> get_tyvars env ty
| None -> (env, ISet.empty, ISet.empty)
in
( env,
ISet.union (ISet.union positive1 positive2) positive3,
ISet.union (ISet.union negative1 negative2) negative3 )
| (_, Thas_member hm) ->
let { hm_type; hm_name = _; hm_class_id = _; hm_explicit_targs = _ } =
hm
in
get_tyvars env hm_type
| (_, Thas_type_member htm) ->
let { htm_id = _; htm_lower; htm_upper } = htm in
let (env, poslo, neglo) = get_tyvars env htm_lower in
let (env, posup, negup) = get_tyvars env htm_upper in
(env, ISet.union posup neglo, ISet.union poslo negup)
| (_, Tcan_index ci) ->
let (env, pos1, neg1) = get_tyvars env ci.ci_val in
let (env, pos2, neg2) = get_tyvars env ci.ci_key in
(env, ISet.union pos1 pos2, ISet.union neg1 neg2)
| (_, Tcan_traverse ct) ->
let (env, pos1, neg1) = get_tyvars env ct.ct_val in
let (env, pos2, neg2) =
match ct.ct_key with
| None -> (env, ISet.empty, ISet.empty)
| Some ct_key -> get_tyvars env ct_key
in
(env, ISet.union pos1 pos2, ISet.union neg1 neg2)
| (_, TCunion (lty, cty))
| (_, TCintersection (lty, cty)) ->
let (env, positive1, negative1) = get_tyvars env lty in
let (env, positive2, negative2) = get_tyvars_i env (ConstraintType cty) in
(env, ISet.union positive1 positive2, ISet.union negative1 negative2))
and get_tyvars_variance_list (env, acc_positive, acc_negative) variancel tyl =
match (variancel, tyl) with
| (variance :: variancel, ty :: tyl) ->
let (env, positive, negative) = get_tyvars env ty in
let (acc_positive, acc_negative) =
match variance with
| Ast_defs.Covariant ->
(ISet.union acc_positive positive, ISet.union acc_negative negative)
| Ast_defs.Contravariant ->
(ISet.union acc_positive negative, ISet.union acc_negative positive)
| Ast_defs.Invariant ->
let positive_or_negative = ISet.union positive negative in
( ISet.union acc_positive positive_or_negative,
ISet.union acc_negative positive_or_negative )
in
get_tyvars_variance_list (env, acc_positive, acc_negative) variancel tyl
| _ -> (env, acc_positive, acc_negative)
let rec set_tyvar_appears_covariantly_and_propagate env var =
if get_tyvar_appears_covariantly env var then
env
else
let env = set_tyvar_appears_covariantly env var in
let lower_bounds = get_tyvar_lower_bounds env var in
update_variance_of_tyvars_occurring_in_lower_bounds env lower_bounds
and set_tyvar_appears_contravariantly_and_propagate env var =
if get_tyvar_appears_contravariantly env var then
env
else
let env = set_tyvar_appears_contravariantly env var in
let upper_bounds = get_tyvar_upper_bounds env var in
update_variance_of_tyvars_occurring_in_upper_bounds env upper_bounds
and update_variance_of_tyvars_occurring_in_lower_bounds env tys =
ITySet.fold
(fun ty env -> update_variance_of_tyvars_occurring_in_lower_bound env ty)
tys
env
and update_variance_of_tyvars_occurring_in_upper_bounds env tys =
ITySet.fold
(fun ty env -> update_variance_of_tyvars_occurring_in_upper_bound env ty)
tys
env
and update_variance_of_tyvars_occurring_in_lower_bound env ty =
let (env, ety) = expand_internal_type env ty in
match ety with
| LoclType ty when is_tyvar ty -> env
| _ ->
let (env, positive, negative) = get_tyvars_i env ty in
let env =
ISet.fold
(fun var env -> set_tyvar_appears_covariantly env var)
positive
env
in
let env =
ISet.fold
(fun var env -> set_tyvar_appears_contravariantly env var)
negative
env
in
env
and update_variance_of_tyvars_occurring_in_upper_bound env ty =
let (env, ety) = expand_internal_type env ty in
match ety with
| LoclType ty when is_tyvar ty -> env
| _ ->
let (env, positive, negative) = get_tyvars_i env ty in
let env =
ISet.fold
(fun var env -> set_tyvar_appears_contravariantly env var)
positive
env
in
let env =
ISet.fold
(fun var env -> set_tyvar_appears_covariantly env var)
negative
env
in
env
let set_tyvar_appears_covariantly = set_tyvar_appears_covariantly_and_propagate
let set_tyvar_appears_contravariantly =
set_tyvar_appears_contravariantly_and_propagate
(* After a type variable var has been "solved", or bound to a type ty, we need
* to update the variance of type variables occurring in ty. Suppose that
* variable var is marked "appears covariantly", i.e. it appears (at least) in
* positive positions in the type of an expression. Then when we substitute ty
* for var, variables that appear positively in ty must now be marked as
* appearing covariantly; variables that appear negatively in ty must now be
* marked as appearing contravariantly. And the dual, if the variable var is marked
* "appears contravariantly".
*)
let update_variance_after_bind env var ty =
let appears_contravariantly = get_tyvar_appears_contravariantly env var in
let appears_covariantly = get_tyvar_appears_covariantly env var in
let (env, positive, negative) = get_tyvars env ty in
let env =
ISet.fold
(fun var env ->
let env =
if appears_contravariantly then
set_tyvar_appears_contravariantly env var
else
env
in
if appears_covariantly then
set_tyvar_appears_covariantly env var
else
env)
positive
env
in
let env =
ISet.fold
(fun var env ->
let env =
if appears_contravariantly then
set_tyvar_appears_covariantly env var
else
env
in
if appears_covariantly then
set_tyvar_appears_contravariantly env var
else
env)
negative
env
in
env
let set_tyvar_variance_i env ?(flip = false) ?(for_all_vars = false) ty =
log_env_change "set_tyvar_variance" env
@@
let current = get_current_tyvars env in
if (not for_all_vars) && List.is_empty current then
env
else
let (env, positive, negative) = get_tyvars_i env ty in
let (positive, negative) =
if flip then
(negative, positive)
else
(positive, negative)
in
let tyvars =
if for_all_vars then
ISet.union positive negative |> ISet.elements
else
current
in
List.fold_left tyvars ~init:env ~f:(fun env var ->
let env =
if ISet.mem var positive then
set_tyvar_appears_covariantly env var
else
env
in
let env =
if ISet.mem var negative then
set_tyvar_appears_contravariantly env var
else
env
in
env)
let set_tyvar_variance env ?(flip = false) ?(for_all_vars = false) ty =
set_tyvar_variance_i env ~flip ~for_all_vars (LoclType ty)
let add_tyvar_upper_bound ?intersect env var (ty : internal_type) =
log_env_change "add_tyvar_upper_bound" env
@@ {
env with
inference_env =
Inf.add_tyvar_upper_bound ?intersect env.inference_env var ty;
}
(* Add a single new upper bound [ty] to type variable [var] in [env.inference_env].
* 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_and_update_variances
?intersect env var (ty : internal_type) =
log_env_change "add_tyvar_upper_bound" env
@@
let env = add_tyvar_upper_bound ?intersect env var ty in
if get_tyvar_appears_contravariantly env var then
update_variance_of_tyvars_occurring_in_upper_bound env ty
else
env
(* Remove type variable `upper_var` from the upper bounds on `var`, if it exists
*)
let remove_tyvar_upper_bound env var upper_var =
log_env_change "remove_tyvar_upper_bound" env
@@ {
env with
inference_env =
Inf.remove_tyvar_upper_bound env.inference_env var upper_var;
}
(* Remove type variable `lower_var` from the lower bounds on `var`, if it exists
*)
let remove_tyvar_lower_bound env var lower_var =
log_env_change "remove_tyvar_lower_bound var" env
@@ {
env with
inference_env =
Inf.remove_tyvar_lower_bound env.inference_env var lower_var;
}
let add_tyvar_lower_bound ?union env var ty =
log_env_change "add_tyvar_lower_bound" env
@@ {
env with
inference_env = Inf.add_tyvar_lower_bound ?union env.inference_env var ty;
}
(* 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_and_update_variances ?union env var ty =
log_env_change "add_tyvar_lower_bound" env
@@
let env = add_tyvar_lower_bound ?union env var ty in
if get_tyvar_appears_covariantly env var then
update_variance_of_tyvars_occurring_in_lower_bound env ty
else
env
let get_all_tyvars env = Inf.get_vars env.inference_env
let remove_var env var ~search_in_upper_bounds_of ~search_in_lower_bounds_of =
log_env_change "remove_var" env
@@ {
env with
inference_env =
Inf.remove_var
env.inference_env
var
~search_in_upper_bounds_of
~search_in_lower_bounds_of;
}
let unsolve env v = { env with inference_env = Inf.unsolve env.inference_env v }
module Log = struct
(** Convert a type variable from an environment into json *)
let tyvar_to_json
(p_locl_ty : locl_ty -> string)
(p_internal_type : internal_type -> string)
(env : env)
(v : Ident.t) =
Inf.Log.tyvar_to_json p_locl_ty p_internal_type env.inference_env v
end |
OCaml Interface | hhvm/hphp/hack/src/typing/env/typing_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.
*
*)
open Typing_env_types
open Decl_provider
open Typing_defs
module Cls = Decl_provider.Class
module TPEnv = Type_parameter_env
type 'a class_or_typedef_result =
'a Decl_enforceability.class_or_typedef_result =
| ClassResult of 'a
| TypedefResult of Typing_defs.typedef_type
val simplify_unions_ref : (env -> locl_ty -> env * locl_ty) ref
val show_env : env -> string
val pp_env : Format.formatter -> env -> unit
val get_tcopt : env -> TypecheckerOptions.t
val map_tcopt : env -> f:(TypecheckerOptions.t -> TypecheckerOptions.t) -> env
val get_deps_mode : env -> Typing_deps_mode.t
val get_ctx : env -> Provider_context.t
val get_tracing_info : env -> Decl_counters.tracing_info option
(** Functions related to type variable scopes *)
(**
Open a new "type variable" scope and record this in the environment.
Within this scope, you can
- generate fresh type variables, using [fresh_type_X] functions
- query the currently fresh type variables, using [get_current_tyvars]
- close the scope
The usual usage pattern within type inference is:
1. Open a type variable scope using [open_tyvars] before checking an AST node.
2. Check the AST node; generate fresh type variables as necessary; make calls
to subtyping functions such as [Typing_ops.sub_type] that will record constraints
on those type variables.
3. Call [set_tyvar_variance] on the type of the expression to correctly set the
variance of the type variables.
4. Call [Typing_solver.close_tyvars_and_solve] to solve type variables that can
be solved immediately, and close the type variable scope.
*)
val open_tyvars : env -> Pos.t -> env
(** Generate a fresh type variable type with variance not yet recorded *)
val fresh_type : env -> Pos.t -> env * locl_ty
(** Generate a fresh type variable type with optional variance and
the given reason information *)
val fresh_type_reason :
?variance:Ast_defs.variance -> env -> Pos.t -> Reason.t -> env * locl_ty
(** Generate a fresh type variable type that is assumed to be invariant, so
it won't be solved automatically at the end of the scope *)
val fresh_type_invariant : env -> Pos.t -> env * locl_ty
(** Generate a fresh type variable to stand for an unknown type in the
case of type errors. *)
val fresh_type_error : env -> Pos.t -> env * locl_ty
val fresh_type_error_contravariant : env -> Pos.t -> env * locl_ty
(** What type variables are fresh in the current scope? *)
val get_current_tyvars : env -> Ident.t list
(** Close the current type variable scope.
You might want to call [Typing_solver.close_tyvars_and_solve] instead. *)
val close_tyvars : env -> env
val add : env -> ?tyvar_pos:Pos.t -> int -> locl_ty -> env
val make_tyvar_no_more_occur_in_tyvar : env -> int -> no_more_in:int -> env
val tyvar_is_solved : env -> int -> bool
val wrap_ty_in_var :
env -> Reason.t -> locl_ty -> Typing_env_types.env * locl_ty
val get_type : env -> Reason.t -> int -> env * locl_ty
val expand_var : env -> Reason.t -> Ident.t -> env * locl_ty
val expand_type : env -> locl_ty -> env * locl_ty
val expand_internal_type : env -> internal_type -> env * internal_type
val is_typedef : env -> type_key -> bool
val is_typedef_visible :
env -> ?expand_visible_newtype:bool -> name:string -> typedef_type -> bool
val get_enum : env -> type_key -> class_decl option
val is_enum : env -> type_key -> bool
val is_enum_class : env -> type_key -> bool
val get_enum_constraint : env -> type_key -> decl_ty option
val env_with_method_droot_member : env -> string -> static:bool -> env
val env_with_constructor_droot_member : env -> env
(** Get class declaration from the appropriate backend and add dependency. *)
val get_class : env -> type_key -> class_decl option
val add_parent_dep : env -> skip_constructor_dep:bool -> string -> unit
(** Get function declaration from the appropriate backend and add dependency. *)
val get_fun : env -> Decl_provider.fun_key -> Decl_provider.fun_decl option
(** Get type alias declaration from the appropriate backend and add dependency. *)
val get_typedef : env -> type_key -> typedef_decl option
val get_class_or_typedef :
env -> type_key -> Typing_classes_heap.Api.t class_or_typedef_result option
(** Get class constant declaration from the appropriate backend and add dependency. *)
val get_const : env -> class_decl -> string -> class_const option
(** Get class constants declaration from the appropriate backend and add dependency. *)
val consts : env -> class_decl -> (string * class_const) list
(** Get type constant declaration from the appropriate backend and add dependency. *)
val get_typeconst : env -> class_decl -> string -> typeconst_type option
(** Get global constant declaration from the appropriate backend and add dependency. *)
val get_gconst : env -> gconst_key -> gconst_decl option
(** Get static member declaration of a class from the appropriate backend and add dependency. *)
val get_static_member : bool -> env -> class_decl -> string -> class_elt option
val most_similar : string -> 'a list -> ('a -> string) -> 'a option
val suggest_static_member :
bool -> class_decl -> string -> (Pos_or_decl.t * string) option
(** Get class member declaration from the appropriate backend and add dependency. *)
val get_member : bool -> env -> class_decl -> string -> class_elt option
val suggest_member :
bool -> class_decl -> string -> (Pos_or_decl.t * string) option
(** Get class constructor declaration from the appropriate backend and add dependency. *)
val get_construct : env -> class_decl -> class_elt option * consistent_kind
val get_return : env -> Typing_env_return_info.t
val set_return : env -> Typing_env_return_info.t -> env
val get_readonly : env -> bool
val set_readonly : env -> bool -> env
val get_params : env -> (locl_ty * Pos.t * locl_ty option) Local_id.Map.t
val set_param : env -> Local_id.t -> locl_ty * Pos.t * locl_ty option -> env
val set_log_level : env -> string -> int -> env
val get_log_level : env -> string -> int
val log_env_change_ : string -> ?level:int -> env -> env * 'res -> env * 'res
val log_env_change : string -> ?level:int -> env -> env -> env
val clear_params : env -> env
val with_env : env -> (env -> env * 'a) -> env * 'a
val with_origin : env -> Decl_counters.origin -> (env -> env * 'a) -> env * 'a
val with_origin2 :
env -> Decl_counters.origin -> (env -> env * 'a * 'b) -> env * 'a * 'b
val with_inside_expr_tree :
env -> Aast_defs.hint -> (env -> env * 'a * 'b) -> env * 'a * 'b
val with_outside_expr_tree :
env -> (env -> Aast.class_name option -> env * 'a * 'b) -> env * 'a * 'b
val inside_expr_tree : env -> Aast_defs.hint -> env
val outside_expr_tree : env -> env
val is_in_expr_tree : env -> bool
val is_static : env -> bool
val get_val_kind : env -> Typing_defs.val_kind
val get_self_ty : env -> locl_ty option
val get_self_class_type : env -> (pos_id * exact * locl_ty list) option
val get_self_id : env -> string option
val get_self_class : env -> class_decl option
val get_parent_id : env -> string option
val get_parent_ty : env -> decl_ty option
val get_parent_class : env -> class_decl option
val get_fn_kind : env -> Ast_defs.fun_kind
val get_file : env -> Relative_path.t
val get_current_decl_and_file : env -> Pos_or_decl.ctx
(** Check that the position is in the current decl and if it is, resolve
it with the current file. *)
val fill_in_pos_filename_if_in_current_decl :
env -> Pos_or_decl.t -> Pos.t option
(** This will check that the first position of the given reasons is in the
current decl and if yes use it as primary error position. If no,
it will error at a default position in the current file and log the failed
assertion.
This also sets the error code to the code for unification error
if none is provided. *)
val unify_error_assert_primary_pos_in_current_decl :
env -> Typing_error.Reasons_callback.t
(** This will check that the first position of the given reasons is in the
current decl and if yes use it as primary error position. If no,
it will error at a default position in the current file and log the failed
assertion.
This also sets the error code to the code for invalid type hint error
if none is provided. *)
val invalid_type_hint_assert_primary_pos_in_current_decl :
env -> Typing_error.Reasons_callback.t
val set_fn_kind : env -> Ast_defs.fun_kind -> env
val set_current_module : env -> Ast_defs.id option -> env
val set_internal : env -> bool -> env
val set_support_dynamic_type : env -> bool -> env
val set_everything_sdt : env -> bool -> env
val set_no_auto_likes : env -> bool -> env
val get_module : env -> module_key -> module_decl option
val get_current_module : env -> string option
(** Register the current top-level structure as being dependent on the current
module *)
val make_depend_on_current_module : Typing_env_types.env -> unit
(** Register the droot as being dependent on all of the ancestor classes,
interfaces, and traits of the given class (i.e., the recursive ancestors
returned by [Typing_classes_heap.Api.all_ancestor_names] and stored in
[Decl_defs.dc_ancestors]). Should be invoked once when typechecking the
given class (after [droot] has been set to correspond to the given class). *)
val make_depend_on_ancestors :
Typing_env_types.env -> Decl_provider.Class.t -> unit
val get_internal : env -> bool
val get_support_dynamic_type : env -> bool
val get_no_auto_likes : env -> bool
val set_self : env -> string -> locl_ty -> env
(** Run a given function with self unset in the environment.
Restore self after the function finishes executing. This is used when
checking attributes applied to a class, because the self keyword is not
allowed as part of an argument to an attribute *)
val run_with_no_self : env -> (env -> env * 'a) -> env * 'a
val set_parent : env -> string -> decl_ty -> env
val set_static : env -> env
val set_val_kind : env -> Typing_defs.val_kind -> env
val set_mode : env -> FileInfo.mode -> env
val get_mode : env -> FileInfo.mode
val is_strict : env -> bool
val is_hhi : env -> bool
val forget_members : env -> Reason.blame -> env
val forget_prefixed_members : env -> Local_id.t -> Reason.blame -> env
val forget_suffixed_members : env -> string -> Reason.blame -> env
val get_fake_members : env -> Typing_fake_members.t
module FakeMembers : sig
val update_fake_members : env -> Typing_fake_members.t -> env
val is_valid : env -> Nast.expr -> string -> bool
val is_valid_static : env -> Nast.class_id_ -> string -> bool
val check_static_invalid :
env -> Nast.class_id_ -> string -> locl_ty -> env * locl_ty
val check_instance_invalid :
env -> Nast.expr -> string -> locl_ty -> env * locl_ty
val make : env -> Nast.expr -> string -> Pos.t -> env * Local_id.t
val make_static : env -> Nast.class_id_ -> string -> Pos.t -> env * Local_id.t
end
val tany : env -> locl_phase ty_
val next_cont_opt : env -> Typing_per_cont_env.per_cont_entry option
val all_continuations : env -> Typing_continuations.t list
val set_local :
?immutable:bool ->
is_defined:bool ->
bound_ty:locl_ty option ->
env ->
Local_id.t ->
locl_ty ->
Pos.t ->
env
val is_using_var : env -> Local_id.t -> bool
val set_using_var : env -> Local_id.t -> env
val unset_local : env -> Local_id.t -> env
val get_local : env -> Local_id.t -> Typing_local_types.local
val get_locals :
?quiet:bool -> env -> 'a Aast.capture_lid list -> Typing_local_types.t
val set_locals : env -> Typing_local_types.t -> env
val set_fake_members : env -> Typing_fake_members.t -> env
val is_local_present : env -> Local_id.t -> bool
val get_local_check_defined : env -> Aast.lid -> Typing_local_types.local
val set_local_expr_id :
env ->
Local_id.t ->
Typing_local_types.expression_id ->
(env, env * Typing_error.t) result
val get_local_expr_id :
env -> Local_id.t -> Typing_local_types.expression_id option
val get_tpenv : env -> TPEnv.t
val get_global_tpenv : env -> TPEnv.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 -> TPEnv.tparam_bounds
val get_upper_bounds : env -> string -> locl_ty list -> TPEnv.tparam_bounds
val get_equal_bounds : env -> string -> locl_ty list -> TPEnv.tparam_bounds
val get_reified : env -> string -> Aast.reify_kind
val get_enforceable : env -> string -> bool
val get_newable : env -> string -> bool
val get_require_dynamic : env -> string -> bool
val add_upper_bound :
?intersect:(locl_ty -> locl_ty list -> locl_ty list) ->
env ->
string ->
locl_ty ->
env
val add_lower_bound :
?union:(locl_ty -> locl_ty list -> locl_ty list) ->
env ->
string ->
locl_ty ->
env
val get_tparams : env -> locl_ty -> SSet.t
val add_lower_bound_global : env -> string -> locl_ty -> env
val add_upper_bound_global : env -> string -> locl_ty -> env
val env_with_tpenv : env -> TPEnv.t -> env
val env_with_global_tpenv : env -> TPEnv.t -> env
val add_generic_parameters : env -> decl_tparam list -> env
val get_generic_parameters : env -> string list
val is_generic_parameter : env -> string -> bool
val get_tyvar_pos : env -> Ident.t -> Pos.t
(* Get or add to bounds on type variables *)
val get_tyvar_lower_bounds : env -> Ident.t -> Internal_type_set.t
val get_tyvar_upper_bounds : env -> Ident.t -> Internal_type_set.t
val set_tyvar_lower_bounds : env -> Ident.t -> Internal_type_set.t -> env
val set_tyvar_upper_bounds : env -> Ident.t -> Internal_type_set.t -> env
(* Optionally supply intersection or union operations to simplify the bounds *)
val add_tyvar_upper_bound :
?intersect:(internal_type -> internal_type list -> internal_type list) ->
env ->
Ident.t ->
internal_type ->
env
val add_tyvar_upper_bound_and_update_variances :
?intersect:(internal_type -> internal_type list -> internal_type list) ->
env ->
Ident.t ->
internal_type ->
env
val add_tyvar_lower_bound :
?union:(internal_type -> internal_type list -> internal_type list) ->
env ->
Ident.t ->
internal_type ->
env
val add_tyvar_lower_bound_and_update_variances :
?union:(internal_type -> internal_type list -> internal_type list) ->
env ->
Ident.t ->
internal_type ->
env
val remove_tyvar_upper_bound : env -> Ident.t -> Ident.t -> env
val remove_tyvar_lower_bound : env -> Ident.t -> Ident.t -> env
val set_tyvar_appears_covariantly : env -> Ident.t -> env
val set_tyvar_appears_contravariantly : env -> Ident.t -> env
val set_tyvar_eager_solve_fail : env -> Ident.t -> env
val get_tyvar_appears_covariantly : env -> Ident.t -> bool
val get_tyvar_appears_contravariantly : env -> Ident.t -> bool
val get_tyvar_appears_invariantly : env -> Ident.t -> bool
val get_tyvar_eager_solve_fail : env -> Ident.t -> bool
val get_tyvar_type_const : env -> int -> pos_id -> (pos_id * locl_ty) option
val set_tyvar_type_const : env -> int -> pos_id -> locl_ty -> env
val get_tyvar_type_consts : env -> int -> (pos_id * locl_ty) SMap.t
val get_all_tyvars : env -> Ident.t list
val fresh_param_name : env -> string -> env * string
val add_fresh_generic_parameter_by_kind :
env -> Pos_or_decl.t -> string -> Typing_kinding_defs.kind -> env * string
val add_fresh_generic_parameter :
env ->
Pos_or_decl.t ->
string ->
reified:Aast.reify_kind ->
enforceable:bool ->
newable:bool ->
env * string
val is_fresh_generic_parameter : string -> bool
val get_tpenv_size : env -> int
val get_tpenv_tparams : env -> SSet.t
val set_env_callable_pos : env -> Pos.t -> env
val fun_is_constructor : env -> bool
val set_fun_is_constructor : env -> bool -> env
val set_fun_tast_info : env -> Tast.fun_tast_info -> env
val env_with_locals : env -> Typing_per_cont_env.t -> env
val reinitialize_locals : env -> env
val closure : env -> (env -> env * 'a) -> env * 'a
val in_try : env -> (env -> env * 'a) -> env * 'a
val save : TPEnv.t -> env -> Tast.saved_env
val set_condition_type : env -> SMap.key -> Typing_defs.decl_ty -> env
val get_condition_type : env -> SMap.key -> Typing_defs.decl_ty option
val add_subtype_prop : env -> Typing_logic.subtype_prop -> env
val set_tyvar_variance_i :
env -> ?flip:bool -> ?for_all_vars:bool -> Typing_defs.internal_type -> env
val set_tyvar_variance :
env -> ?flip:bool -> ?for_all_vars:bool -> Typing_defs.locl_ty -> env
val update_variance_after_bind : env -> int -> Typing_defs.locl_ty -> env
val is_consistent : env -> bool
val mark_inconsistent : env -> env
val get_package_for_module : env -> string -> Package.t option
val get_package_by_name : env -> string -> Package.t option
val load_packages : env -> SSet.t -> env
val load_cross_packages_from_attr : env -> ('a, 'b) Aast.user_attributes -> env
val with_packages : env -> SSet.t -> (env -> env * 'a) -> env * 'a
val is_package_loaded : env -> string -> bool
(** Remove solved variable from environment by replacing it by its binding. *)
val remove_var :
env ->
Ident.t ->
search_in_upper_bounds_of:ISet.t ->
search_in_lower_bounds_of:ISet.t ->
env
val unsolve : env -> Ident.t -> env
module Log : sig
(** Convert a type variable from an environment into json *)
val tyvar_to_json :
(locl_ty -> string) ->
(internal_type -> string) ->
env ->
Ident.t ->
Hh_json.json
end |
Rust | hhvm/hphp/hack/src/typing/hh_distc_types/hh_distc_types.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
//
// @generated <<SignedSource::*O*zOeWoEQle#+L!plEphiEmie@IsG>>
//
// To regenerate this file, run:
// hphp/hack/src/oxidized_regen.sh
use eq_modulo_pos::EqModuloPos;
use no_pos_hash::NoPosHash;
use ocamlrep::FromOcamlRep;
use ocamlrep::ToOcamlRep;
use serde::Deserialize;
use serde::Serialize;
#[allow(unused_imports)]
use crate::*;
#[derive(
Clone,
Debug,
Deserialize,
Eq,
EqModuloPos,
FromOcamlRep,
Hash,
NoPosHash,
Ord,
PartialEq,
PartialOrd,
Serialize,
ToOcamlRep,
)]
#[rust_to_ocaml(attr = "deriving show")]
#[repr(C, u8)]
pub enum Event {
Errors(errors::Errors),
TypingStart(isize),
TypingProgress(isize),
} |
Rust | hhvm/hphp/hack/src/typing/hh_distc_types/lib.rs | // Copyright (c) Meta Platforms, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
mod hh_distc_types;
pub use hh_distc_types::*; |
OCaml | hhvm/hphp/hack/src/typing/nast_check/attribute_nast_checks.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 Aast
module SN = Naming_special_names
let find_attribute (name : string) (attrs : Nast.user_attribute list) :
Nast.user_attribute option =
let matches_name { ua_name = (_, attr_name); _ } =
String.equal attr_name name
in
List.find_opt matches_name attrs
let has_attribute (name : string) (attrs : Nast.user_attribute list) : bool =
match find_attribute name attrs with
| Some _ -> true
| None -> false
let check_soft_internal_without_internal
(internal : bool) (attrs : Nast.user_attribute list) =
match find_attribute SN.UserAttributes.uaSoftInternal attrs with
| Some { ua_name = (pos, _); _ } when not internal ->
Errors.add_error
Nast_check_error.(to_user_error @@ Soft_internal_without_internal pos)
| _ -> ()
let check_soft_internal_on_param fp =
match
find_attribute SN.UserAttributes.uaSoftInternal fp.param_user_attributes
with
| Some { ua_name = (pos, attr_name); _ } -> begin
match fp.param_visibility with
| Some Internal -> ()
| Some _ ->
Errors.add_error
Nast_check_error.(to_user_error @@ Soft_internal_without_internal pos)
| None ->
Errors.add_error
Nast_check_error.(
to_user_error
@@ Wrong_expression_kind_builtin_attribute
{ expr_kind = "a parameter"; pos; attr_name })
end
| _ -> ()
let check_attribute_arity attrs attr_name arg_spec =
let attr = Naming_attributes.find attr_name attrs in
let prim_err_opt =
match (arg_spec, attr) with
| (`Range (min_args, _), Some { ua_name = (pos, _); ua_params })
when List.length ua_params < min_args ->
Some
(Nast_check_error.Attribute_too_few_arguments
{ pos; name = attr_name; expected = min_args })
(* Errors.attribute_too_few_arguments pos attr_name min_args *)
| (`Range (_, max_args), Some { ua_name = (pos, _); ua_params })
when List.length ua_params > max_args ->
Some
(Nast_check_error.Attribute_too_many_arguments
{ pos; name = attr_name; expected = max_args })
(* Errors.attribute_too_many_arguments pos attr_name max_args *)
| (`Exact expected_args, Some { ua_name = (pos, _); ua_params })
when List.length ua_params <> expected_args ->
Some
(Nast_check_error.Attribute_not_exact_number_of_args
{
pos;
name = attr_name;
expected = expected_args;
actual = List.length ua_params;
})
| _ -> None
in
Option.iter
(fun err -> Errors.add_error Nast_check_error.(to_user_error err))
prim_err_opt
let attr_pos (attr : ('a, 'b) user_attribute) : Pos.t = fst attr.ua_name
(* Ban methods having both __Memoize and __MemoizeLSB. *)
let check_duplicate_memoize (attrs : Nast.user_attribute list) : unit =
let memoize = find_attribute SN.UserAttributes.uaMemoize attrs in
let memoize_lsb = find_attribute SN.UserAttributes.uaMemoizeLSB attrs in
match (memoize, memoize_lsb) with
| (Some memoize, Some memoize_lsb) ->
Errors.add_error
Nast_check_error.(
to_user_error
@@ Attribute_conflicting_memoize
{ pos = attr_pos memoize; second_pos = attr_pos memoize_lsb })
| _ -> ()
let check_deprecated_static attrs =
let attr = Naming_attributes.find SN.UserAttributes.uaDeprecated attrs in
match attr with
| Some { ua_name = _; ua_params = [msg] }
| Some { ua_name = _; ua_params = [msg; _] } -> begin
match Nast_eval.static_string msg with
| Error p ->
Errors.add_error
Nast_check_error.(
to_user_error
@@ Attribute_param_type { pos = p; x = "static string literal" })
| _ -> ()
end
| _ -> ()
let check_no_auto_dynamic env attrs =
if TypecheckerOptions.enable_no_auto_dynamic (Nast_check_env.get_tcopt env)
then
()
else
let attr = Naming_attributes.find SN.UserAttributes.uaNoAutoDynamic attrs in
match attr with
| Some { ua_name = (pos, _); _ } when not (Pos.is_hhi pos) ->
Errors.add_error
Nast_check_error.(to_user_error @@ Attribute_no_auto_dynamic pos)
| _ -> ()
let check_ifc_enabled tcopt attrs =
let inferflows_opt = find_attribute SN.UserAttributes.uaInferFlows attrs in
match
( inferflows_opt,
TypecheckerOptions.experimental_feature_enabled
tcopt
TypecheckerOptions.experimental_infer_flows )
with
| (Some { ua_name = (pos, _); _ }, false) ->
Errors.experimental_feature pos "IFC InferFlows"
| _ -> ()
(* TODO: error if both Governed and InferFlows are attributes on a function or method *)
let handler =
object
inherit Nast_visitor.handler_base
method! at_fun_ env f =
let variadic_param =
List.find_opt (fun p -> p.param_is_variadic) f.f_params
in
(* Ban arguments on functions with the __EntryPoint attribute. *)
if has_attribute SN.UserAttributes.uaEntryPoint f.f_user_attributes then begin
(match f.f_params with
| [] -> ()
| param :: _ ->
Errors.add_error
Nast_check_error.(
to_user_error @@ Entrypoint_arguments param.param_pos));
match variadic_param with
| Some p ->
Errors.add_error
Nast_check_error.(to_user_error @@ Entrypoint_arguments p.param_pos)
| None -> ()
end;
(* Ban variadic arguments on memoized functions. *)
(if has_attribute "__Memoize" f.f_user_attributes then
match variadic_param with
| Some p ->
Errors.add_error
Nast_check_error.(to_user_error @@ Variadic_memoize p.param_pos)
| None -> ());
check_attribute_arity
f.f_user_attributes
SN.UserAttributes.uaPolicied
(`Range (0, 1));
check_attribute_arity
f.f_user_attributes
SN.UserAttributes.uaInferFlows
(`Exact 0);
check_attribute_arity
f.f_user_attributes
SN.UserAttributes.uaDeprecated
(`Range (1, 2));
check_deprecated_static f.f_user_attributes;
check_no_auto_dynamic env f.f_user_attributes;
check_ifc_enabled (Nast_check_env.get_tcopt env) f.f_user_attributes;
let params = f.f_params in
List.iter
(fun fp ->
check_attribute_arity
fp.param_user_attributes
SN.UserAttributes.uaExternal
(`Exact 0);
check_attribute_arity
fp.param_user_attributes
SN.UserAttributes.uaCanCall
(`Exact 0);
check_soft_internal_on_param fp)
params
method! at_fun_def _env fd =
(* Ban arguments on functions with the __EntryPoint attribute. *)
if
has_attribute SN.UserAttributes.uaEntryPoint fd.fd_fun.f_user_attributes
then begin
match fd.fd_tparams with
| [] -> ()
| tparam :: _ ->
Errors.add_error
Nast_check_error.(
to_user_error @@ Entrypoint_generics (fst tparam.tp_name))
end;
check_soft_internal_without_internal
fd.fd_internal
fd.fd_fun.f_user_attributes
method! at_method_ env m =
let variadic_param =
List.find_opt (fun p -> p.param_is_variadic) m.m_params
in
check_attribute_arity
m.m_user_attributes
SN.UserAttributes.uaPolicied
(`Range (0, 1));
check_attribute_arity
m.m_user_attributes
SN.UserAttributes.uaInferFlows
(`Exact 0);
check_ifc_enabled (Nast_check_env.get_tcopt env) m.m_user_attributes;
check_attribute_arity
m.m_user_attributes
SN.UserAttributes.uaDeprecated
(`Range (1, 2));
check_soft_internal_without_internal
(Aast_defs.equal_visibility m.m_visibility Aast_defs.Internal)
m.m_user_attributes;
check_deprecated_static m.m_user_attributes;
check_duplicate_memoize m.m_user_attributes;
check_no_auto_dynamic env m.m_user_attributes;
List.iter check_soft_internal_on_param m.m_params;
(* Ban variadic arguments on memoized methods. *)
if
has_attribute "__Memoize" m.m_user_attributes
|| has_attribute "__MemoizeLSB" m.m_user_attributes
then
match variadic_param with
| Some p ->
Errors.add_error
Nast_check_error.(to_user_error @@ Variadic_memoize p.param_pos)
| None -> ()
method! at_class_ env c =
check_no_auto_dynamic env c.c_user_attributes;
check_soft_internal_without_internal c.c_internal c.c_user_attributes;
check_attribute_arity
c.c_user_attributes
SN.UserAttributes.uaDocs
(`Exact 1);
List.iter
(fun cv ->
check_soft_internal_without_internal
(Aast_defs.equal_visibility cv.cv_visibility Aast_defs.Internal)
cv.cv_user_attributes)
c.c_vars
end |
OCaml Interface | hhvm/hphp/hack/src/typing/nast_check/attribute_nast_checks.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val handler : Nast_visitor.handler_base |
OCaml | hhvm/hphp/hack/src/typing/nast_check/class_tparams_check.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
type ctx = { class_tparams: Nast.tparam list }
let visitor =
object (this)
inherit [ctx] Nast_visitor.iter_with_state as super
method! on_hint (env, state) (pos, h) =
begin
match h with
| Habstr (tp_name, args) ->
List.iter
state.class_tparams
~f:(fun { tp_name = (c_tp_pos, c_tp_name); _ } ->
if String.equal c_tp_name tp_name then
Errors.add_error
Nast_check_error.(
to_user_error
@@ Typeconst_depends_on_external_tparam
{ pos; ext_pos = c_tp_pos; ext_name = c_tp_name }));
List.iter args ~f:(this#on_hint (env, state))
| _ -> ()
end;
super#on_hint (env, state) (pos, h)
end
let handler =
object
inherit Nast_visitor.handler_base
method! at_class_ env c =
let state = { class_tparams = c.c_tparams } in
let on_hint = visitor#on_hint (env, state) in
List.iter c.c_typeconsts ~f:(fun t ->
match t.c_tconst_kind with
| TCAbstract
{
c_atc_as_constraint = a;
c_atc_super_constraint = s;
c_atc_default = d;
} ->
Option.iter a ~f:on_hint;
Option.iter s ~f:on_hint;
Option.iter d ~f:on_hint
| TCConcrete { c_tc_type = t } -> on_hint t)
end |
OCaml | hhvm/hphp/hack/src/typing/nast_check/class_typeconst_check.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
open Nast_check_env
(* TODO: delete this check *)
let error_if_abstract_type_constant_with_default env typeconst =
if
not
(TypecheckerOptions.experimental_feature_enabled
(get_tcopt env)
TypecheckerOptions.experimental_abstract_type_const_with_default)
then
match typeconst.c_tconst_kind with
| Aast.TCAbstract { c_atc_default = Some _; _ } ->
let (pos, _) = typeconst.c_tconst_name in
Errors.experimental_feature pos "abstract type constant with default"
| _ -> ()
let handler =
object
inherit Nast_visitor.handler_base
method! at_class_ env c =
let check_typeconst typeconst =
error_if_abstract_type_constant_with_default env typeconst;
()
in
List.iter c.c_typeconsts ~f:check_typeconst
end |
OCaml | hhvm/hphp/hack/src/typing/nast_check/const_prohibited_check.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
open Nast_check_env
module SN = Naming_special_names
let has_const attrs = Naming_attributes.mem SN.UserAttributes.uaConst attrs
let error_if_const pos attrs =
if has_const attrs then
Errors.experimental_feature pos "The __Const attribute is not supported."
let handler =
object
inherit Nast_visitor.handler_base
method! at_class_ env c =
(* Const handling:
* disallow __Const attribute unless typechecker option is enabled
*)
let pos = fst c.c_name in
if not (TypecheckerOptions.const_attribute (get_tcopt env)) then (
error_if_const pos c.c_user_attributes;
List.iter c.c_vars ~f:(fun cv ->
error_if_const pos cv.cv_user_attributes)
)
end |
OCaml | hhvm/hphp/hack/src/typing/nast_check/control_context_check.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Aast
open Nast_check_env
let handler =
object
inherit Nast_visitor.handler_base
method! at_stmt env s =
let p = fst s in
let err_opt =
let open Nast_check_error in
match (snd s, env.control_context) with
| (Break, Toplevel) -> Some (Toplevel_break p)
| (Continue, Toplevel) -> Some (Toplevel_continue p)
| (Continue, SwitchContext) -> Some (Continue_in_switch p)
| (Return _, _) when env.is_finally -> Some (Return_in_finally p)
| _ -> None
in
Option.iter
(fun err -> Errors.add_error Nast_check_error.(to_user_error err))
err_opt
end |
hhvm/hphp/hack/src/typing/nast_check/dune | (library
(name nast_check_error)
(wrapped false)
(modules
nast_check_error
)
(libraries
ast
error_codes
user_error))
(library
(name nast_check)
(wrapped false)
(modules
attribute_nast_checks
class_tparams_check
class_typeconst_check
const_prohibited_check
control_context_check
duplicate_class_member_check
duplicate_xhp_attribute_check
dynamically_callable_attr_check
function_pointer_check
global_const_check
illegal_name_check
inout_check
interface_check
list_rvalue_check
naming_coroutine_check
nast_check
nast_class_method_check
nast_generics_check
pessimisation_node_recording
php_lambda_check
private_final_check
prop_modifier_prohibited_check
read_from_append_check
shape_name_check
type_structure_leak_check
unbound_name_check
well_formed_internal_trait
)
(libraries
ast
core_kernel
decl_provider
naming_provider
nast
nast_eval
nast_visitor
typing_utils
utils_core)) |
|
OCaml | hhvm/hphp/hack/src/typing/nast_check/duplicate_class_member_check.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
(* We use the same namespace as constants within the class so we cannot have
* a const and type const with the same name
*)
let error_if_repeated_name member_or_const =
let seen = Caml.Hashtbl.create 0 in
List.iter member_or_const ~f:(fun (pos, name) ->
match Caml.Hashtbl.find_opt seen name with
| Some p' ->
Errors.add_error
Naming_error.(
to_user_error
@@ Error_name_already_bound { pos; name; prev_pos = p' })
| None -> Caml.Hashtbl.replace seen name pos)
let handler =
object
inherit Nast_visitor.handler_base
method! at_class_ _ c =
let typeconst_names =
List.map c.c_typeconsts ~f:(fun tc -> tc.c_tconst_name)
in
let const_names = List.map c.c_consts ~f:(fun cc -> cc.cc_id) in
let combined_names = List.append typeconst_names const_names in
error_if_repeated_name combined_names;
()
end |
OCaml | hhvm/hphp/hack/src/typing/nast_check/duplicate_xhp_attribute_check.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
[@@@warning "-33"]
open Hh_prelude
[@@@warning "+33"]
open Aast
(* Produce a syntax error on XHP expressions of the form:
* <foo x={1} x={2} />
*
* This is not currently enforced in the parser because syntax errors cannot
* be HH_FIXME'd. Once codebases are clean, we can move this check to the
* parser itself.
*)
let error_if_repeated_attribute (attribs : ('ex, 'en) xhp_attribute list) =
let rec loop attribs (seen : SSet.t) =
match attribs with
| Xhp_simple { xs_name = (pos, name); _ } :: _ when SSet.mem name seen ->
Errors.add_error
Parsing_error.(
to_user_error
@@ Xhp_parsing_error
{ pos; msg = Printf.sprintf "Cannot redeclare %s" name })
| Xhp_simple { xs_name = (_, name); _ } :: attribs ->
loop attribs (SSet.add name seen)
| Xhp_spread _ :: attribs -> loop attribs seen
| [] -> ()
in
loop attribs SSet.empty
let handler =
object
inherit Nast_visitor.handler_base
method! at_expr _ (_, _, e) =
(match e with
| Aast.Xml (_, attribs, _) -> error_if_repeated_attribute attribs
| _ -> ());
()
end |
OCaml | hhvm/hphp/hack/src/typing/nast_check/dynamically_callable_attr_check.ml | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
[@@@warning "-33"]
open Hh_prelude
[@@@warning "+33"]
open Hh_prelude
open Aast
module SN = Naming_special_names
let has_reified_generics tparaml =
List.exists
~f:(fun tparam ->
match tparam.tp_reified with
| Erased -> false
| SoftReified
| Reified ->
true)
tparaml
let handler =
object
inherit Nast_visitor.handler_base
method! at_method_ _ m =
let (pos, _) = m.m_name in
let vis = m.m_visibility in
let attr = m.m_user_attributes in
let check_reified_callable p =
if has_reified_generics m.m_tparams then
Errors.add_error
Nast_check_error.(to_user_error @@ Dynamically_callable_reified p)
in
match
( Naming_attributes.mem_pos SN.UserAttributes.uaDynamicallyCallable attr,
vis )
with
| (Some p, Public)
| (Some p, Internal) ->
check_reified_callable p
| (Some p, _) ->
let vis =
match vis with
| Public -> Naming_error.Vpublic
| Private -> Naming_error.Vprivate
| Protected -> Naming_error.Vprotected
| Internal -> Naming_error.Vinternal
in
Errors.add_error
Naming_error.(
to_user_error
@@ Illegal_use_of_dynamically_callable
{ attr_pos = p; meth_pos = pos; vis });
check_reified_callable p
| _ -> ()
method! at_fun_def _ fd =
let attrs = fd.fd_fun.f_user_attributes in
match
Naming_attributes.mem_pos SN.UserAttributes.uaDynamicallyCallable attrs
with
| Some p ->
if has_reified_generics fd.fd_tparams then
Errors.add_error
Nast_check_error.(to_user_error @@ Dynamically_callable_reified p);
()
| _ -> ()
end |
OCaml Interface | hhvm/hphp/hack/src/typing/nast_check/dynamically_callable_attr_check.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val handler : Nast_visitor.handler_base |
OCaml | hhvm/hphp/hack/src/typing/nast_check/function_pointer_check.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type env = {
in_final_class: bool;
class_name: string option;
parent_name: string option;
is_trait: bool;
}
let handler =
object
inherit [env] Stateful_aast_visitor.default_nast_visitor_with_state
method initial_state =
{
in_final_class = false;
class_name = None;
parent_name = None;
is_trait = false;
}
method! at_class_ _ c =
let parent_name =
match c.Aast.c_extends with
| (_, Aast.Happly ((_, parent_name), _)) :: _ -> Some parent_name
| _ -> None
in
let is_trait = Ast_defs.is_c_trait c.Aast.c_kind in
{
in_final_class = c.Aast.c_final;
class_name = Some (snd c.Aast.c_name);
parent_name;
is_trait;
}
method! at_expr env (_, _, e) =
let () =
match e with
| Aast.FunctionPointer
(Aast.FP_class_const ((_, p, Aast.CIself), (_, meth_name)), _) ->
if not env.in_final_class then
if env.is_trait then
Errors.add_error
Naming_error.(
to_user_error
@@ Self_in_non_final_function_pointer
{ pos = p; class_name = None; meth_name })
else
Errors.add_error
Naming_error.(
to_user_error
@@ Self_in_non_final_function_pointer
{ pos = p; class_name = env.class_name; meth_name })
| Aast.FunctionPointer
(Aast.FP_class_const ((_, p, Aast.CIparent), (_, meth_name)), _) ->
Errors.add_error
Naming_error.(
to_user_error
@@ Parent_in_function_pointer
{ pos = p; parent_name = env.parent_name; meth_name })
| _ -> ()
in
env
end |
OCaml | hhvm/hphp/hack/src/typing/nast_check/global_const_check.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
let error_if_no_typehint { cst_mode; cst_type; cst_name; cst_value; _ } =
if (not (FileInfo.is_hhi cst_mode)) && Option.is_none cst_type then
let (_, _, expr) = cst_value in
let (pos, const_name) = cst_name
and ty_name =
match expr with
| String _ -> "string"
| Int _ -> "int"
| Float _ -> "float"
| _ -> "mixed"
in
Errors.add_error
Naming_error.(
to_user_error @@ Const_without_typehint { pos; const_name; ty_name })
let error_if_pseudo_constant gconst =
if Option.is_some gconst.cst_namespace.Namespace_env.ns_name then
let (pos, name) = gconst.cst_name in
let name = Utils.strip_all_ns name in
if Naming_special_names.PseudoConsts.is_pseudo_const (Utils.add_ns name)
then
Errors.add_error
Naming_error.(to_user_error @@ Name_is_reserved { pos; name })
let handler =
object
inherit Nast_visitor.handler_base
method! at_gconst _ gconst =
error_if_no_typehint gconst;
error_if_pseudo_constant gconst;
()
end |
OCaml | hhvm/hphp/hack/src/typing/nast_check/illegal_name_check.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
open Utils
open Nast_check_env
module SN = Naming_special_names
let is_magic =
let h = Caml.Hashtbl.create 23 in
let a x = Caml.Hashtbl.add h x true in
let _ =
SSet.iter
(fun m -> if String.( <> ) m SN.Members.__toString then a m)
SN.Members.as_set
in
(fun (_, s) -> Caml.Hashtbl.mem h s)
(* Class consts and typeconsts cannot be named "class" *)
let error_if_is_named_class (pos, name) =
if String.equal (String.lowercase name) "class" then
Errors.add_error
Naming_error.(to_user_error @@ Illegal_member_variable_class pos)
let handler =
object
inherit Nast_visitor.handler_base
method! at_class_ _ c =
List.iter c.c_typeconsts ~f:(fun tc ->
error_if_is_named_class tc.c_tconst_name);
List.iter c.c_consts ~f:(fun cc -> error_if_is_named_class cc.cc_id)
method! at_expr env (_, _, e) =
let func_name =
match env.function_name with
| None -> None
| Some sid -> Some (snd sid)
in
match e with
| Id (pos, const) ->
let ck = env.classish_kind in
if not (SN.PseudoConsts.is_pseudo_const const) then
()
else if
String.equal const SN.PseudoConsts.g__CLASS__ && Option.is_none ck
then
Errors.add_error Naming_error.(to_user_error @@ Illegal_CLASS pos)
else if
String.equal const SN.PseudoConsts.g__TRAIT__
&& not
(Option.equal
Ast_defs.equal_classish_kind
ck
(Some Ast_defs.Ctrait))
then
Errors.add_error Naming_error.(to_user_error @@ Illegal_TRAIT pos)
| Class_const ((_, _, CIexpr (_, _, Id (_, "parent"))), (_, m_name))
when Option.equal String.equal func_name (Some m_name) ->
()
| Class_const (_, ((pos, meth_name) as mid))
when is_magic mid
&& not (Option.equal String.equal func_name (Some meth_name)) ->
Errors.add_error
Nast_check_error.(to_user_error @@ Magic { pos; meth_name })
| Obj_get (_, (_, _, Id s), _, _) when is_magic s ->
let (pos, meth_name) = s in
Errors.add_error
Nast_check_error.(to_user_error @@ Magic { pos; meth_name })
| Method_caller (_, meth) when is_magic meth ->
let (pos, meth_name) = meth in
Errors.add_error
Nast_check_error.(to_user_error @@ Magic { pos; meth_name })
| _ -> ()
method! at_fun_def _ fd =
let (pos, fname) = fd.fd_name in
let fname_lower = String.lowercase (strip_ns fname) in
if
String.equal fname_lower SN.Members.__construct
|| String.equal fname_lower "using"
then
Errors.add_error
Nast_check_error.(
to_user_error @@ Illegal_function_name { pos; name = fname })
method! at_method_ env m =
let (pos, name) = m.m_name in
if String.equal name SN.Members.__destruct then
Errors.add_error
Nast_check_error.(to_user_error @@ Illegal_destructor pos);
match env.class_name with
| Some _ -> ()
| None -> assert false
end |
OCaml | hhvm/hphp/hack/src/typing/nast_check/inout_check.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
module SN = Naming_special_names
let check_param _env params p user_attributes name =
List.iter params ~f:(fun param ->
match param.param_callconv with
| Ast_defs.Pinout _ ->
let pos = param.param_pos in
if SSet.mem name SN.Members.as_set then
Errors.add_error
Nast_check_error.(to_user_error @@ Inout_params_special pos)
| Ast_defs.Pnormal -> ());
let inout =
List.find params ~f:(fun x ->
match x.param_callconv with
| Ast_defs.Pinout _ -> true
| Ast_defs.Pnormal -> false)
in
match inout with
| Some param ->
if
Naming_attributes.mem2
SN.UserAttributes.uaMemoize
SN.UserAttributes.uaMemoizeLSB
user_attributes
then
Errors.add_error
Nast_check_error.(
to_user_error
@@ Inout_params_memoize { pos = p; param_pos = param.param_pos })
| _ -> ()
let handler =
object
inherit Nast_visitor.handler_base
method! at_fun_def env fd =
let f = fd.fd_fun in
let (p, name) = fd.fd_name in
check_param env f.f_params p f.f_user_attributes name
method! at_method_ env m =
let (p, name) = m.m_name in
check_param env m.m_params p m.m_user_attributes name
end |
OCaml Interface | hhvm/hphp/hack/src/typing/nast_check/inout_check.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val handler : Nast_visitor.handler_base |
OCaml | hhvm/hphp/hack/src/typing/nast_check/interface_check.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
let enforce_no_body m =
match m.m_body.fb_ast with
| [] -> ()
| _ ->
Errors.add_error
Nast_check_error.(to_user_error @@ Abstract_body (fst m.m_name))
let check_interface c =
List.iter c.c_uses ~f:(fun (p, _) ->
Errors.add_error
Nast_check_error.(to_user_error @@ Interface_uses_trait p));
let (statics, vars) = split_vars c.c_vars in
begin
match vars with
| hd :: _ ->
let pos = fst hd.cv_id in
Errors.add_error
Nast_check_error.(to_user_error @@ Interface_with_member_variable pos)
| _ -> ()
end;
begin
match statics with
| hd :: _ ->
let pos = fst hd.cv_id in
Errors.add_error
Nast_check_error.(
to_user_error @@ Interface_with_static_member_variable pos)
| _ -> ()
end;
(* make sure that interfaces only have empty public methods *)
List.iter ~f:enforce_no_body c.c_methods
let handler =
object
inherit Nast_visitor.handler_base
method! at_class_ _ c =
if Ast_defs.is_c_interface c.c_kind then check_interface c
end |
OCaml | hhvm/hphp/hack/src/typing/nast_check/list_rvalue_check.ml | (*
* Copyright (c) 2021, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Aast
type env = { in_lvalue: bool }
let visitor =
object (self)
inherit [_] Aast.iter as super
method! on_expr env ((_, p, expr_) as e) =
match expr_ with
| Binop Aast.{ bop = Ast_defs.Eq None; lhs = e1; rhs = e2 } ->
(* Allow list($foo) = $bar; *)
self#on_expr { in_lvalue = true } e1;
self#on_expr env e2
| List _ ->
if env.in_lvalue then
(* list() can nest, so allow list(list($x)) = $foo; *)
super#on_expr env e
else
(* Ban list() in rvalue positions, e.g. foo(list($bar)) *)
Errors.add_error Nast_check_error.(to_user_error @@ List_rvalue p)
| _ -> super#on_expr { in_lvalue = false } e
method! on_stmt env s =
match snd s with
| Aast.Foreach (val_expr, as_expr, body) ->
self#on_expr env val_expr;
(* Allow foreach($foo as list($x, $y)) { ... } *)
self#on_as_expr { in_lvalue = true } as_expr;
self#on_block env body
| _ -> super#on_stmt env s
end
let handler =
object
inherit Nast_visitor.handler_base
method! at_fun_ _env f = visitor#on_fun_ { in_lvalue = false } f
method! at_method_ _env m = visitor#on_method_ { in_lvalue = false } m
end |
OCaml | hhvm/hphp/hack/src/typing/nast_check/naming_coroutine_check.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
open Nast_check_env
let is_generator env =
let fun_kind = env.function_kind in
Option.equal Ast_defs.equal_fun_kind fun_kind (Some Ast_defs.FGenerator)
|| Option.equal
Ast_defs.equal_fun_kind
fun_kind
(Some Ast_defs.FAsyncGenerator)
let is_sync env =
let fun_kind = env.function_kind in
Option.equal Ast_defs.equal_fun_kind fun_kind (Some Ast_defs.FGenerator)
|| Option.equal Ast_defs.equal_fun_kind fun_kind (Some Ast_defs.FSync)
let handler =
object
inherit Nast_visitor.handler_base
method! at_expr env (_, p, e) =
match e with
| Await _ when is_sync env ->
let func_pos =
match env.function_name with
| None -> None
| Some sid -> Some (fst sid)
in
Errors.add_error
Nast_check_error.(
to_user_error @@ Await_in_sync_function { pos = p; func_pos })
| _ -> ()
method! at_stmt env =
function
| (_, Using { us_has_await; us_exprs; _ })
when us_has_await && is_sync env ->
Errors.add_error
Nast_check_error.(
to_user_error
@@ Await_in_sync_function { pos = fst us_exprs; func_pos = None })
| (_, Foreach (_, (Await_as_v (p, _) | Await_as_kv (p, _, _)), _))
| (p, Awaitall _)
when is_sync env ->
Errors.add_error
Nast_check_error.(
to_user_error @@ Await_in_sync_function { pos = p; func_pos = None })
| (p, Return (Some _)) when is_generator env ->
Errors.add_error Nast_check_error.(to_user_error @@ Return_in_gen p)
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/typing/nast_check/nast_check.ml | [@@@warning "-33"]
open Hh_prelude
[@@@warning "+33"]
let visitor ctx =
let tcopt = Provider_context.get_tcopt ctx in
let record_fine_grained_dependencies =
TypecheckerOptions.record_fine_grained_dependencies tcopt
and rust_elab = TypecheckerOptions.rust_elab tcopt in
let handlers =
if rust_elab then
[]
else
[
Const_prohibited_check.handler;
Prop_modifier_prohibited_check.handler;
Inout_check.handler;
Naming_coroutine_check.handler;
Interface_check.handler;
Illegal_name_check.handler;
Class_tparams_check.handler;
Control_context_check.handler;
Read_from_append_check.handler;
Dynamically_callable_attr_check.handler;
Nast_generics_check.handler;
Nast_class_method_check.handler;
Global_const_check.handler;
Duplicate_class_member_check.handler;
Shape_name_check.handler;
Php_lambda_check.handler;
Duplicate_xhp_attribute_check.handler;
Attribute_nast_checks.handler;
List_rvalue_check.handler;
Private_final_check.handler;
Well_formed_internal_trait.handler;
Type_structure_leak_check.handler;
]
in
let handlers =
if record_fine_grained_dependencies then
Pessimisation_node_recording.handler :: handlers
else
handlers
in
let handlers =
if TypecheckerOptions.skip_tast_checks (Provider_context.get_tcopt ctx) then
[]
else
handlers
in
Nast_visitor.iter_with handlers
let stateful_visitor ctx =
Stateful_aast_visitor.checker
(Stateful_aast_visitor.combine_visitors
(Unbound_name_check.handler ctx)
Function_pointer_check.handler)
let program ctx p =
let () = (visitor ctx)#go ctx p in
let v = stateful_visitor ctx in
v#on_program v#initial_state p
let def ctx d =
let () = (visitor ctx)#go_def ctx d in
let v = stateful_visitor ctx in
v#on_def v#initial_state d |
OCaml Interface | hhvm/hphp/hack/src/typing/nast_check/nast_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 program : Provider_context.t -> Nast.program -> unit
val def : Provider_context.t -> Nast.def -> unit |
OCaml | hhvm/hphp/hack/src/typing/nast_check/nast_check_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.NastCheck
module SN = Naming_special_names
type verb =
| Vreq_implement
| Vimplement
type t =
| Repeated_record_field_name of {
pos: Pos.t;
name: string;
prev_pos: Pos_or_decl.t;
}
| Dynamically_callable_reified of Pos.t
| No_construct_parent of Pos.t
| Nonstatic_method_in_abstract_final_class of Pos.t
| Constructor_required of {
pos: Pos.t;
class_name: string;
prop_names: string list;
}
| Not_initialized of {
pos: Pos.t;
class_name: string;
props: (Pos_or_decl.t * string) list;
}
| Call_before_init of {
pos: Pos.t;
prop_name: string;
}
| Abstract_with_body of Pos.t
| Not_abstract_without_typeconst of Pos.t
| Typeconst_depends_on_external_tparam of {
pos: Pos.t;
ext_pos: Pos.t;
ext_name: string;
}
| Interface_with_partial_typeconst of Pos.t
| Partially_abstract_typeconst_definition of Pos.t
| Refinement_in_typestruct of {
pos: Pos.t;
kind: string;
}
| Multiple_xhp_category of Pos.t
| Return_in_gen of Pos.t
| Return_in_finally of Pos.t
| Toplevel_break of Pos.t
| Toplevel_continue of Pos.t
| Continue_in_switch of Pos.t
| Await_in_sync_function of {
pos: Pos.t;
func_pos: Pos.t option;
}
| Interface_uses_trait of Pos.t
| Static_memoized_function of Pos.t
| Magic of {
pos: Pos.t;
meth_name: string;
}
| Non_interface of {
pos: Pos.t;
name: string;
verb: verb;
}
| ToString_returns_string of Pos.t
| ToString_visibility of Pos.t
| Uses_non_trait of {
pos: Pos.t;
name: string;
kind: string;
}
| Requires_non_class of {
pos: Pos.t;
name: string;
kind: string;
}
| Requires_final_class of {
pos: Pos.t;
name: string;
}
| Abstract_body of Pos.t
| Interface_with_member_variable of Pos.t
| Interface_with_static_member_variable of Pos.t
| Illegal_function_name of {
pos: Pos.t;
name: string;
}
| Entrypoint_arguments of Pos.t
| Entrypoint_generics of Pos.t
| Variadic_memoize of Pos.t
| Abstract_method_memoize of Pos.t
| Instance_property_in_abstract_final_class of Pos.t
| Inout_params_special of Pos.t
| Inout_params_memoize of {
pos: Pos.t;
param_pos: Pos.t;
}
| Inout_in_transformed_pseudofunction of {
pos: Pos.t;
fn_name: string;
}
| Reading_from_append of Pos.t
| List_rvalue of Pos.t
| Illegal_destructor of Pos.t
| Illegal_context of {
pos: Pos.t;
name: string;
}
| Case_fallthrough of {
switch_pos: Pos.t;
case_pos: Pos.t;
next_pos: Pos.t option;
}
| Default_fallthrough of Pos.t
| Php_lambda_disallowed of Pos.t
| Internal_method_with_invalid_visibility of {
pos: Pos.t;
vis: Ast_defs.visibility;
}
| Private_and_final of Pos.t
| Internal_member_inside_public_trait of {
member_pos: Pos.t;
trait_pos: Pos.t;
}
| Attribute_conflicting_memoize of {
pos: Pos.t;
second_pos: Pos.t;
}
| Soft_internal_without_internal of Pos.t
| Wrong_expression_kind_builtin_attribute of {
pos: Pos.t;
attr_name: string;
expr_kind: string;
}
| Attribute_too_many_arguments of {
pos: Pos.t;
name: string;
expected: int;
}
| Attribute_too_few_arguments of {
pos: Pos.t;
name: string;
expected: int;
}
| Attribute_not_exact_number_of_args of {
pos: Pos.t;
name: string;
actual: int;
expected: int;
}
| Attribute_param_type of {
pos: Pos.t;
x: string;
}
| Attribute_no_auto_dynamic of Pos.t
| Generic_at_runtime of {
pos: Pos.t;
prefix: string;
}
| Generics_not_allowed of Pos.t
| Local_variable_modified_and_used of {
pos: Pos.t;
pos_useds: Pos.t list;
}
| Local_variable_modified_twice of {
pos: Pos.t;
pos_modifieds: Pos.t list;
}
| Assign_during_case of Pos.t
| Read_before_write of {
pos: Pos.t;
member_name: string;
}
| Lateinit_with_default of Pos.t
| Missing_assign of Pos.t
let repeated_record_field_name pos name prev_pos =
User_error.make
Error_code.(to_enum RepeatedRecordFieldName)
( pos,
Printf.sprintf "Duplicate record field %s" (Markdown_lite.md_codify name)
)
[(prev_pos, "Previous field is here")]
let dynamically_callable_reified attr_pos =
User_error.make
Error_code.(to_enum DynamicallyCallableReified)
( attr_pos,
"`__DynamicallyCallable` cannot be used on reified functions or methods"
)
[]
let no_construct_parent pos =
User_error.make
Error_code.(to_enum NoConstructParent)
( pos,
Utils.sl
[
"You are extending a class that needs to be initialized\n";
"Make sure you call `parent::__construct`.\n";
] )
[]
let nonstatic_method_in_abstract_final_class pos =
User_error.make
Error_code.(to_enum NonstaticMethodInAbstractFinalClass)
( pos,
"Abstract final classes cannot have nonstatic methods or constructors." )
[]
let constructor_required pos name prop_names =
let name = Render.strip_ns name in
let props_str =
List.map ~f:Markdown_lite.md_codify prop_names |> String.concat ~sep:" "
in
User_error.make
Error_code.(to_enum ConstructorRequired)
( pos,
"Lacking `__construct`, class "
^ Markdown_lite.md_codify name
^ " does not initialize its private member(s): "
^ props_str )
[]
let not_initialized pos cname props =
let cname = Render.strip_ns cname in
let prop_msgs =
List.map props ~f:(fun (pos, prop) ->
( pos,
Markdown_lite.md_codify ("$this->" ^ prop) ^ " is not initialized." ))
in
User_error.make
Error_code.(to_enum NotInitialized)
( pos,
"Class "
^ Markdown_lite.md_codify cname
^ " has properties that cannot be null and aren't always set in `__construct`."
)
prop_msgs
let call_before_init pos cv =
User_error.make
Error_code.(to_enum CallBeforeInit)
( pos,
Utils.sl
([
"Until the initialization of `$this` is over,";
" you can only call private methods\n";
"The initialization is not over because ";
]
@
if String.equal cv "parent::__construct" then
["you forgot to call `parent::__construct`"]
else
[
Markdown_lite.md_codify ("$this->" ^ cv);
" can still potentially be null";
]) )
[]
let abstract_with_body pos =
User_error.make
Error_code.(to_enum AbstractWithBody)
(pos, "This method is declared as abstract, but has a body")
[]
let not_abstract_without_typeconst pos =
User_error.make
Error_code.(to_enum NotAbstractWithoutTypeconst)
( pos,
"This type constant is not declared as abstract, it must have"
^ " an assigned type" )
[]
let typeconst_depends_on_external_tparam pos ext_pos ext_name =
let claim =
( pos,
"A type constant can only use type parameters declared in its own"
^ " type parameter list" )
and reasons =
[
( Pos_or_decl.of_raw_pos ext_pos,
Format.sprintf
"%s was declared as a type parameter here"
(Markdown_lite.md_codify ext_name) );
]
in
User_error.make
Error_code.(to_enum TypeconstDependsOnExternalTparam)
claim
reasons
let interface_with_partial_typeconst pos =
User_error.make
Error_code.(to_enum InterfaceWithPartialTypeconst)
(pos, "An interface cannot contain a partially abstract type constant")
[]
let partially_abstract_typeconst_definition pos =
User_error.make
Error_code.(to_enum PartiallyAbstractTypeconstDefinition)
(pos, "`as` constraints are only legal on abstract type constants")
[]
let refinement_in_typestruct kind pos =
User_error.make
Error_code.(to_enum RefinementInTypeStruct)
( pos,
"Type refinements cannot appear on the right-hand side of " ^ kind ^ "."
)
[]
let multiple_xhp_category pos =
User_error.make
Error_code.(to_enum MultipleXhpCategory)
(pos, "XHP classes can only contain one category declaration")
[]
let return_in_gen pos =
User_error.make
Error_code.(to_enum ReturnInGen)
( pos,
"You cannot return a value in a generator (a generator"
^ " is a function that uses `yield`)" )
[]
let return_in_finally pos =
User_error.make
Error_code.(to_enum ReturnInFinally)
( pos,
"Don't use `return` in a `finally` block;"
^ " there's nothing to receive the return value" )
[]
let toplevel_break pos =
User_error.make
Error_code.(to_enum ToplevelBreak)
(pos, "`break` can only be used inside loops or `switch` statements")
[]
let toplevel_continue pos =
User_error.make
Error_code.(to_enum ToplevelContinue)
(pos, "`continue` can only be used inside loops")
[]
let continue_in_switch pos =
User_error.make
Error_code.(to_enum ContinueInSwitch)
( pos,
"In PHP, `continue;` inside a switch statement is equivalent to `break;`."
^ " Hack does not support this; use `break` if that is what you meant." )
[]
let await_in_sync_function pos func_pos =
let quickfixes =
match func_pos with
| None -> []
| Some fix_pos ->
let (_, start_col) = Pos.line_column fix_pos in
let fix_pos = Pos.set_col_end (start_col - 9) fix_pos in
let fix_pos = Pos.set_col_start (start_col - 9) fix_pos in
[
Quickfix.make
~title:("Make function " ^ Markdown_lite.md_codify "async")
~new_text:"async "
fix_pos;
]
in
User_error.make
Error_code.(to_enum AwaitInSyncFunction)
~quickfixes
(pos, "`await` can only be used inside `async` functions")
[]
let interface_uses_trait pos =
User_error.make
Error_code.(to_enum InterfaceUsesTrait)
(pos, "Interfaces cannot use traits")
[]
let static_memoized_function pos =
User_error.make
Error_code.(to_enum StaticMemoizedFunction)
( pos,
"`memoize` is not allowed on static methods in classes that aren't final "
)
[]
let magic pos meth_name =
User_error.make
Error_code.(to_enum Magic)
( pos,
Format.sprintf "%s is a magic method and cannot be called directly"
@@ Markdown_lite.md_codify meth_name )
[]
let toString_returns_string pos =
User_error.make
Error_code.(to_enum ToStringReturnsString)
(pos, "`__toString` should return a string")
[]
let toString_visibility pos =
User_error.make
Error_code.(to_enum ToStringVisibility)
(pos, "`__toString` must have public visibility and cannot be static")
[]
let abstract_body pos =
User_error.make
Error_code.(to_enum AbstractBody)
(pos, "This method shouldn't have a body")
[]
let interface_with_member_variable pos =
User_error.make
Error_code.(to_enum InterfaceWithMemberVariable)
(pos, "Interfaces cannot have member variables")
[]
let interface_with_static_member_variable pos =
User_error.make
Error_code.(to_enum InterfaceWithStaticMemberVariable)
(pos, "Interfaces cannot have static variables")
[]
let illegal_function_name pos name =
User_error.make
Error_code.(to_enum IllegalFunctionName)
( pos,
Format.sprintf
"Illegal function name: %s"
(Render.strip_ns name |> Markdown_lite.md_codify) )
[]
let entrypoint_arguments pos =
User_error.make
Error_code.(to_enum EntryPointArguments)
( pos,
sprintf
"`%s` functions cannot take arguments."
SN.UserAttributes.uaEntryPoint )
[]
let entrypoint_generics pos =
User_error.make
Error_code.(to_enum EntryPointGenerics)
( pos,
sprintf
"`%s` functions cannot have generic parameters."
SN.UserAttributes.uaEntryPoint )
[]
let variadic_memoize pos =
User_error.make
Error_code.(to_enum VariadicMemoize)
(pos, "Memoized functions cannot be variadic.")
[]
let abstract_method_memoize pos =
User_error.make
Error_code.(to_enum AbstractMethodMemoize)
(pos, "Abstract methods cannot be memoized.")
[]
let instance_property_in_abstract_final_class pos =
User_error.make
Error_code.(to_enum InstancePropertyInAbstractFinalClass)
(pos, "Abstract final classes cannot have instance properties.")
[]
let inout_params_special pos =
User_error.make
Error_code.(to_enum InoutParamsSpecial)
(pos, "Methods with special semantics cannot have `inout` parameters.")
[]
let inout_params_memoize pos param_pos =
User_error.make
Error_code.(to_enum InoutParamsMemoize)
(pos, "Functions with `inout` parameters cannot be memoized")
[(Pos_or_decl.of_raw_pos param_pos, "This is an `inout` parameter")]
let inout_in_transformed_pseudofunction pos fn_name =
User_error.make
Error_code.(to_enum InoutInTransformedPsuedofunction)
(pos, Printf.sprintf "Unexpected `inout` argument for `%s`" fn_name)
[]
let reading_from_append pos =
User_error.make
Error_code.(to_enum ReadingFromAppend)
(pos, "Cannot use `[]` for reading")
[]
let list_rvalue pos =
User_error.make
Error_code.(to_enum ListRvalue)
( pos,
"`list()` can only be used for destructuring assignment. Did you mean `tuple()` or `vec[]`?"
)
[]
let illegal_destructor pos =
User_error.make
Error_code.(to_enum IllegalDestructor)
( pos,
"Destructors are not supported in Hack; use other patterns like "
^ "`IDisposable`/`using` or `try`/`catch` instead." )
[]
let illegal_context pos name =
User_error.make
Error_code.(to_enum IllegalContext)
( pos,
Format.sprintf
"Illegal context: %s\nCannot use a context defined outside namespace %s"
(Markdown_lite.md_codify name)
Naming_special_names.Coeffects.contexts )
[]
let case_fallthrough switch_pos case_pos next_pos =
let quickfixes =
match next_pos with
| None -> []
| Some next_pos ->
let (_, start_col) = Pos.line_column next_pos in
let offset = String.length "case " in
let new_pos =
Pos.set_col_end (start_col - offset)
@@ Pos.set_col_start (start_col - offset) next_pos
in
let new_text =
" // FALLTHROUGH\n" ^ String.make (start_col - offset) ' '
in
[
Quickfix.make
~title:"Mark this `case` as explicitly falling through"
~new_text
new_pos;
]
in
let claim =
( switch_pos,
"This `switch` has a `case` that implicitly falls through and is "
^ "not annotated with `// FALLTHROUGH`" )
and reasons =
[
( Pos_or_decl.of_raw_pos case_pos,
"This `case` implicitly falls through. Did you forget to add `break` or `return`?"
);
]
in
User_error.make ~quickfixes Error_code.(to_enum CaseFallthrough) claim reasons
let default_fallthrough pos =
User_error.make
Error_code.(to_enum DefaultFallthrough)
( pos,
"This `switch` has a default case that implicitly falls "
^ "through and is not annotated with `// FALLTHROUGH`" )
[]
let php_lambda_disallowed pos =
User_error.make
Error_code.(to_enum PhpLambdaDisallowed)
(pos, "PHP style anonymous functions are not allowed.")
[]
let non_interface pos name verb =
let verb_str =
match verb with
| Vimplement -> "implement"
| Vreq_implement -> "require implementation of"
in
User_error.make
Error_code.(to_enum NonInterface)
( pos,
Format.sprintf
"Cannot %s %s - it is not an interface"
verb_str
(Markdown_lite.md_codify @@ Render.strip_ns name) )
[]
let uses_non_trait pos name kind =
User_error.make
Error_code.(to_enum UsesNonTrait)
( pos,
Format.sprintf
"%s is not a trait. It is %s."
(Markdown_lite.md_codify @@ Render.strip_ns name)
kind )
[]
let requires_non_class pos name kind =
User_error.make
Error_code.(to_enum RequiresNonClass)
( pos,
Format.sprintf
"%s is not a class. It is %s."
(Markdown_lite.md_codify @@ Render.strip_ns name)
kind )
[]
let requires_final_class pos name =
User_error.make
Error_code.(to_enum RequiresFinalClass)
( pos,
Format.sprintf
"%s is a `final` class, so it cannot be extended."
(Markdown_lite.md_codify @@ Render.strip_ns name) )
[]
let internal_method_with_invalid_visibility pos vis =
let vis_str =
String.lowercase @@ Markdown_lite.md_codify @@ Ast_defs.show_visibility vis
in
let msg =
Format.sprintf
"`__Internal` methods must be public, they cannot be %s"
vis_str
in
User_error.make Error_code.(to_enum InternalProtectedOrPrivate) (pos, msg) []
let private_and_final pos =
User_error.make
Error_code.(to_enum PrivateAndFinal)
(pos, "Class methods cannot be both `private` and `final`.")
[]
let soft_internal_without_internal pos =
User_error.make
Error_code.(to_enum Soft_internal_without_internal)
( pos,
"<<__SoftInternal>> can only be used on internal symbols. Try adding internal to this symbol."
)
[]
let internal_member_inside_public_trait member_pos trait_pos =
User_error.make
Error_code.(to_enum InternalMemberInsidePublicTrait)
(member_pos, "You cannot make this trait member `internal`")
[
( Pos_or_decl.of_raw_pos trait_pos,
"Only `internal` traits can have `internal` members" );
]
let attribute_conflicting_memoize pos second_pos =
User_error.make
Error_code.(to_enum AttributeConflictingMemoize)
( pos,
Printf.sprintf
"Methods cannot be both %s and %s."
(Markdown_lite.md_codify Naming_special_names.UserAttributes.uaMemoize)
(Markdown_lite.md_codify
Naming_special_names.UserAttributes.uaMemoizeLSB) )
[
( Pos_or_decl.of_raw_pos second_pos,
"Conflicting memoize attribute is here" );
]
let wrong_expression_kind_builtin_attribute pos attr expr_kind =
User_error.make
Error_codes.Typing.(to_enum WrongExpressionKindAttribute)
( pos,
Printf.sprintf
"The %s attribute cannot be used on %s."
(Render.strip_ns attr |> Markdown_lite.md_codify)
expr_kind )
[]
let attribute_too_many_arguments pos name expected =
User_error.make
Error_codes.Typing.(to_enum AttributeTooManyArguments)
( pos,
"The attribute "
^ Markdown_lite.md_codify name
^ " expects at most "
^ Render.pluralize_arguments expected )
[]
let attribute_too_few_arguments pos name expected =
User_error.make
Error_codes.Typing.(to_enum AttributeTooFewArguments)
( pos,
"The attribute "
^ Markdown_lite.md_codify name
^ " expects at least "
^ Render.pluralize_arguments expected )
[]
let attribute_not_exact_number_of_args pos name expected actual =
let code =
if actual > expected then
Error_codes.Typing.AttributeTooManyArguments
else
Error_codes.Typing.AttributeTooFewArguments
and claim =
( pos,
"The attribute "
^ Markdown_lite.md_codify name
^ " expects "
^
match expected with
| 0 -> "no arguments"
| 1 -> "exactly 1 argument"
| _ -> "exactly " ^ string_of_int expected ^ " arguments" )
in
User_error.make Error_codes.Typing.(to_enum code) claim []
let attribute_param_type pos x =
User_error.make
Error_codes.Typing.(to_enum AttributeParamType)
(pos, "This attribute parameter should be " ^ x)
[]
let attribute_no_auto_dynamic pos =
User_error.make
Error_codes.Typing.(to_enum AttributeNoAutoDynamic)
(pos, "This attribute is not yet supported in user code")
[]
let generic_at_runtime p prefix =
User_error.make
Error_codes.Typing.(to_enum ErasedGenericAtRuntime)
( p,
prefix
^ " generics can only be used in type hints because they do not exist at runtime."
)
[]
let generics_not_allowed p =
User_error.make
Error_codes.Typing.(to_enum GenericsNotAllowed)
(p, "Generics are not allowed in this position.")
[]
let local_variable_modified_and_used pos_modified pos_used_l =
let used_msg p = (Pos_or_decl.of_raw_pos p, "And accessed here") in
User_error.make
Error_codes.Typing.(to_enum LocalVariableModifedAndUsed)
( pos_modified,
"Unsequenced modification and access to local variable. Modified here" )
(List.map pos_used_l ~f:used_msg)
let local_variable_modified_twice pos_modified pos_modified_l =
let modified_msg p = (Pos_or_decl.of_raw_pos p, "And also modified here") in
User_error.make
Error_codes.Typing.(to_enum LocalVariableModifedTwice)
(pos_modified, "Unsequenced modifications to local variable. Modified here")
(List.map pos_modified_l ~f:modified_msg)
let assign_during_case p =
User_error.make
Error_codes.Typing.(to_enum AssignDuringCase)
(p, "Don't assign to variables inside of case labels")
[]
let read_before_write (pos, v) =
User_error.make
Error_codes.Typing.(to_enum ReadBeforeWrite)
( pos,
Utils.sl
[
"Read access to ";
Markdown_lite.md_codify ("$this->" ^ v);
" before initialization";
] )
[]
let lateinit_with_default pos =
User_error.make
Error_codes.Typing.(to_enum LateInitWithDefault)
(pos, "A late-initialized property cannot have a default value")
[]
let missing_assign pos =
User_error.make
Error_codes.Typing.(to_enum MissingAssign)
(pos, "Please assign a value")
[]
(* --------------------------------------------- *)
let to_user_error = function
| Repeated_record_field_name { pos; name; prev_pos } ->
repeated_record_field_name pos name prev_pos
| Dynamically_callable_reified pos -> dynamically_callable_reified pos
| No_construct_parent pos -> no_construct_parent pos
| Nonstatic_method_in_abstract_final_class pos ->
nonstatic_method_in_abstract_final_class pos
| Constructor_required { pos; class_name; prop_names } ->
constructor_required pos class_name prop_names
| Not_initialized { pos; class_name; props } ->
not_initialized pos class_name props
| Call_before_init { pos; prop_name } -> call_before_init pos prop_name
| Abstract_with_body pos -> abstract_with_body pos
| Not_abstract_without_typeconst pos -> not_abstract_without_typeconst pos
| Typeconst_depends_on_external_tparam { pos; ext_pos; ext_name } ->
typeconst_depends_on_external_tparam pos ext_pos ext_name
| Interface_with_partial_typeconst pos -> interface_with_partial_typeconst pos
| Partially_abstract_typeconst_definition pos ->
partially_abstract_typeconst_definition pos
| Refinement_in_typestruct { pos; kind } -> refinement_in_typestruct kind pos
| Multiple_xhp_category pos -> multiple_xhp_category pos
| Return_in_gen pos -> return_in_gen pos
| Return_in_finally pos -> return_in_finally pos
| Toplevel_break pos -> toplevel_break pos
| Toplevel_continue pos -> toplevel_continue pos
| Continue_in_switch pos -> continue_in_switch pos
| Await_in_sync_function { pos; func_pos } ->
await_in_sync_function pos func_pos
| Interface_uses_trait pos -> interface_uses_trait pos
| Static_memoized_function pos -> static_memoized_function pos
| Magic { pos; meth_name } -> magic pos meth_name
| ToString_returns_string pos -> toString_returns_string pos
| ToString_visibility pos -> toString_visibility pos
| Abstract_body pos -> abstract_body pos
| Interface_with_member_variable pos -> interface_with_member_variable pos
| Interface_with_static_member_variable pos ->
interface_with_static_member_variable pos
| Illegal_function_name { pos; name } -> illegal_function_name pos name
| Entrypoint_arguments pos -> entrypoint_arguments pos
| Entrypoint_generics pos -> entrypoint_generics pos
| Variadic_memoize pos -> variadic_memoize pos
| Abstract_method_memoize pos -> abstract_method_memoize pos
| Instance_property_in_abstract_final_class pos ->
instance_property_in_abstract_final_class pos
| Inout_params_special pos -> inout_params_special pos
| Inout_params_memoize { pos; param_pos } ->
inout_params_memoize pos param_pos
| Inout_in_transformed_pseudofunction { pos; fn_name } ->
inout_in_transformed_pseudofunction pos fn_name
| Reading_from_append pos -> reading_from_append pos
| List_rvalue pos -> list_rvalue pos
| Illegal_destructor pos -> illegal_destructor pos
| Illegal_context { pos; name } -> illegal_context pos name
| Case_fallthrough { switch_pos; case_pos; next_pos } ->
case_fallthrough switch_pos case_pos next_pos
| Default_fallthrough pos -> default_fallthrough pos
| Php_lambda_disallowed pos -> php_lambda_disallowed pos
| Non_interface { pos; name; verb } -> non_interface pos name verb
| Uses_non_trait { pos; name; kind } -> uses_non_trait pos name kind
| Requires_non_class { pos; name; kind } -> requires_non_class pos name kind
| Requires_final_class { pos; name } -> requires_final_class pos name
| Internal_method_with_invalid_visibility { pos; vis } ->
internal_method_with_invalid_visibility pos vis
| Private_and_final pos -> private_and_final pos
| Internal_member_inside_public_trait { member_pos; trait_pos } ->
internal_member_inside_public_trait member_pos trait_pos
| Attribute_conflicting_memoize { pos; second_pos } ->
attribute_conflicting_memoize pos second_pos
| Soft_internal_without_internal pos -> soft_internal_without_internal pos
| Wrong_expression_kind_builtin_attribute { pos; attr_name; expr_kind } ->
wrong_expression_kind_builtin_attribute pos attr_name expr_kind
| Attribute_too_many_arguments { pos; name; expected } ->
attribute_too_many_arguments pos name expected
| Attribute_too_few_arguments { pos; name; expected } ->
attribute_too_few_arguments pos name expected
| Attribute_not_exact_number_of_args { pos; name; expected; actual } ->
attribute_not_exact_number_of_args pos name expected actual
| Attribute_param_type { pos; x } -> attribute_param_type pos x
| Attribute_no_auto_dynamic pos -> attribute_no_auto_dynamic pos
| Generic_at_runtime { pos; prefix } -> generic_at_runtime pos prefix
| Generics_not_allowed pos -> generics_not_allowed pos
| Local_variable_modified_and_used { pos; pos_useds } ->
local_variable_modified_and_used pos pos_useds
| Local_variable_modified_twice { pos; pos_modifieds } ->
local_variable_modified_twice pos pos_modifieds
| Assign_during_case pos -> assign_during_case pos
| Read_before_write { pos; member_name } ->
read_before_write (pos, member_name)
| Lateinit_with_default pos -> lateinit_with_default pos
| Missing_assign pos -> missing_assign pos |
OCaml Interface | hhvm/hphp/hack/src/typing/nast_check/nast_check_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.NastCheck
type verb =
| Vreq_implement
| Vimplement
type t =
| Repeated_record_field_name of {
pos: Pos.t;
name: string;
prev_pos: Pos_or_decl.t;
}
| Dynamically_callable_reified of Pos.t
| No_construct_parent of Pos.t
| Nonstatic_method_in_abstract_final_class of Pos.t
| Constructor_required of {
pos: Pos.t;
class_name: string;
prop_names: string list;
}
| Not_initialized of {
pos: Pos.t;
class_name: string;
props: (Pos_or_decl.t * string) list;
}
| Call_before_init of {
pos: Pos.t;
prop_name: string;
}
| Abstract_with_body of Pos.t
| Not_abstract_without_typeconst of Pos.t
| Typeconst_depends_on_external_tparam of {
pos: Pos.t;
ext_pos: Pos.t;
ext_name: string;
}
| Interface_with_partial_typeconst of Pos.t
| Partially_abstract_typeconst_definition of Pos.t
| Refinement_in_typestruct of {
pos: Pos.t;
kind: string;
}
| Multiple_xhp_category of Pos.t
| Return_in_gen of Pos.t
| Return_in_finally of Pos.t
| Toplevel_break of Pos.t
| Toplevel_continue of Pos.t
| Continue_in_switch of Pos.t
| Await_in_sync_function of {
pos: Pos.t;
func_pos: Pos.t option;
}
| Interface_uses_trait of Pos.t
| Static_memoized_function of Pos.t
| Magic of {
pos: Pos.t;
meth_name: string;
}
| Non_interface of {
pos: Pos.t;
name: string;
verb: verb;
}
| ToString_returns_string of Pos.t
| ToString_visibility of Pos.t
| Uses_non_trait of {
pos: Pos.t;
name: string;
kind: string;
}
| Requires_non_class of {
pos: Pos.t;
name: string;
kind: string;
}
| Requires_final_class of {
pos: Pos.t;
name: string;
}
| Abstract_body of Pos.t
| Interface_with_member_variable of Pos.t
| Interface_with_static_member_variable of Pos.t
| Illegal_function_name of {
pos: Pos.t;
name: string;
}
| Entrypoint_arguments of Pos.t
| Entrypoint_generics of Pos.t
| Variadic_memoize of Pos.t
| Abstract_method_memoize of Pos.t
| Instance_property_in_abstract_final_class of Pos.t
| Inout_params_special of Pos.t
| Inout_params_memoize of {
pos: Pos.t;
param_pos: Pos.t;
}
| Inout_in_transformed_pseudofunction of {
pos: Pos.t;
fn_name: string;
}
| Reading_from_append of Pos.t
| List_rvalue of Pos.t
| Illegal_destructor of Pos.t
| Illegal_context of {
pos: Pos.t;
name: string;
}
| Case_fallthrough of {
switch_pos: Pos.t;
case_pos: Pos.t;
next_pos: Pos.t option;
}
| Default_fallthrough of Pos.t
| Php_lambda_disallowed of Pos.t
| Internal_method_with_invalid_visibility of {
pos: Pos.t;
vis: Ast_defs.visibility;
}
| Private_and_final of Pos.t
| Internal_member_inside_public_trait of {
member_pos: Pos.t;
trait_pos: Pos.t;
}
| Attribute_conflicting_memoize of {
pos: Pos.t;
second_pos: Pos.t;
}
| Soft_internal_without_internal of Pos.t
| Wrong_expression_kind_builtin_attribute of {
pos: Pos.t;
attr_name: string;
expr_kind: string;
}
| Attribute_too_many_arguments of {
pos: Pos.t;
name: string;
expected: int;
}
| Attribute_too_few_arguments of {
pos: Pos.t;
name: string;
expected: int;
}
| Attribute_not_exact_number_of_args of {
pos: Pos.t;
name: string;
actual: int;
expected: int;
}
| Attribute_param_type of {
pos: Pos.t;
x: string;
}
| Attribute_no_auto_dynamic of Pos.t
| Generic_at_runtime of {
pos: Pos.t;
prefix: string;
}
| Generics_not_allowed of Pos.t
| Local_variable_modified_and_used of {
pos: Pos.t;
pos_useds: Pos.t list;
}
| Local_variable_modified_twice of {
pos: Pos.t;
pos_modifieds: Pos.t list;
}
| Assign_during_case of Pos.t
| Read_before_write of {
pos: Pos.t;
member_name: string;
}
| Lateinit_with_default of Pos.t
| Missing_assign of Pos.t
val to_user_error : t -> (Pos.t, Pos_or_decl.t) User_error.t |
OCaml | hhvm/hphp/hack/src/typing/nast_check/nast_class_method_check.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
module UA = Naming_special_names.UserAttributes
let is_memoizable user_attributes =
Naming_attributes.mem2 UA.uaMemoize UA.uaMemoizeLSB user_attributes
let error_if_duplicate_method_names methods =
let _ =
List.fold_left
methods
~init:SSet.empty
~f:(fun seen_methods { m_name = (pos, meth_name); _ } ->
if SSet.mem meth_name seen_methods then
Errors.add_error
Naming_error.(
to_user_error @@ Method_name_already_bound { pos; meth_name });
SSet.add meth_name seen_methods)
in
()
let error_if_abstract_method_is_memoized method_ =
if method_.m_abstract && is_memoizable method_.m_user_attributes then
Errors.add_error
Nast_check_error.(
to_user_error @@ Abstract_method_memoize (fst method_.m_name))
let handler =
object
inherit Nast_visitor.handler_base
method! at_class_ _ class_ =
error_if_duplicate_method_names class_.c_methods
method! at_method_ _ method_ = error_if_abstract_method_is_memoized method_
end |
OCaml | hhvm/hphp/hack/src/typing/nast_check/nast_generics_check.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
(** Information about type parameters that are and were in scope. The first boolean flag
indicates if the variable is still in scope or if it was only in scope earlier
(true means still in scope).
The second boolean flag indicates whether the type parameter is higher-kinded *)
type tparam_info = (pos * bool * bool) SMap.t
let error_if_is_this (pos, name) =
if String.equal (String.lowercase name) "this" then
Errors.add_error Naming_error.(to_user_error @@ This_reserved pos)
let error_if_invalid_tparam_name ~nested ~is_hk (pos, name) =
match
( String.equal name Naming_special_names.Typehints.wildcard,
nested && not is_hk )
with
| (true, false) ->
Errors.add_error
Naming_error.(to_user_error @@ Wildcard_tparam_disallowed pos)
| (true, true) -> ()
| _ ->
if String.is_empty name || not (Char.equal name.[0] 'T') then
Errors.add_error Naming_error.(to_user_error @@ Start_with_T pos)
let error_if_reified ~because_nested (pos, name) = function
| Erased -> ()
| SoftReified
| Reified ->
Errors.add_error
Naming_error.(
to_user_error
@@ HKT_unsupported_feature
{ pos; because_nested; var_name = name; feature = Ft_reification })
let error_if_user_attributes ~because_nested (pos, name) attrs =
if not (List.is_empty attrs) then
Errors.add_error
Naming_error.(
to_user_error
@@ HKT_unsupported_feature
{ pos; because_nested; var_name = name; feature = Ft_user_attrs })
let error_if_not_invariant ~because_nested (pos, name) =
let open Ast_defs in
function
| Invariant -> ()
| Covariant
| Contravariant ->
Errors.add_error
Naming_error.(
to_user_error
@@ HKT_unsupported_feature
{ pos; because_nested; var_name = name; feature = Ft_variance })
let error_if_constraints_present ~because_nested (pos, name) constraints =
if not (List.is_empty constraints) then
Errors.add_error
Naming_error.(
to_user_error
@@ HKT_unsupported_feature
{ pos; because_nested; var_name = name; feature = Ft_constraints })
let rec check_tparam ~nested (seen : tparam_info) tparam =
let name = tparam.tp_name in
let is_higher_kinded = not (List.is_empty tparam.tp_parameters) in
error_if_is_this name;
error_if_invalid_tparam_name ~nested ~is_hk:is_higher_kinded name;
if nested then begin
error_if_constraints_present ~because_nested:true name tparam.tp_constraints;
error_if_reified ~because_nested:true name tparam.tp_reified;
error_if_user_attributes ~because_nested:true name tparam.tp_user_attributes;
error_if_not_invariant ~because_nested:true name tparam.tp_variance
end;
if is_higher_kinded then begin
error_if_constraints_present
~because_nested:false
name
tparam.tp_constraints;
error_if_reified ~because_nested:false name tparam.tp_reified;
error_if_user_attributes
~because_nested:false
name
tparam.tp_user_attributes;
error_if_not_invariant ~because_nested:false name tparam.tp_variance
end;
check_tparams ~nested:true seen tparam.tp_parameters
(* See not on Naming.type_param about scoping of type parameters *)
and check_tparams ~nested (seen : tparam_info) tparams =
let bring_into_scope (seen : tparam_info) tparam =
let is_hk = not (List.is_empty tparam.tp_parameters) in
let (pos, name) = tparam.tp_name in
if String.equal name Naming_special_names.Typehints.wildcard then
seen
else begin
(match SMap.find_opt name seen with
| Some (prev_pos, true, _) ->
Errors.add_error
Naming_error.(
to_user_error
@@ Shadowed_tparam { pos; prev_pos; tparam_name = name })
| Some (_, false, _) ->
Errors.add_error
Naming_error.(
to_user_error
@@ Tparam_non_shadowing_reuse { pos; tparam_name = name })
| None -> ());
SMap.add name (pos, true, is_hk) seen
end
in
let remove_from_scope (seen : tparam_info) tparam =
let (pos, name) = tparam.tp_name in
if String.equal name Naming_special_names.Typehints.wildcard then
seen
else
(* Using a dummy value for the higher-kindedness, we don't care once
it's out of scope *)
SMap.add name (pos, false, false) seen
in
let seen = List.fold_left tparams ~f:bring_into_scope ~init:seen in
let seen = List.fold_left tparams ~f:(check_tparam ~nested) ~init:seen in
if nested then
List.fold_left tparams ~f:remove_from_scope ~init:seen
else
seen
let check_where_constraints (seen : tparam_info) cstrs =
let visitor =
object (this)
inherit [_] Aast.iter as super
method! on_hint env (pos, h) =
match h with
| Aast.Habstr (t, args) ->
(match SMap.find_opt t seen with
| Some (_, true, true) ->
Errors.add_error
Naming_error.(
to_user_error
@@ HKT_unsupported_feature
{
pos;
because_nested = false;
var_name = t;
feature = Ft_where_constraints;
})
| Some _
| None ->
());
List.iter args ~f:(this#on_hint env)
| _ -> super#on_hint env (pos, h)
end
in
List.iter cstrs ~f:(fun (h1, _, h2) ->
visitor#on_hint () h1;
visitor#on_hint () h2)
let check_class class_ =
let seen_class_tparams =
check_tparams ~nested:false SMap.empty class_.c_tparams
in
(* Due to ~nested:false above, the class tparams are still marked as in scope *)
let check_method method_tparams method_where_cstrs =
let seen = check_tparams ~nested:false seen_class_tparams method_tparams in
check_where_constraints seen method_where_cstrs
in
List.iter class_.c_methods ~f:(fun m ->
check_method m.m_tparams m.m_where_constraints)
let handler =
object
inherit Nast_visitor.handler_base
method! at_fun_def _ fd =
let seen = check_tparams ~nested:false SMap.empty fd.fd_tparams in
(* Due to ~nested:false above, the function tparams are still marked as in scope *)
check_where_constraints seen fd.fd_where_constraints
method! at_class_ _ = check_class
method! at_typedef _ typedef =
check_tparams ~nested:false SMap.empty typedef.t_tparams |> ignore
end |
OCaml Interface | hhvm/hphp/hack/src/typing/nast_check/nast_generics_check.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val handler : Nast_visitor.handler_base |
OCaml | hhvm/hphp/hack/src/typing/nast_check/pessimisation_node_recording.ml | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Nast_check_env
let handler =
object
inherit Nast_visitor.handler_base
method! at_fun_def env fd =
let ctx = env.ctx in
let deps_mode = Provider_context.get_deps_mode ctx in
let name = fd.Aast.fd_name |> Ast_defs.get_id in
let node = Typing_deps.Dep.Fun name in
Typing_pessimisation_deps.add_node deps_mode node None
method! at_method_ env method_ =
let class_ = env.class_name |> Option.value_exn in
let name = method_.Aast.m_name |> Ast_defs.get_id in
let static = method_.Aast.m_static in
let abstract = method_.Aast.m_abstract in
let external_ = method_.Aast.m_external in
if
(not abstract)
&& (not external_)
&& not String.(name = Naming_special_names.Members.__construct)
then
let ctx = env.ctx in
let deps_mode = Provider_context.get_deps_mode ctx in
let class_dep = Typing_deps.Dep.Type class_ in
let member =
if static then
Typing_pessimisation_deps.SMethod name
else
Typing_pessimisation_deps.Method name
in
Typing_pessimisation_deps.add_node deps_mode class_dep (Some member)
end |
OCaml Interface | hhvm/hphp/hack/src/typing/nast_check/pessimisation_node_recording.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val handler : Nast_visitor.handler_base |
OCaml | hhvm/hphp/hack/src/typing/nast_check/php_lambda_check.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Aast
open Nast_check_env
let handler =
object
inherit Nast_visitor.handler_base
method! at_expr env (_, pos, expr) =
if TypecheckerOptions.error_php_lambdas (get_tcopt env) then
match expr with
| Efun _ ->
Errors.add_error
Nast_check_error.(to_user_error @@ Php_lambda_disallowed pos)
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/typing/nast_check/private_final_check.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
[@@@warning "-33"]
open Hh_prelude
[@@@warning "+33"]
open Aast
(* Ban `private final` on classes, but not traits. *)
let handler =
object
inherit Nast_visitor.handler_base
method! at_method_ env m =
match (env.Nast_check_env.classish_kind, m.m_visibility, m.m_final) with
| (Some Ast_defs.Ctrait, _, _) -> ()
| (_, Private, true) ->
let (pos, _) = m.m_name in
Errors.add_error
Nast_check_error.(to_user_error @@ Private_and_final pos)
| _ -> ()
end |
OCaml | hhvm/hphp/hack/src/typing/nast_check/prop_modifier_prohibited_check.ml | (*
* Copyright () 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Aast
open Nast_check_env
module SN = Naming_special_names
let error_if_static_prop_is_const env cv =
if
cv.cv_is_static
&& (not (TypecheckerOptions.const_static_props (get_tcopt env)))
&& Naming_attributes.mem SN.UserAttributes.uaConst cv.cv_user_attributes
then
let pos = fst cv.cv_id in
Errors.experimental_feature pos "Const properties cannot be static."
(* Non-static properties cannot have attribute __LSB *)
let error_if_nonstatic_prop_with_lsb cv =
if not cv.cv_is_static then
let lsb_pos =
Naming_attributes.mem_pos SN.UserAttributes.uaLSB cv.cv_user_attributes
in
Option.iter lsb_pos ~f:(fun pos ->
Errors.add_error
Naming_error.(to_user_error @@ Nonstatic_property_with_lsb pos))
let unnecessary_lsb c cv =
let attr = SN.UserAttributes.uaLSB in
match Naming_attributes.mem_pos attr cv.cv_user_attributes with
| None -> ()
| Some pos ->
let (class_pos, class_name) = c.c_name in
let suggestion = None in
Errors.add_error
Naming_error.(
to_user_error
@@ Unnecessary_attribute
{ pos; attr; class_pos; class_name; suggestion })
let handler =
object
inherit Nast_visitor.handler_base
method! at_class_ env cv =
let check_vars cv =
error_if_static_prop_is_const env cv;
error_if_nonstatic_prop_with_lsb cv;
()
in
List.iter cv.c_vars ~f:check_vars;
if cv.c_final then List.iter cv.c_vars ~f:(unnecessary_lsb cv)
end |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.