language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
OCaml
hhvm/hphp/hack/src/stubs/startup_initializer.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. * *) (** Perform process wide startup initialization for hack server. *) let init () = ()
OCaml Interface
hhvm/hphp/hack/src/stubs/state_loader.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 dirty_files = { master_changes: Relative_path.t list; local_changes: Relative_path.t list; } type hot_decls_paths = { legacy_hot_decls_path: string; shallow_hot_decls_path: string; } type native_load_result = { naming_table_path: string; corresponding_rev: Hg.rev; mergebase_rev: Hg.global_rev option; mergebase: Hg.hg_rev option Future.t; is_cached: bool; state_distance: int; deptable_fn: string; dirty_files: dirty_files Future.t; hot_decls_paths: hot_decls_paths; errors_path: string; } type saved_state_handle = { saved_state_for_rev: Hg.rev; saved_state_everstore_handle: string; watchman_mergebase: MonitorUtils.watchman_mergebase option; } type error = unit type verbose_error = { message: string; stack: Utils.callstack; auto_retry: bool; environment: string option; } [@@deriving show] val error_string_verbose : error -> verbose_error val cached_state : load_64bit:bool -> ?saved_state_handle:saved_state_handle -> config_hash:string -> rev:Hg.rev -> (Hg.rev * string * MonitorUtils.watchman_mergebase option) option val fetch_saved_state : load_64bit:bool -> ?cache_limit:int -> config:State_loader_config.timeouts -> config_hash:string -> saved_state_handle -> (string, error) result Future.t val mk_state_future : config:State_loader_config.timeouts -> load_64bit:bool -> ?saved_state_handle:saved_state_handle -> config_hash:string option -> ignore_hh_version:bool -> ignore_hhconfig:bool -> use_prechecked_files:bool -> Path.t -> (native_load_result, error) result Future.t
OCaml
hhvm/hphp/hack/src/stubs/state_loader_futures.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. * *) let get_project_metadata ~progress_callback:_ ~saved_state_type:_ ~repo:_ ~ignore_hh_version:_ ~opts:_ = failwith "Not implemented" let load ~ssopt:_ ~progress_callback:_ ~watchman_opts:_ ~ignore_hh_version:_ ~saved_state_type:_ = Future.of_value (Error "Not implemented") let wait_for_finish _ = failwith "Not implemented" let wait_for_finish_with_debug_details _ = failwith "Not implemented" let download_and_unpack_saved_state_from_manifold ~ssopt:_ ~progress_callback:_ ~manifold_path:_ ~target_path:_ ~saved_state_type:_ = failwith "Not implemented"
OCaml
hhvm/hphp/hack/src/stubs/state_loader_lwt.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. * *) let get_project_metadata ~progress_callback:_ ~saved_state_type:_ ~repo:_ ~ignore_hh_version:_ ~opts:_ = failwith "Not implemented" let load ~ssopt:_ ~progress_callback:_ ~watchman_opts:_ ~ignore_hh_version:_ ~saved_state_type:_ = failwith "Not implemented" let load_internal ~ssopt:_ ~progress_callback:_ ~watchman_opts:_ ~ignore_hh_version:_ ~saved_state_type:_ = failwith "Not implemented" let prepare_download_dir ~saved_state_type:_ = failwith "Not implemented" let get_saved_state_target_path ~download_dir:_ ~manifold_path:_ = failwith "Not implemented" let download_and_unpack_saved_state_from_manifold ~ssopt:_ ~progress_callback:_ ~manifold_path:_ ~target_path:_ ~saved_state_type:_ = failwith "Not implemented"
hhvm/hphp/hack/src/stubs/experiments_config_file/dune
(* -*- tuareg -*- *) let library_entry name suffix = Printf.sprintf "(library (name %s) (wrapped false) (modules) (libraries %s_%s))" name name suffix let fb_entry name = library_entry name "fb" let stubs_entry name = library_entry name "stubs" let entry is_fb name = if is_fb then fb_entry name else stubs_entry name let () = (* test presence of fb subfolder *) let current_dir = Sys.getcwd () in (* we are in src/stubs/xxx, locate src/facebook/utils *) let src_dir = Filename.dirname @@ Filename.dirname current_dir in let fb_dir = Filename.concat src_dir "facebook" in let fb_utils_dir = Filename.concat fb_dir "utils" in (* locate src/facebook/utils/dune *) let fb_dune = Filename.concat fb_utils_dir "dune" in let is_fb = Sys.file_exists fb_dune in let lib_name = entry is_fb "experiments_config_file" in Jbuild_plugin.V1.send lib_name
hhvm/hphp/hack/src/stubs/flytrap/dune
(* -*- tuareg -*- *) let library_entry name suffix = Printf.sprintf "(library (name %s) (wrapped false) (modules) (libraries %s_%s))" name name suffix let fb_entry name = library_entry name "fb" let stubs_entry name = library_entry name "stubs" let entry is_fb name = if is_fb then fb_entry name else stubs_entry name let () = (* test presence of fb subfolder *) let current_dir = Sys.getcwd () in (* we are in src/stubs/xxx, locate src/facebook/utils *) let src_dir = Filename.dirname @@ Filename.dirname current_dir in let fb_dir = Filename.concat src_dir "facebook" in let fb_utils_dir = Filename.concat fb_dir "utils" in (* locate src/facebook/utils/dune *) let fb_dune = Filename.concat fb_utils_dir "dune" in let is_fb = Sys.file_exists fb_dune in let lib_name = entry is_fb "flytrap" in Jbuild_plugin.V1.send lib_name
hhvm/hphp/hack/src/stubs/logging/dune
(library (name logging_stubs) (wrapped false) (modules featureLogging hackEventLogger hackcEventLogger hackfmtEventLogger typingLogger) )
OCaml
hhvm/hphp/hack/src/stubs/logging/featureLogging.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. * *) module Lambda = struct let contextual_params = "" let explicit_params = "" let no_params = "" let non_function_typed_context = "" let non_strict_unknown_params = "" let untyped_context = "" let unknown_params = "" let unknown_params_with_uses _ = "" let fresh_tyvar_params = "" end
OCaml
hhvm/hphp/hack/src/stubs/logging/hackcEventLogger.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. * *) let init _ = () let init_sync _ = () let success ~filename:_ ~parsing_t:_ ~codegen_t:_ ~printing_t:_ ~mode:_ = () let fail ~filename:_ ~mode:_ ~exc:_ = () let log_peak_mem ~filename:_ _vm_rss _vm_hwm _action = ()
OCaml
hhvm/hphp/hack/src/stubs/logging/hackEventLogger.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module PerFileProfilingConfig = struct type profile_decling = | DeclingOff | DeclingTopCounts | DeclingAllTelemetry of { callstacks: bool } type t = { profile_log: bool; profile_type_check_duration_threshold: float; profile_type_check_memory_threshold_mb: int; profile_type_check_twice: bool; profile_decling: profile_decling; profile_owner: string option; profile_desc: string option; profile_slow_threshold: float; } let default = { profile_log = false; profile_type_check_duration_threshold = 0.05 (* seconds *); profile_type_check_memory_threshold_mb = 100; profile_type_check_twice = false; profile_decling = DeclingOff; profile_owner = None; profile_desc = None; profile_slow_threshold = 0.; } end type serialized_globals = Serialized_globals let serialize_globals () = Serialized_globals type rollout_flags = { log_saved_state_age_and_distance: bool; fetch_remote_old_decls: bool; ide_max_num_decls: int; ide_max_num_shallow_decls: int; max_typechecker_worker_memory_mb: int; max_workers: int; use_max_typechecker_worker_memory_for_decl_deferral: bool; specify_manifold_api_key: bool; populate_member_heaps: bool; shm_use_sharded_hashtbl: bool; shm_cache_size: int; remote_old_decls_no_limit: bool; use_manifold_cython_client: bool; disable_naming_table_fallback_loading: bool; use_type_alias_heap: bool; override_load_state_natively: bool; use_server_revision_tracker_v2: bool; rust_provider_backend: bool; use_hh_distc_instead_of_hulk: bool; consume_streaming_errors: bool; hh_distc_fanout_threshold: int; rust_elab: bool; ide_load_naming_table_on_disk: bool; ide_naming_table_update_threshold: int; ide_batch_process_changes: bool; use_compressed_dep_graph: bool; glean_v2: bool; } let flush () = () let deserialize_globals _ = () let set_use_watchman _ = () let set_use_full_fidelity_parser _ = () let set_search_chunk_size _ = () let set_changed_mergebase _ = () let set_from _ = () let set_hhconfig_version _ = () let set_rollout_group _ = () let set_rollout_flags _ = () let typechecker_exit _ _ _ ~exit_type:_ ~exit_code:_ ~exit_status:_ ~is_oom:_ = () let init ~root:_ ~hhconfig_version:_ ~init_id:_ ~custom_columns:_ ~informant_managed:_ ~rollout_flags:_ ~rollout_group:_ ~time:_ ~max_workers:_ ~per_file_profiling:_ = () let init_worker ~root:_ ~hhconfig_version:_ ~init_id:_ ~custom_columns:_ ~rollout_flags:_ ~rollout_group:_ ~time:_ ~per_file_profiling:_ = () let init_monitor ~from:_ ~custom_columns:_ ~proc_stack:_ ~hhconfig_version:_ ~rollout_flags:_ ~rollout_group:_ _ _ _ = () let init_batch_tool ~init_id:_ ~root:_ ~time:_ = () let starting_first_server _ = () let refuse_to_restart_server ~reason:_ ~server_state:_ ~version_matches:_ = () let server_receipt_to_monitor_write_exn ~server_receipt_to_monitor_file:_ _ = () let server_receipt_to_monitor_read_exn ~server_receipt_to_monitor_file:_ _ _ = () let init_lazy_end _ ~approach_name:_ ~init_error:_ ~init_type:_ = () let server_is_partially_ready () = () let server_is_ready _ = () let load_deptable_end _ = () let saved_state_download_and_load_done ~load_state_approach:_ ~success:_ ~state_result:_ _ = () let tried_to_be_hg_aware_with_precomputed_saved_state_warning _ = () let tried_to_load_non_existant_compressed_dep_graph _ = () let init_start ~experiments_config_meta:_ _ = () let nfs_root _ = () let load_state_worker_end ~is_cached:_ _ _ = () let vcs_changed_files_end _ _ = () let type_check_dirty ~start_t:_ ~dirty_count:_ ~recheck_count:_ = () let out_of_date _ = () let lock_stolen _ = () let client_init ~init_id:_ ~custom_columns:_ _ = () let serverless_ide_init ~init_id:_ = () let client_set_mode _ = () let serverless_ide_set_root _ = () let client_start _ = () let client_stop _ = () let client_restart ~data:_ = () let client_check_start () = () let client_check _ _ ~init_proc_stack:_ ~spinner:_ = () let client_check_partial _ _ ~init_proc_stack:_ ~spinner:_ = () let client_check_bad_exit _ _ ~init_proc_stack:_ ~spinner:_ = () let client_check_errors_file_restarted _ = () let client_lsp_method_handled ~root:_ ~method_:_ ~kind:_ ~path_opt:_ ~result_count:_ ~result_extra_telemetry:_ ~tracking_id:_ ~start_queue_time:_ ~start_hh_server_state:_ ~start_handle_time:_ ~serverless_ide_flag:_ = () let client_lsp_method_exception ~root:_ ~method_:_ ~kind:_ ~path_opt:_ ~tracking_id:_ ~start_queue_time:_ ~start_hh_server_state:_ ~start_handle_time:_ ~message:_ ~data_opt:_ ~source:_ = () let serverless_ide_bug ~message:_ ~data:_ = () let client_lsp_exception ~root:_ ~message:_ ~data_opt:_ ~source:_ = () let serverless_ide_startup ?count:_ ~start_time:_ _ = () let serverless_ide_load_naming_table ~start_time:_ ~local_file_count:_ _ = () let serverless_ide_destroy_ok _ = () let serverless_ide_destroy_error _ _ _ = () let server_hung_up ~external_exit_status:_ ~client_exn:_ ~client_stack:_ ~server_exit_status:_ ~server_stack:_ ~server_msg:_ = () let client_bad_exit ~command_name:_ _ _ = () let glean_init ~reponame:_ ~init_time:_ ~prev_init_time:_ = () let glean_init_failure ~reponame:_ ~init_time:_ ~prev_init_time:_ ~e:_ = () let glean_query ~reponame:_ ~mode:_ ~start_time:_ ~glean_init_time:_ ~count:_ ~query:_ ~query_text:_ = () let glean_query_error ~reponame:_ ~mode:_ ~start_time:_ ~glean_init_time:_ ~query:_ ~query_text:_ ~e:_ = () let glean_fetch_namespaces ~count:_ ~start_time:_ = () let glean_fetch_namespaces_error _ = () let ranked_autocomplete_duration ~start_time:_ = () let ranked_autocomplete_request_duration ~start_time:_ = () let monitor_dead_but_typechecker_alive () = () let spinner_heartbeat _ ~spinner:_ = () let spinner_change ~spinner:_ ~next:_ = () let client_established_connection _ = () let client_connect_once ~t_start:_ = () let client_connect_once_failure ~t_start:_ _ _ = () let client_connect_to_monitor_slow_log () = () let client_connect_autostart () = () let check_response _ = () let got_client_channels _ = () let get_client_channels_exception _ = () let got_persistent_client_channels _ = () let get_persistent_client_channels_exception _ = () let handled_connection _ = () let handle_connection_exception _ _ = () let handled_persistent_connection _ = () let handle_persistent_connection_exception _ _ ~is_fatal:_ = () let server_file_edited_error ~reason:_ _ = () let handled_command _ ~start_t:_ ~major_gc_time:_ ~minor_gc_time:_ ~parsed_files:_ = () let remote_scheduler_get_dirty_files_end _ _ = () let remote_scheduler_update_dependency_graph_end ~edges:_ _ = () let remote_scheduler_save_naming_end _ = () let credentials_check_failure _ _ = () let credentials_check_end _ _ = () let remote_worker_type_check_end _ ~start_t:_ = () let remote_worker_load_naming_end _ = () let recheck_end ~last_recheck_duration:_ ~update_batch_count:_ ~total_changed_files:_ ~total_rechecked:_ _ = () let indexing_end ~desc:_ _ = () let parsing_end _ _ ~parsed_count:_ = () let parsing_end_for_init _ _ ~parsed_count:_ ~desc:_ = () let parsing_end_for_typecheck _ _ ~parsed_count:_ = () let naming_costly_iter ~start_t:_ = () let naming_end ~count:_ _ _ = () let global_naming_end ~count:_ ~desc:_ ~heap_size:_ ~start_t:_ = () let run_search_end _ = () let update_search_end _ _ = () let naming_from_saved_state_end _ = () let naming_sqlite_local_changes_nonempty _ = () let naming_sqlite_has_changes_since_baseline _ = () let type_decl_end _ = () let remote_old_decl_end _ _ = () let first_redecl_end _ _ = () let second_redecl_end _ _ = () let type_check_primary_position_bug ~current_file:_ ~message:_ ~stack:_ = () let type_check_exn_bug ~path:_ ~pos:_ ~e:_ = () let invariant_violation_bug ?path:_ ?pos:_ ?data:_ ?data_int:_ ?telemetry:_ _ = () let decl_consistency_bug ?path:_ ?pos:_ ?data:_ _ = () let live_squiggle_diff ~uri:_ ~reason:_ ~expected_error_count:_ _ = () let type_check_end _ ~heap_size:_ ~started_count:_ ~total_rechecked_count:_ ~desc:_ ~experiments:_ ~start_t:_ = () let notifier_returned _ _ = () let load_state_exn _ = () let naming_table_sqlite_missing _ = () let prechecked_update_rechecked _ = () let prechecked_evaluate_init _ _ = () let prechecked_evaluate_incremental _ _ = () let check_mergebase_failed _ _ = () let check_mergebase_success _ = () let type_at_pos_batch ~start_time:_ ~num_files:_ ~num_positions:_ ~results:_ = () let worker_large_data_send ~path:_ _ = () let with_id ~stage:_ _ f = f () let with_rechecked_stats ~update_batch_count:_ ~total_changed_files:_ ~total_rechecked:_ f = f () let with_init_type _ f = f () let with_check_kind ~check_kind:_ ~check_reason:_ f = f () let state_loader_dirty_files _ = () let changed_while_parsing_end _ = () let saved_state_load_ok _ ~start_time:_ = () let saved_state_load_failure _ ~start_time:_ = () let saved_state_dirty_files_ok ~start_time:_ = () let saved_state_dirty_files_failure _ ~start_time:_ = () let saved_state_load_naming_table_on_disk _ ~start_time:_ = () let monitor_update_status _ _ = () let find_svn_rev_failed _ _ = () let revision_tracker_init_svn_rev_failed _ = () (** Watchman Event Watcher client running in the informant *) let informant_watcher_not_available _ = () let informant_watcher_unknown_state _ = () let informant_watcher_mid_update_state _ = () let informant_watcher_settled_state _ = () let informant_watcher_starting_server_from_settling _ = () (** Server Monitor events *) let accepting_on_socket_exception _ = () let malformed_build_id _ = () let send_fd_failure _ = () let typechecker_already_running _ = () (** Watchman Event Watcher events *) let init_watchman_event_watcher _ _ = () let init_watchman_failed _ = () let restarting_watchman_subscription _ = () let watchman_uncaught_exception _ = () let monitor_giving_up_exception _ = () let processed_clients _ = () let invalid_mercurial_state_transition ~state:_ = () let server_revision_tracker_forced_reset ~telemetry:_ = () let search_symbol_index ~query_text:_ ~max_results:_ ~results:_ ~kind_filter:_ ~duration:_ ~caller:_ ~search_provider:_ = () let shallow_decl_errors_emitted _ = () let server_progress_write_exn ~server_progress_file:_ _ = () let server_progress_read_exn ~server_progress_file:_ _ = () let worker_exception _ = () (* Typing service events. *) let hulk_type_check_end _ _ ~start_t:_ = () module ProfileTypeCheck = struct type stats = unit type batch_info = unit type typecheck_info = unit let get_stats ~include_current_process:_ ~include_slightly_costly_stats:_ ~shmem_heap_size:_ _ = () let get_typecheck_info ~init_id:_ ~check_reason:_ ~recheck_id:_ ~start_hh_stats:_ ~start_typecheck_stats:_ ~config:_ = () let get_batch_info ~typecheck_info:_ ~worker_id:_ ~batch_number:_ ~batch_size:_ ~start_batch_stats:_ = () let process_workitem ~batch_info:_ ~workitem_index:_ ~file:_ ~file_was_already_deferred:_ ~decl:_ ~error_code:_ ~workitem_ends_under_cap:_ ~workitem_start_stats:_ ~workitem_end_stats:_ ~workitem_end_second_stats:_ = () let compute_tast ~path:_ ~telemetry:_ ~start_time:_ = () end module CGroup = struct let error _ = () let step ~cgroup:_ ~step_group:_ ~step:_ ~start_time:_ ~total_relative_to:_ ~anon_relative_to:_ ~shmem_relative_to:_ ~file_relative_to:_ ~total_start:_ ~anon_start:_ ~shmem_start:_ ~file_start:_ ~total_hwm:_ ~total:_ ~anon:_ ~shmem:_ ~file:_ ~secs_at_total_gb:_ ~secs_above_total_gb_summary:_ = () end module Memory = struct let profile_if_needed () = () end module ProfileDecl = struct let count_decl ~kind:_ ~cpu_duration:_ ~decl_id:_ ~decl_name:_ ~decl_origin:_ ~decl_file:_ ~decl_callstack:_ ~decl_start_time:_ ~subdecl_member_name:_ ~subdecl_eagerness:_ ~subdecl_callstack:_ ~subdecl_start_time:_ = () end module Rage = struct let rage_start ~rageid:_ ~desc:_ ~root:_ ~from:_ ~disk_config:_ = () let rage_watchman ~rageid:_ ~items:_ = () let rage ~rageid:_ ~desc:_ ~vscode_bugid:_ ~merged_logs:_ ~root:_ ~from:_ ~hhconfig_version:_ ~disk_config:_ ~experiments:_ ~experiments_config_meta:_ ~items:_ ~result:_ ~start_time:_ = () end module Fanouts = struct let log_class ~class_name:_ ~class_diff:_ ~class_diff_category:_ ~fanout_cardinal:_ ~direct_references_cardinal:_ ~descendants_cardinal:_ ~children_cardinal:_ = () let log ~changes_cardinal:_ ~fanout_cardinal:_ ~max_class_fanout_cardinal:_ = () end
OCaml
hhvm/hphp/hack/src/stubs/logging/hackfmtEventLogger.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. * *) let init _ = () let exit ~time_taken:_ ~error:_ ~exit_code:_ ~mode:_ ~file:_ ~root:_ = () let format_tree_end ~start_t:_ ~end_t:_ ~mode:_ ~file:_ ~root:_ = () let format_range_end ~start_t:_ ~end_t:_ ~mode:_ ~file:_ ~root:_ = () let format_intervals_end ~start_t:_ ~end_t:_ ~mode:_ ~file:_ ~root:_ = () let format_at_offset_end ~start_t:_ ~end_t:_ ~mode:_ ~file:_ ~root:_ = ()
OCaml
hhvm/hphp/hack/src/stubs/logging/typingLogger.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module InferenceCnstr = struct let log _ ~pos:_ ~size:_ ~n_disj:_ ~n_conj:_ = () end let flush_buffers _ = ()
OCaml
hhvm/hphp/hack/src/stubs/logging/common/eventLogger.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type init_settings = { scuba_table_name: string; (* File descriptors for the logger daemon's stdout and stderr. *) log_out: Unix.file_descr; log_err: Unix.file_descr; } type init_mode = (* Sends everything to /dev/null. *) | Event_logger_fake | Event_logger_real of init_settings let init ?log_pid:_ ?init_id:_ _ _ = () let init_fake () = () let disable_logging _ = () let log _ = () let log_subsampling ?subsample_key:_ ?max_tolerable_long_term_interval:_ ?max_tolerable_short_term_spike:_ ?logger:_ ?now:_ _ = () let logger_pid () = None let set_init_type _ = () let log_if_initialized _ = () let sharedmem_gc_ran _ _ _ _ = () let sharedmem_init_done _ = () let sharedmem_failed_anonymous_memfd_init _ = () let sharedmem_failed_to_use_shm_dir ~shm_dir:_ ~reason:_ = () let sharedmem_less_than_minimum_available ~shm_dir:_ ~shm_min_avail:_ ~avail:_ = () let sharedmem_access_sample ~heap_name:_ ~key:_ ~write_time:_ = () let find_done ~time_taken:_ ~name:_ = () let log_gc_stats () = () let flush _ = () let watchman_error _ = () let watchman_warning _ = () let watchman_died_caught _ = () let watchman_uncaught_failure _ = () let watchman_connection_reestablished _ = () let watchman_connection_reestablishment_failed _ = () let watchman_timeout _ = () let dfind_ready _ _ = () let recheck_disk_files () = ()
OCaml
hhvm/hphp/hack/src/stubs/logging/common/eventLoggerLwt.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) let flush () = Lwt.return_unit
OCaml
hhvm/hphp/hack/src/stubs/logging/common/scuba.ml
(** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module Table = struct let of_name _ = () end let new_sample _ _ = () let add_int _ _ _ = () let add_normal _ _ _ = () let add_denorm _ _ _ = () let add_normvector _ _ _ = () let add_tags _ _ _ = ()
hhvm/hphp/hack/src/substitution_mutation/dune
(library (name substitution_mutation) (wrapped false) (flags (:standard -linkall)) (modules substitution_mutation) (libraries core_kernel annotated_ast naming_special_names) (preprocess (pps visitors.ppx ppx_deriving.std)))
OCaml
hhvm/hphp/hack/src/substitution_mutation/substitution_mutation.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 A = Aast let tparam_id tparam = snd tparam.A.tp_name let mutate_type_hint tparam_mapping (hint : 'a A.type_hint) = (* TODO: The implementation is shallow. Use a visitor to deeply replace type hints. *) match hint with | (ann, Some (_, A.Happly ((pos, id), []))) | (ann, Some (pos, A.Habstr (id, _))) -> begin match SMap.find_opt id tparam_mapping with | Some hint_ -> (ann, Some (pos, hint_)) | None -> hint end | hint -> hint let mutate_param tparam_mapping param = let param_type_hint = mutate_type_hint tparam_mapping param.A.param_type_hint in A.{ param with param_type_hint } let mutate_tparams tparams = let default_hint = A.(Hprim Tint) in let eliminate_tparam (tparams, mapping) tparam = (* TODO: Respect the bounds on the type parameter *) let mapping = SMap.add (tparam_id tparam) default_hint mapping in (tparams, mapping) in List.fold ~init:([], SMap.empty) ~f:eliminate_tparam tparams let mutate_fun_def fd = let fun_ = fd.A.fd_fun in let (fd_tparams, tparam_mapping) = mutate_tparams fd.A.fd_tparams in let f_params = List.map ~f:(mutate_param tparam_mapping) fun_.A.f_params in let f_ret = mutate_type_hint tparam_mapping fun_.A.f_ret in let fd_fun = A.{ fun_ with f_params; f_ret } in A.{ fd with fd_fun; fd_tparams }
OCaml Interface
hhvm/hphp/hack/src/substitution_mutation/substitution_mutation.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 mutate_fun_def : ('a, 'b) Aast.fun_def -> ('a, 'b) Aast.fun_def
hhvm/hphp/hack/src/third-party/avl/LICENSE
In the following, "the Library" refers to all files marked "Copyright INRIA" this directory. The Library is distributed under the terms of the GNU Library General Public License version 2 (included below). As a special exception to the GNU Library General Public License, you may link, statically or dynamically, a "work that uses the Library" with a publicly distributed version of the Library to produce an executable file containing portions of the Library, and distribute that executable file under terms of your choice, without any of the additional requirements listed in clause 6 of the GNU Library General Public License. By "a publicly distributed version of the Library", we mean either the unmodified Library as distributed by INRIA, or a modified version of the Library that is distributed under the conditions defined in clause 2 of the GNU Library General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU Library General Public License. ---------------------------------------------------------------------- GNU LIBRARY GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1991 Free Software Foundation, Inc. 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the library GPL. It is numbered 2 because it goes with version 2 of the ordinary GPL.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Library General Public License, applies to some specially designated Free Software Foundation software, and to any other libraries whose authors decide to use it. You can use it for your libraries, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library, or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link a program with the library, you must provide complete object files to the recipients so that they can relink them with the library, after making changes to the library and recompiling it. And you must show them these terms so they know their rights. Our method of protecting your rights has two steps: (1) copyright the library, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the library. Also, for each distributor's protection, we want to make certain that everyone understands that there is no warranty for this free library. If the library is modified by someone else and passed on, we want its recipients to know that what they have is not the original version, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that companies distributing free software will individually obtain patent licenses, thus in effect transforming the program into proprietary software. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License, which was designed for utility programs. This license, the GNU Library General Public License, applies to certain designated libraries. This license is quite different from the ordinary one; be sure to read it in full, and don't assume that anything in it is the same as in the ordinary license. The reason we have a separate public license for some libraries is that they blur the distinction we usually make between modifying or adding to a program and simply using it. Linking a program with a library, without changing the library, is in some sense simply using the library, and is analogous to running a utility program or application program. However, in a textual and legal sense, the linked executable is a combined work, a derivative of the original library, and the ordinary General Public License treats it as such. Because of this blurred distinction, using the ordinary General Public License for libraries did not effectively promote software sharing, because most developers did not use the libraries. We concluded that weaker conditions might promote sharing better. However, unrestricted linking of non-free programs would deprive the users of those programs of all benefit from the free status of the libraries themselves. This Library General Public License is intended to permit developers of non-free programs to use free libraries, while preserving your freedom as a user of such programs to change the free libraries that are incorporated in them. (We have not seen how to achieve this as regards changes in header files, but we have achieved it as regards changes in the actual functions of the Library.) The hope is that this will lead to faster development of free libraries. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, while the latter only works together with the library. Note that it is possible for a library to be covered by the ordinary General Public License rather than by this special one. GNU LIBRARY GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Library General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also compile or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. c) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. d) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Library General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the library's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. <signature of Ty Coon>, 1 April 1990 Ty Coon, President of Vice That's all there is to it!
OCaml
hhvm/hphp/hack/src/third-party/avl/monoidAvl.ml
(***********************************************************************) (* *) (* Objective Caml *) (* *) (* Xavier Leroy, projet Cristal, INRIA Rocquencourt *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. All rights reserved. This file is distributed *) (* under the terms of the GNU Library General Public License, with *) (* the special exception on linking described in file LICENSE. *) (* *) (***********************************************************************) (* This code has been copy/pasted from the OCaml standard library. * There is only a slight modification. * Every element of the Avl tree is augmented with an additional element * of a monoid. * During all the operations on the tree, the element of the monoid * is maintained, the composition is always from left to right. * So if you have the tree ((0, Empty, Empty), 34, (45, Empty, Empty) * The "augmented tree" will look like this: * (make 0, 0, Empty, Empty), * (compose (make 0) (compose ((make 34) (make 45)))), 34, * (make 34, 45, Empty, Empty) * * We need this data-structure to quickly scan a tree. * We want 2 operations to be fast: * 1) add a file with a timestamp to the tree * 2) fetch all the files younger than time t * * The element of the monoid is helping us to make 2) fast. * Our composition function is "max", this way for any given * node we know how old the youngest element in a node is. * If the youngest element is too old, we can cut the branch. * (cf function walk in monoidAvl.ml) *) module type MonoidOrderedType = sig type elt val compare : elt -> elt -> int type monoelt val neutral : monoelt (* This better be associative *) val compose : monoelt -> monoelt -> monoelt val make : elt -> monoelt end module type S = sig type elt type monoelt type t val empty : t val is_empty : t -> bool val mem : elt -> t -> bool val add : elt -> t -> t val singleton : elt -> t val remove : elt -> t -> t val union : t -> t -> t val inter : t -> t -> t val diff : t -> t -> t val compare : t -> t -> int val equal : t -> t -> bool val subset : t -> t -> bool val iter : (elt -> unit) -> t -> unit val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a val for_all : (elt -> bool) -> t -> bool val exists : (elt -> bool) -> t -> bool val filter : (elt -> bool) -> t -> t val partition : (elt -> bool) -> t -> t * t val cardinal : t -> int val elements : t -> elt list val min_elt : t -> elt val max_elt : t -> elt val choose : t -> elt val split : elt -> t -> t * bool * t val walk : (monoelt -> bool) -> (elt -> unit) -> t -> unit end module Make (Ord : MonoidOrderedType) = struct type elt = Ord.elt type monoelt = Ord.monoelt type t = | Empty | Node of monoelt * t * elt * t * int let height = function | Empty -> 0 | Node (_, _, _, _, h) -> h let get_monoelt = function | Empty -> Ord.neutral | Node (x, _, _, _, _) -> x let create l v r = let hl = match l with | Empty -> 0 | Node (_, _, _, _, h) -> h in let hr = match r with | Empty -> 0 | Node (_, _, _, _, h) -> h in let monoelt = Ord.make v in let monoelt = Ord.compose (get_monoelt l) monoelt in let monoelt = Ord.compose monoelt (get_monoelt r) in Node ( monoelt, l, v, r, if hl >= hr then hl + 1 else hr + 1 ) let bal l v r = let hl = match l with | Empty -> 0 | Node (_, _, _, _, h) -> h in let hr = match r with | Empty -> 0 | Node (_, _, _, _, h) -> h in if hl > hr + 2 then match l with | Empty -> invalid_arg "Set.bal" | Node (_, ll, lv, lr, _) -> if height ll >= height lr then create ll lv (create lr v r) else ( match lr with | Empty -> invalid_arg "Set.bal" | Node (_, lrl, lrv, lrr, _) -> create (create ll lv lrl) lrv (create lrr v r) ) else if hr > hl + 2 then match r with | Empty -> invalid_arg "Set.bal" | Node (_, rl, rv, rr, _) -> if height rr >= height rl then create (create l v rl) rv rr else ( match rl with | Empty -> invalid_arg "Set.bal" | Node (_, rll, rlv, rlr, _) -> create (create l v rll) rlv (create rlr rv rr) ) else create l v r let rec add x = function | Empty -> Node (Ord.make x, Empty, x, Empty, 1) | Node (_, l, v, r, _) -> let c = Ord.compare x v in if c = 0 then create l x r else if c < 0 then bal (add x l) v r else bal l v (add x r) let rec join l v r = match (l, r) with | (Empty, _) -> add v r | (_, Empty) -> add v l | (Node (_, ll, lv, lr, lh), Node (_, rl, rv, rr, rh)) -> if lh > rh + 2 then bal ll lv (join lr v r) else if rh > lh + 2 then bal (join l v rl) rv rr else create l v r let rec min_elt = function | Empty -> raise Not_found | Node (_, Empty, v, _, _) -> v | Node (_, l, _, _, _) -> min_elt l let rec max_elt = function | Empty -> raise Not_found | Node (_, _, v, Empty, _) -> v | Node (_, _, _, r, _) -> max_elt r let rec remove_min_elt = function | Empty -> invalid_arg "Set.remove_min_elt" | Node (_, Empty, _, r, _) -> r | Node (_, l, v, r, _) -> bal (remove_min_elt l) v r let merge t1 t2 = match (t1, t2) with | (Empty, t) -> t | (t, Empty) -> t | (_, _) -> bal t1 (min_elt t2) (remove_min_elt t2) let concat t1 t2 = match (t1, t2) with | (Empty, t) -> t | (t, Empty) -> t | (_, _) -> join t1 (min_elt t2) (remove_min_elt t2) let rec split x = function | Empty -> (Empty, false, Empty) | Node (_, l, v, r, _) -> let c = Ord.compare x v in if c = 0 then (l, true, r) else if c < 0 then let (ll, pres, rl) = split x l in (ll, pres, join rl v r) else let (lr, pres, rr) = split x r in (join l v lr, pres, rr) let empty = Empty let is_empty = function | Empty -> true | _ -> false let rec mem x = function | Empty -> false | Node (_, l, v, r, _) -> let c = Ord.compare x v in c = 0 || mem x ( if c < 0 then l else r ) let singleton x = Node (Ord.make x, Empty, x, Empty, 1) let rec remove x = function | Empty -> Empty | Node (_, l, v, r, _) -> let c = Ord.compare x v in if c = 0 then merge l r else if c < 0 then bal (remove x l) v r else bal l v (remove x r) let rec union s1 s2 = match (s1, s2) with | (Empty, t2) -> t2 | (t1, Empty) -> t1 | (Node (_, l1, v1, r1, h1), Node (_, l2, v2, r2, h2)) -> if h1 >= h2 then if h2 = 1 then add v2 s1 else let (l2, _, r2) = split v1 s2 in join (union l1 l2) v1 (union r1 r2) else if h1 = 1 then add v1 s2 else let (l1, _, r1) = split v2 s1 in join (union l1 l2) v2 (union r1 r2) let rec inter s1 s2 = match (s1, s2) with | (Empty, _) -> Empty | (_, Empty) -> Empty | (Node (_, l1, v1, r1, _), t2) -> (match split v1 t2 with | (l2, false, r2) -> concat (inter l1 l2) (inter r1 r2) | (l2, true, r2) -> join (inter l1 l2) v1 (inter r1 r2)) let rec diff s1 s2 = match (s1, s2) with | (Empty, _) -> Empty | (t1, Empty) -> t1 | (Node (_, l1, v1, r1, _), t2) -> (match split v1 t2 with | (l2, false, r2) -> join (diff l1 l2) v1 (diff r1 r2) | (l2, true, r2) -> concat (diff l1 l2) (diff r1 r2)) type enumeration = | End | More of elt * t * enumeration let rec cons_enum s e = match s with | Empty -> e | Node (_, l, v, r, _) -> cons_enum l (More (v, r, e)) let rec compare_aux e1 e2 = match (e1, e2) with | (End, End) -> 0 | (End, _) -> -1 | (_, End) -> 1 | (More (v1, r1, e1), More (v2, r2, e2)) -> let c = Ord.compare v1 v2 in if c <> 0 then c else compare_aux (cons_enum r1 e1) (cons_enum r2 e2) let compare s1 s2 = compare_aux (cons_enum s1 End) (cons_enum s2 End) let equal s1 s2 = compare s1 s2 = 0 let rec subset s1 s2 = match (s1, s2) with | (Empty, _) -> true | (_, Empty) -> false | (Node (_, l1, v1, r1, _), (Node (_, l2, v2, r2, _) as t2)) -> let c = Ord.compare v1 v2 in if c = 0 then subset l1 l2 && subset r1 r2 else if c < 0 then let node = create l1 v1 Empty in subset node l2 && subset r1 t2 else let node = create Empty v1 r1 in subset node r2 && subset l1 t2 let rec iter f = function | Empty -> () | Node (_, l, v, r, _) -> iter f l; f v; iter f r let rec fold f s accu = match s with | Empty -> accu | Node (_, l, v, r, _) -> fold f r (f v (fold f l accu)) let rec for_all p = function | Empty -> true | Node (_, l, v, r, _) -> p v && for_all p l && for_all p r let rec exists p = function | Empty -> false | Node (_, l, v, r, _) -> p v || exists p l || exists p r let filter p s = let rec filt accu = function | Empty -> accu | Node (_, l, v, r, _) -> filt (filt ( if p v then add v accu else accu ) l) r in filt Empty s let partition p s = let rec part ((t, f) as accu) = function | Empty -> accu | Node (_, l, v, r, _) -> part (part ( if p v then (add v t, f) else (t, add v f) ) l) r in part (Empty, Empty) s let rec cardinal = function | Empty -> 0 | Node (_, l, _, r, _) -> cardinal l + 1 + cardinal r let rec elements_aux accu = function | Empty -> accu | Node (_, l, v, r, _) -> elements_aux (v :: elements_aux accu r) l let elements s = elements_aux [] s let choose = min_elt let rec walk cut_branch work t = match t with | Empty -> () | Node (elt, _, _, _, _) when cut_branch elt -> () | Node (_, l, key, r, _) -> walk cut_branch work l; if cut_branch (Ord.make key) then () else work key; walk cut_branch work r end
OCaml Interface
hhvm/hphp/hack/src/third-party/avl/monoidAvl.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) (* Xavier Leroy, projet Cristal, INRIA Rocquencourt *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. All rights reserved. This file is distributed *) (* under the terms of the GNU Library General Public License, with *) (* the special exception on linking described in file LICENSE. *) (* *) (***********************************************************************) (* This code has been copy/pasted from the OCaml standard library. * There is only a slight modification. * Every element of the Avl tree is augmented with an additional element * of a monoid. * During all the operations on the tree, the element of the monoid * is maintained, the composition is always from left to right. * So if you have the tree ((0, Empty, Empty), 34, (45, Empty, Empty) * The "augmented tree" will look like this: * (make 0, 0, Empty, Empty), * (compose (make 0) (compose ((make 34) (make 45)))), 34, * (make 34, 45, Empty, Empty) * * We need this data-structure to quickly scan a tree. * We want 2 operations to be fast: * 1) add a file with a timestamp to the tree * 2) fetch all the files younger than time t * * The element of the monoid is helping us to make 2) fast. * Our composition function is "max", this way for any given * node we know how old the youngest element in a node is. * If the youngest element is too old, we can cut the branch. * (cf function walk in monoidAvl.ml) *) module type MonoidOrderedType = sig type elt val compare : elt -> elt -> int type monoelt val neutral : monoelt val compose : monoelt -> monoelt -> monoelt val make : elt -> monoelt end module type S = sig type elt type monoelt type t val empty : t val is_empty : t -> bool val mem : elt -> t -> bool val add : elt -> t -> t val singleton : elt -> t val remove : elt -> t -> t val union : t -> t -> t val inter : t -> t -> t val diff : t -> t -> t val compare : t -> t -> int val equal : t -> t -> bool val subset : t -> t -> bool val iter : (elt -> unit) -> t -> unit val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a val for_all : (elt -> bool) -> t -> bool val exists : (elt -> bool) -> t -> bool val filter : (elt -> bool) -> t -> t val partition : (elt -> bool) -> t -> t * t val cardinal : t -> int val elements : t -> elt list val min_elt : t -> elt val max_elt : t -> elt val choose : t -> elt val split : elt -> t -> t * bool * t val walk : (monoelt -> bool) -> (elt -> unit) -> t -> unit end module Make (Ord : MonoidOrderedType) : S with type elt = Ord.elt with type monoelt = Ord.monoelt
OCaml
hhvm/hphp/hack/src/third-party/inotify/inotify.ml
(* * Copyright (C) 2006-2008 Vincent Hanquez <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * Inotify OCaml binding *) type selector = | S_Access | S_Attrib | S_Close_write | S_Close_nowrite | S_Create | S_Delete | S_Delete_self | S_Modify | S_Move_self | S_Moved_from | S_Moved_to | S_Open | S_Dont_follow | S_Mask_add | S_Oneshot | S_Onlydir (* convenience *) | S_Move | S_Close | S_All type event_kind = | Access | Attrib | Close_write | Close_nowrite | Create | Delete | Delete_self | Modify | Move_self | Moved_from | Moved_to | Open | Ignored | Isdir | Q_overflow | Unmount let string_of_event_kind = function | Access -> "ACCESS" | Attrib -> "ATTRIB" | Close_write -> "CLOSE_WRITE" | Close_nowrite -> "CLOSE_NOWRITE" | Create -> "CREATE" | Delete -> "DELETE" | Delete_self -> "DELETE_SELF" | Modify -> "MODIFY" | Move_self -> "MOVE_SELF" | Moved_from -> "MOVED_FROM" | Moved_to -> "MOVED_TO" | Open -> "OPEN" | Ignored -> "IGNORED" | Isdir -> "ISDIR" | Q_overflow -> "Q_OVERFLOW" | Unmount -> "UNMOUNT" type watch = int type event = watch * event_kind list * int32 * string option external create : unit -> Unix.file_descr = "caml_inotify_init" external add_watch : Unix.file_descr -> string -> selector list -> watch = "caml_inotify_add_watch" external rm_watch : Unix.file_descr -> watch -> unit = "caml_inotify_rm_watch" external convert : Bytes.t -> watch * event_kind list * int32 * int = "caml_inotify_convert" external struct_size : unit -> int = "caml_inotify_struct_size" external name_max : unit -> int = "caml_inotify_name_max" let int_of_watch watch = watch let watch_of_int watch = watch let string_of_event (watch, events, cookie, name) = Printf.sprintf "watch=%d cookie=%ld events=%s%s" watch cookie (String.concat "|" (List.map string_of_event_kind events)) (match name with | None -> "" | Some name' -> Printf.sprintf " %S" name') let read fd = (* Turns out that reading from blocking descriptors always requires a buffer of the maximum size, which is, from the inotify man page: The behavior when the buffer given to read(2) is too small to return information about the next event depends on the kernel version: in kernels before 2.6.21, read(2) returns 0; since kernel 2.6.21, read(2) fails with the error EINVAL. Specifying a buffer of size sizeof(struct inotify_event) + NAME_MAX + 1 *) let event_size = struct_size () in let buf_size = event_size + name_max () + 1 in let buf = Bytes.create buf_size in let bytes_read = Unix.read fd buf 0 buf_size in let read_c_string pos = Bytes.sub_string buf pos (Bytes.index_from buf pos '\x00' - pos) in let rec read_one pos rest = if bytes_read < pos + event_size then rest else let (watch, mask, cookie, len) = convert (Bytes.sub buf pos event_size) in if bytes_read < pos + event_size + len then rest else let name = if len > 0 then Some (read_c_string (pos + event_size)) else None in read_one (pos + event_size + len) ((watch, mask, cookie, name) :: rest) in List.rev (read_one 0 [])
OCaml Interface
hhvm/hphp/hack/src/third-party/inotify/inotify.mli
(* * Copyright (C) 2006-2008 Vincent Hanquez <[email protected]> * Copyright (C) 2014 Peter Zotov <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * *) (** Inotify binding for OCaml @see <http://man7.org/linux/man-pages/man7/inotify.7.html> Inotify manual page *) (** Type of event masks. *) type selector = | S_Access | S_Attrib | S_Close_write | S_Close_nowrite | S_Create | S_Delete | S_Delete_self | S_Modify | S_Move_self | S_Moved_from | S_Moved_to | S_Open | S_Dont_follow | S_Mask_add | S_Oneshot | S_Onlydir | S_Move | S_Close | S_All (** Type of observed events. *) type event_kind = | Access | Attrib | Close_write | Close_nowrite | Create | Delete | Delete_self | Modify | Move_self | Moved_from | Moved_to | Open | Ignored | Isdir | Q_overflow | Unmount (** Type of watch descriptors. *) type watch (** Type of received events, corresponding to [struct inotify_event]. In event [wd, kinds, cookie, path], [wd] corresponds to [inotify_event.wd], [kinds] corresponds to the bits set in [inotify_event.mask], [cookie] corresponds to [inotify_event.cookie], [path] is [Some filename] if [inotify_event.len > 0] and [None] otherwise. *) type event = watch * event_kind list * int32 * string option (** [int_of_watch wd] returns the underlying integer representation of watch descriptor [wd]. *) val int_of_watch : watch -> int (**/**) (* [watch_of_int i] is the {!watch} corresponding to the integer [i]. It violates the construction privacy of the {!watch} type but is useful when using {!event} as a network portable type. *) val watch_of_int : int -> watch (**/**) (** [string_of_event_kind ek] returns the string representation of event kind [ek], e.g. [string_of_event_kind Move_self] ≡ ["MOVE_SELF"]. *) val string_of_event_kind : event_kind -> string (** [string_of_event event] returns the string representation of event [ev], e.g. [string_of_event] *) val string_of_event : event -> string (** [create ()] returns a fresh inotify file descriptor or raises [Unix.Unix_error(errno, "inotify_init", "")]. *) val create : unit -> Unix.file_descr (** [add_watch fd path events] starts observing events from [events] for path [path] at inotify file descriptor [fd] and returns a fresh watch descriptor, or raises [Unix.Unix_error(errno, "inotify_add_watch", path)]. *) val add_watch : Unix.file_descr -> string -> selector list -> watch (** [rm_watch fd watch] stops observing events corresponding to watch descriptor [watch] at inotify file descriptor [fd], or raises [Unix.Unix_error(errno, "inotify_rm_watch", path)]. *) val rm_watch : Unix.file_descr -> watch -> unit (** [read fd] requests a list of events for inotify file descriptor [fd]. Each event will include the watch descriptor, which can be used to determine the path that caused it, and [Moved_to] and [Moved_from] events will include a cookie that allows to associate them with each other. If {!read} is not called often enough, the kernel event buffer may overflow, in which case the event kind list will consist of [[Q_overflow]]. Such an event would be associated with a watch descriptor [-1], never returned from {!add_watch}. *) val read : Unix.file_descr -> event list
C
hhvm/hphp/hack/src/third-party/inotify/inotify_stubs.c
/* * Copyright (C) 2006-2008 Vincent Hanquez <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * Inotify Ocaml binding - C glue */ #include <errno.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <limits.h> #include <caml/mlvalues.h> #include <caml/memory.h> #include <caml/alloc.h> #include <caml/custom.h> #include <caml/fail.h> #include <caml/signals.h> #include <caml/callback.h> #include <caml/unixsupport.h> #include <sys/inotify.h> static int inotify_flag_table[] = { IN_ACCESS, IN_ATTRIB, IN_CLOSE_WRITE, IN_CLOSE_NOWRITE, IN_CREATE, IN_DELETE, IN_DELETE_SELF, IN_MODIFY, IN_MOVE_SELF, IN_MOVED_FROM, IN_MOVED_TO, IN_OPEN, IN_DONT_FOLLOW, IN_MASK_ADD, IN_ONESHOT, IN_ONLYDIR, IN_MOVE, IN_CLOSE, IN_ALL_EVENTS, 0 }; static int inotify_return_table[] = { IN_ACCESS, IN_ATTRIB, IN_CLOSE_WRITE, IN_CLOSE_NOWRITE, IN_CREATE, IN_DELETE, IN_DELETE_SELF, IN_MODIFY, IN_MOVE_SELF, IN_MOVED_FROM, IN_MOVED_TO, IN_OPEN, IN_IGNORED, IN_ISDIR, IN_Q_OVERFLOW, IN_UNMOUNT, 0 }; value caml_inotify_init(value unit) { CAMLparam1(unit); int fd = inotify_init(); if (fd == -1) uerror("inotify_init", Nothing); CAMLreturn(Val_int(fd)); } value caml_inotify_add_watch(value fd, value path, value selector_flags) { CAMLparam3(fd, path, selector_flags); int selector = caml_convert_flag_list(selector_flags, inotify_flag_table); int watch = inotify_add_watch(Int_val(fd), String_val(path), selector); if (watch == -1) uerror("inotify_add_watch", path); CAMLreturn(Val_int(watch)); } value caml_inotify_rm_watch(value fd, value watch) { CAMLparam2(fd, watch); int ret = inotify_rm_watch(Int_val(fd), Int_val(watch)); if (ret == -1) uerror("inotify_rm_watch", Nothing); CAMLreturn(Val_unit); } value caml_inotify_struct_size(void) { CAMLparam0(); CAMLreturn(Val_int(sizeof(struct inotify_event))); } value caml_inotify_name_max(void) { CAMLparam0(); CAMLreturn(Val_int(NAME_MAX)); } value caml_inotify_convert(value buf) { CAMLparam1(buf); CAMLlocal3(event, list, next); list = next = Val_emptylist; struct inotify_event ievent; memcpy(&ievent, String_val(buf), sizeof(struct inotify_event)); int flag; for (flag = 0; inotify_return_table[flag]; flag++) { if (!(ievent.mask & inotify_return_table[flag])) continue; next = caml_alloc_small(2, Tag_cons); Field(next, 0) = Val_int(flag); Field(next, 1) = list; list = next; } event = caml_alloc_tuple(4); Store_field(event, 0, Val_int(ievent.wd)); Store_field(event, 1, list); Store_field(event, 2, caml_copy_int32(ievent.cookie)); Store_field(event, 3, Val_int(ievent.len)); CAMLreturn(event); }
hhvm/hphp/hack/src/third-party/inotify/LICENSE
The Library is distributed under the terms of the GNU Library General Public License version 2.1 (included below). As a special exception to the GNU Library General Public License, you may link, statically or dynamically, a "work that uses the Library" with a publicly distributed version of the Library to produce an executable file containing portions of the Library, and distribute that executable file under terms of your choice, without any of the additional requirements listed in clause 6 of the GNU Library General Public License. By "a publicly distributed version of the Library", we mean either the unmodified Library as distributed, or a modified version of the Library that is distributed under the conditions defined in clause 3 of the GNU Library General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU Library General Public License. ------------ GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. one line to give the library's name and an idea of what it does. Copyright (C) year name of author This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. signature of Ty Coon, 1 April 1990 Ty Coon, President of Vice That's all there is to it!
C/C++
hhvm/hphp/hack/src/third-party/libancillary/ancillary.h
/*************************************************************************** * libancillary - black magic on Unix domain sockets * (C) Nicolas George * ancillary.c - public header ***************************************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ANCILLARY_H__ #define ANCILLARY_H__ /*************************************************************************** * Start of the readable part. ***************************************************************************/ #define ANCIL_MAX_N_FDS 960 /* * Maximum number of fds that can be sent or received using the "esay" * functions; this is so that all can fit in one page. */ extern int ancil_send_fds_with_buffer(int, const int *, unsigned, void *); /* * ancil_send_fds_with_buffer(sock, n_fds, fds, buffer) * * Sends the file descriptors in the array pointed by fds, of length n_fds * on the socket sock. * buffer is a writeable memory area large enough to hold the required data * structures. * Returns: -1 and errno in case of error, 0 in case of success. */ extern int ancil_recv_fds_with_buffer(int, int *, unsigned, void *); /* * ancil_recv_fds_with_buffer(sock, n_fds, fds, buffer) * * Receives *n_fds file descriptors into the array pointed by fds * from the socket sock. * buffer is a writeable memory area large enough to hold the required data * structures. * Returns: -1 and errno in case of error, the actual number of received fd * in case of success */ #define ANCIL_FD_BUFFER(n) \ struct { \ int fd[n]; \ struct cmsghdr h; \ } /* ANCIL_FD_BUFFER(n) * * A structure type suitable to be used as buffer for n file descriptors. * Requires <sys/socket.h>. * Example: * ANCIL_FD_BUFFER(42) buffer; * ancil_recv_fds_with_buffer(sock, 42, my_fds, &buffer); */ extern int ancil_send_fds(int, const int *, unsigned); /* * ancil_send_fds(sock, n_fds, fds) * * Sends the file descriptors in the array pointed by fds, of length n_fds * on the socket sock. * n_fds must not be greater than ANCIL_MAX_N_FDS. * Returns: -1 and errno in case of error, 0 in case of success. */ extern int ancil_recv_fds(int, int *, unsigned); /* * ancil_recv_fds(sock, n_fds, fds) * * Receives *n_fds file descriptors into the array pointed by fds * from the socket sock. * *n_fds must not be greater than ANCIL_MAX_N_FDS. * Returns: -1 and errno in case of error, the actual number of received fd * in case of success. */ extern int ancil_send_fd(int, int); /* ancil_recv_fd(sock, fd); * * Sends the file descriptor fd on the socket sock. * Returns : -1 and errno in case of error, 0 in case of success. */ extern int ancil_recv_fd(int, int *); /* ancil_send_fd(sock, &fd); * * Receives the file descriptor fd from the socket sock. * Returns : -1 and errno in case of error, 0 in case of success. */ #endif /* ANCILLARY_H__ */
hhvm/hphp/hack/src/third-party/libancillary/API
This library provide an easy interface to the black magic that can be done on Unix domain sockets, like passing file descriptors from one process to another. Programs that uses this library should include the ancillary.h header file. Nothing else is required. All functions of this library require the following header: #include <ancillary.h> At this time, the only ancillary data defined by the Single Unix Specification (v3) is file descriptors. Passing file descriptors int ancil_send_fd(socket, file_descriptor) int socket: the Unix socket int file_descriptor: the file descriptor Return value: 0 for success, -1 for failure. Sends one file descriptor on a socket. In case of failure, errno is set; the possible values are the ones of the sendmsg(2) system call. int ancil_recv_fd(socket, file_descriptor) int socket: the Unix socket int *file_descriptor: pointer to the returned file descriptor Return value: 0 for success, -1 for failure Receives one file descriptor from a socket. In case of success, the file descriptor is stored in the integer pointed to by file_descriptor. In case of failure, errno is set; the possible values are the ones of the recvmsg(2) system call. The behavior is undefined if the recv_fd does not match a send_fd* on the other side. int ancil_send_fds(socket, file_descriptors, num_file_descriptors) int socket: the Unix socket const int *file_descriptors: array of file descriptors unsigned num_file_descriptors: number of file descriptors Return value: 0 for success, -1 for failure Sends several file descriptors on a socket. In case of failure, errno is set; the possible values are the ones of the sendmsg(2) system call. The maximum number of file descriptors that can be sent using this function is ANCIL_MAX_N_FDS; the behavior is undefined in case of overflow, probably a stack corruption. int ancil_recv_fds(socket, file_descriptors, num_file_descriptors) int socket: the Unix socket int *file_descriptors: return array of file descriptors unsigned num_file_descriptors: number of file descriptors Return value: number of received fd for success, -1 for failure Receives several file descriptors from a socket, no more than num_file_descriptors. In case of success, the received file descriptors are stored in the array pointed to by file_descriptors. In case of failure, errno is set; the possible values are the ones of the recvmsg(2) system call. The maximum number of file descriptors that can be received using this function is ANCIL_MAX_N_FDS; the behavior is undefined in case of overflow, probably a stack corruption. The behavior is undefined if the recv_fds does not match a send_fd* on the other side, or if the number of received file descriptors is more than num_file_descriptors. int ancil_send_fds_with_buffer(socket, fds, num, buffer) int socket: the Unix socket const int *fds: array of file descriptors unsigned num: number of file descriptors void *buffer: buffer to hold the system data structures Return value: 0 for success, -1 for failure Sends several file descriptors on a socket. In case of failure, errno is set; the possible values are the ones of the sendmsg(2) system call. The buffer argument must point to a memory area large enough to hold the system data structures, see ANCIL_FD_BUFFER. int ancil_send_fds_with_buffer(socket, fds, num, buffer) int socket: the Unix socket int *fds: return array of file descriptors unsigned num: number of file descriptors void *buffer: buffer to hold the system data structures Return value: number of received fd for success, -1 for failure Receives several file descriptors from a socket, no more than num_file_descriptors. In case of success, the received file descriptors are stored in the array pointed to by file_descriptors. In case of failure, errno is set; the possible values are the ones of the recvmsg(2) system call. The behavior is undefined if the recv_fds does not match a send_fd* on the other side, or if the number of received file descriptors is more than num_file_descriptors. The buffer argument must point to a memory area large enough to hold the system data structures, see ANCIL_FD_BUFFER. ANCIL_MAX_N_FDS Maximum number of file descriptors that can be sent with the sent_fds and recv_fds functions. If you have to send more at once, use the *_with_buffer versions. The value is enough to send "quite a few" file descriptors. ANCIL_FD_BUFFER(n) int n: number of file descriptors Expands to a structure data type large enough to hold the system data structures for n file descriptors. So the address of a variable declared of type ANCIL_FD_BUFFER(n) is suitable as the buffer argument for *_with_buffer on n file descriptors. To use this macro, you need <sys/types.h> and <sys/socket.h>. Bevare: with Solaris, the _XPG4_2 macro must be defined before sys/socket is included. Tuning the compilation This library is designed to be included in projects, not installed in /usr/lib. If your project does not use some of the functions, the TUNE_OPTS variable in the Makefile allows not to build them. It is a list of proprocessor options: -DNDEBUG: turn assertions off (see assert(3)) -DSPARE_SEND_FDS: do not build ancil_send_fds -DSPARE_SEND_FD: do not build ancil_send_fd -DSPARE_RECV_FDS: do not build ancil_recv_fds -DSPARE_RECV_FD: do not build ancil_recv_fd
hhvm/hphp/hack/src/third-party/libancillary/COPYING
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
hhvm/hphp/hack/src/third-party/libancillary/dune
(library (name libancillary_c) (wrapped false) (foreign_stubs (language c) (names fd_recv fd_send) (flags (:standard -I%{env:CMAKE_SOURCE_DIR=xxx}))))
C
hhvm/hphp/hack/src/third-party/libancillary/fd_recv.c
/*************************************************************************** * libancillary - black magic on Unix domain sockets * (C) Nicolas George * fd_send.c - receiving file descriptors ***************************************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _XPG4_2 /* Solaris sucks */ # define _XPG4_2 #endif #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/uio.h> #include <assert.h> #if defined(__FreeBSD__) # include <sys/param.h> /* FreeBSD sucks */ #endif #include "hphp/hack/src/third-party/libancillary/ancillary.h" int ancil_recv_fds_with_buffer(int sock, int *fds, unsigned n_fds, void *buffer) { struct msghdr msghdr; char nothing; struct iovec nothing_ptr; struct cmsghdr *cmsg; int i; nothing_ptr.iov_base = &nothing; nothing_ptr.iov_len = 1; msghdr.msg_name = NULL; msghdr.msg_namelen = 0; msghdr.msg_iov = &nothing_ptr; msghdr.msg_iovlen = 1; msghdr.msg_flags = 0; msghdr.msg_control = buffer; msghdr.msg_controllen = CMSG_SPACE(sizeof(int) * n_fds); cmsg = CMSG_FIRSTHDR(&msghdr); cmsg->cmsg_len = CMSG_LEN(sizeof(int) * n_fds); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; for(i = 0; i < n_fds; i++) ((int *)CMSG_DATA(cmsg))[i] = -1; if(recvmsg(sock, &msghdr, 0) < 0) { return(-1); } for(i = 0; i < n_fds; i++) { fds[i] = ((int *)CMSG_DATA(cmsg))[i]; } n_fds = (cmsg->cmsg_len - sizeof(struct cmsghdr)) / sizeof(int); return(n_fds); } #ifndef SPARE_RECV_FDS int ancil_recv_fds(int sock, int *fd, unsigned n_fds) { ANCIL_FD_BUFFER(ANCIL_MAX_N_FDS) buffer; assert(n_fds <= ANCIL_MAX_N_FDS); return(ancil_recv_fds_with_buffer(sock, fd, n_fds, &buffer)); } #endif /* SPARE_RECV_FDS */ #ifndef SPARE_RECV_FD int ancil_recv_fd(int sock, int *fd) { ANCIL_FD_BUFFER(1) buffer; return(ancil_recv_fds_with_buffer(sock, fd, 1, &buffer) == 1 ? 0 : -1); } #endif /* SPARE_RECV_FD */
C
hhvm/hphp/hack/src/third-party/libancillary/fd_send.c
/*************************************************************************** * libancillary - black magic on Unix domain sockets * (C) Nicolas George * fd_send.c - sending file descriptors ***************************************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _XPG4_2 /* Solaris sucks */ # define _XPG4_2 #endif #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/uio.h> #include <assert.h> #if defined(__FreeBSD__) # include <sys/param.h> /* FreeBSD sucks */ #endif #include "hphp/hack/src/third-party/libancillary/ancillary.h" int ancil_send_fds_with_buffer(int sock, const int *fds, unsigned n_fds, void *buffer) { struct msghdr msghdr; char nothing = '!'; struct iovec nothing_ptr; struct cmsghdr *cmsg; int i; nothing_ptr.iov_base = &nothing; nothing_ptr.iov_len = 1; msghdr.msg_name = NULL; msghdr.msg_namelen = 0; msghdr.msg_iov = &nothing_ptr; msghdr.msg_iovlen = 1; msghdr.msg_flags = 0; msghdr.msg_control = buffer; msghdr.msg_controllen = CMSG_SPACE(sizeof(int) * n_fds); cmsg = CMSG_FIRSTHDR(&msghdr); cmsg->cmsg_len = CMSG_LEN(sizeof(int) * n_fds); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; for(i = 0; i < n_fds; i++) ((int *)CMSG_DATA(cmsg))[i] = fds[i]; return(sendmsg(sock, &msghdr, 0) >= 0 ? 0 : -1); } #ifndef SPARE_SEND_FDS int ancil_send_fds(int sock, const int *fds, unsigned n_fds) { ANCIL_FD_BUFFER(ANCIL_MAX_N_FDS) buffer; assert(n_fds <= ANCIL_MAX_N_FDS); return(ancil_send_fds_with_buffer(sock, fds, n_fds, &buffer)); } #endif /* SPARE_SEND_FDS */ #ifndef SPARE_SEND_FD int ancil_send_fd(int sock, int fd) { ANCIL_FD_BUFFER(1) buffer; return(ancil_send_fds_with_buffer(sock, &fd, 1, &buffer)); } #endif /* SPARE_SEND_FD */
C
hhvm/hphp/hack/src/third-party/libancillary/test.c
/*************************************************************************** * libancillary - black magic on Unix domain sockets * (C) Nicolas George * test.c - testing and example program ***************************************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <sys/socket.h> #include "ancillary.h" void child_process(int sock) { int fd; int fds[2], nfds; char b[] = "This is on the received fd!\n"; if(ancil_recv_fd(sock, &fd)) { perror("ancil_recv_fd"); exit(1); } else { printf("Received fd: %d\n", fd); } write(fd, b, sizeof(b)); close(fd); sleep(2); nfds = ancil_recv_fds(sock, fds, 2); if(nfds < 0) { perror("ancil_recv_fds"); exit(1); } else { printf("Received %d/2 fds : %d %d.\n", nfds, fds[0], fds[1]); } } void parent_process(int sock) { int fds[2] = { 1, 2 }; if(ancil_send_fd(sock, 1)) { perror("ancil_send_fd"); exit(1); } else { printf("Sent fd.\n"); } sleep(1); if(ancil_send_fds(sock, fds, 2)) { perror("ancil_send_fds"); exit(1); } else { printf("Sent two fds.\n"); } } int main(void) { int sock[2]; if(socketpair(PF_UNIX, SOCK_STREAM, 0, sock)) { perror("socketpair"); exit(1); } else { printf("Established socket pair: (%d, %d)\n", sock[0], sock[1]); } switch(fork()) { case 0: close(sock[0]); child_process(sock[1]); break; case -1: perror("fork"); exit(1); default: close(sock[1]); parent_process(sock[0]); wait(NULL); break; } return(0); }
OCaml
hhvm/hphp/hack/src/typing/ancestor_route.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 Cls = Decl_provider.Class module Env = Typing_env (* Find dependency routes between classish types. This is used in error reporting, to show how a class ultimately inherited something (e.g. an abstract method) that caused a type error. *) let get_class env name = Decl_provider.get_class ?tracing_info:(Env.get_tracing_info env) (Env.get_ctx env) name (** All the parent classes, used traits, and implemented interfaces of [type_name]. This is the flattened inheritance tree. *) let all_ancestor_names env (type_name : string) : string list = let decl = get_class env type_name in match decl with | Some decl -> Cls.all_ancestor_names decl | None -> [] let has_ancestor env (classish_name : string) (ancestor_name : string) : bool = match get_class env classish_name with | Some decl -> Cls.has_ancestor decl ancestor_name | None -> false (** Return the ancestors of [classish_name] that also depend on [ancestor_name]. *) let find_ancestors_using env (classish_name : string) (ancestor_name : string) : string list = let ancestors = all_ancestor_names env classish_name in List.filter ancestors ~f:(fun name -> has_ancestor env name ancestor_name) (** Sort a list of classish names according to how many ancestors they have, in ascending order. *) let sort_by_num_ancestors env (names : string list) : string list = let num_ancestors cls_name = List.length (all_ancestor_names env cls_name) in let compare cls_x cls_y = Int.compare (num_ancestors cls_x) (num_ancestors cls_y) in List.dedup_and_sort names ~compare (** Return a list showing a route from [classish] name to [ancestor] name. If multiple routes exist, return the longest one. trait One {} trait Two { use One; } class Three { use Two; } The route from Three to One in this example is ["Three"; "Two"; "One"]. *) let find_route env ~classish ~ancestor : string list = let rec classish_between classish ancestor seen : string list = if SSet.mem classish seen then (* The class hierarchy is bad: it contains a cycle. Ensure we still terminate. *) [] else (* Find all the ancestors that use this trait. *) let ancestors = find_ancestors_using env classish ancestor in (* Choose the ancestor closest to [classish] by taking the ancestor that has the most ancestors itself. *) let sorted_ancestors = List.rev (sort_by_num_ancestors env ancestors) in match sorted_ancestors with | [] -> [] | [ancestor] -> [ancestor] | anc :: _ -> anc :: classish_between anc ancestor (SSet.add classish seen) in [classish] @ classish_between classish ancestor SSet.empty @ [ancestor] (** Find the position in [classish_name] that means it depends on [ancestor_name]. For example, if [ancestor_name] is a trait, this will return the `use Foo;` position. *) let reason_pos env (classish_name : string) (ancestor_name : string) : Pos_or_decl.t = match get_class env classish_name with | Some decl -> (match Cls.get_ancestor decl ancestor_name with | Some trait_ty -> Typing_defs_core.get_pos trait_ty | None -> Pos_or_decl.none) | None -> Pos_or_decl.none (** Given a list of [items], apply the function [f] to every two adjacent items. E.g. for [1; 2; 3] we return [(f 1 2); (f 2 3)]. *) let rec pairwise_map (items : 'a list) (f : 'a -> 'a -> 'b) : 'b list = match items with | [] -> [] | [_] -> [] | x :: y :: rest -> f x y :: pairwise_map (y :: rest) f (** Return a list of positions from [classish] name to [ancestor] name. *) let describe_route (env : Typing_env_types.env) ~(classish : string) ~(ancestor : string) : (Pos_or_decl.t * string) list = let route = find_route env ~classish ~ancestor in pairwise_map route (fun classish parent -> ( reason_pos env classish parent, Printf.sprintf "`%s` uses `%s`" (Utils.strip_ns classish) (Utils.strip_ns parent) )) (** Show that [classish] uses [via], and the full path from [via] to [ancestor]. *) let describe_route_via env ~(classish : string) ~(ancestor : string) ~(via : string) : (Pos_or_decl.t * string) list = let result = if String.equal via ancestor then [] else describe_route env ~classish:via ~ancestor in ( reason_pos env classish via, Printf.sprintf "`%s` uses `%s`" (Utils.strip_ns classish) (Utils.strip_ns via) ) :: result
OCaml Interface
hhvm/hphp/hack/src/typing/ancestor_route.mli
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val find_route : Typing_env_types.env -> classish:string -> ancestor:string -> string list val describe_route : Typing_env_types.env -> classish:string -> ancestor:string -> (Pos_or_decl.t * string) list val describe_route_via : Typing_env_types.env -> classish:string -> ancestor:string -> via:string -> (Pos_or_decl.t * string) list
OCaml
hhvm/hphp/hack/src/typing/class_refinement.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 let is_empty { cr_consts } = SMap.is_empty cr_consts let has_refined_const pos_id cr = SMap.mem (snd pos_id) cr.cr_consts let get_refined_const (_, id) cr = SMap.find_opt id cr.cr_consts let fold_refined_consts cr ~init:acc ~f = SMap.fold f cr.cr_consts acc let add_refined_const id tr cr = let combine (type a) (r1 : a refined_const) (r2 : a refined_const) = (* Note: previous stages ensure that is_ctx are compatible *) let rc_bound = match (r1.rc_bound, r2.rc_bound) with | ((TRexact _ as exact), _) | (_, (TRexact _ as exact)) -> exact | ( TRloose { tr_lower = ls1; tr_upper = us1 }, TRloose { tr_lower = ls2; tr_upper = us2 } ) -> TRloose { tr_lower = ls1 @ ls2; tr_upper = us1 @ us2 } in { rc_bound; rc_is_ctx = r1.rc_is_ctx } in { cr_consts = SMap.add ~combine id tr cr.cr_consts } let map_refined_const (type a) f ({ rc_bound; rc_is_ctx } : a refined_const) = let rc_bound = match rc_bound with | TRexact ty -> TRexact (f ty) | TRloose { tr_lower = ls; tr_upper = us } -> TRloose { tr_lower = List.map ls ~f; tr_upper = List.map us ~f } in { rc_bound; rc_is_ctx } let map f { cr_consts = rcs } = { cr_consts = SMap.map (map_refined_const f) rcs } let fold_map_refined_const (type ph acc) (f : acc -> ph ty -> acc * ph ty) (acc : acc) _ ({ rc_bound; rc_is_ctx } : ph refined_const) = let (acc, rc_bound) = match rc_bound with | TRexact ty -> let (acc, ty) = f acc ty in (acc, TRexact ty) | TRloose { tr_lower = ls; tr_upper = us } -> let (acc, ls) = List.fold_map ~f ~init:acc ls in let (acc, us) = List.fold_map ~f ~init:acc us in (acc, TRloose { tr_lower = ls; tr_upper = us }) in (acc, { rc_bound; rc_is_ctx }) let fold_map (f : 'acc -> decl_ty -> 'acc * decl_ty) acc { cr_consts = rcs } : 'acc * decl_phase class_refinement = let (acc, rcs) = SMap.map_env (fold_map_refined_const f) acc rcs in (acc, { cr_consts = rcs }) let fold_refined_const { rc_bound; rc_is_ctx = _ } ~init:acc ~f = match rc_bound with | TRexact ty -> f acc ty | TRloose { tr_lower = ls; tr_upper = us } -> let acc = List.fold ~f ~init:acc ls in let acc = List.fold ~f ~init:acc us in acc let fold { cr_consts = rcs } ~init:acc ~f = SMap.fold (fun _ rc acc -> fold_refined_const rc ~init:acc ~f) rcs acc let iter f r = fold r ~init:() ~f:(fun () -> f) let to_string ty_to_string cr = let rc_to_string { rc_bound; _ } = match rc_bound with | TRexact ty -> "= " ^ ty_to_string ty | TRloose { tr_lower = ls; tr_upper = us } -> let l1 = List.map ls ~f:(fun ty -> "as " ^ ty_to_string ty) in let l2 = List.map us ~f:(fun ty -> "super " ^ ty_to_string ty) in String.concat ~sep:" " (l1 @ l2) in let members_list = let f name rc acc = let kind = refined_const_kind_str rc in (kind ^ " " ^ name ^ " " ^ rc_to_string rc) :: acc in SMap.fold f cr.cr_consts [] in "{" ^ String.concat ~sep:"; " members_list ^ "}"
OCaml
hhvm/hphp/hack/src/typing/deferred_decl.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude (** A [deferment] is a file which contains a decl that we need to fetch before we continue with our scheduled typechecking work. The handler of exception [Defer (d.php, "\\D")] will typically call [add_deferment ~d:(d.php, "\\D")]. *) type deferment = Relative_path.t * string [@@deriving show, ord] (** We raise [Defer] when a file requires a number of decls above the threshold *) exception Defer type state = { enabled: bool; counter: int; (** Counter for decls needing to be computed out of the ASTs. *) declaration_threshold_opt: int option; (** If [counter] goes beyond this threshold, we raise and defer the typechecking. *) memory_mb_threshold_opt: int option; (** If memory goes beyond this threshold, we raise and defer the typechecking. *) } let state : state ref = ref { enabled = false; counter = 0; declaration_threshold_opt = None; memory_mb_threshold_opt = None; } let reset ~(enable : bool) ~(declaration_threshold_opt : int option) ~(memory_mb_threshold_opt : int option) : unit = state := { enabled = enable; counter = 0; declaration_threshold_opt; memory_mb_threshold_opt; } (** Increment the counter of decls needing computing. *) let increment_counter () : unit = if !state.enabled then state := { !state with counter = !state.counter + 1 } (** Call [raise_if_should_defer ()] if you're typechecking some file, and discover that you need to fetch yet another class. This will raise if the counter for computed class decls is over the set up threshold. *) let raise_if_should_defer () : unit = match ( !state.enabled, !state.declaration_threshold_opt, !state.memory_mb_threshold_opt ) with | (true, Some declaration_threshold, _) when !state.counter >= declaration_threshold -> raise Defer | (true, _, Some memory_mb_threshold) when let word_bytes = Sys.word_size / 8 in let megabyte = 1024 * 1024 in Gc.((quick_stat ()).Stat.heap_words) * word_bytes / megabyte >= memory_mb_threshold -> raise Defer | _ -> increment_counter () let with_deferred_decls ~enable ~declaration_threshold_opt ~memory_mb_threshold_opt f = reset ~enable ~declaration_threshold_opt ~memory_mb_threshold_opt; let cleanup () = reset ~enable:false ~declaration_threshold_opt:None ~memory_mb_threshold_opt:None in try let result = f () in cleanup (); Ok result with | Defer -> cleanup (); Error ()
OCaml Interface
hhvm/hphp/hack/src/typing/deferred_decl.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 Hh_prelude (* Ideally, this exception should not be part of this mli, but there is one place where we catch all exceptions and we need to ignore this one. TODO: clean that up somehow *) exception Defer (** A [deferment] is a file which contains a decl that we need to fetch before we continue with our scheduled typechecking work. The handler of exception [Defer (d.php, "\\D")] will typically call [add_deferment ~d:(d.php, "\\D")]. *) type deferment = Relative_path.t * string [@@deriving show, ord] (** Call [raise_if_should_defer ()] if you're typechecking some file, and discover that you need to fetch yet another class. This will raise if the counter for computed class decls is over the set up threshold. *) val raise_if_should_defer : unit -> unit val with_deferred_decls : enable:bool -> declaration_threshold_opt:int option -> memory_mb_threshold_opt:int option -> (unit -> 'res) -> ('res, unit) Result.t
hhvm/hphp/hack/src/typing/dune
(library (name format_helpers) (wrapped false) (modules format_helpers) (libraries core_kernel hh_autoimport) (preprocess (pps ppx_deriving.std))) (library (name hint_print) (wrapped false) (modules hint_print) (libraries annotated_ast ast core_kernel format_helpers naming_special_names) (preprocess (pps ppx_deriving.std))) (library (name typing_defs_core) (wrapped false) (modules tanySentinel typing_defs_core typing_defs_flags typing_reason xhp_attribute) (libraries ast heap_ident nast pos pos_or_decl) (preprocess (pps ppx_deriving.std ppx_hash))) (library (name typing_error) (wrapped false) (modules typing_error) (libraries ast pos pos_or_decl typing_defs_core error_codes user_error) (preprocess (pps ppx_deriving.std))) (library (name typing_error_utils) (wrapped false) (modules typing_error_utils) (libraries core_kernel custom_error_eval errors error_codes pos pos_or_decl typing_error typing_env_types typing_env typing_print typing_utils user_error)) (library (name typing_defs) (wrapped false) (modules type_visitor class_refinement typing_defs) (libraries ast core_kernel heap_ident hh_autoimport ide_rpc_api_types nast pos pos_or_decl relative_path typing_defs_core typing_error utils_core) (preprocess (pps ppx_deriving.std ppx_hash))) (library (name deferred_decl) (wrapped false) (modules deferred_decl) (libraries relative_path utils_core) (preprocess (pps ppx_deriving.std))) (library (name typing_class_types) (wrapped false) (modules typing_class_types) (libraries collections decl_defs pos_or_decl shallow_decl_defs typing_defs utils_core) (preprocess (pps ppx_deriving.std))) (library (name typing_heap) (wrapped false) (modules typing_classes_heap) (libraries core_kernel decl decl_counters decl_folded_class deferred_decl naming_provider shallow_decl_defs typing_class_types typing_defs) (preprocess (pps ppx_deriving.std))) (library (name tast_env) (wrapped false) (modules tast_env tast_expand tast_utils tast_visitor typing_env_from_def typing_equality_check) (libraries typing) (preprocess (pps ppx_deriving.std))) (library (name nast_visitor) (wrapped false) (modules nast_check_env nast_visitor stateful_aast_visitor ) (libraries nast provider_context naming_attributes_params) (preprocess (pps ppx_deriving.std))) (library (name typing_common) (wrapped false) (modules type_validator typing_const_reifiable typing_enforceable_hint typing_reified_check typing_tdef typing_variance) (libraries common decl decl_provider hackfmt_doc hackfmt_env hackfmt logging naming_attributes naming symbol typechecker_options type_mapper_generic typing_ast typing_defs typing_env typing_algebra typing_heap global_config) (preprocess (pps ppx_deriving.std))) (library (name tast_type_collector) (wrapped false) (modules tast_type_collector) (libraries core_kernel full_fidelity tast_env) (preprocess (pps ppx_deriving.std))) (library (name typing_modules) (wrapped false) (modules typing_modules) (libraries typing_env typing_env_types decl_provider)) (library (name typing) (wrapped false) (modules nastInitCheck type_parameter_env_ops typing_alias typing_ast_print typing_arithmetic typing_array_access typing_async typing_attributes typing_debug typing_escape typing_expand typing_exts typing_func_terminality typing_generic_rules typing_helpers typing_lenv typing_local_ops typing_native typing_param typing_per_cont_ops typing_regex typing_sequencing typing_shapes typing_special_fun typing_structure typing_substring typing_try typing_xhp) (libraries decl_enum decl_init_check decl_nast logging naming_special_names nast_check package_info pcre procs_procs typing_common typing_error_utils type_mapper typing_modules) (preprocess (pps ppx_deriving.std))) (library (name typing_skeleton) (wrapped false) (modules typing_skeleton) (libraries typing_defs) (preprocess (pps ppx_deriving.std))) (library (name typing_toplevel) (wrapped false) (modules typing typing_class typing_memoize typing_toplevel typing_typedef typing_toplevel_profile) (libraries tast_check typing typing_wellformedness)) (library (name typing_wellformedness) (wrapped false) (modules ancestor_route trait_reuse_check typing_extends typing_requirements typing_subtype_method typing_type_wellformedness) (libraries typing_algebra typing_common typing_modules typing_skeleton) (preprocess (pps ppx_deriving.std))) (library (name type_mapper_generic) (wrapped false) (modules type_mapper_generic) (libraries common core_kernel typing_defs) (preprocess (pps ppx_deriving.std))) (library (name type_mapper_forget) (wrapped false) (modules type_mapper_forget) (libraries common core_kernel type_mapper_generic typing_defs) (preprocess (pps ppx_deriving.std))) (library (name typing_algebra) (wrapped false) (modules typing_algebra typing_case_types typing_coeffects typing_coercion typing_dynamic typing_enforceability typing_enum typing_intersection typing_generic_constraint typing_kinding typing_logic_helpers typing_object_get typing_ops typing_partial_enforcement typing_phase typing_return typing_solver typing_solver_utils typing_subtype typing_subtype_tconst typing_taccess typing_type_member typing_union) (libraries type_mapper typing_dependent_type typing_disposable typing_env typing_log typing_utils typing_visibility decl_typedef_expand lru) (preprocess (pps ppx_deriving.std))) (library (name typing_visibility) (wrapped false) (modules typing_visibility) (libraries typing_modules typing_utils) (preprocess (pps ppx_deriving.std))) (library (name typing_disposable) (wrapped false) (modules typing_disposable) (libraries typing_utils typing_error_utils) (preprocess (pps ppx_deriving.std))) (library (name typing_dependent_type) (wrapped false) (modules typing_dependent_type) (libraries typing_utils) (preprocess (pps ppx_deriving.std))) (library (name typing_utils) (wrapped false) (modules typing_utils) (libraries typing_env typing_logic typing_error errors) (preprocess (pps ppx_deriving.std))) (library (name type_mapper) (wrapped false) (modules type_mapper) (libraries typing_env) (preprocess (pps ppx_deriving.std))) (library (name typing_print) (wrapped false) (modules typing_print) (libraries decl_provider hackfmt typing_logic typing_env_types) (preprocess (pps ppx_deriving.std))) (library (name typing_log) (wrapped false) (modules typing_log ) (libraries decl_provider hackfmt typing_logic typing_env_types typing_print) (preprocess (pps ppx_deriving.std))) (library (name typing_logic) (wrapped false) (modules typing_logic) (libraries typing_defs) (preprocess (pps ppx_deriving.std))) (library (name typing_env_types) (wrapped false) (modules typing_cont_key typing_continuations typing_env_return_info typing_env_types typing_fake_members typing_local_types typing_per_cont_env) (libraries decl decl_counters typing_ast) (preprocess (pps ppx_deriving.std))) (library (name typing_ast) (wrapped false) (modules internal_type_set tast tast_with_dynamic typing_kinding_defs type_parameter_env typing_set typing_inference_env typing_log_value typing_make_type typing_tyvar_occurrences) (libraries annotated_ast ast common core_kernel errors typing_error naming_attributes nast type_mapper_forget typing_defs typing_logic typechecker_options) (preprocess (pps ppx_deriving.std ppx_hash))) (library (name typing_check_job) (wrapped false) (modules typing_check_job) (libraries core_kernel deferred_decl errors typing_error file_info nast substitution_mutation heap_global_storage typing_deps typing_toplevel) (preprocess (pps ppx_deriving.std))) (library (name typing_check) (wrapped false) (modules typing_check_service) (libraries biglist cgroupprofiler core_kernel decl_counters hh_distc_ffi depgraph_decompress_ffi decl_service server_env server_env_build deferred_decl diagnostic_pusher errors typing_error typing_service_types file_info map_reduce nast gc_utils global_options hh_distc_types heap_global_storage procs_bucket counters typing typing_defs typing_deps typing_pessimisation_deps typing_check_job) (preprocess (pps ppx_deriving.std))) (library (name hh_distc_types) (wrapped false) (modules hh_distc_types) (libraries errors) (preprocess (pps ppx_deriving.std)))
OCaml
hhvm/hphp/hack/src/typing/format_helpers.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude let pf fmt = Format.fprintf fmt let string = Format.pp_print_string let sp ppf _ = Format.pp_print_space ppf () let cut ppf _ = Format.pp_print_cut ppf () let to_to_string pp_v v = Format.asprintf "%a" pp_v v let of_to_string f ppf v = string ppf (f v) let cond ~pp_t ~pp_f ppf test = if test then pp_t ppf () else pp_f ppf () let pair ?sep:(pp_sep = sp) pp_a pp_b ppf (a, b) = pp_a ppf a; pp_sep ppf (); pp_b ppf b let triple ?sep:(pp_sep = sp) pp_a pp_b pp_c ppf (a, b, c) = pp_a ppf a; pp_sep ppf (); pp_b ppf b; pp_sep ppf (); pp_c ppf c let prefix pp_pfx pp_v ppf v = pp_pfx ppf (); pp_v ppf v let suffix pp_sfx pp_v ppf v = pp_v ppf v; pp_sfx ppf () let surround l r pp_v ppf v = string ppf l; pp_v ppf v; string ppf r let quote pp_v ppf v = surround "'" "'" pp_v ppf v let parens pp_v ppf v = surround "(" ")" pp_v ppf v let braces pp_v ppf v = surround "{" "}" pp_v ppf v let angles pp_v ppf v = surround "<" ">" pp_v ppf v let brackets pp_v ppf v = surround "[" "]" pp_v ppf v let comma ppf _ = string ppf ","; sp ppf () let amp ppf _ = sp ppf (); string ppf "&"; sp ppf () let equal_to ppf _ = sp ppf (); string ppf "="; sp ppf () let colon ppf _ = sp ppf (); string ppf ":"; sp ppf () let semicolon ppf _ = string ppf ";" let semi_sep ppf _ = semicolon ppf (); sp ppf () let arrow ppf _ = string ppf "->" let with_ ppf _ = sp ppf (); string ppf "with"; sp ppf () let fat_arrow ppf _ = sp ppf (); string ppf "=>"; sp ppf () let const str ppf _ = string ppf str let dbl_colon v = const "::" v let dbl_hash v = const "#" v let vbar ppf _ = sp ppf (); string ppf "|"; sp ppf () let nop _ _ = () let const pp_v v ppf _ = pp_v ppf v let option ?none:(pp_none = nop) pp_v ppf = function | Some v -> pp_v ppf v | _ -> pp_none ppf () let list ?sep:(pp_sep = sp) pp_elt ppf v = let is_first = ref true in let pp_elt v = if !is_first then is_first := false else pp_sep ppf (); pp_elt ppf v in List.iter ~f:pp_elt v let hbox pp_v ppf v = Format.( pp_open_hbox ppf (); pp_v ppf v; pp_close_box ppf ()) let vbox ?(indent = 0) pp_v ppf v = Format.( pp_open_vbox ppf indent; pp_v ppf v; pp_close_box ppf ())
OCaml
hhvm/hphp/hack/src/typing/hh_distc_types.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type event = | Errors of Errors.t | TypingStart of int | TypingProgress of int [@@deriving show]
OCaml
hhvm/hphp/hack/src/typing/hint_print.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 SN = Naming_special_names module Fmt = Format_helpers let strip_ns obj_name = match String.rsplit2 obj_name ~on:'\\' with | Some (_, name) -> name | None -> obj_name let pp_paramkind ppf = Ast_defs.( function | Pinout _ -> Fmt.string ppf "inout" | Pnormal -> ()) let any_type_name = "ANY_TYPE" let rec pp_hint ~is_ctx ppf (pos, hint_) = match hint_ with | Aast.Hany | Aast.Herr -> Fmt.string ppf any_type_name | Aast.Hthis -> Fmt.string ppf "this" | Aast.Hdynamic -> Fmt.string ppf "dynamic" | Aast.Hnothing -> Fmt.string ppf "nothing" | Aast.Hmixed -> Fmt.string ppf "mixed" | Aast.Hwildcard -> Fmt.string ppf "_" | Aast.Hnonnull -> Fmt.string ppf "nonnull" | Aast.Hvar name -> Fmt.string ppf name | Aast.Hfun_context name -> Fmt.(prefix (const string "ctx ") string) ppf name | Aast.Hoption hint -> Fmt.(prefix (const string "?") @@ pp_hint ~is_ctx:false) ppf hint | Aast.Hlike hint -> Fmt.(prefix (const string "~") @@ pp_hint ~is_ctx:false) ppf hint | Aast.Hsoft hint -> Fmt.(prefix (const string "@") @@ pp_hint ~is_ctx:false) ppf hint | Aast.Htuple hints -> Fmt.(parens @@ list ~sep:comma @@ pp_hint ~is_ctx:false) ppf hints | Aast.Hunion hints -> Fmt.(parens @@ list ~sep:vbar @@ pp_hint ~is_ctx:false) ppf hints | Aast.Hintersection hints when is_ctx -> Fmt.(brackets @@ list ~sep:comma @@ pp_hint ~is_ctx:true) ppf hints | Aast.Hintersection hints -> Fmt.(parens @@ list ~sep:amp @@ pp_hint ~is_ctx:false) ppf hints | Aast.Hprim prim -> Fmt.string ppf (Aast_defs.string_of_tprim prim) | Aast.Haccess (root, ids) -> Fmt.( pair ~sep:dbl_colon (pp_hint ~is_ctx:false) @@ list ~sep:dbl_colon string) ppf (root, List.map ~f:snd ids) | Aast.Hrefinement (ty, members) -> let pp_bounds ~is_ctx ppf bounds = let bound ppf (kind, hint) = Fmt.string ppf (match kind with | `E -> "= " | `L -> "as " | `U -> "super "); pp_hint ~is_ctx ppf hint in Fmt.list ~sep:Fmt.(const string " ") bound ppf bounds in let member ppf = function | Aast.Rtype (ident, ref) -> Fmt.string ppf ("type " ^ snd ident ^ " "); pp_bounds ~is_ctx:false ppf (match ref with | Aast.TRexact hint -> [(`E, hint)] | Aast.TRloose { Aast.tr_lower; tr_upper } -> List.map tr_lower ~f:(fun x -> (`L, x)) @ List.map tr_upper ~f:(fun x -> (`U, x))) | Aast.Rctx (ident, ref) -> Fmt.string ppf ("ctx " ^ snd ident ^ " "); pp_bounds ~is_ctx:true ppf (match ref with | Aast.CRexact hint -> [(`E, hint)] | Aast.CRloose { Aast.cr_lower; cr_upper } -> let opt_map = Option.value_map ~default:[] in opt_map cr_lower ~f:(fun x -> [(`L, x)]) @ opt_map cr_upper ~f:(fun x -> [(`U, x)])) in Fmt.(suffix with_ (pp_hint ~is_ctx:false)) ppf ty; Fmt.(braces (list ~sep:semi_sep member)) ppf members | Aast.Hvec_or_dict (None, vhint) -> Fmt.(prefix (const string "vec_or_dict") @@ angles @@ pp_hint ~is_ctx:false) ppf vhint | Aast.Hvec_or_dict (Some khint, vhint) -> Fmt.( prefix (const string "vec_or_dict") @@ angles @@ pair ~sep:comma (pp_hint ~is_ctx:false) (pp_hint ~is_ctx:false)) ppf (khint, vhint) | Aast.Happly ((p, name), hs) when is_ctx -> pp_hint ~is_ctx:false ppf (pos, Aast.Happly ((p, strip_ns name), hs)) | Aast.Habstr (name, []) | Aast.Happly ((_, name), []) -> Fmt.string ppf name | Aast.Habstr (name, hints) | Aast.Happly ((_, name), hints) -> Fmt.( prefix (const string name) @@ angles @@ list ~sep:comma @@ pp_hint ~is_ctx:false) ppf hints | Aast.( Hfun { hf_param_tys; hf_param_info; hf_variadic_ty; hf_return_ty; hf_ctxs; _; }) -> let hf_param_kinds = List.map hf_param_info ~f:(fun i -> Option.bind i ~f:(fun i -> match i.Aast.hfparam_kind with | Ast_defs.Pnormal -> None | Ast_defs.Pinout p -> Some (Ast_defs.Pinout p))) in let pp_typed_param ppf kp = Fmt.( pair ~sep:nop (option @@ suffix sp pp_paramkind) @@ pp_hint ~is_ctx:false) ppf kp in let pp_fun_params ppf (ps, v) = Fmt.( parens @@ pair ~sep:nop (list ~sep:comma pp_typed_param) (option @@ surround ", " "..." @@ pp_hint ~is_ctx:false)) ppf (ps, v) in let all_params = (List.zip_exn hf_param_kinds hf_param_tys, hf_variadic_ty) in Fmt.( parens @@ pair ~sep:colon (prefix (const string "function") @@ pair ~sep:nop pp_fun_params (option pp_contexts)) @@ pp_hint ~is_ctx:false) ppf ((all_params, hf_ctxs), hf_return_ty) | Aast.(Hshape { nsi_allows_unknown_fields; nsi_field_map = [] }) -> Fmt.( prefix (const string "shape") @@ parens @@ cond ~pp_t:(const string "...") ~pp_f:nop) ppf nsi_allows_unknown_fields | Aast.(Hshape { nsi_allows_unknown_fields; nsi_field_map }) -> Fmt.( prefix (const string "shape") @@ parens @@ pair ~sep:nop (list ~sep:comma pp_shape_field) (cond ~pp_t:(const string ", ...") ~pp_f:nop)) ppf (nsi_field_map, nsi_allows_unknown_fields) and pp_shape_field ppf Aast.{ sfi_optional; sfi_name; sfi_hint } = Fmt.( pair ~sep:fat_arrow (pair ~sep:nop (cond ~pp_t:(const string "?") ~pp_f:nop) pp_shape_field_name) @@ pp_hint ~is_ctx:false) ppf ((sfi_optional, sfi_name), sfi_hint) and pp_shape_field_name ppf = function | Ast_defs.SFlit_int (_, s) -> Fmt.string ppf s | Ast_defs.SFlit_str (_, s) -> Fmt.(quote string) ppf s | Ast_defs.SFclass_const ((_, c), (_, s)) -> Fmt.(pair ~sep:dbl_colon string string) ppf (c, s) and pp_contexts ppf (_, ctxts) = Fmt.(brackets @@ list ~sep:comma @@ pp_hint ~is_ctx:true) ppf ctxts let rec pp_binop ppf = function | Ast_defs.Plus -> Fmt.string ppf "+" | Ast_defs.Minus -> Fmt.string ppf "-" | Ast_defs.Star -> Fmt.string ppf "*" | Ast_defs.Slash -> Fmt.string ppf "/" | Ast_defs.Eqeq -> Fmt.string ppf "==" | Ast_defs.Eqeqeq -> Fmt.string ppf "===" | Ast_defs.Starstar -> Fmt.string ppf "**" | Ast_defs.Diff -> Fmt.string ppf "diff" | Ast_defs.Diff2 -> Fmt.string ppf "diff2" | Ast_defs.Ampamp -> Fmt.string ppf "&&" | Ast_defs.Barbar -> Fmt.string ppf "||" | Ast_defs.Lt -> Fmt.string ppf "<" | Ast_defs.Lte -> Fmt.string ppf "<=" | Ast_defs.Gt -> Fmt.string ppf ">" | Ast_defs.Gte -> Fmt.string ppf ">=" | Ast_defs.Dot -> Fmt.string ppf "." | Ast_defs.Amp -> Fmt.string ppf "&" | Ast_defs.Bar -> Fmt.string ppf "|" | Ast_defs.Ltlt -> Fmt.string ppf "<<" | Ast_defs.Gtgt -> Fmt.string ppf ">>" | Ast_defs.Percent -> Fmt.string ppf "%" | Ast_defs.Xor -> Fmt.string ppf "^" | Ast_defs.Cmp -> Fmt.string ppf "<=>" | Ast_defs.QuestionQuestion -> Fmt.string ppf "??" | Ast_defs.Eq (Some op) -> Fmt.(suffix (const string "=") pp_binop) ppf op | Ast_defs.Eq _ -> Fmt.string ppf "=" let pp_unop ppf op = match op with | Ast_defs.Utild -> Fmt.string ppf "~" | Ast_defs.Unot -> Fmt.string ppf "!" | Ast_defs.Uplus -> Fmt.string ppf "+" | Ast_defs.Uminus -> Fmt.string ppf "-" | Ast_defs.Uincr | Ast_defs.Upincr -> Fmt.string ppf "++" | Ast_defs.Udecr | Ast_defs.Updecr -> Fmt.string ppf "--" | Ast_defs.Usilence -> Fmt.string ppf "@" let is_postfix_unop = function | Ast_defs.Updecr | Ast_defs.Upincr -> true | _ -> false let pp_targ ppf (_, hint) = pp_hint ~is_ctx:false ppf hint let pp_targs ppf = function | [] -> () | targs -> Fmt.(angles @@ list ~sep:comma pp_targ) ppf targs let pp_vc_kind ppf = function | Aast_defs.Vector -> Fmt.string ppf "Vector" | Aast_defs.ImmVector -> Fmt.string ppf "ImmVector" | Aast_defs.Vec -> Fmt.string ppf "vec" | Aast_defs.Set -> Fmt.string ppf "Set" | Aast_defs.ImmSet -> Fmt.string ppf "ImmSet" | Aast_defs.Keyset -> Fmt.string ppf "keyset" let pp_kvc_kind ppf = function | Aast_defs.Dict -> Fmt.string ppf "dict" | Aast_defs.Map -> Fmt.string ppf "Map" | Aast_defs.ImmMap -> Fmt.string ppf "ImmMap" let pp_lid ppf lid = Fmt.(prefix (const string "$") string) ppf @@ Local_id.get_name lid let rec pp_expr ppf (_, _, expr_) = pp_expr_ ppf expr_ and pp_expr_ ppf = function | Aast.Darray (kv_ty_opt, kvs) -> Fmt.( prefix (const string "darray") @@ pair ~sep:nop (option @@ angles @@ pair ~sep:comma pp_targ pp_targ) (brackets @@ list ~sep:comma @@ pair ~sep:fat_arrow pp_expr pp_expr)) ppf (kv_ty_opt, kvs) | Aast.Varray (k_ty_opt, ks) -> Fmt.( prefix (const string "varray") @@ pair ~sep:nop (option @@ angles pp_targ) (brackets @@ list ~sep:comma pp_expr)) ppf (k_ty_opt, ks) | Aast.Shape flds -> Fmt.( prefix (const string "shape") @@ parens @@ list ~sep:comma @@ pair ~sep:fat_arrow pp_shape_field_name pp_expr) ppf flds | Aast.ValCollection ((_, kind), targ_opt, exprs) -> let delim = match kind with | Aast_defs.Keyset | Aast_defs.Vec -> Fmt.brackets | _ -> Fmt.braces in Fmt.( pair ~sep:nop pp_vc_kind @@ pair ~sep:nop (option @@ angles @@ pp_targ) (delim @@ list ~sep:comma pp_expr)) ppf (kind, (targ_opt, exprs)) | Aast.KeyValCollection ((_, kind), targs_opt, flds) -> let delim = match kind with | Aast_defs.Dict -> Fmt.brackets | _ -> Fmt.braces in Fmt.( pair ~sep:nop pp_kvc_kind @@ pair ~sep:nop (option @@ angles @@ pair ~sep:comma pp_targ pp_targ) (delim @@ list ~sep:comma @@ pair ~sep:fat_arrow pp_expr pp_expr)) ppf (kind, (targs_opt, flds)) | Aast.Null -> Fmt.string ppf "null" | Aast.This -> Fmt.string ppf "this" | Aast.True -> Fmt.string ppf "true" | Aast.False -> Fmt.string ppf "false" | Aast.Id (_, id) -> Fmt.string ppf id | Aast.Lvar (_, lid) -> pp_lid ppf lid | Aast.Dollardollar _ -> Fmt.string ppf "$$" | Aast.Clone expr -> Fmt.(prefix (const string "clone") pp_expr) ppf expr | Aast.Array_get (arr_expr, idx_expr_opt) -> Fmt.(pair ~sep:nop pp_expr @@ brackets @@ option pp_expr) ppf (arr_expr, idx_expr_opt) | Aast.(Obj_get (obj_expr, get_expr, OG_nullsafe, Is_method)) -> Fmt.(pair ~sep:arrow (suffix (const string "?") pp_expr) pp_expr) ppf (obj_expr, get_expr) | Aast.(Obj_get (obj_expr, get_expr, OG_nullsafe, _)) -> Fmt.(parens @@ pair ~sep:arrow (suffix (const string "?") pp_expr) pp_expr) ppf (obj_expr, get_expr) | Aast.(Obj_get (obj_expr, get_expr, _, Is_method)) -> Fmt.(pair ~sep:arrow pp_expr pp_expr) ppf (obj_expr, get_expr) | Aast.(Obj_get (obj_expr, get_expr, _, _)) -> Fmt.(parens @@ pair ~sep:arrow pp_expr pp_expr) ppf (obj_expr, get_expr) | Aast.(Class_get (class_id, class_get_expr, Is_method)) -> Fmt.(pair ~sep:dbl_colon pp_class_id pp_class_get_expr) ppf (class_id, class_get_expr) | Aast.Class_get (class_id, class_get_expr, _) -> Fmt.(parens @@ pair ~sep:dbl_colon pp_class_id pp_class_get_expr) ppf (class_id, class_get_expr) | Aast.Class_const (class_id, (_, cname)) -> Fmt.(pair ~sep:dbl_colon pp_class_id string) ppf (class_id, cname) | Aast.(Call { func; targs; args; unpacked_arg }) -> Fmt.(pair ~sep:nop pp_expr @@ pair ~sep:nop pp_targs pp_arg_exprs) ppf (func, (targs, (args, unpacked_arg))) | Aast.FunctionPointer (id, targs) -> Fmt.(pair ~sep:nop pp_function_ptr_id (angles @@ list ~sep:comma pp_targ)) ppf (id, targs) | Aast.Int str | Aast.Float str -> Fmt.string ppf str | Aast.String str -> Fmt.(quote string) ppf @@ String.substr_replace_all ~pattern:"'" ~with_:"\\'" str | Aast.String2 exprs -> Fmt.(quote @@ list ~sep:sp pp_expr) ppf exprs | Aast.PrefixedString (pfx, expr) -> Fmt.(pair ~sep:nop string @@ quote pp_expr) ppf (pfx, expr) | Aast.Yield afield -> Fmt.(prefix (const string "yield") pp_afield) ppf afield | Aast.Await expr -> Fmt.(prefix (const string "await") pp_expr) ppf expr | Aast.ReadonlyExpr expr -> Fmt.(prefix (const string "readonly") pp_expr) ppf expr | Aast.List exprs -> Fmt.(prefix (const string "list") @@ parens @@ list ~sep:comma pp_expr) ppf exprs | Aast.Tuple exprs -> Fmt.(prefix (const string "tuple") @@ parens @@ list ~sep:comma pp_expr) ppf exprs | Aast.Cast (hint, expr) -> Fmt.(pair ~sep:nop (parens @@ pp_hint ~is_ctx:false) pp_expr) ppf (hint, expr) | Aast.Unop (unop, expr) when is_postfix_unop unop -> Fmt.(pair ~sep:nop pp_expr pp_unop) ppf (expr, unop) | Aast.Unop (unop, expr) -> Fmt.(pair ~sep:nop pp_unop pp_expr) ppf (unop, expr) | Aast.(Binop { bop; lhs; rhs }) -> Fmt.(pair ~sep:sp pp_expr @@ pair ~sep:sp pp_binop pp_expr) ppf (lhs, (bop, rhs)) | Aast.Pipe (_lid, e1, e2) -> Fmt.(pair ~sep:(const string " |> ") pp_expr pp_expr) ppf (e1, e2) | Aast.Eif (cond, Some texpr, fexpr) -> Fmt.( pair ~sep:(const string " ? ") pp_expr @@ pair ~sep:colon pp_expr pp_expr) ppf (cond, (texpr, fexpr)) | Aast.Eif (cond, _, expr) -> Fmt.(pair ~sep:(const string " ?: ") pp_expr pp_expr) ppf (cond, expr) | Aast.Is (expr, hint) -> Fmt.(pair ~sep:(const string " is ") pp_expr @@ pp_hint ~is_ctx:false) ppf (expr, hint) | Aast.As (expr, hint, false) -> Fmt.(pair ~sep:(const string " as ") pp_expr @@ pp_hint ~is_ctx:false) ppf (expr, hint) | Aast.As (expr, hint, true) -> Fmt.(pair ~sep:(const string " ?as ") pp_expr @@ pp_hint ~is_ctx:false) ppf (expr, hint) | Aast.Upcast (expr, hint) -> Fmt.(pair ~sep:(const string " upcast ") pp_expr @@ pp_hint ~is_ctx:false) ppf (expr, hint) | Aast.New (class_id, targs, exprs, expr_opt, _) -> Fmt.( prefix (const string "new") @@ pair ~sep:nop pp_class_id @@ pair ~sep:nop pp_targs pp_arg_exprs) ppf ( class_id, (targs, (List.map ~f:(fun e -> (Ast_defs.Pnormal, e)) exprs, expr_opt)) ) | Aast.Lplaceholder _ -> Fmt.string ppf "$_" | Aast.Pair (targs_opt, fst, snd) -> Fmt.( prefix (const string "Pair") @@ pair ~sep:nop (option @@ angles @@ pair ~sep:comma pp_targ pp_targ) (braces @@ pair ~sep:comma pp_expr pp_expr)) ppf (targs_opt, (fst, snd)) | Aast.Hole (expr, _, _, _) -> pp_expr ppf expr | Aast.EnumClassLabel (opt_sid, name) -> begin match opt_sid with | None -> Fmt.(prefix dbl_hash string) ppf name | Some (_, class_name) -> Fmt.(pair ~sep:dbl_hash Fmt.string string) ppf (class_name, name) end | Aast.Invalid (Some expr) -> pp_expr ppf expr | Aast.Package (_, id) -> Fmt.string ppf id | Aast.Invalid _ | Aast.Efun _ | Aast.Lfun _ | Aast.Xml _ | Aast.Import _ | Aast.Collection _ | Aast.ExpressionTree _ | Aast.Method_caller _ | Aast.ET_Splice _ | Aast.Omitted -> () and pp_arg_exprs ppf (exprs, expr_opt) = match exprs with | [] -> Fmt.(parens @@ option @@ prefix (const string "...") pp_expr) ppf expr_opt | _ -> Fmt.( parens @@ pair ~sep:comma (list ~sep:comma pp_arg) (option @@ prefix (const string "...") pp_expr)) ppf (exprs, expr_opt) and pp_arg ppf (pk, e) = match pk with | Ast_defs.Pnormal -> pp_expr ppf e | Ast_defs.Pinout _ -> Fmt.(pair ~sep:sp pp_paramkind pp_expr) ppf (pk, e) and pp_afield ppf = function | Aast.AFvalue expr -> pp_expr ppf expr | Aast.AFkvalue (key_expr, val_expr) -> Fmt.(pair ~sep:fat_arrow pp_expr pp_expr) ppf (key_expr, val_expr) and pp_class_id ppf (_, _, class_id_) = match class_id_ with | Aast.CIparent -> Fmt.string ppf "parent" | Aast.CIstatic -> Fmt.string ppf "static" | Aast.CIself -> Fmt.string ppf "self" | Aast.CI (_, name) -> Fmt.string ppf name | Aast.CIexpr expr -> pp_expr ppf expr and pp_class_get_expr ppf = function | Aast.CGexpr expr -> pp_expr ppf expr | Aast.CGstring (_, name) -> Fmt.string ppf name and pp_function_ptr_id ppf = function | Aast.FP_id (_, name) -> Fmt.string ppf name | Aast.FP_class_const (class_id, (_, str)) -> Fmt.(pair ~sep:dbl_colon pp_class_id string) ppf (class_id, str) let pp_user_attr ppf Aast.{ ua_name = (_, nm); ua_params; _ } = match ua_params with | [] -> Fmt.string ppf nm | _ -> Fmt.(pair ~sep:nop string @@ parens @@ list ~sep:comma pp_expr) ppf (nm, ua_params) let pp_user_attrs ppf = function | [] -> () | rs -> Fmt.(angles @@ angles @@ list ~sep:comma pp_user_attr) ppf rs let pp_variance ppf = Ast_defs.( function | Covariant -> Fmt.string ppf "+" | Contravariant -> Fmt.string ppf "-" | Invariant -> ()) let pp_constraint_kind ppf = Ast_defs.( function | Constraint_as -> Fmt.string ppf "as" | Constraint_eq -> Fmt.string ppf "=" | Constraint_super -> Fmt.string ppf "super") let pp_constraint ppf (kind, hint) = Format.(fprintf ppf {|%a %a|}) pp_constraint_kind kind (pp_hint ~is_ctx:false) hint let pp_tp_reified ppf = Aast.( function | Erased -> () | SoftReified | Reified -> Fmt.string ppf "reify") let rec pp_tparam ppf Aast. { tp_variance; tp_name = (_, name); tp_parameters; tp_constraints; tp_reified; tp_user_attributes; } = Format.( fprintf ppf {|%a %a %a%s %a %a |} pp_user_attrs tp_user_attributes pp_tp_reified tp_reified pp_variance tp_variance name pp_tparams tp_parameters Fmt.(list ~sep:sp pp_constraint) tp_constraints) and pp_tparams ppf ps = match List.filter ~f:(fun Aast.{ tp_name = (_, name); _ } -> not (SN.Coeffects.is_generated_generic name)) ps with | [] -> () | ps -> Fmt.(angles @@ list ~sep:comma pp_tparam) ppf ps let pp_type_hint ~is_ret_type ppf (_, hint) = if is_ret_type then Fmt.(option @@ prefix (const string ": ") @@ pp_hint ~is_ctx:false) ppf hint else Fmt.(option @@ suffix sp @@ pp_hint ~is_ctx:false) ppf hint
OCaml Interface
hhvm/hphp/hack/src/typing/hint_print.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 pp_tparam : Format.formatter -> ('a, 'b) Aast.tparam -> unit val pp_tparams : Format.formatter -> ('a, 'b) Aast.tparam list -> unit val pp_hint : is_ctx:bool -> Format.formatter -> Aast.hint -> unit val pp_user_attrs : Format.formatter -> ('a, 'b) Aast.user_attribute list -> unit val pp_type_hint : is_ret_type:bool -> Format.formatter -> 'a Aast.type_hint -> unit val any_type_name : string
OCaml
hhvm/hphp/hack/src/typing/internal_type_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 = internal_type [@@deriving show] let compare ty1 ty2 = match (ty1, ty2) with | (LoclType ty1, LoclType ty2) -> compare_locl_ty ty1 ty2 | (ConstraintType ty1, ConstraintType ty2) -> constraint_ty_compare ty1 ty2 | (LoclType _, ConstraintType _) -> 1 | (ConstraintType _, LoclType _) -> -1 end include Caml.Set.Make (Ty_) let fold_map set ~init:acc ~f = fold (fun x (acc, res) -> let (acc, x) = f acc x in let res = add x res in (acc, res)) set (acc, empty) 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/nastInitCheck.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (* Module checking that all the class members are properly initialized. * To be more precise, this checks that if the constructor does not throw, * it initializes all members. *) open Hh_prelude open Aast open Nast module DICheck = Decl_init_check module SN = Naming_special_names module Native = Typing_native module SSetWTop = struct type t = | Top | Set of SSet.t let union s1 s2 = match (s1, s2) with | (Top, _) | (_, Top) -> Top | (Set s1, Set s2) -> Set (SSet.union s1 s2) let inter s1 s2 = match (s1, s2) with | (Top, s) | (s, Top) -> s | (Set s1, Set s2) -> Set (SSet.inter s1 s2) let inter_list (sl : t list) = List.fold_left ~f:inter ~init:Top sl let add x s = match s with | Top -> Top | Set s -> Set (SSet.add x s) let mem x s = match s with | Top -> true | Set s -> SSet.mem x s let empty = Set SSet.empty end let parent_init_prop = "parent::" ^ SN.Members.__construct let lookup_props env class_name props = SSet.fold begin fun name map -> let ty_opt = if String.equal name parent_init_prop then Some (Typing_make_type.nonnull Typing_reason.Rnone) else Typing_env.get_class env class_name |> Option.bind ~f:(fun cls -> Typing_env.get_member false env cls name) |> Option.bind ~f:(fun ce -> Some (Lazy.force ce.Typing_defs.ce_type)) in SMap.add name ty_opt map end props SMap.empty (* If a type is missing, nullable, or dynamic, initialization is not required *) let type_does_not_require_init env ty_opt = match ty_opt with | None -> true | Some ty -> let ((env, ty_err_opt), ty) = Typing_phase.localize_no_subst env ~ignore_errors:true ty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let null = Typing_make_type.null Typing_reason.Rnone in Typing_subtype.is_sub_type env null ty || let dynamic = Typing_make_type.dynamic Typing_reason.Rnone in Typing_subtype.is_sub_type env dynamic ty && Typing_subtype.is_sub_type env ty dynamic module S = SSetWTop (* Exception raised when we hit a return statement and the initialization * is not over. * When that is the case, we bubble up back to the toplevel environment. * An example (right hand side is the set of things initialized): * * $this->x = 0; // { x } * if(...) { * $this->y = 1; // { x, y } * if(...) { * $this->z = 2; // { x, y, z } * return; // raise InitReturn with set { x, y, z} * } // exception caught, re-raise with { x, y } * } // exception caught, re-reraise with { x } * * What is effectively initialized: { x } *) exception InitReturn of S.t let filter_props_by_type env cls props = lookup_props env cls props |> SMap.filter (fun _ ty -> not (type_does_not_require_init env ty)) |> SMap.keys |> SSet.of_list (* Module initializing the environment Originally, every class member has 2 possible states, Vok ==> when it is declared as optional, it is the job of the typer to make sure it is always check for the null case not our problem here Vnull ==> The value is now null, it MUST be initialized, and cannot be used before it has been initialized. Concerning the methods, basically the information we are interested in is, which class members do they initialize? But we don't want to recompute it every time it is called. So we memoize the result: hence the type method status. *) module Env = struct type method_status = (* We already computed this method *) | Done (* We have never computed this private method before *) | Todo of func_body type t = { methods: method_status ref SMap.t; props: Typing_defs.decl_ty option SMap.t; tenv: Typing_env_types.env; parent_cstr_props: SSet.t; init_not_required_props: SSet.t; } let rec make tenv c = let (_, _, methods) = split_methods c.c_methods in let methods = List.fold_left ~f:method_ ~init:SMap.empty methods in (* In Zoncolan, we don't support eviction. We don't support lazy reparsing of shallow decls. If we try and the shallow decl is not available, we'll crash Zoncolan. Therefore, we shouldn't fallback. *) let ctx = Typing_env.get_ctx tenv in let supports_eviction = Provider_backend.supports_eviction (Provider_context.get_backend ctx) in let fallback = if not supports_eviction then Decl_env.no_fallback else fun _env x -> Option.map ~f:fst (Decl_folded_class.class_decl_if_missing ~sh:SharedMem.Uses ctx x) in let get_class_add_dep env x = Decl_env.get_class_and_add_dep ~cache:SMap.empty ~shmem_fallback:true ~fallback env x in (* Error when an abstract class has private properties but lacks a constructor *) let has_own_cstr = let (c_constructor, _, _) = split_methods c.c_methods in match c_constructor with | Some s -> not s.m_abstract | None -> false in let (private_props, _) = (DICheck.private_deferred_init_props ~has_own_cstr c, SSet.empty) in let private_props = lookup_props tenv (snd c.c_name) private_props in (if Ast_defs.is_c_abstract c.c_kind && not has_own_cstr then let uninit = SMap.filter (fun _ ty_opt -> not (type_does_not_require_init tenv ty_opt)) private_props in if not @@ SMap.is_empty uninit then let prop_names = SMap.bindings uninit |> List.map ~f:fst and (pos, class_name) = c.c_name in Errors.add_error Nast_check_error.( to_user_error @@ Constructor_required { pos; class_name; prop_names })); let ( add_init_not_required_props, add_trait_props, add_parent_props, add_parent, parent_cstr_props ) = let decl_env = tenv.Typing_env_types.decl_env in ( DICheck.init_not_required_props c, DICheck.trait_props ~get_class_add_dep decl_env c, DICheck.parent_props ~get_class_add_dep decl_env c, DICheck.parent ~get_class_add_dep decl_env c, DICheck.parent_initialized_members ~get_class_add_dep decl_env c |> filter_props_by_type tenv (snd c.c_name) ) in let init_not_required_props = add_init_not_required_props SSet.empty in let props = SSet.empty |> DICheck.own_props c (* If we define our own constructor, we need to pretend any traits we use * did *not* define a constructor, because they are not reachable through * parent::__construct or similar functions. *) |> add_trait_props |> add_parent_props |> add_parent |> lookup_props tenv (snd c.c_name) |> SMap.filter (fun _ ty_opt -> not (type_does_not_require_init tenv ty_opt)) in { methods; props; parent_cstr_props; tenv; init_not_required_props } and method_ acc m = if not (Aast.equal_visibility m.m_visibility Private) then acc else let name = snd m.m_name in let acc = SMap.add name (ref (Todo m.m_body)) acc in acc let get_method env m = SMap.find_opt m env.methods end open Env (*****************************************************************************) (* List of functions that can use '$this' before the initialization is * over. *) (*****************************************************************************) let is_whitelisted = function | x when String.equal x SN.StdlibFunctions.get_class -> true | _ -> false let is_lateinit cv = Naming_attributes.mem SN.UserAttributes.uaLateInit cv.cv_user_attributes let class_prop_pos class_name prop_name ctx : Pos_or_decl.t = match Decl_provider.get_class ctx class_name with | None -> Pos_or_decl.none | Some decl -> (match Decl_provider.Class.get_prop decl prop_name with | None -> Pos_or_decl.none | Some elt -> let member_origin = elt.Typing_defs.ce_origin in let get_class_by_name ctx x = let open Option.Monad_infix in Naming_provider.get_type_path ctx x >>= fun fn -> Ast_provider.find_class_in_file ctx fn x ~full:false in (match get_class_by_name ctx member_origin with | None -> Pos_or_decl.none | Some cls -> (match List.find cls.Aast.c_vars ~f:(fun cv -> String.equal (snd cv.Aast.cv_id) prop_name) with | None -> (* We found the class prop's origin via Typing_defs.ce_origin, so we *should* find the prop in the class. This is an invariant violation. *) HackEventLogger.decl_consistency_bug "nastInitCheck can't find expected class prop" ~data: (Printf.sprintf "class_name=%s; member_origin=%s; prop_name=%s" class_name member_origin prop_name); Errors.internal_error Pos.none ("Invariant violation: please report this bug via the VSCode bug button. Expected to find prop_name " ^ prop_name ^ " in class " ^ member_origin); Pos_or_decl.none | Some cv -> Pos_or_decl.of_raw_pos @@ fst cv.Aast.cv_id))) (** * Returns the set of properties initialized by the constructor. * More exactly, returns a SSetWTop.t, i.e. either a set, or Top, which is * the top element of the set of sets of properties, i.e. a set containing * all the possible properties. * Top is returned for a block of statements if * this block always throws. It is an abstract construct used to deal * gracefully with control flow. * * For example, if we have an `if` statement like: * * ``` * if (...) { * // This branch initialize a set of properties S1 * ... * } else { * // This branch initialize another set of properties S2 * ... * } * ``` * * then the set `S` of properties initialized by this `if` statement is the * intersection `S1 /\ S2`. * If one of the branches throws, say the first branch, then the set `S` * of properties initialized by the `if` statement is equal to the set of * properties initialized by the branch that does not throw, i.e. `S = S2`. * This amounts to saying that `S1` is some top element of the set of sets * of variables, which we call `Top`, which has the property that for all * set S of properties, S is included in `Top`, such that `S = S1 /\ S2` * still holds. *) let rec constructor env cstr = match cstr with | None -> S.empty | Some cstr -> let check_param_initializer e = ignore (expr env S.empty e) in List.iter cstr.m_params ~f:(fun p -> Option.iter p.param_expr ~f:check_param_initializer); let b = cstr.m_body in toplevel env S.empty b.fb_ast and assign _env acc x = S.add x acc and assign_expr env acc e1 = match e1 with | (_, _, Obj_get ((_, _, This), (_, _, Id (_, y)), _, Is_prop)) -> assign env acc y | (_, _, List el) -> List.fold_left ~f:(assign_expr env) ~init:acc el | _ -> acc and argument_list env acc el = List.fold_left ~f:(fun acc_ (_, e) -> expr env acc_ e) ~init:acc el and stmt env acc st = let expr = expr env in let block = block env in let catch = catch env in let case = case env in let default_case = default_case env in match snd st with | Expr (* only in top level!*) ( _, _, Call { func = (_, _, Class_const ((_, _, CIparent), (_, m))); args; _ } ) when String.equal m SN.Members.__construct -> let acc = argument_list env acc args in assign env acc DICheck.parent_init_prop | Expr e -> if Typing_func_terminality.expression_exits env.tenv e then S.Top else expr acc e | Break -> acc | Continue -> acc | Throw _ -> S.Top | Return None -> if are_all_init env acc then acc else raise (InitReturn acc) | Yield_break -> S.Top | Return (Some x) -> let acc = expr acc x in if are_all_init env acc then acc else raise (InitReturn acc) | Awaitall (el, b) -> let acc = List.fold_left el ~init:acc ~f:(fun acc (_, e2) -> expr acc e2) in let acc = block acc b in acc | If (e1, b1, b2) -> let acc = expr acc e1 in let b1 = block acc b1 in let b2 = block acc b2 in S.union acc (S.inter b1 b2) | Do (b, e) -> let acc = block acc b in expr acc e | While (e, _) -> expr acc e | Using us -> let acc = List.fold_left (snd us.us_exprs) ~f:expr ~init:acc in block acc us.us_block | For (e1, _, _, _) -> exprl env acc e1 | Switch (e, cl, dfl) -> let acc = expr acc e in (* Filter out cases that fallthrough *) (* NOTE: 'default' never fallthough *) let cl_body = List.filter cl ~f:case_has_body in let cl = List.map cl_body ~f:(case acc) in let cdfl = dfl |> Option.map ~f:(default_case acc) in let c = S.inter_list cl in let c = Option.fold ~init:c ~f:S.inter cdfl in S.union acc c | Foreach (e, _, _) -> let acc = expr acc e in acc | Try (b, cl, fb) -> let c = block acc b in let f = block acc fb in let cl = List.map cl ~f:(catch acc) in let c = S.inter_list (c :: cl) in (* the finally block executes even if *none* of try and catch do *) let acc = S.union acc f in S.union acc c | Fallthrough -> S.empty | Noop -> acc | Declare_local (_, _, Some e) -> expr acc e | Declare_local (_, _, None) -> acc | Block b -> block acc b | Markup _ -> acc | AssertEnv _ -> acc | Match _ -> failwith "TODO(jakebailey): match statements" and toplevel env acc l = try List.fold_left ~f:(stmt env) ~init:acc l with | InitReturn acc -> acc and block env acc l = let acc_before_block = acc in try List.fold_left ~f:(stmt env) ~init:acc l with | InitReturn _ -> (* The block has a return statement, forget what was initialized in it *) raise (InitReturn acc_before_block) and are_all_init env set = SMap.fold (fun cv _ acc -> acc && S.mem cv set) env.props true and check_all_init pos env acc = SMap.iter begin fun prop_name _ -> if not (S.mem prop_name acc) then Errors.add_error Nast_check_error.( to_user_error @@ Call_before_init { pos; prop_name }) end env.props and exprl env acc l = List.fold_left ~f:(expr env) ~init:acc l and expr env acc (_, p, e) = expr_ env acc p e and expr_ env acc p e = let expr = expr env in let exprl = exprl env in let field = field env in let afield = afield env in let fun_paraml = fun_paraml env in match e with | Darray (_, fdl) -> List.fold_left ~f:field ~init:acc fdl | Varray (_, fdl) -> List.fold_left ~f:expr ~init:acc fdl | ValCollection (_, _, el) -> exprl acc el | KeyValCollection (_, _, fdl) -> List.fold_left ~f:field ~init:acc fdl | This -> check_all_init p env acc; acc | Method_caller _ | EnumClassLabel _ | Id _ -> acc | Lvar _ | Lplaceholder _ | Dollardollar _ -> acc | Obj_get ((_, _, This), (_, _, Id ((_, vx) as v)), _, Is_prop) -> if SMap.mem vx env.props && not (S.mem vx acc) then ( let (pos, member_name) = v in Errors.add_error Nast_check_error.( to_user_error @@ Read_before_write { pos; member_name }); acc ) else if SSet.mem vx env.parent_cstr_props && (not (SSet.mem vx env.init_not_required_props)) && (not (S.mem vx acc)) && not (S.mem parent_init_prop acc) then ( (* We're reading a property that's initialised in the parent constructor, but we haven't called the parent constructor yet. *) let (pos, member_name) = v in Errors.add_error Nast_check_error.( to_user_error @@ Read_before_write { pos; member_name }); acc ) else acc | Clone e -> expr acc e | Obj_get (e1, e2, _, _) -> let acc = expr acc e1 in expr acc e2 | Array_get (e, eo) -> let acc = expr acc e in (match eo with | None -> acc | Some e -> expr acc e) | Class_const _ | Class_get _ -> acc | Call { func = (_, p, Obj_get ((_, _, This), (_, _, Id (_, f)), _, Is_method)); args; unpacked_arg; _; } -> let method_ = Env.get_method env f in (match method_ with | None -> check_all_init p env acc; acc | Some method_ -> (match !method_ with | Done -> acc | Todo b -> (* First time we encounter this private method. Let's check its * arguments first, and then recurse into the method body. *) let acc = argument_list env acc args in let acc = Option.value_map ~f:(expr acc) ~default:acc unpacked_arg in method_ := Done; toplevel env acc b.fb_ast)) | Call { func; args; unpacked_arg; _ } -> let args = match func with | (_, _, Id (_, fun_name)) when is_whitelisted fun_name -> List.filter args ~f:(function | (_, (_, _, This)) -> false | _ -> true) | _ -> args in let acc = argument_list env acc args in let acc = Option.value_map ~f:(expr acc) ~default:acc unpacked_arg in expr acc func | True | False | Int _ | Float _ | Null | String _ | String2 _ | PrefixedString _ -> acc | Yield e -> afield acc e | Await e -> expr acc e | Tuple el -> List.fold_left ~f:expr ~init:acc el | List _ -> (* List is always an lvalue *) acc | New (_, _, el, unpacked_element, _) -> let acc = exprl acc el in let acc = Option.value_map ~default:acc ~f:(expr acc) unpacked_element in acc | Pair (_, e1, e2) -> let acc = expr acc e1 in expr acc e2 | Cast (_, e) | Unop (_, e) -> expr acc e | Binop Aast.{ bop = Ast_defs.Eq None; lhs = e1; rhs = e2 } -> let acc = expr acc e2 in assign_expr env acc e1 | Binop Aast.{ bop = Ast_defs.Ampamp; lhs = e; _ } | Binop Aast.{ bop = Ast_defs.Barbar; lhs = e; _ } -> expr acc e | Binop Aast.{ lhs = e1; rhs = e2; _ } -> let acc = expr acc e1 in expr acc e2 | Pipe (_, e1, e2) -> let acc = expr acc e1 in expr acc e2 | Eif (e1, None, e3) -> let acc = expr acc e1 in expr acc e3 | Eif (e1, Some e2, e3) -> let acc = expr acc e1 in let acc = expr acc e2 in expr acc e3 | Is (e, _) -> expr acc e | As (e, _, _) -> expr acc e | Upcast (e, _) -> expr acc e | Efun { ef_fun = f; _ } | Lfun (f, _) -> let acc = fun_paraml acc f.f_params in (* We don't need to analyze the body of closures *) acc | Xml (_, l, el) -> let l = List.map l ~f:get_xhp_attr_expr in let acc = exprl acc l in exprl acc el | Shape fdm -> List.fold_left ~f: begin (fun acc (_, v) -> expr acc v) end ~init:acc fdm | ExpressionTree _ -> acc | Omitted -> acc | Import _ -> acc | Collection _ -> acc | FunctionPointer _ -> acc | ET_Splice e -> expr acc e | ReadonlyExpr e -> expr acc e | Hole (e, _, _, _) -> expr acc e (* Don't analyze invalid expressions *) | Invalid _ -> acc | Package _ -> acc and case env acc ((_, b) : (_, _) Aast.case) = block env acc b and case_has_body ((_, b) : (_, _) Aast.case) = not (List.is_empty b) and default_case env acc ((_, b) : (_, _) Aast.default_case) = block env acc b and catch env acc (_, _, b) = block env acc b and field env acc (e1, e2) = let acc = expr env acc e1 in let acc = expr env acc e2 in acc and afield env acc = function | AFvalue e -> expr env acc e | AFkvalue (e1, e2) -> let acc = expr env acc e1 in let acc = expr env acc e2 in acc and fun_param env acc param = match param.param_expr with | None -> acc | Some x -> expr env acc x and fun_paraml env acc l = List.fold_left ~f:(fun_param env) ~init:acc l let class_ tenv c = let is_hhi = FileInfo.is_hhi c.c_mode in if not is_hhi then List.iter c.c_vars ~f:(fun cv -> match cv.cv_expr with | Some _ when is_lateinit cv -> Errors.add_error Nast_check_error.( to_user_error @@ Lateinit_with_default (fst cv.cv_id)) | None when cv.cv_is_static -> let ty_opt = Option.map ~f:(Decl_hint.hint tenv.Typing_env_types.decl_env) (hint_of_type_hint cv.cv_type) in if is_lateinit cv || cv.cv_abstract || type_does_not_require_init tenv ty_opt then () else Errors.add_error Nast_check_error.(to_user_error @@ Missing_assign (fst cv.cv_id)) | _ -> ()); let (c_constructor, _, _) = split_methods c.c_methods in match c_constructor with | _ when Ast_defs.is_c_interface c.c_kind -> () | Some _ when FileInfo.is_hhi c.c_mode -> () | Some m when Native.is_native_meth ~env:tenv m -> (* If we're checking a `__Native` constructor then all bets are off: there's * no way to verify that properties are initialized correctly, including if * we've called parent::__construct. *) () | _ -> let p = match c_constructor with | Some m -> fst m.m_name | None -> fst c.c_name in let env = Env.make tenv c in let inits = constructor env c_constructor in let check_inits inits = let uninit_props = SMap.filter (fun k _ -> not (SSet.mem k inits)) env.props in if not (SMap.is_empty uninit_props) then if SMap.mem DICheck.parent_init_prop uninit_props then Errors.add_error Nast_check_error.(to_user_error @@ No_construct_parent p) else let class_uninit_props = SMap.filter (fun prop _ -> not (SSet.mem prop env.init_not_required_props)) uninit_props in if (not (SMap.is_empty class_uninit_props)) && not is_hhi then Errors.add_error Nast_check_error.( to_user_error @@ Not_initialized { pos = p; class_name = snd c.c_name; props = SMap.bindings class_uninit_props |> List.map ~f:(fun (name, _) -> let pos = class_prop_pos (snd c.c_name) name (Typing_env.get_ctx tenv) in (pos, name)); }) in let check_throws_or_init_all inits = match inits with | S.Top -> (* Constructor always throw, so checking that all properties are * initialized is irrelevant. *) () | S.Set inits -> check_inits inits in if Ast_defs.is_c_trait c.c_kind || Ast_defs.is_c_abstract c.c_kind then let has_constructor = match c_constructor with | None -> false | Some m when m.m_abstract -> false | Some _ -> true in if has_constructor then check_throws_or_init_all inits else () else check_throws_or_init_all inits
OCaml Interface
hhvm/hphp/hack/src/typing/nastInitCheck.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 class_ : Typing_env_types.env -> Nast.class_ -> unit
OCaml
hhvm/hphp/hack/src/typing/nast_check_env.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 control_context = | Toplevel | LoopContext | SwitchContext type env = { ctx: Provider_context.t; classish_kind: Ast_defs.classish_kind option; class_name: string option; function_name: Ast_defs.id option; file_mode: FileInfo.mode; function_kind: Ast_defs.fun_kind option; is_finally: bool; control_context: control_context; array_append_allowed: bool; module_: Ast_defs.id option; } let get_tcopt env = Provider_context.get_tcopt env.ctx let fun_env env f = { env with function_kind = Some f.f_fun_kind } let fun_def_env env fd = { (fun_env env fd.fd_fun) with function_name = Some fd.fd_name; file_mode = fd.fd_mode; module_ = fd.fd_module; } let method_env env m = { env with function_name = Some m.m_name; function_kind = Some m.m_fun_kind } let class_env env c = { env with classish_kind = Some c.c_kind; class_name = Some (snd c.c_name); file_mode = c.c_mode; module_ = c.c_module; } let typedef_env env t = { env with file_mode = t.t_mode; module_ = t.t_module } let get_empty_env ctx = { ctx; classish_kind = None; class_name = None; function_name = None; file_mode = FileInfo.Mstrict; function_kind = None; is_finally = false; control_context = Toplevel; array_append_allowed = false; module_ = None; } let def_env ctx x = let empty_env = get_empty_env ctx in match x with | Fun f -> fun_def_env empty_env f | Class c -> class_env empty_env c | Typedef t -> typedef_env empty_env t | SetModule _ | Constant _ | Stmt _ | Namespace _ | NamespaceUse _ | SetNamespaceEnv _ | FileAttributes _ (* TODO(T108206307) *) | Module _ -> empty_env
OCaml
hhvm/hphp/hack/src/typing/nast_visitor.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 class virtual iter = object (self) inherit [_] Aast.iter as super (* Entry point *) method go (ctx : Provider_context.t) (program : Nast.program) = self#on_list (fun () -> self#go_def ctx) () program method go_def ctx x = self#on_def (def_env ctx x) x method! on_fun_def env x = super#on_fun_def (fun_def_env env x) x method! on_fun_ env x = super#on_fun_ (fun_env env x) x method! on_method_ env x = super#on_method_ (method_env env x) x method! on_class_ env x = super#on_class_ (class_env env x) x method! on_Try env b cl fb = self#on_block env b; List.iter cl ~f:(fun c -> self#on_catch env c); self#on_block { env with is_finally = true } fb method! on_Do env = super#on_Do { env with control_context = LoopContext } method! on_While env = super#on_While { env with control_context = LoopContext } method! on_For env = super#on_For { env with control_context = LoopContext } method! on_Foreach env = super#on_Foreach { env with control_context = LoopContext } method! on_Switch env = super#on_Switch { env with control_context = SwitchContext } method! on_Efun env = super#on_Efun { env with is_finally = false; control_context = Toplevel } method! on_Lfun env = super#on_Lfun { env with is_finally = false; control_context = Toplevel } method! on_Obj_get env = super#on_Obj_get { env with array_append_allowed = false } method! on_Array_get env = super#on_Array_get { env with array_append_allowed = false } method! on_Binop env (Aast.{ bop; lhs; rhs } as binop) = match bop with | Ast_defs.Eq None -> self#on_expr { env with array_append_allowed = true } lhs; self#on_expr env rhs | _ -> super#on_Binop env binop method! on_func_body env fb = match fb.fb_ast with | [(_, If (((_, _, Id (_, _)) as id), then_stmt, else_stmt))] -> super#on_expr env id; self#on_block env then_stmt; self#on_block env else_stmt | _ -> super#on_func_body env fb method! on_expr env e = match e with | (_, _, Call call_expr) -> self#on_Call env call_expr | (_, _, Binop ({ bop = Ast_defs.Eq None; _ } as binop)) -> self#on_Binop env binop | _ -> super#on_expr env e end class virtual ['state] iter_with_state = object (self) inherit [_] Aast.iter as super (* Entry point *) method go (state : 'state) (ctx : Provider_context.t) (program : Nast.program) = self#on_list (fun () -> self#go_def state ctx) () program method go_def state ctx x = self#on_def (def_env ctx x, state) x method! on_fun_def (env, state) x = super#on_fun_def (fun_def_env env x, state) x end class type handler = object method at_fun_def : env -> Nast.fun_def -> unit method at_fun_ : env -> Nast.fun_ -> unit method at_class_ : env -> Nast.class_ -> unit method at_method_ : env -> Nast.method_ -> unit method at_expr : env -> Nast.expr -> unit method at_stmt : env -> Nast.stmt -> unit method at_hint : env -> hint -> unit method at_contexts : env -> contexts -> unit method at_typedef : env -> Nast.typedef -> unit method at_gconst : env -> Nast.gconst -> unit end class virtual handler_base : handler = object method at_fun_def _ _ = () method at_fun_ _ _ = () method at_class_ _ _ = () method at_method_ _ _ = () method at_expr _ _ = () method at_stmt _ _ = () method at_hint _ _ = () method at_contexts _ _ = () method at_typedef _ _ = () method at_gconst _ _ = () end let iter_with (handlers : handler list) : iter = object inherit iter as super method! on_fun_def env x = List.iter handlers ~f:(fun v -> v#at_fun_def env x); super#on_fun_def env x method! on_fun_ env x = List.iter handlers ~f:(fun v -> v#at_fun_ env x); super#on_fun_ env x method! on_class_ env x = List.iter handlers ~f:(fun v -> v#at_class_ env x); super#on_class_ env x method! on_method_ env x = List.iter handlers ~f:(fun v -> v#at_method_ env x); super#on_method_ env x method! on_expr env x = List.iter handlers ~f:(fun v -> v#at_expr env x); super#on_expr env x method! on_stmt env x = List.iter handlers ~f:(fun v -> v#at_stmt env x); super#on_stmt env x method! on_hint env h = List.iter handlers ~f:(fun v -> v#at_hint env h); super#on_hint env h method! on_contexts env cl = List.iter handlers ~f:(fun v -> v#at_contexts env cl); super#on_contexts env cl method! on_typedef env t = List.iter handlers ~f:(fun v -> v#at_typedef env t); super#on_typedef env t method! on_gconst env gconst = List.iter handlers ~f:(fun v -> v#at_gconst env gconst); super#on_gconst env gconst end
OCaml
hhvm/hphp/hack/src/typing/stateful_aast_visitor.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. * *) (** * Classes that implement this will be called at every node in the AST * Used to implement NAST error checking * The order of the nodes traversed will be from root (program) to leaf * Each method will always be called at their respective nodes * Each class can maintain their own state which will be threaded to children *) class type virtual ['env] nast_visitor_with_state = object method virtual initial_state : 'env method at_fun_def : 'env -> Nast.fun_def -> 'env method at_class_ : 'env -> Nast.class_ -> 'env method at_method_ : 'env -> Nast.method_ -> 'env method at_expr : 'env -> Nast.expr -> 'env method at_stmt : 'env -> Nast.stmt -> 'env method at_hint : 'env -> Aast.hint -> 'env method at_typedef : 'env -> Nast.typedef -> 'env method at_gconst : 'env -> Nast.gconst -> 'env method at_file_attribute : 'env -> Nast.file_attribute -> 'env method at_shape_field_name : 'env -> Nast.shape_field_name -> 'env method at_user_attribute : 'env -> Nast.user_attribute -> 'env method at_class_id : 'env -> Nast.class_id -> 'env method at_catch : 'env -> Nast.catch -> 'env method at_targ : 'env -> Nast.targ -> 'env method at_class_hint : 'env -> Nast.class_hint -> 'env method at_trait_hint : 'env -> Nast.trait_hint -> 'env method at_xhp_attr_hint : 'env -> Nast.xhp_attr_hint -> 'env end class virtual ['env] default_nast_visitor_with_state : ['env] nast_visitor_with_state = object method virtual initial_state : 'env method at_fun_def env _ = env method at_class_ env _ = env method at_method_ env _ = env method at_expr env _ = env method at_stmt env _ = env method at_hint env _ = env method at_typedef env _ = env method at_gconst env _ = env method at_file_attribute env _ = env method at_shape_field_name env _ = env method at_user_attribute env _ = env method at_class_id env _ = env method at_catch env _ = env method at_targ env _ = env method at_class_hint env _ = env method at_trait_hint env _ = env method at_xhp_attr_hint env _ = env end let combine_visitors = let visit v1 v2 (env1, env2) node = (v1 env1 node, v2 env2 node) in let combine (visitor1 : 'env1 nast_visitor_with_state) (visitor2 : 'env2 nast_visitor_with_state) : ('env1 * 'env2) nast_visitor_with_state = object method initial_state = (visitor1#initial_state, visitor2#initial_state) method at_fun_def = visit visitor1#at_fun_def visitor2#at_fun_def method at_class_ = visit visitor1#at_class_ visitor2#at_class_ method at_method_ = visit visitor1#at_method_ visitor2#at_method_ method at_expr = visit visitor1#at_expr visitor2#at_expr method at_stmt = visit visitor1#at_stmt visitor2#at_stmt method at_hint = visit visitor1#at_hint visitor2#at_hint method at_typedef = visit visitor1#at_typedef visitor2#at_typedef method at_gconst = visit visitor1#at_gconst visitor2#at_gconst method at_file_attribute = visit visitor1#at_file_attribute visitor2#at_file_attribute method at_shape_field_name = visit visitor1#at_shape_field_name visitor2#at_shape_field_name method at_user_attribute = visit visitor1#at_user_attribute visitor2#at_user_attribute method at_class_id = visit visitor1#at_class_id visitor2#at_class_id method at_catch = visit visitor1#at_catch visitor2#at_catch method at_targ = visit visitor1#at_targ visitor2#at_targ method at_class_hint = visit visitor1#at_class_hint visitor2#at_class_hint method at_trait_hint = visit visitor1#at_trait_hint visitor2#at_trait_hint method at_xhp_attr_hint = visit visitor1#at_xhp_attr_hint visitor2#at_xhp_attr_hint end in combine let checker (visitor : 'env nast_visitor_with_state) = object inherit [_] Aast.iter as super method initial_state = visitor#initial_state method! on_fun_def env f = let env = visitor#at_fun_def env f in super#on_fun_def env f method! on_class_ env c = let env = visitor#at_class_ env c in super#on_class_ env c method! on_method_ env m = let env = visitor#at_method_ env m in super#on_method_ env m method! on_expr env e = match e with | (_, _, Aast.Invalid _) -> () | _ -> let env = visitor#at_expr env e in super#on_expr env e method! on_stmt env s = let env = visitor#at_stmt env s in super#on_stmt env s method! on_hint env h = let env = visitor#at_hint env h in super#on_hint env h method! on_typedef env td = let env = visitor#at_typedef env td in super#on_typedef env td method! on_gconst env gc = let env = visitor#at_gconst env gc in super#on_gconst env gc method! on_file_attribute env fa = let env = visitor#at_file_attribute env fa in super#on_file_attribute env fa method! on_shape_field_name env sfn = let env = visitor#at_shape_field_name env sfn in super#on_shape_field_name env sfn method! on_user_attribute env ua = let env = visitor#at_user_attribute env ua in super#on_user_attribute env ua method! on_class_id env ci = let env = visitor#at_class_id env ci in super#on_class_id env ci method! on_catch env catch = let env = visitor#at_catch env catch in super#on_catch env catch method! on_targ env targ = let env = visitor#at_targ env targ in super#on_targ env targ method! on_class_hint env ch = let env = visitor#at_class_hint env ch in super#on_class_hint env ch method! on_trait_hint env th = let env = visitor#at_trait_hint env th in super#on_trait_hint env th method! on_xhp_attr_hint env xhp_attr = let env = visitor#at_xhp_attr_hint env xhp_attr in super#on_xhp_attr_hint env xhp_attr end
OCaml
hhvm/hphp/hack/src/typing/tanySentinel.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude type t = unit [@@deriving eq, hash] let value : t = ()
OCaml Interface
hhvm/hphp/hack/src/typing/tanySentinel.mli
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type t [@@deriving eq, hash] val value : t
OCaml
hhvm/hphp/hack/src/typing/tast.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. * *) include Aast_defs [@@@warning "-33"] open Hh_prelude [@@@warning "+33"] (* This is the current notion of type in the typed AST. * In future we might want to reconsider this and define a new representation * that omits type inference artefacts such as type variables and lambda * identifiers. *) type ty = Typing_defs.locl_ty [@@deriving hash] type possibly_enforced_ty = Typing_defs.locl_possibly_enforced_ty type decl_ty = Typing_defs.decl_ty type val_kind = Typing_defs.val_kind let pp_ty = Typing_defs.pp_locl_ty let show_ty = Typing_defs.show_locl_ty let pp_decl_ty = Typing_defs.pp_decl_ty let show_decl_ty = Typing_defs.show_decl_ty let pp_ifc_fun_decl fmt d = Typing_defs.pp_ifc_fun_decl fmt d (* Contains information about a specific function that we a) want to make available to TAST checks b) isn't otherwise (space-efficiently) present in the saved typing env *) type fun_tast_info = { has_implicit_return: bool; has_readonly: bool; (** True if there are leaves of the function's imaginary CFG without a return statement *) } [@@deriving show] type check_status = | COnce (** The definition is checked only once. *) | CUnderNormalAssumptions (** The definition is checked twice and this is the check under normal assumptions that is using the parameter and return types that are written in the source code (but potentially implicitly pessimised). *) | CUnderDynamicAssumptions (** The definition is checked twice and this is the check under dynamic assumptions that is using the dynamic type for parameters and return. *) [@@deriving show] let is_under_dynamic_assumptions = function | COnce | CUnderNormalAssumptions -> false | CUnderDynamicAssumptions -> true type saved_env = { tcopt: TypecheckerOptions.t; [@opaque] inference_env: Typing_inference_env.t; tpenv: Type_parameter_env.t; condition_types: decl_ty SMap.t; fun_tast_info: fun_tast_info option; checked: check_status; (** Indicates how many types the callable was checked and under what assumptions. *) } [@@deriving show] type program = (ty, saved_env) Aast.program [@@deriving show] type def = (ty, (saved_env[@hash.ignore])) Aast.def [@@deriving hash] type def_with_dynamic = def Tast_with_dynamic.t [@@deriving hash] type expr = (ty, saved_env) Aast.expr type expr_ = (ty, saved_env) Aast.expr_ type stmt = (ty, saved_env) Aast.stmt type stmt_ = (ty, saved_env) Aast.stmt_ type case = (ty, saved_env) Aast.case type block = (ty, saved_env) Aast.block type class_ = (ty, saved_env) Aast.class_ type class_id = (ty, saved_env) Aast.class_id type type_hint = ty Aast.type_hint type targ = ty Aast.targ type class_get_expr = (ty, saved_env) Aast.class_get_expr type class_typeconst_def = (ty, saved_env) Aast.class_typeconst_def type user_attribute = (ty, saved_env) Aast.user_attribute type capture_lid = ty Aast.capture_lid type fun_ = (ty, saved_env) Aast.fun_ type efun = (ty, saved_env) Aast.efun type file_attribute = (ty, saved_env) Aast.file_attribute type fun_def = (ty, saved_env) Aast.fun_def type fun_param = (ty, saved_env) Aast.fun_param type func_body = (ty, saved_env) Aast.func_body type method_ = (ty, saved_env) Aast.method_ type class_var = (ty, saved_env) Aast.class_var type class_const = (ty, saved_env) Aast.class_const type tparam = (ty, saved_env) Aast.tparam type typedef = (ty, saved_env) Aast.typedef type gconst = (ty, saved_env) Aast.gconst type module_def = (ty, saved_env) Aast.module_def type call_expr = (ty, saved_env) Aast.call_expr type by_names = { fun_tasts: def Tast_with_dynamic.t SMap.t; class_tasts: def Tast_with_dynamic.t SMap.t; typedef_tasts: def SMap.t; gconst_tasts: def SMap.t; module_tasts: def SMap.t; } let empty_by_names = { fun_tasts = SMap.empty; class_tasts = SMap.empty; typedef_tasts = SMap.empty; gconst_tasts = SMap.empty; module_tasts = SMap.empty; } let tasts_as_list ({ fun_tasts; class_tasts; typedef_tasts; gconst_tasts; module_tasts } : by_names) : def Tast_with_dynamic.t list = SMap.values fun_tasts @ SMap.values class_tasts @ List.map ~f:Tast_with_dynamic.mk_without_dynamic (SMap.values typedef_tasts) @ List.map ~f:Tast_with_dynamic.mk_without_dynamic (SMap.values gconst_tasts) @ List.map ~f:Tast_with_dynamic.mk_without_dynamic (SMap.values module_tasts) let empty_saved_env tcopt : saved_env = { tcopt; inference_env = Typing_inference_env.empty_inference_env; tpenv = Type_parameter_env.empty; condition_types = SMap.empty; fun_tast_info = None; checked = COnce; } (* Used when an env is needed in codegen. * TODO: (arkumar,wilfred,thomasjiang) T42509373 Fix when when needed *) let dummy_saved_env = empty_saved_env GlobalOptions.default let dummy_type_hint (hint : hint option) : ty * hint option = (Typing_defs.mk (Typing_reason.Rnone, Typing_defs.Tdynamic), hint) (* Helper function to create an annotation for a typed and positioned expression. * Do not construct this tuple directly - at some point we will build * some abstraction in so that we can change the representation (e.g. put * further annotations on the expression) as we see fit. *) let make_expr_annotation _p ty : ty = ty (* Helper function to create a typed and positioned expression. * Do not construct this triple directly - at some point we will build * some abstraction in so that we can change the representation (e.g. put * further annotations on the expression) as we see fit. *) let make_typed_expr p ty te : expr = (make_expr_annotation p ty, p, te) (* Get the position of an expression *) let get_position ((_, p, _) : expr) = p (* Get the type of an expression *) let get_type ((ty, _, _) : expr) = ty let nast_converter = object inherit [_] Aast.map as super method on_'ex _ _ = () method on_'en _ _ = () method! on_Hole _ ex _ _ src = let ((_, pos, ex_) as ex) = super#on_expr () ex in let mk_call hints name = let targs = List.map ~f:(fun hint -> ((), super#on_hint () hint)) hints in let func = ((), pos, Aast.Id (pos, name)) in let args = [(Ast_defs.Pnormal, ex)] in Aast.Call { func; targs; args; unpacked_arg = None } in match src with | Aast.UnsafeCast hints -> mk_call hints Naming_special_names.PseudoFunctions.unsafe_cast | Aast.UnsafeNonnullCast -> mk_call [] Naming_special_names.PseudoFunctions.unsafe_nonnull_cast | Aast.EnforcedCast hints -> mk_call hints Naming_special_names.PseudoFunctions.enforced_cast | _ -> ex_ end let to_nast p = nast_converter#on_program () p let to_nast_expr (tast : expr) : Nast.expr = nast_converter#on_expr () tast let to_nast_class_id_ cid = nast_converter#on_class_id_ () cid
OCaml
hhvm/hphp/hack/src/typing/tast_env.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 class_or_typedef_result = | ClassResult of Decl_provider.class_decl | TypedefResult of Typing_defs.typedef_type (** {!Tast_env.env} is just an alias to {!Typing_env.env}, and the functions we provide for it are largely just aliases to functions that take a {!Typing_env.env}. If you find that you need to add a new alias here, please take care to ensure that it always works with the information available in the {!env} constructed by {!Tast_visitor} classes. Only a subset of the information available in the inference phase ({!module:Typing}) will be persisted in a {!Tast.program} (and thus available to {!Tast_visitor}). Most of the persisted information comes from {!Typing_env.save}. *) let show_env _ = "<env>" let pp_env _ _ = Printf.printf "%s\n" "<env>" type env = Typing_env_types.env type t = env [@@deriving show] exception Not_in_class let print_ty = Typing_print.full_strip_ns let print_decl_ty = Typing_print.full_strip_ns_decl let print_error_ty = Typing_print.error let print_ty_with_identity env phase_ty sym_occurrence sym_definition = match phase_ty with | Typing_defs.DeclTy ty -> let ((env, ty_err_opt), ty) = Typing_phase.localize_no_subst env ~ignore_errors:true ty in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); Typing_print.full_with_identity env ty sym_occurrence sym_definition | Typing_defs.LoclTy ty -> Typing_print.full_with_identity env ty sym_occurrence sym_definition let ty_to_json env ?show_like_ty ty = Typing_print.to_json env ?show_like_ty ty let json_to_locl_ty = Typing_print.json_to_locl_ty let get_self_id = Typing_env.get_self_id let get_self_ty = Typing_env.get_self_ty let get_parent_id = Typing_env.get_parent_id let get_self_ty_exn env = match get_self_ty env with | Some self_ty -> self_ty | None -> raise Not_in_class let get_class = Typing_env.get_class let get_class_or_typedef env x = match Typing_env.get_class_or_typedef env x with | Some (Typing_env.ClassResult cd) -> Some (ClassResult cd) | Some (Typing_env.TypedefResult td) -> Some (TypedefResult td) | None -> None let is_in_expr_tree = Typing_env.is_in_expr_tree let inside_expr_tree = Typing_env.inside_expr_tree let outside_expr_tree = Typing_env.outside_expr_tree let is_static = Typing_env.is_static let is_strict = Typing_env.is_strict let get_mode = Typing_env.get_mode let get_tcopt = Typing_env.get_tcopt let get_ctx = Typing_env.get_ctx let expand_type = Typing_env.expand_type let strip_dynamic = Typing_utils.strip_dynamic let set_static = Typing_env.set_static let set_val_kind = Typing_env.set_val_kind let set_inside_constructor env = { env with Typing_env_types.inside_constructor = true } let get_inside_constructor env = env.Typing_env_types.inside_constructor let get_decl_env env = env.Typing_env_types.decl_env let get_val_kind = Typing_env.get_val_kind let get_file = Typing_env.get_file let get_deps_mode = Typing_env.get_deps_mode let fully_expand = Typing_expand.fully_expand (*****************************************************************************) (* Given some class type or unresolved union of class types, return the * identifiers of all classes the type may represent. * * Intended for uses like constructing call graphs and finding references, where * we have the statically known class type of some runtime value or class ID and * we would like the name of that class. *) (*****************************************************************************) type receiver_identifier = | RIclass of string | RIdynamic | RIerr | RIany let get_receiver_ids env ty = let open Typing_defs in let rec aux seen acc ty = match get_node ty with | Tclass ((_, cid), _, _) -> RIclass cid :: acc | Toption ty | Tdependent (_, ty) | Tnewtype (_, _, ty) -> aux seen acc ty | Tunion tys | Tintersection tys -> List.fold tys ~init:acc ~f:(aux seen) | Tgeneric (name, targs) when not (List.mem ~equal:String.equal seen name) -> let seen = name :: seen in let upper_bounds = Typing_env.get_upper_bounds env name targs in Typing_set.fold (fun ty acc -> aux seen acc ty) upper_bounds acc | Tdynamic -> [RIdynamic] | Tany _ -> [RIany] | _ -> acc in List.rev (aux [] [] (Typing_expand.fully_expand env ty)) let get_class_ids env ty = get_receiver_ids env ty |> List.filter_map ~f:(function | RIclass cid -> Some cid | _ -> None) let non_null = Typing_solver.non_null let get_concrete_supertypes = Typing_utils.get_concrete_supertypes ~include_case_types:false let is_visible = Typing_visibility.is_visible let assert_nontrivial = Typing_equality_check.assert_nontrivial let hint_to_ty env = Decl_hint.hint env.Typing_env_types.decl_env let localize env ety_env dty = let ((env, ty_err_opt), lty) = Typing_phase.localize ~ety_env env dty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (env, lty) let localize_hint_for_refinement env h = let ((env, _ty_err_opt), lty) = Typing_phase.localize_hint_for_refinement env h in (env, lty) let localize_no_subst env ~ignore_errors dty = let ((env, ty_err_opt), lty) = Typing_phase.localize_no_subst env ~ignore_errors dty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (env, lty) let get_upper_bounds = Typing_env.get_upper_bounds let fresh_type = Typing_env.fresh_type let is_fresh_generic_parameter = Typing_env.is_fresh_generic_parameter let simplify_unions env ty = Typing_union.simplify_unions env ty let union_list env r tyl = Typing_union.union_list env r tyl let get_reified = Typing_env.get_reified let get_enforceable = Typing_env.get_enforceable let get_newable = Typing_env.get_newable let assert_subtype p reason env ty_have ty_expect on_error = let (env, ty_err_opt) = Typing_ops.sub_type p reason env ty_have ty_expect on_error in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; env let is_sub_type env ty_sub ty_super = Typing_subtype.is_sub_type env ty_sub ty_super let is_dynamic_aware_sub_type env ty_sub ty_super = Typing_subtype.is_dynamic_aware_sub_type env ty_sub ty_super let can_subtype env ty_sub ty_super = Typing_subtype.can_sub_type env ty_sub ty_super let is_sub_type_for_union env ty_sub ty_super = Typing_subtype.is_sub_type_for_union env ty_sub ty_super let referenced_typeconsts env root ids = let root = hint_to_ty env root in let ety_env = Typing_defs.empty_expand_env in let (tcs, ty_err_opt) = Typing_taccess.referenced_typeconsts env ety_env (root, ids) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; tcs let empty ctx = Typing_env_types.empty ctx Relative_path.default ~droot:None let restore_saved_env env saved_env = let module Env = Typing_env_types in let ctx = Provider_context.map_tcopt env.Env.decl_env.Decl_env.ctx ~f:(fun _tcopt -> saved_env.Tast.tcopt) in let decl_env = { env.Env.decl_env with Decl_env.ctx } in { env with Env.decl_env; Env.genv = { env.Env.genv with Env.tcopt = saved_env.Tast.tcopt; Env.condition_types = saved_env.Tast.condition_types; }; Env.inference_env = Typing_inference_env.simple_merge env.Env.inference_env saved_env.Tast.inference_env; Env.tpenv = saved_env.Tast.tpenv; Env.fun_tast_info = saved_env.Tast.fun_tast_info; Env.checked = saved_env.Tast.checked; } module EnvFromDef = Typing_env_from_def open Tast let check_fun_tast_info_present env = function | Some _ -> () | None -> Errors.internal_error env.Typing_env_types.genv.Typing_env_types.callable_pos "fun_tast_info of a function or method was not filled in before TAST checking" let restore_method_env env m = let se = m.m_annotation in restore_saved_env env se let restore_fun_env env f = let se = f.f_annotation in restore_saved_env env se let fun_env ctx fd = let f = fd.fd_fun in let ctx = Provider_context.map_tcopt ctx ~f:(fun _tcopt -> f.f_annotation.tcopt) in let env = EnvFromDef.fun_env ~origin:Decl_counters.Tast ctx fd in restore_fun_env env f let class_env ctx c = let ctx = Provider_context.map_tcopt ctx ~f:(fun _tcopt -> c.c_annotation.tcopt) in let env = EnvFromDef.class_env ~origin:Decl_counters.Tast ctx c in restore_saved_env env c.c_annotation let typedef_env ctx t = let ctx = Provider_context.map_tcopt ctx ~f:(fun _tcopt -> t.t_annotation.tcopt) in let env = EnvFromDef.typedef_env ~origin:Decl_counters.Tast ctx t in restore_saved_env env t.t_annotation let gconst_env ctx cst = let ctx = Provider_context.map_tcopt ctx ~f:(fun _tcopt -> cst.cst_annotation.tcopt) in let env = EnvFromDef.gconst_env ~origin:Decl_counters.Tast ctx cst in restore_saved_env env cst.cst_annotation let def_env ctx d = match d with | Fun x -> fun_env ctx x | Class x -> class_env ctx x | Typedef x -> typedef_env ctx x | Constant x -> gconst_env ctx x (* TODO T44306013 *) (* The following nodes are included in the TAST, but are not typechecked. * However, we need to return an env here so for now create an empty env using * the default typechecker options. *) | Stmt _ | Namespace _ | NamespaceUse _ | SetNamespaceEnv _ | SetModule _ | FileAttributes _ (* TODO(T108206307) *) | Module _ -> empty ctx let typing_env_as_tast_env env = env let tast_env_as_typing_env env = env let is_xhp_child = Typing_xhp.is_xhp_child let get_enum = Typing_env.get_enum let is_typedef = Typing_env.is_typedef let get_typedef = Typing_env.get_typedef let is_typedef_visible = Typing_env.is_typedef_visible let is_enum = Typing_env.is_enum let get_fun = Typing_env.get_fun let set_allow_wildcards env = { env with Typing_env_types.allow_wildcards = true } let get_allow_wildcards env = env.Typing_env_types.allow_wildcards let is_enum_class env c = Typing_env.is_enum_class env c let extract_from_fun_tast_info env extractor default_value = let fun_tast_info = env.Typing_env_types.fun_tast_info in check_fun_tast_info_present env fun_tast_info; match fun_tast_info with | Some fun_tast_info -> extractor fun_tast_info | None -> (* In this case, check_fun_tast_info_present reported an error already *) default_value let fun_has_implicit_return (env : t) = extract_from_fun_tast_info env (fun info -> info.has_implicit_return) false let fun_has_readonly (env : t) = extract_from_fun_tast_info env (fun info -> info.has_readonly) false let get_const env cls name = Typing_env.get_const env cls name let consts env cls = Typing_env.consts env cls let fill_in_pos_filename_if_in_current_decl = Typing_env.fill_in_pos_filename_if_in_current_decl let is_hhi = Typing_env.is_hhi let get_check_status env = env.Typing_env_types.checked let get_current_decl_and_file = Typing_env.get_current_decl_and_file
OCaml Interface
hhvm/hphp/hack/src/typing/tast_env.mli
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type env [@@deriving show] type t = env [@@deriving show] exception Not_in_class type class_or_typedef_result = | ClassResult of Decl_provider.class_decl | TypedefResult of Typing_defs.typedef_type (** Return a string representation of the given type using Hack-like syntax. *) val print_ty : env -> Typing_defs.locl_ty -> string val print_decl_ty : ?msg:bool -> env -> Typing_defs.decl_ty -> string val print_error_ty : ?ignore_dynamic:bool -> env -> Typing_defs.locl_ty -> string (** Return a string representation of the given type using Hack-like syntax, formatted with limited width and line breaks, including additional information from the {!SymbolOccurrence.t} and (if provided) {!SymbolDefinition.t}. *) val print_ty_with_identity : env -> Typing_defs.phase_ty -> 'b SymbolOccurrence.t -> 'b SymbolDefinition.t option -> string (** Return a JSON representation of the given type. *) val ty_to_json : env -> ?show_like_ty:bool -> Typing_defs.locl_ty -> Hh_json.json (** Convert a JSON representation of a type back into a locl-phase type. *) val json_to_locl_ty : ?keytrace:Hh_json.Access.keytrace -> Provider_context.t -> Hh_json.json -> (Typing_defs.locl_ty, Typing_defs.deserialization_error) result (** Return the name of the enclosing class definition. When not in a class definition, return {!None}. *) val get_self_id : env -> string option (** Return the type of the enclosing class definition. When not in a class definition, return {!None}. *) val get_self_ty : env -> Tast.ty option (** Return the type of the enclosing class definition. When not in a class definition, raise {!Not_in_class}. *) val get_self_ty_exn : env -> Tast.ty (** Return the name of the parent of the enclosing class definition. When not in a class definition or no parent exists, return {!None}. *) val get_parent_id : env -> string option (** Return the info of the given class from the typing heap. *) val get_class : env -> Decl_provider.type_key -> Decl_provider.class_decl option val get_class_or_typedef : env -> Decl_provider.type_key -> class_or_typedef_result option val is_in_expr_tree : env -> bool val inside_expr_tree : env -> Tast.hint -> env val outside_expr_tree : env -> env (** Return {true} when in the definition of a static property or method. *) val is_static : env -> bool (** Return {true} if the containing file was checked in strict mode. *) val is_strict : env -> bool (** Return the mode of the containing file *) val get_mode : env -> FileInfo.mode (** Return the {!TypecheckerOptions.t} with which this TAST was checked. *) val get_tcopt : env -> TypecheckerOptions.t (** Return the {!Provider_context.t} with which this TAST was checked. *) val get_ctx : env -> Provider_context.t val get_file : env -> Relative_path.t val get_deps_mode : env -> Typing_deps_mode.t (* Return the {!Relative_path.t} of the file the env is from *) (** Expand a type variable ({!Typing_defs.Tvar}) to the type it refers to. *) val expand_type : env -> Tast.ty -> env * Tast.ty (** Eliminate type variables ({!Typing_defs.Tvar}) in the given type by recursively replacing them with the type they refer to. *) val fully_expand : env -> Tast.ty -> Tast.ty (** Strip ~ from type *) val strip_dynamic : env -> Tast.ty -> Tast.ty (** Types that can have methods called on them. Usually a class but also includes dynamic types *) type receiver_identifier = | RIclass of string | RIdynamic | RIerr | RIany (** Given some class type or unresolved union of class types, return the identifiers of all receivers the type may represent. *) val get_receiver_ids : env -> Tast.ty -> receiver_identifier list (** Given some class type or unresolved union of class types, return the identifiers of all classes the type may represent. *) val get_class_ids : env -> Tast.ty -> string list (** Strip away all Toptions that we possibly can in a type, expanding type variables along the way, turning ?T -> T. *) val non_null : env -> Pos_or_decl.t -> Tast.ty -> env * Tast.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>(...)) The abstract_enum flag controls whether arraykey bound enums are considered abstract, or as arraykey bound. *) val get_concrete_supertypes : ?expand_supportdyn:bool -> abstract_enum:bool -> env -> Tast.ty -> env * Tast.ty list (** Return {true} if the given {Decl_provider.class_decl} (referred to by the given {class_id_}, if provided) allows the current class (the one returned by {!get_self}) to access its members with the given {visibility}. *) val is_visible : is_method:bool -> env -> Typing_defs.ce_visibility * bool -> Nast.class_id_ option -> Decl_provider.class_decl -> bool (** Assert that the types of values involved in a strict (non-)equality comparison are compatible; e.g., that the types are not statically known to be disjoint, in which case the comparison will always return true or false. *) val assert_nontrivial : Pos.t -> Ast_defs.bop -> env -> Tast.ty -> Tast.ty -> unit (** Return the declaration-phase type the given hint represents. *) val hint_to_ty : env -> Aast.hint -> Typing_defs.decl_ty val localize : env -> Typing_defs.expand_env -> Typing_defs.decl_ty -> env * Tast.ty val localize_hint_for_refinement : env -> Aast.hint -> env * Tast.ty (** Transforms a declaration phase type ({!Typing_defs.decl_ty}) into a localized type ({!Typing_defs.locl_ty} = {!Tast.ty}). Performs no substitutions of generics and initializes the late static bound type ({!Typing_defs.Tthis}) to the current class type (the type returned by {!get_self}). This is mostly provided as legacy support for {!AutocompleteService}, and should not be considered a general mechanism for transforming a {decl_ty} to a {!Tast.ty}. {!quiet} silences certain errors because those errors have already fired and/or are not appropriate at the time we call localize. *) val localize_no_subst : env -> ignore_errors:bool -> Typing_defs.decl_ty -> env * Tast.ty (** Get the upper bounds of the type parameter with the given name. FIXME: This function cannot return correct bounds at this time, because during TAST checks, the Next continuation in the typing environment (which stores information about type parameters) is gone. *) val get_upper_bounds : env -> string -> Typing_defs.locl_ty list -> Type_parameter_env.tparam_bounds (** Get the reification of the type parameter with the given name. *) val get_reified : env -> string -> Aast.reify_kind (** Get whether the type parameter supports testing with is/as. *) val get_enforceable : env -> string -> bool (** Indicates whether the type parameter with the given name is <<__Newable>>. *) val get_newable : env -> string -> bool val fresh_type : env -> Pos.t -> env * Typing_defs.locl_ty (** Return whether the type parameter with the given name was implicity created as part of an `instanceof`, `is`, or `as` expression (instead of being explicitly declared in code by the user). *) val is_fresh_generic_parameter : string -> bool (** Assert that one type is a subtype of another, resolving unbound type variables in both types (if any), with {!env} reflecting the new state of these type variables. Produce an error if they cannot be subtypes. *) val assert_subtype : Pos.t -> Typing_reason.ureason -> env -> Tast.ty -> Tast.ty -> Typing_error.Callback.t -> env (** Return {true} when the first type is a subtype of the second type regardless of the values of unbound type variables in both types (if any). *) val is_sub_type : env -> Tast.ty -> Tast.ty -> bool val is_dynamic_aware_sub_type : env -> Tast.ty -> Tast.ty -> bool (** Return {true} when the first type can be considered a subtype of the second type after resolving unbound type variables in both types (if any). *) val can_subtype : env -> Tast.ty -> Tast.ty -> bool (** Return {true} when the first type is a subtype of the second type. There is no type T such that for all T', T <: T' and T' <: T (which is the case for Tany and Terr in `can_subtype`) *) val is_sub_type_for_union : env -> Tast.ty -> Tast.ty -> bool (** Simplify unions in a type. *) val simplify_unions : env -> Tast.ty -> env * Tast.ty (** Union a list of types. *) val union_list : env -> Typing_reason.t -> Tast.ty list -> env * Tast.ty (** Returns (class_name, tconst_name, tconst_reference_position) for each type constant referenced in the type access path. *) val referenced_typeconsts : env -> Aast.hint -> Aast.sid list -> (string * string * Pos.t) list (** Return an {!env} for which {!is_static} will return {true}. If you are using {!Tast_visitor}, you should have no need of this. *) val set_static : env -> env (** Return an {!env} for which {!val_kind} is set to the second argument. *) val set_val_kind : env -> Typing_defs.val_kind -> env (** Returns the val_kind of the typing environment *) val get_val_kind : env -> Typing_defs.val_kind (** Returns an {!env} for which {!inside_constructor} is set to {true}. If you are using {!Tast_visitor}, you should have no need of this. *) val set_inside_constructor : env -> env (** Returns whether or not the typing environment is inside the constructor of a class *) val get_inside_constructor : env -> bool (** Returns a {!Decl_env.env} *) val get_decl_env : env -> Decl_env.env (** Construct an empty {!env}. Unlikely to be the best choice; prefer using {!Tast_visitor} or constructing an {!env} from a {!Tast.def}. *) val empty : Provider_context.t -> env (** Construct an {!env} from a toplevel definition. *) val def_env : Provider_context.t -> Tast.def -> env (** Construct an {!env} from a method definition and the {!env} of the context it appears in. *) val restore_method_env : env -> Tast.method_ -> env (** Construct an {!env} from a lambda definition and the {!env} of the context it appears in. *) val restore_fun_env : env -> Tast.fun_ -> env val typing_env_as_tast_env : Typing_env_types.env -> env val tast_env_as_typing_env : env -> Typing_env_types.env (** Verify that an XHP body expression is legal. *) val is_xhp_child : env -> Pos.t -> Tast.ty -> bool * Typing_error.t option val get_enum : env -> Decl_provider.type_key -> Decl_provider.class_decl option val is_typedef : env -> Decl_provider.type_key -> bool val is_typedef_visible : env -> ?expand_visible_newtype:bool -> name:string -> Typing_defs.typedef_type -> bool val get_typedef : env -> Decl_provider.type_key -> Decl_provider.typedef_decl option val is_enum : env -> Decl_provider.type_key -> bool val get_fun : env -> Decl_provider.fun_key -> Decl_provider.fun_decl option val set_allow_wildcards : env -> env val get_allow_wildcards : env -> bool (*val is_enum_class : env -> Decl_provider.type_key -> bool*) val is_enum_class : env -> string -> bool val fun_has_implicit_return : env -> bool val fun_has_readonly : env -> bool val get_const : env -> Decl_provider.class_decl -> string -> Typing_defs.class_const option val consts : env -> Decl_provider.class_decl -> (string * Typing_defs.class_const) list (** 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 (** Check if the environment is for a definition in a while that is a builtin. *) val is_hhi : env -> bool (** See {!Tast.check_status} to understand what this function returns from the environment. *) val get_check_status : env -> Tast.check_status val get_current_decl_and_file : env -> Pos_or_decl.ctx
OCaml
hhvm/hphp/hack/src/typing/tast_expand.ml
(* * Copyright (c) 2017, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Typing_defs (* Eliminate residue of type inference: * 1. Tvars are replaced (deep) by the expanded type * 2. Singleton unions are eliminated * TODO TAST: * Transform completely unconstrained types to Tmixed * Consider using a fresh datatype for TAST types. *) let expand_ty ?var_hook ?pos env ty = let rec exp_ty ty = begin match (get_node ty, var_hook) with | (Tvar var, Some hook) -> hook var | _ -> () end; let (_, ety) = Tast_env.expand_type env ty in let ety = match deref ety with | (_, (Tany _ | Tnonnull | Tprim _ | Tdynamic | Tneg _)) -> ety | (p, Tgeneric (name, args)) -> mk (p, Tgeneric (name, exp_tys args)) | (p, Tclass (n, e, tyl)) -> mk (p, Tclass (n, e, exp_tys tyl)) | (p, Tunion tyl) -> mk (p, Tunion (exp_tys tyl)) | (p, Tintersection tyl) -> mk (p, Tintersection (exp_tys tyl)) | (p, Toption ty) -> mk (p, Toption (exp_ty ty)) | (p, Ttuple tyl) -> mk (p, Ttuple (exp_tys tyl)) | (p, Tfun ft) -> mk (p, Tfun (exp_fun_type ft)) | (p, Tnewtype (n, tyl, ty)) -> mk (p, Tnewtype (n, exp_tys tyl, exp_ty ty)) | (p, Tdependent (n, ty)) -> mk (p, Tdependent (n, exp_ty ty)) | (p, Tshape s) -> mk (p, Tshape (exp_shape_type s)) | (p, Tvec_or_dict (ty1, ty2)) -> mk (p, Tvec_or_dict (exp_ty ty1, exp_ty ty2)) | (p, Tvar v) -> (match pos with | None -> mk (p, Tvar v) | Some pos -> if TypecheckerOptions.disallow_unresolved_type_variables (Tast_env.get_tcopt env) then Typing_error_utils.add_typing_error ~env:(Tast_env.tast_env_as_typing_env env) Typing_error.(primary @@ Primary.Unresolved_tyvar pos); mk (p, Tvar v)) (* TODO(T36532263) see if that needs updating *) | (_, Taccess _) -> ety | (_, Tunapplied_alias _) -> ety in ety and exp_tys tyl = List.map ~f:exp_ty tyl and exp_fun_type { ft_tparams; ft_where_constraints; ft_ret; ft_flags; ft_params; ft_implicit_params; ft_ifc_decl; ft_cross_package; } = { ft_flags; ft_ifc_decl; ft_cross_package; ft_tparams = List.map ~f:exp_tparam ft_tparams; ft_where_constraints = List.map ~f:exp_where_constraint ft_where_constraints; ft_ret = exp_possibly_enforced_ty ft_ret; ft_params = List.map ~f:exp_fun_param ft_params; ft_implicit_params = exp_fun_implicit_params ft_implicit_params; } and exp_fun_param { fp_pos; fp_name; fp_type; fp_flags } = { fp_pos; fp_name; fp_type = exp_possibly_enforced_ty fp_type; fp_flags } and exp_fun_implicit_params { capability } = let capability = match capability with | CapTy ty -> CapTy (exp_ty ty) | CapDefaults p -> CapDefaults p in { capability } and exp_possibly_enforced_ty { et_type; et_enforced } = { et_type = exp_ty et_type; et_enforced } and exp_sft { sft_optional; sft_ty } = { sft_optional; sft_ty = exp_ty sft_ty } and exp_shape_type { s_origin = shape_origin; s_unknown_value = shape_kind; s_fields = fields; } = { s_origin = shape_origin; s_unknown_value = shape_kind; (* TODO(shapes) exp_ty s_unknown_value *) s_fields = TShapeMap.map exp_sft fields; } and exp_tparam t = { t with tp_constraints = List.map ~f:(fun (ck, ty) -> (ck, exp_ty ty)) t.tp_constraints; } and exp_where_constraint (ty1, ck, ty2) = (exp_ty ty1, ck, exp_ty ty2) in exp_ty ty let expander = object (self) inherit Tast_visitor.endo method! on_expr env (ty, pos, expr_) = (expand_ty ~pos env ty, pos, self#on_expr_ env expr_) method! on_class_id env (ty, pos, cid_) = (expand_ty ~pos env ty, pos, self#on_class_id_ env cid_) method! on_'ex env ty = expand_ty env ty end (* Replace all types in a program AST by their expansions *) let expand_program tast = expander#go tast
OCaml Interface
hhvm/hphp/hack/src/typing/tast_expand.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 expand_ty : ?var_hook:(Ident.t -> unit) -> ?pos:Pos.t -> Tast_env.env -> Typing_defs.locl_ty -> Typing_defs.locl_ty val expand_program : Provider_context.t -> Tast.def list -> Tast.def list
OCaml
hhvm/hphp/hack/src/typing/tast_type_collector.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 type collected_type = Tast_env.env * Typing_defs.phase_ty [@@deriving show] let type_collector = object (self) inherit [_] Tast_visitor.reduce as super method zero = Pos.AbsolutePosMap.empty method plus = Pos.AbsolutePosMap.union ~combine:(fun _ a b -> Some (a @ b)) method! on_expr env (ty, p, expr_) = self#plus (Pos.AbsolutePosMap.singleton (Pos.to_absolute p) [(env, Typing_defs.LoclTy ty)]) (super#on_expr env (ty, p, expr_)) method! on_class_id env (ty, _, cid) = match cid with | Aast.CI (p, _) -> Pos.AbsolutePosMap.singleton (Pos.to_absolute p) [(env, Typing_defs.LoclTy ty)] | _ -> Pos.AbsolutePosMap.empty method! on_fun_param env fp = self#plus (Pos.AbsolutePosMap.singleton (Pos.to_absolute fp.Aast.param_pos) [(env, Typing_defs.LoclTy fp.Aast.param_annotation)]) (super#on_fun_param env fp) method! on_hint (env : Tast_env.t) hint = let (pos, _) = hint in let ty = Tast_env.hint_to_ty env hint in Pos.AbsolutePosMap.singleton (Pos.to_absolute pos) [(env, Typing_defs.DeclTy ty)] end let collect_types tast = Errors.ignore_ (fun () -> type_collector#go tast) (* Ideally this would be just Pos.AbsolutePosMap.find_opt, however the positions in the Tast are off by 1 from positions in the full fidelity parse trees. TODO: Fix this when the full fidelity parse tree becomes the parser for type checking. *) let get_from_pos_map (position : Pos.absolute) (map : collected_type list Pos.AbsolutePosMap.t) = let position = Pos.advance_one position in Pos.AbsolutePosMap.find_opt position map
OCaml Interface
hhvm/hphp/hack/src/typing/tast_type_collector.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 collected_type = Tast_env.env * Typing_defs.phase_ty [@@deriving show] val collect_types : Provider_context.t -> Tast.def list -> collected_type list Pos.AbsolutePosMap.t val get_from_pos_map : Pos.absolute -> collected_type list Pos.AbsolutePosMap.t -> collected_type list option
OCaml
hhvm/hphp/hack/src/typing/tast_utils.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Ast_defs open Aast_defs open Typing_defs module Env = Tast_env module MakeType = Typing_make_type module Cls = Decl_provider.Class module SN = Naming_special_names (** Return true if ty definitely does not contain null. I.e., the return value false can mean two things: ty does contain null, e.g., it is an option type; or we cannot tell, e.g., it is an opaque newtype. *) let rec type_non_nullable env ty = let (_, ty) = Env.expand_type env ty in match get_node ty with | Tprim ( Tint | Tbool | Tfloat | Tstring | Tresource | Tnum | Tarraykey | Tnoreturn ) | Tnonnull | Tfun _ | Ttuple _ | Tshape _ | Tclass _ -> true | Tnewtype (_, _, ty) | Tdependent (_, ty) when type_non_nullable env ty -> true | Tunion tyl when not (List.is_empty tyl) -> List.for_all tyl ~f:(type_non_nullable env) | _ -> false (* Truthiness utilities ******************************************************) (* For types other than bool used in condition expressions, boolean binary expressions, and casts to bool. An always-truthy type used in a condition is always a logic error. A nullable possibly-falsy type used in a condition is a sketchy null check--it isn't clear whether the user meant to check for null or for one of the other falsy values. *) type truthiness = | Unknown | Always_truthy | Always_falsy | Possibly_falsy let fold_truthiness acc truthiness = match (acc, truthiness) with | (Unknown, _) | (_, Unknown) -> Unknown | (Always_truthy, Always_truthy) -> Always_truthy | (Always_falsy, Always_falsy) -> Always_falsy | (Possibly_falsy, Possibly_falsy) -> Possibly_falsy | _ -> Possibly_falsy let intersect_truthiness tr1 tr2 = match (tr1, tr2) with | (Unknown, Possibly_falsy) | (Possibly_falsy, Unknown) -> Unknown | (Unknown, tr) | (tr, Unknown) -> tr | (Always_truthy, _) | (_, Always_truthy) -> Always_truthy | (Always_falsy, _) | (_, Always_falsy) -> Always_falsy | (Possibly_falsy, Possibly_falsy) -> Possibly_falsy let (tclass_is_falsy_when_empty, is_traversable) = let r = Typing_reason.Rnone in let mixed = MakeType.mixed r in let simple_xml_el = MakeType.class_type r "\\SimpleXMLElement" [] in let container_type = MakeType.container r mixed in let pair_type = MakeType.pair r mixed mixed in let tclass_is_falsy_when_empty env ty = Env.can_subtype env ty simple_xml_el || Env.can_subtype env ty container_type && not (Env.can_subtype env ty pair_type) in let trv = MakeType.traversable r mixed in let is_traversable env ty = Env.can_subtype env ty trv in (tclass_is_falsy_when_empty, is_traversable) (** Return the {!truthiness} of {ty}. Only possibly-falsy types are suitable scrutinees in a truthiness test--it is reasonable to test the truthiness of nullable types and container types which are falsy when empty. Other types (e.g. user-defined objects) are always truthy, so testing their truthiness indicates a logic error. *) let rec truthiness env ty = let (env, ty) = Env.expand_type env ty in match get_node ty with | Tany _ | Tdynamic | Tvar _ -> Unknown | Tnonnull | Tneg _ | Toption _ -> Possibly_falsy | Tnewtype (id, _, _) when Env.is_enum env id -> Possibly_falsy | Tclass ((_, cid), _, _) -> if String.equal cid SN.Classes.cStringish then Possibly_falsy else if String.equal cid SN.Classes.cXHPChild then Possibly_falsy else if tclass_is_falsy_when_empty env ty then Possibly_falsy else if not (is_traversable env ty) then Always_truthy else ( (* Classes which implement Traversable but not Container will always be truthy when empty. If this Tclass is instead an interface type like KeyedTraversable, the value may or may not be truthy when empty. *) match Decl_provider.get_class (Env.get_ctx env) cid with | None -> Unknown | Some cls -> (match Cls.kind cls with | Cclass _ -> Always_truthy | Cinterface | Cenum | Cenum_class _ -> Possibly_falsy | Ctrait -> Unknown) ) | Tprim Tresource -> Always_truthy | Tprim Tnull -> Always_falsy | Tprim Tvoid -> Always_falsy | Tprim Tnoreturn -> Unknown | Tprim (Tint | Tbool | Tfloat | Tstring | Tnum | Tarraykey) -> Possibly_falsy | Tunion tyl -> begin match List.map tyl ~f:(truthiness env) with | [] -> Unknown | hd :: tl -> List.fold tl ~init:hd ~f:fold_truthiness end | Tintersection tyl -> List.map tyl ~f:(truthiness env) |> List.fold ~init:Possibly_falsy ~f:intersect_truthiness | Tgeneric _ | Tnewtype _ | Tdependent _ -> let (env, tyl) = Env.get_concrete_supertypes ~abstract_enum:true env ty in begin match List.map tyl ~f:(truthiness env) with | [] -> Unknown | hd :: tl -> List.fold tl ~init:hd ~f:fold_truthiness end | Tshape { s_origin = _; s_unknown_value = shape_kind; s_fields = fields } -> if is_nothing shape_kind && TShapeMap.is_empty fields then Always_falsy else let has_non_optional_fields = TShapeMap.fold (fun _ { sft_optional = opt; _ } -> ( || ) (not opt)) fields false in if has_non_optional_fields then Always_truthy else Possibly_falsy | Ttuple [] -> Always_falsy | Ttuple (_ :: _) -> (* A tuple is a vec at runtime, and non-empty vecs are truthy. *) Always_truthy | Tfun _ | Taccess _ -> (* TODO(T36532263) check if that's ok *) Unknown | Tvec_or_dict _ -> (* TODO(T69768816) determine which variant is correct for vec_or_dict *) Unknown | Tunapplied_alias _ -> Typing_defs.error_Tunapplied_alias_in_illegal_context () (** When a type represented by one of these variants is used in a truthiness test, it indicates a potential logic error, since the truthiness of some values in the type may be surprising. *) type sketchy_type_kind = | String | Arraykey | Stringish | XHPChild (** Truthiness tests on strings may not behave as expected. The user may not know that the string "0" is falsy, and may have intended only to check for emptiness. *) | Traversable_interface of string (** Interface types which implement Traversable but not Container may be always truthy, even when empty. *) let rec find_sketchy_types env acc ty = let (env, ety) = Env.expand_type env ty in match get_node ety with | Toption ty -> find_sketchy_types env acc ty | Tprim Tstring -> String :: acc | Tprim Tarraykey -> Arraykey :: acc | Tclass ((_, cid), _, _) -> if String.equal cid SN.Classes.cStringish then Stringish :: acc else if String.equal cid SN.Classes.cXHPChild then XHPChild :: acc else if tclass_is_falsy_when_empty env ty || not (is_traversable env ty) then acc else ( match Decl_provider.get_class (Env.get_ctx env) cid with | None -> acc | Some cls -> (match Cls.kind cls with | Cinterface -> Traversable_interface (Env.print_ty env ty) :: acc | Cclass _ | Ctrait | Cenum_class _ | Cenum -> acc) ) | Tunion tyl -> List.fold tyl ~init:acc ~f:(find_sketchy_types env) | Tintersection tyl -> (* If one of the types in tyl does not have any sketchy type, then it's ok. *) let sketchy_tys = List.map tyl ~f:(find_sketchy_types env []) in let sketchy_tys = if List.exists sketchy_tys ~f:List.is_empty then [] else List.fold sketchy_tys ~init:[] ~f:( @ ) in sketchy_tys @ acc | Tgeneric _ | Tnewtype _ | Tdependent _ -> let (env, tyl) = Env.get_concrete_supertypes ~abstract_enum:true env ty in List.fold tyl ~init:acc ~f:(find_sketchy_types env) | Tany _ | Tnonnull | Tdynamic | Tprim _ | Tfun _ | Ttuple _ | Tshape _ | Tvar _ | Tvec_or_dict _ | Tunapplied_alias _ | Taccess _ | Tneg _ -> acc let find_sketchy_types env ty = find_sketchy_types env [] ty
OCaml Interface
hhvm/hphp/hack/src/typing/tast_utils.mli
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val type_non_nullable : Tast_env.env -> Tast.ty -> bool type truthiness = | Unknown | Always_truthy | Always_falsy | Possibly_falsy val truthiness : Tast_env.env -> Tast.ty -> truthiness type sketchy_type_kind = | String | Arraykey | Stringish | XHPChild | Traversable_interface of string val find_sketchy_types : Tast_env.env -> Tast.ty -> sketchy_type_kind list
OCaml
hhvm/hphp/hack/src/typing/tast_visitor.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 module Env = Tast_env class virtual iter = object (self) inherit [_] Aast.iter as super (* Entry point *) method go ctx program = self#on_list (fun () -> self#go_def ctx) () program method go_def ctx x = self#on_def (Env.def_env ctx x) x method! on_expr_ env expr_ = match expr_ with | Aast.Invalid _ -> () | _ -> super#on_expr_ env expr_ method! on_fun_ env x = super#on_fun_ (Env.restore_fun_env env x) x method! on_method_ env x = let env = if String.equal (snd x.Aast.m_name) Naming_special_names.Members.__construct then Env.set_inside_constructor env else if x.Aast.m_static then Env.set_static env else env in super#on_method_ (Env.restore_method_env env x) x method! on_class_var env cv = let env = if cv.Aast.cv_is_static then Env.set_static env else env in super#on_class_var env cv method! on_Binop env (Aast.{ bop; lhs; rhs } as binop) = match bop with | Ast_defs.Eq _ -> self#on_bop env bop; self#on_expr (Env.set_val_kind env Typing_defs.Lval) lhs; self#on_expr env rhs | _ -> super#on_Binop env binop method! on_Is env e h = let env = Env.set_allow_wildcards env in super#on_Is env e h method! on_As env e h = let env = Env.set_allow_wildcards env in super#on_As env e h method! on_expression_tree env Aast. { et_hint; et_splices; et_function_pointers; et_virtualized_expr; et_runtime_expr; et_dollardollar_pos = _; } = self#on_hint env et_hint; self#on_block env et_splices; let env = Env.inside_expr_tree env et_hint in self#on_block env et_function_pointers; self#on_expr env et_virtualized_expr; let env = Env.outside_expr_tree env in self#on_expr env et_runtime_expr method! on_ET_Splice env e = let env = Env.outside_expr_tree env in super#on_ET_Splice env e end class virtual ['state] iter_with_state = object (self) inherit [_] Aast.iter as super (* Entry point *) method go (state : 'state) ctx program = self#on_list (fun () -> self#go_def ctx state) () program method go_def ctx state x = self#on_def (Env.def_env ctx x, state) x method! on_expr_ env expr_ = match expr_ with | Aast.Invalid _ -> () | _ -> super#on_expr_ env expr_ method on_fun_with_env (env, state) x = super#on_fun_ (env, state) x method! on_fun_ (env, state) x = self#on_fun_with_env (Env.restore_fun_env env x, state) x method on_method_with_env (env, state) x = super#on_method_ (env, state) x method! on_method_ (env, state) x = let env = if String.equal (snd x.Aast.m_name) Naming_special_names.Members.__construct then Env.set_inside_constructor env else if x.Aast.m_static then Env.set_static env else env in self#on_method_with_env (Env.restore_method_env env x, state) x method on_class_var_with_env (env, state) cv = super#on_class_var (env, state) cv method! on_class_var (env, state) cv = let env = if cv.Aast.cv_is_static then Env.set_static env else env in self#on_class_var_with_env (env, state) cv method! on_Binop (env, state) (Aast.{ bop; lhs; rhs } as binop) = match bop with | Ast_defs.Eq _ -> self#on_bop (env, state) bop; self#on_expr (Env.set_val_kind env Typing_defs.Lval, state) lhs; self#on_expr (env, state) rhs | _ -> super#on_Binop (env, state) binop method! on_Is (env, state) e h = let env = Env.set_allow_wildcards env in super#on_Is (env, state) e h method! on_As (env, state) e h = let env = Env.set_allow_wildcards env in super#on_As (env, state) e h method! on_expression_tree (env, state) Aast. { et_hint; et_splices; et_function_pointers; et_virtualized_expr; et_runtime_expr; et_dollardollar_pos = _; } = self#on_hint (env, state) et_hint; self#on_block (env, state) et_splices; let env = Env.inside_expr_tree env et_hint in self#on_block (env, state) et_function_pointers; self#on_expr (env, state) et_virtualized_expr; let env = Env.outside_expr_tree env in self#on_expr (env, state) et_runtime_expr method! on_ET_Splice (env, state) e = let env = Env.outside_expr_tree env in super#on_ET_Splice (env, state) e end class virtual ['a] reduce = object (self) inherit [_] Aast.reduce as super (* Entry point *) method go ctx program : 'a = self#on_list (fun () -> self#go_def ctx) () program method go_def ctx x = self#on_def (Env.def_env ctx x) x method! on_expr_ env expr_ = match expr_ with | Aast.Invalid _ -> self#zero | _ -> super#on_expr_ env expr_ method! on_fun_ env x = super#on_fun_ (Env.restore_fun_env env x) x method! on_method_ env x = let env = if String.equal (snd x.Aast.m_name) Naming_special_names.Members.__construct then Env.set_inside_constructor env else if x.Aast.m_static then Env.set_static env else env in super#on_method_ (Env.restore_method_env env x) x method! on_class_var env cv = let env = if cv.Aast.cv_is_static then Env.set_static env else env in super#on_class_var env cv method! on_Binop env (Aast.{ bop; lhs; rhs } as binop) = match bop with | Ast_defs.Eq _ -> let op = self#on_bop env bop in let e1 = self#on_expr (Env.set_val_kind env Typing_defs.Lval) lhs in let e2 = self#on_expr env rhs in self#plus e1 (self#plus op e2) | _ -> super#on_Binop env binop method! on_Is env e h = let env = Env.set_allow_wildcards env in super#on_Is env e h method! on_As env e h = let env = Env.set_allow_wildcards env in super#on_As env e h method! on_expression_tree env Aast. { et_hint = hint; et_splices; et_function_pointers; et_virtualized_expr; et_runtime_expr; et_dollardollar_pos = _; } = let et_hint = self#on_hint env hint in let et_splices = self#on_block env et_splices in let env = Env.inside_expr_tree env hint in let et_function_pointers = self#on_block env et_function_pointers in let et_virtualized_expr = self#on_expr env et_virtualized_expr in let env = Env.outside_expr_tree env in let et_runtime_expr = self#on_expr env et_runtime_expr in self#plus et_hint (self#plus et_splices (self#plus et_function_pointers (self#plus et_virtualized_expr et_runtime_expr))) method! on_ET_Splice env e = let env = Env.outside_expr_tree env in super#on_ET_Splice env e end class virtual map = object (self) inherit [_] Aast.map as super method on_'ex _ ex = ex method on_'en _ en = en (* Entry point *) method go ctx program : Tast.program = self#on_list (fun () -> self#go_def ctx) () program method go_def ctx x = self#on_def (Env.def_env ctx x) x method! on_expr_ env expr_ = match expr_ with | Aast.Invalid _ -> expr_ | _ -> super#on_expr_ env expr_ method! on_fun_ env x = super#on_fun_ (Env.restore_fun_env env x) x method! on_method_ env x = let env = if String.equal (snd x.Aast.m_name) Naming_special_names.Members.__construct then Env.set_inside_constructor env else if x.Aast.m_static then Env.set_static env else env in super#on_method_ (Env.restore_method_env env x) x method! on_class_var env cv = let env = if cv.Aast.cv_is_static then Env.set_static env else env in super#on_class_var env cv method! on_Binop env (Aast.{ bop; lhs; rhs } as binop) = match bop with | Ast_defs.Eq _ -> Aast.Binop Aast. { bop = self#on_bop env bop; lhs = self#on_expr (Env.set_val_kind env Typing_defs.Lval) lhs; rhs = self#on_expr env rhs; } | _ -> super#on_Binop env binop method! on_Is env e h = let env = Env.set_allow_wildcards env in super#on_Is env e h method! on_As env e h = let env = Env.set_allow_wildcards env in super#on_As env e h method! on_expression_tree env Aast. { et_hint; et_splices; et_function_pointers; et_virtualized_expr; et_runtime_expr; et_dollardollar_pos; } = let et_hint = self#on_hint env et_hint in let et_splices = self#on_block env et_splices in let et_function_pointers = let env = Env.inside_expr_tree env et_hint in self#on_block env et_function_pointers in let et_virtualized_expr = let env = Env.inside_expr_tree env et_hint in self#on_expr env et_virtualized_expr in let et_runtime_expr = self#on_expr env et_runtime_expr in Aast. { et_hint; et_splices; et_function_pointers; et_virtualized_expr; et_runtime_expr; et_dollardollar_pos; } method! on_ET_Splice env e = let env = Env.outside_expr_tree env in super#on_ET_Splice env e end class virtual endo = object (self) inherit [_] Aast.endo as super method on_'ex _ ex = ex method on_'en _ en = en (* Entry point *) method go ctx program = self#on_list (fun () -> self#go_def ctx) () program method go_def ctx x = self#on_def (Env.def_env ctx x) x method! on_expr_ env expr_ = match expr_ with | Aast.Invalid _ -> expr_ | _ -> super#on_expr_ env expr_ method! on_fun_ env x = super#on_fun_ (Env.restore_fun_env env x) x method! on_method_ env x = let env = if String.equal (snd x.Aast.m_name) Naming_special_names.Members.__construct then Env.set_inside_constructor env else if x.Aast.m_static then Env.set_static env else env in super#on_method_ (Env.restore_method_env env x) x method! on_class_var env cv = let env = if cv.Aast.cv_is_static then Env.set_static env else env in super#on_class_var env cv method! on_Binop env this (Aast.{ bop = op; lhs = e1; rhs = e2 } as binop) = match op with | Ast_defs.Eq _ -> let op' = self#on_bop env op in let e1' = self#on_expr (Env.set_val_kind env Typing_defs.Lval) e1 in let e2' = self#on_expr env e2 in if Ast_defs.equal_bop op op' && phys_equal e1 e2' && phys_equal e2 e2' then this else Aast.(Binop { bop = op'; lhs = e1'; rhs = e2' }) | _ -> super#on_Binop env this binop method! on_Is env e h = let env = Env.set_allow_wildcards env in super#on_Is env e h method! on_As env e h = let env = Env.set_allow_wildcards env in super#on_As env e h method! on_expression_tree env Aast. { et_hint; et_splices; et_function_pointers; et_virtualized_expr; et_runtime_expr; et_dollardollar_pos; } = let et_hint = self#on_hint env et_hint in let et_splices = self#on_block env et_splices in let et_function_pointers = let env = Env.inside_expr_tree env et_hint in self#on_block env et_function_pointers in let et_virtualized_expr = let env = Env.inside_expr_tree env et_hint in self#on_expr env et_virtualized_expr in let et_runtime_expr = self#on_expr env et_runtime_expr in Aast. { et_hint; et_splices; et_function_pointers; et_virtualized_expr; et_runtime_expr; et_dollardollar_pos; } method! on_ET_Splice env e = let env = Env.outside_expr_tree env in super#on_ET_Splice env e end (** A {!handler} is an {!iter} visitor which is not in control of the iteration (and thus cannot change the order of the iteration or choose not to visit some subtrees). Intended to be used with {!iter_with} to aggregate many checks into a single pass over a TAST. *) class type handler = object method at_class_ : Env.t -> Tast.class_ -> unit method at_typedef : Env.t -> Tast.typedef -> unit method at_gconst : Env.t -> Tast.gconst -> unit method at_fun_def : Env.t -> Tast.fun_def -> unit method at_method_ : Env.t -> Tast.method_ -> unit method at_expr : Env.t -> Tast.expr -> unit method at_stmt : Env.t -> Tast.stmt -> unit method at_fun_ : Env.t -> Tast.fun_ -> unit method at_Call : Env.t -> Tast.call_expr -> unit method at_hint : Env.t -> Aast.hint -> unit method at_tparam : Env.t -> Tast.tparam -> unit method at_user_attribute : Env.t -> Tast.user_attribute -> unit method at_class_typeconst_def : Env.t -> Tast.class_typeconst_def -> unit method at_xhp_child : Env.t -> Tast.xhp_child -> unit end (** A {!handler} which does not need to make use of every visitation method can inherit from this no-op base class. *) class virtual handler_base : handler = object method at_class_ _ _ = () method at_typedef _ _ = () method at_gconst _ _ = () method at_fun_def _ _ = () method at_method_ _ _ = () method at_expr _ _ = () method at_stmt _ _ = () method at_fun_ _ _ = () method at_Call _ _ = () method at_hint _ _ = () method at_tparam _ _ = () method at_user_attribute _ _ = () method at_class_typeconst_def _ _ = () method at_xhp_child _ _ = () end (** Return an {!iter} visitor which invokes all of the given handlers upon visiting each node. *) let iter_with (handlers : handler list) : iter = object inherit iter as super method! on_class_ env x = List.iter handlers ~f:(fun v -> v#at_class_ env x); super#on_class_ env x method! on_typedef env x = List.iter handlers ~f:(fun v -> v#at_typedef env x); super#on_typedef env x method! on_gconst env x = List.iter handlers ~f:(fun v -> v#at_gconst env x); super#on_gconst env x method! on_fun_def env x = List.iter handlers ~f:(fun v -> v#at_fun_def env x); super#on_fun_def env x method! on_method_ env x = List.iter handlers ~f:(fun v -> v#at_method_ env x); super#on_method_ env x method! on_expr env x = List.iter handlers ~f:(fun v -> v#at_expr env x); super#on_expr env x method! on_stmt env x = List.iter handlers ~f:(fun v -> v#at_stmt env x); super#on_stmt env x method! on_fun_ env x = List.iter handlers ~f:(fun v -> v#at_fun_ env x); super#on_fun_ env x method! on_Call env call_expr = List.iter handlers ~f:(fun v -> v#at_Call env call_expr); super#on_Call env call_expr method! on_hint env h = List.iter handlers ~f:(fun v -> v#at_hint env h); super#on_hint env h method! on_tparam env h = List.iter handlers ~f:(fun v -> v#at_tparam env h); super#on_tparam env h method! on_user_attribute env ua = List.iter handlers ~f:(fun v -> v#at_user_attribute env ua); super#on_user_attribute env ua method! on_class_typeconst_def env tc = List.iter handlers ~f:(fun v -> v#at_class_typeconst_def env tc); super#on_class_typeconst_def env tc method! on_xhp_child env c = List.iter handlers ~f:(fun v -> v#at_xhp_child env c); super#on_xhp_child env c end
OCaml
hhvm/hphp/hack/src/typing/tast_with_dynamic.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude type 'a t = { under_normal_assumptions: 'a; under_dynamic_assumptions: 'a option; } [@@deriving eq, hash] let mk_without_dynamic under_normal_assumptions = { under_normal_assumptions; under_dynamic_assumptions = None } let map ~f x = { under_normal_assumptions = f x.under_normal_assumptions; under_dynamic_assumptions = Option.map ~f x.under_dynamic_assumptions; } let combine ~f x y = { under_normal_assumptions = f x.under_normal_assumptions y.under_normal_assumptions; under_dynamic_assumptions = begin match (x.under_dynamic_assumptions, y.under_dynamic_assumptions) with | (None, None) -> None | (Some x, None) -> Some x | (None, Some y) -> Some y | (Some x, Some y) -> Some (f x y) end; } let all x = let { under_normal_assumptions; under_dynamic_assumptions } = x in match under_dynamic_assumptions with | None -> [under_normal_assumptions] | Some under_dynamic_assumptions -> [under_normal_assumptions; under_dynamic_assumptions] let append xs ys = combine ~f:( @ ) xs ys let cons x xs = append (map ~f:(fun x -> x :: []) x) xs let collect xs = List.fold_right ~f:cons ~init:(mk_without_dynamic []) xs
OCaml Interface
hhvm/hphp/hack/src/typing/tast_with_dynamic.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 'a t = { under_normal_assumptions: 'a; under_dynamic_assumptions: 'a option; } [@@deriving eq, hash] val mk_without_dynamic : 'a -> 'a t val map : f:('a -> 'b) -> 'a t -> 'b t val combine : f:('a -> 'a -> 'a) -> 'a t -> 'a t -> 'a t val all : 'a t -> 'a list val cons : 'a t -> 'a list t -> 'a list t val append : 'a list t -> 'a list t -> 'a list t val collect : 'a t list -> 'a list t
OCaml
hhvm/hphp/hack/src/typing/trait_reuse_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. * *) (** Ban reuse of traits that have final methods. *) open Hh_prelude module Cls = Decl_provider.Class module Env = Typing_env let strip_ns = Utils.strip_ns let get_class env name = Decl_provider.get_class ?tracing_info:(Env.get_tracing_info env) (Env.get_ctx env) name let is_class env name = match get_class env name with | None -> false | Some c -> Cls.kind c |> Ast_defs.is_c_class (** Return the position where class/trait [type_name] is defined. *) let classish_def_pos env type_name : Pos_or_decl.t = let decl = get_class env type_name in match decl with | Some decl -> Cls.pos decl | None -> Pos_or_decl.none (** The final methods in [type_name] (excluding inherited methods), both instance and static methods. *) let final_methods env (type_name : string) : (string * Typing_defs.class_elt) list = let decl = get_class env type_name in match decl with | Some decl -> let methods = Cls.methods decl @ Cls.smethods decl in List.filter ~f:(fun (_, m) -> String.equal m.Typing_defs.ce_origin type_name && Typing_defs.get_ce_final m) methods | None -> [] (** Return a list of positions explaining why a final method is reused. *) let relevant_positions (env : Typing_env_types.env) ~class_name ~first_using_parent_or_trait_name ~second_using_trait_name ~reused_trait : string * (Pos_or_decl.t * string) list = let route = Ancestor_route.find_route env ~classish:first_using_parent_or_trait_name ~ancestor:reused_trait in let using_cls_name = match List.find (List.rev route) ~f:(is_class env) with | None -> class_name | Some c -> c in let result = if String.equal second_using_trait_name reused_trait then [] else Ancestor_route.describe_route env ~classish:second_using_trait_name ~ancestor:reused_trait in (* Show the position of the ancestor class that also uses this trait. *) let result = result @ [ ( classish_def_pos env using_cls_name, Printf.sprintf "`%s` is defined here" (strip_ns using_cls_name) ); ] in (* Since traits can use multiple other traits, show the full trait path so users can see how the trait reuse occurred. *) let result = result @ Ancestor_route.describe_route env ~classish:using_cls_name ~ancestor:reused_trait in (* Finally, show the final method in the trait. *) let (meth_name, meth) = List.hd_exn (final_methods env reused_trait) in ( using_cls_name, result @ [ ( Lazy.force meth.Typing_defs.ce_pos, Printf.sprintf "`%s` has a final method `%s`" (strip_ns reused_trait) meth_name ); ] ) let trait_reuse_with_final_method_error env class_elt ~class_name ~first_using_parent_or_trait ~second_using_trait:(second_using_trait_pos, second_using_trait) = let trait_name = class_elt.Typing_defs.ce_origin in let first_using_parent_or_trait_name = Cls.name first_using_parent_or_trait in let second_using_trait_name = Cls.name second_using_trait in let trace = lazy (relevant_positions env ~class_name ~first_using_parent_or_trait_name ~second_using_trait_name ~reused_trait:trait_name) in Typing_error.( primary @@ Primary.Trait_reuse_with_final_method { pos = second_using_trait_pos; trait_name; parent_cls_name = Lazy.map trace ~f:fst; trace = Lazy.map trace ~f:snd; }) let method_import_via_diamond_error env (class_name_pos, class_name) (method_name, class_elt) ~first_using_trait ~second_using_trait = let trait_name = class_elt.Typing_defs.ce_origin in Typing_error.( primary @@ Primary.Method_import_via_diamond { pos = class_name_pos; class_name; method_pos = force class_elt.Typing_defs.ce_pos; method_name; trace1 = lazy (Ancestor_route.describe_route_via env ~classish:class_name ~ancestor:trait_name ~via:(Cls.name second_using_trait)); trace2 = lazy (Ancestor_route.describe_route_via env ~classish:class_name ~ancestor:trait_name ~via:(Cls.name first_using_trait)); }) let property_import_via_diamond_error ~generic env (class_name_pos, class_name) (property_name, class_elt) ~first_using_trait ~second_using_trait = let trait_name = class_elt.Typing_defs.ce_origin in Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Property_import_via_diamond { generic; pos = class_name_pos; class_name; property_pos = Typing_defs.get_pos (Lazy.force class_elt.Typing_defs.ce_type); property_name; trace1 = lazy (Ancestor_route.describe_route_via env ~classish:class_name ~ancestor:trait_name ~via:(Cls.name second_using_trait)); trace2 = lazy (Ancestor_route.describe_route_via env ~classish:class_name ~ancestor:trait_name ~via:(Cls.name first_using_trait)); })
OCaml Interface
hhvm/hphp/hack/src/typing/trait_reuse_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 trait_reuse_with_final_method_error : Typing_env_types.env -> Typing_defs.class_elt -> class_name:string -> first_using_parent_or_trait:Decl_provider.class_decl -> second_using_trait:Pos.t * Decl_provider.class_decl -> Typing_error.t val method_import_via_diamond_error : Typing_env_types.env -> Pos.t * string -> string * Typing_defs.class_elt -> first_using_trait:Decl_provider.class_decl -> second_using_trait:Decl_provider.class_decl -> Typing_error.t val property_import_via_diamond_error : generic:bool -> Typing_env_types.env -> Pos.t * string -> string * Typing_defs.class_elt -> first_using_trait:Decl_provider.class_decl -> second_using_trait:Decl_provider.class_decl -> unit
OCaml
hhvm/hphp/hack/src/typing/type_mapper.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 Typing_defs open Typing_env_types module Env = Typing_env module Map = Type_mapper_generic type result = env * locl_ty let fresh_env env = env class type type_mapper_type = object inherit [env] Map.type_mapper_type end class shallow_type_mapper : type_mapper_type = object inherit [env] Map.shallow_type_mapper end class deep_type_mapper : type_mapper_type = object inherit [env] Map.deep_type_mapper end class virtual tunion_type_mapper = object inherit [env] Map.tunion_type_mapper end class virtual tinter_type_mapper = object inherit [env] Map.tinter_type_mapper end (* Mixin that expands type variables. *) class virtual tvar_expanding_type_mapper = object (this) method on_tvar env (r : Reason.t) n = let (env, ty) = Env.get_type env r n in if is_tyvar ty then (env, ty) else this#on_type env ty method virtual on_type : env -> locl_ty -> result end (* Mixin that maps across the type inside the typevar, and then changes * its value to the result. *) class virtual tvar_substituting_type_mapper = object (this) method on_tvar (env : env) (r : Reason.t) n = let (env, ty) = Env.get_type env r n in if is_tyvar ty then (env, ty) else let (env, ty) = this#on_type env ty in let env = Env.add env n ty in (env, ty) method virtual on_type : env -> locl_ty -> result end (** Type mapper which only maps types under combinations of unions, options and intersections. *) class union_inter_type_mapper = object inherit shallow_type_mapper inherit! tunion_type_mapper inherit! tinter_type_mapper inherit! tvar_expanding_type_mapper end
OCaml
hhvm/hphp/hack/src/typing/type_mapper_forget.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Typing_defs module Map = Type_mapper_generic type env = { (* the tyvar to be removed *) tyvar: int; (* why did we need to forget this type? *) forget_reason: Reason.t option; } let make_env tyvar = let forget_reason = None in { tyvar; forget_reason } class type forget_tyvar_mapper_type = object inherit [env] Map.internal_type_mapper_type inherit [env] Map.locl_constraint_type_mapper_type method recurse_opt : env -> locl_ty -> locl_ty option method recurse_internal_type_opt : env -> internal_type -> internal_type option end (** Type mapper which forgets a type variable, i.e. removes all occurences of a type variable *) class forget_tyvar_mapper : forget_tyvar_mapper_type = object (this) inherit [env] Map.deep_type_mapper inherit! [env] Map.constraint_type_mapper inherit! [env] Map.internal_type_mapper method private result_opt : type a. env -> a -> a option = fun env x -> match env.forget_reason with | Some _ -> None | None -> Some x method recurse_opt env locl_ty = let (env, locl_ty) = this#on_type env locl_ty in this#result_opt env locl_ty method recurse_internal_type_opt env ity = let (env, ity) = this#on_internal_type env ity in this#result_opt env ity method! on_tvar env r var = if Int.equal var env.tyvar then ({ env with forget_reason = Some r }, mk (r, Tunion [])) else (env, mk (r, Tvar var)) method! on_tunion env r tyl = let tyl = List.filter_map tyl ~f:(fun x -> let (env, ty) = this#on_type env x in this#recurse_opt env ty) in (env, mk (r, Tunion tyl)) method! on_tintersection env r tyl = let tyl = List.filter_map tyl ~f:(fun x -> let (env, ty) = this#on_type env x in this#recurse_opt env ty) in (env, mk (r, Tintersection tyl)) end
OCaml
hhvm/hphp/hack/src/typing/type_mapper_generic.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 Reason = Typing_reason let fresh_env env = env class type ['env] type_mapper_type = object method on_tvar : 'env -> Reason.t -> int -> 'env * locl_ty method on_tnonnull : 'env -> Reason.t -> 'env * locl_ty method on_tdynamic : 'env -> Reason.t -> 'env * locl_ty method on_tany : 'env -> Reason.t -> 'env * locl_ty method on_tprim : 'env -> Reason.t -> Aast.tprim -> 'env * locl_ty method on_ttuple : 'env -> Reason.t -> locl_ty list -> 'env * locl_ty method on_tunion : 'env -> Reason.t -> locl_ty list -> 'env * locl_ty method on_tintersection : 'env -> Reason.t -> locl_ty list -> 'env * locl_ty method on_toption : 'env -> Reason.t -> locl_ty -> 'env * locl_ty method on_tfun : 'env -> Reason.t -> locl_fun_type -> 'env * locl_ty method on_tgeneric : 'env -> Reason.t -> string -> locl_ty list -> 'env * locl_ty method on_tunapplied_alias : 'env -> Reason.t -> string -> 'env * locl_ty method on_tnewtype : 'env -> Reason.t -> string -> locl_ty list -> locl_ty -> 'env * locl_ty method on_tdependent : 'env -> Reason.t -> dependent_type -> locl_ty -> 'env * locl_ty method on_tclass : 'env -> Reason.t -> pos_id -> exact -> locl_ty list -> 'env * locl_ty method on_tshape : 'env -> Reason.t -> locl_phase shape_type -> 'env * locl_ty method on_tvec_or_dict : 'env -> Reason.t -> locl_ty -> locl_ty -> 'env * locl_ty method on_taccess : 'env -> Reason.t -> locl_ty -> pos_id -> 'env * locl_ty method on_neg_type : 'env -> Reason.t -> neg_type -> 'env * locl_ty method on_type : 'env -> locl_ty -> 'env * locl_ty method on_locl_ty_list : 'env -> locl_ty list -> 'env * locl_ty list end (* Base type mapper implementation that doesn't recursively go into the * types. *) class ['env] shallow_type_mapper : ['env] type_mapper_type = object (this) method on_tvar env r n = (env, mk (r, Tvar n)) method on_tnonnull env r = (env, mk (r, Tnonnull)) method on_tdynamic env r = (env, mk (r, Tdynamic)) method on_tany env r = (env, mk (r, Typing_defs.make_tany ())) method on_tprim env r p = (env, mk (r, Tprim p)) method on_ttuple env r tyl = (env, mk (r, Ttuple tyl)) method on_tunion env r tyl = (env, mk (r, Tunion tyl)) method on_tintersection env r tyl = (env, mk (r, Tintersection tyl)) method on_toption env r ty = (env, mk (r, Toption ty)) method on_tfun env r fun_type = (env, mk (r, Tfun fun_type)) method on_tgeneric env r name args = (env, mk (r, Tgeneric (name, args))) method on_tunapplied_alias env r name = (env, mk (r, Tunapplied_alias name)) method on_tnewtype env r name tyl ty = (env, mk (r, Tnewtype (name, tyl, ty))) method on_tdependent env r dep ty = (env, mk (r, Tdependent (dep, ty))) method on_tclass env r x e tyl = (env, mk (r, Tclass (x, e, tyl))) method on_tshape env r { s_origin = _; s_unknown_value = shape_kind; s_fields = fdm } = ( env, mk ( r, Tshape { (* TODO(shapes) Should this reset the origin? *) s_origin = Missing_origin; s_unknown_value = shape_kind; s_fields = fdm; } ) ) method on_tvec_or_dict env r ty1 ty2 = (env, mk (r, Tvec_or_dict (ty1, ty2))) method on_taccess env r ty id = (env, mk (r, Taccess (ty, id))) method on_neg_type env r p = (env, mk (r, Tneg p)) method on_type env ty = let (r, ty) = deref ty in match ty with | Tvar n -> this#on_tvar env r n | Tnonnull -> this#on_tnonnull env r | Tany _ -> this#on_tany env r | Tprim p -> this#on_tprim env r p | Ttuple tyl -> this#on_ttuple env r tyl | Tunion tyl -> this#on_tunion env r tyl | Tintersection tyl -> this#on_tintersection env r tyl | Toption ty -> this#on_toption env r ty | Tfun fun_type -> this#on_tfun env r fun_type | Tgeneric (x, args) -> this#on_tgeneric env r x args | Tnewtype (x, tyl, ty) -> this#on_tnewtype env r x tyl ty | Tdependent (x, ty) -> this#on_tdependent env r x ty | Tclass (x, e, tyl) -> this#on_tclass env r x e tyl | Tdynamic -> this#on_tdynamic env r | Tshape s -> this#on_tshape env r s | Tvec_or_dict (ty1, ty2) -> this#on_tvec_or_dict env r ty1 ty2 | Tunapplied_alias name -> this#on_tunapplied_alias env r name | Taccess (ty, id) -> this#on_taccess env r ty id | Tneg ty -> this#on_neg_type env r ty method on_locl_ty_list env tyl = List.map_env env tyl ~f:this#on_type end (* Mixin class - adding it to shallow type mapper creates a mapper that * traverses the type by going inside Tunion *) class virtual ['env] tunion_type_mapper = object (this) method on_tunion env r tyl : 'env * locl_ty = let (env, tyl) = this#on_locl_ty_list env tyl in (env, mk (r, Tunion tyl)) method virtual on_locl_ty_list : 'env -> locl_ty list -> 'env * locl_ty list end class virtual ['env] tinter_type_mapper = object (this) method on_tintersection env r tyl : 'env * locl_ty = let (env, tyl) = this#on_locl_ty_list env tyl in (env, mk (r, Tintersection tyl)) method virtual on_locl_ty_list : 'env -> locl_ty list -> 'env * locl_ty list end (* Mixin that expands type variables. *) class virtual ['env] tvar_expanding_type_mapper = object (this) method on_tvar (env, expand) r n = let (env, ty) = expand env r n in if is_tyvar ty then ((env, expand), ty) else this#on_type (env, expand) ty method virtual on_type : 'env * ('env -> Reason.t -> int -> 'env * locl_ty) -> locl_ty -> ('env * ('env -> Reason.t -> int -> 'env * locl_ty)) * locl_ty end (* Mixin that maps across the type inside the typevar, and then changes * its value to the result. *) class virtual ['env] tvar_substituting_type_mapper = object (this) method on_tvar ((env, expand, add) : 'env * ('env -> Reason.t -> int -> 'env * locl_ty) * ('env -> int -> locl_ty -> 'env)) (r : Reason.t) (n : int) = let (env, ty) = expand env r n in if is_tyvar ty then (env, ty) else let ((env, _expand, add), ty) = this#on_type (env, expand, add) ty in let env = add env n ty in (env, ty) method virtual on_type : 'env * ('env -> Reason.t -> int -> 'env * locl_ty) * ('env -> int -> locl_ty -> 'env) -> locl_ty -> ('env * ('env -> Reason.t -> int -> 'env * locl_ty) * ('env -> int -> locl_ty -> 'env)) * locl_ty end (* Implementation of type_mapper that recursively visits everything in the * type. * NOTE: by default it doesn't to anything to Tvars. Include one of the mixins * below to specify how you want to treat type variables. *) class ['env] deep_type_mapper = object (this) inherit ['env] shallow_type_mapper inherit! ['env] tunion_type_mapper inherit! ['env] tinter_type_mapper method! on_ttuple env r tyl = let (env, tyl) = this#on_locl_ty_list env tyl in (env, mk (r, Ttuple tyl)) method! on_toption env r ty = let (env, ty) = this#on_type env ty in (env, mk (r, Toption ty)) method! on_tfun env r ft = let on_param env param = let (env, ty) = this#on_possibly_enforced_ty env param.fp_type in (env, { param with fp_type = ty }) in let (env, params) = List.map_env env ft.ft_params ~f:on_param in let (env, ret) = this#on_possibly_enforced_ty env ft.ft_ret in (env, mk (r, Tfun { ft with ft_params = params; ft_ret = ret })) method! on_tnewtype env r x tyl cstr = let (env, tyl) = List.map_env env tyl ~f:this#on_type in let (env, cstr) = this#on_type env cstr in (env, mk (r, Tnewtype (x, tyl, cstr))) method! on_tdependent env r x cstr = let (env, cstr) = this#on_type env cstr in (env, mk (r, Tdependent (x, cstr))) method! on_tclass env r x e tyl = let (env, tyl) = this#on_locl_ty_list env tyl in (env, mk (r, Tclass (x, e, tyl))) method! on_tshape env r { s_origin = _; s_unknown_value = shape_kind; s_fields = fdm } = let (env, fdm) = ShapeFieldMap.map_env this#on_type env fdm in ( env, mk ( r, Tshape { s_origin = Missing_origin; s_unknown_value = shape_kind; (* TODO(shapes) this#on_type env shape_kind? *) s_fields = fdm; } ) ) method private on_opt_type env x = match x with | None -> (env, None) | Some x -> let (env, x) = this#on_type env x in (env, Some x) method private on_possibly_enforced_ty env x = let (env, et_type) = this#on_type env x.et_type in (env, { x with et_type }) end class type ['env] constraint_type_mapper_type = object method on_constraint_type : 'env -> constraint_type -> 'env * constraint_type method on_constraint_type_ : 'env -> Reason.t -> constraint_type_ -> 'env * constraint_type method on_Thas_member : 'env -> Reason.t -> has_member -> 'env * constraint_type method on_Thas_type_member : 'env -> Reason.t -> has_type_member -> 'env * constraint_type method on_Tcan_index : 'env -> Reason.t -> can_index -> 'env * constraint_type method on_Tcan_traverse : 'env -> Reason.t -> can_traverse -> 'env * constraint_type method on_Tdestructure : 'env -> Reason.t -> destructure -> 'env * constraint_type method on_TCunion : 'env -> Reason.t -> locl_ty -> constraint_type -> 'env * constraint_type method on_TCintersection : 'env -> Reason.t -> locl_ty -> constraint_type -> 'env * constraint_type end class type ['env] locl_constraint_type_mapper_type = object inherit ['env] constraint_type_mapper_type inherit ['env] type_mapper_type end class ['env] constraint_type_mapper : ['env] locl_constraint_type_mapper_type = object (this) inherit ['env] deep_type_mapper method on_constraint_type env ty = let (r, ty) = deref_constraint_type ty in this#on_constraint_type_ env r ty method on_constraint_type_ env r ty_ = match ty_ with | Thas_member hm -> this#on_Thas_member env r hm | Thas_type_member htm -> this#on_Thas_type_member env r htm | Tcan_index ci -> this#on_Tcan_index env r ci | Tcan_traverse ct -> this#on_Tcan_traverse env r ct | Tdestructure tyl -> this#on_Tdestructure env r tyl | TCunion (lty, cty) -> this#on_TCunion env r lty cty | TCintersection (lty, cty) -> this#on_TCintersection env r lty cty method on_Thas_member env r hm = let { hm_name; hm_type; hm_class_id; hm_explicit_targs } = hm in let (env, hm_type) = this#on_type env hm_type in let hm = { hm_name; hm_type; hm_class_id; hm_explicit_targs } in (env, mk_constraint_type (r, Thas_member hm)) method on_Thas_type_member env r htm = let { htm_id; htm_lower; htm_upper } = htm in let (env, htm_lower) = this#on_type env htm_lower in let (env, htm_upper) = this#on_type env htm_upper in let htm = { htm_id; htm_lower; htm_upper } in (env, mk_constraint_type (r, Thas_type_member htm)) method on_Tcan_index env r ci = let { ci_key; ci_shape; ci_val; ci_expr_pos; ci_index_pos } = ci in let (env, ci_key) = this#on_type env ci_key in let (env, ci_val) = this#on_type env ci_val in let ci = { ci_key; ci_shape; ci_val; ci_expr_pos; ci_index_pos } in (env, mk_constraint_type (r, Tcan_index ci)) method on_Tcan_traverse env r ct = let { ct_key; ct_val; ct_is_await; ct_reason } = ct in let (env, ct_key) = this#on_opt_type env ct_key in let (env, ct_val) = this#on_type env ct_val in let ct = { ct_key; ct_val; ct_is_await; ct_reason } in (env, mk_constraint_type (r, Tcan_traverse ct)) method on_Tdestructure env r { d_required; d_optional; d_variadic; d_kind } = let (env, d_required) = this#on_locl_ty_list env d_required in let (env, d_optional) = this#on_locl_ty_list env d_optional in let (env, d_variadic) = this#on_opt_type env d_variadic in ( env, mk_constraint_type (r, Tdestructure { d_required; d_optional; d_variadic; d_kind }) ) method on_TCunion env r lty cty = let (env, lty) = this#on_type env lty in let (env, cty) = this#on_constraint_type env cty in (env, mk_constraint_type (r, TCunion (lty, cty))) method on_TCintersection env r lty cty = let (env, lty) = this#on_type env lty in let (env, cty) = this#on_constraint_type env cty in (env, mk_constraint_type (r, TCintersection (lty, cty))) end class type ['env] internal_type_mapper_type = object inherit ['env] locl_constraint_type_mapper_type method on_internal_type : 'env -> internal_type -> 'env * internal_type method on_LoclType : 'env -> locl_ty -> 'env * internal_type method on_ConstraintType : 'env -> constraint_type -> 'env * internal_type end class ['env] internal_type_mapper : ['env] internal_type_mapper_type = object (this) inherit ['env] constraint_type_mapper method on_internal_type env ty = match ty with | LoclType ty -> this#on_LoclType env ty | ConstraintType ty -> this#on_ConstraintType env ty method on_LoclType env ty = let (env, ty) = this#on_type env ty in (env, LoclType ty) method on_ConstraintType env ty = let (env, ty) = this#on_constraint_type env ty in (env, ConstraintType ty) end
OCaml Interface
hhvm/hphp/hack/src/typing/type_mapper_generic.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. * *) [@@@warning "-33"] open Hh_prelude [@@@warning "+33"] val fresh_env : 'env -> 'env class type ['env] type_mapper_type = object method on_tvar : 'env -> Typing_reason.t -> int -> 'env * Typing_defs.locl_ty method on_tnonnull : 'env -> Typing_reason.t -> 'env * Typing_defs.locl_ty method on_tdynamic : 'env -> Typing_reason.t -> 'env * Typing_defs.locl_ty method on_tany : 'env -> Typing_reason.t -> 'env * Typing_defs.locl_ty method on_tprim : 'env -> Typing_reason.t -> Aast.tprim -> 'env * Typing_defs.locl_ty method on_ttuple : 'env -> Typing_reason.t -> Typing_defs.locl_ty list -> 'env * Typing_defs.locl_ty method on_tunion : 'env -> Typing_reason.t -> Typing_defs.locl_ty list -> 'env * Typing_defs.locl_ty method on_tintersection : 'env -> Typing_reason.t -> Typing_defs.locl_ty list -> 'env * Typing_defs.locl_ty method on_toption : 'env -> Typing_reason.t -> Typing_defs.locl_ty -> 'env * Typing_defs.locl_ty method on_tfun : 'env -> Typing_reason.t -> Typing_defs.locl_fun_type -> 'env * Typing_defs.locl_ty method on_tgeneric : 'env -> Typing_reason.t -> string -> Typing_defs.locl_ty list -> 'env * Typing_defs.locl_ty method on_tunapplied_alias : 'env -> Typing_reason.t -> string -> 'env * Typing_defs.locl_ty method on_tnewtype : 'env -> Typing_reason.t -> string -> Typing_defs.locl_ty list -> Typing_defs.locl_ty -> 'env * Typing_defs.locl_ty method on_tdependent : 'env -> Typing_reason.t -> Typing_defs.dependent_type -> Typing_defs.locl_ty -> 'env * Typing_defs.locl_ty method on_tclass : 'env -> Typing_reason.t -> Typing_defs.pos_id -> Typing_defs.exact -> Typing_defs.locl_ty list -> 'env * Typing_defs.locl_ty method on_tshape : 'env -> Typing_reason.t -> Typing_defs.locl_phase Typing_defs.shape_type -> 'env * Typing_defs.locl_ty method on_tvec_or_dict : 'env -> Typing_reason.t -> Typing_defs.locl_ty -> Typing_defs.locl_ty -> 'env * Typing_defs.locl_ty method on_taccess : 'env -> Typing_reason.t -> Typing_defs.locl_ty -> Typing_defs.pos_id -> 'env * Typing_defs.locl_ty method on_neg_type : 'env -> Typing_reason.t -> Typing_defs.neg_type -> 'env * Typing_defs.locl_ty method on_type : 'env -> Typing_defs.locl_ty -> 'env * Typing_defs.locl_ty method on_locl_ty_list : 'env -> Typing_defs.locl_ty list -> 'env * Typing_defs.locl_ty list end (* Base type mapper implementation that doesn't recursively go into the * types. *) class ['env] shallow_type_mapper : ['env] type_mapper_type (* Mixin class - adding it to shallow type mapper creates a mapper that * traverses the type by going inside Tunion *) class virtual ['env] tunion_type_mapper : object method on_tunion : 'env -> Typing_reason.t -> Typing_defs.locl_ty list -> 'env * Typing_defs.locl_ty method virtual on_locl_ty_list : 'env -> Typing_defs.locl_ty list -> 'env * Typing_defs.locl_ty list end class virtual ['env] tinter_type_mapper : object method on_tintersection : 'env -> Typing_reason.t -> Typing_defs.locl_ty list -> 'env * Typing_defs.locl_ty method virtual on_locl_ty_list : 'env -> Typing_defs.locl_ty list -> 'env * Typing_defs.locl_ty list end (* Mixin that expands type variables. *) class virtual ['env] tvar_expanding_type_mapper : object method on_tvar : 'env * ('env -> Typing_reason.t -> int -> 'env * Typing_defs.locl_ty) -> Typing_reason.t -> int -> ('env * ('env -> Typing_reason.t -> int -> 'env * Typing_defs.locl_ty)) * Typing_defs.locl_ty method virtual on_type : 'env * ('env -> Typing_reason.t -> int -> 'env * Typing_defs.locl_ty) -> Typing_defs.locl_ty -> ('env * ('env -> Typing_reason.t -> int -> 'env * Typing_defs.locl_ty)) * Typing_defs.locl_ty end (* Mixin that maps across the type inside the typevar, and then changes * its value to the result. *) class virtual ['env] tvar_substituting_type_mapper : object method on_tvar : 'env * ('env -> Typing_reason.t -> int -> 'env * Typing_defs.locl_ty) * ('env -> int -> Typing_defs.locl_ty -> 'env) -> Typing_reason.t -> int -> 'env * Typing_defs.locl_ty method virtual on_type : 'env * ('env -> Typing_reason.t -> int -> 'env * Typing_defs.locl_ty) * ('env -> int -> Typing_defs.locl_ty -> 'env) -> Typing_defs.locl_ty -> ('env * ('env -> Typing_reason.t -> int -> 'env * Typing_defs.locl_ty) * ('env -> int -> Typing_defs.locl_ty -> 'env)) * Typing_defs.locl_ty end (* Implementation of type_mapper that recursively visits everything in the * type. * NOTE: by default it doesn't do anything to Tvars. Include one of the mixins * below to specify how you want to treat type variables. *) class ['env] deep_type_mapper : ['env] type_mapper_type class type ['env] constraint_type_mapper_type = object method on_constraint_type : 'env -> Typing_defs.constraint_type -> 'env * Typing_defs.constraint_type method on_constraint_type_ : 'env -> Typing_reason.t -> Typing_defs.constraint_type_ -> 'env * Typing_defs.constraint_type method on_Thas_member : 'env -> Typing_reason.t -> Typing_defs.has_member -> 'env * Typing_defs.constraint_type method on_Thas_type_member : 'env -> Typing_reason.t -> Typing_defs.has_type_member -> 'env * Typing_defs.constraint_type method on_Tcan_index : 'env -> Typing_reason.t -> Typing_defs.can_index -> 'env * Typing_defs.constraint_type method on_Tcan_traverse : 'env -> Typing_reason.t -> Typing_defs.can_traverse -> 'env * Typing_defs.constraint_type method on_Tdestructure : 'env -> Typing_reason.t -> Typing_defs.destructure -> 'env * Typing_defs.constraint_type method on_TCunion : 'env -> Typing_reason.t -> Typing_defs.locl_ty -> Typing_defs.constraint_type -> 'env * Typing_defs.constraint_type method on_TCintersection : 'env -> Typing_reason.t -> Typing_defs.locl_ty -> Typing_defs.constraint_type -> 'env * Typing_defs.constraint_type end class type ['env] locl_constraint_type_mapper_type = object inherit ['env] constraint_type_mapper_type inherit ['env] type_mapper_type end class ['env] constraint_type_mapper : ['env] locl_constraint_type_mapper_type class type ['env] internal_type_mapper_type = object inherit ['env] locl_constraint_type_mapper_type method on_internal_type : 'env -> Typing_defs.internal_type -> 'env * Typing_defs.internal_type method on_LoclType : 'env -> Typing_defs.locl_ty -> 'env * Typing_defs.internal_type method on_ConstraintType : 'env -> Typing_defs.constraint_type -> 'env * Typing_defs.internal_type end class ['env] internal_type_mapper : ['env] internal_type_mapper_type
OCaml
hhvm/hphp/hack/src/typing/type_parameter_env.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) [@@@warning "-33"] open Hh_prelude [@@@warning "+33"] open Typing_defs open Typing_kinding_defs module SN = Naming_special_names module TySet = Typing_set type tparam_name = string type tparam_bounds = TySet.t let empty_bounds = TySet.empty let singleton_bound ty = TySet.singleton ty type tparam_info = Typing_kinding_defs.kind let tparam_info_size tpinfo = TySet.cardinal tpinfo.lower_bounds + TySet.cardinal tpinfo.upper_bounds type t = { tparams: (Pos_or_decl.t * tparam_info) SMap.t; (** The position indicates where the type parameter was defined. It may be Pos.none if the type parameter denotes a fresh type variable (i.e., without a source location that defines it) *) consistent: bool; } let empty = { tparams = SMap.empty; consistent = true } let mem name tpenv = SMap.mem name tpenv.tparams let get_with_pos name tpenv = SMap.find_opt name tpenv.tparams let get name tpenv = Option.map (get_with_pos name tpenv) ~f:snd let get_tparams tpenv = tpenv.tparams let add ~def_pos name tpinfo tpenv = { tpenv with tparams = SMap.add name (def_pos, tpinfo) tpenv.tparams } let union tpenv1 tpenv2 = { tparams = SMap.union tpenv1.tparams tpenv2.tparams; consistent = tpenv1.consistent && tpenv2.consistent; } (* TODO(T70068435): needs to learn about parameters if higher-kinded? *) let size tpenv = SMap.fold (fun _ (_, tpinfo) count -> tparam_info_size tpinfo + count) tpenv.tparams 0 let fold f tpenv accu = SMap.fold (fun name (_, tparam_info) acc -> f name tparam_info acc) tpenv.tparams accu let merge_env env tpenv1 tpenv2 ~combine = let (env, tparams) = match (tpenv1.consistent, tpenv2.consistent) with | (false, true) -> (env, tpenv2.tparams) | (true, false) -> (env, tpenv1.tparams) | _ -> SMap.merge_env env tpenv1.tparams tpenv2.tparams ~combine in (env, { tparams; consistent = tpenv1.consistent || tpenv2.consistent }) let get_lower_bounds tpenv name tyargs = (* TODO(T70068435) For now, anything with tyargs cannot have bounds. Eventually, we need to instantiate the parameters with the provided args. We must support the case here that the number of provided tyargs does not match the number of expected arguments for the named type parameter. In this case, chop off superfluous argumnents and fill in Tany for missing ones. *) match (get name tpenv, tyargs) with | (_, _ :: _) | (None, _) -> empty_bounds | (Some { lower_bounds; _ }, _) -> lower_bounds let get_upper_bounds tpenv name tyargs = (* TODO(T70068435) For now, anything with tyargs cannot have bounds. Eventually, we need to instantiate the parameters with the provided args. We must support the case here that the number of provided tyargs does not match the number of expected arguments for the named type parameter. In this case, chop off superfluous argumnents and fill in Tany for missing ones. *) match (get name tpenv, tyargs) with | (_, _ :: _) | (None, _) -> empty_bounds | (Some { upper_bounds; _ }, _) -> upper_bounds let get_arity tpenv name = match get name tpenv with | None -> 0 | Some { parameters; _ } -> List.length parameters let get_reified tpenv name = match get name tpenv with | None -> Aast.Erased | Some { reified; _ } -> reified let get_enforceable tpenv name = match get name tpenv with | None -> false | Some { enforceable; _ } -> enforceable let get_newable tpenv name = match get name tpenv with | None -> false | Some { newable; _ } -> newable let get_require_dynamic tpenv name = match get name tpenv with | None -> false | Some { require_dynamic; _ } -> require_dynamic let get_pos tpenv name = match get_with_pos name tpenv with | None -> Pos_or_decl.none | Some (pos, _) -> pos let get_tparam_names tpenv = SMap.keys tpenv.tparams let is_consistent tpenv = tpenv.consistent let mark_inconsistent tpenv = { tpenv with consistent = false } (* This assumes that [name] is a nullary generic parameter *) let rec is_generic_param ~elide_nullable ty name = match get_node ty with | Tgeneric (name', []) -> String.equal name name' | Toption ty when elide_nullable -> is_generic_param ~elide_nullable ty name | _ -> false (* Add a single new upper bound [ty] to generic parameter [name] in [tpenv] *) let add_upper_bound_ tpenv name ty = (* Don't add superfluous T <: T or T <: ?T to environment *) if is_generic_param ~elide_nullable:true ty name then tpenv else let (def_pos, tpinfo) = match get_with_pos name tpenv with | None -> ( Pos_or_decl.none, { lower_bounds = empty_bounds; upper_bounds = singleton_bound ty; reified = Aast.Erased; enforceable = false; newable = false; require_dynamic = false; parameters = []; } ) | Some (pos, tp) -> (pos, { tp with upper_bounds = TySet.add ty tp.upper_bounds }) in add ~def_pos name tpinfo tpenv (* Add a single new lower bound [ty] to generic parameter [name] in [tpenv] *) let add_lower_bound_ tpenv name ty = (* Don't add superfluous T <: T to environment *) if is_generic_param ~elide_nullable:false ty name then tpenv else let (def_pos, tpinfo) = match get_with_pos name tpenv with | None -> ( Pos_or_decl.none, { lower_bounds = singleton_bound ty; upper_bounds = empty_bounds; reified = Aast.Erased; enforceable = false; newable = false; require_dynamic = false; parameters = []; } ) | Some (pos, tp) -> (pos, { tp with lower_bounds = TySet.add ty tp.lower_bounds }) in add ~def_pos name tpinfo tpenv (* Add a single new upper bound [ty] to generic parameter [name]. * 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_tpenv name ty = let tpenv = match deref ty with | (r, Tgeneric (formal_super, [])) -> add_lower_bound_ env_tpenv formal_super (mk (r, Tgeneric (name, []))) | (_r, Tgeneric (_formal_super, _tyargs)) -> (* TODO(T70068435) Revisit this when implementing bounds on HK generic vars *) env_tpenv | _ -> env_tpenv in match intersect with | None -> add_upper_bound_ env_tpenv name ty | Some intersect -> let tyl = intersect ty (TySet.elements (get_upper_bounds env_tpenv name [])) in let add_generic ty tys = if is_generic_param ~elide_nullable:true ty name then tys else TySet.add ty tys in let def_pos = get_pos env_tpenv name in let upper_bounds = List.fold_right ~init:TySet.empty ~f:add_generic tyl in let lower_bounds = get_lower_bounds env_tpenv name [] in let reified = get_reified env_tpenv name in let enforceable = get_enforceable env_tpenv name in let newable = get_newable env_tpenv name in let require_dynamic = get_require_dynamic env_tpenv name in let parameters = [] in add ~def_pos name { lower_bounds; upper_bounds; reified; enforceable; newable; require_dynamic; parameters; } tpenv (* Add a single new upper lower [ty] to generic parameter [name]. * 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_tpenv name ty = let tpenv = match deref ty with | (r, Tgeneric (formal_sub, [])) -> add_upper_bound_ env_tpenv formal_sub (mk (r, Tgeneric (name, []))) | (_r, Tgeneric (_formal_sub, _tyargs)) -> (* TODO(T70068435) Revisit this when implementing bounds on HK generic vars *) env_tpenv | _ -> env_tpenv in match union with | None -> add_lower_bound_ env_tpenv name ty | Some union -> let tyl = union ty (TySet.elements (get_lower_bounds env_tpenv name [])) in let def_pos = get_pos env_tpenv name in let lower_bounds = List.fold_right ~init:TySet.empty ~f:TySet.add tyl in let upper_bounds = get_upper_bounds env_tpenv name [] in let reified = get_reified env_tpenv name in let enforceable = get_enforceable env_tpenv name in let newable = get_newable env_tpenv name in let require_dynamic = get_require_dynamic env_tpenv name in let parameters = [] in add ~def_pos name { lower_bounds; upper_bounds; reified; enforceable; newable; require_dynamic; parameters; } tpenv let remove_upper_bound tpenv name bound = match get_with_pos name tpenv with | None -> tpenv | Some (def_pos, tparam_info) -> let bounds = tparam_info.upper_bounds in let bounds = TySet.remove bound bounds in let tparam_info = { tparam_info with upper_bounds = bounds } in add ~def_pos name tparam_info tpenv let remove_lower_bound tpenv name bound = match get_with_pos name tpenv with | None -> tpenv | Some (def_pos, tparam_info) -> let bounds = tparam_info.lower_bounds in let bounds = TySet.remove bound bounds in let tparam_info = { tparam_info with lower_bounds = bounds } in add ~def_pos name tparam_info tpenv let remove tpenv name = (* TODO(T70068435) Revisit this function when implementing bounds on HK generic vars, in particular, look at the two Tgeneric below. *) let tparam = mk (Typing_reason.Rnone, Tgeneric (name, [])) in let lower_bounds = get_lower_bounds tpenv name [] in let remove_from_upper_bounds_of ty tpenv = match get_node ty with | Tgeneric (name, _tyargs) -> remove_upper_bound tpenv name tparam | _ -> tpenv in let tpenv = TySet.fold remove_from_upper_bounds_of lower_bounds tpenv in let upper_bounds = get_upper_bounds tpenv name [] in let remove_from_lower_bounds_of ty tpenv = match get_node ty with | Tgeneric (name, _tyargs) -> remove_lower_bound tpenv name tparam | _ -> tpenv in let tpenv = TySet.fold remove_from_lower_bounds_of upper_bounds tpenv in { tpenv with tparams = SMap.remove name tpenv.tparams } (* Add type parameters to environment, initially with no bounds. * Existing type parameters with the same name will be overridden. *) let add_generic_parameters tpenv tparaml = let rec make_param_info ast_tparam = let { tp_user_attributes; tp_tparams; _ } = ast_tparam in let enforceable = Attributes.mem SN.UserAttributes.uaEnforceable tp_user_attributes in let newable = Attributes.mem SN.UserAttributes.uaNewable tp_user_attributes in let require_dynamic = Attributes.mem SN.UserAttributes.uaRequireDynamic tp_user_attributes in let nested_params = List.map tp_tparams ~f:(fun tp -> (tp.tp_name, make_param_info tp)) in { lower_bounds = empty_bounds; upper_bounds = empty_bounds; reified = ast_tparam.tp_reified; enforceable; newable; require_dynamic; parameters = nested_params; } in let add_top tpenv ast_tparam = let (pos, name) = ast_tparam.tp_name in add ~def_pos:pos name (make_param_info ast_tparam) tpenv in List.fold_left tparaml ~f:add_top ~init:tpenv let get_parameter_names tpi = List.map tpi.parameters ~f:(fun (name, _) -> snd name) let rec pp_tparam_info fmt tpi = Format.fprintf fmt "@[<hv 2>{ "; Format.fprintf fmt "@[%s =@ " "lower_bounds"; TySet.pp fmt tpi.lower_bounds; Format.fprintf fmt "@]"; Format.fprintf fmt ";@ "; Format.fprintf fmt "@[%s =@ " "upper_bounds"; TySet.pp fmt tpi.upper_bounds; Format.fprintf fmt "@]"; Format.fprintf fmt ";@ "; Format.fprintf fmt "@[%s =@ " "reified"; Aast.pp_reify_kind fmt tpi.reified; Format.fprintf fmt "@]"; Format.fprintf fmt ";@ "; Format.fprintf fmt "@[%s =@ " "enforceable"; Format.pp_print_bool fmt tpi.enforceable; Format.fprintf fmt "@]"; Format.fprintf fmt ";@ "; Format.fprintf fmt "@[%s =@ " "newable"; Format.pp_print_bool fmt tpi.newable; Format.fprintf fmt "@]"; Format.fprintf fmt "(@[parameters: (@,"; ignore (List.fold_left ~f:(fun sep (name, x) -> if sep then Format.fprintf fmt ";@ "; let () = Typing_defs.pp_pos_id fmt name in Format.fprintf fmt ":@ "; pp_tparam_info fmt x; true) ~init:false tpi.parameters); Format.fprintf fmt "@,]@]"; Format.fprintf fmt "@,))@]"; Format.fprintf fmt " }@]" let pp_tpenv fmt tpenv = Format.fprintf fmt "@[<hv 2>{ "; Format.fprintf fmt "@[%s =@ " "tparams"; (* FiXME: also print position? *) SMap.pp (fun fmt (_, tpi) -> pp_tparam_info fmt tpi) fmt tpenv.tparams; Format.fprintf fmt "@[%s =@ " "consistent"; Format.pp_print_bool fmt tpenv.consistent; Format.fprintf fmt " }@]" let pp = pp_tpenv
OCaml Interface
hhvm/hphp/hack/src/typing/type_parameter_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. * *) type tparam_name = string type tparam_bounds = Typing_set.t type tparam_info = Typing_kinding_defs.kind type t val empty : t val mem : tparam_name -> t -> bool val get : tparam_name -> t -> tparam_info option val get_with_pos : tparam_name -> t -> (Pos_or_decl.t * tparam_info) option val add : def_pos:Pos_or_decl.t -> tparam_name -> tparam_info -> t -> t val union : t -> t -> t val size : t -> int val fold : (tparam_name -> tparam_info -> 'a -> 'a) -> t -> 'a -> 'a val merge_env : 'env -> t -> t -> combine: ('env -> tparam_name -> (Pos_or_decl.t * tparam_info) option -> (Pos_or_decl.t * tparam_info) option -> 'env * (Pos_or_decl.t * tparam_info) option) -> 'env * t val get_lower_bounds : t -> tparam_name -> Typing_defs.locl_ty list -> tparam_bounds val get_upper_bounds : t -> tparam_name -> Typing_defs.locl_ty list -> tparam_bounds (** value > 0, indicates higher-kinded type parameter *) val get_arity : t -> tparam_name -> int val get_reified : t -> tparam_name -> Aast.reify_kind val get_enforceable : t -> tparam_name -> bool val get_newable : t -> tparam_name -> bool val get_require_dynamic : t -> tparam_name -> bool val get_tparam_names : t -> tparam_name list val get_tparams : t -> (Pos_or_decl.t * tparam_info) SMap.t val is_consistent : t -> bool (** When we detect that the set of constraints on the type parameters cannot be satisfied, we can mark the env as inconsistent using this. *) val mark_inconsistent : t -> t (** Add a single new upper bound to a generic parameter. 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) *) val add_upper_bound : ?intersect: (Typing_defs.locl_ty -> Typing_defs.locl_ty list -> Typing_defs.locl_ty list) -> t -> tparam_name -> Typing_defs.locl_ty -> t (** Add a single new upper lower to a generic parameter. 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 *) val add_lower_bound : ?union: (Typing_defs.locl_ty -> Typing_defs.locl_ty list -> Typing_defs.locl_ty list) -> t -> tparam_name -> Typing_defs.locl_ty -> t (** Add type parameters to environment, initially with no bounds. Existing type parameters with the same name will be overridden. *) val add_generic_parameters : t -> Typing_defs.decl_tparam list -> t val remove : t -> tparam_name -> t val get_parameter_names : tparam_info -> tparam_name list val pp : Format.formatter -> t -> unit
OCaml
hhvm/hphp/hack/src/typing/type_parameter_env_ops.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module TPEnv = Type_parameter_env module KDefs = Typing_kinding_defs module TySet = Typing_set module Env = Typing_env open Hh_prelude open Common open Typing_defs let intersect_upper_bounds env r ul = Typing_intersection.intersect_list env r (TySet.elements ul) let union_lower_bounds env r ll = Typing_union.union_list env r (TySet.elements ll) let join_lower_bounds env l1 l2 = (* Special case: subset inclusion. Return subset * (e.g. if t|u <: T or t <: T then t <: T ) *) if TySet.subset l1 l2 then (env, l1) else if TySet.subset l2 l1 then (env, l2) else (* Convert upper bounds to equivalent union *) let (env, union1) = union_lower_bounds env Reason.Rnone l1 in let (env, union2) = union_lower_bounds env Reason.Rnone l2 in let (env, new_lower) = Typing_intersection.intersect env ~r:Reason.Rnone union1 union2 in (env, TySet.singleton new_lower) let join_upper_bounds env u1 u2 = (* Special case: subset inclusion. Return subset * (e.g. if T <: t & u, or T <: t, then T <: t) *) if TySet.subset u1 u2 then (env, u1) else if TySet.subset u2 u1 then (env, u2) else (* Convert upper bounds to equivalent intersection *) let (env, inter1) = intersect_upper_bounds env Reason.Rnone u1 in let (env, inter2) = intersect_upper_bounds env Reason.Rnone u2 in let (env, new_upper) = Typing_union.union env inter1 inter2 in (env, TySet.singleton new_upper) (* Merge two type parameter environments. Given tpenv1 and tpenv2 we want * to compute a "merged" environment tpenv such that * tpenv1 |- tpenv * and tpenv2 |- tpenv * * If a type parameter is defined only on one input, we do not include it in tpenv. * If it appears in both, supposing we have * l1 <: T <: u1 in tpenv1 * and l2 <: T <: u2 in tpenv2 * with multiple lower bounds reduced to a union, and multiple upper bounds * reduced to an intersection, then the resulting tpenv will have * l1&l2 <: T <: u1|u2 *) let join env tpenv1 tpenv2 = let merge_pos p1 p2 = if Pos_or_decl.equal p1 Pos_or_decl.none then p2 else p1 in TPEnv.merge_env env tpenv1 tpenv2 ~combine:(fun env _tparam info1 info2 -> match (info1, info2) with | ( Some (pos1, (KDefs.{ lower_bounds = l1; upper_bounds = u1; _ } as info1)), Some (pos2, KDefs.{ lower_bounds = l2; upper_bounds = u2; _ }) ) -> let (env, lower_bounds) = join_lower_bounds env l1 l2 in let (env, upper_bounds) = join_upper_bounds env u1 u2 in let pos = merge_pos pos1 pos2 in (env, Some (pos, KDefs.{ info1 with lower_bounds; upper_bounds })) | (Some (pos, info), _) -> (env, Some (pos, info)) | (_, Some (pos, info)) -> (env, Some (pos, info)) | (_, _) -> (env, None)) let get_tpenv_equal_bounds env name tyargs = let lower = TPEnv.get_lower_bounds env name tyargs in let upper = TPEnv.get_upper_bounds env name tyargs in TySet.inter lower upper (** Given a list of type parameter names, attempt to simplify away those type parameters by looking for a type to which they are equal in the tpenv. If such a type exists, remove the type parameter from the tpenv. Returns a set of substitutions mapping each type parameter name to the type to which it is equal if found, otherwise to itself. *) let simplify_tpenv env (tparams : ((_ * string) option * locl_ty) list) r = (* TODO(T70068435) TODO(T70087549) This currently assumes that [tparams] only contains non-HK type paramters. (as seen in the Tgenerics created within and their arguments ignored) Once Type_parameter_env know about kinds, we can at least check here that this precondition is satisfied. *) let old_env = env in let tpenv = Env.get_tpenv env in (* For each tparam, "solve" it if it falls in any of those categories: * - there exists a type ty to which it is equal * - it is covariant and has upper bound ty (or mixed if absent) * - it is contravariant and lower bound ty (or nothing if absent). * In which case remove tparam from tpenv and add substitution * (tparam -> ty) to substs. *) let (env, tpenv, substs) = List.fold tparams ~init:(env, tpenv, SMap.empty) ~f:(fun (env, tpenv, substs) (p_opt, ty) -> let reason = get_reason ty in match p_opt with | None -> (env, tpenv, substs) | Some (tp, tparam_name) -> let equal_bounds = get_tpenv_equal_bounds tpenv tparam_name [] in let lower_bounds = TPEnv.get_lower_bounds tpenv tparam_name [] in let upper_bounds = TPEnv.get_upper_bounds tpenv tparam_name [] in let (env, lower_bound) = union_lower_bounds env reason lower_bounds in let (env, upper_bound) = intersect_upper_bounds env reason upper_bounds in (* remove tparam_name from tpenv, and in any lower/upper bound set * where it occurs. * We don't need to do any merging of lower/upper bounds, * because all its lower/upper bounds * are already lower/upper bounds of `bound` (and other bounds) * thanks to the transitive closure we've done in * Typing_subtype.add_constraint. *) let (tpenv, substs) = match (tp.tp_variance, TySet.choose_opt equal_bounds) with | (_, Some bound) -> let tpenv = TPEnv.remove tpenv tparam_name in let substs = SMap.add tparam_name bound substs in (tpenv, substs) | (Ast_defs.Covariant, _) -> let tpenv = TPEnv.remove tpenv tparam_name in let substs = SMap.add tparam_name upper_bound substs in (tpenv, substs) | (Ast_defs.Contravariant, _) -> let tpenv = TPEnv.remove tpenv tparam_name in let substs = SMap.add tparam_name lower_bound substs in (tpenv, substs) | _ -> (* TODO see comment at beginning of function *) let tparam_ty = mk (r, Tgeneric (tparam_name, [])) in let substs = SMap.add tparam_name tparam_ty substs in (tpenv, substs) in (env, tpenv, substs)) in let env = Env.env_with_tpenv env tpenv in (* reduce the set of substitutions. For example, for a set of substitutions * like * Ta -> Tb * Tb -> int * simplify to: * Ta -> int * Tb -> int *) let rec reduce substs tparam = match SMap.find_opt tparam substs with | None -> (substs, None) | Some subst -> (match get_node subst with | Tgeneric (tparam', []) when String.( <> ) tparam' tparam -> (* TODO see comment at beginning of function *) let (substs, new_subst_opt) = reduce substs tparam' in begin match new_subst_opt with | None -> (substs, Some subst) | Some new_subst -> let substs = SMap.add tparam new_subst substs in (substs, Some new_subst) end | _ -> (substs, Some subst)) in let reduce substs (p_opt, _) = match p_opt with | None -> substs | Some (_, name) -> fst (reduce substs name) in let substs = List.fold tparams ~init:substs ~f:reduce in let env = Env.log_env_change "simplify_tpenv" old_env env in (env, substs)
OCaml Interface
hhvm/hphp/hack/src/typing/type_parameter_env_ops.mli
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module Env = Typing_env open Typing_defs open Typing_env_types (** Given a list of type parameter names, attempt to simplify away those type parameters by looking for a type to which they are equal in the tpenv. If such a type exists, remove the type parameter from the tpenv. Returns a set of substitutions mapping each type parameter name to the type to which it is equal if found, otherwise to itself. *) val simplify_tpenv : env -> (('a tparam * string) option * locl_ty) list -> Typing_reason.t -> env * locl_ty SMap.t (** Merge two type parameter environments. Given tpenv1 and tpenv2 we want to compute a "merged" environment tpenv such that tpenv1 |- tpenv and tpenv2 |- tpenv If a type parameter is defined only on one input, we do not include it in tpenv. If it appears in both, supposing we have l1 <: T <: u1 in tpenv1 and l2 <: T <: u2 in tpenv2 with multiple lower bounds reduced to a union, and multiple upper bounds reduced to an intersection, then the resulting tpenv will have l1&l2 <: T <: u1|u2 *) val join : env -> Type_parameter_env.t -> Type_parameter_env.t -> env * Type_parameter_env.t
OCaml
hhvm/hphp/hack/src/typing/type_validator.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Typing_defs module Env = Typing_env module MakeType = Typing_make_type module Reason = Typing_reason type validity = | Valid | Invalid : (Reason.decl_t * string) list -> validity (* In hint positions, reified types are not resolved *) type reification = | Resolved | Unresolved type validation_state = { env: Typing_env_types.env; ety_env: expand_env; validity: validity; inside_reified_class_generic_position: bool; reification: reification; expanded_typedefs: SSet.t; } type error_emitter = Pos.t -> (Pos_or_decl.t * string) list Lazy.t -> unit class virtual type_validator = object (this) inherit [validation_state] Type_visitor.decl_type_visitor method on_enum acc _ _ = acc method on_class acc _ _ tyl = List.fold_left tyl ~f:this#on_type ~init:acc method on_newtype acc _ _ tyl as_cstr super_cstr ty = List.fold_left (ty :: as_cstr :: super_cstr :: tyl) ~f:this#on_type ~init:acc method on_alias acc _ _ tyl ty = List.fold_left (ty :: tyl) ~f:this#on_type ~init:acc method on_typeconst acc _class typeconst = match typeconst.ttc_kind with | TCConcrete { tc_type } -> this#on_type acc tc_type | TCAbstract { atc_as_constraint; atc_super_constraint; atc_default } -> let acc = Option.fold ~f:this#on_type ~init:acc atc_as_constraint in let acc = Option.fold ~f:this#on_type ~init:acc atc_super_constraint in let acc = Option.fold ~f:this#on_type ~init:acc atc_default in acc method! on_taccess acc _r (root, id) = let ((env, ty_err_opt), root) = Typing_phase.localize acc.env ~ety_env:acc.ety_env root in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let (env, tyl) = Typing_utils.get_concrete_supertypes ~abstract_enum:true env root in 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_ -> let (id_pos, id_name) = id in Decl_provider.Class.get_typeconst class_ id_name >>= fun typeconst -> let (ety_env, has_cycle) = Typing_defs.add_type_expansion_check_cycles { acc.ety_env with this_ty = ty } (id_pos, class_name ^ "::" ^ id_name) in match has_cycle with | Some _ -> (* This type is cyclic, give up checking it. We've already reported an error. *) None | None -> Some (this#on_typeconst { acc with ety_env } class_ typeconst) ) | _ -> acc) method! on_tapply acc r (pos, name) tyl = if Env.is_enum acc.env name && List.is_empty tyl then this#on_enum acc r (pos, name) else match Env.get_class_or_typedef acc.env name with | Some (Env.TypedefResult td) -> let { td_pos = _; td_vis = _; td_module = _; td_tparams; td_type; td_as_constraint; td_super_constraint; td_is_ctx = _; td_attributes = _; td_internal = _; td_docs_url = _; } = td in if SSet.mem name acc.expanded_typedefs then acc else let acc = { acc with expanded_typedefs = SSet.add name acc.expanded_typedefs; } in let subst = Decl_instantiate.make_subst td_tparams tyl in let td_type = Decl_instantiate.instantiate subst td_type in if Env.is_typedef_visible acc.env ~name td then this#on_alias acc r (pos, name) tyl td_type else let td_as_constraint = match td_as_constraint with | None -> mk (r, Tmixed) | Some ty -> Decl_instantiate.instantiate subst ty in let td_super_constraint = match td_super_constraint with | None -> MakeType.nothing r | Some ty -> Decl_instantiate.instantiate subst ty in this#on_newtype acc r (pos, name) tyl td_as_constraint td_super_constraint td_type | _ -> this#on_class acc r (pos, name) tyl (* Use_pos is the primary error position *) method validate_type env use_pos root_ty ?(reification = Unresolved) emit_error = let state = this#on_type { env; ety_env = { Typing_defs.empty_expand_env with this_ty = Option.value (Env.get_self_ty env) ~default:(MakeType.nothing Reason.none); }; expanded_typedefs = SSet.empty; validity = Valid; inside_reified_class_generic_position = false; reification; } root_ty in match state.validity with | Invalid reasons -> emit_error use_pos @@ lazy (List.map reasons ~f:(fun (r, msg) -> (Reason.to_pos r, msg))) | Valid -> () method validate_hint (env : Typing_env_types.env) (hint : Aast.hint) ?(reification : reification = Unresolved) (emit_error : error_emitter) : unit = let hint_ty = Decl_hint.hint env.Typing_env_types.decl_env hint in this#validate_type env (fst hint) hint_ty ~reification emit_error (* Takes in and accumulates a list of reasons *) method invalid_list state reasons = match state.validity with | Valid -> { state with validity = Invalid reasons } | Invalid prev_reasons -> { state with validity = Invalid (prev_reasons @ reasons) } method invalid state r msg = match state.validity with | Valid -> { state with validity = Invalid [(r, msg)] } | Invalid _ -> state end
OCaml Interface
hhvm/hphp/hack/src/typing/type_validator.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 validity type reification = | Resolved | Unresolved type validation_state = { env: Typing_env_types.env; ety_env: Typing_defs.expand_env; validity: validity; inside_reified_class_generic_position: bool; reification: reification; expanded_typedefs: SSet.t; } type error_emitter = Pos.t -> (Pos_or_decl.t * string) list Lazy.t -> unit class virtual type_validator : object inherit [validation_state] Type_visitor.decl_type_visitor_type method invalid : validation_state -> Typing_reason.decl_t -> string -> validation_state method invalid_list : validation_state -> (Typing_reason.decl_t * string) list -> validation_state method on_alias : validation_state -> Typing_reason.decl_t -> Pos_or_decl.t * string -> Typing_defs.decl_ty list -> Typing_defs.decl_ty -> validation_state method on_class : validation_state -> Typing_reason.decl_t -> Pos_or_decl.t * string -> Typing_defs.decl_ty list -> validation_state method on_enum : validation_state -> Typing_reason.decl_t -> Pos_or_decl.t * string -> validation_state method on_newtype : validation_state -> Typing_reason.decl_t -> Pos_or_decl.t * string -> Typing_defs.decl_ty list -> Typing_defs.decl_ty -> Typing_defs.decl_ty -> Typing_defs.decl_ty -> validation_state method on_taccess : validation_state -> Typing_reason.decl_t -> Typing_defs.decl_phase Typing_defs.taccess_type -> validation_state method on_typeconst : validation_state -> Decl_provider.Class.t -> Typing_defs.typeconst_type -> validation_state method validate_hint : Typing_env_types.env -> Aast.hint -> ?reification:reification -> error_emitter -> unit method validate_type : Typing_env_types.env -> Pos.t -> Typing_defs.decl_ty -> ?reification:reification -> error_emitter -> unit end
OCaml
hhvm/hphp/hack/src/typing/type_visitor.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Typing_defs module Reason = Typing_reason class type ['a] decl_type_visitor_type = object method on_tany : 'a -> decl_phase Reason.t_ -> 'a method on_tmixed : 'a -> decl_phase Reason.t_ -> 'a method on_twildcard : 'a -> decl_phase Reason.t_ -> 'a method on_tnonnull : 'a -> decl_phase Reason.t_ -> 'a method on_tdynamic : 'a -> decl_phase Reason.t_ -> 'a method on_tthis : 'a -> decl_phase Reason.t_ -> 'a method on_tvec_or_dict : 'a -> decl_phase Reason.t_ -> decl_ty -> decl_ty -> 'a method on_tgeneric : 'a -> decl_phase Reason.t_ -> string -> decl_ty list -> 'a method on_toption : 'a -> decl_phase Reason.t_ -> decl_ty -> 'a method on_tlike : 'a -> decl_phase Reason.t_ -> decl_ty -> 'a method on_tprim : 'a -> decl_phase Reason.t_ -> Aast.tprim -> 'a method on_tvar : 'a -> decl_phase Reason.t_ -> Ident.t -> 'a method on_type : 'a -> decl_ty -> 'a method on_tfun : 'a -> decl_phase Reason.t_ -> decl_fun_type -> 'a method on_tapply : 'a -> decl_phase Reason.t_ -> pos_id -> decl_ty list -> 'a method on_ttuple : 'a -> decl_phase Reason.t_ -> decl_ty list -> 'a method on_tunion : 'a -> decl_phase Reason.t_ -> decl_ty list -> 'a method on_tintersection : 'a -> decl_phase Reason.t_ -> decl_ty list -> 'a method on_tshape : 'a -> decl_phase Reason.t_ -> decl_phase shape_type -> 'a method on_taccess : 'a -> decl_phase Reason.t_ -> decl_phase taccess_type -> 'a method on_trefinement : 'a -> decl_phase Reason.t_ -> decl_ty -> decl_class_refinement -> 'a method on_tnewtype : 'a -> decl_phase Reason.t_ -> string -> decl_ty list -> decl_ty -> 'a end class virtual ['a] decl_type_visitor : ['a] decl_type_visitor_type = object (this) method on_tany acc _ = acc method on_tmixed acc _ = acc method on_twildcard acc _ = acc method on_tnonnull acc _ = acc method on_tdynamic acc _ = acc method on_tthis acc _ = acc method on_tvec_or_dict acc _ ty1 ty2 = let acc = this#on_type acc ty1 in this#on_type acc ty2 method on_tgeneric acc _ _ tyl = List.fold_left tyl ~f:this#on_type ~init:acc method on_toption acc _ ty = this#on_type acc ty method on_tlike acc _ ty = this#on_type acc ty method on_tprim acc _ _ = acc method on_tvar acc _ _ = acc method on_tfun acc _ { ft_params; ft_tparams; ft_ret; _ } = let acc = List.fold_left ~f:this#on_type ~init:acc (List.map ft_params ~f:(fun x -> x.fp_type.et_type)) in let tparams = List.map ft_tparams ~f:(fun t -> List.map t.tp_constraints ~f:snd) in let acc = List.fold_left tparams ~f:(fun acc tp -> List.fold ~f:this#on_type ~init:acc tp) ~init:acc in this#on_type acc ft_ret.et_type method on_tapply acc _ _ tyl = List.fold_left tyl ~f:this#on_type ~init:acc method on_trefinement acc _ ty rs = let acc = this#on_type acc ty in Class_refinement.fold rs ~init:acc ~f:this#on_type method on_taccess acc _ (root, _ids) = this#on_type acc root method on_ttuple acc _ tyl = List.fold_left tyl ~f:this#on_type ~init:acc method on_tunion acc _ tyl = List.fold_left tyl ~f:this#on_type ~init:acc method on_tintersection acc _ tyl = List.fold_left tyl ~f:this#on_type ~init:acc method on_tshape acc _ { s_origin = _; s_unknown_value = kind; s_fields = fdm } = let acc = this#on_type acc kind in let f _ { sft_ty; _ } acc = this#on_type acc sft_ty in TShapeMap.fold f fdm acc method on_tnewtype acc _ _ tyl ty = let acc = List.fold_left tyl ~f:this#on_type ~init:acc in let acc = this#on_type acc ty in acc method on_type acc ty = let (r, x) = deref ty in match x with | Tany _ -> this#on_tany acc r | Tmixed -> this#on_tmixed acc r | Twildcard -> this#on_twildcard acc r | Tnonnull -> this#on_tnonnull acc r | Tdynamic -> this#on_tdynamic acc r | Tthis -> this#on_tthis acc r | Tvec_or_dict (ty1, ty2) -> this#on_tvec_or_dict acc r ty1 ty2 | Tgeneric (s, args) -> this#on_tgeneric acc r s args | Toption ty -> this#on_toption acc r ty | Tlike ty -> this#on_tlike acc r ty | Tprim prim -> this#on_tprim acc r prim | Tfun fty -> this#on_tfun acc r fty | Tapply (s, tyl) -> this#on_tapply acc r s tyl | Trefinement (ty, rs) -> this#on_trefinement acc r ty rs | Taccess aty -> this#on_taccess acc r aty | Ttuple tyl -> this#on_ttuple acc r tyl | Tunion tyl -> this#on_tunion acc r tyl | Tintersection tyl -> this#on_tintersection acc r tyl | Tshape s -> this#on_tshape acc r s | Tnewtype (name, tyl, ty) -> this#on_tnewtype acc r name tyl ty end class type ['a] locl_type_visitor_type = object method on_tany : 'a -> Reason.t -> 'a method on_tnonnull : 'a -> Reason.t -> 'a method on_tdynamic : 'a -> Reason.t -> 'a method on_toption : 'a -> Reason.t -> locl_ty -> 'a method on_tprim : 'a -> Reason.t -> Aast.tprim -> 'a method on_tvar : 'a -> Reason.t -> Ident.t -> 'a method on_type : 'a -> locl_ty -> 'a method on_tfun : 'a -> Reason.t -> locl_fun_type -> 'a method on_tgeneric : 'a -> Reason.t -> string -> locl_ty list -> 'a method on_tnewtype : 'a -> Reason.t -> string -> locl_ty list -> locl_ty -> 'a method on_tdependent : 'a -> Reason.t -> dependent_type -> locl_ty -> 'a method on_ttuple : 'a -> Reason.t -> locl_ty list -> 'a method on_tunion : 'a -> Reason.t -> locl_ty list -> 'a method on_tintersection : 'a -> Reason.t -> locl_ty list -> 'a method on_tunion : 'a -> Reason.t -> locl_ty list -> 'a method on_tintersection : 'a -> Reason.t -> locl_ty list -> 'a method on_tvec_or_dict : 'a -> Reason.t -> locl_ty -> locl_ty -> 'a method on_tshape : 'a -> Reason.t -> locl_phase shape_type -> 'a method on_tclass : 'a -> Reason.t -> pos_id -> exact -> locl_ty list -> 'a method on_class_refinement : 'a -> locl_class_refinement -> 'a method on_tlist : 'a -> Reason.t -> locl_ty list -> 'a method on_tunapplied_alias : 'a -> Reason.t -> string -> 'a method on_taccess : 'a -> Reason.t -> locl_phase taccess_type -> 'a method on_neg_type : 'a -> Reason.t -> neg_type -> 'a end class virtual ['a] locl_type_visitor : ['a] locl_type_visitor_type = object (this) method on_tany acc _ = acc method on_tnonnull acc _ = acc method on_tdynamic acc _ = acc method on_toption acc _ ty = this#on_type acc ty method on_tprim acc _ _ = acc method on_tvar acc _ _ = acc method on_tfun acc _ { ft_params; ft_tparams; ft_ret; _ } = let acc = List.fold_left ~f:this#on_type ~init:acc (List.map ft_params ~f:(fun x -> x.fp_type.et_type)) in let tparams = List.map ft_tparams ~f:(fun t -> List.map t.tp_constraints ~f:snd) in let acc = List.fold_left tparams ~f:(fun acc tp -> List.fold ~f:this#on_type ~init:acc tp) ~init:acc in this#on_type acc ft_ret.et_type method on_tgeneric acc _ _ tyl = List.fold_left tyl ~f:this#on_type ~init:acc method on_tnewtype acc _ _ tyl ty = let acc = List.fold_left tyl ~f:this#on_type ~init:acc in let acc = this#on_type acc ty in acc method on_tdependent acc _ _ ty = let acc = this#on_type acc ty in acc method on_ttuple acc _ tyl = List.fold_left tyl ~f:this#on_type ~init:acc method on_tunion acc _ tyl = List.fold_left tyl ~f:this#on_type ~init:acc method on_tintersection acc _ tyl = List.fold_left tyl ~f:this#on_type ~init:acc method on_tshape acc _ { s_origin = _; s_unknown_value = kind; s_fields = fdm } = let acc = this#on_type acc kind in let f _ { sft_ty; _ } acc = this#on_type acc sft_ty in TShapeMap.fold f fdm acc method on_tclass acc _ _ exact tyl = let acc = match exact with | Exact -> acc | Nonexact cr -> this#on_class_refinement acc cr in List.fold_left tyl ~f:this#on_type ~init:acc method on_class_refinement acc { cr_consts } = SMap.fold (fun _const_name { rc_bound; rc_is_ctx = _ } acc -> match rc_bound with | TRexact ty -> this#on_type acc ty | TRloose { tr_lower = l; tr_upper = u } -> let on_tlist acc = List.fold_left ~f:this#on_type ~init:acc in on_tlist (on_tlist acc u) l) cr_consts acc method on_tlist acc _ tyl = List.fold_left tyl ~f:this#on_type ~init:acc method on_tvec_or_dict acc _ ty1 ty2 = let acc = this#on_type acc ty1 in this#on_type acc ty2 method on_neg_type acc r neg_ty = match neg_ty with | Neg_prim p -> this#on_tprim acc r p | Neg_class c -> this#on_tclass acc r c nonexact [] method on_tunapplied_alias acc _ _ = acc method on_taccess acc _ (ty, _ids) = this#on_type acc ty method on_type acc ty = let (r, x) = deref ty in match x with | Tany _ -> this#on_tany acc r | Tnonnull -> this#on_tnonnull acc r | Tdynamic -> this#on_tdynamic acc r | Toption ty -> this#on_toption acc r ty | Tprim prim -> this#on_tprim acc r prim | Tvar id -> this#on_tvar acc r id | Tfun fty -> this#on_tfun acc r fty | Tgeneric (x, args) -> this#on_tgeneric acc r x args | Tnewtype (x, tyl, ty) -> this#on_tnewtype acc r x tyl ty | Tdependent (x, ty) -> this#on_tdependent acc r x ty | Ttuple tyl -> this#on_ttuple acc r tyl | Tunion tyl -> this#on_tunion acc r tyl | Tintersection tyl -> this#on_tintersection acc r tyl | Tshape s -> this#on_tshape acc r s | Tclass (cls, exact, tyl) -> this#on_tclass acc r cls exact tyl | Tvec_or_dict (ty1, ty2) -> this#on_tvec_or_dict acc r ty1 ty2 | Tunapplied_alias n -> this#on_tunapplied_alias acc r n | Taccess (ty, ids) -> this#on_taccess acc r (ty, ids) | Tneg tneg -> this#on_neg_type acc r tneg end class type ['a] internal_type_visitor_type = object inherit ['a] locl_type_visitor_type method on_internal_type : 'a -> internal_type -> 'a method on_constraint_type : 'a -> constraint_type -> 'a method on_locl_type : 'a -> locl_ty -> 'a method on_locl_type_list : 'a -> locl_ty list -> 'a method on_locl_type_option : 'a -> locl_ty option -> 'a method on_thas_member : 'a -> Reason.t -> has_member -> 'a method on_has_member : 'a -> Reason.t -> has_member -> 'a method on_thas_type_member : 'a -> Reason.t -> has_type_member -> 'a method on_has_type_member : 'a -> Reason.t -> has_type_member -> 'a method on_tcan_index : 'a -> Reason.t -> can_index -> 'a method on_tcan_traverse : 'a -> Reason.t -> can_traverse -> 'a method on_can_index : 'a -> Reason.t -> can_index -> 'a method on_can_traverse : 'a -> Reason.t -> can_traverse -> 'a method on_tdestructure : 'a -> Reason.t -> destructure -> 'a method on_destructure : 'a -> Reason.t -> destructure -> 'a method on_tcunion : 'a -> Reason.t -> locl_ty -> constraint_type -> 'a method on_tcintersection : 'a -> Reason.t -> locl_ty -> constraint_type -> 'a end class ['a] internal_type_visitor : ['a] internal_type_visitor_type = object (this) method on_internal_type acc ty = match ty with | LoclType ty -> this#on_locl_type acc ty | ConstraintType ty -> this#on_constraint_type acc ty method on_constraint_type acc ty = let (r, ty) = deref_constraint_type ty in match ty with | Thas_member hm -> this#on_thas_member acc r hm | Thas_type_member htm -> this#on_thas_type_member acc r htm | Tcan_index ci -> this#on_tcan_index acc r ci | Tcan_traverse ct -> this#on_tcan_traverse acc r ct | Tdestructure des -> this#on_tdestructure acc r des | TCunion (lty, cty) -> this#on_tcunion acc r lty cty | TCintersection (lty, cty) -> this#on_tcintersection acc r lty cty method on_locl_type acc ty = this#on_type acc ty method on_locl_type_list acc tyl = List.fold tyl ~init:acc ~f:this#on_locl_type method on_locl_type_option acc ty = Option.fold ty ~init:acc ~f:this#on_locl_type method on_thas_member acc r hm = this#on_has_member acc r hm method on_has_member acc _r hm = let { hm_name = _; hm_type; hm_class_id = _; hm_explicit_targs = _ } = hm in this#on_locl_type acc hm_type method on_thas_type_member acc r htm = this#on_has_type_member acc r htm method on_has_type_member acc _r htm = let { htm_id = _; htm_lower; htm_upper } = htm in let acc = this#on_locl_type acc htm_lower in let acc = this#on_locl_type acc htm_upper in acc method on_tcan_index acc r hm = this#on_can_index acc r hm method on_tcan_traverse acc r hm = this#on_can_traverse acc r hm method on_can_index acc _r ci = let acc = this#on_locl_type acc ci.ci_key in this#on_locl_type acc ci.ci_val method on_can_traverse acc _r ct = let acc = this#on_locl_type_option acc ct.ct_key in let acc = this#on_locl_type acc ct.ct_val in acc method on_tdestructure acc r des = this#on_destructure acc r des method on_destructure acc _r des = let { d_required; d_optional; d_variadic; d_kind = _ } = des in let acc = this#on_locl_type_list acc d_required in let acc = this#on_locl_type_list acc d_optional in let acc = this#on_locl_type_option acc d_variadic in acc method on_tcunion acc _r lty cty = let acc = this#on_locl_type acc lty in let acc = this#on_constraint_type acc cty in acc method on_tcintersection acc _r lty cty = let acc = this#on_locl_type acc lty in let acc = this#on_constraint_type acc cty in acc inherit ['a] locl_type_visitor end
OCaml Interface
hhvm/hphp/hack/src/typing/type_visitor.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. * *) class type ['a] decl_type_visitor_type = object method on_tany : 'a -> Typing_reason.decl_t -> 'a method on_tmixed : 'a -> Typing_reason.decl_t -> 'a method on_twildcard : 'a -> Typing_reason.decl_t -> 'a method on_tnonnull : 'a -> Typing_reason.decl_t -> 'a method on_tdynamic : 'a -> Typing_reason.decl_t -> 'a method on_tthis : 'a -> Typing_reason.decl_t -> 'a method on_tvec_or_dict : 'a -> Typing_reason.decl_t -> Typing_defs.decl_ty -> Typing_defs.decl_ty -> 'a method on_tgeneric : 'a -> Typing_reason.decl_t -> string -> Typing_defs.decl_ty list -> 'a method on_toption : 'a -> Typing_reason.decl_t -> Typing_defs.decl_ty -> 'a method on_tlike : 'a -> Typing_reason.decl_t -> Typing_defs.decl_ty -> 'a method on_tprim : 'a -> Typing_reason.decl_t -> Aast.tprim -> 'a method on_tvar : 'a -> Typing_reason.decl_t -> Ident.t -> 'a method on_type : 'a -> Typing_defs.decl_ty -> 'a method on_tfun : 'a -> Typing_reason.decl_t -> Typing_defs.decl_fun_type -> 'a method on_tapply : 'a -> Typing_reason.decl_t -> Typing_defs.pos_id -> Typing_defs.decl_ty list -> 'a method on_ttuple : 'a -> Typing_reason.decl_t -> Typing_defs.decl_ty list -> 'a method on_tunion : 'a -> Typing_reason.decl_t -> Typing_defs.decl_ty list -> 'a method on_tintersection : 'a -> Typing_reason.decl_t -> Typing_defs.decl_ty list -> 'a method on_tshape : 'a -> Typing_reason.decl_t -> Typing_defs.decl_phase Typing_defs.shape_type -> 'a method on_taccess : 'a -> Typing_reason.decl_t -> Typing_defs.decl_phase Typing_defs.taccess_type -> 'a method on_trefinement : 'a -> Typing_reason.decl_t -> Typing_defs.decl_ty -> Typing_defs.decl_class_refinement -> 'a method on_tnewtype : 'a -> Typing_reason.decl_t -> string -> Typing_defs.decl_ty list -> Typing_defs.decl_ty -> 'a end class virtual ['a] decl_type_visitor : ['a] decl_type_visitor_type class type ['a] locl_type_visitor_type = object method on_tany : 'a -> Typing_reason.t -> 'a method on_tnonnull : 'a -> Typing_reason.t -> 'a method on_tdynamic : 'a -> Typing_reason.t -> 'a method on_toption : 'a -> Typing_reason.t -> Typing_defs.locl_ty -> 'a method on_tprim : 'a -> Typing_reason.t -> Aast.tprim -> 'a method on_tvar : 'a -> Typing_reason.t -> Ident.t -> 'a method on_type : 'a -> Typing_defs.locl_ty -> 'a method on_tfun : 'a -> Typing_reason.t -> Typing_defs.locl_fun_type -> 'a method on_tgeneric : 'a -> Typing_reason.t -> string -> Typing_defs.locl_ty list -> 'a method on_tnewtype : 'a -> Typing_reason.t -> string -> Typing_defs.locl_ty list -> Typing_defs.locl_ty -> 'a method on_tdependent : 'a -> Typing_reason.t -> Typing_defs.dependent_type -> Typing_defs.locl_ty -> 'a method on_ttuple : 'a -> Typing_reason.t -> Typing_defs.locl_ty list -> 'a method on_tunion : 'a -> Typing_reason.t -> Typing_defs.locl_ty list -> 'a method on_tintersection : 'a -> Typing_reason.t -> Typing_defs.locl_ty list -> 'a method on_tunion : 'a -> Typing_reason.t -> Typing_defs.locl_ty list -> 'a method on_tintersection : 'a -> Typing_reason.t -> Typing_defs.locl_ty list -> 'a method on_tvec_or_dict : 'a -> Typing_reason.t -> Typing_defs.locl_ty -> Typing_defs.locl_ty -> 'a method on_tshape : 'a -> Typing_reason.t -> Typing_defs.locl_phase Typing_defs.shape_type -> 'a method on_tclass : 'a -> Typing_reason.t -> Typing_defs.pos_id -> Typing_defs.exact -> Typing_defs.locl_ty list -> 'a method on_class_refinement : 'a -> Typing_defs.locl_class_refinement -> 'a method on_tlist : 'a -> Typing_reason.t -> Typing_defs.locl_ty list -> 'a method on_tunapplied_alias : 'a -> Typing_reason.t -> string -> 'a method on_taccess : 'a -> Typing_reason.t -> Typing_defs.locl_phase Typing_defs.taccess_type -> 'a method on_neg_type : 'a -> Typing_reason.t -> Typing_defs.neg_type -> 'a end class virtual ['a] locl_type_visitor : ['a] locl_type_visitor_type class type ['a] internal_type_visitor_type = object inherit ['a] locl_type_visitor_type method on_internal_type : 'a -> Typing_defs.internal_type -> 'a method on_constraint_type : 'a -> Typing_defs.constraint_type -> 'a method on_locl_type : 'a -> Typing_defs.locl_ty -> 'a method on_locl_type_list : 'a -> Typing_defs.locl_ty list -> 'a method on_locl_type_option : 'a -> Typing_defs.locl_ty option -> 'a method on_thas_member : 'a -> Typing_reason.t -> Typing_defs.has_member -> 'a method on_has_member : 'a -> Typing_reason.t -> Typing_defs.has_member -> 'a method on_thas_type_member : 'a -> Typing_reason.t -> Typing_defs.has_type_member -> 'a method on_has_type_member : 'a -> Typing_reason.t -> Typing_defs.has_type_member -> 'a method on_tcan_index : 'a -> Typing_reason.t -> Typing_defs.can_index -> 'a method on_tcan_traverse : 'a -> Typing_reason.t -> Typing_defs.can_traverse -> 'a method on_can_index : 'a -> Typing_reason.t -> Typing_defs.can_index -> 'a method on_can_traverse : 'a -> Typing_reason.t -> Typing_defs.can_traverse -> 'a method on_tdestructure : 'a -> Typing_reason.t -> Typing_defs.destructure -> 'a method on_destructure : 'a -> Typing_reason.t -> Typing_defs.destructure -> 'a method on_tcunion : 'a -> Typing_reason.t -> Typing_defs.locl_ty -> Typing_defs.constraint_type -> 'a method on_tcintersection : 'a -> Typing_reason.t -> Typing_defs.locl_ty -> Typing_defs.constraint_type -> 'a end class ['a] internal_type_visitor : ['a] internal_type_visitor_type
OCaml
hhvm/hphp/hack/src/typing/typing.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 Tast open Typing_defs open Typing_env_types open Utils open Typing_helpers module TFTerm = Typing_func_terminality module TUtils = Typing_utils module Reason = Typing_reason module Type = Typing_ops module Env = Typing_env module Inf = Typing_inference_env module LEnv = Typing_lenv module Async = Typing_async module SubType = Typing_subtype module Union = Typing_union module Inter = Typing_intersection module SN = Naming_special_names module TVis = Typing_visibility module Phase = Typing_phase module TOG = Typing_object_get module Subst = Decl_subst module ExprDepTy = Typing_dependent_type.ExprDepTy module TCO = TypecheckerOptions module C = Typing_continuations module CMap = C.Map module Try = Typing_try module FL = FeatureLogging module MakeType = Typing_make_type module Cls = Decl_provider.Class module Fake = Typing_fake_members module ExpectedTy = Typing_helpers.ExpectedTy module ITySet = Internal_type_set type newable_class_info = env * Tast.targ list * Tast.class_id * [ `Class of pos_id * Cls.t * locl_ty | `Dynamic ] list type dyn_func_kind = | Supportdyn_function | Like_function type branch_info = { lset: Local_id.Set.t; pkgs: SSet.t; } (*****************************************************************************) (* Debugging *) (*****************************************************************************) (* A guess as to the last position we were typechecking, for use in debugging, * such as figuring out what a runaway hh_server thread is doing. Updated * only best-effort -- it's an approximation to point debugging in the right * direction, nothing more. *) let debug_last_pos = ref Pos.none let debug_print_last_pos _ = Hh_logger.info "Last typecheck pos: %s" (Pos.string (Pos.to_absolute !debug_last_pos)) (*****************************************************************************) (* Helpers *) (*****************************************************************************) let log_iteration_count env pos n = let should_log_iteration_count = Env.get_tcopt env |> TCO.log_levels |> SMap.find_opt "loop_iteration_count" |> Option.is_some in if should_log_iteration_count then let msg = Format.asprintf "Loop iteration count %s:%a: %d\n" (Pos.to_absolute pos |> Pos.filename) Pos.pp pos n in Hh_logger.log "%s" msg let mk_ty_mismatch_opt ty_have ty_expect = function | Some _ -> Some (ty_have, ty_expect) | _ -> None let mk_ty_mismatch_res ty_have ty_expect = function | Some _ -> Error (ty_have, ty_expect) | _ -> Ok ty_have let mk_hole ?(source = Aast.Typing) ((_, pos, _) as expr) ~ty_have ~ty_expect = if equal_locl_ty ty_have ty_expect then expr else (* if the hole is generated from typing, we leave the type unchanged, if it is a call to `[unsafe|enforced]_cast`, we give it the expected type *) let ty_hole = match source with | Aast.Typing -> ty_have | UnsafeCast _ | UnsafeNonnullCast | EnforcedCast _ -> ty_expect in make_typed_expr pos ty_hole @@ Aast.Hole (expr, ty_have, ty_expect, source) let hole_on_ty_mismatch (te : Tast.expr) ~ty_mismatch_opt : Tast.expr = Option.value_map ty_mismatch_opt ~default:te ~f:(fun (ty_have, ty_expect) -> mk_hole te ~ty_have ~ty_expect) (* When typing compound assignments we generate a 'fake' expression which desugars it to the operation on the rhs of the assignment. If there was a subtyping error, we end up with the Hole on the fake rhs rather than the original rhs. This function rewrites the desugared expression with the Hole in the correct place *) let resugar_binop expr = match expr with | ( topt, p, Aast.( Binop { bop = _; lhs = te1; rhs = ( _, _, Hole ( (_, _, Binop { bop = op; lhs = _; rhs = te2 }), ty_have, ty_expect, source ) ); }) ) -> let hte2 = mk_hole te2 ~ty_have ~ty_expect ~source in let te = Aast.Binop { bop = Ast_defs.Eq (Some op); lhs = te1; rhs = hte2 } in Some (topt, p, te) | ( topt, p, Aast.Binop { bop = _; lhs = te1; rhs = (_, _, Aast.Binop { bop = op; lhs = _; rhs = te2 }); } ) -> let te = Aast.Binop { bop = Ast_defs.Eq (Some op); lhs = te1; rhs = te2 } in Some (topt, p, te) | _ -> None (* When recording subtyping or coercion errors for union and intersection types we need to look at the error for each element and then reconstruct any errors into a union or intersection. If there were no errors for any element, the result if also `Ok`; if there was an error for at least on element we have `Error` with list of actual and expected types *) let fold_coercion_errs errs = List.fold_left errs ~init:(Ok []) ~f:(fun acc err -> match (acc, err) with | (Ok xs, Ok x) -> Ok (x :: xs) | (Ok xs, Error (x, y)) -> Error (x :: xs, y :: xs) | (Error (xs, ys), Ok x) -> Error (x :: xs, x :: ys) | (Error (xs, ys), Error (x, y)) -> Error (x :: xs, y :: ys)) let union_coercion_errs errs = Result.fold ~ok:(fun tys -> Ok (MakeType.union Reason.Rnone tys)) ~error:(fun (acts, exps) -> Error (MakeType.union Reason.Rnone acts, MakeType.union Reason.Rnone exps)) @@ fold_coercion_errs errs let intersect_coercion_errs errs = Result.fold ~ok:(fun tys -> Ok (MakeType.intersection Reason.Rnone tys)) ~error:(fun (acts, exps) -> Error ( MakeType.intersection Reason.Rnone acts, MakeType.intersection Reason.Rnone exps )) @@ fold_coercion_errs errs (** Given the type of an argument that has been unpacked and typed against positional and variadic function parameter types, apply the subtyping / coercion errors back to the original packed type. *) let pack_errs pos ty subtyping_errs = let nothing = MakeType.nothing @@ Reason.Rsolve_fail (Pos_or_decl.of_raw_pos pos) in let rec aux ~k = function (* Case 1: we have a type error at this positional parameter so replace the type parameter which caused it with the expected type *) | ((Some (_, ty) :: rest, var_opt), _ :: tys) (* Case 2: there was no type error here so retain the original type parameter *) | ((None :: rest, var_opt), ty :: tys) -> (* recurse for any remaining positional parameters and add the corrected (case 1) or original (case 2) type to the front of the list of type parameters in the continuation *) aux ((rest, var_opt), tys) ~k:(fun tys -> k (ty :: tys)) (* Case 3: we have a type error at the variadic parameter so replace the type parameter which cased it with the expected type *) | ((_, (Some (_, ty) as var_opt)), _ :: tys) -> (* recurse with the variadic parameter error and add the corrected type to the front of the list of type parameters in the continuation *) aux (([], var_opt), tys) ~k:(fun tys -> k (ty :: tys)) (* Case 4: we have a variadic parameter but no error - we're done so pass the remaining unchanged type parameters into the contination to rebuild corrected type params in the right order *) | ((_, None), tys) -> k tys (* Case 5: no more type parameters - again we're done so pass empty list to continuation and rebuild corrected type params in the right order *) | (_, []) -> k [] in (* The only types that _can_ be upacked are tuples and pairs; match on the type to get the type parameters, pass them to our recursive function aux to subsitute the expected type where we have a type error then reconstruct the type in the continuation *) match deref ty with | (r, Ttuple tys) -> aux (subtyping_errs, tys) ~k:(fun tys -> mk (r, Ttuple tys)) | (r, Tclass (pos_id, exact, tys)) -> aux (subtyping_errs, tys) ~k:(fun tys -> mk (r, Tclass (pos_id, exact, tys))) | _ -> nothing let triple_to_pair (env, te, ty) = (env, (te, ty)) let with_special_coeffects env cap_ty unsafe_cap_ty f = let init = Option.map (Env.next_cont_opt env) ~f:(fun next_cont -> let initial_locals = next_cont.Typing_per_cont_env.local_types in let tpenv = Env.get_tpenv env in (initial_locals, tpenv)) in LEnv.stash_and_do env (Env.all_continuations env) (fun env -> let env = match init with | None -> env | Some (initial_locals, tpenv) -> let env = Env.reinitialize_locals env in let env = Env.set_locals env initial_locals in let env = Env.env_with_tpenv env tpenv in env in let (env, _ty) = Typing_coeffects.register_capabilities env cap_ty unsafe_cap_ty in f env) (* Set all the types in an expression to the given type. *) let with_type ty env (e : Nast.expr) : Tast.expr = let visitor = object (self) inherit [_] Aast.map method! on_expr env ((), p, expr_) = (ty, p, self#on_expr_ env expr_) method on_'ex _ () = ty method on_'en _ _ = env end in visitor#on_expr () e let expr_error env p (e : Nast.expr) = let (env, ty) = Env.fresh_type_error env p in (env, with_type ty Tast.dummy_saved_env e, ty) let unbound_name env (pos, name) e = if Tast.is_under_dynamic_assumptions env.checked then expr_error env pos e else let class_exists = let ctx = Env.get_ctx env in let decl = Decl_provider.get_class ctx name in match decl with | None -> false | Some dc -> Ast_defs.is_c_class (Cls.kind dc) in Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.Unbound_name { pos; name; class_exists }); expr_error env pos e (* Is this type Traversable<vty> or Container<vty> for some vty? *) let get_value_collection_inst env p vc_kind ty = let arraykey_on ty = match vc_kind with | Set | ImmSet | Keyset -> let reason = Reason.Rset_element p in let arraykey = MakeType.arraykey reason in let (env, ty) = Inter.intersect env ~r:reason arraykey ty in Some (env, ty) | Vector | ImmVector | Vec -> Some (env, ty) in match get_node ty with | Tclass ((_, c), _, [vty]) when String.equal c SN.Collections.cTraversable || String.equal c SN.Collections.cContainer -> arraykey_on vty (* If we're expecting a mixed or a nonnull then we can just assume * that the element type is mixed if it is a vec-like type and arraykey if it * is a set-like one. *) | Tnonnull -> arraykey_on (MakeType.mixed (get_reason ty)) | Tany _ -> Some (env, ty) | Tdynamic when Tast.is_under_dynamic_assumptions env.checked -> (* interpret dynamic as Traversable<dynamic> or keyset<arraykey> *) arraykey_on ty | _ -> None (* Is this type KeyedTraversable<kty,vty> * or KeyedContainer<kty,vty> * for some kty, vty? *) let get_key_value_collection_inst env p ty = match get_node ty with | Tclass ((_, c), _, [kty; vty]) when String.equal c SN.Collections.cKeyedTraversable || String.equal c SN.Collections.cKeyedContainer -> let reason = Reason.Rkey_value_collection_key p in let arraykey = MakeType.arraykey reason in let (env, kty) = Inter.intersect env ~r:reason kty arraykey in Some (env, kty, vty) (* If we're expecting a mixed or a nonnull then we can just assume * that the key type is arraykey and the value type is mixed *) | Tnonnull -> let arraykey = MakeType.arraykey (Reason.Rkey_value_collection_key p) in let mixed = MakeType.mixed (Reason.Rwitness p) in Some (env, arraykey, mixed) | Tany _ -> Some (env, ty, ty) | Tdynamic when Tast.is_under_dynamic_assumptions env.checked -> (* interpret dynamic as KeyedTraversable<arraykey, dynamic> *) let arraykey = MakeType.arraykey (Reason.Rkey_value_collection_key p) in Some (env, arraykey, ty) | _ -> None (* Is this type varray<vty> or a supertype for some vty? *) let vc_kind_to_supers kind = match kind with | Vector -> [SN.Collections.cVector; SN.Collections.cMutableVector] | ImmVector -> [SN.Collections.cImmVector; SN.Collections.cConstVector] | Vec -> [SN.Collections.cVec] | Set -> [SN.Collections.cSet; SN.Collections.cMutableSet] | ImmSet -> [SN.Collections.cImmSet; SN.Collections.cConstSet] | Keyset -> [SN.Collections.cKeyset] let kvc_kind_to_supers kind = match kind with | Map -> [SN.Collections.cMap; SN.Collections.cMutableMap] | ImmMap -> [SN.Collections.cImmMap; SN.Collections.cConstMap] | Dict -> [SN.Collections.cDict] (* Is this type one of the value collection types with element type vty? *) let get_vc_inst env p vc_kind ty = let classnames = vc_kind_to_supers vc_kind in match get_node ty with | Tclass ((_, c), _, [vty]) when List.exists classnames ~f:(String.equal c) -> Some (env, vty) | _ -> get_value_collection_inst env p vc_kind ty (* Is this type one of the three key-value collection types * e.g. dict<kty,vty> or a supertype for some kty and vty? *) let get_kvc_inst env p kvc_kind ty = let classnames = kvc_kind_to_supers kvc_kind in match get_node ty with | Tclass ((_, c), _, [kty; vty]) when List.exists classnames ~f:(String.equal c) -> Some (env, kty, vty) | _ -> get_key_value_collection_inst env p ty (* Check whether this is a function type that (a) either returns a disposable * or (b) has the <<__ReturnDisposable>> attribute *) let is_return_disposable_fun_type env ty = let (_env, ty) = Env.expand_type env ty in let ty = TUtils.strip_dynamic env ty in let (_, _env, ty) = TUtils.strip_supportdyn env ty in match get_node ty with | Tfun ft -> get_ft_return_disposable ft || Option.is_some (Typing_disposable.is_disposable_type env ft.ft_ret.et_type) | _ -> false (* Turn an environment into a local_id_map suitable to be embedded * into an AssertEnv statement *) let annot_map env = match Env.next_cont_opt env with | Some { Typing_per_cont_env.local_types; _ } -> Some (Local_id.Map.filter_map (fun _ Typing_local_types. { ty; defined; bound_ty = _; pos; eid = _expr_id } -> if defined then Some (pos, ty) else None) local_types) | None -> None (* Similar to annot_map above, but filters the map to only contain * information about locals in lset *) let refinement_annot_map env lset = match annot_map env with | Some map -> let map = Local_id.Map.filter (fun lid _ -> Local_id.Set.mem lid lset) map in if Local_id.Map.is_empty map then None else Some map | None -> None let assert_env_blk ~pos ~at annotation_kind env_map_opt blk = let mk_assert map = (pos, Aast.AssertEnv (annotation_kind, map)) in let annot_blk = Option.to_list (Option.map ~f:mk_assert env_map_opt) in match at with | `Start -> annot_blk @ blk | `End -> blk @ annot_blk let assert_env_stmt ~pos ~at annotation_kind env_map_opt stmt = let mk_assert map = (pos, Aast.AssertEnv (annotation_kind, map)) in match env_map_opt with | Some env_map -> let stmt = (pos, stmt) in let blk = match at with | `Start -> [mk_assert env_map; stmt] | `End -> [stmt; mk_assert env_map] in Aast.Block blk | None -> stmt let set_tcopt_unstable_features env { fa_user_attributes; _ } = match Naming_attributes.find SN.UserAttributes.uaEnableUnstableFeatures fa_user_attributes with | None -> env | Some { ua_name = _; ua_params } -> let ( = ) = String.equal in List.fold ua_params ~init:env ~f:(fun env (_, _, feature) -> match feature with | Aast.String s when s = SN.UnstableFeatures.ifc -> Env.map_tcopt ~f:TCO.enable_ifc env | Aast.String s when s = SN.UnstableFeatures.modules -> Env.map_tcopt ~f:(fun t -> TCO.set_modules t true) env | Aast.String s when s = SN.UnstableFeatures.expression_trees -> Env.map_tcopt ~f:(fun t -> TCO.set_tco_enable_expression_trees t true) env | _ -> env) (** Do a subtype check of inferred type against expected type. * The optional coerce_for_op parameter controls whether any arguments of type * dynamic can be coerced to enforceable types because they are arguments to a * built-in operator. *) let check_expected_ty_res ~(coerce_for_op : bool) (message : string) (env : env) (inferred_ty : locl_ty) (expected : ExpectedTy.t option) : (env, env) result = match expected with | None -> Ok env | Some ExpectedTy.{ pos = p; reason = ur; ty; coerce } -> Typing_log.( log_with_level env "typing" ~level:1 (fun () -> log_types (Pos_or_decl.of_raw_pos p) env [ Log_head ( Printf.sprintf "Typing.check_expected_ty %s enforced=%s" message (match ty.et_enforced with | Unenforced -> "unenforced" | Enforced -> "enforced"), [ Log_type ("inferred_ty", inferred_ty); Log_type ("expected_ty", ty.et_type); ] ); ])); let (env, ty_err_opt) = Typing_coercion.coerce_type ~coerce_for_op ~coerce p ur env inferred_ty ty Typing_error.Callback.unify_error in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); Option.value_map ~default:(Ok env) ~f:(fun _ -> Error env) ty_err_opt let check_expected_ty message env inferred_ty expected = Result.fold ~ok:Fn.id ~error:Fn.id @@ check_expected_ty_res ~coerce_for_op:false message env inferred_ty expected (* Set a local; must not be already assigned if it is a using variable *) let set_local ?(is_using_clause = false) ~is_defined ~bound_ty env (pos, x) ty = if Env.is_using_var env x then Typing_error_utils.add_typing_error ~env Typing_error.( primary (if is_using_clause then Primary.Duplicate_using_var pos else Primary.Illegal_disposable { pos; verb = `assigned })); let env = Env.set_local ~is_defined ~bound_ty env x ty pos in if is_using_clause then Env.set_using_var env x else env (* Require a new construct with disposable *) let rec enforce_return_disposable env e = match e with | (_, _, New _) -> () | (_, _, Call _) -> () | (_, _, Await (_, _, Call _)) -> () | (_, _, Hole (e, _, _, _)) -> enforce_return_disposable env e | (_, p, _) -> Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.Invalid_return_disposable p) (* Wrappers around the function with the same name in LEnv, which only * performs the move/save and merge operation if we are in a try block or in a * function with return type 'noreturn'. * This enables significant perf improvement, because this is called at every * function of method call, when most calls are outside of a try block. *) let move_and_merge_next_in_catch ~join_pos env = if env.in_try || TFTerm.is_noreturn env then LEnv.move_and_merge_next_in_cont env ~join_pos C.Catch else LEnv.drop_cont env C.Next let save_and_merge_next_in_catch ~join_pos env = if env.in_try || TFTerm.is_noreturn env then LEnv.save_and_merge_next_in_cont env ~join_pos C.Catch else env let might_throw env = save_and_merge_next_in_catch env let branch : type res. join_pos:Pos.t -> env -> (env -> env * res) -> (env -> env * res) -> env * res * res = fun ~join_pos env branch1 branch2 -> let parent_lenv = env.lenv in let (env, tbr1) = branch1 env in let lenv1 = env.lenv in let env = { env with lenv = parent_lenv } in let (env, tbr2) = branch2 env in let lenv2 = env.lenv in let env = LEnv.union_lenvs env ~join_pos parent_lenv lenv1 lenv2 in (env, tbr1, tbr2) let as_expr env ty1 pe e = let env = Env.open_tyvars env pe in let (env, tv) = if TUtils.is_tyvar_error env ty1 then Env.fresh_type_error env pe else Env.fresh_type env pe in let (env, ct) = match e with | As_v _ -> ( env, { ct_key = None; ct_val = tv; ct_is_await = false; ct_reason = Reason.Rforeach pe; } ) | As_kv _ -> let (env, tk) = Env.fresh_type env pe in ( env, { ct_key = Some tk; ct_val = tv; ct_is_await = false; ct_reason = Reason.Rforeach pe; } ) | Await_as_v _ -> ( env, { ct_key = None; ct_val = tv; ct_is_await = true; ct_reason = Reason.Rasyncforeach pe; } ) | Await_as_kv _ -> let (env, tk) = Env.fresh_type env pe in ( env, { ct_key = Some tk; ct_val = tv; ct_is_await = true; ct_reason = Reason.Rasyncforeach pe; } ) in let expected_ty = ConstraintType (mk_constraint_type (Reason.Rforeach pe, Tcan_traverse ct)) in let (ty_actual, is_option) = match get_node ty1 with | Toption ty_actual -> (ty_actual, true) | _ -> (ty1, false) in let (env, ty_err_opt1) = Type.sub_type_i pe Reason.URforeach env (LoclType ty_actual) expected_ty Typing_error.Callback.unify_error in (* Handle the case where we have a nullable type where the inner type does support `Tcan_traverse` *) let (ty_mismatch_opt, ty_err_opt2) = match ty_err_opt1 with | None when is_option -> let ty_str = lazy (Typing_print.full_strip_ns env ty1) in let ty_ct = SubType.can_traverse_to_iface ct in let ct_str = lazy (Typing_print.full_strip_ns env ty_ct) in let reasons_opt = Some Lazy.( ty_str >>= fun ty_str -> map ct_str ~f:(fun ct_str -> let msg = "Expected `" ^ ct_str ^ "` " in Reason.to_string msg ct.ct_reason @ [ ( Pos_or_decl.of_raw_pos pe, Format.sprintf "But got `?%s`" ty_str ); ])) in (* We actually failed so generate the error we should have seen *) let ty_err = Typing_error.( primary @@ Primary.Unify_error { pos = pe; msg_opt = None; reasons_opt }) in (Some (ty1, ty_actual), Some ty_err) | Some _ -> let ty_mismatch = match mk_ty_mismatch_res ty1 expected_ty ty_err_opt1 with | Ok _ -> None | Error (act, LoclType exp) -> Some (act, exp) | Error (act, ConstraintType _) -> Some (act, SubType.can_traverse_to_iface ct) in (ty_mismatch, None) | None -> (None, None) in let ty_err_opt = Option.merge ty_err_opt1 ty_err_opt2 ~f:Typing_error.both in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let env = Env.set_tyvar_variance_i env expected_ty in let tk = match ct.ct_key with | None -> MakeType.mixed Reason.Rnone | Some tk -> tk in (Typing_solver.close_tyvars_and_solve env, tk, tv, ty_mismatch_opt) (* These functions invoke special printing functions for Typing_env. They do not * appear in user code, but we still check top level function calls against their * names. *) let typing_env_pseudofunctions = SN.PseudoFunctions.( String.Hash_set.of_list ~growth_allowed:false [ hh_show; hh_expect; hh_expect_equivalent; hh_show_env; hh_log_level; hh_force_solve; hh_loop_forever; hh_time; ]) let do_hh_expect ~equivalent env use_pos explicit_targs p tys = match explicit_targs with | [targ] -> let ((env, ty_err_opt), (expected_ty, _)) = Phase.localize_targ ~check_well_kinded:true env (snd targ) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let right_expected_ty = if TCO.enable_sound_dynamic (Env.get_tcopt env) then MakeType.locl_like (Reason.Renforceable (get_pos expected_ty)) expected_ty else expected_ty in (match tys with | [expr_ty] -> let res = SubType.sub_type env expr_ty right_expected_ty @@ Some Typing_error.( Reasons_callback.of_primary_error @@ Primary.Hh_expect { pos = p; equivalent }) in let (env, ty_err_opt) = match res with | (env, None) -> if equivalent then SubType.sub_type env expected_ty expr_ty @@ Some Typing_error.( Reasons_callback.of_primary_error @@ Primary.Hh_expect { pos = p; equivalent }) else (env, None) | env_err -> env_err in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; env | _ -> env) | _ -> (Typing_error_utils.add_typing_error ~env @@ Typing_error.( primary @@ Primary.Expected_tparam { pos = use_pos; decl_pos = Pos_or_decl.none; n = 1 })); env let loop_forever env = (* forever = up to 10 minutes, to avoid accidentally stuck processes *) for i = 1 to 600 do (* Look up things in shared memory occasionally to have a chance to be * interrupted *) match Env.get_class env "FOR_TEST_ONLY" with | None -> Unix.sleep 1 | _ -> assert false done; Utils.assert_false_log_backtrace (Some "hh_loop_forever was looping for more than 10 minutes") let hh_time_start_times = ref SMap.empty (* Wrap the code you'd like to profile with `hh_time` annotations, e.g., hh_time('start'); // Expensive to typecheck code hh_time('stop'); `hh_time` admits an optional tag parameter to allow for multiple timings in the same file. hh_time('start', 'Timing 1'); // Expensive to typecheck code hh_time('stop', 'Timinig 1'); hh_time('start', 'Timing 2'); // Some more expensive to typecheck code hh_time('stop', 'Timinig 2'); Limitation: Timings are not scoped, so multiple uses of the same tag with `hh_time('start', tag)` will overwrite the beginning time of the previous timing. *) let do_hh_time el = let go command tag = match command with | Aast.String "start" -> let start_time = Unix.gettimeofday () in hh_time_start_times := SMap.add tag start_time !hh_time_start_times | Aast.String "stop" -> let stop_time = Unix.gettimeofday () in begin match SMap.find_opt tag !hh_time_start_times with | Some start_time -> let elapsed_time_ms = (stop_time -. start_time) *. 1000. in Printf.printf "%s: %0.2fms\n" tag elapsed_time_ms | None -> () end | _ -> () in match el with | [(_, (_, _, command))] -> go command "_" | [(_, (_, _, command)); (_, (_, _, Aast.String tag))] -> go command tag | _ -> () let is_parameter env x = Local_id.Map.mem x (Env.get_params env) let check_escaping_var env (pos, x) = let err_opt = if Env.is_using_var env x then let open Typing_error.Primary in Some (if Local_id.equal x this then Escaping_this pos else if is_parameter env x then Escaping_disposable_param pos else Escaping_disposable pos) else None in Option.iter err_opt ~f:(fun err -> Typing_error_utils.add_typing_error ~env @@ Typing_error.primary err) let make_result env p te ty = (* Set the variance of any type variables that were generated according * to how they appear in the expression type *) let env = Env.set_tyvar_variance env ty in let (env, te) = TUtils.make_simplify_typed_expr env p ty te in (env, te, ty) let localize_targ env ta = let pos = fst ta in let (env, targ) = Phase.localize_targ ~check_well_kinded:true env ta in (env, targ, ExpectedTy.make pos Reason.URhint (fst targ)) let rec set_function_pointer env ty = match get_node ty with | Tfun ft -> let ft = set_ft_is_function_pointer ft true in (env, mk (get_reason ty, Tfun ft)) | Tnewtype (name, _, ty1) when String.equal name SN.Classes.cSupportDyn -> let (env, ty1) = set_function_pointer env ty1 in TUtils.make_supportdyn (get_reason ty) env ty1 | _ -> (env, ty) let rec set_readonly_this pos env ty = match get_node ty with | Tfun ft -> let ft = set_ft_readonly_this ft true in (env, mk (get_reason ty, Tfun ft)) | Tnewtype (name, _, ty1) when String.equal name SN.Classes.cSupportDyn -> let (env, ty1) = set_readonly_this pos env ty1 in TUtils.make_supportdyn (get_reason ty) env ty1 | _ -> (env, ty) let xhp_attribute_decl_ty env sid obj attr = let (namepstr, valpty) = attr in let (valp, valty) = valpty in let ((env, e1), (declty, _tal)) = TOG.obj_get ~obj_pos:(fst sid) ~is_method:false ~inst_meth:false ~meth_caller:false ~nullsafe:None ~coerce_from_ty:None ~explicit_targs:[] ~class_id:(CI sid) ~member_id:namepstr ~on_error:Typing_error.Callback.unify_error env obj in let ureason = Reason.URxhp (snd sid, snd namepstr) in let (env, e2) = Typing_coercion.coerce_type valp ureason env valty (MakeType.unenforced declty) Typing_error.Callback.xhp_attribute_does_not_match_hint in let ty_mismatch_opt = mk_ty_mismatch_opt valty declty e2 in Option.( iter ~f:(Typing_error_utils.add_typing_error ~env) @@ merge e1 e2 ~f:Typing_error.both); (env, declty, ty_mismatch_opt) let closure_check_param env param = match hint_of_type_hint param.param_type_hint with | None -> env | Some hty -> let hint_pos = fst hty in let ((env, ty_err_opt1), hty) = Phase.localize_hint_for_lambda env hty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt1; let paramty = Env.get_local env (Local_id.make_unscoped param.param_name) in let (env, ty_err_opt2) = Typing_coercion.coerce_type hint_pos Reason.URhint env paramty.Typing_local_types.ty (MakeType.unenforced hty) Typing_error.Callback.unify_error in Option.iter ty_err_opt2 ~f:(Typing_error_utils.add_typing_error ~env); env let stash_conts_for_closure env p is_anon (captured : Typing_local_types.local Aast.capture_lid list) f = let with_ty_for_lid ((_, name) as lid) = (Env.get_local env name, lid) in let captured = if is_anon && TCO.any_coeffects (Env.get_tcopt env) then Typing_coeffects.( with_ty_for_lid (Pos.none, local_capability_id) :: with_ty_for_lid (Pos.none, capability_id) :: captured) else captured in let captured = if Env.is_local_present env this && not (Env.is_in_expr_tree env) then with_ty_for_lid (Pos.none, this) :: captured else captured in let init = Option.map (Env.next_cont_opt env) ~f:(fun next_cont -> let initial_locals = if is_anon then Env.get_locals env captured else next_cont.Typing_per_cont_env.local_types in let initial_fakes = Fake.forget (Env.get_fake_members env) Reason.(Blame (p, BSlambda)) in let tpenv = Env.get_tpenv env in (initial_locals, initial_fakes, tpenv)) in LEnv.stash_and_do env (Env.all_continuations env) (fun env -> let env = match init with | None -> env | Some (initial_locals, initial_fakes, tpenv) -> let env = Env.reinitialize_locals env in let env = Env.set_locals env initial_locals in let env = Env.set_fake_members env initial_fakes in let env = Env.env_with_tpenv env tpenv in env in f env) let requires_consistent_construct = function | CIstatic -> true | CIexpr _ -> true | CIparent -> false | CIself -> false | CI _ -> false (* Caller will be looking for a particular form of expected type * e.g. a function type (when checking lambdas) or tuple type (when checking * tuples). First expand the expected type and elide single union; also * strip nullables, so ?t becomes t, as context will always accept a t if a ?t * is expected. * * If strip_supportdyn is true, then we are expecting a function or shape type for the expected type, * and we should decompose supportdyn<t>, and like-push, and return true to * indicate that the type supports dynamic. * * Note: we currently do not generally expand ?t into (null | t), so ~?t is (dynamic | Toption t). *) let expand_expected_and_get_node ?(strip_supportdyn = false) ~pessimisable_builtin env (expected : ExpectedTy.t option) = let rec unbox ~under_supportdyn env ty = let (env, ty) = Env.expand_type env ty in match TUtils.try_strip_dynamic env ty with | Some stripped_ty -> (* We've got a type ty = ~stripped_ty so under Sound Dynamic we need to * account for like-pushing: the rule (shown here for vec) * t <:D dynamic * ---------------------- * vec<~t> <: ~vec<t> * So if expected type is ~vec<t> then we can actually ask for vec<~t> * which is more generous. *) if TCO.enable_sound_dynamic env.genv.tcopt then begin let (env, opt_ty) = if (not strip_supportdyn) && TCO.enable_sound_dynamic (Env.get_tcopt env) && pessimisable_builtin then (env, None) else Typing_dynamic.try_push_like env stripped_ty in match opt_ty with | None -> unbox ~under_supportdyn env stripped_ty | Some rty -> (* We can only apply like-pushing if the type actually supports dynamic. * We know this if we've gone under a supportdyn, *OR* if the type is * known to be a dynamic-aware subtype of dynamic. The latter might fail * if it's yet to be resolved i.e. a type variable, in which case we just * remove the expected type. *) if under_supportdyn || TUtils.is_supportdyn env rty then unbox ~under_supportdyn:true env rty else (env, None) end else unbox ~under_supportdyn env stripped_ty | None -> begin match get_node ty with | Tunion [ty] -> unbox ~under_supportdyn env ty | Toption ty -> unbox ~under_supportdyn env ty | Tnewtype (name, [ty], _) when String.equal name SN.Classes.cSupportDyn -> let (env, result) = unbox ~under_supportdyn:true env ty in begin match result with | None -> (env, None) | Some (ty, _) -> (env, Some (ty, true)) end | _ -> (env, Some (ty, false)) end in match expected with | None -> (env, None) | Some ExpectedTy.{ pos = p; reason = ur; ty = { et_type = ty; _ }; _ } -> let (env, res) = unbox ~under_supportdyn:false env ty in (match res with | None -> (env, None) | Some (uty, supportdyn) -> if supportdyn && not strip_supportdyn then (env, None) else (env, Some (p, ur, supportdyn, uty, get_node uty))) let uninstantiable_error env reason_pos cid c_tc_pos c_name c_usage_pos c_ty = let reason_ty_opt = match cid with | CIexpr _ -> Some (reason_pos, lazy (Typing_print.error env c_ty)) | _ -> None in let err = Typing_error.( primary @@ Primary.Uninstantiable_class { pos = c_usage_pos; class_name = c_name; reason_ty_opt; decl_pos = c_tc_pos; }) in Typing_error_utils.add_typing_error ~env err let coerce_to_throwable pos env exn_ty = let throwable_ty = MakeType.throwable (Reason.Rthrow pos) in Typing_coercion.coerce_type ~coerce_for_op:true pos Reason.URthrow env exn_ty { et_type = throwable_ty; et_enforced = Enforced } Typing_error.Callback.unify_error (* Bind lvar to ty and, if a hint is supplied, ty must be a subtype of it. If there is already a binding for lvar, make sure that its explicit type bound (if it has one) is respected. *) let set_valid_rvalue ?(is_using_clause = false) ~is_defined p env lvar hint_ty ty = let (env, hty, sub_bound_ty) = match hint_ty with | None -> (env, None, ty) | Some hty -> let (env, err) = Typing_subtype.sub_type env ty hty (Some Typing_error.( Reasons_callback.of_primary_error @@ Typing_error.Primary.Unify_error { pos = p; msg_opt = Some "Typed locals can only be assigned values whose type is compatible with the declared type."; reasons_opt = None; })) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) err; (env, Some hty, hty) in let (env, new_bound_ty, new_ty) = if Env.is_local_present env lvar then let local = Env.get_local env lvar in match local.Typing_local_types.bound_ty with | None -> (env, hty, ty) | Some old_bound_ty -> let (env, err) = Typing_subtype.sub_type env sub_bound_ty old_bound_ty (Some (Typing_error.Reasons_callback.unify_error_at p)) in (match err with | None -> (env, Some (Option.value hty ~default:old_bound_ty), ty) | Some err -> Typing_error_utils.add_typing_error ~env err; (* If the new type or bound violates the old one, then we want to check the remainder of the code with the type of the variable set to the bound *) (env, Some old_bound_ty, old_bound_ty)) else (env, hty, ty) in let env = set_local ~is_using_clause ~is_defined ~bound_ty:new_bound_ty env (p, lvar) new_ty in (* We are assigning a new value to the local variable, so we need to * generate a new expression id *) match Env.set_local_expr_id env lvar (Ident.tmp ()) with | Ok env -> env | Error (env, err) -> Typing_error_utils.add_typing_error ~env err; env let is_hack_collection env ty = (* TODO(like types) This fails if a collection is used as a parameter under * pessimization, because ~Vector<int> </: ConstCollection<mixed>. This is the * test we use to see whether to update the expression id for expressions * $vector[0] = $x and $vector[] = $x. If this is false, the receiver is assumed * to be a Hack array which are COW. This approximation breaks down in the presence * of dynamic. It is unclear whether we should change an expression id if the * receiver is dynamic. *) match get_node ty with | Tvar _ when TUtils.is_tyvar_error env ty -> (true, None) | _ -> Typing_solver.is_sub_type env ty (MakeType.const_collection Reason.Rnone (MakeType.mixed Reason.Rnone)) let check_class_get env p def_pos cid mid ce (_, _cid_pos, e) function_pointer = match e with | CIself when get_ce_abstract ce -> begin match Env.get_self_id env with | Some self -> begin (* at runtime, self:: in a trait is a call to whatever * self:: is in the context of the non-trait "use"-ing * the trait's code *) match Env.get_class env self with | Some cls when Ast_defs.is_c_trait (Cls.kind cls) -> (* Ban self::some_abstract_method() in a trait, if the * method is also defined in a trait. * * Abstract methods from interfaces are fine: we'll check * in the child class that we actually have an * implementation. *) (match Decl_provider.get_class (Env.get_ctx env) ce.ce_origin with | Some meth_cls when Ast_defs.is_c_trait (Cls.kind meth_cls) -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Self_abstract_call { meth_name = mid; self_pos = _cid_pos; pos = p; decl_pos = def_pos; }) | _ -> ()) | _ -> (* Ban self::some_abstract_method() in a class. This will * always error. *) Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Self_abstract_call { meth_name = mid; self_pos = _cid_pos; pos = p; decl_pos = def_pos; }) end | None -> () end | CIparent when get_ce_abstract ce -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Parent_abstract_call { meth_name = mid; pos = p; decl_pos = def_pos }) | CI _ when get_ce_abstract ce && function_pointer -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Abstract_function_pointer { class_name = cid; meth_name = mid; pos = p; decl_pos = def_pos }) | CI _ when get_ce_abstract ce -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Classname_abstract_call { class_name = cid; meth_name = mid; pos = p; decl_pos = def_pos }) | CI (_, class_name) when get_ce_synthesized ce -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Static_synthetic_method { class_name; meth_name = mid; pos = p; decl_pos = def_pos }) | _ -> () (** Given an identifier for a function, find its function type in the * environment and localise it with the input type parameters. *) let fun_type_of_id env x tal el = match Env.get_fun env (snd x) with | None -> let (env, _, ty) = unbound_name env x ((), Pos.none, Aast.Null) in (env, ty, []) | Some fd -> (match get_node fd.fe_type with | Tfun ft -> let ft = let pessimise = TCO.pessimise_builtins (Env.get_tcopt env) in Typing_special_fun.transform_special_fun_ty ~pessimise ft x (List.length el) in let ety_env = empty_expand_env in let ((env, ty_err_opt1), tal) = Phase.localize_targs ~check_well_kinded:true ~is_method:true ~def_pos:fd.fe_pos ~use_pos:(fst x) ~use_name:(strip_ns (snd x)) env ft.ft_tparams (List.map ~f:snd tal) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt1; let ft = Typing_enforceability.compute_enforced_and_pessimize_fun_type ~this_class:None env ft in let use_pos = fst x in let def_pos = fd.fe_pos in let ((env, ty_err_opt2), ft) = Phase.( localize_ft ~instantiation: { use_name = strip_ns (snd x); use_pos; explicit_targs = tal } ~def_pos ~ety_env env ft) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt2; let fty = Typing_dynamic.maybe_wrap_with_supportdyn ~should_wrap: (TCO.enable_sound_dynamic (Env.get_tcopt env) && fd.fe_support_dynamic_type) (Reason.localize (get_reason fd.fe_type)) ft in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) (TVis.check_deprecated ~use_pos ~def_pos env fd.fe_deprecated); Option.iter ~f:(Typing_error_utils.add_typing_error ~env) (TVis.check_cross_package ~use_pos ~def_pos env ft.ft_cross_package); Option.iter ~f:(Typing_error_utils.add_typing_error ~env) (TVis.check_top_level_access ~in_signature:false ~use_pos:(fst x) ~def_pos:fd.fe_pos env fd.fe_internal (Option.map fd.fe_module ~f:snd)); (env, fty, tal) | _ -> failwith "Expected function type") (** * Checks if a class (given by cty) contains a given static method. * * We could refactor this + class_get *) let class_contains_smethod env cty (_pos, mid) = let lookup_member ty = match get_class_type ty with | Some ((_, c), _, _) -> (match Env.get_class env c with | None -> false | Some class_ -> Option.is_some @@ Env.get_static_member true env class_ mid) | None -> false in let (_env, tyl) = TUtils.get_concrete_supertypes ~abstract_enum:true env cty in List.exists tyl ~f:lookup_member (* To be a valid trait declaration, all of its 'require extends' must * match; since there's no multiple inheritance, it follows that all of * the 'require extends' must belong to the same inheritance hierarchy * and one of them should be the child of all the others *) let trait_most_concrete_req_class trait env = List.fold (Cls.all_ancestor_reqs trait) ~f: begin fun acc (_p, ty) -> let (_r, (_p, name), _paraml) = TUtils.unwrap_class_type ty in let keep = match acc with | Some (c, _ty) -> Cls.has_ancestor c name | None -> false in if keep then acc else let class_ = Env.get_class env name in match class_ with | None -> acc | Some c when Ast_defs.is_c_interface (Cls.kind c) -> acc | Some c when Ast_defs.is_c_trait (Cls.kind c) -> (* this is an error case for which Typing_type_wellformedness spits out * an error, but does *not* currently remove the offending * 'require extends' or 'require implements' *) acc | Some c -> Some (c, ty) end ~init:None let check_arity ?(did_unpack = false) env pos pos_def ft (arity : int) = let exp_min = Typing_defs.arity_min ft in if arity < exp_min then Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Typing_too_few_args { expected = exp_min; actual = arity; pos; decl_pos = pos_def }); if get_ft_variadic ft then () else (* No variadics *) let exp_max = List.length ft.ft_params in let arity = if did_unpack then arity + 1 else arity in if arity > exp_max then Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Typing_too_many_args { expected = exp_max; actual = arity; pos; decl_pos = pos_def }) let check_lambda_arity env lambda_pos def_pos lambda_ft expected_ft = match (get_ft_variadic lambda_ft, get_ft_variadic expected_ft) with | (false, false) -> let expected = Typing_defs.arity_min expected_ft in let actual = Typing_defs.arity_min lambda_ft in let prim_err_opt = if actual < expected then Some (Typing_error.Primary.Typing_too_few_args { expected; actual; pos = lambda_pos; decl_pos = def_pos }) (* Errors.typing_too_few_args expected_min lambda_min lambda_pos def_pos; *) else if actual > expected then Some (Typing_error.Primary.Typing_too_many_args { expected; actual; pos = lambda_pos; decl_pos = def_pos }) (* Errors.typing_too_many_args expected_minlambda_min lambda_pos def_pos *) else None in Option.iter prim_err_opt ~f:(fun err -> Typing_error_utils.add_typing_error ~env @@ Typing_error.primary err) | (_, _) -> () (* The variadic capture argument is an array listing the passed * variable arguments for the purposes of the function body; callsites * should not unify with it *) let variadic_param env ft = if get_ft_variadic ft then (env, List.last ft.ft_params) else (env, None) let param_modes ?(is_variadic = false) ({ fp_pos; _ } as fp) (_, pos, _) param_kind ~env = let err_opt = let open Typing_error.Primary in match (get_fp_mode fp, param_kind) with | (FPnormal, Ast_defs.Pnormal) -> None | (FPinout, Ast_defs.Pinout _) -> None | (FPnormal, Ast_defs.Pinout p) -> Some (Inout_annotation_unexpected { pos = Pos.merge p pos; decl_pos = fp_pos; param_is_variadic = is_variadic; qfx_pos = p; }) | (FPinout, Ast_defs.Pnormal) -> Some (Inout_annotation_missing { pos; decl_pos = fp_pos }) in Option.iter err_opt ~f:(fun err -> Typing_error_utils.add_typing_error ~env @@ Typing_error.primary err) let split_remaining_params_required_optional ft remaining_params = (* Same example as above * * function f(int $i, string $j, float $k = 3.14, mixed ...$m): void {} * function g((string, float, bool) $t): void { * f(3, ...$t); * } * * `remaining_params` will contain [string, float] and there has been 1 parameter consumed. The min_arity * of this function is 2, so there is 1 required parameter remaining and 1 optional parameter. *) let original_params = if get_ft_variadic ft then List.drop_last_exn ft.ft_params else ft.ft_params in let min_arity = List.count ~f:(fun fp -> not (Typing_defs.get_fp_has_default fp)) original_params in let consumed = List.length original_params - List.length remaining_params in let required_remaining = Int.max (min_arity - consumed) 0 in let (required_params, optional_params) = List.split_n remaining_params required_remaining in (consumed, required_params, optional_params) let generate_splat_type_vars env p required_params optional_params variadic_param = let (env, d_required) = List.map_env env required_params ~f:(fun env _ -> Env.fresh_type env p) in let (env, d_optional) = List.map_env env optional_params ~f:(fun env _ -> Env.fresh_type env p) in let (env, d_variadic) = match variadic_param with | None -> (env, None) | Some _ -> let (env, ty) = Env.fresh_type env p in (env, Some ty) in (env, (d_required, d_optional, d_variadic)) let check_argument_type_against_parameter_type_helper ~dynamic_func env pos param arg_ty = Typing_log.( log_with_level env "typing" ~level:2 (fun () -> log_types (Pos_or_decl.of_raw_pos pos) env [ Log_head ( ("Typing.check_argument_type_against_parameter_type_helper " ^ match dynamic_func with | None -> "None" | Some Supportdyn_function -> "sd" | Some Like_function -> "~"), [ Log_type ("param_ty", param.fp_type.et_type); Log_type ("arg_ty", arg_ty); ] ); ])); let param_ty = match dynamic_func with | Some dyn_func_kind -> begin (* It is only sound to add like types to the parameters of supportdyn functions, since in this case we are semantically just using the &dynamic part of the type to call them. For like functions, they have to check both sides. *) match dyn_func_kind with | Supportdyn_function -> MakeType.locl_like (get_reason param.fp_type.et_type) param.fp_type.et_type | Like_function -> param.fp_type.et_type end | None -> param.fp_type.et_type in Typing_coercion.coerce_type ~coerce:None pos Reason.URparam env arg_ty { param.fp_type with et_type = param_ty } Typing_error.Callback.unify_error let check_argument_type_against_parameter_type ~dynamic_func env param param_kind (((_, pos, expr_) as e : Nast.expr), arg_ty) ~is_variadic = param_modes ~is_variadic ~env param e param_kind; (* When checking params, the type 'x' may be expression dependent. Since * we store the expression id in the local env for Lvar, we want to apply * it in this case. *) let (env, dep_ty) = match expr_ with | Hole ((_, _, Lvar _), _, _, _) | Lvar _ -> ExprDepTy.make env ~cid:(CIexpr e) arg_ty | _ -> (env, arg_ty) in let pos = match param_kind with | Ast_defs.Pnormal -> pos | Ast_defs.Pinout pk_pos -> Pos.merge pk_pos pos in let (env, opt_e, used_dynamic) = (* First try statically *) let (env1, e1opt) = check_argument_type_against_parameter_type_helper ~dynamic_func:None env pos param dep_ty in if Option.is_some dynamic_func then match e1opt with | None -> (env1, None, false) | Some e1 -> let (env2, e2opt) = check_argument_type_against_parameter_type_helper ~dynamic_func env pos param dep_ty in (match e2opt with (* We used dynamic calling to get a successful check *) | None -> (env2, None, true) (* We failed on both, pick the one with fewest errors! (preferring static on a tie) *) | Some e2 -> if Typing_error.count e1 <= Typing_error.count e2 then (env1, Some e1, false) else (env2, Some e2, true)) else (env1, e1opt, false) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) opt_e; (env, mk_ty_mismatch_opt arg_ty param.fp_type.et_type opt_e, used_dynamic) let bad_call env p ty = if not (TUtils.is_tyvar_error env ty) then Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Bad_call { pos = p; ty_name = lazy (Typing_print.error env ty) }) let rec make_a_local_of ~include_this env e = match e with | (_, p, Class_get ((_, _, cname), CGstring (_, member_name), _)) -> let (env, local) = Env.FakeMembers.make_static env cname member_name p in (env, Some (p, local)) | ( _, p, Obj_get ( (((_, _, This) | (_, _, Lvar _)) as obj), (_, _, Id (_, member_name)), _, _ ) ) -> let (env, local) = Env.FakeMembers.make env obj member_name p in (env, Some (p, local)) | (_, _, Lvar x) | (_, _, Dollardollar x) -> (env, Some x) | (_, p, This) when include_this -> (env, Some (p, this)) | (_, _, Hole (e, _, _, _)) | (_, _, ReadonlyExpr e) -> make_a_local_of ~include_this env e | _ -> (env, None) let strip_supportdyn ty = (* Currently we don't check for support dynamic at runtime, so we * must simply treat supportdyn<t> as t when refining *) match get_node ty with | Tnewtype (name, [ty], _) when String.equal name SN.Classes.cSupportDyn -> ty | _ -> ty let get_bound_ty_for_lvar env e = match e with | (_, _, Lvar (_, lid)) -> (Typing_env.get_local env lid).Typing_local_types.bound_ty | _ -> None (* This function captures the common bits of logic behind refinement * of the type of a local variable or a class member variable as a * result of a dynamic check (e.g., nullity check, simple type check * using functions like is_int, is_string, is_array etc.). The * argument refine is a function that takes the type of the variable * and returns a refined type (making necessary changes to the * environment, which is threaded through). * * All refinement functions return, in addition to the updated * environment, a (conservative) set of all the locals that got * refined. This set is used to construct AssertEnv statmements in * the typed AST. *) let refine_lvalue_type env ((ty, _, _) as te) ~refine = let e = Tast.to_nast_expr te in let (env, localopt) = make_a_local_of ~include_this:false env e in (* TODO TAST: generate an assignment to the fake local in the TAST *) match localopt with | Some lid -> let (env, ty) = refine env ty in let bound_ty = get_bound_ty_for_lvar env e in (* Refining the type of a typed local shouldn't change it's given bound. We assume that the supplied refine function returns a subtype of the type it's given, so that the refined type remains a subtype of the bound *) ( set_local ~is_defined:true ~bound_ty env lid ty, Local_id.Set.singleton (snd lid) ) | None -> (env, Local_id.Set.empty) let rec condition_nullity ~nonnull (env : env) te = match te with (* assignment: both the rhs and lhs of the '=' must be made null/non-null *) | (_, _, Aast.Binop { bop = Ast_defs.Eq None; lhs = var; rhs = te }) -> let (env, lset1) = condition_nullity ~nonnull env te in let (env, lset2) = condition_nullity ~nonnull env var in (env, Local_id.Set.union lset1 lset2) (* case where `Shapes::idx(...)` must be made null/non-null *) | ( _, _, Aast.Call { func = (_, _, Aast.Class_const ((_, _, Aast.CI (_, shapes)), (_, idx))); args = [(Ast_defs.Pnormal, shape); (Ast_defs.Pnormal, field)]; _; } ) when String.equal shapes SN.Shapes.cShapes && String.equal idx SN.Shapes.idx -> let field = Tast.to_nast_expr field in let refine env shape_ty = if nonnull then Typing_shapes.shapes_idx_not_null env shape_ty field else (env, shape_ty) in refine_lvalue_type env shape ~refine | (_, _, Hole (te, _, _, _)) -> condition_nullity ~nonnull env te | (_, p, _) -> let refine env ty = if nonnull then Typing_solver.non_null env (Pos_or_decl.of_raw_pos p) ty else let r = Reason.Rwitness_from_decl (get_pos ty) in Inter.intersect env ~r ty (MakeType.null r) in refine_lvalue_type env te ~refine (** If we are dealing with a refinement like $x is MyClass<A, B> then class_info is the class info of MyClass and hint_tyl corresponds to A, B. *) let generate_fresh_tparams env class_info p reason hint_tyl = let tparams_len = List.length (Cls.tparams class_info) in let hint_tyl = List.take hint_tyl tparams_len in let pad_len = tparams_len - List.length hint_tyl in let hint_tyl = List.map hint_tyl ~f:(fun x -> Some x) @ List.init pad_len ~f:(fun _ -> None) in let replace_wildcard env hint_ty tp = let { tp_name = (_, tparam_name); tp_reified = reified; tp_user_attributes; _; } = tp in let enforceable = Attributes.mem SN.UserAttributes.uaEnforceable tp_user_attributes in let newable = Attributes.mem SN.UserAttributes.uaNewable tp_user_attributes in match hint_ty with | Some ty -> begin match get_node ty with | Tgeneric (name, _targs) when Env.is_fresh_generic_parameter name -> (* TODO(T69551141) handle type arguments above and below *) (env, (Some (tp, name), MakeType.generic reason name)) | _ -> (env, (None, ty)) end | None -> let (env, new_name) = Env.add_fresh_generic_parameter env (Pos_or_decl.of_raw_pos p) tparam_name ~reified ~enforceable ~newable in (* TODO(T69551141) handle type arguments for Tgeneric *) (env, (Some (tp, new_name), MakeType.generic reason new_name)) in let (env, tparams_and_tyl) = List.map2_env env hint_tyl (Cls.tparams class_info) ~f:replace_wildcard in let (tparams_with_new_names, tyl_fresh) = List.unzip tparams_and_tyl in (env, tparams_with_new_names, tyl_fresh) let safely_refine_class_type env p class_name class_info ivar_ty obj_ty reason (tparams_with_new_names : (decl_tparam * string) option list) tyl_fresh = (* Type of variable in block will be class name * with fresh type parameters *) let obj_ty = mk (get_reason obj_ty, Tclass (class_name, nonexact, tyl_fresh)) in let tparams = Cls.tparams class_info in (* Add in constraints as assumptions on those type parameters *) let ety_env = { empty_expand_env with substs = Subst.make_locl tparams tyl_fresh; this_ty = obj_ty; } in let add_bounds env (t, ty_fresh) = List.fold_left t.tp_constraints ~init:env ~f:(fun env (ck, ty) -> (* Substitute fresh type parameters for * original formals in constraint *) let ((env, ty_err_opt), ty) = Phase.localize ~ety_env env ty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; SubType.add_constraint env ck ty_fresh ty @@ Some (Typing_error.Reasons_callback.unify_error_at p)) in let env = List.fold_left (List.zip_exn tparams tyl_fresh) ~f:add_bounds ~init:env in (* Finally, if we have a class-test on something with static classish type, * then we can chase the hierarchy and decompose the types to deduce * further assumptions on type parameters. For example, we might have * class B<Tb> { ... } * class C extends B<int> * and have obj_ty = C and x_ty = B<T> for a generic parameter Aast. * Then SubType.add_constraint will deduce that T=int and add int as * both lower and upper bound on T in env.lenv.tpenv * * We only wish to do this if the types are in a possible subtype relationship. *) let (env, supertypes) = TUtils.get_concrete_supertypes ~abstract_enum:true ~include_case_types:true env ivar_ty in let rec might_be_supertype env ty = let (_env, ty) = Env.expand_type env ty in match get_node ty with | Tclass ((_, name), _, _) when String.equal name (Cls.name class_info) || Cls.has_ancestor class_info name || Cls.requires_ancestor class_info name -> true | Tnewtype (name, tyl, _) -> (* For case types we want to open the union, filtering it to only the * variant types that share the same data type as [obj_ty] *) let (env, variants_opt) = Typing_case_types.get_variant_tys env name tyl in begin match variants_opt with | Some variants -> let (env, ty) = Typing_case_types.filter_variants_using_datatype env (get_reason ty) variants obj_ty in might_be_supertype env ty | None -> false end | Toption ty -> might_be_supertype env ty | Tunion tyl -> List.for_all tyl ~f:(might_be_supertype env) | _ -> false in let env = List.fold_left supertypes ~init:env ~f:(fun env ty -> if might_be_supertype env ty then SubType.add_constraint env Ast_defs.Constraint_as obj_ty ty @@ Some (Typing_error.Reasons_callback.unify_error_at p) else env) in (* It's often the case that the fresh name isn't necessary. For * example, if C<T> extends B<T>, and we have $x:B<t> for some type t * then $x is C should refine to $x:C<t>. * We take a simple approach: * For a fresh type parameter T#1, if * - There is an eqality constraint T#1 = t, * - T#1 is covariant, and T#1 has upper bound t (or mixed if absent) * - T#1 is contravariant, and T#1 has lower bound t (or nothing if absent) * then replace T#1 with t. * This is done in Type_parameter_env_ops.simplify_tpenv *) let (env, tparam_substs) = Type_parameter_env_ops.simplify_tpenv env (List.zip_exn tparams_with_new_names tyl_fresh) reason in let tyl_fresh = List.map2_exn tyl_fresh tparams_with_new_names ~f:(fun orig_ty tparam_opt -> match tparam_opt with | None -> orig_ty | Some (_tp, name) -> SMap.find name tparam_substs) in let obj_ty_simplified = mk (get_reason obj_ty, Tclass (class_name, nonexact, tyl_fresh)) in (env, obj_ty_simplified) (** Transform a hint like `A<_>` to a localized type like `A<T#1>` for refinement of an instance variable. ivar_ty is the previous type of that instance variable. Return the intersection of the hint and variable. Returns the env, refined type, and a boolean true if ivar_ty was a class or tuple containing a class and false otherwise. *) let rec class_for_refinement env p reason ivar_pos ivar_ty hint_ty = let (env, hint_ty) = Env.expand_type env hint_ty in match (get_node ivar_ty, get_node hint_ty) with | (_, Tclass (((_, cid) as _c), _, tyl)) -> begin match Env.get_class env cid with | Some class_info -> let (env, tparams_with_new_names, tyl_fresh) = generate_fresh_tparams env class_info p reason tyl in let (env, ty) = safely_refine_class_type env p _c class_info ivar_ty hint_ty reason tparams_with_new_names tyl_fresh in (env, (ty, true)) | None -> (env, (MakeType.nothing (Reason.Rmissing_class ivar_pos), true)) end | (Ttuple ivar_tyl, Ttuple hint_tyl) when Int.equal (List.length ivar_tyl) (List.length hint_tyl) -> let (env, tyl) = List.map2_env env ivar_tyl hint_tyl ~f:(fun env ivar_ty hint_ty -> class_for_refinement env p reason ivar_pos ivar_ty hint_ty) in (env, (MakeType.tuple reason (List.map ~f:fst tyl), List.exists ~f:snd tyl)) | _ -> (env, (hint_ty, false)) let refine_and_simplify_intersection ~hint_first env p reason ivar_pos ivar_ty hint_ty = let intersect ~hint_first ~is_class env r ty hint_ty = let (env, hint_ty) = if is_class && TCO.enable_sound_dynamic (Env.get_tcopt env) && TUtils.is_supportdyn env ty then TUtils.make_supportdyn reason env hint_ty else (env, hint_ty) in (* Sometimes the type checker is sensitive to the ordering of intersections *) if hint_first then Inter.intersect env ~r hint_ty ty else Inter.intersect env ~r ty hint_ty in let like_type_simplify ty = (* Distribute the intersection over the union *) let (env, (hint_ty, is_class)) = class_for_refinement env p reason ivar_pos ty hint_ty in let (env, ty2) = intersect ~hint_first:false ~is_class env reason ty hint_ty in match get_node hint_ty with (* If the hint is fully enforced, keep that information around *) | Tclass (_, _, []) | Tprim _ -> let (env, dyn_ty) = Inter.intersect env ~r:reason (MakeType.dynamic reason) hint_ty in Union.union env dyn_ty ty2 | _ -> (env, MakeType.locl_like reason ty2) in match TUtils.try_strip_dynamic env ivar_ty with | Some ty when TCO.enable_sound_dynamic (Env.get_tcopt env) -> like_type_simplify ty | _ -> let (env, (hint_ty, is_class)) = class_for_refinement env p reason ivar_pos ivar_ty hint_ty in intersect ~hint_first ~is_class env reason ivar_ty hint_ty let ish_weakening env hint hint_ty = match hint with | (_, Aast.Happly ((_, name), _)) -> let enum_opt = Option.(Env.get_enum env name >>= Cls.enum_type) in begin match enum_opt with | Some { te_base; _ } -> begin match Typing_defs.get_node te_base with | Typing_defs.(Tprim Tarraykey) -> hint_ty | _ -> MakeType.intersection Reason.Rnone [ MakeType.locl_like Reason.Rnone hint_ty; MakeType.arraykey Reason.Rnone; ] end | _ -> hint_ty end | _ -> hint_ty let refine_for_is ~hint_first env tparamet ivar reason hint = let (env, lset) = match snd hint with | Aast.Hnonnull -> condition_nullity ~nonnull:tparamet env ivar | Aast.Hprim Tnull -> condition_nullity ~nonnull:(not tparamet) env ivar | _ -> (env, Local_id.Set.empty) in let (env, locl) = make_a_local_of ~include_this:true env (Tast.to_nast_expr ivar) in match locl with | Some locl_ivar -> let ((env, ty_err_opt), hint_ty) = Phase.localize_hint_for_refinement env hint in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let hint_ty = strip_supportdyn hint_ty in let hint_ty = if Env.get_tcopt env |> TCO.pessimise_builtins then ish_weakening env hint hint_ty else hint_ty in let (env, hint_ty) = if not tparamet then Inter.negate_type env reason hint_ty ~approx:TUtils.ApproxUp else (env, hint_ty) in let (env, refined_ty) = refine_and_simplify_intersection ~hint_first env (fst hint) reason (fst locl_ivar) (fst3 ivar) hint_ty in let bound_ty = get_bound_ty_for_lvar env ivar in ( set_local ~is_defined:true ~bound_ty env locl_ivar refined_ty, Local_id.Set.singleton (snd locl_ivar) ) | None -> (env, lset) let refine_for_equality pos env te ty = let (env, locl) = make_a_local_of ~include_this:true env (Tast.to_nast_expr te) in match locl with | Some locl_ivar -> let (env, refined_ty) = refine_and_simplify_intersection ~hint_first:false env pos (Reason.Requal pos) (fst locl_ivar) (fst3 te) ty in let bound_ty = get_bound_ty_for_lvar env te in ( set_local ~is_defined:true ~bound_ty env locl_ivar refined_ty, Local_id.Set.singleton (snd locl_ivar) ) | None -> (env, Local_id.Set.empty) type legacy_arrays = | HackDictOrDArray | HackVecOrVArray (* Refine type for is_array, is_vec, is_keyset and is_dict tests * `pred_name` is the function name itself (e.g. 'is_vec') * `p` is position of the function name in the source * `arg_expr` is the argument to the function *) let safely_refine_is_array env ty p pred_name arg_expr = refine_lvalue_type env arg_expr ~refine:(fun env arg_ty -> let r = Reason.Rpredicated (p, pred_name) in let (env, tarrkey_name) = Env.add_fresh_generic_parameter env (Pos_or_decl.of_raw_pos p) "Tk" ~reified:Erased ~enforceable:false ~newable:false in (* TODO(T69551141) handle type arguments for Tgeneric *) let tarrkey = MakeType.generic r tarrkey_name in let env = SubType.add_constraint env Ast_defs.Constraint_as tarrkey (MakeType.arraykey r) @@ Some (Typing_error.Reasons_callback.unify_error_at p) in let (env, tfresh_name) = Env.add_fresh_generic_parameter env (Pos_or_decl.of_raw_pos p) "T" ~reified:Erased ~enforceable:false ~newable:false in (* TODO(T69551141) handle type arguments for Tgeneric *) let tfresh = MakeType.generic r tfresh_name in (* This is the refined type of e inside the branch *) let hint_ty = match ty with | HackDictOrDArray -> MakeType.dict r tarrkey tfresh | HackVecOrVArray -> MakeType.vec r tfresh in let (_, arg_pos, _) = arg_expr in let (env, (refined_ty, _)) = class_for_refinement env p r arg_pos arg_ty hint_ty in (* Add constraints on generic parameters that must * hold for refined_ty <:arg_ty. For example, if arg_ty is Traversable<T> * and refined_ty is keyset<T#1> then we know T#1 <: T. * See analogous code in safely_refine_class_type. *) let (env, supertypes) = TUtils.get_concrete_supertypes ~expand_supportdyn:false ~abstract_enum:true env arg_ty in let env = List.fold_left supertypes ~init:env ~f:(fun env ty -> SubType.add_constraint env Ast_defs.Constraint_as hint_ty ty @@ Some (Typing_error.Reasons_callback.unify_error_at p)) in Inter.intersect ~r env refined_ty arg_ty) let key_exists env pos shape field = let field = Tast.to_nast_expr field in refine_lvalue_type env shape ~refine:(fun env shape_ty -> 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 -> (env, shape_ty) | Some field_name -> let field_name = TShapeField.of_ast Pos_or_decl.of_raw_pos field_name in Typing_shapes.refine_shape field_name pos env shape_ty) (** Add a fresh type parameter to [env] with a name starting [prefix] and a constraint on [ty]. *) let synthesize_type_param env p prefix ty = let (env, name) = match get_node ty with (* Don't generate another fresh generic off an existing fresh generic *) | Tgeneric (n, _) when Env.is_fresh_generic_parameter n -> (env, n) | _ -> let (env, name) = Env.fresh_param_name env prefix in let env = Env.add_upper_bound_global env name ty in let env = Env.add_lower_bound_global env name ty in (env, name) in let hint = (p, Aast.Habstr (name, [])) in (hint, env) (** Transform calls to MyVisitor::makeTree with [f]. *) let rec rewrite_expr_tree_maketree env expr f = let (pos, p, expr_) = expr in let (env, expr_) = match expr_ with | Call ({ func = ( fun_pos, p, (Lfun (fun_, idl) | Efun { ef_fun = fun_; ef_use = idl; _ }) ); _; } as call_expr) -> (* Express tree literals containing splices use an anonymous function that returns the makeTree call. (function() { $0splice1 = "whatever"; return MyVisitor::makeTree(...); })() *) let map_stmt env s = match s with | (pos, Return (Some expr)) -> let (env, expr) = rewrite_expr_tree_maketree env expr f in (env, (pos, Return (Some expr))) | _ -> (env, s) in let (env, body_ast) = List.map_env env fun_.f_body.fb_ast ~f:map_stmt in let fun_ = { fun_ with f_body = { fb_ast = body_ast } } in (env, Call { call_expr with func = (fun_pos, p, Lfun (fun_, idl)) }) | Call _ -> (* The desugarer might give us a simple call to makeTree, so we can process it immediately. *) f env expr_ | _ -> (env, expr_) in (env, (pos, p, expr_)) (** Given [expr], a runtime expression for an expression tree, add a type parameter to the makeTree call. This enables expression tree visitors to use phantom type parameters. The visitor can be defined with __Explicit. public static function makeTree<<<__Explicit>> TInfer>(...) { ... } Userland calls to this method must provide an explicit type. MyVisitor::makeTree<MyVisitorInt>(...); For expression tree literals, we run type inference and provide a synthesized type parameter to the desugared runtime expression. MyVisitor`1`; // we infer MyVisitorInt // we add this constrained type parameter: MyVisitor::makeTree<TInfer#1>(...) where TInfer#1 = MyVisitorInt *) let maketree_with_type_param env p expr expected_ty = let (hint_virtual, env) = synthesize_type_param env p "TInfer" expected_ty in let rewrite_expr env expr = match expr with | Call e -> (env, Call { e with targs = [((), hint_virtual)] }) | e -> (env, e) in rewrite_expr_tree_maketree env expr rewrite_expr module EnumClassLabelOps = struct type result = | Success of Tast.expr * locl_ty | ClassNotFound | LabelNotFound of Tast.expr * locl_ty | Skip (** Given an [enum_id] and a [label_name], tries to see if [enum_id] has a constant named [label_name]. In such case, creates the expected typed expression. If [label_name] is not there, it will register an error. [ctor] is either `MemberOf` or `Label` [full] describes if the original expression was a full label, as in E#A, or a short version, as in #A *) let expand pos env ~full ~ctor enum_id label_name (ty_pos : Pos_or_decl.t option) = let (_, enum_name) = enum_id in let cls = Env.get_class env enum_name in match cls with | Some cls -> (match Env.get_const env cls label_name with | Some const_def -> let dty = const_def.cc_type in (* the enum constant has type MemberOf<X, Y>. If we are * processing a Label argument, we just switch MemberOf for * Label. *) let dty = match deref dty with | (r, Tapply ((p, _), args)) -> mk (r, Tapply ((p, ctor), args)) | _ -> dty in let ((env, ty_err_opt), lty) = Phase.localize_no_subst env ~ignore_errors:true dty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let hi = lty in let qualifier = if full then Some enum_id else None in let te = (hi, pos, Aast.EnumClassLabel (qualifier, label_name)) in (env, Success (te, lty)) | None -> let consts = Cls.consts cls |> List.filter ~f:(fun (name, _) -> not (String.equal name SN.Members.mClass)) in let most_similar = match Env.most_similar label_name consts fst with | Some (name, const) -> Some ( (if full then Render.strip_ns enum_name ^ "#" ^ name else "#" ^ name), const.cc_pos ) | None -> None in Typing_error_utils.add_typing_error ~env Typing_error.( enum @@ Primary.Enum.Enum_class_label_unknown { pos; label_name; enum_name; decl_pos = Cls.pos cls; most_similar; ty_pos; }); let (env, ty) = Env.fresh_type_error env pos in let te = (ty, pos, Aast.EnumClassLabel (None, label_name)) in (env, LabelNotFound (te, ty))) | None -> (env, ClassNotFound) end type valkind = | Lvalue | Lvalue_subexpr | Other let is_lvalue = function | Lvalue -> true | Lvalue_subexpr | Other -> false (* Given a localized parameter type and parameter information, infer * a type for the parameter default expression (if present) and check that * it is a subtype of the parameter type (if present). * Set the type of the parameter in the locals environment *) let rec bind_param env ?(immutable = false) ?(can_read_globals = false) ?(no_auto_likes = false) (opt_ty1, param) = let (env, param_te, ty1) = match param.param_expr with | None -> begin match opt_ty1 with | None -> (* If no parameter type has been provided, we assume that an error * has already been reported, and generate an error type variable *) let (env, err_ty) = Env.fresh_type_error_contravariant env param.param_pos in (env, None, err_ty) | Some ty1 -> (env, None, ty1) end | Some e -> let decl_hint = Option.map ~f:(Decl_hint.hint env.decl_env) (hint_of_type_hint param.param_type_hint) in let enforced = match decl_hint with | None -> Unenforced | Some ty -> Typing_enforceability.get_enforcement ~this_class:(Env.get_self_class env) env ty in let expected = match opt_ty1 with | None -> None | Some ty1 -> let ty1_enforced = { et_type = ty1; et_enforced = enforced } in ExpectedTy.make_and_allow_coercion_opt env param.param_pos Reason.URparam ty1_enforced in let (env, (te, ty2)) = let reason = Reason.Rwitness param.param_pos in let pure = MakeType.mixed reason in let cap = if can_read_globals then MakeType.capability reason SN.Capabilities.accessGlobals else pure in with_special_coeffects env cap pure @@ fun env -> expr ?expected env e ~allow_awaitable:(*?*) false |> triple_to_pair in Typing_sequencing.sequence_check_expr e; let (env, ty1) = match opt_ty1 with (* Type hint is missing *) | None -> (env, ty2) (* Otherwise we have an explicit type, and the default expression type * must be a subtype *) | Some ty1 -> (* Under Sound Dynamic, if t is the declared type of the parameter, then we * allow the default expression to have any type u such that u <: ~t. * If t is enforced, then the parameter is assumed to have that type when checking the body, * because we know that enforcement will ensure this. * If t is not enforced, then the parameter is assumed to have type u|t when checking the body, * as though the default expression had been assigned conditionally to the parameter. *) let support_dynamic = TCO.enable_sound_dynamic (Env.get_tcopt env) && Env.get_support_dynamic_type env in let like_ty1 = if support_dynamic && not no_auto_likes then TUtils.make_like env ty1 else ty1 in let (env, ty_err_opt) = Typing_coercion.coerce_type param.param_pos Reason.URhint env ty2 { et_type = like_ty1; et_enforced = enforced } Typing_error.Callback.parameter_default_value_wrong_type in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); if support_dynamic then match enforced with | Enforced -> (env, ty1) | _ -> Union.union env ty1 ty2 else (env, ty1) in (env, Some te, ty1) in let (env, user_attributes) = attributes_check_def env SN.AttributeKinds.parameter param.param_user_attributes in let tparam = { Aast.param_annotation = Tast.make_expr_annotation param.param_pos ty1; Aast.param_type_hint = (ty1, hint_of_type_hint param.param_type_hint); Aast.param_is_variadic = param.param_is_variadic; Aast.param_pos = param.param_pos; Aast.param_name = param.param_name; Aast.param_expr = param_te; Aast.param_callconv = param.param_callconv; Aast.param_readonly = param.param_readonly; Aast.param_user_attributes = user_attributes; Aast.param_visibility = param.param_visibility; } in let mode = get_param_mode param.param_callconv in let out_ty = match mode with | FPinout -> let decl_hint = Option.map ~f:(Decl_hint.hint env.decl_env) (hint_of_type_hint param.param_type_hint) in let enforced = match decl_hint with | None -> Unenforced | Some ty -> Typing_enforceability.get_enforcement ~this_class:(Env.get_self_class env) env ty in begin match enforced with | Enforced when TCO.enable_sound_dynamic env.genv.tcopt && Env.get_support_dynamic_type env -> Some (TUtils.make_like env ty1) | _ -> (* In implicit SD mode, all inout parameters are pessimised, unless marked <<__NoAutoLikes>> *) if TCO.everything_sdt env.genv.tcopt && not no_auto_likes then Some (TUtils.make_like env ty1) else Some ty1 end | _ -> None in let id = Local_id.make_unscoped param.param_name in (* Parameters are not typed locals and so have no bound *) let env = Env.set_local ~is_defined:true ~bound_ty:None ~immutable env id ty1 param.param_pos in let env = Env.set_param env id (ty1, param.param_pos, out_ty) in let env = if has_accept_disposable_attribute param then Env.set_using_var env id else env in (env, tparam) and bind_params env ?(can_read_globals = false) ~no_auto_likes ctxs param_tys params = let params_need_immutable = Typing_coeffects.get_ctx_vars ctxs in let bind_param_and_check env lty_and_param = let (_ty, param) = lty_and_param in let name = param.param_name in let immutable = List.exists ~f:(String.equal name) params_need_immutable in let (env, fun_param) = bind_param ~immutable ~can_read_globals ~no_auto_likes env lty_and_param in (env, fun_param) in List.map_env env (List.zip_exn param_tys params) ~f:bind_param_and_check (*****************************************************************************) (* function used to type closures, functions and methods *) (*****************************************************************************) and fun_ ?(abstract = false) ?(native = false) ?(disable = false) env return pos named_body f_kind = Env.with_env env (fun env -> debug_last_pos := pos; let env = Env.set_return env return in let (env, tb) = if disable then let () = Errors.internal_error pos ("Type inference for this function has been disabled by the " ^ SN.UserAttributes.uaDisableTypecheckerInternal ^ " attribute") in block env [] else block env named_body.fb_ast in Typing_sequencing.sequence_check_block named_body.fb_ast; let { Typing_env_return_info.return_type = ret; _ } = Env.get_return env in let has_implicit_return = LEnv.has_next env in let has_readonly = Env.get_readonly env in let env = if (not has_implicit_return) || abstract || native || Env.is_hhi env then env else Typing_return.fun_implicit_return env pos ret.et_type f_kind in let env = Env.set_fun_tast_info env Tast.{ has_implicit_return; has_readonly } in debug_last_pos := Pos.none; (env, tb)) and block env stl = Env.with_origin env Decl_counters.Body @@ fun env -> (* To insert an `AssertEnv`, `stmt` might return a `Block`. We eliminate it here to keep ASTs `Block`-free. *) let (env, stl) = List.fold ~init:(env, []) stl ~f:(fun (env, stl) st -> let (env, st) = stmt env st in (* Accumulate statements in reverse order *) let stl = match st with | (_, Aast.Block stl') -> List.rev stl' @ stl | _ -> st :: stl in (env, stl)) in (env, List.rev stl) (* Ensure that `ty` is a subtype of IDisposable (for `using`) or * IAsyncDisposable (for `await using`) *) and has_dispose_method env has_await p e ty = let meth = if has_await then SN.Members.__disposeAsync else SN.Members.__dispose in let (_, obj_pos, _) = e in let ((env, ty_err_opt), (tfty, _tal)) = TOG.obj_get ~obj_pos ~is_method:true ~inst_meth:false ~meth_caller:false ~nullsafe:None ~coerce_from_ty:None ~explicit_targs:[] ~class_id:(CIexpr e) ~member_id:(p, meth) ~on_error:(Typing_error.Callback.using_error p ~has_await) env ty in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let (env, (_tel, _typed_unpack_element, _ty, _should_forget_fakes)) = call ~expected:None ~expr_pos:p ~recv_pos:obj_pos env tfty [] None in env (* Check an individual component in the expression `e` in the * `using (e) { ... }` statement. * This consists of either * a simple assignment `$x = e`, in which `$x` is the using variable, or * an arbitrary expression `e`, in which case a temporary is the using * variable, inaccessible in the source. * Return the typed expression and its type, and any variables that must * be designated as "using variables" for avoiding escapes. *) and check_using_expr has_await env ((_, pos, content) as using_clause) = match content with (* Simple assignment to local of form `$lvar = e` *) | Binop { bop = Ast_defs.Eq None; lhs = (_, lvar_pos, Lvar lvar); rhs = e } -> let (env, te, ty) = expr ~is_using_clause:true env e ~allow_awaitable:(*?*) false in let env = has_dispose_method env has_await pos e ty in let env = set_valid_rvalue ~is_using_clause:true ~is_defined:true (fst lvar) env (snd lvar) None ty in let (env, inner_tast) = TUtils.make_simplify_typed_expr env lvar_pos ty (Aast.Lvar lvar) in let (env, tast) = TUtils.make_simplify_typed_expr env pos ty (Aast.Binop { bop = Ast_defs.Eq None; lhs = inner_tast; rhs = te }) in (env, (tast, [snd lvar])) (* Arbitrary expression. This will be assigned to a temporary *) | _ -> let (env, typed_using_clause, ty) = expr ~is_using_clause:true env using_clause ~allow_awaitable:(*?*) false in let env = has_dispose_method env has_await pos using_clause ty in (env, (typed_using_clause, [])) (* Check the using clause e in * `using (e) { ... }` statement (`has_await = false`) or * `await using (e) { ... }` statement (`has_await = true`). * `using_clauses` is a list of expressions. * Return the typed expression, and any variables that must * be designated as "using variables" for avoiding escapes. *) and check_using_clause env has_await using_clauses = let (env, pairs) = List.map_env env using_clauses ~f:(check_using_expr has_await) in let (typed_using_clauses, vars) = List.unzip pairs in (env, typed_using_clauses, List.concat vars) and stmt env (pos, st) = let (env, st) = stmt_ env pos st in Typing_debug.log_env_if_too_big pos env; (env, (pos, st)) and stmt_ env pos st = let expr ?(allow_awaitable = (*?*) false) = expr ~allow_awaitable in let exprs = exprs ~allow_awaitable:(*?*) false in (* Type check a loop. f env = (env, result) checks the body of the loop. * We iterate over the loop until the "next" continuation environment is * stable. alias_depth is supposed to be an upper bound on this; but in * certain cases this fails (e.g. a generic type grows unboundedly). TODO: * fix this. *) let infer_loop env f = let in_loop_outer = env.in_loop in let alias_depth = if in_loop_outer then 1 else Typing_alias.get_depth (pos, st) in let max_number_of_iterations = Option.value ~default:alias_depth (Env.get_tcopt env |> TCO.loop_iteration_upper_bound) in let env = { env with in_loop = true } in let continuations_converge env old_conts new_conts = CMap.for_all2 ~f:(fun _ old_cont_entry new_cont_entry -> Typing_per_cont_ops.is_sub_opt_entry SubType.is_sub_type env new_cont_entry old_cont_entry) old_conts new_conts in let rec loop env n = (* Remember the old environment *) let old_conts = env.lenv.per_cont_env in let (env, result) = f env in let new_conts = env.lenv.per_cont_env in (* Finish if we reach the bound, or if the environments match *) if Int.equal n max_number_of_iterations || continuations_converge env old_conts new_conts then let () = log_iteration_count env pos n in let env = { env with in_loop = in_loop_outer } in (env, result) else loop env (n + 1) in loop env 1 in let env = Env.open_tyvars env pos in (fun (env, tb) -> let ((env, ty_err_opt), res) = (Typing_solver.close_tyvars_and_solve env, tb) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (env, res)) @@ match st with | Fallthrough -> let env = LEnv.move_and_merge_next_in_cont ~join_pos:pos env C.Fallthrough in (env, Aast.Fallthrough) | Noop -> (env, Aast.Noop) | AssertEnv _ -> (env, Aast.Noop) | Yield_break -> let env = LEnv.move_and_merge_next_in_cont ~join_pos:pos env C.Exit in (env, Aast.Yield_break) | Expr e -> let (env, te, _) = expr env e in let env = if TFTerm.typed_expression_exits te then LEnv.move_and_merge_next_in_cont env ~join_pos:pos C.Exit else env in (env, Aast.Expr te) | If (e, b1, b2) -> let assert_refinement_env = assert_env_blk ~pos ~at:`Start Aast.Refinement in let (env, te, _) = expr env e in let (env, tb1, tb2) = branch ~join_pos:pos env (fun env -> let (env, { lset; pkgs }) = condition env true te in let (env, b1) = Env.with_packages env pkgs @@ fun env -> let refinement_map = refinement_annot_map env lset in let (env, b1) = block env b1 in let b1 = assert_refinement_env refinement_map b1 in (env, b1) in let rec get_loaded_packages_from_invariant (_, _, e) acc = match e with | Aast.Package (_, pkg) -> SSet.add pkg acc | Aast.Binop { bop = Ast_defs.Ampamp; lhs; rhs } -> get_loaded_packages_from_invariant lhs acc |> get_loaded_packages_from_invariant rhs | _ -> acc in (* Since `invariant(cond, msg)` is typed as `if (!cond) { invariant_violation(msg) }`, revisit the branch and harvest packages loaded in `cond` if the branch contains an invariant statement. *) let env = List.fold ~init:env b1 ~f:(fun env (_, tst) -> match (te, tst) with | ( (_, _, Aast.Unop (Ast_defs.Unot, e)), Aast.Expr (_, _, Call { func = (_, _, Id (_, s)); _ }) ) when String.equal s SN.AutoimportedFunctions.invariant_violation -> get_loaded_packages_from_invariant e SSet.empty |> Env.load_packages env | _ -> env) in (env, b1)) (fun env -> let (env, { lset; pkgs }) = condition env false te in Env.with_packages env pkgs @@ fun env -> let refinement_map = refinement_annot_map env lset in let (env, b2) = block env b2 in let b2 = assert_refinement_env refinement_map b2 in (env, b2)) in (* TODO TAST: annotate with joined types *) (env, Aast.If (te, tb1, tb2)) | Return None -> let env = Typing_return.check_inout_return pos env in let rty = MakeType.void (Reason.Rwitness pos) in let { Typing_env_return_info.return_type = expected_return; _ } = Env.get_return env in let expected_return = Typing_return.strip_awaitable (Env.get_fn_kind env) env expected_return in let env = match Env.get_fn_kind env with | Ast_defs.FGenerator | Ast_defs.FAsyncGenerator -> env | _ -> Typing_return.implicit_return env pos ~expected:expected_return.et_type ~actual:rty ~hint_pos:None ~is_async:false in let env = LEnv.move_and_merge_next_in_cont ~join_pos:pos env C.Exit in (env, Aast.Return None) | Return (Some e) -> let env = Typing_return.check_inout_return pos env in let (_, expr_pos, _) = e in let Typing_env_return_info.{ return_type; return_disposable } = Env.get_return env in let return_type = Typing_return.strip_awaitable (Env.get_fn_kind env) env return_type in let expected = Some (ExpectedTy.make_and_allow_coercion expr_pos Reason.URreturn return_type) in if return_disposable then enforce_return_disposable env e; let (env, te, rty) = expr ~is_using_clause:return_disposable ?expected env e in (* This is a unify_error rather than a return_type_mismatch because the return * statement is the problem, not the return type itself. *) let (env, ty_err_opt) = Typing_coercion.coerce_type expr_pos Reason.URreturn env rty return_type Typing_error.Callback.unify_error in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let ty_mismatch_opt = mk_ty_mismatch_opt rty return_type.et_type ty_err_opt in let env = LEnv.move_and_merge_next_in_cont ~join_pos:pos env C.Exit in (env, Aast.Return (Some (hole_on_ty_mismatch ~ty_mismatch_opt te))) | Do (b, e) -> (* NOTE: leaks scope as currently implemented; this matches the behavior in naming (cf. `do_stmt` in naming/naming.ml). *) let (env, (tb, te)) = LEnv.stash_and_do env [C.Continue; C.Break; C.Do] (fun env -> let env = LEnv.save_and_merge_next_in_cont ~join_pos:pos env C.Do in let (env, _) = block env b in (* saving the locals in continue here even if there is no continue * statement because they must be merged at the end of the loop, in * case there is no iteration *) let env = LEnv.save_and_merge_next_in_cont ~join_pos:pos env C.Continue in let (env, tb) = infer_loop env (fun env -> let env = LEnv.update_next_from_conts ~join_pos:pos env [C.Continue; C.Next] in (* The following is necessary in case there is an assignment in the * expression *) let (env, te, _) = expr env e in let (env, { pkgs; _ }) = condition env true te in Env.with_packages env pkgs @@ fun env -> let env = LEnv.update_next_from_conts ~join_pos:pos env [C.Do; C.Next] in let (env, tb) = block env b in (env, tb)) in let env = LEnv.update_next_from_conts ~join_pos:pos env [C.Continue; C.Next] in let (env, te, _) = expr env e in let (env, _) = condition env false te in let env = LEnv.update_next_from_conts ~join_pos:pos env [C.Break; C.Next] in (env, (tb, te))) in (env, Aast.Do (tb, te)) | While (e, b) -> let (env, (te, tb, refinement_map)) = LEnv.stash_and_do env [C.Continue; C.Break] (fun env -> let env = LEnv.save_and_merge_next_in_cont ~join_pos:pos env C.Continue in let (env, tb) = infer_loop env (fun env -> let env = LEnv.update_next_from_conts ~join_pos:pos env [C.Continue; C.Next] in let join_map = annot_map env in (* The following is necessary in case there is an assignment in the * expression *) let (env, te, _) = expr env e in let (env, { lset; pkgs }) = condition env true te in Env.with_packages env pkgs @@ fun env -> let refinement_map = refinement_annot_map env lset in (* TODO TAST: avoid repeated generation of block *) let (env, tb) = block env b in (* Annotate loop body with join and refined environments *) let assert_env_blk = assert_env_blk ~pos ~at:`Start in let tb = assert_env_blk Aast.Refinement refinement_map tb in let tb = assert_env_blk Aast.Join join_map tb in (env, tb)) in let env = LEnv.update_next_from_conts ~join_pos:pos env [C.Continue; C.Next] in let (env, te, _) = expr env e in let (env, { lset; _ }) = condition env false te in let refinement_map_at_exit = refinement_annot_map env lset in let env = LEnv.update_next_from_conts env ~join_pos:pos [C.Break; C.Next] in (env, (te, tb, refinement_map_at_exit))) in let while_st = Aast.While (te, tb) in (* Export the refined environment after the exit condition holds *) let while_st = assert_env_stmt ~pos ~at:`End Aast.Refinement refinement_map while_st in (env, while_st) | Using { us_has_await = has_await; us_exprs = (loc, using_clause); us_block = using_block; us_is_block_scoped; } -> let (env, typed_using_clause, using_vars) = check_using_clause env has_await using_clause in let (env, typed_using_block) = block env using_block in (* Remove any using variables from the environment, as they should not * be in scope outside the block *) let env = List.fold_left using_vars ~init:env ~f:Env.unset_local in ( env, Aast.Using Aast. { us_has_await = has_await; us_exprs = (loc, typed_using_clause); us_block = typed_using_block; us_is_block_scoped; } ) | For (e1, e2, e3, b) -> let e2 = match e2 with | Some e2 -> e2 | None -> ((), Pos.none, True) in let (env, (te1, te2, te3, tb, refinement_map)) = LEnv.stash_and_do env [C.Continue; C.Break] (fun env -> (* For loops leak their initializer, but nothing that's defined in the body *) let (env, te1, _) = exprs env e1 in (* initializer *) let env = LEnv.save_and_merge_next_in_cont ~join_pos:pos env C.Continue in let (env, (tb, te3)) = infer_loop env (fun env -> (* The following is necessary in case there is an assignment in the * expression *) let (env, te2, _) = expr env e2 in let (env, { lset; pkgs }) = condition env true te2 in Env.with_packages env pkgs @@ fun env -> let refinement_map = refinement_annot_map env lset in let (env, tb) = block env b in let env = LEnv.update_next_from_conts ~join_pos:pos env [C.Continue; C.Next] in let join_map = annot_map env in let (env, te3, _) = exprs env e3 in (* Export the join and refinement environments *) let assert_env_blk = assert_env_blk ~pos ~at:`Start in let tb = assert_env_blk Aast.Refinement refinement_map tb in let tb = assert_env_blk Aast.Join join_map tb in (env, (tb, te3))) in let env = LEnv.update_next_from_conts ~join_pos:pos env [C.Continue; C.Next] in let (env, te2, _) = expr env e2 in let (env, { lset; _ }) = condition env false te2 in let refinement_map_at_exit = refinement_annot_map env lset in let env = LEnv.update_next_from_conts ~join_pos:pos env [C.Break; C.Next] in (env, (te1, te2, te3, tb, refinement_map_at_exit))) in let for_st = Aast.For (te1, Some te2, te3, tb) in let for_st = assert_env_stmt ~pos ~at:`End Aast.Refinement refinement_map for_st in (env, for_st) | Switch (((_, pos, _) as e), cl, dfl) -> let (env, te, ty) = expr env e in (* NB: A 'continue' inside a 'switch' block is equivalent to a 'break'. * See the note in * http://php.net/manual/en/control-structures.continue.php *) let (env, (te, tcl, tdfl)) = LEnv.stash_and_do env [C.Continue; C.Break] (fun env -> let parent_locals = LEnv.get_all_locals env in let (env, tcl, tdfl) = case_list parent_locals ty env pos cl dfl in let env = LEnv.update_next_from_conts ~join_pos:pos env [C.Continue; C.Break; C.Next] in (env, (te, tcl, tdfl))) in (env, Aast.Switch (te, tcl, tdfl)) | Foreach (e1, e2, b) -> (* It's safe to do foreach over a disposable, as no leaking is possible *) let (env, te1, ty1) = expr ~accept_using_var:true env e1 in let (env, (te1, te2, tb)) = LEnv.stash_and_do env [C.Continue; C.Break] (fun env -> let env = LEnv.save_and_merge_next_in_cont ~join_pos:pos env C.Continue in let (_, p1, _) = e1 in let ((env, ty_err_opt), tk, tv, ty_mismatch_opt) = as_expr env ty1 p1 e2 in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let (env, (te2, tb)) = infer_loop env (fun env -> let env = LEnv.update_next_from_conts ~join_pos:pos env [C.Continue; C.Next] in let join_map = annot_map env in let (env, te2) = bind_as_expr env p1 tk tv e2 in let (env, tb) = block env b in (* Export the join environment *) let tb = assert_env_blk ~pos ~at:`Start Aast.Join join_map tb in (env, (te2, tb))) in let env = LEnv.update_next_from_conts ~join_pos:pos env [C.Continue; C.Break; C.Next] in (env, (hole_on_ty_mismatch ~ty_mismatch_opt te1, te2, tb))) in (env, Aast.Foreach (te1, te2, tb)) | Try (tb, cl, fb) -> let (env, ttb, tcl, tfb) = try_catch ~join_pos:pos env tb cl fb in (env, Aast.Try (ttb, tcl, tfb)) | Awaitall (el, b) -> let env = might_throw ~join_pos:pos env in let (env, el) = List.fold_left el ~init:(env, []) ~f:(fun (env, tel) (e1, e2) -> let (env, te2, ty2) = expr env e2 ~allow_awaitable:true in let (_, pos2, _) = e2 in let (env, ty2) = Async.overload_extract_from_awaitable env ~p:pos2 ty2 in match e1 with | Some e1 -> let pos = fst e1 in let (env, _, _, ty_mismatch_opt) = assign pos env ((), pos, Lvar e1) pos2 ty2 in (env, (Some e1, hole_on_ty_mismatch ~ty_mismatch_opt te2) :: tel) | None -> (env, (None, te2) :: tel)) in let (env, b) = block env b in (env, Aast.Awaitall (el, b)) | Throw e -> let (_, p, _) = e in let (env, te, ty) = expr env e in let (env, ty_err_opt) = coerce_to_throwable p env ty in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let env = move_and_merge_next_in_catch ~join_pos:pos env in (env, Aast.Throw te) | Continue -> let env = LEnv.move_and_merge_next_in_cont ~join_pos:pos env C.Continue in (env, Aast.Continue) | Break -> let env = LEnv.move_and_merge_next_in_cont ~join_pos:pos env C.Break in (env, Aast.Break) | Declare_local ((p, lvar), hint, exp) -> let hint = if TypecheckerOptions.everything_sdt env.genv.tcopt then (fst hint, Hlike hint) else hint in let ((env, err), hty) = Phase.localize_hint_no_subst env ~ignore_errors:false hint in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) err; let (is_defined, env, te, ety) = match exp with | None -> (false, env, None, Typing_make_type.nothing (Reason.Rwitness p)) | Some exp -> let (env, te, ety) = expr env exp in (true, env, Some te, ety) in let env = set_valid_rvalue ~is_defined p env lvar (Some hty) ety in (env, Aast.Declare_local ((p, lvar), hint, te)) | Match _ -> failwith "TODO(jakebailey): match statements" | Block _ | Markup _ -> failwith "Unexpected nodes in AST. These nodes should have been removed in naming." and finally_w_cont fb env ctx = (* The only locals in scope are the ones from the current continuation *) let env = Env.env_with_locals env @@ CMap.singleton C.Next ctx in let (env, _tfb) = block env fb in (env, LEnv.get_all_locals env) and finally ~join_pos env fb = match fb with | [] -> let env = LEnv.update_next_from_conts ~join_pos env [C.Next; C.Finally] in (env, []) | _ -> let initial_locals = LEnv.get_all_locals env in (* First typecheck the finally block against all relevant continuations merged * together. The relevant continuations are those corresponding to statements * which will cause control flow to jump to the finally block, e.g. `break`. * During this phase, record errors found in the finally block, but discard * the resulting environment. *) let env = LEnv.update_next_from_conts ~join_pos env Typing_per_cont_env.continuations_for_finally in let (env, tfb) = block env fb in let env = Env.env_with_locals env initial_locals in (* Second, typecheck the finally block once against each continuation. This * helps be more clever about what each continuation will be after the * finally block. * We don't want to record errors during this phase, because certain types * of errors will fire wrongly. For example, if $x is nullable in some * continuations but not in others, then we must use `?->` on $x, but an * error will fire when typechecking the finally block againts continuations * where $x is non-null. *) let finally_w_cont env _key = finally_w_cont fb env in let (env, locals_map) = Errors.ignore_ (fun () -> CMap.map_env finally_w_cont env initial_locals) in let union env _key = LEnv.union_contextopts ~join_pos env in let (env, locals) = Try.finally_merge union env locals_map in (Env.env_with_locals env locals, tfb) and try_catch ~join_pos env tb cl fb = let parent_locals = LEnv.get_all_locals env in (* If any `break`, `continue`, `exit`, etc. happens directly inside the `try` * block, they will cause control flow to go to the `finally` block first. * I.o.w. the `finally` block is typechecked with the corresponding continuations. * Therefore we need to stash the corresponding pre-existing continuations * so that we don't typecheck the finally block with those. *) let env = LEnv.drop_conts env Typing_per_cont_env.continuations_for_finally in let (env, (ttb, tcb)) = Env.in_try env (fun env -> let (env, ttb) = block env tb in let env = LEnv.move_and_merge_next_in_cont ~join_pos env C.Finally in let catchctx = LEnv.get_cont_option env C.Catch in let (env, lenvtcblist) = List.map_env env ~f:(catch catchctx) cl in let (lenvl, tcb) = List.unzip lenvtcblist in let env = LEnv.union_lenv_list ~join_pos env env.lenv lenvl in let env = LEnv.move_and_merge_next_in_cont ~join_pos env C.Finally in (env, (ttb, tcb))) in let (env, tfb) = finally ~join_pos env fb in let env = LEnv.update_next_from_conts ~join_pos env [C.Finally] in let env = LEnv.drop_cont env C.Finally in let env = LEnv.restore_and_merge_conts_from ~join_pos env parent_locals Typing_per_cont_env.continuations_for_finally in (env, ttb, tcb, tfb) and case_list parent_locals ty env switch_pos cl dfl = let initialize_next_cont env = let env = LEnv.restore_conts_from env parent_locals [C.Next] in let env = LEnv.update_next_from_conts ~join_pos:switch_pos env [C.Next; C.Fallthrough] in LEnv.drop_cont env C.Fallthrough in let check_fallthrough env switch_pos case_pos ~next_pos block ~last ~is_default = if (not (List.is_empty block)) && not last then match LEnv.get_cont_option env C.Next with | Some _ -> Errors.add_error Nast_check_error.( to_user_error @@ if is_default then Default_fallthrough switch_pos else Case_fallthrough { switch_pos; case_pos; next_pos }) | None -> () in let env = (* below, we try to find out if the switch is exhaustive *) let has_default = Option.is_some dfl in let ((env, ty_err_opt), ty) = (* If it hasn't got a default clause then we need to solve type variables * in order to check for an enum *) if has_default then let (env, ty) = Env.expand_type env ty in ((env, None), ty) else Typing_solver.expand_type_and_solve env ~description_of_expected:"a value" switch_pos ty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (* leverage that enums are checked for exhaustivity *) let is_enum = let top_type = MakeType.class_type Reason.Rnone SN.Classes.cHH_BuiltinEnum [MakeType.mixed Reason.Rnone] in SubType.is_sub_type_for_union env ty top_type in (* register that the runtime may throw in case we cannot prove that the switch is exhaustive *) if has_default || is_enum then env else might_throw ~join_pos:switch_pos env in let (env, tcl) = let rec case_list env = function | [] -> (env, []) | (((_, pos, _) as e), b) :: rl -> let env = initialize_next_cont env in let (env, te, _) = expr env e ~allow_awaitable:(*?*) false in let (env, tb) = block env b in let last = List.is_empty rl && Option.is_none dfl in let next_pos = match rl with | ((_, next_pos, _), _) :: _ -> Some next_pos | [] -> None in check_fallthrough env switch_pos pos ~next_pos b ~last ~is_default:false; let (env, tcl) = case_list env rl in (env, (te, tb) :: tcl) in case_list env cl in let (env, tdfl) = match dfl with | None -> (env, None) | Some (pos, b) -> let env = initialize_next_cont env in let (env, tb) = block env b in check_fallthrough env switch_pos pos ~next_pos:None b ~last:true ~is_default:true; (env, Some (pos, tb)) in (env, tcl, tdfl) and catch catchctx env (sid, exn_lvar, b) = let env = LEnv.replace_cont env C.Next catchctx in let cid = CI sid in let ety_p = fst sid in let (env, _, _, _) = instantiable_cid ety_p env cid [] in let (env, _tal, _te, ety) = class_expr env [] ((), ety_p, cid) in let (env, ty_err_opt) = coerce_to_throwable ety_p env ety in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let (p, x) = exn_lvar in let env = set_valid_rvalue ~is_defined:true p env x None ety in let (env, tb) = block env b in (env, (env.lenv, (sid, exn_lvar, tb))) and bind_as_expr env p ty1 ty2 aexpr = match aexpr with | As_v ev -> let (env, te, _, _) = assign p env ev p ty2 in (env, Aast.As_v te) | Await_as_v (p, ev) -> let (env, te, _, _) = assign p env ev p ty2 in (env, Aast.Await_as_v (p, te)) | As_kv ((_, p, Lvar ((_, k) as id)), ev) -> let env = set_valid_rvalue ~is_defined:true p env k None ty1 in let (env, te, _, _) = assign p env ev p ty2 in let (env, tk) = TUtils.make_simplify_typed_expr env p ty1 (Aast.Lvar id) in (env, Aast.As_kv (tk, te)) | As_kv ((_, p, (Lplaceholder _ as k)), ev) -> let (env, te, _, _) = assign p env ev p ty2 in let (env, tk) = TUtils.make_simplify_typed_expr env p ty1 k in (env, Aast.As_kv (tk, te)) | Await_as_kv (p, (_, p1, Lvar ((_, k) as id)), ev) -> let env = set_valid_rvalue ~is_defined:true p env k None ty1 in let (env, te, _, _) = assign p env ev p ty2 in let (env, tk) = TUtils.make_simplify_typed_expr env p1 ty1 (Aast.Lvar id) in (env, Aast.Await_as_kv (p, tk, te)) | Await_as_kv (p, (_, p1, (Lplaceholder _ as k)), ev) -> let (env, te, _, _) = assign p env ev p ty2 in let (env, tk) = TUtils.make_simplify_typed_expr env p1 ty1 k in (env, Aast.Await_as_kv (p, tk, te)) | _ -> (* TODO Probably impossible, should check that *) assert false and expr ?(expected : ExpectedTy.t option) ?(accept_using_var = false) ?(is_using_clause = false) ?(valkind = Other) ?(check_defined = true) ?in_await ~allow_awaitable env ((_, p, _) as e) = try begin match expected with | None -> () | Some ExpectedTy.{ reason = r; ty = { et_type = ty; _ }; _ } -> Typing_log.( log_with_level env "typing" ~level:1 (fun () -> log_types (Pos_or_decl.of_raw_pos p) env [ Log_head ( "Typing.expr " ^ Reason.string_of_ureason r, [Log_type ("expected_ty", ty)] ); ])) end; raw_expr ~accept_using_var ~is_using_clause ~valkind ~check_defined ?in_await ?expected ~allow_awaitable env e with | Inf.InconsistentTypeVarState _ as exn -> (* we don't want to catch unwanted exceptions here, eg Timeouts *) Errors.exception_occurred p (Exception.wrap exn); expr_error env p e (*let (env, ty) = Env.fresh_type_error env p in make_result env p (invalid_expr_ env p) @@ ty*) (* Some (legacy) special functions are allowed in initializers, therefore treat them as pure and insert the matching capabilities. *) and expr_with_pure_coeffects ?(expected : ExpectedTy.t option) ~allow_awaitable env e = let (_, p, _) = e in let pure = MakeType.mixed (Reason.Rwitness p) in let (env, (te, ty)) = with_special_coeffects env pure pure @@ fun env -> expr env e ?expected ~allow_awaitable |> triple_to_pair in (env, te, ty) and raw_expr ?(accept_using_var = false) ?(is_using_clause = false) ?(expected : ExpectedTy.t option) ?lhs_of_null_coalesce ?(valkind = Other) ?(check_defined = true) ?in_await ~allow_awaitable env e = let (_, p, _) = e in debug_last_pos := p; expr_ ~accept_using_var ~is_using_clause ?expected ?lhs_of_null_coalesce ?in_await ~allow_awaitable ~valkind ~check_defined env e and lvalue env e = expr_ ~valkind:Lvalue ~check_defined:false env e ~allow_awaitable:(*?*) false and lvalues env el = match el with | [] -> (env, [], []) | e :: el -> let (env, te, ty) = lvalue env e in let (env, tel, tyl) = lvalues env el in (env, te :: tel, ty :: tyl) (* $x ?? 0 is handled similarly to $x ?: 0, except that the latter will also * look for sketchy null checks in the condition. *) (* TODO TAST: type refinement should be made explicit in the typed AST *) and eif env ~(expected : ExpectedTy.t option) ?in_await p c e1 e2 = let (env, tc, tyc) = raw_expr env c ~allow_awaitable:false in let parent_lenv = env.lenv in let (env, _) = condition env true tc in let (env, te1, ty1) = match e1 with | None -> let (env, ty) = Typing_solver.non_null env (Pos_or_decl.of_raw_pos p) tyc in (env, None, ty) | Some e1 -> let (env, te1, ty1) = expr ?expected ?in_await env e1 ~allow_awaitable:true in (env, Some te1, ty1) in let lenv1 = env.lenv in let env = { env with lenv = parent_lenv } in let (env, _) = condition env false tc in let (env, te2, ty2) = expr ?expected ?in_await env e2 ~allow_awaitable:true in let lenv2 = env.lenv in let env = LEnv.union_lenvs ~join_pos:p env parent_lenv lenv1 lenv2 in let (env, ty) = Union.union ~approx_cancel_neg:true env ty1 ty2 in make_result env p (Aast.Eif (tc, te1, te2)) ty and exprs ?(accept_using_var = false) ?(expected : ExpectedTy.t option) ?(valkind = Other) ?(check_defined = true) ~allow_awaitable env el = match el with | [] -> (env, [], []) | e :: el -> let (env, te, ty) = expr ~accept_using_var ?expected ~valkind ~check_defined env e ~allow_awaitable in let (env, tel, tyl) = exprs ~accept_using_var ?expected ~valkind ~check_defined env el ~allow_awaitable in (env, te :: tel, ty :: tyl) and argument_list_exprs expr_cb env el = match el with | [] -> (env, [], []) | (pk, e) :: el -> let (env, te, ty) = expr_cb env e in let (env, tel, tyl) = argument_list_exprs expr_cb env el in (env, (pk, te) :: tel, ty :: tyl) and exprs_expected (pos, ur, expected_tyl) env el = match (el, expected_tyl) with | ([], _) -> (env, [], []) | (e :: el, expected_ty :: expected_tyl) -> let expected = ExpectedTy.make pos ur expected_ty in let (env, te, ty) = expr ~expected env e ~allow_awaitable:(*?*) false in let (env, tel, tyl) = exprs_expected (pos, ur, expected_tyl) env el in (env, te :: tel, ty :: tyl) | (el, []) -> exprs env el ~allow_awaitable:(*?*) false and coerce_nonlike_and_like ~coerce_for_op ~coerce env pos reason ty ety ety_like = let (env1, err1) = Typing_coercion.coerce_type ~coerce_for_op ~coerce pos reason env ty ety Typing_error.Callback.unify_error in begin match err1 with | None -> (env1, None, false) | Some _ -> (* Now check against the pessimised type *) let (env2, err2) = Typing_coercion.coerce_type ~coerce_for_op ~coerce pos reason env ty ety_like Typing_error.Callback.unify_error in (env2, err2, true) end and expr_ ?(expected : ExpectedTy.t option) ?(accept_using_var = false) ?(is_using_clause = false) ?lhs_of_null_coalesce ?in_await ~allow_awaitable ~(valkind : valkind) ~check_defined env ((_, p, e) as outer) = let env = Env.open_tyvars env p in (fun (env, te, ty) -> let (env, ty_err_opt) = Typing_solver.close_tyvars_and_solve env in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (env, te, ty)) @@ let expr ?(allow_awaitable = allow_awaitable) = expr ~check_defined ~allow_awaitable in let exprs = exprs ~check_defined ~allow_awaitable in let raw_expr ?(allow_awaitable = allow_awaitable) = raw_expr ~check_defined ~allow_awaitable in (* * Given an expected type for elements (as extracted from a parameter or return hint, * or explicit type argument), a list of expressions, and a function that infers * the type of an element, infer an element type for the whole collection. * * explicit is true if the expected type is just the explicit type argument * can_pessimise is true if this is a pessimisable builtin (e.g. Vector) * bound is the bound on the type parameter if present (only ever arraykey) *) let infer_element_type_for_collection ~(expected : ExpectedTy.t option) ~explicit ~reason ~can_pessimise ~bound ~use_pos r env exprs expr_infer = (* Is this a pessimisable builtin constructor *and* the flag is set? *) let do_pessimise_builtin = can_pessimise && TCO.pessimise_builtins (Env.get_tcopt env) in (* Under Sound Dynamic, for pessimisable builtins we add a like to the expected type * that is used to check the element expressions. * * For non-pessimised builtins we also do this if the type is explicit * but if an element actually has a like type then this must be reflected * in the inferred type argument. * e.g. contrast Vector<int>{ $li } which has type Vector<int> * and Pair<int,string> { $li, "A" } which has type Pair<~int,string> *) let non_pessimised_builtin_explicit = TCO.pessimise_builtins (Env.get_tcopt env) && explicit && not do_pessimise_builtin in (* The supertype is the type argument of the result. * If there is an expected type then it's just this, but we might have to * add a like to it if it's the explicit type argument and we have a non-pessimised builtin. * Otherwise, we generate a fresh type variable and generate constraints against it. *) let (env, expected_with_implicit_like, supertype) = match expected with | Some ExpectedTy.{ pos; ty = ety; reason; _ } -> begin (* We add an implicit like type to the expected type of elements if * There is an explicit type argument on the collection constructor, or * This is a pessimised builtin (e.g. Vector), or * There is a runtime-enforced bound (because it does no harm to allow dynamic) *) let (env, like_ty) = if TCO.enable_sound_dynamic (Env.get_tcopt env) && (explicit || do_pessimise_builtin || Option.is_some bound) then Typing_array_access.pessimise_type env ety.et_type else (env, ety.et_type) in let expected_with_implicit_like = Some ExpectedTy.(make pos reason like_ty) in let (env, supertype) = if explicit then (env, ety.et_type) else (* Extract the underlying type from the expected type. * If it's an intersection, pick up the type under the like * e.g. For ~int & arraykey we want to pick up int * Otherwise, just strip the like. *) match get_node ety.et_type with | Tintersection tyl -> let (had_dynamic, tyl) = List.map_env false tyl ~f:(fun had_dynamic ty -> match TUtils.try_strip_dynamic env ty with | None -> (had_dynamic, ty) | Some ty -> (true, ty)) in if had_dynamic then (* Put the intersection back together without the dynamic *) let (env, ty) = Inter.simplify_intersections env (mk (get_reason ety.et_type, Tintersection tyl)) in (env, ty) else (env, ety.et_type) | _ -> (env, TUtils.strip_dynamic env ety.et_type) in (env, expected_with_implicit_like, supertype) end | None -> let (env, ty) = Env.fresh_type_reason env use_pos r in (env, None, ty) in (* Actually type the elements, given the expected element type *) let (env, exprs_and_tys) = List.map_env env exprs ~f:(expr_infer ~expected:expected_with_implicit_like) in let (exprs, tys) = List.unzip exprs_and_tys in let coerce_for_op = Option.is_some bound && not (TCO.pessimise_builtins (Env.get_tcopt env)) in (* Take the inferred type ty of each value and assert that it's a subtype * of the (optionally with like type added) result type argument. *) let subtype_value env ty = let (env, ty_err_opt, used_dynamic) = if non_pessimised_builtin_explicit then (* We have an explicit type argument for a non-pessimised builtin. * We try first to check the value type against the non-pessimised type argument. * If that fails, we try it against a pessimised type argument. *) match expected_with_implicit_like with | Some ExpectedTy.{ pos; reason; ty = ety_like; coerce; _ } -> coerce_nonlike_and_like ~coerce_for_op ~coerce env pos reason ty (MakeType.unenforced supertype) ety_like (* Shouldn't happen *) | _ -> (env, None, false) else let (env, ety) = if coerce_for_op then (env, MakeType.enforced supertype) else match expected_with_implicit_like with | None -> let (env, supertype) = if can_pessimise then Typing_array_access.maybe_pessimise_type env supertype else (env, supertype) in (env, MakeType.unenforced supertype) | Some e -> (env, e.ExpectedTy.ty) in let (env, ty_err_opt) = Typing_coercion.coerce_type ~coerce_for_op ~coerce:None use_pos reason env ty ety Typing_error.Callback.unify_error in (env, ty_err_opt, false) in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); (env, ty_err_opt, used_dynamic) in let (env, rev_ty_err_opts, used_dynamic) = List.fold_left tys ~init:(env, [], false) ~f:(fun (env, errs, used_dynamic) ty -> let (env, ty_err_opt, u) = subtype_value env ty in match ty_err_opt with | None -> (env, None :: errs, u || used_dynamic) | Some _ -> (env, Some (ty, supertype) :: errs, u || used_dynamic)) in (* used_dynamic is set if we had an explicit type argument t that is not * a like type, but one of the inferred element types is of the form ~u. * In this case we infer ~t as the element type for the whole collection. *) let (env, result_type) = if used_dynamic then Typing_array_access.pessimise_type env supertype else (env, supertype) in let (env, result_type) = match bound with | Some ty -> Inter.intersect env ~r:(get_reason ty) ty result_type | None -> (env, result_type) in let exprs = List.map2_exn ~f:(fun te ty_mismatch_opt -> match te with | (_, _, Hole _) -> te | _ -> hole_on_ty_mismatch te ~ty_mismatch_opt) exprs (List.rev rev_ty_err_opts) in (env, exprs, result_type) in let check_collection_tparams env name tys = (* varrays and darrays are not classes but they share the same constraints with vec and dict respectively *) let name = if String.equal name SN.Typehints.varray then SN.Collections.cVec else if String.equal name SN.Typehints.darray then SN.Collections.cDict else name in (* Class retrieval always succeeds because we're fetching a collection decl from an HHI file. *) match Env.get_class env name with | Some class_ -> let ety_env = { (empty_expand_env_with_on_error (Env.invalid_type_hint_assert_primary_pos_in_current_decl env)) with substs = TUtils.make_locl_subst_for_class_tparams class_ tys; } in let (env, ty_err_opt) = Phase.check_tparams_constraints ~use_pos:p ~ety_env env (Cls.tparams class_) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; env | None -> let desc = "Missing collection decl during type parameter check" and telemetry = Telemetry.(create () |> string_ ~key:"class name" ~value:name) in Errors.invariant_violation p telemetry desc ~report_to_user:false; (* Continue typechecking without performing the check on a best effort basis. *) env in List.iter ~f:(Typing_error_utils.add_typing_error ~env) @@ Typing_type_wellformedness.expr env outer; match e with | Import _ | Collection _ -> failwith "AST should not contain these nodes" | Hole (e, _, _, _) -> expr_ ?expected ~accept_using_var ~is_using_clause ?lhs_of_null_coalesce ?in_await ~allow_awaitable ~valkind ~check_defined env e | Invalid expr_opt -> let ty = MakeType.nothing @@ Reason.Rinvalid in let expr_opt = Option.map ~f:(Aast.map_expr (fun _ -> ty) (fun _ -> Tast.dummy_saved_env)) expr_opt in let expr_ = Aast.Invalid expr_opt in make_result env p expr_ ty | Omitted -> (* If an expression is omitted in an lvalue position, currently only * possible in a list destructuring construct such as `list(,$x) = $y;`, * we want to assign anything *to* the index of the omitted expression, * so give it type `mixed`. If an expression is omitted in an rvalue position, * currently only constant declarations (e.g. in hhi files), then we want * to be to assign *from* the expression, so give it type `nothing`. *) let ty = match valkind with | Lvalue | Lvalue_subexpr -> MakeType.mixed (Reason.Rwitness p) | Other -> MakeType.nothing (Reason.Rwitness p) in make_result env p Aast.Omitted ty | Varray (th, el) | ValCollection (_, th, el) -> let ( get_expected_kind, name, subtype_val, make_expr, make_ty, key_bound, pessimisable_builtin ) = match e with | ValCollection ((kind_pos, kind), _, _) -> let class_name = Nast.vc_kind_to_name kind in let (subtype_val, key_bound, pessimisable_builtin) = match kind with | Set | ImmSet -> ( arraykey_value p class_name true, Some (MakeType.arraykey (Reason.Rtype_variable_generics (p, "Tk", strip_ns class_name))), true ) | Keyset -> ( arraykey_value p class_name true, Some (MakeType.arraykey (Reason.Rtype_variable_generics (p, "Tk", strip_ns class_name))), false ) | Vector | ImmVector -> (array_value, None, true) | Vec -> (array_value, None, false) in ( get_vc_inst env p kind, class_name, subtype_val, (fun th elements -> Aast.ValCollection ((kind_pos, kind), th, elements)), (fun value_ty -> MakeType.class_type (Reason.Rwitness p) class_name [value_ty]), key_bound, pessimisable_builtin ) | Varray _ -> ( get_vc_inst env p Vec, "varray", array_value, (fun th elements -> Aast.ValCollection ((p, Vec), th, elements)), (fun value_ty -> MakeType.vec (Reason.Rwitness p) value_ty), None, false ) | _ -> (* The parent match makes this case impossible *) failwith "impossible match case" in (* Use expected type to determine expected element type *) let (env, elem_expected, th) = match th with | Some (_, tv) -> let ((env, ty_err_opt), tv, tv_expected) = localize_targ env tv in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let env = check_collection_tparams env name [fst tv] in (env, Some tv_expected, Some tv) | None -> begin match expand_expected_and_get_node ~pessimisable_builtin env expected with | (env, Some (pos, ur, _, ety, _)) -> begin match get_expected_kind ety with | Some (env, vty) -> (env, Some (ExpectedTy.make pos ur vty), None) | None -> (env, None, None) end | _ -> (env, None, None) end in let (env, tel, elem_ty) = infer_element_type_for_collection ~expected:elem_expected ~explicit:(Option.is_some th) ~use_pos:p ~reason:Reason.URvector ~can_pessimise:pessimisable_builtin ~bound:key_bound (Reason.Rtype_variable_generics (p, "T", strip_ns name)) env el subtype_val in make_result env p (make_expr th tel) (make_ty elem_ty) | Darray (th, l) | KeyValCollection (_, th, l) -> let (get_expected_kind, name, make_expr, make_ty, pessimisable_builtin) = match e with | KeyValCollection ((kind_pos, kind), _, _) -> let class_name = Nast.kvc_kind_to_name kind in ( get_kvc_inst env p kind, class_name, (fun th pairs -> Aast.KeyValCollection ((kind_pos, kind), th, pairs)), (fun k v -> MakeType.class_type (Reason.Rwitness p) class_name [k; v]), (match kind with | Dict -> false | _ -> true) ) | Darray _ -> let name = "darray" in ( get_kvc_inst env p Dict, name, (fun th pairs -> Aast.KeyValCollection ((p, Dict), th, pairs)), (fun k v -> MakeType.dict (Reason.Rwitness p) k v), false ) | _ -> (* The parent match makes this case impossible *) failwith "impossible match case" in (* Use expected type to determine expected key and value types *) let (env, kexpected, vexpected, th) = match th with | Some ((_, tk), (_, tv)) -> let ((env, ty_err_opt1), tk, tk_expected) = localize_targ env tk in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt1; let ((env, ty_err_opt2), tv, tv_expected) = localize_targ env tv in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt2; let env = check_collection_tparams env name [fst tk; fst tv] in (env, Some tk_expected, Some tv_expected, Some (tk, tv)) | _ -> begin (* no explicit typehint, fallback to supplied expect *) match expand_expected_and_get_node ~pessimisable_builtin env expected with | (env, Some (pos, reason, _, ety, _)) -> begin match get_expected_kind ety with | Some (env, kty, vty) -> let k_expected = ExpectedTy.make pos reason kty in let v_expected = ExpectedTy.make pos reason vty in (env, Some k_expected, Some v_expected, None) | None -> (env, None, None, None) end | _ -> (env, None, None, None) end in let (kl, vl) = List.unzip l in let r = Reason.Rtype_variable_generics (p, "Tk", strip_ns name) in let (env, tkl, k) = infer_element_type_for_collection ~expected:kexpected ~explicit:(Option.is_some th) ~use_pos:p ~reason:(Reason.URkey name) ~bound:(Some (MakeType.arraykey r)) ~can_pessimise:pessimisable_builtin r env kl (arraykey_value p name false) in let (env, tvl, v) = infer_element_type_for_collection ~expected:vexpected ~explicit:(Option.is_some th) ~use_pos:p ~reason:(Reason.URvalue name) ~can_pessimise:pessimisable_builtin ~bound:None (Reason.Rtype_variable_generics (p, "Tv", strip_ns name)) env vl array_value in let pairs = List.zip_exn tkl tvl in make_result env p (make_expr th pairs) (make_ty k v) | Clone e -> let (env, te, ty) = expr env e in (* Clone only works on objects; anything else fatals at runtime. * Constructing a call `e`->__clone() checks that `e` is an object and * checks coeffects on __clone *) let (_, pe, _) = e in let ((env, ty_err_opt), (tfty, _tal)) = TOG.obj_get ~obj_pos:pe ~is_method:true ~inst_meth:false ~meth_caller:false ~nullsafe:None ~coerce_from_ty:None ~explicit_targs:[] ~class_id:(CIexpr e) ~member_id:(p, SN.Members.__clone) ~on_error:Typing_error.Callback.unify_error env ty in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let (env, (_tel, _typed_unpack_element, _ty, _should_forget_fakes)) = call ~expected:None ~expr_pos:p ~recv_pos:p env tfty [] None in make_result env p (Aast.Clone te) ty | This -> if Option.is_none (Env.get_self_ty env) then Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.This_var_outside_class p); if Env.is_in_expr_tree env then Typing_error_utils.add_typing_error ~env Typing_error.(expr_tree @@ Primary.Expr_tree.This_var_in_expr_tree p); if not accept_using_var then check_escaping_var env (p, this); let ty = if check_defined then Env.get_local_check_defined env (p, this) else Env.get_local env this in let r = Reason.Rwitness p in (* $this isn't a typed local and so has no bound *) let ty = mk (r, get_node ty.Typing_local_types.ty) in make_result env p Aast.This ty | True -> make_result env p Aast.True (MakeType.bool (Reason.Rwitness p)) | False -> make_result env p Aast.False (MakeType.bool (Reason.Rwitness p)) (* TODO TAST: consider checking that the integer is in range. Right now * it's possible for HHVM to fail on well-typed Hack code *) | Int s -> make_result env p (Aast.Int s) (MakeType.int (Reason.Rwitness p)) | Float s -> make_result env p (Aast.Float s) (MakeType.float (Reason.Rwitness p)) (* TODO TAST: consider introducing a "null" type, and defining ?t to * be null | t *) | Null -> make_result env p Aast.Null (MakeType.null (Reason.Rwitness p)) | String s -> make_result env p (Aast.String s) (MakeType.string (Reason.Rwitness p)) | String2 idl -> let (env, tel) = string2 env idl in make_result env p (Aast.String2 tel) (MakeType.string (Reason.Rwitness p)) | PrefixedString (n, e) -> if String.( <> ) n "re" then ( Errors.experimental_feature p "String prefixes other than `re` are not yet supported."; expr_error env p outer ) else let (env, te, ty) = expr env e in let (_, pe, expr_) = e in let env = Typing_substring.sub_string pe env ty in (match expr_ with | String _ -> begin try make_result env p (Aast.PrefixedString (n, te)) (Typing_regex.type_pattern e) with | Pcre.Error (Pcre.BadPattern (s, i)) -> let reason = `bad_patt (s ^ " [" ^ string_of_int i ^ "]") in Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Bad_regex_pattern { pos = pe; reason }); expr_error env pe e | Typing_regex.Empty_regex_pattern -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Bad_regex_pattern { pos = pe; reason = `empty_patt }); expr_error env pe e | Typing_regex.Missing_delimiter -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Bad_regex_pattern { pos = pe; reason = `missing_delim }); expr_error env pe e | Typing_regex.Invalid_global_option -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Bad_regex_pattern { pos = pe; reason = `invalid_option }); expr_error env pe e end | String2 _ -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Re_prefixed_non_string { pos = pe; reason = `embedded_expr }); expr_error env pe e | _ -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Re_prefixed_non_string { pos = pe; reason = `non_string }); expr_error env pe e) | Id ((cst_pos, cst_name) as id) -> (match Env.get_gconst env cst_name with | None -> Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.Unbound_global cst_pos); let (env, ty) = Env.fresh_type_error env cst_pos in make_result env cst_pos (Aast.Id id) ty | Some const -> let ((env, ty_err_opt), ty) = Phase.localize_no_subst env ~ignore_errors:true const.cd_type in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; make_result env p (Aast.Id id) ty) | Method_caller (((pos, class_name) as pos_cname), meth_name) -> (* meth_caller('X', 'foo') desugars to: * $x ==> $x->foo() *) let class_ = Env.get_class env class_name in (match class_ with | None -> unbound_name env pos_cname outer | Some class_ -> (* Create a class type for the given object instantiated with unresolved * types for its type parameters. *) let () = if Ast_defs.is_c_trait (Cls.kind class_) then Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Meth_caller_trait { pos; trait_name = class_name }) in let (env, tvarl) = List.map_env env (Cls.tparams class_) ~f:(fun env _ -> Env.fresh_type env p) in let params = List.map (Cls.tparams class_) ~f:(fun { tp_name = (p, n); _ } -> (* TODO(T69551141) handle type arguments for Tgeneric *) MakeType.generic (Reason.Rwitness_from_decl p) n) in let obj_type = MakeType.apply (Reason.Rwitness_from_decl (Pos_or_decl.of_raw_pos p)) (Positioned.of_raw_positioned pos_cname) params in let ety_env = { (empty_expand_env_with_on_error (Typing_error.Reasons_callback.invalid_type_hint pos)) with substs = TUtils.make_locl_subst_for_class_tparams class_ tvarl; } in let ((env, ty_err_opt1), local_obj_ty) = Phase.localize ~ety_env env obj_type in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt1; let ((env, ty_err_opt2), (fty, _tal)) = TOG.obj_get ~obj_pos:pos ~is_method:true ~nullsafe:None ~inst_meth:false ~meth_caller:true ~coerce_from_ty:None ~explicit_targs:[] ~class_id:(CI (pos, class_name)) ~member_id:meth_name ~on_error:Typing_error.Callback.unify_error env local_obj_ty in Option.iter ty_err_opt2 ~f:(Typing_error_utils.add_typing_error ~env); let (env, fty) = Env.expand_type env fty in (match deref (strip_supportdyn fty) with | (reason, Tfun ftype) -> (* We are creating a fake closure: * function(Class $x, arg_types_of(Class::meth_name)) : return_type_of(Class::meth_name) *) let ety_env = { ety_env with on_error = Some (Env.unify_error_assert_primary_pos_in_current_decl env); } in let (env, ty_err_opt3) = Phase.check_tparams_constraints ~use_pos:p ~ety_env env (Cls.tparams class_) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt3; let local_obj_fp = TUtils.default_fun_param local_obj_ty in let fty = { ftype with ft_params = local_obj_fp :: ftype.ft_params } in let caller = { ft_tparams = fty.ft_tparams; ft_where_constraints = fty.ft_where_constraints; ft_params = fty.ft_params; ft_implicit_params = fty.ft_implicit_params; ft_ret = fty.ft_ret; ft_flags = fty.ft_flags; ft_ifc_decl = fty.ft_ifc_decl; ft_cross_package = fty.ft_cross_package; } in let ty = Typing_dynamic.maybe_wrap_with_supportdyn ~should_wrap:(TCO.enable_sound_dynamic (Env.get_tcopt env)) reason caller in make_result env p (Aast.Method_caller (pos_cname, meth_name)) ty | _ -> (* Shouldn't happen *) let (env, ty) = Env.fresh_type_error env pos in make_result env p (Aast.Method_caller (pos_cname, meth_name)) ty)) | FunctionPointer (FP_class_const (cid, meth), targs) -> let (env, _, ce, cty) = class_expr env [] cid in let (env, (fpty, tal)) = class_get ~is_method:true ~is_const:false ~transform_fty:None ~incl_tc:false (* What is this? *) ~coerce_from_ty:None (* What is this? *) ~explicit_targs:targs ~is_function_pointer:true env cty meth cid in let env = Env.set_tyvar_variance env fpty in let (env, fpty) = set_function_pointer env fpty in (* All function pointers are readonly_this since they are either toplevel or static *) let (env, fpty) = set_readonly_this p env fpty in make_result env p (Aast.FunctionPointer (FP_class_const (ce, meth), tal)) fpty | Lplaceholder p -> let r = Reason.Rplaceholder p in let ty = MakeType.void r in make_result env p (Aast.Lplaceholder p) ty | Dollardollar id -> let ty = Env.get_local_check_defined env id in let env = might_throw ~join_pos:p env in make_result env p (Aast.Dollardollar id) ty.Typing_local_types.ty | Lvar ((_, x) as id) -> if not accept_using_var then check_escaping_var env id; let ty = if check_defined then Env.get_local_check_defined env id else Env.get_local env x in make_result env p (Aast.Lvar id) ty.Typing_local_types.ty | Tuple el -> let (env, expected) = expand_expected_and_get_node ~pessimisable_builtin:false env expected in let (env, tel, tyl) = match expected with | Some (pos, ur, _, _, Ttuple expected_tyl) -> exprs_expected (pos, ur, expected_tyl) env el | _ -> exprs env el in let ty = MakeType.tuple (Reason.Rwitness p) tyl in make_result env p (Aast.Tuple tel) ty | List el -> let (env, tel, tyl) = match valkind with | Lvalue | Lvalue_subexpr -> lvalues env el | Other -> let (env, expected) = expand_expected_and_get_node ~pessimisable_builtin:true env expected in (match expected with | Some (pos, ur, _, _, Ttuple expected_tyl) -> exprs_expected (pos, ur, expected_tyl) env el | _ -> exprs env el) in let ty = MakeType.tuple (Reason.Rwitness p) tyl in make_result env p (Aast.List tel) ty | Pair (th, e1, e2) -> let (env, expected1, expected2, th) = match th with | Some ((_, t1), (_, t2)) -> let ((env, ty_err_opt1), t1, t1_expected) = localize_targ env t1 in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt1; let ((env, ty_err_opt2), t2, t2_expected) = localize_targ env t2 in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt2; (env, Some t1_expected, Some t2_expected, Some (t1, t2)) | None -> (* Use expected type to determine expected element types *) (match expand_expected_and_get_node ~pessimisable_builtin:false env expected with | (env, Some (pos, reason, _, _ty, Tclass ((_, k), _, [ty1; ty2]))) when String.equal k SN.Collections.cPair -> let ty1_expected = ExpectedTy.make pos reason ty1 in let ty2_expected = ExpectedTy.make pos reason ty2 in (env, Some ty1_expected, Some ty2_expected, None) | _ -> (env, None, None, None)) in let (_, p1, _) = e1 in let (_, p2, _) = e2 in let (env, tel1, ty1) = infer_element_type_for_collection ~expected:expected1 ~explicit:(Option.is_some th) ~can_pessimise:false ~use_pos:p1 ~reason:Reason.URpair_value ~bound:None (Reason.Rtype_variable_generics (p1, "T1", "Pair")) env [e1] array_value in let (env, tel2, ty2) = infer_element_type_for_collection ~expected:expected2 ~explicit:(Option.is_some th) ~can_pessimise:false ~use_pos:p2 ~reason:Reason.URpair_value ~bound:None (Reason.Rtype_variable_generics (p2, "T2", "Pair")) env [e2] array_value in let ty = MakeType.pair (Reason.Rwitness p) ty1 ty2 in let te1 = List.hd_exn tel1 in let te2 = List.hd_exn tel2 in make_result env p (Aast.Pair (th, te1, te2)) ty | Array_get (e, None) -> let (env, te, _) = update_array_type p env e valkind in let env = might_throw ~join_pos:p env in (* NAST check reports an error if [] is used for reading in an lvalue context. *) let (env, ty) = Env.fresh_type_error env p in make_result env p (Aast.Array_get (te, None)) ty | Array_get (e1, Some e2) -> let (env, te1, ty1) = update_array_type ?lhs_of_null_coalesce p env e1 valkind in let (env, te2, ty2) = expr env e2 in let env = might_throw ~join_pos:p env in let is_lvalue = is_lvalue valkind in let (_, p1, _) = e1 in let (env, (ty, arr_ty_mismatch_opt, key_ty_mismatch_opt)) = Typing_array_access.array_get ~array_pos:p1 ~expr_pos:p ?lhs_of_null_coalesce is_lvalue env ty1 e2 ty2 in make_result env p (Aast.Array_get ( hole_on_ty_mismatch ~ty_mismatch_opt:arr_ty_mismatch_opt te1, Some (hole_on_ty_mismatch ~ty_mismatch_opt:key_ty_mismatch_opt te2) )) ty | Call { func = (_, pos_id, Id (_, s)) as e; targs; args; unpacked_arg = None } when Hash_set.mem typing_env_pseudofunctions s -> let (env, _tel, tys) = argument_list_exprs (expr ~accept_using_var:true) env args in let env = if String.equal s SN.PseudoFunctions.hh_expect then do_hh_expect ~equivalent:false env pos_id targs p tys else if String.equal s SN.PseudoFunctions.hh_expect_equivalent then do_hh_expect ~equivalent:true env pos_id targs p tys else if not (List.is_empty targs) then ( Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Expected_tparam { decl_pos = Pos_or_decl.none; pos = pos_id; n = 0 }); env ) else if String.equal s SN.PseudoFunctions.hh_show then ( List.iter tys ~f:(Typing_log.hh_show p env); env ) else if String.equal s SN.PseudoFunctions.hh_show_env then ( Typing_log.hh_show_env p env; env ) else if String.equal s SN.PseudoFunctions.hh_log_level then match args with | [ (Ast_defs.Pnormal, (_, _, Aast.String key_str)); (Ast_defs.Pnormal, (_, _, Aast.Int level_str)); ] -> Env.set_log_level env key_str (int_of_string level_str) | _ -> env else if String.equal s SN.PseudoFunctions.hh_force_solve then ( let (env, ty_err_opt) = Typing_solver.solve_all_unsolved_tyvars env in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; env ) else if String.equal s SN.PseudoFunctions.hh_loop_forever then let _ = loop_forever env in env else if String.equal s SN.PseudoFunctions.hh_time then begin do_hh_time args; env end else env in (* Discard the environment and whether fake members should be forgotten to make sure that pseudo functions don't change the typechecker behaviour. *) let ((_env, te, ty), _should_forget_fakes) = let env = might_throw ~join_pos:p env in dispatch_call ~is_using_clause ~expected ~valkind ?in_await p env e targs args None in (env, te, ty) | Call { func; targs; args; unpacked_arg } -> let env = might_throw ~join_pos:p env in let ((env, te, ty), should_forget_fakes) = dispatch_call ~is_using_clause ~expected ~valkind ?in_await p env func targs args unpacked_arg in let env = if should_forget_fakes then Env.forget_members env Reason.(Blame (p, BScall)) else env in (env, te, ty) | FunctionPointer (FP_id fid, targs) -> let (env, fty, targs) = fun_type_of_id env fid targs [] in let e = Aast.FunctionPointer (FP_id fid, targs) in let (env, fty) = set_function_pointer env fty in (* All function pointers are readonly_this since they are always a toplevel function or static method *) let (env, fty) = set_readonly_this p env fty in make_result env p e fty | Binop { bop = Ast_defs.QuestionQuestion; lhs = e1; rhs = e2 } -> let (env, te1, ty1) = raw_expr ~lhs_of_null_coalesce:true env e1 ~allow_awaitable:true in let parent_lenv = env.lenv in let lenv1 = env.lenv in let (env, te2, ty2) = expr ?expected env e2 ~allow_awaitable:true in let lenv2 = env.lenv in let env = LEnv.union_lenvs ~join_pos:p env parent_lenv lenv1 lenv2 in (* There are two cases: either the left argument was null in which case we evaluate the second argument which gets as ty2, or that ty1 wasn't null. The following intersection adds the nonnull information. *) let (env, ty1) = Inter.intersect env ~r:Reason.Rnone ty1 (MakeType.nonnull Reason.Rnone) in let (env, ty) = Union.union ~approx_cancel_neg:true env ty1 ty2 in make_result env p (Aast.Binop { bop = Ast_defs.QuestionQuestion; lhs = te1; rhs = te2 }) ty | Binop { bop = Ast_defs.Eq op_opt; lhs = e1; rhs = e2 } -> let make_result env p te ty = let (env, te, ty) = make_result env p te ty in let env = Typing_local_ops.check_assignment env te in (env, te, ty) in (match op_opt with (* For example, e1 += e2. This is typed and translated as if * written e1 = e1 + e2. * TODO TAST: is this right? e1 will get evaluated more than once *) | Some op -> let (_, _, expr_) = e1 in (match (op, expr_) with | (Ast_defs.QuestionQuestion, Class_get _) -> Errors.experimental_feature p "null coalesce assignment operator with static properties"; expr_error env p outer | _ -> let e_fake = ( (), p, Binop { bop = Ast_defs.Eq None; lhs = e1; rhs = ((), p, Binop { bop = op; lhs = e1; rhs = e2 }); } ) in let (env, te_fake, ty) = raw_expr env e_fake in let te_opt = resugar_binop te_fake in begin match te_opt with | Some (_, _, te) -> make_result env p te ty | _ -> assert false end) | None -> let (env, te2, ty2) = raw_expr env e2 in let (_, pos2, _) = te2 in let (env, te1, ty, ty_mismatch_opt) = assign p env e1 pos2 ty2 in let te = Aast.Binop { bop = Ast_defs.Eq None; lhs = te1; rhs = hole_on_ty_mismatch ~ty_mismatch_opt te2; } in make_result env p te ty) | Binop { bop = (Ast_defs.Ampamp | Ast_defs.Barbar) as bop; lhs = e1; rhs = e2 } -> let c = Ast_defs.(equal_bop bop Ampamp) in let (env, te1, _) = expr env e1 in let lenv = env.lenv in let (env, _) = condition env c te1 in let (env, te2, _) = expr env e2 in let env = { env with lenv } in make_result env p (Aast.Binop { bop; lhs = te1; rhs = te2 }) (MakeType.bool (Reason.Rlogic_ret p)) | Binop { bop; lhs = e1; rhs = e2 } -> let (env, te1, ty1) = raw_expr env e1 in let (env, te2, ty2) = raw_expr env e2 in let env = match bop with (* TODO: This could be less conservative: we only need to account for * the possibility of exception if the operator is `/` or `/=`. *) | Ast_defs.Eqeqeq | Ast_defs.Diff2 -> env | _ -> might_throw ~join_pos:p env in let (_, p1, _) = e1 in let (_, p2, _) = e2 in let (env, te3, ty) = Typing_arithmetic.binop p env bop p1 te1 ty1 p2 te2 ty2 in (env, te3, ty) | Pipe (e0, e1, e2) -> (* If it weren't for local variable assignment or refinement the pipe * expression e1 |> e2 could be typed using this rule (E is environment with * types for locals): * * E |- e1 : ty1 E[$$:ty1] |- e2 : ty2 * -------------------------------------- * E |- e1|>e2 : ty2 * * The possibility of e2 changing the types of locals in E means that E * can evolve, and so we need to restore $$ to its original state. *) let (env, te1, ty1) = expr env e1 in let dd_var = Local_id.make_unscoped SN.SpecialIdents.dollardollar in let dd_old_ty = if Env.is_local_present env dd_var then Some (Env.get_local env dd_var) else None in (* $$ isn't a typed local so it doesn't need a bound *) let env = Env.set_local ~is_defined:true ~bound_ty:None env dd_var ty1 Pos.none in let (env, te2, ty2) = expr env e2 ~allow_awaitable:true in let env = match dd_old_ty with | None -> Env.unset_local env dd_var | Some local -> Typing_local_types.( Env.set_local ~is_defined:true ~bound_ty:local.bound_ty env dd_var local.ty local.pos) in let (env, te, ty) = make_result env p (Aast.Pipe (e0, te1, te2)) ty2 in (env, te, ty) | Unop (uop, e) -> let (env, te, ty) = raw_expr env e in let env = might_throw ~join_pos:p env in let (env, tuop, ty) = Typing_arithmetic.unop p env uop te ty in let env = Typing_local_ops.check_assignment env te in (env, tuop, ty) | Eif (c, e1, e2) -> eif env ~expected ?in_await p c e1 e2 | Class_const ((_, p, CI sid), pstr) when String.equal (snd pstr) "class" && Env.is_typedef env (snd sid) -> begin match Env.get_typedef env (snd sid) with | Some { td_tparams = tparaml; _ } -> (* Typedef type parameters cannot have constraints *) let params = List.map ~f: begin fun { tp_name = (p, x); _ } -> (* TODO(T69551141) handle type arguments for Tgeneric *) MakeType.generic (Reason.Rwitness_from_decl p) x end tparaml in let p_ = Pos_or_decl.of_raw_pos p in let tdef = mk ( Reason.Rwitness_from_decl p_, Tapply (Positioned.of_raw_positioned sid, params) ) in let typename = mk ( Reason.Rwitness_from_decl p_, Tapply ((p_, SN.Classes.cTypename), [tdef]) ) in let (env, tparams) = List.map_env env tparaml ~f:(fun env _tp -> Env.fresh_type env p) in let ety_env = { (empty_expand_env_with_on_error (Env.invalid_type_hint_assert_primary_pos_in_current_decl env)) with substs = Subst.make_locl tparaml tparams; } in let (env, ty_err_opt1) = Phase.check_tparams_constraints ~use_pos:p ~ety_env env tparaml in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt1; let ((env, ty_err_opt2), ty) = Phase.localize ~ety_env env typename in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt2; make_result env p (Class_const ((ty, p, CI sid), pstr)) ty | None -> (* Should not expect None as we've checked whether the sid is a typedef *) expr_error env p outer end | Class_const (cid, mid) -> class_const env p (cid, mid) | Class_get (((_, _, cid_) as cid), CGstring mid, Is_prop) when Env.FakeMembers.is_valid_static env cid_ (snd mid) -> let (env, local) = Env.FakeMembers.make_static env cid_ (snd mid) p in let local = ((), p, Lvar (p, local)) in let (env, _, ty) = expr env local in let (env, _tal, te, _) = class_expr env [] cid in make_result env p (Aast.Class_get (te, Aast.CGstring mid, Is_prop)) ty (* Statically-known static property access e.g. Foo::$x *) | Class_get (((_, _, cid_) as cid), CGstring mid, prop_or_method) -> let (env, _tal, te, cty) = class_expr env [] cid in let env = might_throw ~join_pos:p env in let (env, (ty, _tal)) = class_get ~is_method:(equal_prop_or_method prop_or_method Is_method) ~is_const:false ~transform_fty:None ~coerce_from_ty:None env cty mid cid in let (env, ty) = Env.FakeMembers.check_static_invalid env cid_ (snd mid) ty in make_result env p (Aast.Class_get (te, Aast.CGstring mid, prop_or_method)) ty (* Dynamic static method invocation or property access. `$y = "bar"; Foo::$y()` is interpreted as `Foo::bar()` *) | Class_get (cid, CGexpr m, prop_or_method) -> let (env, _tal, te, cty) = class_expr env [] cid in (* Match Obj_get dynamic instance property access behavior *) let (env, tm, _) = expr env m in let (env, ty) = if TUtils.is_dynamic env cty || TCO.enable_sound_dynamic (Env.get_tcopt env) then (env, MakeType.dynamic (Reason.Rwitness p)) else Env.fresh_type_error env p in let env = might_throw ~join_pos:p env in make_result env p (Aast.Class_get (te, Aast.CGexpr tm, prop_or_method)) ty (* Fake member property access. For example: * if ($x->f !== null) { ...$x->f... } *) | Obj_get (e, (_, pid, Id (py, y)), nf, is_prop) when Env.FakeMembers.is_valid env e y -> let env = might_throw ~join_pos:p env in let (env, local) = Env.FakeMembers.make env e y p in let local = ((), p, Lvar (p, local)) in let (env, _, ty) = expr env local in let env = xhp_check_get_attribute p env e y nf in let (env, t_lhs, _) = expr ~accept_using_var:true env e in let (env, t_rhs) = TUtils.make_simplify_typed_expr env pid ty (Aast.Id (py, y)) in make_result env p (Aast.Obj_get (t_lhs, t_rhs, nf, is_prop)) ty (* Statically-known instance property access e.g. $x->f *) | Obj_get (e1, (_, pm, Id m), nullflavor, prop_or_method) -> let env = xhp_check_get_attribute p env e1 (snd m) nullflavor in let (env, te1, ty1) = expr ~accept_using_var:true env e1 in let env = might_throw ~join_pos:p env in (* We typecheck Obj_get by checking whether it is a subtype of Thas_member(m, #1) where #1 is a fresh type variable. *) let (env, mem_ty) = Env.fresh_type env p in let (_, p1, _) = e1 in let r = Reason.Rwitness p1 in let has_member_ty = MakeType.has_member r ~name:m ~ty:mem_ty ~class_id:(CIexpr e1) ~explicit_targs:None in let lty1 = LoclType ty1 in let ((env, ty_err_opt), result_ty, ty_mismatch_opt) = match nullflavor with | OG_nullthrows -> let (env, ty_err_opt) = Type.sub_type_i p1 Reason.URnone env lty1 has_member_ty Typing_error.Callback.unify_error in let ty_mismatch = mk_ty_mismatch_opt ty1 (MakeType.nothing Reason.none) ty_err_opt in ((env, ty_err_opt), mem_ty, ty_mismatch) | OG_nullsafe -> (* In that case ty1 is a subtype of ?Thas_member(m, #1) and the result is ?#1 if ty1 is nullable. *) let r = Reason.Rnullsafe_op p in let null_ty = MakeType.null r in let (env, null_has_mem_ty) = Union.union_i env r has_member_ty null_ty in let (env, ty_err_opt) = Type.sub_type_i p1 Reason.URnone env lty1 null_has_mem_ty Typing_error.Callback.unify_error in let ty_mismatch = mk_ty_mismatch_opt ty1 (MakeType.nothing Reason.none) ty_err_opt in let (env, null_or_nothing_ty) = Inter.intersect env ~r null_ty ty1 in let (env, result_ty) = Union.union env null_or_nothing_ty mem_ty in ((env, ty_err_opt), result_ty, ty_mismatch) in let (env, result_ty) = Env.FakeMembers.check_instance_invalid env e1 (snd m) result_ty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let (env, inner_te) = TUtils.make_simplify_typed_expr env pm result_ty (Aast.Id m) in make_result env p (Aast.Obj_get ( hole_on_ty_mismatch ~ty_mismatch_opt te1, inner_te, nullflavor, prop_or_method )) result_ty (* Dynamic instance property access e.g. $x->$f *) | Obj_get (e1, e2, nullflavor, prop_or_method) -> let (env, te1, ty1) = expr ~accept_using_var:true env e1 in let (env, ty_err_opt) = (* Under Sound Dynamic, check that e1 supports dynamic *) Typing_coercion.coerce_type ~coerce:(Some Typing_logic.CoerceToDynamic) p Reason.URdynamic_prop env ty1 (MakeType.unenforced (MakeType.dynamic (Reason.Rwitness p))) Typing_error.Callback.unify_error in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let (env, te2, _) = expr env e2 in let (env, ty) = (env, MakeType.dynamic (Reason.Rdynamic_prop p)) in let (_, pos, te2) = te2 in let env = might_throw ~join_pos:p env in let (env, te2) = TUtils.make_simplify_typed_expr env pos ty te2 in make_result env p (Aast.Obj_get (te1, te2, nullflavor, prop_or_method)) ty | Yield af -> let (env, (taf, opt_key, value)) = array_field ~allow_awaitable env af in let Typing_env_return_info.{ return_type = expected_return; _ } = Env.get_return env in let send = match get_node expected_return.et_type with | Tclass (_, _, _ :: _ :: send :: _) -> send | Tdynamic when Tast.is_under_dynamic_assumptions env.checked -> expected_return.et_type | _ -> Errors.internal_error p "Return type is not a generator"; MakeType.union (Reason.Ryield_send p) [] in let is_async = match Env.get_fn_kind env with | Ast_defs.FGenerator -> false (* This could also catch sync/async non-generators, but an error would * have already been generated elsewhere *) | _ -> true in let (env, key) = match (af, opt_key) with | (AFvalue (_, p, _), None) -> if is_async then let (env, ty) = Env.fresh_type env p in (env, MakeType.nullable (Reason.Ryield_asyncnull p) ty) else (env, MakeType.int (Reason.Rwitness p)) | (_, Some x) -> (env, x) | (_, _) -> assert false in let rty = if is_async then MakeType.async_generator (Reason.Ryield_asyncgen p) key value send else MakeType.generator (Reason.Ryield_gen p) key value send in let Typing_env_return_info.{ return_type = expected_return; _ } = Env.get_return env in let (env, ty_err_opt) = Typing_coercion.coerce_type p Reason.URyield env rty expected_return Typing_error.Callback.unify_error in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let env = Env.forget_members env Reason.(Blame (p, BScall)) in let env = LEnv.save_and_merge_next_in_cont ~join_pos:p env C.Exit in make_result env p (Aast.Yield taf) (MakeType.nullable (Reason.Ryield_send p) send) | Await e -> begin match e with | (_, p, Aast.Call { func = (_, _, Aast.Id (_, f)); _ }) when String.equal f SN.PseudoFunctions.unsafe_cast || String.equal f SN.PseudoFunctions.unsafe_nonnull_cast -> Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.Unsafe_cast_await p) | _ -> () end; let env = might_throw ~join_pos:p env in (* Await is permitted in a using clause e.g. using (await make_handle()) *) let (env, te, rty) = expr ~is_using_clause ~in_await:(Reason.Rwitness p) env e ~allow_awaitable:true in let (env, ty) = Async.overload_extract_from_awaitable env ~p rty in make_result env p (Aast.Await te) ty | ReadonlyExpr e -> let env = Env.set_readonly env true in let (env, te, rty) = expr ~is_using_clause env e in make_result env p (Aast.ReadonlyExpr te) rty | New (((_, pos, _) as cid), explicit_targs, el, unpacked_element, ()) -> let env = might_throw ~join_pos:p env in let ( env, tc, tal, tel, typed_unpack_element, ty, ctor_fty, should_forget_fakes ) = new_object ~expected ~is_using_clause ~check_parent:false ~check_not_abstract:true pos env cid explicit_targs (List.map ~f:(fun e -> (Ast_defs.Pnormal, e)) el) unpacked_element in let env = if should_forget_fakes then Env.forget_members env Reason.(Blame (p, BScall)) else env in make_result env p (Aast.New (tc, tal, List.map ~f:snd tel, typed_unpack_element, ctor_fty)) ty | Cast (hint, e) -> let (env, te, ty2) = expr ?in_await env e in let env = might_throw ~join_pos:p env in let (env, ty_err_opt1) = if TCO.experimental_feature_enabled (Env.get_tcopt env) TCO.experimental_forbid_nullable_cast && not (TUtils.is_mixed env ty2) then SubType.sub_type_or_fail env ty2 (MakeType.nonnull (get_reason ty2)) @@ Some Typing_error.( primary @@ Primary.Nullable_cast { pos = p; ty_name = lazy (Typing_print.error env ty2); ty_pos = get_pos ty2; }) else (env, None) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt1; let ((env, ty_err_opt2), ty) = Phase.localize_hint_no_subst env ~ignore_errors:false hint in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt2; make_result env p (Aast.Cast (hint, te)) ty | ExpressionTree et -> expression_tree env p et | Is (e, hint) -> let (env, te, _) = expr env e in make_result env p (Aast.Is (te, hint)) (MakeType.bool (Reason.Rwitness p)) | As (e, hint, is_nullable) -> let refine_type env lpos lty rty = let reason = Reason.Ras lpos in let (env, rty) = Env.expand_type env rty in refine_and_simplify_intersection ~hint_first:false env p reason lpos lty rty in let (env, te, expr_ty) = expr env e in let env = might_throw ~join_pos:p env in let ((env, ty_err_opt1), hint_ty) = Phase.localize_hint_for_refinement env hint in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt1; let hint_ty = strip_supportdyn hint_ty in let hint_ty = if TCO.pessimise_builtins (Env.get_tcopt env) then ish_weakening env hint hint_ty else hint_ty in let ((env, ty_err_opt2), hint_ty) = if Typing_defs.is_dynamic hint_ty then let enable_sound_dynamic = TCO.enable_sound_dynamic env.genv.tcopt in let (env, ty_err_opt) = if enable_sound_dynamic then TUtils.supports_dynamic env expr_ty @@ Some (Typing_error.Reasons_callback.unify_error_at p) else (env, None) in let (env, locl) = make_a_local_of ~include_this:true env e in let env = match locl with | Some ivar -> let bound_ty = get_bound_ty_for_lvar env e in let env = match bound_ty with | None -> env | Some bound_ty -> (* If the typed local variable will have its type replaced by dynamic, we need to check that the bound isn't violated. *) let (env, err) = SubType.sub_type ~coerce:None env hint_ty bound_ty @@ Some (Typing_error.Reasons_callback.unify_error_at p) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) err; env in set_local ~is_defined:true ~bound_ty env ivar hint_ty | None -> env in ((env, ty_err_opt), hint_ty) else if is_nullable then let (_, e_p, _) = e in let (env, hint_ty) = refine_type env e_p expr_ty hint_ty in ((env, None), MakeType.nullable (Reason.Rwitness p) hint_ty) else let (env, locl) = make_a_local_of ~include_this:true env e in match locl with | Some ((ivar_pos, _) as ivar) -> let (env, hint_ty) = refine_type env ivar_pos expr_ty hint_ty in let bound_ty = get_bound_ty_for_lvar env e in (* refine_type returns a subtype of the expr type, and hence cannot violate the bound *) let env = set_local ~is_defined:true ~bound_ty env ivar hint_ty in ((env, None), hint_ty) | None -> let (_, e_p, _) = e in let (env, ty) = refine_type env e_p expr_ty hint_ty in ((env, None), ty) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt2; make_result env p (Aast.As (te, hint, is_nullable)) hint_ty | Upcast (e, hint) -> let (env, te, expr_ty) = expr env e in let ((env, ty_err_opt), hint_ty) = Phase.localize_hint_no_subst env ~ignore_errors:false hint in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let env = upcast env p expr_ty hint_ty in make_result env p (Aast.Upcast (te, hint)) hint_ty | Efun { ef_fun = f; ef_use = idl; ef_closure_class_name = closure_class_name } -> lambda ~is_anon:true ~closure_class_name ?expected p env f idl | Lfun (f, idl) -> lambda ~is_anon:false ~closure_class_name:None ?expected p env f idl | Xml (sid, attrl, el) -> let cid = CI sid in let (env, _tal, _te, classes) = class_id_for_new ~exact:nonexact p env cid [] in (* OK to ignore rest of list; class_info only used for errors, and * cid = CI sid cannot produce a union of classes anyhow *) let class_info = List.find_map classes ~f:(function | `Dynamic -> None | `Class (_, class_info, _) -> Some class_info) in let (env, te, obj) = (* New statements derived from Xml literals are of the following form: * * __construct( * darray<string,mixed> $attributes, * varray<mixed> $children, * string $file, * int $line * ); *) let new_exp = Typing_xhp.rewrite_xml_into_new p sid attrl el in expr ?expected env new_exp in let tchildren = match te with | ( _, _, New ( _, _, [ _; ( _, _, (Varray (_, children) | ValCollection ((_, Vec), _, children)) ); _; _; ], _, _ ) ) -> (* Typing_xhp.rewrite_xml_into_new generates an AST node for a `varray[]` literal, which is interpreted as a vec[] *) children | _ -> (* We end up in this case when the cosntructed new expression does not typecheck. *) [] in let (env, typed_attrs) = xhp_attribute_exprs env class_info attrl sid obj in let txml = Aast.Xml (sid, typed_attrs, tchildren) in (match class_info with | None -> let ty = MakeType.nothing (Reason.Rmissing_class p) in make_result env p txml ty | Some _ -> make_result env p txml obj) | Shape fdm -> let expr_helper ?expected env (k, e) = let (env, et, ty) = expr ?expected env e in (env, (k, et, ty)) in let (env, tfdm) = match expand_expected_and_get_node ~pessimisable_builtin:false ~strip_supportdyn:true env expected with | (env, Some (pos, ur, _, _, Tshape { s_fields = expected_fdm; _ })) -> List.map_env env ~f:(fun env ((k, _) as ke) -> let tk = TShapeField.of_ast Pos_or_decl.of_raw_pos k in match TShapeMap.find_opt tk expected_fdm with | None -> expr_helper env ke | Some sft -> expr_helper ~expected:(ExpectedTy.make pos ur sft.sft_ty) env ke) fdm | _ -> List.map_env env ~f:expr_helper fdm in let fdm = List.fold_left ~f:(fun acc (k, _, ty) -> let tk = TShapeField.of_ast Pos_or_decl.of_raw_pos k in TShapeMap.add tk { sft_optional = false; sft_ty = ty } acc) ~init:TShapeMap.empty tfdm in let env = Typing_shapes.check_shape_keys_validity env (List.map tfdm ~f:fst3) in (* Fields are fully known, because this shape is constructed * using shape keyword and we know exactly what fields are set. *) make_result env p (Aast.Shape (List.map ~f:(fun (k, te, _) -> (k, te)) tfdm)) (MakeType.closed_shape (Reason.Rshape_literal p) fdm) | ET_Splice e -> Env.with_outside_expr_tree env (fun env dsl_name -> et_splice env dsl_name p e) | EnumClassLabel (None, s) -> let (env, expect_label, lty_opt) = match expected with | Some ety -> let (env, lty) = Env.expand_type env ety.ExpectedTy.ty.et_type in let expect_label = match get_node (TUtils.strip_dynamic env lty) with | Tnewtype (name, _, _) -> String.equal SN.Classes.cEnumClassLabel name | _ -> false in (env, expect_label, Some lty) | None -> (env, false, None) in let () = if expect_label then Typing_error_utils.add_typing_error ~env Typing_error.(enum @@ Primary.Enum.Enum_class_label_as_expr p) else let expected_ty_msg_opt = Option.map lty_opt ~f:(fun lty -> let ty_str = lazy (Typing_print.error env lty) in let r = get_reason lty in Lazy.map ty_str ~f:(fun ty_str -> Reason.to_string (Format.sprintf "Expected %s" ty_str) r)) in Typing_error_utils.add_typing_error ~env Typing_error.( enum @@ Primary.Enum.Enum_class_label_member_mismatch { pos = p; label = s; expected_ty_msg_opt }) in let (env, ty) = Env.fresh_type_error env p in make_result env p (Aast.EnumClassLabel (None, s)) ty | EnumClassLabel ((Some cname as e), name) -> let (env, res) = EnumClassLabelOps.expand p env ~full:true ~ctor:SN.Classes.cEnumClassLabel cname name None in let error () = let (env, ty) = Env.fresh_type_error env p in make_result env p (Aast.EnumClassLabel (e, name)) ty in (match res with | EnumClassLabelOps.Success ((_, _, texpr), lty) -> make_result env p texpr lty | EnumClassLabelOps.ClassNotFound -> (* Error registered in nast_check/unbound_name_check *) error () | EnumClassLabelOps.LabelNotFound _ -> (* Error registered in EnumClassLabelOps.expand *) error () | EnumClassLabelOps.Skip -> Typing_error_utils.add_typing_error ~env Typing_error.(enum @@ Primary.Enum.Enum_class_label_as_expr p); error ()) | Package ((p, _) as id) -> make_result env p (Aast.Package id) (MakeType.bool (Reason.Rwitness p)) and class_const ?(incl_tc = false) env p (cid, mid) = let (env, _tal, ce, cty) = class_expr env [] cid in let env = match get_node cty with | Tclass ((_, n), _, _) when Env.is_enum_class env n && String.(SN.Members.mClass <> snd mid) -> Typing_local_ops.enforce_enum_class_variant p env | _ -> env in let (env, (const_ty, _tal)) = class_get ~is_method:false ~is_const:true ~transform_fty:None ~incl_tc ~coerce_from_ty:None env cty mid cid in make_result env p (Aast.Class_const (ce, mid)) const_ty (* Here the body of a function or lambda is typechecked again to ensure it is safe * to call it from a dynamic context (eg. under dyn..dyn->dyn assumptions). * The code below must be kept in sync with with the fun_def checks. *) and check_function_dynamically_callable ~this_class:_ env f_name f params_decl_ty ret_locl_ty = let env = { env with checked = CUnderDynamicAssumptions } in Typing_log.log_sd_pass env f.f_span; let make_dynamic pos = MakeType.dynamic (Reason.Rsupport_dynamic_type pos) in let dynamic_return_ty = make_dynamic (get_pos ret_locl_ty) in let hint_pos = match f.f_ret with | (_, None) -> (match f_name with | Some (pos, _) -> (* We don't have a return hint, highlight the function name instead. *) pos | None -> (* Anonymos function, just use the position of the whole function. *) f.f_span) | (_, Some (pos, _)) -> pos in let dynamic_return_info = Typing_return.make_info hint_pos f.f_fun_kind f.f_user_attributes env (MakeType.unenforced dynamic_return_ty) in let (env, param_tys) = Typing_param.make_param_local_tys ~dynamic_mode:true ~no_auto_likes:false env params_decl_ty f.f_params in let (env, dynamic_params) = bind_params ~no_auto_likes:false env f.f_ctxs param_tys f.f_params in let (pos, name) = match f_name with | Some n -> n | None -> (f.f_span, ";anonymous") in let env = set_tyvars_variance_in_callable env dynamic_return_ty param_tys in let disable = Naming_attributes.mem SN.UserAttributes.uaDisableTypecheckerInternal f.f_user_attributes in let (env, dynamic_body) = Errors.try_with_result (fun () -> fun_ ~disable env dynamic_return_info pos f.f_body f.f_fun_kind) (fun env_and_dynamic_body error -> if not @@ TCO.everything_sdt env.genv.tcopt then Errors.function_is_not_dynamically_callable name error; env_and_dynamic_body) in (env, dynamic_params, dynamic_body, dynamic_return_ty) and lambda ~is_anon ~closure_class_name ?expected p env f idl = (* This is the function type as declared on the lambda itself. * If type hints are absent then use Twildcard instead. *) let declared_fe = Decl_nast.lambda_decl_in_env env.decl_env f in let { fe_type; fe_pos; _ } = declared_fe in let (declared_pos, declared_ft) = match get_node fe_type with | Tfun ft -> (fe_pos, ft) | _ -> failwith "Not a function" in let declared_decl_ft = Typing_enforceability.compute_enforced_and_pessimize_fun_type ~this_class:(Env.get_self_class env) env declared_ft in (* When creating a closure, the 'this' type will mean the late bound type * of the current enclosing class *) let ety_env = empty_expand_env_with_on_error (Env.invalid_type_hint_assert_primary_pos_in_current_decl env) in (* For Twildcard types, generate fresh type variables *) let ety_env = { ety_env with wildcard_action = Wildcard_fresh_tyvar } in let ((env, ty_err_opt), declared_ft) = Phase.( localize_ft ~instantiation:{ use_name = "lambda"; use_pos = p; explicit_targs = [] } ~ety_env ~def_pos:declared_pos env declared_decl_ft) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let idl = List.map idl ~f:(fun ((), ((_, name) as id)) -> (* Check that none of the explicit capture variables are from a using clause *) check_escaping_var env id; let ty = Env.get_local env name in (ty, id)) in (* Ensure that variadic parameter has a name *) (if get_ft_variadic declared_ft then match List.last declared_ft.ft_params with | Some { fp_name = None; _ } -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Ellipsis_strict_mode { require = `Param_name; pos = p }) | _ -> ()); (* Is the return type declared? *) let is_explicit = Option.is_some (hint_of_type_hint f.f_ret) in let check_body_under_known_params ~supportdyn env ?ret_ty ft : env * _ * locl_ty = let (env, (tefun, ft, support_dynamic_type)) = closure_make ~supportdyn ~closure_class_name ?ret_ty env p declared_decl_ft f ft idl is_anon in let ty = mk (Reason.Rwitness p, Tfun ft) in let ty = if support_dynamic_type then MakeType.supportdyn (Reason.Rwitness p) ty else ty in (env, tefun, ty) in let (env, eexpected) = expand_expected_and_get_node ~strip_supportdyn:true ~pessimisable_builtin:true env expected in match eexpected with | _ (* When we're in a dynamic pass of a function (or closure) don't type inner closures * at all, simply assign them a dynamic type. * Exception: we're checking an expression tree. Even in the dynamic pass, * maketree_with_type_param needs the lambda to be typed precisely. *) when Tast.is_under_dynamic_assumptions env.checked && not (Env.is_in_expr_tree env) -> make_result env p Aast.Omitted (MakeType.dynamic (Reason.Rwitness p)) | Some (_pos, _ur, supportdyn, ty, Tfun expected_ft) -> (* First check that arities match up *) check_lambda_arity env p (get_pos ty) declared_ft expected_ft; (* Use declared types for parameters in preference to those determined * by the context (expected parameters): they might be more general. *) let rec replace_non_declared_types declared_decl_ft_params declared_ft_params expected_ft_params = match (declared_decl_ft_params, declared_ft_params, expected_ft_params) with | ( declared_decl_ft_param :: declared_decl_ft_params, declared_ft_param :: declared_ft_params, expected_ft_param :: expected_ft_params ) -> let rest = replace_non_declared_types declared_decl_ft_params declared_ft_params expected_ft_params in (* If the type parameter did not have a type hint, it is Twildcard and we use the expected type instead. Otherwise, declared type takes precedence. *) let resolved_ft_param = if Typing_defs.is_wildcard declared_decl_ft_param.fp_type.et_type then { declared_ft_param with fp_type = expected_ft_param.fp_type } else declared_ft_param in resolved_ft_param :: rest | (_, _, []) -> (* Morally, this case should match on ([],[]) because we already check arity mismatch between declared and expected types. We handle it more generally here to be graceful. *) declared_ft_params | ([], [], _) -> if (not (get_ft_variadic declared_ft)) && get_ft_variadic expected_ft then [] else (* This means the expected_ft params list can have more parameters * than declared parameters in the lambda. For variadics, this is OK. *) expected_ft_params | _ -> failwith "declared_decl_ft_params length not same as declared_ft_params" in let expected_ft = { expected_ft with ft_params = replace_non_declared_types declared_decl_ft.ft_params declared_ft.ft_params expected_ft.ft_params; ft_implicit_params = declared_ft.ft_implicit_params; ft_flags = declared_ft.ft_flags; } in (* Don't bother passing in `void` if there is no explicit return *) let ret_ty = match get_node expected_ft.ft_ret.et_type with | Tprim Tvoid when not is_explicit -> None | _ -> Some expected_ft.ft_ret.et_type in Typing_log.increment_feature_count env FL.Lambda.contextual_params; check_body_under_known_params ~supportdyn env ?ret_ty expected_ft | _ -> (* If all parameters are annotated with explicit types, then type-check * the body under those assumptions and pick up the result type *) let all_explicit_params = List.for_all f.f_params ~f:(fun param -> Option.is_some (hint_of_type_hint param.param_type_hint)) in if all_explicit_params then ( Typing_log.increment_feature_count env (if List.is_empty f.f_params then FL.Lambda.no_params else FL.Lambda.explicit_params); check_body_under_known_params ~supportdyn:false env declared_ft ) else ( match eexpected with | Some (_pos, _ur, supportdyn, expected_ty, _) when TUtils.is_mixed env expected_ty || is_nonnull expected_ty || is_dynamic expected_ty -> (* If the expected type of a lambda is mixed, nonnull or dynamic, * or supportdyn of these, we construct a function type where the * undeclared parameters are set to mixed (when expected type of * lambda is mixed or nonnull), or dynamic (when expected type of * lambda is dynamic). Wrap mixed or nonnull in supportdyn if the * expected type is supportdyn. * We leave the return type alone, inferring it if necessary. * * For an expected mixed/nonnull type, one could argue that the lambda * doesn't even need to be checked as it can't be called (there is * no downcast to function type). Thus, we should be using nothing * to type the arguments. But generally users are very confused by * the use of nothing and would expect the lambda body to be * checked as though it could be called. *) let r = Reason.Rwitness p in let param_type = if is_dynamic expected_ty then MakeType.dynamic r else if supportdyn then MakeType.supportdyn r (MakeType.mixed r) else MakeType.mixed r in let replace_non_declared_type declared_decl_ft_param declared_ft_param = let is_undeclared = Typing_defs.is_wildcard declared_decl_ft_param.fp_type.et_type in if is_undeclared then let enforced_ty = { et_enforced = Unenforced; et_type = param_type } in { declared_ft_param with fp_type = enforced_ty } else declared_ft_param in let expected_ft = let ft_params = List.map2_exn ~f:replace_non_declared_type declared_decl_ft.ft_params declared_ft.ft_params in { declared_ft with ft_params } in check_body_under_known_params ~supportdyn env expected_ft | _ -> (* Missing types in parameter and result will have been replaced by fresh type variables *) Typing_log.increment_feature_count env FL.Lambda.fresh_tyvar_params; let declared_ty = mk (Reason.Rnone, Tfun declared_ft) in let supportdyn = Env.get_support_dynamic_type env in let declared_ty = if supportdyn then MakeType.supportdyn Reason.Rnone declared_ty else declared_ty in let env = check_expected_ty "Lambda" env declared_ty expected in let env = Env.set_tyvar_variance env declared_ty in (* TODO(jjwu): the declared_ft here is set to public, but is actually inferred from the surrounding context (don't think this matters in practice, since we check lambdas separately) *) check_body_under_known_params ~supportdyn env ~ret_ty:declared_ft.ft_ret.et_type declared_ft ) (** If `prop` is is an attribute, typecheck against the translated `base_expr->getAttribute(prop)` as property accesses are translated to this expression. *) and xhp_check_get_attribute pos env base_expr prop null_flavour = (* All and only attributes start with `:` when represented as properties. *) if String.is_prefix prop ~prefix:":" then let base_lenv = env.lenv in let call_get_attr = Typing_xhp.rewrite_attribute_access_into_call pos base_expr null_flavour in let (env, _, _) = expr ~allow_awaitable:false env call_get_attr in (* Snap the local env back to avoid manipualting refinements twice. *) { env with lenv = base_lenv } else env (** * Process a spread operator by computing the intersection of XHP attributes * between the spread expression and the XHP constructor onto which we're * spreading. *) and xhp_spread_attribute env c_onto valexpr sid obj = let (_, p, _) = valexpr in let (env, te, valty) = expr env valexpr ~allow_awaitable:(*?*) false in let ((env, xhp_req_err_opt), attr_ptys) = match c_onto with | None -> ((env, None), []) | Some class_info -> Typing_xhp.get_spread_attributes env p class_info valty in Option.iter xhp_req_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let (env, has_ty_mismatch) = List.fold_left attr_ptys ~f:(fun (env, has_err) attr -> let (env, _, err_opt) = xhp_attribute_decl_ty env sid obj attr in (env, has_err || Option.is_some err_opt)) ~init:(env, false) in (* If we have a subtyping error for any attribute, the best we can do here is give an expected type of nothing *) let ty_mismatch_opt = if has_ty_mismatch then Some (valty, MakeType.nothing Reason.Rnone) else None in (* Build the typed attribute node *) let typed_attr = Aast.Xhp_spread (hole_on_ty_mismatch ~ty_mismatch_opt te) in (env, typed_attr) (** * Simple XHP attributes (attr={expr} form) are simply interpreted as a member * variable prefixed with a colon. *) and xhp_simple_attribute env id valexpr sid obj = let (_, p, _) = valexpr in let (env, te, valty) = expr env valexpr ~allow_awaitable:(*?*) false in (* This converts the attribute name to a member name. *) let name = ":" ^ snd id in let attr_pty = ((fst id, name), (p, valty)) in let (env, decl_ty, ty_mismatch_opt) = xhp_attribute_decl_ty env sid obj attr_pty in let typed_attr = Aast.Xhp_simple { xs_name = id; xs_type = decl_ty; xs_expr = hole_on_ty_mismatch ~ty_mismatch_opt te; } in (env, typed_attr) (** * Typecheck the attribute expressions - this just checks that the expressions are * valid, not that they match the declared type for the attribute and, * in case of spreads, makes sure they are XHP. *) and xhp_attribute_exprs env cls_decl attrl sid obj = let handle_attr (env, typed_attrl) attr = let (env, typed_attr) = match attr with | Xhp_simple { xs_name = id; xs_expr = valexpr; _ } -> xhp_simple_attribute env id valexpr sid obj | Xhp_spread valexpr -> xhp_spread_attribute env cls_decl valexpr sid obj in (env, typed_attr :: typed_attrl) in let (env, typed_attrl) = List.fold_left ~f:handle_attr ~init:(env, []) attrl in (env, List.rev typed_attrl) (*****************************************************************************) (* Anonymous functions & lambdas. *) (*****************************************************************************) and closure_bind_param params (env, t_params) ty : env * Tast.fun_param list = match !params with | [] -> (* This code cannot be executed normally, because the arity is wrong * and it will error later. Bind as many parameters as we can and carry * on. *) (env, t_params) | param :: paraml -> params := paraml; (match hint_of_type_hint param.param_type_hint with | Some h -> let decl_ty = Decl_hint.hint env.decl_env h in (match Typing_enforceability.get_enforcement ~this_class:(Env.get_self_class env) env decl_ty with | Unenforced -> Typing_log.log_pessimise_param env ~is_promoted_property:false param.param_pos param.param_callconv param.param_name | Enforced -> ()); let ((env, ty_err_opt1), h) = Phase.localize_no_subst env ~ignore_errors:false decl_ty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt1; let (env, t_param) = bind_param env (Some h, param) in (env, t_params @ [t_param]) | None -> let ty = mk (Reason.Rlambda_param (param.param_pos, get_reason ty), get_node ty) in let (env, t_param) = bind_param env (Some ty, param) in (env, t_params @ [t_param])) and closure_bind_variadic env vparam variadic_ty = let ((env, ty_err_opt), ty, pos) = match hint_of_type_hint vparam.param_type_hint with | None -> (* if the hint is missing, use the type we expect *) ((env, None), variadic_ty, get_pos variadic_ty) | Some hint -> let ((env, ty_err_opt1), h) = Phase.localize_hint_for_lambda env hint in ((env, ty_err_opt1), h, Pos_or_decl.of_raw_pos vparam.param_pos) in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let r = Reason.Rvar_param_from_decl pos in let arr_values = mk (r, get_node ty) in let ty = MakeType.vec r arr_values in let (env, t_variadic) = bind_param env (Some ty, vparam) in (env, t_variadic) and closure_bind_opt_param env param : env = match param.param_expr with | None -> let (env, _) = bind_param env (None, param) in env | Some default -> let (env, _te, ty) = expr env default ~allow_awaitable:(*?*) false in Typing_sequencing.sequence_check_expr default; let (env, _) = bind_param env (Some ty, param) in env (* Make a type-checking function for an anonymous function or lambda. *) (* Here ret_ty should include Awaitable wrapper *) (* TODO: ?el is never set; so we need to fix variadic use of lambda *) and closure_make ?el ?ret_ty ?(check_escapes = true) ~supportdyn ~closure_class_name env lambda_pos decl_ft f ft idl is_anon = let type_closure f = (* Wrap the function f so that it can freely clobber function-specific parts of the environment; the clobbered parts are restored before returning the result. Additionally, we also prevent type parameters created in the closure from unsoundly leaking into the environment of the enclosing function. Also here we wrap `supportdyn<_>` around the function type if this is an SDT function. *) let snap = Typing_escape.snapshot_env env in let (env, (escaping, (te, ft, support_dynamic_type))) = Env.closure env (fun env -> stash_conts_for_closure env lambda_pos is_anon idl (fun env -> let (env, res) = f env in let escaping = Typing_escape.escaping_from_snapshot snap env in (env, (escaping, res)))) in (* After the body of the function is checked, erase all the type parameters created from the env and the return type. *) let (env, ret_ty) = if check_escapes then Typing_escape.refresh_env_and_type ~remove:escaping ~pos:lambda_pos env ft.ft_ret.et_type else (env, ft.ft_ret.et_type) in ( env, ( te, { ft with ft_ret = { ft.ft_ret with et_type = ret_ty } }, support_dynamic_type ) ) in type_closure @@ fun env -> let nb = f.f_body in (* Extract capabilities from AAST and add them to the environment *) let (env, capability) = match (f.f_ctxs, f.f_unsafe_ctxs) with | (None, None) -> (* if the closure has no explicit coeffect annotations, do _not_ insert (unsafe) capabilities into the environment; instead, rely on the fact that a capability from an enclosing scope can simply be captured, which has the same semantics as redeclaring and shadowing with another same-typed capability. This avoid unnecessary overhead in the most common case, i.e., when a closure does not need a different (usually smaller) set of capabilities. *) ( env, (Env.get_local env Typing_coeffects.local_capability_id) .Typing_local_types.ty ) | (_, _) -> let (env, cap_ty, unsafe_cap_ty) = Typing_coeffects.type_capability env f.f_ctxs f.f_unsafe_ctxs f.f_span in let (env, _) = Typing_coeffects.register_capabilities env cap_ty unsafe_cap_ty in (env, cap_ty) in let ft = { ft with ft_implicit_params = { capability = CapTy capability } } in (* Check attributes on the lambda *) let (env, user_attributes) = attributes_check_def env SN.AttributeKinds.lambda f.f_user_attributes in (* Regard a lambda as supporting dynamic if * it has the attribute <<__SupportDynamicType>>; * or its enclosing method, function or class has the attribute <<__SupportDynamicType>>; * or it must support dynamic because of the expected type *) let support_dynamic_type = Naming_attributes.mem SN.UserAttributes.uaSupportDynamicType user_attributes || Env.get_support_dynamic_type env || supportdyn in let no_auto_likes = Naming_attributes.mem SN.UserAttributes.uaNoAutoLikes user_attributes || Env.get_no_auto_likes env in (* A closure typed in env with parameters p1..pn and captured variables c1..cn * roughly compiles to * * class Closure$name { * private env(c1) c1; * ... * private env(cn) cn; * public static function __invoke(p1, ..., pn) { * /* closure body, references to cn are replaced with $this->cn */ * } * } * * To make a class SDT without considering enforcement, we make its properties * like types so that they may be written values with type `dynamic`. The following * fold analogously makes an SDT closure's captured variables be like types, and * elsewhere we skip typing closures entirely when typing the dynamic pass of a function. * * This is clearly a less precise way to type closures, but it allows us to avoid typing * SDT closures 2^depth times. *) let env = if support_dynamic_type then (* quiet to avoid duplicate error about capturing an undefined variable *) let locals = Env.get_locals ~quiet:true env idl in let like_locals = Local_id.Map.map (fun local -> Typing_local_types.{ local with ty = TUtils.make_like env local.ty }) locals in Env.set_locals env like_locals else env in (* Inout parameters should be pessimised in implicit pessimisation mode *) let ft = if support_dynamic_type && (not no_auto_likes) && TCO.everything_sdt env.genv.tcopt then { ft with ft_params = List.map ft.ft_params ~f:(fun fp -> match get_fp_mode fp with | FPinout -> { fp with fp_type = { fp.fp_type with et_type = TUtils.make_like env fp.fp_type.et_type; }; } | _ -> fp); } else ft in let env = Env.clear_params env in let non_variadic_ft_params = if get_ft_variadic ft then List.drop_last_exn ft.ft_params else ft.ft_params in let make_variadic_arg env varg tyl = let remaining_types = (* It's possible the variadic arg will capture the variadic * parameter of the supplied arity (if arity is Fvariadic) * and additional supplied params. * * For example in cases such as: * lambda1 = (int $a, string...$c) ==> {}; * lambda1(1, "hello", ...$y); (where $y is a variadic string) * lambda1(1, "hello", "world"); * then ...$c will contain "hello" and everything in $y in the first * example, and "hello" and "world" in the second example. * * To account for a mismatch in arity, we take the remaining supplied * parameters and return a list of all their types. We'll use this * to create a union type when creating the typed variadic arg. *) let remaining_params = List.drop non_variadic_ft_params (List.length f.f_params - 1) in List.map ~f:(fun param -> param.fp_type.et_type) remaining_params in let r = Reason.Rvar_param varg.param_pos in let union = Tunion (tyl @ remaining_types) in let (env, t_param) = closure_bind_variadic env varg (mk (r, union)) in (env, [t_param]) in let (env, t_variadic_params) = match ( List.find f.f_params ~f:(fun p -> p.param_is_variadic), get_ft_variadic ft ) with | (Some arg, true) -> make_variadic_arg env arg [(List.last_exn ft.ft_params).fp_type.et_type] | (Some arg, false) -> make_variadic_arg env arg [] | (_, _) -> (env, []) in let non_variadic_params = List.filter f.f_params ~f:(fun p -> not p.param_is_variadic) in let params = ref non_variadic_params in let (env, t_params) = List.fold_left ~f:(closure_bind_param params) ~init:(env, []) (List.map non_variadic_ft_params ~f:(fun x -> x.fp_type.et_type)) in let env = List.fold_left ~f:closure_bind_opt_param ~init:env !params in let env = List.fold_left ~f:closure_check_param ~init:env non_variadic_params in let env = match el with | None -> env | Some x -> let rec iter l1 l2 = match (l1, l2) with | (_, []) -> () | ([], _) -> () | (x1 :: rl1, (pkx_2, x2) :: rl2) -> param_modes ~env x1 x2 pkx_2; iter rl1 rl2 in iter non_variadic_ft_params x; wfold_left2 inout_write_back env non_variadic_ft_params x in let env = Env.set_fn_kind env f.f_fun_kind in let decl_ty = Option.map ~f:(Decl_hint.hint env.decl_env) (hint_of_type_hint f.f_ret) in let hint_pos = match snd f.f_ret with | Some (ret_pos, _) -> ret_pos | None -> lambda_pos in let ety_env = empty_expand_env_with_on_error (Env.invalid_type_hint_assert_primary_pos_in_current_decl env) in let ety_env = { ety_env with wildcard_action = Wildcard_fresh_tyvar } in let this_class = Env.get_self_class env in let params_decl_ty = List.map decl_ft.ft_params ~f:(fun { fp_type = { et_type; _ }; _ } -> if Typing_defs.is_wildcard et_type then None else Some et_type) in (* Do we need to re-check the body of the lambda under dynamic assumptions? *) let sdt_dynamic_check_required = support_dynamic_type && not (Typing_dynamic.function_parameters_safe_for_dynamic ~this_class env params_decl_ty) in (* We wrap result type in supportdyn if it's explicit and dynamic check isn't required. * This is an easy way to ensure that the return values support dynamic. *) let wrap_return_supportdyn = support_dynamic_type && not sdt_dynamic_check_required in let (env, hret) = Typing_return.make_return_type ~ety_env ~this_class ~is_toplevel:false env ~supportdyn:wrap_return_supportdyn ~hint_pos ~explicit:decl_ty ~default:ret_ty in let ft = { ft with ft_ret = hret } in let env = Env.set_return env (Typing_return.make_info hint_pos f.f_fun_kind [] env hret) in let local_tpenv = Env.get_tpenv env in (* Outer pipe variables aren't available in closures. Note that * locals are restored by Env.closure after processing the closure *) let env = Env.unset_local env (Local_id.make_unscoped SN.SpecialIdents.dollardollar) in let sound_dynamic_check_saved_env = env in let (env, tb) = block env nb.fb_ast in let has_implicit_return = LEnv.has_next env in let env = if not has_implicit_return then env else Typing_return.fun_implicit_return env lambda_pos hret.et_type f.f_fun_kind in (* For an SDT lambda that doesn't have a second check under dynamic assumptions, * and with an inferred return type, we must check that the return type supports dynamic *) let env = if support_dynamic_type && (not sdt_dynamic_check_required) && not wrap_return_supportdyn then ( let (env, ty_err_opt) = SubType.sub_type ~coerce:(Some Typing_logic.CoerceToDynamic) env hret.et_type (MakeType.dynamic (Reason.Rsupport_dynamic_type (Pos_or_decl.of_raw_pos hint_pos))) @@ Some (Typing_error.Reasons_callback.unify_error_at hint_pos) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; env ) else env in let has_readonly = Env.get_readonly env in let env = Env.set_fun_tast_info env Tast.{ has_implicit_return; has_readonly } in let env = if sdt_dynamic_check_required then begin Fn.ignore @@ check_function_dynamically_callable ~this_class sound_dynamic_check_saved_env None f params_decl_ty hret.et_type; (* The following modification is independent from the line above that does the dynamic check. Check status is changed to dynamic assumptions within the call above. Because we don't store alternative lambdas in the TAST, we unconditionally overwrite the check status to be under normal assumptions here. *) { env with checked = Tast.CUnderNormalAssumptions } end else env in let tfun_ = { Aast.f_annotation = Env.save local_tpenv env; Aast.f_readonly_this = f.f_readonly_this; Aast.f_span = f.f_span; Aast.f_ret = (hret.et_type, hint_of_type_hint f.f_ret); Aast.f_readonly_ret = f.f_readonly_ret; Aast.f_fun_kind = f.f_fun_kind; Aast.f_user_attributes = user_attributes; Aast.f_body = { Aast.fb_ast = tb }; Aast.f_ctxs = f.f_ctxs; Aast.f_unsafe_ctxs = f.f_unsafe_ctxs; Aast.f_params = t_params @ t_variadic_params; Aast.f_external = f.f_external; Aast.f_doc_comment = f.f_doc_comment; } in let ty = mk (Reason.Rwitness lambda_pos, Tfun ft) in let idl_ty = List.map idl ~f:(fun (local, lid) -> (local.Typing_local_types.ty, lid)) in let (env, te) = TUtils.make_simplify_typed_expr env lambda_pos ty (if is_anon then Aast.Efun { ef_fun = tfun_; ef_use = idl_ty; ef_closure_class_name = closure_class_name; } else Aast.Lfun (tfun_, idl_ty)) in let env = Env.set_tyvar_variance env ty in (env, (te, ft, support_dynamic_type)) (*****************************************************************************) (* End of anonymous functions & lambdas. *) (*****************************************************************************) (*****************************************************************************) (* Expression trees *) (*****************************************************************************) and expression_tree env p et = let { et_hint; et_splices; et_function_pointers; et_virtualized_expr; et_runtime_expr; et_dollardollar_pos; } = et in (* Slight hack to deal with |> $$ support *) let env = match et_dollardollar_pos with | Some dd_pos -> let dollardollar_var = Local_id.make_unscoped SN.ExpressionTrees.dollardollarTmpVar in let dd_var = Local_id.make_unscoped SN.SpecialIdents.dollardollar in let dd_defined = Env.is_local_present env dd_var in if not dd_defined then let () = Errors.add_error Naming_error.( to_user_error @@ Undefined { pos = dd_pos; var_name = SN.SpecialIdents.dollardollar; did_you_mean = None; }) in let nothing_ty = MakeType.nothing Reason.Rnone in Env.set_local ~is_defined:true ~bound_ty:None env dollardollar_var nothing_ty Pos.none else let dd_local = Env.get_local env dd_var in Typing_local_types.( Env.set_local ~is_defined:true ~bound_ty:None env dollardollar_var dd_local.ty dd_local.pos) | None -> env in (* Given the expression tree literal: MyVisitor`1 + ${ foo() }` First, type check the expressions that are spliced in, so foo() in this example. *) let (env, t_splices) = block env et_splices in (* Next, typecheck the function pointer assignments *) let (env, _, t_function_pointers) = Env.with_inside_expr_tree env et_hint (fun env -> let (env, t_function_pointers) = block env et_function_pointers in (env, (), t_function_pointers)) in (* Type check the virtualized expression, which will look roughly like this: function() { $0splice0 = foo(); return MyVisitor::intType()->__plus($0splice0); } *) let (env, t_virtualized_expr, ty_virtual) = Env.with_inside_expr_tree env et_hint (fun env -> expr env et_virtualized_expr ~allow_awaitable:false) in (* If the virtualized expression type is pessimised, we should strip off likes. * Do this through supportdyn and unions. *) let rec strip_all_likes env ty = let (env, ty) = Env.expand_type env ty in match get_node ty with | Tnewtype (name, [ty'], _) when String.equal name SN.Classes.cSupportDyn -> let (env, ty'') = strip_all_likes env ty' in (env, MakeType.supportdyn (get_reason ty) ty'') | Tunion tyl -> let tyl = List.filter tyl ~f:(fun ty -> not (Typing_defs.is_dynamic ty)) in let (env, tyl) = List.map_env env tyl ~f:strip_all_likes in Union.union_list env (get_reason ty) tyl | _ -> (env, ty) in let (env, ty_virtual) = strip_all_likes env ty_virtual in (* Given the runtime expression: MyVisitor::makeTree(...) add the inferred type as a type parameter: MyVisitor::makeTree<MyVisitorInt>(...) and then typecheck. *) let (env, runtime_expr) = maketree_with_type_param env p et_runtime_expr ty_virtual in let (env, t_runtime_expr, ty_runtime_expr) = expr env runtime_expr ~allow_awaitable:false in make_result env p (Aast.ExpressionTree { et_hint; et_splices = t_splices; et_function_pointers = t_function_pointers; et_virtualized_expr = t_virtualized_expr; et_runtime_expr = t_runtime_expr; et_dollardollar_pos; }) ty_runtime_expr and et_splice env dsl_opt p e = let open Option.Let_syntax in let dsl_opt = let* (_, dsl_name) = dsl_opt in return dsl_name in (* Error Reporting: The unification error reported by checking against `Spliceable<_, _, _>` is confusing to users. We improve the error message by including contextual information we pull from the definition of the DSL class. Particularly we: - Use the type specified in the DSL classes splice method - If there is a docs url attached to the class, use it *) let rec contextual_reasons ~ty env = let* dsl_name = dsl_opt in let* cls = Env.get_class env dsl_name in let* { ce_type = (lazy fun_ty); _ } = Env.get_member true env cls SN.ExpressionTrees.splice in (* Pull the type of third argument to `MyDsl::splice()`. If we change the number of arguments this method takes, we will need to update this match expression *) let* splice_ty = match get_node fun_ty with | Tfun { ft_params = [_; _; splice_ty]; _ } -> return @@ splice_ty.fp_type.et_type | _ -> None in return @@ lazy (error_reason ~splice_ty ~ty ~dsl_name env) and error_reason ~splice_ty ~ty ~dsl_name env = let err_splice_ty = Printf.sprintf "Expected `%s` because you are splicing into a `%s` expression or block" (Typing_print.with_blank_tyvars (fun () -> Typing_print.full_strip_ns_decl env splice_ty)) (Utils.strip_ns dsl_name) in let err_ty = Printf.sprintf "But got `%s`" @@ Typing_print.with_blank_tyvars (fun () -> Typing_print.full_strip_ns env ty) in Reason.to_string err_splice_ty (get_reason splice_ty) @ Reason.to_string err_ty (get_reason ty) in let docs_url = lazy (let* dsl_name = dsl_opt in let* cls = Env.get_class env dsl_name in Cls.get_docs_url cls) in let (env, te, ty) = expr env e ~allow_awaitable:(*?*) false in let (env, ty_visitor) = Env.fresh_type env p in let (env, ty_res) = Env.fresh_type env p in let (env, ty_infer) = Env.fresh_type env p in let spliceable_type = let raw_spliceable_type = MakeType.spliceable (Reason.Rsplice p) ty_visitor ty_res ty_infer in if TCO.pessimise_builtins (Env.get_tcopt env) then MakeType.locl_like (Reason.Rsplice p) raw_spliceable_type else raw_spliceable_type in let (_, expr_pos, _) = e in let (env, ty_err_opt) = SubType.sub_type env ty spliceable_type @@ Some (Typing_error.Reasons_callback.expr_tree_splice_error p ~expr_pos:(Pos_or_decl.of_raw_pos expr_pos) ~contextual_reasons:(contextual_reasons ~ty env) ~dsl_opt ~docs_url) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; make_result env p (Aast.ET_Splice te) ty_infer (*****************************************************************************) (* End expression trees *) (*****************************************************************************) and new_object ~(expected : ExpectedTy.t option) ~check_parent ~check_not_abstract ~is_using_clause p env ((_, _, cid_) as cid) explicit_targs el unpacked_element = (* Obtain class info from the cid expression. We get multiple * results with a CIexpr that has a union type, e.g. in $classname = (mycond()? classname<A>: classname<B>); new $classname(); *) let (env, tal, tcid, classes) = instantiable_cid ~exact:Exact p env cid_ explicit_targs in let allow_abstract_bound_generic = match tcid with | (ty, _, Aast.CI (_, tn)) -> is_generic_equal_to tn ty | _ -> false in let gather (env, _tel, _typed_unpack_element, should_forget_fakes_acc) (cname, class_info, c_ty) = if check_not_abstract && Cls.abstract class_info && (not (requires_consistent_construct cid_)) && not allow_abstract_bound_generic then uninstantiable_error env p cid_ (Cls.pos class_info) (Cls.name class_info) p c_ty; let (env, obj_ty_, params) = let (env, c_ty) = Env.expand_type env c_ty in match (cid_, tal, get_class_type c_ty) with (* Explicit type arguments *) | (CI _, _ :: _, Some (_, _, tyl)) -> (env, get_node c_ty, tyl) | (_, _, class_type_opt) -> let (env, params) = List.map_env env (Cls.tparams class_info) ~f:(fun env tparam -> let (env, tvar) = Env.fresh_type_reason env p (Reason.Rtype_variable_generics (p, snd tparam.tp_name, strip_ns (snd cname))) in Typing_log.log_new_tvar_for_new_object env p tvar cname tparam; (env, tvar)) in begin match class_type_opt with | Some (_, Exact, _) -> (env, Tclass (cname, Exact, params), params) | _ -> (env, Tclass (cname, nonexact, params), params) end in if (not check_parent) && (not is_using_clause) && Typing_disposable.is_disposable_class env class_info then Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.Invalid_new_disposable p); let r_witness = Reason.Rwitness p in let obj_ty = mk (r_witness, obj_ty_) in let (env, c_ty) = match cid_ with | CIstatic -> (env, mk (r_witness, get_node c_ty)) | CIexpr _ -> let c_ty = mk (r_witness, get_node c_ty) in (* When constructing from a (classname) variable, the variable * dictates what the constructed object is going to be. This allows * for generic and dependent types to be correctly carried * through the 'new $foo()' iff the constructed obj_ty is a * supertype of the variable-dictated c_ty *) let (env, ty_err_opt) = Typing_ops.sub_type p Reason.URnone env c_ty obj_ty Typing_error.Callback.unify_error in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (env, c_ty) | _ -> (env, obj_ty) in let (env, new_ty) = let (cid_ty, _, _) = tcid in let (env, cid_ty) = Env.expand_type env cid_ty in if is_generic cid_ty then (env, cid_ty) else if check_parent then (env, c_ty) else ExprDepTy.make env ~cid:cid_ c_ty in (* Set variance according to type of `new` expression now. Lambda arguments * to the constructor might depend on it, and `call_construct` only uses * `ctor_fty` to set the variance which has void return type *) let env = Env.set_tyvar_variance env new_ty in let (env, tel, typed_unpack_element, ctor_fty, should_forget_fakes) = let env = check_expected_ty "New" env new_ty expected in call_construct p env class_info params el unpacked_element cid new_ty in let should_forget_fakes_acc = should_forget_fakes_acc || should_forget_fakes in (if equal_consistent_kind (snd (Cls.construct class_info)) Inconsistent then match cid_ with | CIstatic -> let (class_pos, class_name) = cname in Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.New_inconsistent_construct { pos = p; class_name; class_pos; kind = `static }) | CIexpr _ -> let (class_pos, class_name) = cname in Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.New_inconsistent_construct { pos = p; class_name; class_pos; kind = `classname }) | _ -> ()); match cid_ with | CIparent -> let (env, ctor_fty) = match fst (Cls.construct class_info) with | Some ({ ce_type = (lazy ty); _ } as ce) -> let ety_env = { empty_expand_env with substs = TUtils.make_locl_subst_for_class_tparams class_info params; this_ty = obj_ty; } in if get_ce_abstract ce then Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Parent_abstract_call { meth_name = SN.Members.__construct; pos = p; decl_pos = get_pos ctor_fty; }); let ((env, ty_err_opt), ctor_fty) = Phase.localize ~ety_env env ty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (env, ctor_fty) | None -> (env, ctor_fty) in ( (env, tel, typed_unpack_element, should_forget_fakes_acc), (obj_ty, ctor_fty) ) | CIstatic | CI _ | CIself -> ( (env, tel, typed_unpack_element, should_forget_fakes_acc), (c_ty, ctor_fty) ) | CIexpr _ -> ( (env, tel, typed_unpack_element, should_forget_fakes_acc), (c_ty, ctor_fty) ) in let (had_dynamic, classes) = List.fold classes ~init:(false, []) ~f:(fun (seen_dynamic, classes) -> function | `Dynamic -> (true, classes) | `Class (cname, class_info, c_ty) -> (seen_dynamic, (cname, class_info, c_ty) :: classes)) in let ( (env, tel, typed_unpack_element, should_forget_fakes), class_types_and_ctor_types ) = List.fold_map classes ~init:(env, [], None, false) ~f:gather in let class_types_and_ctor_types = let r = Reason.Rdynamic_construct p in let dyn = (mk (r, Tdynamic), mk (r, Tdynamic)) in if had_dynamic then dyn :: class_types_and_ctor_types else class_types_and_ctor_types in let (env, tel, typed_unpack_element, ty, ctor_fty) = match class_types_and_ctor_types with | [] -> let (env, tel, _) = argument_list_exprs (expr ~allow_awaitable:false) env el in let (env, typed_unpack_element, _) = match unpacked_element with | None -> (env, None, MakeType.nothing Reason.Rnone) | Some unpacked_element -> let (env, e, ty) = expr env unpacked_element ~allow_awaitable:(*?*) false in (env, Some e, ty) in let (env, ty) = Env.fresh_type_error env p in (env, tel, typed_unpack_element, ty, ty) | [(ty, ctor_fty)] -> (env, tel, typed_unpack_element, ty, ctor_fty) | l -> let (tyl, ctyl) = List.unzip l in let r = Reason.Rwitness p in (env, tel, typed_unpack_element, mk (r, Tunion tyl), mk (r, Tunion ctyl)) in let (env, new_ty) = let (cid_ty, _, _) = tcid in let (env, cid_ty) = Env.expand_type env cid_ty in if is_generic cid_ty then (env, cid_ty) else if check_parent then (env, ty) else ExprDepTy.make env ~cid:cid_ ty in ( env, tcid, tal, tel, typed_unpack_element, new_ty, ctor_fty, should_forget_fakes ) and attributes_check_def env kind attrs = let new_object attr_pos env attr_cid params = let (env, _, _, _, _, _, _, _) = new_object ~expected:None ~check_parent:false ~check_not_abstract:false ~is_using_clause:false attr_pos env ((), attr_pos, Aast.CI (Positioned.unsafe_to_raw_positioned attr_cid)) [] (List.map ~f:(fun e -> (Ast_defs.Pnormal, e)) params) (* list of attr parameter literals *) None (* no variadic arguments *) in env in let env = Typing_attributes.check_def env new_object kind attrs in let (env, user_attrs) = List.map_env env attrs ~f:user_attribute in (* If NoAutoDynamic is set, disable everything_sdt *) let env = if Naming_attributes.mem SN.UserAttributes.uaNoAutoDynamic user_attrs then Env.set_everything_sdt env false else env in (env, user_attrs) (** Get class infos for a class expression (e.g. `parent`, `self` or regular classnames) - which might resolve to a union or intersection of classes - and check they are instantiable. FIXME: we need to separate our instantiability into two parts. Currently, all this function is doing is checking if a given type is inhabited -- that is, whether there are runtime values of type Aast. However, instantiability should be the stricter notion that T has a runtime constructor; that is, `new T()` should be valid. In particular, interfaces are inhabited, but not instantiable. To make this work with classname, we likely need to add something like concrete_classname<T>, where T cannot be an interface. *) and instantiable_cid ?(exact = nonexact) p env cid explicit_targs : newable_class_info = let (env, tal, te, classes) = class_id_for_new ~exact p env cid explicit_targs in List.iter classes ~f:(function | `Dynamic -> () | `Class ((pos, name), class_info, c_ty) -> let pos = Pos_or_decl.unsafe_to_raw_pos pos in let kind = Cls.kind class_info in if Ast_defs.is_c_trait kind || Ast_defs.is_c_enum kind || Ast_defs.is_c_enum_class kind then match cid with | CIexpr _ | CI _ -> uninstantiable_error env p cid (Cls.pos class_info) name pos c_ty | CIstatic | CIparent | CIself -> () else if Ast_defs.is_c_abstract kind && Cls.final class_info then uninstantiable_error env p cid (Cls.pos class_info) name pos c_ty else ()); (env, tal, te, classes) (* Deal with assignment of a value of type ty2 to lvalue e1 *) and assign p env e1 pos2 ty2 = assign_with_subtype_err_ p Reason.URassign env e1 pos2 ty2 and assign_ p ur env e1 pos2 ty2 = let (env, te, ty, _err) = assign_with_subtype_err_ p ur env e1 pos2 ty2 in (env, te, ty) and assign_with_subtype_err_ p ur env (e1 : Nast.expr) pos2 ty2 = match e1 with | (_, _, Hole (e, _, _, _)) -> assign_with_subtype_err_ p ur env e pos2 ty2 | _ -> let allow_awaitable = (*?*) false in let env = match e1 with | (_, _, Lvar (_, x)) -> Env.forget_prefixed_members env x Reason.(Blame (p, BSassignment)) (* If we ever extend fake members from $x->a to more complicated lvalues such as $x->a->b, we would need to call forget_prefixed_members on other lvalues as well. *) | (_, _, Obj_get (_, (_, _, Id (_, property)), _, _)) -> Env.forget_suffixed_members env property Reason.(Blame (p, BSassignment)) | _ -> env in (match e1 with | (_, _, Lvar ((_, x) as id)) -> let env = set_valid_rvalue ~is_defined:true p env x None ty2 in let (_, p1, _) = e1 in let (env, te, ty) = make_result env p1 (Aast.Lvar id) ty2 in (env, te, ty, None) | (_, _, Lplaceholder id) -> let placeholder_ty = MakeType.void (Reason.Rplaceholder p) in let (_, p1, _) = e1 in let (env, te, ty) = make_result env p1 (Aast.Lplaceholder id) placeholder_ty in (env, te, ty, None) | (_, _, List el) -> (* Generate fresh types for each lhs list element, then subtype against rhs type. If original type was generated from an error, propagate this to avoid cascading errors. *) let is_error_type = TUtils.is_tyvar_error env ty2 in let env = Env.open_tyvars env p in let (env, tyl) = List.map_env env el ~f:(fun env (_, p, _e) -> if is_error_type then Env.fresh_type_error env p else Env.fresh_type env p) in let (_, p1, _) = e1 in let destructure_ty = MakeType.list_destructure (Reason.Rdestructure p1) tyl in let env = Env.set_tyvar_variance_i env destructure_ty in let lty2 = LoclType ty2 in let assign_accumulate (env, tel, errs) (lvalue : Nast.expr) ty2 = let (env, te, _, err_opt) = assign p env lvalue pos2 ty2 in (env, te :: tel, err_opt :: errs) in let type_list_elem env = let (env, reversed_tel, rev_subtype_errs) = List.fold2_exn el tyl ~init:(env, [], []) ~f:assign_accumulate in let (_, p1, _) = e1 in let (env, te, ty) = make_result env p1 (Aast.List (List.rev reversed_tel)) ty2 in (env, te, ty, List.rev rev_subtype_errs) in (* Here we attempt to unify the type of the rhs we assigning with a number of fresh tyvars corresponding to the arity of the lhs `list` if we have a failure in subtyping the fresh tyvars in `destructure_ty`, we have a rhs which cannot be destructured to the variables on the lhs; e.g. `list($x,$y) = 2` or `list($x,$y) = tuple (1,2,3)` in the error case, we add a `Hole` with expected type `nothing` since there is no type we can suggest was expected in the ok case were the destrucutring succeeded, the fresh vars now have types so we can subtype each element, accumulate the errors and pack back into the rhs structure as our expected type *) let (env, ty_err1) = Type.sub_type_i p ur env lty2 destructure_ty Typing_error.Callback.unify_error in let (env, ty_err2) = Typing_solver.close_tyvars_and_solve env in let ty_err_opt = Option.merge ty_err1 ty_err2 ~f:Typing_error.both in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (match ty_err_opt with | None -> let (env, te, ty, subty_errs) = type_list_elem env in let err_opt = if List.for_all subty_errs ~f:Option.is_none then None else Some (ty2, pack_errs pos2 ty2 (subty_errs, None)) in (env, te, ty, err_opt) | Some _ -> let (env, te, ty, _) = type_list_elem env in let nothing = MakeType.nothing @@ Reason.Rsolve_fail (Pos_or_decl.of_raw_pos pos2) in (env, te, ty, Some (ty2, nothing))) | ( _, pobj, Obj_get (obj, (_, pm, Id ((_, member_name) as m)), nullflavor, prop_or_method) ) -> let lenv = env.lenv in let nullsafe = match nullflavor with | OG_nullthrows -> None | OG_nullsafe -> Some (Reason.Rnullsafe_op pobj) in let (env, tobj, obj_ty) = expr ~accept_using_var:true env obj ~allow_awaitable in let env = might_throw ~join_pos:p env in let (_, p1, _) = obj in let ( (env, ty_err_opt), (declared_ty, _tal), lval_ty_mismatch_opt, rval_ty_mismatch_opt ) = TOG.obj_get_with_mismatches ~obj_pos:p1 ~is_method:false ~nullsafe ~inst_meth:false ~meth_caller:false ~coerce_from_ty:(Some (p, ur, ty2)) ~explicit_targs:[] ~class_id:(CIexpr e1) ~member_id:m ~on_error:Typing_error.Callback.unify_error env obj_ty in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let (env, inner_te) = TUtils.make_simplify_typed_expr env pm declared_ty (Aast.Id m) in let (env, te1) = TUtils.make_simplify_typed_expr env pobj declared_ty (Aast.Obj_get ( hole_on_ty_mismatch ~ty_mismatch_opt:lval_ty_mismatch_opt tobj, inner_te, nullflavor, prop_or_method )) in let env = { env with lenv } in begin match obj with | (_, _, This) | (_, _, Lvar _) -> let (env, local) = Env.FakeMembers.make env obj member_name p in let (env, refined_ty) = Inter.intersect env ~r:(Reason.Rwitness p) declared_ty ty2 in let env = set_valid_rvalue ~is_defined:true p env local None refined_ty in (env, te1, ty2, rval_ty_mismatch_opt) | _ -> (env, te1, ty2, rval_ty_mismatch_opt) end | (_, _, Class_get (((_, _, x) as cid), CGstring (pos_member, y), _)) -> let lenv = env.lenv in let no_fakes = LEnv.env_with_empty_fakes env in let (env, te1, _) = lvalue no_fakes e1 in let env = { env with lenv } in let (env, ety2) = Env.expand_type env ty2 in (* This defers the coercion check to class_get, which looks up the appropriate target type *) let (env, _tal, _, cty) = class_expr env [] cid in let env = might_throw ~join_pos:p env in let (env, (declared_ty, _), rval_err_opt) = class_get_err ~is_method:false ~is_const:false ~transform_fty:None ~coerce_from_ty:(Some (p, ur, ety2)) env cty (pos_member, y) cid in let (env, local) = Env.FakeMembers.make_static env x y p in let (env, refined_ty) = Inter.intersect env ~r:(Reason.Rwitness p) declared_ty ty2 in let env = set_valid_rvalue ~is_defined:true p env local None refined_ty in (env, te1, ty2, rval_err_opt) | (_, _, Obj_get _) | (_, _, Class_get _) -> let lenv = env.lenv in let no_fakes = LEnv.env_with_empty_fakes env in let (env, te1, real_type) = lvalue no_fakes e1 in let (env, exp_real_type) = Env.expand_type env real_type in let env = { env with lenv } in let (env, ty_err_opt) = Typing_coercion.coerce_type p ur env ty2 (MakeType.unenforced exp_real_type) Typing_error.Callback.unify_error in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let ty_mismatch = mk_ty_mismatch_opt ty2 exp_real_type ty_err_opt in (env, te1, ty2, ty_mismatch) | (_, pos, Array_get (e1, None)) -> let parent_lenv = env.lenv in let (env, te1, ty1) = update_array_type pos env e1 Lvalue in let (_, p1, _) = e1 in let (env, (ty1', arr_ty_mismatch_opt, val_ty_mismatch_opt)) = Typing_array_access.assign_array_append ~array_pos:p1 ~expr_pos:p ur env ty1 ty2 in let (ty1_is_hack_collection, ty_err_opt) = is_hack_collection env ty1 in let (env, te1) = if ty1_is_hack_collection then (env, hole_on_ty_mismatch ~ty_mismatch_opt:arr_ty_mismatch_opt te1) else let env = { env with lenv = parent_lenv } in let env = might_throw ~join_pos:p env in let (env, te1, ty, _) = assign_with_subtype_err_ p ur env e1 p1 ty1' in (* Update the actual type to that after assignment *) let arr_ty_mismatch_opt = Option.map arr_ty_mismatch_opt ~f:(fun (_, ty_expect) -> (ty, ty_expect)) in (env, hole_on_ty_mismatch ~ty_mismatch_opt:arr_ty_mismatch_opt te1) in let (env, te, ty) = make_result env pos (Aast.Array_get (te1, None)) ty2 in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (env, te, ty, val_ty_mismatch_opt) | (_, pos, Array_get (e1, Some e)) -> let (env, te, ty) = expr env e ~allow_awaitable in let parent_lenv = env.lenv in let (env, te1, ty1) = update_array_type pos env e1 Lvalue in let env = might_throw ~join_pos:p env in let (_, p1, _) = e1 in let ( env, (ty1', arr_ty_mismatch_opt, key_ty_mismatch_opt, val_ty_mismatch_opt) ) = Typing_array_access.assign_array_get ~array_pos:p1 ~expr_pos:p ur env ty1 e ty ty2 in let (ty1_is_hack_collection, ty_err_opt) = is_hack_collection env ty1 in let (env, te1) = if ty1_is_hack_collection then (env, hole_on_ty_mismatch ~ty_mismatch_opt:arr_ty_mismatch_opt te1) else let env = { env with lenv = parent_lenv } in let env = might_throw ~join_pos:p env in let (env, te1, ty, _) = assign_with_subtype_err_ p ur env e1 p1 ty1' in (* Update the actual type to that after assignment *) let arr_ty_mismatch_opt = Option.map arr_ty_mismatch_opt ~f:(fun (_, ty_expect) -> (ty, ty_expect)) in (env, hole_on_ty_mismatch ~ty_mismatch_opt:arr_ty_mismatch_opt te1) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; ( env, ( ty2, pos, Aast.Array_get ( te1, Some (hole_on_ty_mismatch ~ty_mismatch_opt:key_ty_mismatch_opt te) ) ), ty2, val_ty_mismatch_opt ) | (_, pos, ReadonlyExpr e) -> let (env, te1, ty, err) = assign_with_subtype_err_ pos ur env e pos2 ty2 in (env, (ty, pos, Aast.ReadonlyExpr te1), ty, err) | _ -> assign_simple p ur env e1 ty2) and assign_simple pos ur env e1 ty2 = let (env, te1, ty1) = lvalue env e1 in let (env, ty_err_opt) = Typing_coercion.coerce_type pos ur env ty2 (MakeType.unenforced ty1) Typing_error.Callback.unify_error in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let ty_mismatch = mk_ty_mismatch_opt ty2 ty1 ty_err_opt in (env, te1, ty2, ty_mismatch) and array_field env ~allow_awaitable = function | AFvalue ve -> let (env, tve, tv) = expr env ve ~allow_awaitable in (env, (Aast.AFvalue tve, None, tv)) | AFkvalue (ke, ve) -> let (env, tke, tk) = expr env ke ~allow_awaitable in let (env, tve, tv) = expr env ve ~allow_awaitable in (env, (Aast.AFkvalue (tke, tve), Some tk, tv)) and array_value ~(expected : ExpectedTy.t option) env x = let (env, te, ty) = expr ?expected env x ~allow_awaitable:(*?*) false in (env, (te, ty)) and arraykey_value p class_name is_set ~(expected : ExpectedTy.t option) env ((_, pos, _) as x) = let (env, (te, ty)) = array_value ~expected env x in let (ty_arraykey, reason) = if is_set then ( MakeType.arraykey (Reason.Rset_element pos), Reason.set_element class_name ) else (MakeType.arraykey (Reason.Ridx_dict pos), Reason.index_class class_name) in let ty_expected = { et_type = ty_arraykey; et_enforced = Enforced } in let ((env, ty_err_opt), te) = (* If we have an error in coercion here, we will add a `Hole` indicating the actual and expected type. The `Hole` may then be used in a codemod to add a call to `UNSAFE_CAST` so we need to consider what type we expect. If we were to add an expected type of 'arraykey' here it would be correct but adding an `UNSAFE_CAST<?string,arraykey>($x)` means we get cascading errors if we have e.g. a return type of keyset<string>. To try and prevent this, if this is an optional type where the nonnull part can be coerced to arraykey, we prefer that type as our expected type. *) let (ty_actual, is_option) = match deref ty with | (_, Toption ty_inner) -> (ty_inner, true) | _ -> (ty, false) in let (env, e1) = Typing_coercion.coerce_type ~coerce_for_op:true p reason env ty_actual ty_expected Typing_error.Callback.unify_error in let (ty_mismatch_opt, e2) = match e1 with | None when is_option -> let ty_str = lazy (Typing_print.full_strip_ns env ty_actual) in let reasons_opt = Some (Lazy.map ty_str ~f:(fun ty_str -> Reason.to_string "Expected `arraykey`" (Reason.Ridx_dict pos) @ [(get_pos ty, Format.sprintf "But got `?%s`" ty_str)])) in (* We actually failed so generate the error we should have seen *) let ty_err = Typing_error.( primary @@ Primary.Unify_error { pos; msg_opt = Some (Reason.string_of_ureason reason); reasons_opt; }) in (Some (ty, ty_actual), Some ty_err) | Some _ | None -> (None, None) in let ty_err_opt = Option.merge e1 e2 ~f:Typing_error.both in ((env, ty_err_opt), hole_on_ty_mismatch ~ty_mismatch_opt te) in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); (env, (te, ty)) and check_parent_construct pos recv_pos env el unpacked_element env_parent = let check_not_abstract = false in let ((env, ty_err_opt), env_parent) = Phase.localize_no_subst env ~ignore_errors:true env_parent in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let ( env, _tcid, _tal, tel, typed_unpack_element, parent, fty, should_forget_fakes ) = new_object ~expected:None ~check_parent:true ~check_not_abstract ~is_using_clause:false pos env ((), recv_pos, CIparent) [] el unpacked_element in (* Not sure why we need to equate these types *) let (env, e1) = Type.sub_type pos Reason.URnone env env_parent parent Typing_error.Callback.unify_error in let (env, e2) = Type.sub_type pos Reason.URnone env parent env_parent Typing_error.Callback.unify_error in Option.( iter ~f:(Typing_error_utils.add_typing_error ~env) @@ merge e1 e2 ~f:Typing_error.both); ( env, tel, typed_unpack_element, MakeType.void (Reason.Rwitness pos), parent, fty, should_forget_fakes ) and call_parent_construct pos recv_pos env el unpacked_element = match Env.get_parent_ty env with | Some parent -> check_parent_construct pos recv_pos env el unpacked_element parent | None -> (* continue here *) let (env, ty) = Env.fresh_type_error env pos in let should_invalidate_fake_members = true in let default = (env, [], None, ty, ty, ty, should_invalidate_fake_members) in (match Env.get_self_id env with | Some self -> (match Env.get_class env self with | Some trait when Ast_defs.is_c_trait (Cls.kind trait) -> (match trait_most_concrete_req_class trait env with | None -> Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.Parent_in_trait pos); default | Some (c, parent_ty) -> (match Cls.construct c with | (_, Inconsistent) -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Trait_parent_construct_inconsistent { pos; decl_pos = Cls.pos c }) | _ -> ()); check_parent_construct pos recv_pos env el unpacked_element parent_ty) | Some _self_tc -> Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.Undefined_parent pos); default | None -> assert false) | None -> Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.Parent_outside_class pos); let (env, ty) = Env.fresh_type_error env pos in (env, [], None, ty, ty, ty, should_invalidate_fake_members)) (* Depending on the kind of expression we are dealing with * The typing of call is different. *) and dispatch_call ~(expected : ExpectedTy.t option) ~is_using_clause ~valkind ?in_await p env ((_, fpos, fun_expr) as e : Nast.expr) explicit_targs el unpacked_element = let expr = expr ~allow_awaitable:(*?*) false in let make_call env func targs args unpacked_arg ty = make_result env p (Aast.Call { func; targs; args; unpacked_arg }) ty in (* TODO: Avoid Tany annotations in TAST by eliminating `make_call_special` *) let make_call_special env id tel ty = make_call env (Tast.make_typed_expr fpos (TUtils.mk_tany env fpos) (Aast.Id id)) [] tel None ty in (* For special functions and pseudofunctions with a definition in an HHI * file. It is preferred over [make_call_special] because it does not generate * [TAny] for the function type of the call. *) let make_call_special_from_def env id tel ty_ = let (env, fty, tal) = fun_type_of_id env id explicit_targs el in let ty = match get_node fty with | Tfun ft -> ft.ft_ret.et_type | _ -> ty_ (Reason.Rwitness p) in let (env, te) = TUtils.make_simplify_typed_expr env fpos fty (Aast.Id id) in make_call env te tal tel None ty in let overload_function = overload_function make_call fpos in (* Require [get_idisposable_value()] function calls to be inside a [using] statement. *) let check_disposable_in_return env fty = if is_return_disposable_fun_type env fty && not is_using_clause then Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.Invalid_new_disposable p) in let dispatch_id env id = let (env, fty, tal) = fun_type_of_id env id explicit_targs el in check_disposable_in_return env fty; let (env, (tel, typed_unpack_element, ty, should_forget_fakes)) = call ~expected ~expr_pos:p ~recv_pos:(fst id) env fty el unpacked_element in let (env, inner_te) = TUtils.make_simplify_typed_expr env fpos fty (Aast.Id id) in let result = make_call env inner_te tal tel typed_unpack_element ty in (result, should_forget_fakes) in (* The optional transform_fty parameter is used to transform function * type decls for special static methods, currently just Shapes::at * and Shapes::idx *) let dispatch_class_const ?transform_fty env ((_, pos, e1_) as e1) m = let (env, _tal, tcid, ty1) = class_expr env [] e1 in let this_ty = MakeType.this (Reason.Rwitness fpos) in (* In static context, you can only call parent::foo() on static methods. * In instance context, you can call parent:foo() on static * methods as well as instance methods *) let is_static = (not (Nast.equal_class_id_ e1_ CIparent)) || Env.is_static env || class_contains_smethod env ty1 m in let ((env, ty_err_opt), (fty, tal)) = if not is_static then (* parent::nonStaticFunc() is really weird. It's calling a method * defined on the parent class, but $this is still the child class. *) TOG.obj_get ~inst_meth:false ~meth_caller:false ~is_method:true ~nullsafe:None ~obj_pos:pos ~coerce_from_ty:None ~explicit_targs:[] ~class_id:e1_ ~member_id:m ~on_error:Typing_error.Callback.unify_error ~parent_ty:ty1 env this_ty else let (env, res) = class_get ~coerce_from_ty:None ~is_method:true ~transform_fty ~is_const:false ~explicit_targs env ty1 m e1 in ((env, None), res) in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); check_disposable_in_return env fty; let (env, (tel, typed_unpack_element, ty, should_forget_fakes)) = call ~expected ~expr_pos:p ~recv_pos:fpos env fty el unpacked_element in let (env, te) = TUtils.make_simplify_typed_expr env fpos fty (Aast.Class_const (tcid, m)) in let result = make_call env te tal tel typed_unpack_element ty in (result, should_forget_fakes) in match fun_expr with (* Special top-level function *) | Id ((pos, x) as id) when SN.StdlibFunctions.needs_special_dispatch x -> begin match x with (* Special function [echo]. *) | echo when String.equal echo SN.SpecialFunctions.echo -> (* TODO(tany): TODO(T92020097): * Add [function print(arraykey ...$args)[io]: void] to an HHI file and * remove special casing of [echo] and [print]. *) let env = Typing_local_ops.enforce_io pos env in let (env, tel, _) = argument_list_exprs (expr ~accept_using_var:true) env el in let arraykey_ty = MakeType.arraykey (Reason.Rwitness pos) in let like_ak_ty = MakeType.union (Reason.Rwitness pos) [MakeType.dynamic (Reason.Rwitness pos); arraykey_ty] in let ((env, ty_errs), rev_tel) = List.fold tel ~init:((env, []), []) ~f:(fun ((env, ty_errs), tel) (pk, ((ty, pos, _) as te)) -> let (env, ty_err_opt) = SubType.sub_type env ty like_ak_ty @@ Some (Typing_error.Reasons_callback.invalid_echo_argument_at pos) in let ty_mismatch_opt = mk_ty_mismatch_opt ty arraykey_ty ty_err_opt in let ty_errs = Option.value_map ~default:ty_errs ~f:(fun e -> e :: ty_errs) ty_err_opt in ( (env, ty_errs), (pk, hole_on_ty_mismatch ~ty_mismatch_opt te) :: tel )) in let tel = List.rev rev_tel in let should_forget_fakes = false 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; ( make_call_special env id tel (MakeType.void (Reason.Rwitness pos)), should_forget_fakes ) (* `unsafe_cast` *) | unsafe_cast when String.equal unsafe_cast SN.PseudoFunctions.unsafe_cast || String.equal unsafe_cast SN.PseudoFunctions.unsafe_nonnull_cast -> let result = match el with | [(Ast_defs.Pnormal, original_expr)] when TCO.ignore_unsafe_cast (Env.get_tcopt env) -> expr env original_expr | _ -> (* first type the `unsafe_cast` as a call, handling arity errors *) let (env, fty, tal) = fun_type_of_id env id explicit_targs el in check_disposable_in_return env fty; let (env, (tel, _, ty, _should_forget_fakes)) = call ~expected ~expr_pos:p ~recv_pos:fpos env fty el unpacked_element in (* construct the `Hole` using default value and type arguments if necessary *) let (env, dflt_ty) = Env.fresh_type_invariant env p in let el = match tel with | (_, e) :: _ -> e | [] -> Tast.make_typed_expr fpos dflt_ty Aast.Null and (ty_from, ty_to) = match tal with | (ty_from, _) :: (ty_to, _) :: _ -> (ty_from, ty_to) | (ty, _) :: _ -> (ty, ty) | _ -> (dflt_ty, dflt_ty) in let hole_source = if String.equal unsafe_cast SN.PseudoFunctions.unsafe_cast then UnsafeCast (List.map ~f:snd explicit_targs) else UnsafeNonnullCast in let te = Aast.Hole (el, ty_from, ty_to, hole_source) in make_result env p te ty in let should_forget_fakes = false in (result, should_forget_fakes) (* Special function `isset` *) | isset when String.equal isset SN.PseudoFunctions.isset -> let (env, tel, _) = argument_list_exprs (expr ~accept_using_var:true ~check_defined:false) env el in if Option.is_some unpacked_element then Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Unpacking_disallowed_builtin_function { pos = p; fn_name = isset }); let should_forget_fakes = false in let result = make_call_special_from_def env id tel MakeType.bool in (result, should_forget_fakes) (* Special function `unset` *) | unset when String.equal unset SN.PseudoFunctions.unset -> let (env, tel, _) = argument_list_exprs expr env el in if Option.is_some unpacked_element then Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Unpacking_disallowed_builtin_function { pos = p; fn_name = unset }); let env = Typing_local_ops.check_unset_target env tel in let (env, ty_err_opt) = match (el, unpacked_element) with | ([(Ast_defs.Pnormal, (_, _, Array_get (ea, Some _)))], None) -> let (env, _te, ty) = expr env ea in let r = Reason.Rwitness p in let tmixed = MakeType.mixed r in let super = mk ( r, Tunion [ MakeType.dynamic r; MakeType.dict r tmixed tmixed; MakeType.keyset r tmixed; ] ) in let reason = lazy (Reason.to_string ("This is " ^ Typing_print.error ~ignore_dynamic:true env ty) (get_reason ty)) in SubType.sub_type_or_fail env ty super @@ Some Typing_error.( primary @@ Primary.Unset_nonidx_in_strict { pos = p; reason }) | _ -> let ty_err = Typing_error.( primary @@ Primary.Unset_nonidx_in_strict { pos = p; reason = lazy [] }) in (env, Some ty_err) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let should_forget_fakes = false in let result = match el with | [(_, (_, p, Obj_get (_, _, OG_nullsafe, _)))] -> (Typing_error_utils.add_typing_error ~env @@ Typing_error.(primary @@ Primary.Nullsafe_property_write_context p) ); let (env, ty) = Env.fresh_type_error env p in make_call_special_from_def env id tel (fun _ -> ty) | _ -> make_call_special_from_def env id tel MakeType.void in (result, should_forget_fakes) | type_structure when String.equal type_structure SN.StdlibFunctions.type_structure && Int.equal (List.length el) 2 && Option.is_none unpacked_element -> let should_forget_fakes = false in (match el with | [e1; e2] -> (match e2 with | (_, (_, p, String cst)) -> (* find the class constant implicitly defined by the typeconst *) let cid = match e1 with | (_, (_, _, Class_const (cid, (_, x)))) | (_, (_, _, Class_get (cid, CGstring (_, x), _))) when String.equal x SN.Members.mClass -> cid | _ -> let (_, ((_, p1, _) as e1_)) = e1 in ((), p1, CIexpr e1_) in let result = class_const ~incl_tc:true env p (cid, (p, cst)) in let () = match result with | (_, (ty, _, _), _) when TUtils.is_tyvar_error env ty -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Illegal_type_structure { pos; msg = "Could not resolve the type constant" }) | _ -> () in (result, should_forget_fakes) | _ -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Illegal_type_structure { pos; msg = "Second argument is not a string" }); let result = expr_error env pos e in (result, should_forget_fakes)) | _ -> assert false) | _ -> dispatch_id env id end (* Special Shapes:: function *) | Class_const (((_, _, CI (_, shapes)) as class_id), ((_, x) as method_id)) when String.equal shapes SN.Shapes.cShapes || String.equal shapes SN.Shapes.cReadonlyShapes -> begin match x with (* Special functions `Shapes::at`, `Shapes::idx` and `Shapes::keyExists`. * We implement these by transforming the function type decl that's fetched * from the hhi *) | _ when String.equal x SN.Shapes.at || String.equal x SN.Shapes.idx || String.equal x SN.Shapes.keyExists -> let transform_fty = (* We expect the second argument to at, idx and keyExists to be a literal field name *) match el with | _ :: (_, field) :: _ -> begin 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 -> None | Some field_name -> let field_name = TShapeField.of_ast Pos_or_decl.of_raw_pos field_name in Some (fun fty -> Typing_shapes.transform_special_shapes_fun_ty field_name method_id (List.length el) fty) end | _ -> None in dispatch_class_const env class_id method_id ?transform_fty (* Special function `Shapes::removeKey` *) | remove_key when String.equal remove_key SN.Shapes.removeKey -> overload_function p env class_id method_id el unpacked_element (fun env _ res el _tel -> match el with | [(Ast_defs.Pinout _, shape); (_, field)] -> begin match shape with | (_, _, Lvar (_, lvar)) | (_, _, Hole ((_, _, Lvar (_, lvar)), _, _, _)) -> (* We reevaluate the shape instead of using the shape type evaluated during typechecking against the HHI signature because this argument is inout and bidirectional typechecking causes a union with the open shape type which defeats the purpose of this extra-logical function. *) let (env, _te, shape_ty) = expr env shape in let (env, shape_ty) = Typing_shapes.remove_key p env shape_ty field in let env = set_valid_rvalue ~is_defined:true p env lvar None shape_ty in (env, res) | (_, shape_pos, _) -> Typing_error_utils.add_typing_error ~env Typing_error.( shape @@ Primary.Shape.Invalid_shape_remove_key shape_pos); (env, res) end | _ -> (env, res)) (* Special functions `Shapes::toDict` and `Shapes::toArray` *) | to_dict when String.equal to_dict SN.Shapes.toDict || String.equal to_dict SN.Shapes.toArray -> overload_function p env class_id method_id el unpacked_element (fun env _ res _el tel -> match tel with | [(_, (shape_ty, _, _))] -> Typing_shapes.to_dict env p shape_ty res | _ -> (env, res)) | _ -> dispatch_class_const env class_id method_id end (* Special function `parent::__construct` *) | Class_const ((_, pos, CIparent), ((_, construct) as id)) when String.equal construct SN.Members.__construct -> let (env, tel, typed_unpack_element, ty, pty, ctor_fty, should_forget_fakes) = call_parent_construct p pos env el unpacked_element in let (env, te) = TUtils.make_simplify_typed_expr env fpos ctor_fty (Aast.Class_const ((pty, pos, Aast.CIparent), id)) in let result = make_call env te [] (* tal: no type arguments to constructor *) tel typed_unpack_element ty in (result, should_forget_fakes) (* Calling parent / class method *) | Class_const (class_id, m) -> dispatch_class_const env class_id m (* Readonly Expressions do not affect the type, but need to be threaded through when they're part of a call *) | ReadonlyExpr r -> let env = Env.set_readonly env true in (* Recurse onto the inner call *) let ((env, expr, ty), s) = dispatch_call ~expected ~is_using_clause ~valkind ?in_await p env r explicit_targs el unpacked_element in (match expr with | (ty, _, Call { func; targs; args; unpacked_arg }) -> let (caller_ty, caller_pos, _) = func in (* Rewrap the caller in the readonly expression after we're done *) let (env, wrapped_caller) = TUtils.make_simplify_typed_expr env caller_pos caller_ty (Aast.ReadonlyExpr func) in let result = make_call env wrapped_caller targs args unpacked_arg ty in (result, s) | _ -> ((env, expr, ty), s)) (* Call instance method *) | Obj_get (e1, (_, pos_id, Id m), nullflavor, Is_method) when not (TCO.method_call_inference (Env.get_tcopt env)) -> let (env, te1, ty1) = expr ~accept_using_var:true env e1 in let nullsafe = match nullflavor with | OG_nullthrows -> None | OG_nullsafe -> Some p in let (_, p1, _) = e1 in let ( (env, ty_err_opt), (tfty, tal), lval_ty_mismatch_opt, _rval_ty_mismatch_opt ) = TOG.obj_get_with_mismatches ~obj_pos:p1 ~is_method:true ~inst_meth:false ~meth_caller:false ~nullsafe:(Option.map ~f:(fun p -> Reason.Rnullsafe_op p) nullsafe) ~coerce_from_ty:None ~explicit_targs ~class_id:(CIexpr e1) ~member_id:m ~on_error:Typing_error.Callback.unify_error env ty1 in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); check_disposable_in_return env tfty; let (env, (tel, typed_unpack_element, ty, should_forget_fakes)) = call ~nullsafe ~expected ~expr_pos:p ~recv_pos:pos_id env tfty el unpacked_element in let (env, inner_te) = TUtils.make_simplify_typed_expr env pos_id tfty (Aast.Id m) in let (env, te) = TUtils.make_simplify_typed_expr env fpos tfty (Aast.Obj_get ( hole_on_ty_mismatch ~ty_mismatch_opt:lval_ty_mismatch_opt te1, inner_te, nullflavor, Is_method )) in let result = make_call env te tal tel typed_unpack_element ty in (result, should_forget_fakes) (* Call instance method using new method call inference *) | Obj_get (receiver, (_, pos_id, Id meth), nullflavor, Is_method) -> (***** Typecheck `Obj_get` by enforcing that: - `<instance_type>` <: `Thas_member(m, #1)` where #1 is a fresh type variable. *****) let (env, typed_receiver, receiver_ty) = expr ~accept_using_var:true env receiver in let env = might_throw ~join_pos:p env in let nullsafe = match nullflavor with | OG_nullthrows -> None | OG_nullsafe -> Some p in (* Generate a fresh type `method_ty` for the type of the instance method, i.e. #1 *) let (env, method_ty) = Env.fresh_type env p in (* Create `Thas_member` constraint type *) let (_, receiver_p, _) = receiver in let reason = Reason.Rwitness receiver_p in let has_method_ty = MakeType.has_member reason ~name:meth ~ty:method_ty ~class_id:(CIexpr receiver) ~explicit_targs:(Some explicit_targs) in let env = Env.set_tyvar_variance env method_ty in let (env, has_method_super_ty) = if Option.is_none nullsafe then (env, has_method_ty) else (* If null-safe, then `receiver_ty` <: `?Thas_member(m, #1)`, but *unlike* property access typing in `expr_`, we still use `#1` as our "result" if `receiver_ty` is nullable (as opposed to `?#1`), deferring null-safety handling to after `call` *) let r = Reason.Rnullsafe_op p in let null_ty = MakeType.null r in Union.union_i env r has_method_ty null_ty in let (_, receiver_pos, _) = receiver in let (env, ty_err_opt) = Type.sub_type_i receiver_pos Reason.URnone env (LoclType receiver_ty) has_method_super_ty Typing_error.Callback.unify_error in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let ty_nothing = MakeType.nothing Reason.none in let ty_mismatch_opt = mk_ty_mismatch_opt receiver_ty ty_nothing ty_err_opt in (* Perhaps solve for `method_ty`. Opening and closing a scope is too coarse here - type parameters are localised to fresh type variables over the course of subtyping above, and we do not want to solve these until later. Once we typecheck all function calls with a subtyping of function types, we should not need to solve early at all - transitive closure of subtyping should give enough information. *) let (env, ty_err_opt1) = match get_var method_ty with | Some var -> Typing_solver.solve_to_equal_bound_or_wrt_variance env Reason.Rnone var | None -> (env, None) in let localize_targ env (_, targ) = Phase.localize_targ env targ in let ((env, ty_err_opt), typed_targs) = List.map_env_ty_err_opt env ~f:(localize_targ ~check_well_kinded:true) explicit_targs ~combine_ty_errs:Typing_error.multiple_opt in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; check_disposable_in_return env method_ty; let (env, (typed_params, typed_unpack_element, ret_ty, should_forget_fakes)) = call ~nullsafe ~expected ?in_await ~expr_pos:p ~recv_pos:fpos env method_ty el unpacked_element in (* If the call is nullsafe AND the receiver is nullable, make the return type nullable too *) let (env, ret_ty) = if Option.is_some nullsafe then let r = Reason.Rnullsafe_op p in let null_ty = MakeType.null r in let (env, null_or_nothing_ty) = Inter.intersect env ~r null_ty receiver_ty in let (env, ret_option_ty) = Union.union env null_or_nothing_ty ret_ty in (env, ret_option_ty) else (env, ret_ty) in let (env, inner_te1) = TUtils.make_simplify_typed_expr env pos_id method_ty (Aast.Id meth) in let (env, inner_te2) = TUtils.make_simplify_typed_expr env fpos method_ty (Aast.Obj_get ( hole_on_ty_mismatch ~ty_mismatch_opt typed_receiver, inner_te1, nullflavor, Is_method )) in let result = make_call env inner_te2 typed_targs typed_params typed_unpack_element ret_ty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt1; (result, should_forget_fakes) (* Function invocation *) | Id id -> dispatch_id env id | _ -> let (env, te, fty) = expr env e in let ((env, ty_err_opt1), fty) = Typing_solver.expand_type_and_solve ~description_of_expected:"a function value" env fpos fty in check_disposable_in_return env fty; let (env, (tel, typed_unpack_element, ty, should_forget_fakes)) = call ~expected ~expr_pos:p ~recv_pos:fpos env fty el unpacked_element in let result = make_call env te (* tal: no type arguments to function values, as they are non-generic *) [] tel typed_unpack_element ty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt1; (result, should_forget_fakes) and class_get_res ~is_method ~is_const ~transform_fty ~coerce_from_ty ?(explicit_targs = []) ?(incl_tc = false) ?(is_function_pointer = false) env cty (p, mid) cid = let (env, this_ty) = if is_method then this_for_method env cid cty else (env, cty) in class_get_inner ~is_method ~is_const ~transform_fty ~this_ty ~explicit_targs ~incl_tc ~coerce_from_ty ~is_function_pointer env cid cty (p, mid) and class_get_err ~is_method ~is_const ~transform_fty ~coerce_from_ty ?explicit_targs ?incl_tc ?is_function_pointer env cty (p, mid) cid = let (env, tys, rval_res_opt) = class_get_res ~is_method ~is_const ~transform_fty ~coerce_from_ty ?explicit_targs ?incl_tc ?is_function_pointer env cty (p, mid) cid in let rval_err_opt = Option.bind ~f:Result.error rval_res_opt in (env, tys, rval_err_opt) and class_get ~is_method ~is_const ~transform_fty ~coerce_from_ty ?explicit_targs ?incl_tc ?is_function_pointer env cty (p, mid) cid = let (env, tys, _) = class_get_res ~is_method ~is_const ~transform_fty ~coerce_from_ty ?explicit_targs ?incl_tc ?is_function_pointer env cty (p, mid) cid in (env, tys) and class_get_inner ~is_method ~is_const ~this_ty ~coerce_from_ty ~transform_fty ?(explicit_targs = []) ?(incl_tc = false) ?(is_function_pointer = false) env ((_, _cid_pos, cid_) as cid) cty (p, mid) = let (env, cty) = Env.expand_type env cty in let dflt_rval_err = Option.map ~f:(fun (_, _, ty) -> Ok ty) coerce_from_ty in match deref cty with | (_, (Tdynamic | Tany _)) -> (env, (cty, []), dflt_rval_err) | (_, Tunion tyl) -> let (env, pairs, rval_err_opts) = List.fold_left tyl ~init:(env, [], []) ~f:(fun (env, pairs, rval_err_opts) ty -> let (env, pair, rval_err_opt) = class_get_res ~is_method ~is_const ~transform_fty ~explicit_targs ~incl_tc ~coerce_from_ty ~is_function_pointer env ty (p, mid) cid in (env, pair :: pairs, rval_err_opt :: rval_err_opts)) in let rval_err = Option.(map ~f:union_coercion_errs @@ all rval_err_opts) in let (env, ty) = Union.union_list env (get_reason cty) (List.map ~f:fst pairs) in (env, (ty, []), rval_err) | (_, Tintersection tyl) -> let (env, pairs, rval_err_opts) = TUtils.run_on_intersection_res env tyl ~f:(fun env ty -> class_get_inner ~is_method ~is_const ~transform_fty ~this_ty ~explicit_targs ~incl_tc ~coerce_from_ty ~is_function_pointer env cid ty (p, mid)) in let rval_err = Option.(map ~f:intersect_coercion_errs @@ all rval_err_opts) in let (env, ty) = Inter.intersect_list env (get_reason cty) (List.map ~f:fst pairs) in (env, (ty, []), rval_err) | (_, Tnewtype (_, _, ty)) | (_, Tdependent (_, ty)) -> class_get_inner ~is_method ~is_const ~transform_fty ~this_ty ~explicit_targs ~incl_tc ~coerce_from_ty ~is_function_pointer env cid ty (p, mid) | (r, Tgeneric _) -> let (env, tyl) = TUtils.get_concrete_supertypes ~abstract_enum:true env cty in let (env, has_no_bound) = TUtils.no_upper_bound ~include_sd_mixed:true env tyl in if has_no_bound then begin let (env, ty) = Env.fresh_type_error env p in Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Non_class_member { elt = (if is_method then `meth else `prop); member_name = mid; pos = p; ty_name = lazy (Typing_print.error env cty); decl_pos = get_pos cty; }); (env, (ty, []), dflt_rval_err) end else let (env, ty) = Inter.intersect_list env r tyl in class_get_inner ~is_method ~is_const ~transform_fty ~this_ty ~explicit_targs ~incl_tc ~coerce_from_ty ~is_function_pointer env cid ty (p, mid) | (_, Tclass ((_, c), _, paraml)) -> let class_ = Env.get_class env c in (match class_ with | None -> let ty = MakeType.nothing (Reason.Rmissing_class p) in (env, (ty, []), dflt_rval_err) | Some class_ -> (* TODO akenn: Should we move this to the class_get original call? *) let (env, this_ty) = ExprDepTy.make env ~cid:cid_ this_ty in (* We need to instantiate generic parameters in the method signature *) let ety_env = { empty_expand_env with this_ty; substs = TUtils.make_locl_subst_for_class_tparams class_ paraml; } in let get_smember_from_constraints env class_info = (* Extract the upper bounds on this from where and require class constraints. *) let upper_bounds_from_where_constraints = Cls.upper_bounds_on_this_from_constraints class_info in let upper_bounds_from_require_class_constraints = List.map (Cls.all_ancestor_req_class_requirements class_info) ~f:snd in let (env, ty_err_opt, upper_bounds) = let ((env, ty_err_opt), upper_bounds) = List.map_env_ty_err_opt env (upper_bounds_from_where_constraints @ upper_bounds_from_require_class_constraints) ~f:(fun env up -> Phase.localize ~ety_env env up) ~combine_ty_errs:Typing_error.multiple_opt in (* If class C uses a trait that require class C, then decls for class C * include the require class C constraint. This must be filtered out to avoid * that resolving a static element on class C enters into an infinite recursion. * Similarly, upper bounds on this equivalent via aliases to class C * introduced via class-level where clauses, must be filtered out; this is done * by localizing the bounds before comparing them with the current class name. *) let upper_bounds = List.filter ~f:(fun ty -> match get_node ty with | Tclass ((_, cn), _, _) -> String.( <> ) cn (Cls.name class_info) | _ -> true) upper_bounds in (env, ty_err_opt, upper_bounds) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; if List.is_empty upper_bounds then begin (* there are no upper bounds, raise an error *) Typing_error_utils.add_typing_error ~env @@ TOG.smember_not_found p ~is_const ~is_method ~is_function_pointer class_info mid Typing_error.Callback.unify_error; let (env, ty) = Env.fresh_type_error env p in (env, (ty, []), dflt_rval_err) end else (* since there are upper bounds on this, repeat the search on their intersection *) let (env, inter_ty) = Inter.intersect_list env (Reason.Rwitness p) upper_bounds in class_get_inner ~is_method ~is_const ~transform_fty ~this_ty ~explicit_targs ~incl_tc ~coerce_from_ty ~is_function_pointer env cid inter_ty (p, mid) in let try_get_smember_from_constraints env class_info = Errors.try_with_error (fun () -> get_smember_from_constraints env class_info) (fun () -> Typing_error_utils.add_typing_error ~env @@ TOG.smember_not_found p ~is_const ~is_method ~is_function_pointer class_info mid Typing_error.Callback.unify_error; let (env, ty) = Env.fresh_type_error env p in (env, (ty, []), dflt_rval_err)) in if is_const then ( let const = if incl_tc then Env.get_const env class_ mid else match Env.get_typeconst env class_ mid with | Some _ -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Illegal_typeconst_direct_access p); None | None -> Env.get_const env class_ mid in match const with | None -> try_get_smember_from_constraints env class_ | Some { cc_type; cc_abstract; cc_pos; _ } -> let ((env, ty_err_opt), cc_locl_type) = Phase.localize ~ety_env env cc_type in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (match cc_abstract with | CCAbstract _ -> (match cid_ with | CIstatic | CIexpr _ -> () | _ -> let cc_name = Cls.name class_ ^ "::" ^ mid in let err = Typing_error.( primary @@ Primary.Abstract_const_usage { pos = p; decl_pos = cc_pos; name = cc_name }) in Typing_error_utils.add_typing_error ~env err) | CCConcrete -> ()); (env, (cc_locl_type, []), dflt_rval_err) ) else let static_member_opt = Env.get_static_member is_method env class_ mid in (match static_member_opt with | None -> (* Before raising an error, check if the classish has upper bounds on this * (via class-level where clauses or require class constraints); if yes, repeat * the search on all the upper bounds, if not raise an error. *) try_get_smember_from_constraints env class_ | Some ({ ce_visibility = vis; ce_type = (lazy member_decl_ty); ce_deprecated; _; } as ce) -> let def_pos = get_pos member_decl_ty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) (TVis.check_class_access ~is_method ~use_pos:p ~def_pos env (vis, get_ce_lsb ce) cid_ class_); Option.iter ~f:(Typing_error_utils.add_typing_error ~env) (TVis.check_deprecated ~use_pos:p ~def_pos env ce_deprecated); check_class_get env p def_pos c mid ce cid is_function_pointer; let (env, member_ty, et_enforced, tal) = match deref member_decl_ty with (* We special case Tfun here to allow passing in explicit tparams to localize_ft. *) | (r, Tfun ft) when is_method -> let ft = match transform_fty with | None -> ft | Some f -> f ft in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) (TVis.check_cross_package ~use_pos:p ~def_pos env ft.ft_cross_package); let ((env, ty_err_opt1), explicit_targs) = Phase.localize_targs ~check_well_kinded:true ~is_method:true ~def_pos ~use_pos:p ~use_name:(strip_ns mid) env ft.ft_tparams (List.map ~f:snd explicit_targs) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt1; let ft = Typing_enforceability.compute_enforced_and_pessimize_fun_type ~this_class:(Some class_) env ft in let ((env, ty_err_opt2), ft) = Phase.( localize_ft ~instantiation: { use_name = strip_ns mid; use_pos = p; explicit_targs } ~ety_env ~def_pos env ft) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt2; let fty = Typing_dynamic.maybe_wrap_with_supportdyn ~should_wrap: (get_ce_support_dynamic_type ce && TCO.enable_sound_dynamic env.genv.tcopt) (Reason.localize r) ft in (env, fty, Unenforced, explicit_targs) (* unused *) | _ -> let { et_type; et_enforced } = Typing_enforceability.compute_enforced_and_pessimize_ty ~this_class:(Some class_) env member_decl_ty in let ((env, ty_err_opt), member_ty) = Phase.localize ~ety_env env et_type in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (* TODO(T52753871) make function just return possibly_enforced_ty * after considering intersection case *) (env, member_ty, et_enforced, []) in let (env, member_ty) = if Cls.has_upper_bounds_on_this_from_constraints class_ then let ((env, (member_ty', _), _), succeed) = Errors.try_ (fun () -> (get_smember_from_constraints env class_, true)) (fun _ -> (* No eligible functions found in constraints *) ( (env, (MakeType.mixed Reason.Rnone, []), dflt_rval_err), false )) in if succeed then Inter.intersect env ~r:(Reason.Rwitness p) member_ty member_ty' else (env, member_ty) else (env, member_ty) in let ety = { et_type = member_ty; et_enforced } in let (env, rval_err) = match coerce_from_ty with | None -> (env, None) | Some (p, ur, ty) -> let (env, ty_err_opt) = Typing_coercion.coerce_type p ur env ty (TUtils.make_like_if_enforced env ety) Typing_error.Callback.unify_error in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let ty_mismatch = mk_ty_mismatch_res ty member_ty ty_err_opt in (env, Some ty_mismatch) in (env, (member_ty, tal), rval_err))) | (_, Tunapplied_alias _) -> Typing_defs.error_Tunapplied_alias_in_illegal_context () | ( _, ( Tvar _ | Tnonnull | Tvec_or_dict _ | Toption _ | Tprim _ | Tfun _ | Ttuple _ | Tshape _ | Taccess _ | Tneg _ ) ) -> if not (TUtils.is_tyvar_error env cty) then Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Non_class_member { elt = (if is_method then `meth else `prop); member_name = mid; pos = p; ty_name = lazy (Typing_print.error env cty); decl_pos = get_pos cty; }); let (env, ty) = Env.fresh_type_error env p in (env, (ty, []), dflt_rval_err) and class_id_for_new ~exact p env (cid : Nast.class_id_) (explicit_targs : Nast.targ list) : newable_class_info = let (env, tal, te, cid_ty) = class_expr ~check_targs_well_kinded:true ~check_explicit_targs:true ~exact env explicit_targs ((), p, cid) in (* Need to deal with union case *) let rec get_info res tyl = match tyl with | [] -> (env, tal, te, res) | ty :: tyl -> (match get_node ty with | Tunion tyl' | Tintersection tyl' -> get_info res (tyl' @ tyl) | _ -> (* Instantiation on an abstract class (e.g. from classname<T>) is * via the base type (to check constructor args), but the actual * type `ty` must be preserved. *) (match get_node (TUtils.get_base_type env ty) with | Tdynamic -> get_info (`Dynamic :: res) tyl | Tclass (sid, _, _) -> let class_ = Env.get_class env (snd sid) in (match class_ with | None -> get_info res tyl | Some class_info -> (match (te, cid_ty) with (* When computing the classes for a new T() where T is a generic, * the class must be consistent (final, final constructor, or * <<__ConsistentConstruct>>) for its constructor to be considered *) | ((_, _, Aast.CI (_, c)), ty) when is_generic_equal_to c ty -> (* Only have this choosing behavior for new T(), not all generic types * i.e. new classname<T>, TODO: T41190512 *) if Cls.valid_newable_class class_info then get_info (`Class (sid, class_info, ty) :: res) tyl else get_info res tyl | _ -> get_info (`Class (sid, class_info, ty) :: res) tyl)) | _ -> get_info res tyl)) in get_info [] [cid_ty] (* When invoking a method, the class_id is used to determine what class we * lookup the method in, but the type of 'this' will be the late bound type. * For example: * * class C { * public static function get(): this { return new static(); } * * public static function alias(): this { return self::get(); } * } * * In C::alias, when we invoke self::get(), 'self' is resolved to the class * in the lexical scope (C), so call C::get. However the method is executed in * the current context, so static inside C::get will be resolved to the late * bound type (get_called_class() within C::alias). * * This means when determining the type of this, CIparent and CIself should be * changed to CIstatic. For the other cases of C::get() or $c::get(), we only * look at the left hand side of the '::' and use the type associated * with it. * * Thus C::get() will return a type C, while $c::get() will return the same * type as $c. *) and this_for_method env (_, p, cid) default_ty = match cid with | CIparent | CIself | CIstatic -> let (env, _tal, _te, ty) = class_expr env [] ((), p, CIstatic) in ExprDepTy.make env ~cid:CIstatic ty | _ -> (env, default_ty) (** Resolve class expressions: * self CIself lexically enclosing class * parent CIparent lexically enclosing `extends` class * static CIstatic late-static-bound class (i.e. runtime receiver) * <id> CI id literal class name * <expr> CIexpr expr expression that evaluates to an object or classname *) and class_expr ?(check_targs_well_kinded = false) ?(exact = nonexact) ?(check_explicit_targs = false) (env : env) (tal : Nast.targ list) ((_, p, cid_) : Nast.class_id) : env * Tast.targ list * Tast.class_id * locl_ty = let make_result env tal te ty = (env, tal, (ty, p, te), ty) in match cid_ with | CIparent -> (match Env.get_self_id env with | Some self -> (match Env.get_class env self with | Some trait when Ast_defs.is_c_trait (Cls.kind trait) -> (match trait_most_concrete_req_class trait env with | None -> Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.Parent_in_trait p); let (env, ty) = Env.fresh_type_error env p in make_result env [] Aast.CIparent ty | Some (_, parent_ty) -> (* inside a trait, parent is SN.Typehints.this, but with the * type of the most concrete class that the trait has * "require extend"-ed *) let ((env, ty_err_opt), parent_ty) = Phase.localize_no_subst env ~ignore_errors:true parent_ty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; make_result env [] Aast.CIparent parent_ty) | _ -> begin match Env.get_parent_ty env with | None -> Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.Parent_undefined p); let (env, ty) = Env.fresh_type_error env p in make_result env [] Aast.CIparent ty | Some parent -> let ((env, ty_err_opt), parent) = Phase.localize_no_subst env ~ignore_errors:true parent in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (* parent is still technically the same object. *) make_result env [] Aast.CIparent parent end) | None -> begin match Env.get_parent_ty env with | None -> Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.Parent_undefined p); let (env, ty) = Env.fresh_type_error env p in make_result env [] Aast.CIparent ty | Some parent -> let ((env, ty_err_opt), parent) = Phase.localize_no_subst env ~ignore_errors:true parent in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (* parent is still technically the same object. *) make_result env [] Aast.CIparent parent end) | CIstatic -> let this = if Option.is_some (Env.next_cont_opt env) then MakeType.this (Reason.Rwitness p) else MakeType.nothing (Reason.Rwitness p) in make_result env [] Aast.CIstatic this | CIself -> let (env, ty) = match Env.get_self_class_type env with | Some (c, _, tyl) -> (env, mk (Reason.Rwitness p, Tclass (c, exact, tyl))) | None -> (* Naming phase has already checked and replaced CIself with CI if outside a class *) Errors.internal_error p "Unexpected CIself"; Env.fresh_type_error env p in make_result env [] Aast.CIself ty | CI ((p, id) as c) -> begin match Env.get_pos_and_kind_of_generic env id with | Some (def_pos, kind) -> let simple_kind = Typing_kinding_defs.Simple.from_full_kind kind in let param_nkinds = Typing_kinding_defs.Simple.get_named_parameter_kinds simple_kind in let ((env, ty_err_opt), tal) = Phase.localize_targs_with_kinds ~check_well_kinded:check_targs_well_kinded ~is_method:true ~def_pos ~use_pos:p ~use_name:(strip_ns (snd c)) ~check_explicit_targs env param_nkinds (List.map ~f:snd tal) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let r = Reason.Rhint (Pos_or_decl.of_raw_pos p) in let type_args = List.map tal ~f:fst in let tgeneric = MakeType.generic ~type_args r id in make_result env tal (Aast.CI c) tgeneric | None -> (* Not a type parameter *) let class_ = Env.get_class env id in (match class_ with | None -> let (env, ty) = Env.fresh_type_error env p in make_result env [] (Aast.CI c) ty | Some class_ -> Option.iter ~f:(Typing_error_utils.add_typing_error ~env) (TVis.check_top_level_access ~in_signature:false ~use_pos:p ~def_pos:(Cls.pos class_) env (Cls.internal class_) (Cls.get_module class_)); (* Don't add Exact superfluously to class type if it's final *) let exact = if Cls.final class_ then nonexact else exact in let ((env, ty_err_opt), ty, tal) = List.map ~f:snd tal |> Phase.localize_targs_and_check_constraints ~exact ~check_well_kinded:check_targs_well_kinded ~def_pos:(Cls.pos class_) ~use_pos:p ~check_explicit_targs env c (Reason.Rwitness (fst c)) (Cls.tparams class_) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; make_result env tal (Aast.CI c) ty) end | CIexpr ((_, p, _) as e) -> let (env, te, ty) = expr env e ~allow_awaitable:(*?*) false in let fold_errs errs = let rec aux = function | (Ok xs, Ok x :: rest) -> aux (Ok (x :: xs), rest) | (Ok xs, Error (x, y) :: rest) -> aux (Error (x :: xs, y :: xs), rest) | (Error (xs, ys), Ok x :: rest) -> aux (Error (x :: xs, x :: ys), rest) | (Error (xs, ys), Error (x, y) :: rest) -> aux (Error (x :: xs, y :: ys), rest) | (acc, []) -> acc in aux (Ok [], errs) in let rec resolve_ety env ty = let ((env, ty_err1), ty) = Typing_solver.expand_type_and_solve ~description_of_expected:"an object" env p ty in let base_ty = TUtils.get_base_type env ty in match deref base_ty with | (_, Tnewtype (classname, [the_cls], as_ty)) when String.equal classname SN.Classes.cClassname -> let ((env, ty_err2), (ty, err_res)) = resolve_ety env the_cls in let wrap ty = mk (Reason.none, Tnewtype (classname, [ty], as_ty)) in let err_res = match err_res with | Ok ty -> Ok (wrap ty) | Error (ty_act, ty_exp) -> Error (wrap ty_act, wrap ty_exp) in ((env, Option.merge ty_err1 ty_err2 ~f:Typing_error.both), (ty, err_res)) | (_, Tgeneric _) | (_, Tclass _) -> ((env, ty_err1), (ty, Ok ty)) | (r, Tunion tyl) -> let ((env, ty_err2), res) = List.map_env_ty_err_opt env tyl ~combine_ty_errs:Typing_error.union_opt ~f:resolve_ety in let (tyl, errs) = List.unzip res in let ty = MakeType.union r tyl in let err = match fold_errs errs with | Ok _ -> Ok ty | Error (ty_actuals, ty_expects) -> let ty_actual = MakeType.union Reason.none ty_actuals and ty_expect = MakeType.union Reason.none ty_expects in Error (ty_actual, ty_expect) in ((env, Option.merge ty_err1 ty_err2 ~f:Typing_error.both), (ty, err)) | (r, Tintersection tyl) -> let ((env, ty_err2), res) = TUtils.run_on_intersection_with_ty_err env tyl ~f:resolve_ety in let (tyl, errs) = List.unzip res in let (env, ty) = Inter.intersect_list env r tyl in let (env, err) = match fold_errs errs with | Ok _ -> (env, Ok ty) | Error (ty_actuals, ty_expects) -> let (env, ty_actual) = Inter.intersect_list env Reason.none ty_actuals in let (env, ty_expect) = Inter.intersect_list env Reason.none ty_expects in (env, Error (ty_actual, ty_expect)) in ((env, Option.merge ty_err1 ty_err2 ~f:Typing_error.both), (ty, err)) | (_, Tdynamic) -> ((env, None), (base_ty, Ok base_ty)) | (r, Tvar _) -> let ty_err2 = if TUtils.is_tyvar_error env base_ty then None else Some Typing_error.( primary @@ Primary.Unknown_type { expected = "an object"; pos = p; reason = lazy (Reason.to_string "It is unknown" r); }) in let (env, ty) = Env.fresh_type_error env p in ((env, Option.merge ty_err1 ty_err2 ~f:Typing_error.both), (ty, Ok ty)) | (_, Tunapplied_alias _) -> Typing_defs.error_Tunapplied_alias_in_illegal_context () (* We allow a call through a string in dynamic check mode, as string <:D dynamic *) | (r, Tprim Tstring) when Tast.is_under_dynamic_assumptions env.checked -> ((env, None), (MakeType.dynamic r, Ok (MakeType.dynamic r))) | ( _, ( Tany _ | Tnonnull | Tvec_or_dict _ | Toption _ | Tprim _ | Tfun _ | Ttuple _ | Tnewtype _ | Tdependent _ | Tshape _ | Taccess _ | Tneg _ ) ) -> let ty_err2 = Some Typing_error.( primary @@ Primary.Expected_class { suffix = Some (lazy (", but got " ^ Typing_print.error env base_ty)); pos = p; }) in let ty_nothing = MakeType.nothing Reason.none in let (env, ty) = Env.fresh_type_error env p in let ty_expect = MakeType.classname Reason.none [ty_nothing] in ( (env, Option.merge ty_err1 ty_err2 ~f:Typing_error.both), (ty, Error (base_ty, ty_expect)) ) in let ((env, ty_err_opt), (result_ty, err_res)) = resolve_ety env ty in let ty_mismatch_opt = Result.fold err_res ~ok:(fun _ -> None) ~error:(fun (ty_act, ty_expect) -> Some (ty_act, ty_expect)) in let te = hole_on_ty_mismatch ~ty_mismatch_opt te in let x = make_result env [] (Aast.CIexpr te) result_ty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; x and call_construct p env class_ params el unpacked_element (_, cid_pos, cid_) cid_ty = let r = Reason.Rwitness p in let cid_ty = if Nast.equal_class_id_ cid_ CIparent then MakeType.this r else cid_ty in let ety_env = { empty_expand_env with this_ty = cid_ty; substs = TUtils.make_locl_subst_for_class_tparams class_ params; on_error = Some (Typing_error.Reasons_callback.unify_error_at p); } in let (env, ty_err_opt) = Phase.check_where_constraints ~in_class:true ~use_pos:p ~definition_pos:(Cls.pos class_) ~ety_env env (Cls.where_constraints class_) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let cstr = Env.get_construct env class_ in match fst cstr with | None -> if (not (List.is_empty el)) || Option.is_some unpacked_element then Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.Constructor_no_args p); let (env, tel, _tyl) = argument_list_exprs (expr ~allow_awaitable:false) env el in let should_forget_fakes = true in (* Construct a default __construct type *) let ft = { ft_tparams = []; ft_where_constraints = []; ft_params = []; ft_implicit_params = { capability = CapDefaults (Pos_or_decl.of_raw_pos p) }; ft_flags = make_ft_flags Ast_defs.FSync ~return_disposable:false ~returns_readonly:false ~readonly_this:false ~support_dynamic_type:false ~is_memoized:false ~variadic:false; ft_ret = MakeType.unenforced (MakeType.void r); ft_ifc_decl = default_ifc_fun_decl; ft_cross_package = None; } in let ty = mk (r, Tfun ft) in (env, tel, None, ty, should_forget_fakes) | Some { ce_visibility = vis; ce_type = (lazy m); ce_deprecated; ce_flags; _ } -> let def_pos = get_pos m in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) (TVis.check_obj_access ~is_method:true ~use_pos:p ~def_pos env vis); Option.iter ~f:(Typing_error_utils.add_typing_error ~env) (TVis.check_deprecated ~use_pos:p ~def_pos env ce_deprecated); (* Obtain the type of the constructor *) let (env, m) = let _r = get_reason m |> Reason.localize in match get_node m with | Tfun ft -> let ft = Typing_enforceability.compute_enforced_and_pessimize_fun_type ~this_class:(Some class_) env ft in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) (TVis.check_cross_package ~use_pos:p ~def_pos env ft.ft_cross_package); (* This creates type variables for non-denotable type parameters on constructors. * These are notably different from the tparams on the class, which are handled * at the top of this function. User-written type parameters on constructors * are still a parse error. This is a no-op if ft.ft_tparams is empty. *) let ((env, ty_err_opt1), implicit_constructor_targs) = Phase.localize_targs ~check_well_kinded:true ~is_method:true ~def_pos ~use_pos:p ~use_name:"constructor" env ft.ft_tparams [] in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt1; let ((env, ty_err_opt2), ft) = Phase.( localize_ft ~instantiation: { use_name = "constructor"; use_pos = p; explicit_targs = implicit_constructor_targs; } ~ety_env ~def_pos env ft) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt2; let should_wrap = TCO.enable_sound_dynamic (Env.get_tcopt env) && (Typing_defs_flags.ClassElt.supports_dynamic_type ce_flags || Cls.get_support_dynamic_type class_) in ( env, Typing_dynamic.maybe_wrap_with_supportdyn ~should_wrap (Reason.localize (get_reason m)) ft ) | _ -> Errors.internal_error p "Expected function type for constructor"; Env.fresh_type_error env p in let (env, (tel, typed_unpack_element, _ty, should_forget_fakes)) = call ~expected:None ~expr_pos:p ~recv_pos:cid_pos env m el unpacked_element in (env, tel, typed_unpack_element, m, should_forget_fakes) and inout_write_back env { fp_type; _ } (pk, ((_, pos, _) as e)) = match pk with | Ast_defs.Pinout _ -> (* Translate the write-back semantics of inout parameters. * * This matters because we want to: * (1) make sure we can write to the original argument * (modifiable lvalue check) * (2) allow for growing of locals / Tunions (type side effect) * but otherwise unify the argument type with the parameter hint *) let (env, _te, _ty) = assign_ pos Reason.URparam_inout env e pos fp_type.et_type in env | _ -> env (** Typechecks a call. * Returns in this order the typed expressions for the arguments, for the * variadic arguments, the return type, and a boolean indicating whether fake * members should be forgotten. If dynamic_func is not None, then we are trying * to call the function with dynamic arguments using the fact that is is a SDT * function. That is, we have already ruled out trying to call it with just its * declared type. *) and call ~(expected : ExpectedTy.t option) ?(nullsafe : Pos.t option = None) ?in_await ?(dynamic_func : dyn_func_kind option) ~(expr_pos : Pos.t) ~(recv_pos : Pos.t) env fty (el : (Ast_defs.param_kind * Nast.expr) list) (unpacked_element : Nast.expr option) : env * ((Ast_defs.param_kind * Tast.expr) list * Tast.expr option * locl_ty * bool) = Typing_log.( log_with_level env "typing" ~level:1 (fun () -> log_types (Pos_or_decl.of_raw_pos expr_pos) env [ Log_head ( ("Typing.call " ^ match dynamic_func with | None -> "None" | Some Supportdyn_function -> "sd" | Some Like_function -> "~"), [Log_type ("fty", fty)] ); ])); let rec is_fun_type ty = match get_node ty with | Tfun _ -> true | Tnewtype (name, [ty], _) when String.equal name SN.Classes.cSupportDyn -> is_fun_type ty | _ -> false in (* When we enter a like function, it is safe to ignore the like type if we are already in a supportdyn function. Semantically, dyn & (dyn | (t1 -> t2)) = dyn | (dyn & (t1 -> t2) = dyn, and doing this lets us keep like-stripping the arguments *) let to_like_function dynamic_func = match dynamic_func with | Some _ -> dynamic_func | None -> Some Like_function in let expr = expr ~allow_awaitable:(*?*) false in let (env, tyl) = TUtils.get_concrete_supertypes ~expand_supportdyn:false ~abstract_enum:true env fty in if List.is_empty tyl then begin bad_call env expr_pos fty; let (env, ty_err_opt) = call_untyped_unpack env (get_pos fty) unpacked_element in let should_forget_fakes = true in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let (env, ty) = Env.fresh_type_error env expr_pos in (env, ([], None, ty, should_forget_fakes)) end else let (env, fty) = Inter.intersect_list env (get_reason fty) tyl in let ((env, ty_err_opt), efty) = if TCO.method_call_inference (Env.get_tcopt env) then let (env, ty) = Env.expand_type env fty in ((env, None), ty) else Typing_solver.expand_type_and_solve ~description_of_expected:"a function value" env expr_pos fty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; match TUtils.try_strip_dynamic env efty with | Some ty when TCO.enable_sound_dynamic (Env.get_tcopt env) && is_fun_type ty -> call ~expected ~nullsafe ?in_await ?dynamic_func:(to_like_function dynamic_func) ~expr_pos ~recv_pos env ty el unpacked_element | _ -> (match deref efty with | (r, Tdynamic) when TCO.enable_sound_dynamic (Env.get_tcopt env) -> let ty = MakeType.dynamic (Reason.Rdynamic_call expr_pos) in let el = (* Need to check that the type of the unpacked_element can be, * coerced to dynamic, just like all of the other arguments, in addition * to the check below in call_untyped_unpack, that it is unpackable. * We don't need to unpack and check each type because a tuple is * coercible iff it's constituent types are. *) Option.value_map ~f:(fun u -> el @ [(Ast_defs.Pnormal, u)]) ~default:el unpacked_element in let expected_arg_ty = ExpectedTy.make ~coerce:(Some Typing_logic.CoerceToDynamic) expr_pos Reason.URparam ty in let ((env, e1), tel) = List.map_env_ty_err_opt env el ~combine_ty_errs:Typing_error.multiple_opt ~f:(fun env (pk, elt) -> let (env, te, e_ty) = match elt with (* Special case for unqualified enum class label: treat as dynamic *) | (_, p, EnumClassLabel (None, s)) -> make_result env p (Aast.EnumClassLabel (None, s)) (MakeType.dynamic (Reason.Rwitness p)) | _ -> expr ~expected:expected_arg_ty env elt in let env = match pk with | Ast_defs.Pinout _ -> let (_, pos, _) = elt in let (env, _te, _ty) = assign_ pos Reason.URparam_inout env elt pos efty in env | Ast_defs.Pnormal -> env in let (env, ty_err_opt) = SubType.sub_type ~coerce:(Some Typing_logic.CoerceToDynamic) env e_ty ty @@ Some (Typing_error.Reasons_callback.unify_error_at expr_pos) in let ty_mismatch_opt = mk_ty_mismatch_opt e_ty ty ty_err_opt in ((env, ty_err_opt), (pk, hole_on_ty_mismatch ~ty_mismatch_opt te))) in let (env, e2) = call_untyped_unpack env (Reason.to_pos r) unpacked_element in let should_forget_fakes = true 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, (tel, None, ty, should_forget_fakes)) | (r, ((Tprim Tnull | Tdynamic | Tany _ | Tunion [] | Tvar _) as ty)) when match ty with | Tprim Tnull -> Option.is_some nullsafe | Tvar _ -> TUtils.is_tyvar_error env efty | _ -> true -> let el = Option.value_map ~f:(fun u -> el @ [(Ast_defs.Pnormal, u)]) ~default:el unpacked_element in let (env, tel) = List.map_env env el ~f:(fun env (pk, elt) -> let (env, te, _ty) = expr env elt in let env = match pk with | Ast_defs.Pinout _ -> let (_, pos, _) = elt in let (env, _te, _ty) = assign_ pos Reason.URparam_inout env elt pos efty in env | Ast_defs.Pnormal -> env in (env, (pk, te))) in let (env, ty_err_opt) = call_untyped_unpack env (Reason.to_pos r) unpacked_element in let (env, ty) = match ty with | Tprim Tnull -> (env, mk (r, Tprim Tnull)) | Tdynamic -> (env, MakeType.dynamic (Reason.Rdynamic_call expr_pos)) | Tvar _ when TUtils.is_tyvar_error env efty -> Env.fresh_type_error env expr_pos | Tunion [] | _ (* _ should not happen! *) -> (env, mk (r, Tunion [])) in let should_forget_fakes = true in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (env, (tel, None, ty, should_forget_fakes)) | (_, Tunion [ty]) -> call ~expected ~nullsafe ?in_await ?dynamic_func ~expr_pos ~recv_pos env ty el unpacked_element | (r, Tunion tyl) -> let (env, resl) = List.map_env env tyl ~f:(fun env ty -> call ~expected ~nullsafe ?in_await ?dynamic_func ~expr_pos ~recv_pos env ty el unpacked_element) in let should_forget_fakes = List.exists resl ~f:(fun (_, _, _, forget) -> forget) in let retl = List.map resl ~f:(fun (_, _, x, _) -> x) in let (env, ty) = Union.union_list env r retl in (* We shouldn't be picking arbitrarily for the TAST here, as TAST checks * depend on the types inferred. Here's we're preserving legacy behaviour * by picking the last one. * TODO: don't do this, instead use subtyping to push unions * through function types *) let (tel, typed_unpack_element, _, _) = List.hd_exn (List.rev resl) in (env, (tel, typed_unpack_element, ty, should_forget_fakes)) | (r, Tintersection tyl) -> let (env, resl) = TUtils.run_on_intersection env tyl ~f:(fun env ty -> call ~expected ~nullsafe ?in_await ?dynamic_func ~expr_pos ~recv_pos env ty el unpacked_element) in let should_forget_fakes = List.for_all resl ~f:(fun (_, _, _, forget) -> forget) in let retl = List.map resl ~f:(fun (_, _, x, _) -> x) in let (env, ty) = Inter.intersect_list env r retl in (* We shouldn't be picking arbitrarily for the TAST here, as TAST checks * depend on the types inferred. Here we're preserving legacy behaviour * by picking the last one. * TODO: don't do this, instead use subtyping to push intersections * through function types *) let (tel, typed_unpack_element, _, _) = List.hd_exn (List.rev resl) in (env, (tel, typed_unpack_element, ty, should_forget_fakes)) | (r2, Tfun ft) -> (* Typing of format string functions. It is dependent on the arguments (el) * so it cannot be done earlier. *) let pos_def = Reason.to_pos r2 in let (env, ft) = Typing_exts.retype_magic_func env ft el in let (env, var_param) = variadic_param env ft in (* Force subtype with expected result *) let env = check_expected_ty "Call result" env ft.ft_ret.et_type expected in let env = Env.set_tyvar_variance env ft.ft_ret.et_type in let is_lambda (_, _, e) = match e with | Efun _ | Lfun _ -> true | _ -> false in let get_next_param_info paraml = match paraml with | param :: paraml -> (false, Some param, paraml) | [] -> (true, var_param, paraml) in let rec compute_enum_name env lty = match get_node lty with | Tclass ((_, enum_name), _, _) when Env.is_enum_class env enum_name -> (env, Some enum_name) | Tgeneric (name, _) -> let (env, upper_bounds) = TUtils.collect_enum_class_upper_bounds env name in begin match upper_bounds with | None -> (env, None) | Some upper_bound -> begin (* To avoid ambiguity, we only support the case where * there is a single upper bound that is an EnumClass. * We might want to relax that later (e.g. with the * support for intersections). *) match get_node upper_bound with | Tclass ((_, name), _, _) when Env.is_enum_class env name -> (env, Some name) | _ -> (env, None) end end | Tvar var -> (* minimal support to only deal with Tvar when: * - it is the valueOf from BuiltinEnumClass. * In this case, we know the tvar as a single lowerbound, * `this` which must be an enum class. * - it is a generic "TX::T" from a where clause. We try * to look at an upper bound, if it is an enum class, or fail. * * We could relax this in the future but * I want to avoid complex constraints for now. *) let lower_bounds = Env.get_tyvar_lower_bounds env var in if ITySet.cardinal lower_bounds <> 1 then (env, None) else ( match ITySet.choose lower_bounds with | ConstraintType _ -> (env, None) | LoclType lower -> (match get_node lower with | Tclass ((_, enum_name), _, _) when Env.is_enum_class env enum_name -> (env, Some enum_name) | Tgeneric _ -> compute_enum_name env lower | _ -> (env, None)) ) | _ -> (* Already reported, see Typing_type_wellformedness *) (env, None) in let check_arg env param_kind ((_, pos, arg) as e) opt_param ~is_variadic = match opt_param with | Some param -> (* First check if the parameter is a HH\EnumClass\Label. *) let (env, label_type) = let ety = param.fp_type.et_type in let (env, ety) = Env.expand_type env ety in let is_label env ety = match get_node (TUtils.strip_dynamic env ety) with | Tnewtype (name, [ty_enum; _ty_interface], _) -> if String.equal SN.Classes.cEnumClassLabel name then Some (name, ty_enum) else None | _ -> None in let is_maybe_label = match get_node (TUtils.strip_dynamic env ety) with | Toption ety -> is_label env ety | _ -> is_label env ety in match (arg, is_maybe_label) with | (Aast.EnumClassLabel (None, label_name), Some (name, ty_enum)) -> let ctor = name in (match compute_enum_name env ty_enum with | (env, None) -> (env, EnumClassLabelOps.ClassNotFound) | (env, Some enum_name) -> let ty_pos = Typing_defs.get_pos ty_enum in EnumClassLabelOps.expand pos env ~full:false ~ctor (Pos.none, enum_name) label_name (Some ty_pos)) | (Aast.EnumClassLabel (Some _, _), _) -> (* Full info is here, use normal inference *) (env, EnumClassLabelOps.Skip) | (_, _) -> (env, EnumClassLabelOps.Skip) in let (env, te, ty) = match label_type with | EnumClassLabelOps.Success (te, ty) | EnumClassLabelOps.LabelNotFound (te, ty) -> (env, te, ty) | _ -> (* Expected type has a like type for checking arguments * to supportdyn functions *) let (env, pess_type) = match dynamic_func with | Some Supportdyn_function -> Typing_array_access.pessimise_type env param.fp_type.et_type | _ -> (env, param.fp_type.et_type) in let expected = ExpectedTy.make_and_allow_coercion_opt env pos Reason.URparam { et_type = pess_type; et_enforced = param.fp_type.et_enforced; } in expr ~accept_using_var:(get_fp_accept_disposable param) ?expected env e in let (env, ty_mismatch_opt, used_dynamic) = check_argument_type_against_parameter_type ~dynamic_func env param param_kind (e, ty) ~is_variadic in ( env, Some (hole_on_ty_mismatch ~ty_mismatch_opt te, ty), used_dynamic ) | None -> let (env, te, ty) = expr env e in (env, Some (te, ty), false) in let set_tyvar_variance_from_lambda_param env opt_param = match opt_param with | Some param -> let rec set_params_variance env ty = let ty = TUtils.strip_dynamic env ty in let (env, ty) = Env.expand_type env ty in match get_node ty with | Tunion [ty] -> set_params_variance env ty | Toption ty -> set_params_variance env ty | Tfun { ft_params; ft_ret; _ } -> let env = List.fold ~init:env ~f:(fun env param -> Env.set_tyvar_variance env param.fp_type.et_type) ft_params in Env.set_tyvar_variance env ft_ret.et_type ~flip:true | Tnewtype (name, [ty], _) when String.equal name SN.Classes.cSupportDyn -> set_params_variance env ty | _ -> env in set_params_variance env param.fp_type.et_type | None -> env in (* Given an expected function type ft, check types for the non-unpacked * arguments. Don't check lambda expressions if check_lambdas=false *) let rec check_args_aux check_lambdas env el paraml used_dynamic rl = match el with (* We've got an argument *) | ((pk, e), opt_result) :: el -> (* Pick up next parameter type info *) let (is_variadic, opt_param, paraml) = get_next_param_info paraml in let (env, one_result, used_dynamic') = match (check_lambdas, is_lambda e) with | (false, false) | (true, true) -> check_arg env pk e opt_param ~is_variadic | (false, true) -> let env = set_tyvar_variance_from_lambda_param env opt_param in (env, opt_result, false) | (true, false) -> (env, opt_result, false) in check_args_aux check_lambdas env el paraml (used_dynamic || used_dynamic') (((pk, e), one_result) :: rl) | [] -> (env, rl, paraml, used_dynamic) in let check_args check_lambdas env el paraml = let (env, rl, paraml, used_dynamic) = check_args_aux check_lambdas env el paraml false [] in (env, List.rev rl, paraml, used_dynamic) in (* Same as above, but checks the types of the implicit arguments, which are * read from the context *) let check_implicit_args env = let capability = Typing_coeffects.get_type ft.ft_implicit_params.capability in let should_skip_check = (not (TCO.call_coeffects (Env.get_tcopt env))) (* When inside an expression tree, expressions are virtualized and thus never executed. Safe to skip coeffect checks in this case. *) || Env.is_in_expr_tree env in if should_skip_check then (env, None) else let env_capability = (Env.get_local_check_defined env (expr_pos, Typing_coeffects.capability_id)) .Typing_local_types.ty in let base_error = Typing_error.Primary.( Coeffect (Coeffect.Call_coeffect { pos = recv_pos; available_incl_unsafe = Typing_coeffects.pretty env env_capability; available_pos = Typing_defs.get_pos env_capability; required_pos = Typing_defs.get_pos capability; required = Typing_coeffects.pretty env capability; })) in Type.sub_type expr_pos Reason.URnone env env_capability capability @@ Typing_error.Callback.always base_error in let should_forget_fakes = (* If the function doesn't have write priveleges to properties, fake members cannot be reassigned, so their refinements stand. *) let capability = Typing_coeffects.get_type ft.ft_implicit_params.capability in SubType.is_sub_type env capability (MakeType.capability Reason.Rnone SN.Capabilities.writeProperty) in (* First check the non-lambda arguments. For generic functions, this * is likely to resolve type variables to concrete types *) let rl = List.map el ~f:(fun e -> (e, None)) in let non_variadic_ft_params = if get_ft_variadic ft then List.drop_last_exn ft.ft_params else ft.ft_params in let (env, rl, _, used_dynamic1) = check_args false env rl non_variadic_ft_params in (* Now check the lambda arguments, hopefully with type variables resolved *) let (env, rl, paraml, used_dynamic2) = check_args true env rl non_variadic_ft_params in (* We expect to see results for all arguments after this second pass *) let get_param ((pk, _), opt) = match opt with | Some (((_, pos, _) as e), ty) -> ((pk, e), (pos, ty)) | None -> failwith "missing parameter in check_args" in let (tel, argtys) = let l = List.map rl ~f:get_param in List.unzip l in let (env, ty_err_opt) = check_implicit_args env in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let (env, typed_unpack_element, arity, did_unpack, used_dynamic3) = match unpacked_element with | None -> (env, None, List.length el, false, false) | Some e -> (* Now that we're considering an splat (Some e) we need to construct a type that * represents the remainder of the function's parameters. `paraml` represents those * remaining parameters, and the variadic parameter is stored in `var_param`. For example, given * * function f(int $i, string $j, float $k = 3.14, mixed ...$m): void {} * function g((string, float, bool) $t): void { * f(3, ...$t); * } * * the constraint type we want is splat([#1], [opt#2], #3). *) let (consumed, required_params, optional_params) = split_remaining_params_required_optional ft paraml in let (_, p1, _) = e in let (env, (d_required, d_optional, d_variadic)) = generate_splat_type_vars env p1 required_params optional_params var_param in let destructure_ty = ConstraintType (mk_constraint_type ( Reason.Runpack_param (p1, pos_def, consumed), Tdestructure { d_required; d_optional; d_variadic; d_kind = SplatUnpack; } )) in let (env, te, ty) = expr env e in (* Populate the type variables from the expression in the splat *) let (env, ty_err_opt) = Type.sub_type_i p1 Reason.URparam env (LoclType ty) destructure_ty Typing_error.Callback.unify_error in let (env, te, used_dynamic) = match ty_err_opt with | Some _ -> (* Our type cannot be destructured, add a hole with `nothing` as expected type *) let ty_expect = MakeType.nothing @@ Reason.Rsolve_fail (Pos_or_decl.of_raw_pos expr_pos) in (env, mk_hole te ~ty_have:ty ~ty_expect, false) | None -> (* We have a type that can be destructured so continue and use the type variables for the remaining parameters *) let (env, err_opts, used_dynamic) = List.fold2_exn ~init:(env, [], false) d_required required_params ~f:(fun (env, errs, used_dynamic_acc) elt param -> let (env, err_opt, used_dynamic) = check_argument_type_against_parameter_type ~dynamic_func env param Ast_defs.Pnormal (e, elt) ~is_variadic:false in (env, err_opt :: errs, used_dynamic_acc || used_dynamic)) in let (env, err_opts, used_dynamic) = List.fold2_exn ~init:(env, err_opts, used_dynamic) d_optional optional_params ~f:(fun (env, errs, used_dynamic_acc) elt param -> let (env, err_opt, used_dynamic) = check_argument_type_against_parameter_type ~dynamic_func env param Ast_defs.Pnormal (e, elt) ~is_variadic:false in (env, err_opt :: errs, used_dynamic_acc || used_dynamic)) in let (env, var_err_opt, var_used_dynamic) = Option.map2 d_variadic var_param ~f:(fun v vp -> check_argument_type_against_parameter_type ~dynamic_func env vp Ast_defs.Pnormal (e, v) ~is_variadic:true) |> Option.value ~default:(env, None, false) in let subtyping_errs = (List.rev err_opts, var_err_opt) in let te = match (List.filter_map ~f:Fn.id err_opts, var_err_opt) with | ([], None) -> te | _ -> let (_, pos, _) = te in hole_on_ty_mismatch te ~ty_mismatch_opt: (Some (ty, pack_errs pos ty subtyping_errs)) in (env, te, used_dynamic || var_used_dynamic) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; ( env, Some te, List.length el + List.length d_required, Option.is_some d_variadic, used_dynamic ) in let used_dynamic = used_dynamic1 || used_dynamic2 || used_dynamic3 in (* If dynamic_func is set, then the function type is supportdyn<t1 ... tn -> t> or ~(t1 ... tn -> t) and we are trying to call it as though it were dynamic. Hence all of the arguments must be subtypes of dynamic, regardless of whether they have a like type. *) let env = if used_dynamic then begin let rec check_args_dynamic env argtys = match argtys with (* We've got an argument *) | (pos, argty) :: argtys -> let (env, ty_err_opt) = TUtils.supports_dynamic env argty @@ Some (Typing_error.Reasons_callback.unify_error_at pos) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; check_args_dynamic env argtys | [] -> env in check_args_dynamic env argtys end else env in (* If we unpacked an array, we don't check arity exactly. Since each * unpacked array consumes 1 or many parameters, it is nonsensical to say * that not enough args were passed in (so we don't do the min check). *) let () = check_arity ~did_unpack env expr_pos pos_def ft arity in (* Variadic params cannot be inout so we can stop early *) let env = wfold_left2 inout_write_back env non_variadic_ft_params el in let ret = match dynamic_func with | Some _ when used_dynamic -> MakeType.locl_like r2 ft.ft_ret.et_type | _ -> ft.ft_ret.et_type in (env, (tel, typed_unpack_element, ret, should_forget_fakes)) | (r, Tvar _) when TCO.method_call_inference (Env.get_tcopt env) -> (* Typecheck calls with unresolved function type by constructing a suitable function type from the arguments and invoking subtyping. *) let (env, typed_el, type_of_el) = argument_list_exprs (expr ~accept_using_var:true) env el in let (env, typed_unpacked_element, type_of_unpacked_element) = match unpacked_element with | Some unpacked -> let (env, typed_unpacked, type_of_unpacked) = expr ~accept_using_var:true env unpacked in (env, Some typed_unpacked, Some type_of_unpacked) | None -> (env, None, None) in let mk_function_supertype env pos (type_of_el, type_of_unpacked_element) = let mk_fun_param ty = let flags = (* Keep supertype as permissive as possible: *) make_fp_flags ~mode:FPnormal (* TODO: deal with `inout` parameters *) ~accept_disposable:false (* TODO: deal with disposables *) ~has_default:false ~ifc_external:false ~ifc_can_call:false ~readonly:false in { fp_pos = Pos_or_decl.of_raw_pos pos; fp_name = None; fp_type = MakeType.enforced ty; fp_flags = flags; } in let ft_arity = match type_of_unpacked_element with | Some type_of_unpacked -> let fun_param = mk_fun_param type_of_unpacked in [fun_param] | None -> [] in (* TODO: ensure `ft_params`/`ft_where_constraints` don't affect subtyping *) let ft_tparams = [] in let ft_where_constraints = [] in let ft_cross_package = None in let ft_params = List.map ~f:mk_fun_param type_of_el in let ft_implicit_params = { capability = CapDefaults (Pos_or_decl.of_raw_pos pos) (* TODO(coeffects) should this be a different type? *); } in let (env, return_ty) = Env.fresh_type env pos in let return_ty = match in_await with | None -> return_ty | Some r -> MakeType.awaitable r return_ty in let ft_ret = MakeType.enforced return_ty in let ft_flags = (* Keep supertype as permissive as possible: *) make_ft_flags Ast_defs.FSync (* `FSync` fun can still return `Awaitable<_>` *) ~return_disposable:false (* TODO: deal with disposable return *) ~returns_readonly:false ~readonly_this:false ~support_dynamic_type:false ~is_memoized:false ~variadic:(not (List.is_empty ft_arity)) in let ft_ifc_decl = Typing_defs_core.default_ifc_fun_decl in let fun_locl_type = { ft_tparams; ft_where_constraints; ft_params = ft_params @ ft_arity; ft_implicit_params; ft_ret; ft_flags; ft_ifc_decl; ft_cross_package; } in let fun_type = mk (r, Tfun fun_locl_type) in let env = Env.set_tyvar_variance env fun_type in (env, fun_type, return_ty) in let (env, fun_type, return_ty) = mk_function_supertype env expr_pos (type_of_el, type_of_unpacked_element) in let (env, ty_err_opt) = Type.sub_type expr_pos Reason.URnone env efty fun_type Typing_error.Callback.unify_error in let should_forget_fakes = true in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (env, (typed_el, typed_unpacked_element, return_ty, should_forget_fakes)) | (_, Tnewtype (name, [ty], _)) when String.equal name SN.Classes.cSupportDyn -> let (env, ty) = Env.expand_type env ty in begin match get_node ty with (* If we have a function type of the form supportdyn<(function(t):~u)> then it does no * harm to treat it as supportdyn<(function(~t):~u)> and may produce a more precise * type for function application e.g. consider * function expect<T as supportdyn<mixed> >(T $obj)[]: ~Invariant<T>; * If we have an argument of type ~t then checking against this signature will * produce ~t <: T <: supportdyn<mixed>, so T will be assigned a like type. * But if we check against the signature transformed as above, we will get * t <: T <: supportdyn<mixed> which is more precise. *) | Tfun ft when Option.is_some (TUtils.try_strip_dynamic env ft.ft_ret.et_type) && List.length el = 1 -> let ft_params = List.map ft.ft_params ~f:(fun fp -> { fp with fp_type = { fp.fp_type with et_type = TUtils.make_like env fp.fp_type.et_type; }; }) in let ty = mk (get_reason ty, Tfun { ft with ft_params }) in call ~expected ~nullsafe ?in_await ?dynamic_func ~expr_pos ~recv_pos env ty el unpacked_element | _ -> call ~expected ~nullsafe ?in_await ?dynamic_func:(Some Supportdyn_function) ~expr_pos ~recv_pos env ty el unpacked_element end | _ -> if not (TUtils.is_tyvar_error env efty) then bad_call env expr_pos efty; let (env, ty_err_opt) = call_untyped_unpack env (get_pos efty) unpacked_element in let should_forget_fakes = true in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let (env, ty) = Env.fresh_type_error env expr_pos in (env, ([], None, ty, should_forget_fakes))) and call_untyped_unpack env f_pos unpacked_element = match unpacked_element with (* In the event that we don't have a known function call type, we can still * verify that any unpacked arguments (`...$args`) are something that can * be actually unpacked. *) | None -> (env, None) | Some e -> let (env, _, ety) = expr env e ~allow_awaitable:(*?*) false in let (_, p, _) = e in let (env, ty) = Env.fresh_type env p in let destructure_ty = MakeType.simple_variadic_splat (Reason.Runpack_param (p, f_pos, 0)) ty in Type.sub_type_i p Reason.URnone env (LoclType ety) destructure_ty Typing_error.Callback.unify_error and upcast env p expr_ty hint_ty = let (env, ty_err_opt) = SubType.sub_type ~coerce:(Some Typing_logic.CoerceToDynamic) env expr_ty hint_ty @@ Some (Typing_error.Reasons_callback.unify_error_at p) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; env (** * Build an environment for the true or false branch of * conditional statements. *) and condition env tparamet ((ty, p, e) as te : Tast.expr) = match e with | Aast.Hole (e, _, _, _) -> condition env tparamet e | Aast.True when not tparamet -> (LEnv.drop_cont env C.Next, { lset = Local_id.Set.empty; pkgs = SSet.empty }) | Aast.False when tparamet -> (LEnv.drop_cont env C.Next, { lset = Local_id.Set.empty; pkgs = SSet.empty }) | Aast.Call { func = (_, _, Aast.Id (_, f)); args = [(_, te)]; unpacked_arg = None; _; } when String.equal SN.StdlibFunctions.is_null f -> let (env, lset) = condition_nullity ~nonnull:(not tparamet) env te in (env, { lset; pkgs = SSet.empty }) | Aast.Binop { bop = Ast_defs.Eqeq | Ast_defs.Eqeqeq; lhs = (_, _, Aast.Null); rhs = e; } | Aast.Binop { bop = Ast_defs.Eqeq | Ast_defs.Eqeqeq; lhs = e; rhs = (_, _, Aast.Null); } -> let (env, lset) = condition_nullity ~nonnull:(not tparamet) env e in (env, { lset; pkgs = SSet.empty }) | Aast.Binop { bop = Ast_defs.Eqeq | Ast_defs.Eqeqeq; lhs = (lhs_ty, _, _) as lhs; rhs = (rhs_ty, _, _) as rhs; } when tparamet -> let (env, lset_lhs) = refine_for_equality p env lhs rhs_ty in let (env, lset_rhs) = refine_for_equality p env rhs lhs_ty in let lset = Local_id.Set.union lset_lhs lset_rhs in (env, { lset; pkgs = SSet.empty }) | Aast.Lvar _ | Aast.Obj_get _ | Aast.Class_get _ | Aast.Binop { bop = Ast_defs.Eq None; _ } -> let (env, ety) = Env.expand_type env ty in (match get_node ety with | Tprim Tbool -> (env, { lset = Local_id.Set.empty; pkgs = SSet.empty }) | _ -> let (env, lset) = condition_nullity ~nonnull:tparamet env te in (env, { lset; pkgs = SSet.empty })) | Aast.Binop { bop = (Ast_defs.Diff | Ast_defs.Diff2) as op; lhs = e1; rhs = e2 } -> let op = if Ast_defs.(equal_bop op Diff) then Ast_defs.Eqeq else Ast_defs.Eqeqeq in condition env (not tparamet) (ty, p, Aast.Binop { bop = op; lhs = e1; rhs = e2 }) (* Conjunction of conditions. Matches the two following forms: if (cond1 && cond2) if (!(cond1 || cond2)) *) | Aast.Binop { bop = (Ast_defs.Ampamp | Ast_defs.Barbar) as bop; lhs = e1; rhs = e2 } when Bool.equal tparamet Ast_defs.(equal_bop bop Ampamp) -> let (env, { lset = lset1; pkgs = pkgs1 }) = condition env tparamet e1 in (* This is necessary in case there is an assignment in e2 * We essentially redo what has been undone in the * `Binop (Ampamp|Barbar)` case of `expr` *) let (env, _, _) = expr env (Tast.to_nast_expr e2) ~allow_awaitable:(*?*) false in let (env, { lset = lset2; pkgs = pkgs2 }) = condition env tparamet e2 in let lset = Local_id.Set.union lset1 lset2 in let pkgs = if tparamet then SSet.union pkgs1 pkgs2 else SSet.empty in (env, { lset; pkgs }) (* Disjunction of conditions. Matches the two following forms: if (cond1 || cond2) if (!(cond1 && cond2)) *) | Aast.Binop { bop = (Ast_defs.Ampamp | Ast_defs.Barbar) as bop; lhs = e1; rhs = e2 } when Bool.equal tparamet Ast_defs.(equal_bop bop Barbar) -> let (env, { lset = lset1; _ }, { lset = lset2; _ }) = branch ~join_pos:p env (fun env -> (* Either cond1 is true and we don't know anything about cond2... *) condition env tparamet e1) (fun env -> (* ... Or cond1 is false and therefore cond2 must be true *) let (env, _) = condition env (not tparamet) e1 in (* Similarly to the conjunction case, there might be an assignment in cond2 which we must account for. Again we redo what has been undone in the `Binop (Ampamp|Barbar)` case of `expr` *) let (env, _, _) = expr env (Tast.to_nast_expr e2) ~allow_awaitable:(*?*) false in condition env tparamet e2) in (env, { lset = Local_id.Set.union lset1 lset2; pkgs = SSet.empty }) | Aast.Call { func = (_, p, Aast.Id (_, f)); args = [(_, lv)]; unpacked_arg = None; _; } when tparamet && String.equal f SN.StdlibFunctions.is_dict_or_darray -> let (env, lset) = safely_refine_is_array env HackDictOrDArray p f lv in (env, { lset; pkgs = SSet.empty }) | Aast.Call { func = (_, p, Aast.Id (_, f)); args = [(_, lv)]; unpacked_arg = None; _; } when tparamet && String.equal f SN.StdlibFunctions.is_vec_or_varray -> let (env, lset) = safely_refine_is_array env HackVecOrVArray p f lv in (env, { lset; pkgs = SSet.empty }) | Aast.Call { func = (_, p, Aast.Id (_, f)); args = [(_, lv)]; unpacked_arg = None; _; } when String.equal f SN.StdlibFunctions.is_any_array -> let (env, lset) = refine_for_is ~hint_first:true env tparamet lv (Reason.Rpredicated (p, f)) (p, Happly ((p, "\\HH\\AnyArray"), [(p, Hwildcard); (p, Hwildcard)])) in (env, { lset; pkgs = SSet.empty }) | Aast.Call { func = ( _, _, Aast.Class_const ((_, _, Aast.CI (_, class_name)), (_, method_name)) ); args = [(_, shape); (_, field)]; unpacked_arg = None; _; } when tparamet && String.equal class_name SN.Shapes.cShapes && String.equal method_name SN.Shapes.keyExists -> let (env, lset) = key_exists env p shape field in (env, { lset; pkgs = SSet.empty }) | Aast.Unop (Ast_defs.Unot, e) -> condition env (not tparamet) e | Aast.Is (ivar, h) -> let (env, lset) = refine_for_is ~hint_first:false env tparamet ivar (Reason.Ris (fst h)) h in (env, { lset; pkgs = SSet.empty }) | Aast.Package (_, pkg) when tparamet -> (env, { lset = Local_id.Set.empty; pkgs = SSet.singleton pkg }) | _ -> (env, { lset = Local_id.Set.empty; pkgs = SSet.empty }) and string2 env idl = let (env, tel) = List.fold_left idl ~init:(env, []) ~f:(fun (env, tel) x -> let (env, te, ty) = expr env x ~allow_awaitable:(*?*) false in let (_, p, _) = x in if TCO.enable_strict_string_concat_interp (Env.get_tcopt env) then ( let r = Reason.Rinterp_operand p in let (env, formatter_tyvar) = Env.fresh_type_invariant env p in let stringlike = MakeType.union r [ MakeType.arraykey r; MakeType.dynamic r; MakeType.hh_formatstring r formatter_tyvar; ] in let (env, ty_err_opt) = Typing_ops.sub_type p Reason.URstr_interp env ty stringlike Typing_error.Callback.strict_str_interp_type_mismatch in let ty_mismatch_opt = mk_ty_mismatch_opt ty stringlike ty_err_opt in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (env, hole_on_ty_mismatch ~ty_mismatch_opt te :: tel) ) else let env = Typing_substring.sub_string p env ty in (env, te :: tel)) in (env, List.rev tel) and user_attribute env ua = let (env, typed_ua_params) = List.map_env env ua.ua_params ~f:(fun env e -> let (env, te, _) = expr env e ~allow_awaitable:(*?*) false in (env, te)) in (env, { Aast.ua_name = ua.ua_name; Aast.ua_params = typed_ua_params }) and file_attributes env file_attrs = (* Disable checking of error positions, as file attributes have spans that * aren't subspans of the class or function into which they are copied *) Errors.run_with_span Pos.none @@ fun () -> List.map_env env file_attrs ~f:(fun env fa -> let (env, user_attributes) = attributes_check_def env SN.AttributeKinds.file fa.fa_user_attributes in let env = set_tcopt_unstable_features env fa in ( env, { Aast.fa_user_attributes = user_attributes; Aast.fa_namespace = fa.fa_namespace; } )) and type_param env (t : Nast.tparam) = let (env, user_attributes) = attributes_check_def env SN.AttributeKinds.typeparam t.tp_user_attributes in let (env, tp_parameters) = List.map_env env t.tp_parameters ~f:type_param in ( env, { Aast.tp_variance = t.tp_variance; Aast.tp_name = t.tp_name; Aast.tp_parameters; Aast.tp_constraints = t.tp_constraints; Aast.tp_reified = reify_kind t.tp_reified; Aast.tp_user_attributes = user_attributes; } ) (* Calls the method of a class, but allows the f callback to override the * return value type *) and overload_function make_call fpos p env ((_, cid_pos, _) as class_id) method_id el unpacked_element f = let (env, _tal, tcid, ty) = class_expr env [] class_id in let (env, (fty, tal)) = class_get ~is_method:true ~is_const:false ~transform_fty:None ~coerce_from_ty:None env ty method_id class_id in let (env, (tel, typed_unpack_element, res, should_forget_fakes)) = call ~expected:None ~expr_pos:p ~recv_pos:cid_pos env fty el unpacked_element in let (env, ty) = f env fty res el tel in let (env, fty) = Env.expand_type env fty in let fty = map_ty fty ~f:(function | Tfun ft -> Tfun { ft with ft_ret = MakeType.unenforced ty } | ty -> ty) in let (env, te) = TUtils.make_simplify_typed_expr env fpos fty (Aast.Class_const (tcid, method_id)) in (make_call env te tal tel typed_unpack_element ty, should_forget_fakes) and update_array_type ?lhs_of_null_coalesce p env e1 valkind = match valkind with | Lvalue | Lvalue_subexpr -> begin let (env, te1, ty1) = raw_expr ~valkind:Lvalue_subexpr ~check_defined:true env e1 ~allow_awaitable:(*?*) false in match e1 with | (_, _, Lvar (_, x)) -> let env = if not (Env.is_local_present env x) then (* If the Lvar wasn't in the environment, add it in to avoid reporting subsequent errors. It has no bound since it wasn't a typed local. *) set_local ~is_defined:true ~bound_ty:None env (p, x) ty1 else env in (env, te1, ty1) | _ -> (env, te1, ty1) end | Other -> raw_expr ?lhs_of_null_coalesce env e1 ~allow_awaitable:(*?*) false (* External API *) let expr ?expected env e = Env.with_origin2 env Decl_counters.Body (fun env -> expr ?expected env e ~allow_awaitable:(*?*) false) let expr_with_pure_coeffects ?expected env e = Env.with_origin2 env Decl_counters.Body (fun env -> expr_with_pure_coeffects ?expected env e ~allow_awaitable:(*?*) false) let stmt env st = Env.with_origin env Decl_counters.Body (fun env -> stmt env st) let refine_hint ~pos ~reason env union_ty hint = let h = Decl_hint.hint env.Typing_env_types.decl_env hint in let ety_env = Typing_defs. { empty_expand_env with wildcard_action = Wildcard_fresh_generic_type_argument; } in let ((env, _errors), refining_ty) = Phase.localize env h ~ety_env in let (env, rty) = Env.expand_type env refining_ty in refine_and_simplify_intersection ~hint_first:false env pos reason (fst hint) union_ty rty
OCaml Interface
hhvm/hphp/hack/src/typing/typing.mli
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val debug_print_last_pos : 'a -> unit val expr : ?expected:Typing_helpers.ExpectedTy.t -> Typing_env_types.env -> Nast.expr -> Typing_env_types.env * Tast.expr * Typing_defs.locl_ty val expr_with_pure_coeffects : ?expected:Typing_helpers.ExpectedTy.t -> Typing_env_types.env -> Nast.expr -> Typing_env_types.env * Tast.expr * Typing_defs.locl_ty val stmt : Typing_env_types.env -> Nast.stmt -> Typing_env_types.env * Tast.stmt val bind_params : Typing_env_types.env -> ?can_read_globals:bool -> no_auto_likes:bool -> Aast_defs.contexts option -> Typing_defs.locl_ty option list -> Nast.fun_param list -> Typing_env_types.env * Tast.fun_param list val fun_ : ?abstract:bool -> ?native:bool -> ?disable:bool -> Typing_env_types.env -> Typing_env_return_info.t -> Pos.t -> Nast.func_body -> Ast_defs.fun_kind -> Typing_env_types.env * Tast.stmt list val attributes_check_def : Typing_env_types.env -> string -> Nast.user_attribute list -> Typing_env_types.env * Tast.user_attribute list val file_attributes : Typing_env_types.env -> Nast.file_attribute list -> Typing_env_types.env * Tast.file_attribute list val type_param : Typing_env_types.env -> Nast.tparam -> Typing_env_types.env * Tast.tparam type dyn_func_kind val call : expected:Typing_helpers.ExpectedTy.t option -> ?nullsafe:Pos.t option -> ?in_await:Typing_reason.t -> ?dynamic_func:dyn_func_kind -> expr_pos:Pos.t -> recv_pos:Pos.t -> Typing_env_types.env -> Typing_defs.locl_ty -> (Ast_defs.param_kind * Nast.expr) list -> Nast.expr option -> Typing_env_types.env * ((Ast_defs.param_kind * Tast.expr) list * Tast.expr option * Typing_defs.locl_ty * bool) val with_special_coeffects : Typing_env_types.env -> Typing_defs.locl_ty -> Typing_defs.locl_ty -> (Typing_env_types.env -> Typing_env_types.env * 'a) -> Typing_env_types.env * 'a val triple_to_pair : Typing_env_types.env * 'a * 'b -> Typing_env_types.env * ('a * 'b) val check_function_dynamically_callable : this_class:Decl_provider.Class.t option -> Typing_env_types.env -> Aast_defs.sid option -> Nast.fun_ -> Typing_defs.decl_ty option list -> Typing_defs.locl_ty -> Typing_env_types.env * Tast.fun_param list * Tast.stmt list * Tast.ty val refine_hint : pos:Pos.t -> reason:Typing_reason.t -> Typing_env_types.env -> Typing_defs.locl_ty -> Aast.hint -> Typing_env_types.env * Typing_defs.locl_ty
OCaml
hhvm/hphp/hack/src/typing/typing_algebra.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. * *) module TySet = Typing_set let factorize_common_types tyl1 tyl2 = (* Factorize common types, for example (A | B) & (A | C) = A | (B & C) and (A | B | C1 | D1) & (A | B | C2 | D2) = A | B | ((C1 | D1) & (C2 | D2)) return the common types, followed by the unique types from each input list *) let tys1 = TySet.of_list tyl1 in let tys2 = TySet.of_list tyl2 in let common_tys = TySet.inter tys1 tys2 in let tys1' = TySet.diff tys1 common_tys in let tys2' = TySet.diff tys2 common_tys in let tyl1' = TySet.elements tys1' in let tyl2' = TySet.elements tys2' in let common_tyl = TySet.elements common_tys in (common_tyl, tyl1', tyl2')
OCaml Interface
hhvm/hphp/hack/src/typing/typing_algebra.mli
(* * Copyright (c) 2021, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Typing_defs val factorize_common_types : locl_ty list -> locl_ty list -> locl_ty list * locl_ty list * locl_ty list
OCaml
hhvm/hphp/hack/src/typing/typing_alias.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (*****************************************************************************) (* Module determining how long the longest "aliasing chain" of a given * block is. * * The problem: * The type-inference algorithm needs to find a fix point when dealing with * loops. * * Normally, a fix-point should be reached after 2 iterations. However, * there are pathological cases where this is not true. * It happens when the code is aliasing locals, because the type of locals * can change, a 'chain' of aliases can delay the moment where we reach a * fix point. * * Example: * // $x is an int * $x = $y; * $y = $z; * $z = 'hello'; * // $x will only become an int after 3 iterations. * *) (*****************************************************************************) open Hh_prelude open Common open Aast module Fake = Typing_fake_members (*****************************************************************************) (* Module computing all the aliased locals. * * if one writes '$y = $z', then the binding $y => $z is added to the map. * Note that object/class members are counted are counted as locals * (conservatively), because in some cases, they can behave like locals (cf * Typing_fake_members). *) (*****************************************************************************) module Dep = struct let add x1 x2 acc = let x2 = Local_id.to_string x2 in let prev = Option.value ~default:[] (SMap.find_opt x1 acc) in SMap.add x1 (x2 :: prev) acc let get key acc = match SMap.find_opt key acc with | None -> [] | Some kl -> kl let visitor local = object inherit [string list SMap.t] Nast.Visitor_DEPRECATED.visitor as parent method! on_expr acc ((_, _, e_) as e) = match e_ with | Lvar (_, x) -> add local x acc | Obj_get (((_, _, (This | Lvar _)) as x), (_, _, Id (_, y)), _, _) -> add local (Fake.make_id x y) acc | Class_get ((_, _, x), CGstring (_, y), _) -> add local (Fake.make_static_id x y) acc | _ -> parent#on_expr acc e end let expr local acc e = (visitor local)#on_expr acc e end module AliasMap : sig type t = string list SMap.t val get : string -> t -> string list val make : Nast.stmt -> t end = struct type t = string list SMap.t let get = Dep.get let local_to_string = function | Lvar (_, x) -> Some (Local_id.to_string x) | Obj_get (((_, _, (This | Lvar _)) as x), (_, _, Id (_, y)), _, _) -> Some (Local_id.to_string (Fake.make_id x y)) | Class_get ((_, _, x), CGstring (_, y), _) -> Some (Local_id.to_string (Fake.make_static_id x y)) | _ -> None let visitor = object (this) inherit [string list SMap.t] Nast.Visitor_DEPRECATED.visitor as parent method! on_expr acc ((_, _, e_) as e) = match e_ with | Binop Aast.{ bop = Ast_defs.Eq _; lhs = (_, p, List el); rhs = x2 } -> List.fold_left ~f: begin fun acc e -> this#on_expr acc ( (), p, Binop Aast.{ bop = Ast_defs.Eq None; lhs = e; rhs = x2 } ) end ~init:acc el | Binop Aast.{ bop = Ast_defs.Eq _; lhs; rhs } -> this#on_assign acc lhs rhs | _ -> parent#on_expr acc e method on_assign acc (_, _, e1) e2 = Option.value_map (local_to_string e1) ~f: begin (fun s -> Dep.expr s acc e2) end ~default:acc method! on_efun acc _ = acc method! on_lfun acc _ _ = acc end let make st = visitor#on_stmt SMap.empty st end (*****************************************************************************) (* Given an alias map, returns the length of the longest possible * 'aliasing chain'. * * Example: * $x = $y; * $y = $z; * $z = 'hello'; * * RESULT=3 because of the chain $x => $y => $z *) (*****************************************************************************) module Depth : sig val get : AliasMap.t -> int end = struct let rec fold aliases = SMap.fold begin fun k _ (visited, current_max) -> let (visited, n) = key aliases visited k in (visited, max n current_max) end aliases (SMap.empty, 0) and key aliases visited k = if SMap.mem k visited then (visited, SMap.find k visited) else let visited = SMap.add k 0 visited in let kl = AliasMap.get k aliases in let (visited, depth_l) = List.map_env visited kl ~f:(key aliases) in let my_depth = 1 + List.fold_left ~f:max ~init:0 depth_l in (SMap.add k my_depth visited, my_depth) let get aliases = snd (fold aliases) end (*****************************************************************************) (* Entry point. *) (*****************************************************************************) let get_depth st = let aliases = AliasMap.make st in let result = Depth.get aliases in (* Needs to be at least 2 because of back edges. *) max 2 result
OCaml Interface
hhvm/hphp/hack/src/typing/typing_alias.mli
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val get_depth : Nast.stmt -> int
OCaml
hhvm/hphp/hack/src/typing/typing_arithmetic.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Common open Typing_defs module Env = Typing_env module MakeType = Typing_make_type module Reason = Typing_reason module SN = Naming_special_names let is_sub_dynamic env t = let (r, e) = Typing_solver.is_sub_type env t (MakeType.dynamic Reason.Rnone) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) e; r let is_float env t = let (r, e) = Typing_solver.is_sub_type env t (MakeType.float Reason.Rnone) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) e; r let is_int env t = let (r, e) = Typing_solver.is_sub_type env t (MakeType.int Reason.Rnone) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) e; r (* Checking of numeric operands for arithmetic operators that work only * on integers: * (1) Enforce that it coerce to int * (2) Check if it's dynamic *) let check_dynamic_or_enforce_int env p t r err = let et_type = MakeType.int r in let (env, ty_err_opt) = Typing_coercion.coerce_type ~coerce_for_op:true p Reason.URnone env t { et_type; et_enforced = Enforced } err in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let ty_mismatch = Option.map ty_err_opt ~f:Fn.(const (t, et_type)) in (env, Typing_utils.is_dynamic env t, ty_mismatch) (** [check_like_num p_exp p env ty] ensures that [ty] is a subtype of num or ~num. In the former case, it returns false and the type, in the latter, it returns true, and the type with the ~ removed. If it is not a subtype of either, the error generated refers to the attempt to make [ty] <: num. If there were errors in both cases, we return the errors from the non ~ case. *) let check_like_num ?err p_exp p env ty = let err = match err with | None -> if TypecheckerOptions.math_new_code (Env.get_tcopt env) then Typing_error.Callback.math_invalid_argument else Typing_error.Callback.unify_error | Some err -> err in let et_type = MakeType.num (Reason.Rarith p_exp) in Typing_coercion.coerce_type_like_strip p Reason.URnone env ty et_type err (** [expand_type_and_narrow_to_numeric ~allow_nothing env p ty] forces the solving of [ty] to a numeric type, based on its lower bounds. If allow_nothing is set, then it is allowed to return nothing when [ty] doesn't have numeric. Otherwise the default type of int will be solved to. *) let expand_type_and_narrow_to_numeric ~allow_nothing env p ty = let widen_for_arithmetic env ty = match get_node ty with | Tprim Tast.Tnum | Tprim Tast.Tfloat | Tprim Tast.Tint -> ((env, None), Some ty) | _ -> ((env, None), None) in let default = MakeType.int (Reason.Rarith p) in Typing_solver.expand_type_and_narrow env ~default ~force_solve:true ~allow_nothing ~description_of_expected:"a number" widen_for_arithmetic p ty (** [expand_type_and_try_narrow_to_float env p ty] tries to solve [ty] to float, based on its lower bounds. If it isn't solved to float, no narrowing is done. *) let expand_type_and_try_narrow_to_float env p ty = let widen_for_arithmetic env ty = match get_node ty with | Tprim Tast.Tfloat -> ((env, None), Some ty) | Tgeneric _ -> let float = MakeType.float (get_reason ty) in if Typing_subtype.is_sub_type env ty float then ((env, None), Some float) else ((env, None), None) | _ -> ((env, None), None) in Typing_solver.expand_type_and_narrow env ~force_solve:false ~allow_nothing:false ~description_of_expected:"a number" widen_for_arithmetic p ty (** [expand_type_and_try_narrow_to_nothing env p ty] tries to solve [ty] to nothing, based on its lower bounds. If it isn't solved to nothing, no narrowing is done. *) let expand_type_and_try_narrow_to_nothing env p ty = let widen_for_arithmetic env _ty = ((env, None), None) in Typing_solver.expand_type_and_narrow env ~force_solve:false ~allow_nothing:true ~description_of_expected:"a number" widen_for_arithmetic p ty let hole_on_err ((_, pos, _) as expr) err_opt = Option.value_map err_opt ~default:expr ~f:(fun (ty_have, ty_expect) -> Tast.make_typed_expr pos ty_have @@ Aast.(Hole (expr, ty_have, ty_expect, Typing))) (** [check_for_float_result p env p1 ty1 p2 ty2] Tries to narrow ty1 or ty2 to float, and if one can narrow, then the result is float. However, we don't want to do early solving otherwise, before we've detected the other cases that don't require full solving. *) let check_for_float_result p env p1 ty1 p2 ty2 = let make_float_type ~use_ty1_reason = Some (MakeType.float (if use_ty1_reason then Reason.Rarith_ret_float (p, get_reason ty1, Reason.Afirst) else Reason.Rarith_ret_float (p, get_reason ty2, Reason.Asecond))) in let float_no_reason = MakeType.float Reason.none in let ((env, ty_err_opt), ty1) = expand_type_and_try_narrow_to_float env p1 ty1 in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); if Typing_subtype.is_sub_type env ty1 float_no_reason then (env, make_float_type ~use_ty1_reason:true) else let ((env, ty_err_opt), ty2) = expand_type_and_try_narrow_to_float env p2 ty2 in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); if Typing_subtype.is_sub_type env ty2 float_no_reason then (env, make_float_type ~use_ty1_reason:false) else (env, None) let binop p env bop p1 te1 ty1 p2 te2 ty2 = let make_result ?(is_like = false) env te1 err_opt1 te2 err_opt2 ty = let (env, ty) = if is_like then Typing_union.union env ty (MakeType.dynamic (Reason.Rwitness p)) else (env, ty) in let hte1 = hole_on_err te1 err_opt1 and hte2 = hole_on_err te2 err_opt2 in let (env, te) = Typing_utils.make_simplify_typed_expr env p ty Aast.(Binop { bop; lhs = hte1; rhs = hte2 }) in (env, te, ty) in let int_no_reason = MakeType.int Reason.none in let num_no_reason = MakeType.num Reason.none in let nothing_no_reason = MakeType.nothing Reason.none in let make_nothing_type ~use_ty1_reason = MakeType.nothing (if use_ty1_reason then get_reason ty1 else get_reason ty2) in let is_any = Typing_utils.is_any env in let contains_any = is_any ty1 || is_any ty2 in match bop with (* Type of addition, subtraction and multiplication is essentially * (int,int):int * & (float,num):float * & (num,float):float * & (num,num):num *) | Ast_defs.Plus | Ast_defs.Minus | Ast_defs.Star when not contains_any -> let make_int_type () = MakeType.int (Reason.Rarith_ret_int p) in let make_num_type ~use_ty1_reason = let (r, apos) = if use_ty1_reason then (get_reason ty1, Reason.Afirst) else (get_reason ty2, Reason.Asecond) in MakeType.num (Reason.Rarith_ret_num (p, r, apos)) in let (env, ty1) = Env.expand_type env ty1 in let (env, ty2) = Env.expand_type env ty2 in let is_dynamic1 = Typing_defs.is_dynamic ty1 in let is_dynamic2 = Typing_defs.is_dynamic ty2 in let (env, ty_mismatch1, is_like1, ty1) = check_like_num p p1 env ty1 in let (env, ty_mismatch2, is_like2, ty2) = check_like_num p p2 env ty2 in (* We'll compute the type ignoring whether one of the arguments was a like-type, but we'll add the like type to the result type in the end if one was. *) let is_like = is_like1 || is_like2 in let (env, result_ty) = match check_for_float_result p env p1 ty1 p2 ty2 with | (env, Some ty) -> (env, ty) | (env, None) -> let is_int1 = Typing_subtype.is_sub_type env ty1 int_no_reason in let is_int2 = Typing_subtype.is_sub_type env ty2 int_no_reason in (* If both of the arguments is definitely subtypes of int, then the return is int *) if is_int1 && is_int2 then (env, make_int_type ()) else let is_num1 = Typing_subtype.is_sub_type env num_no_reason ty1 in let is_num2 = Typing_subtype.is_sub_type env num_no_reason ty2 in (* If one argument is exactly num, then the return is num. *) if is_num1 || is_num2 then (env, make_num_type ~use_ty1_reason:is_num1) else (* Otherwise, at least one of the arguments is unsolved, and we need to take care to not solve too eagerly. Put the first one to try in ty1, and the second, if any in ty2. Keep the result of the previous check whether the second type was an int. *) let ( (ty1, p1, is_dynamic1), (ty2, p2, is_int2, is_dynamic2), swapped ) = if is_int1 then ((ty2, p2, is_dynamic2), (ty1, p1, is_int1, is_dynamic1), true) else ((ty1, p1, is_dynamic1), (ty2, p2, is_int2, is_dynamic2), false) in let ((env, ty_err_opt), ty1) = expand_type_and_narrow_to_numeric ~allow_nothing:is_dynamic1 env p1 ty1 in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); (* If the first type solved a subtype of int, and the second was already int, then it is sound to return int. *) let is_int1 = Typing_subtype.is_sub_type env ty1 int_no_reason in if is_int1 && is_int2 then (env, make_int_type ()) else (* If the first type solved to exactly num, then we can just return that *) let is_num1 = Typing_subtype.is_sub_type env num_no_reason ty1 in if is_num1 then (env, make_num_type ~use_ty1_reason:swapped) else (* The second type needs solving too *) let ((env, ty_err_opt), ty2) = expand_type_and_narrow_to_numeric ~allow_nothing:is_dynamic2 env p2 ty2 in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); if Typing_subtype.is_sub_type env ty1 nothing_no_reason && Typing_subtype.is_sub_type env ty2 nothing_no_reason then (env, make_nothing_type ~use_ty1_reason:swapped) else if is_int1 && Typing_subtype.is_sub_type env ty2 int_no_reason then (env, make_int_type ()) else (env, make_num_type ~use_ty1_reason:(not swapped)) in make_result ~is_like env te1 ty_mismatch1 te2 ty_mismatch2 result_ty (* Type of division and exponentiation is essentially * (float,num):float * & (num,float):float * & (num,num):num *) | Ast_defs.Slash | Ast_defs.Starstar when not contains_any -> let make_num_type () = match bop with | Ast_defs.Slash -> MakeType.num (Reason.Rret_div p) | _ -> MakeType.num (Reason.Rarith_ret p) in let (env, ty_mismatch1, is_like1, ty1) = check_like_num p p1 env ty1 in let (env, ty_mismatch2, is_like2, ty2) = check_like_num p p2 env ty2 in (* We'll compute the type ignoring whether one of the arguments was a like-type, but we'll add the like type to the result type in the end if one was. *) let is_like = is_like1 || is_like2 in let (env, result_ty) = match check_for_float_result p env p1 ty1 p2 ty2 with | (env, Some ty) -> (env, ty) | (env, None) -> (* We return num, unless both ty1 and ty2 will solve to nothing. This would happen for dynamic / dynamic, and in that case we want to return nothing, in order to get back dynamic in the end. For that to happen, we would have to have detected like types on both arguments. *) if not (is_like1 && is_like2) then (env, make_num_type ()) else let ((env, ty_err_opt), ty1) = expand_type_and_try_narrow_to_nothing env p1 ty1 in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let ((env, ty_err_opt), ty2) = expand_type_and_try_narrow_to_nothing env p2 ty2 in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); if Typing_subtype.is_sub_type env ty1 nothing_no_reason && Typing_subtype.is_sub_type env ty2 nothing_no_reason then (env, make_nothing_type ~use_ty1_reason:true) else (env, make_num_type ()) in make_result ~is_like env te1 ty_mismatch1 te2 ty_mismatch2 result_ty | Ast_defs.Percent | Ast_defs.Ltlt | Ast_defs.Gtgt when not contains_any -> let err = match bop with | Ast_defs.Percent -> if TypecheckerOptions.math_new_code (Env.get_tcopt env) then Typing_error.Callback.math_invalid_argument else Typing_error.Callback.unify_error | _ -> Typing_error.Callback.bitwise_math_invalid_argument in let (env, _, err_opt1) = check_dynamic_or_enforce_int env p1 ty1 (Reason.Rarith p) err in let (env, _, err_opt2) = check_dynamic_or_enforce_int env p2 ty2 (Reason.Rarith p) err in let r = match bop with | Ast_defs.Percent -> Reason.Rarith_ret_int p | _ -> Reason.Rbitwise_ret p in make_result env te1 err_opt1 te2 err_opt2 (MakeType.int r) | Ast_defs.Xor | Ast_defs.Amp | Ast_defs.Bar when not contains_any -> let (env, is_dynamic1, err_opt1) = check_dynamic_or_enforce_int env p ty1 (Reason.Rbitwise p1) Typing_error.Callback.bitwise_math_invalid_argument in let (env, is_dynamic2, err_opt2) = check_dynamic_or_enforce_int env p ty2 (Reason.Rbitwise p2) Typing_error.Callback.bitwise_math_invalid_argument in let result_ty = if is_dynamic1 && is_dynamic2 then MakeType.dynamic (Reason.Rbitwise_dynamic p) else MakeType.int (Reason.Rbitwise_ret p) in make_result env te1 err_opt1 te2 err_opt2 result_ty | Ast_defs.Eqeq | Ast_defs.Diff -> begin let rec strict_allowable_types ty = let open Aast in match get_node ty with | Tdynamic -> true | Tprim prim -> (match prim with | Tint | Tbool | Tfloat | Tstring -> true | _ -> false) | Tclass ((_, name), _, type_args) (* allow vec, keyset, and dict *) when String.equal name SN.Collections.cVec || String.equal name SN.Collections.cKeyset || String.equal name SN.Collections.cDict -> List.for_all type_args ~f:strict_allowable_types | _ -> false in let same_type env ty1 ty2 = Typing_subtype.is_sub_type env ty1 ty2 && Typing_subtype.is_sub_type env ty2 ty1 || is_sub_dynamic env ty1 || is_sub_dynamic env ty2 in (* Allow value-equating types A, B such that: - [(A <: B and B <: A) or (A and/or B is dynamic)] - AND (A and B are dynamic/primitive) We also allow the basic value container types `vec`, `keyset`, and `dict` to be compared. *) let rec strict_equatable env ty1 ty2 = strict_allowable_types ty1 && strict_allowable_types ty2 && (same_type env ty1 ty2 || (* Cover the case where the containers have a dynamic parameter, since `same_type` would evaluate to false. E.g. `vec<dynamic> == vec<int>` should be allowed. *) match (get_node ty1, get_node ty2) with | ( Tclass ((_, name1), _, container_tys1), Tclass ((_, name2), _, container_tys2) ) when String.equal name1 name2 -> (match List.for_all2 container_tys1 container_tys2 ~f:(strict_equatable env) with | List.Or_unequal_lengths.Ok all_true -> all_true | _ -> false) | _ -> false) in if TypecheckerOptions.strict_value_equality (Env.get_tcopt env) && not (strict_equatable env ty1 ty2) then let tys1 = lazy (Typing_print.error env ty1) and tys2 = lazy (Typing_print.error env ty2) in Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Strict_eq_value_incompatible_types { pos = p; left = Lazy.map tys1 ~f:(fun tys1 -> Reason.to_string ("This is " ^ tys1) (get_reason ty1)); right = Lazy.map tys2 ~f:(fun tys2 -> Reason.to_string ("This is " ^ tys2) (get_reason ty2)); }) end; make_result env te1 None te2 None (MakeType.bool (Reason.Rcomp p)) | Ast_defs.Eqeqeq | Ast_defs.Diff2 -> make_result env te1 None te2 None (MakeType.bool (Reason.Rcomp p)) | Ast_defs.Lt | Ast_defs.Lte | Ast_defs.Gt | Ast_defs.Gte | Ast_defs.Cmp -> let ty_num = MakeType.num (Reason.Rcomp p) in let ty_int = MakeType.int (Reason.Rcomp p) in let ty_bool = MakeType.bool (Reason.Rcomp p) in let ty_result = match bop with | Ast_defs.Cmp -> ty_int | _ -> ty_bool in let ty_string = MakeType.string (Reason.Rcomp p) in let ty_datetime = MakeType.datetime (Reason.Rcomp p) in let ty_datetimeimmutable = MakeType.datetime_immutable (Reason.Rcomp p) in let ty_dynamic = MakeType.dynamic (Reason.Rcomp p) in let both_sub ty = Typing_subtype.can_sub_type env ty1 ty && Typing_subtype.can_sub_type env ty2 ty in (* * Comparison here is allowed when both args are num, both string, or both * DateTime | DateTimeImmutable. Alternatively, either or both args can be * dynamic. We use both_sub to check that both arguments subtype a type. * * This actually does not properly handle union types. For instance, * DateTime | DateTimeImmutable is neither a subtype of DateTime nor * DateTimeImmutable, but it will be the type of an element coming out * of a vector containing both. Further, dynamic could be comparable to * num | string | DateTime | DateTimeImmutable | dynamic. Better union * handling would be an improvement. *) (if (not contains_any) && not (both_sub (MakeType.union (Reason.Rcomp p) [ty_num; ty_dynamic]) || both_sub (MakeType.union (Reason.Rcomp p) [ty_string; ty_dynamic]) || both_sub (MakeType.union (Reason.Rcomp p) [ty_datetime; ty_datetimeimmutable; ty_dynamic])) then let ty1 = lazy (Typing_expand.fully_expand env ty1) and ty2 = lazy (Typing_expand.fully_expand env ty2) in let tys1 = Lazy.map ty1 ~f:(fun ty -> (ty, Typing_print.error env ty)) and tys2 = Lazy.map ty2 ~f:(fun ty -> (ty, Typing_print.error env ty)) in Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Comparison_invalid_types { pos = p; left = Lazy.map tys1 ~f:(fun (ty1, tys1) -> Reason.to_string ("This is " ^ tys1) (get_reason ty1)); right = Lazy.map tys2 ~f:(fun (ty2, tys2) -> Reason.to_string ("This is " ^ tys2) (get_reason ty2)); })); make_result env te1 None te2 None ty_result | Ast_defs.Dot -> (* A bit weird, this one: * function(Stringish | string, Stringish | string) : string) *) if TypecheckerOptions.enable_strict_string_concat_interp (Env.get_tcopt env) then let sub_arraykey env p ty = let r = Reason.Rconcat_operand p in let (env, formatter_tyvar) = Env.fresh_type_invariant env p in let stringlike = MakeType.union r [ MakeType.arraykey r; MakeType.dynamic r; MakeType.hh_formatstring r formatter_tyvar; ] in let (env, ty_err_opt) = Typing_ops.sub_type p Reason.URstr_concat env ty stringlike Typing_error.Callback.strict_str_concat_type_mismatch in let ty_mismatch = Option.map ty_err_opt ~f:(Fn.const (ty, stringlike)) in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); (env, ty_mismatch) in let (env, err_opt1) = sub_arraykey env p1 ty1 in let (env, err_opt2) = sub_arraykey env p2 ty2 in let ty = MakeType.string (Reason.Rconcat_ret p) in make_result env te1 err_opt1 te2 err_opt2 ty else let (env, err_opt1) = Typing_substring.sub_string_err p1 env ty1 in let (env, err_opt2) = Typing_substring.sub_string_err p2 env ty2 in let ty = MakeType.string (Reason.Rconcat_ret p) in make_result env te1 err_opt1 te2 err_opt2 ty | Ast_defs.Barbar | Ast_defs.Ampamp -> make_result env te1 None te2 None (MakeType.bool (Reason.Rlogic_ret p)) | Ast_defs.QuestionQuestion | Ast_defs.Eq _ when not contains_any -> assert false | _ -> assert contains_any; if is_any ty1 then make_result env te1 None te2 None ty1 else make_result env te1 None te2 None ty2 let unop p env uop te ty = let make_result env te err_opt result_ty = let hte = hole_on_err te err_opt in let (env, te) = Typing_utils.make_simplify_typed_expr env p result_ty (Aast.Unop (uop, hte)) in (env, te, result_ty) in let is_any = Typing_utils.is_any env in match uop with | Ast_defs.Unot -> if is_any ty then make_result env te None ty else (* args isn't any or a variant thereof so can actually do stuff *) (* !$x (logical not) works with any type, so we just return Tbool *) make_result env te None (MakeType.bool (Reason.Rlogic_ret p)) | Ast_defs.Utild -> if is_any ty then make_result env te None ty else (* args isn't any or a variant thereof so can actually do stuff *) let (env, is_dynamic, err_opt) = check_dynamic_or_enforce_int env p ty (Reason.Rbitwise p) Typing_error.Callback.bitwise_math_invalid_argument in let result_ty = if is_dynamic then MakeType.dynamic (Reason.Rbitwise_dynamic p) else MakeType.int (Reason.Rbitwise_ret p) in make_result env te err_opt result_ty | Ast_defs.Uplus | Ast_defs.Uminus | Ast_defs.Uincr | Ast_defs.Upincr | Ast_defs.Udecr | Ast_defs.Updecr -> if is_any ty then make_result env te None ty else let allow_nothing = Typing_defs.is_dynamic ty in let (env, ty_mismatch, is_like, ty) = check_like_num ?err: (match uop with | Ast_defs.Uincr | Ast_defs.Upincr | Ast_defs.Udecr | Ast_defs.Updecr -> Some Typing_error.Callback.inc_dec_invalid_argument | _ -> None) p p env ty in let ((env, ty_err_opt), (ty : locl_ty)) = expand_type_and_narrow_to_numeric ~allow_nothing env p ty in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let result_ty = if Typing_subtype.is_sub_type env ty (MakeType.nothing Reason.none) then MakeType.nothing (get_reason ty) else if is_float env ty then MakeType.float (Reason.Rarith_ret_float (p, get_reason ty, Reason.Aonly)) else if is_int env ty then MakeType.int (Reason.Rarith_ret_int p) else MakeType.num (Reason.Rarith_ret_num (p, get_reason ty, Reason.Aonly)) in let (env, result_ty) = if is_like then Typing_union.union env result_ty (MakeType.dynamic (get_reason result_ty)) else (env, result_ty) in make_result env te ty_mismatch result_ty | Ast_defs.Usilence -> (* Silencing does not change the type *) (* any check omitted because would return the same anyway *) make_result env te None ty
OCaml Interface
hhvm/hphp/hack/src/typing/typing_arithmetic.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 binop : Pos.t -> Typing_env_types.env -> Ast_defs.bop -> Pos.t -> Tast.expr -> Typing_defs.locl_ty -> Pos.t -> Tast.expr -> Typing_defs.locl_ty -> Typing_env_types.env * Tast.expr * Tast.ty val unop : Pos.t -> Typing_env_types.env -> Ast_defs.uop -> Tast.expr -> Typing_defs.locl_ty -> Typing_env_types.env * Tast.expr * Tast.ty
OCaml
hhvm/hphp/hack/src/typing/typing_array_access.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 Typing_defs module Env = Typing_env module TUtils = Typing_utils module Reason = Typing_reason module MakeType = Typing_make_type module SubType = Typing_subtype module GenericRules = Typing_generic_rules module SN = Naming_special_names open String.Replace_polymorphic_compare let mk_ty_mismatch_res ty_have ty_expect = Option.value_map ~default:(Ok ty_have) ~f:Fn.(const @@ Error (ty_have, ty_expect)) let err_witness env p = Env.fresh_type_error env p let error_array env p ty = Typing_error_utils.add_typing_error ~env Typing_error.( with_code ~code:Error_code.IndexTypeMismatch @@ primary @@ Primary.Array_access { ctxt = `read; pos = p; decl_pos = get_pos ty; ty_name = lazy (Typing_print.error env ty); }) let error_const_mutation env p ty = Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Const_mutation { pos = p; decl_pos = get_pos ty; ty_name = lazy (Typing_print.error env ty); }); err_witness env p let error_assign_array_append env p ty = if not (TUtils.is_tyvar_error env ty) then Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Array_append { pos = p; decl_pos = get_pos ty; ty_name = lazy (Typing_print.error env ty); }); (env, ty) let maybe_make_supportdyn r env ~supportdyn ty = if supportdyn then Typing_utils.make_supportdyn r env ty else (env, ty) (* Given a type `ty` known to be a lower bound on the type of the array operand * to an array get operation, compute the largest upper bound on that type * that validates the get operation. For example, if `vec<string>` is a lower * bound, then the type must be a subtype of `KeyedContainer<#1,#2>` for some * unresolved types #1 and #2. If `(string,int)` is a lower bound, then * `(#1, #2)` is a suitable upper bound. Shapes are the most complex. If * `shape(known_fields, ...)` is a lower bound (an open shape type), and the * access is through a literal field f, then `shape('f' => #1, ...)` is a * suitable upper bound. *) let widen_for_array_get ~lhs_of_null_coalesce ~expr_pos index_expr 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_array_get", [Log_type ("ty", ty)])])); match deref ty with (* The null type is valid only with a null-coalescing use of array get *) | (_, Tprim Tnull) when lhs_of_null_coalesce -> ((env, None), Some ty) (* dynamic is valid for array get *) | (_, Tdynamic) -> ((env, None), Some ty) (* All class-based containers, and keyset, vec and dict, are subtypes of * some instantiation of KeyedContainer *) | (r, Tclass ((_, cn), _, _)) when cn = SN.Collections.cVector || cn = SN.Collections.cVec || cn = SN.Collections.cMap || cn = SN.Collections.cDict || cn = SN.Collections.cKeyset || cn = SN.Collections.cConstMap || cn = SN.Collections.cImmMap || cn = SN.Collections.cKeyedContainer || cn = SN.Collections.cAnyArray || cn = SN.Collections.cConstVector || cn = SN.Collections.cImmVector -> let (env, element_ty) = Env.fresh_type_invariant env expr_pos in let (env, index_ty) = Env.fresh_type_invariant env expr_pos in let ty = MakeType.keyed_container r index_ty element_ty in ((env, None), Some ty) (* The same is true of PHP arrays *) | (r, Tvec_or_dict _) -> let (env, element_ty) = Env.fresh_type_invariant env expr_pos in let (env, index_ty) = Env.fresh_type_invariant env expr_pos in let ty = MakeType.keyed_container r index_ty element_ty in ((env, None), Some ty) (* For tuples, we just freshen the element types *) | (r, Ttuple tyl) -> begin (* requires integer literal *) match index_expr with (* Should freshen type variables *) | (_, _, Aast.Int _) -> let (env, params) = List.map_env env tyl ~f:(fun env _ty -> Env.fresh_type_invariant env expr_pos) in ((env, None), Some (MakeType.tuple r params)) | _ -> ((env, None), None) end (* Whatever the lower bound, construct an open, singleton shape type. *) | (r, Tshape { s_fields = fdm; _ }) -> begin let (fld_opt, ty_err_opt) = TUtils.shape_field_name_with_ty_err env index_expr in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; match fld_opt with | None -> ((env, None), None) | Some field -> let field = TShapeField.of_ast Pos_or_decl.of_raw_pos field in (match TShapeMap.find_opt field fdm with (* If field is in the lower bound but is optional, then no upper bound makes sense * unless this is a null-coalesce access *) | Some { sft_optional = true; _ } when not lhs_of_null_coalesce -> ((env, None), None) | _ -> let (env, element_ty) = Env.fresh_type_invariant env expr_pos in let (env, rest_ty) = Env.fresh_type_invariant env expr_pos in let upper_fdm = TShapeMap.add field { sft_optional = lhs_of_null_coalesce; sft_ty = element_ty } TShapeMap.empty in let upper_shape_ty = MakeType.shape r rest_ty upper_fdm in ((env, None), Some upper_shape_ty)) end | _ -> ((env, None), None) (* Check that an index to a map-like collection passes the basic test of * being a subtype of arraykey *) let check_arraykey_index error env pos container_ty index_ty = if TypecheckerOptions.disallow_invalid_arraykey (Env.get_tcopt env) then ( let (env, container_ty) = Env.expand_type env container_ty in let reason = match get_node container_ty with | Tclass ((_, cn), _, _) -> Reason.index_class cn | _ -> Reason.index_array in let info_of_type ty = (get_pos ty, lazy (Typing_print.error env ty)) in let container_info = info_of_type container_ty in let index_info = info_of_type index_ty in let ty_arraykey = MakeType.arraykey (Reason.Ridx_dict pos) in let ty_expected = { et_type = ty_arraykey; et_enforced = Enforced } in (* If we have an error in coercion here, we will add a `Hole` indicating the actual and expected type. The `Hole` may then be used in a codemod to add a call to `UNSAFE_CAST` so we need to consider what type we expect. There is a somewhat common pattern in older parts of www to do something like: ``` function keyset_issue(?string $x): keyset<string> { $xs = keyset<string>[]; ... /* HH_FIXME[4435] keyset values must be arraykeys */ $xs[] = $x; return Keyset\filter_nulls($xs); } ``` (even though it is impossible for keysets to contain nulls). If we were to add an expected type of 'arraykey' here it would be correct but adding an `UNSAFE_CAST<?string,arraykey>($x)` means we get cascading errors; here, we now have the wrong return type. To try and prevent this, if this is an optional type where the nonnull part can be coerced to arraykey, we prefer that type as our expected type. *) let base_error = error pos container_info index_info in let (ty_actual, is_option) = match deref index_ty with | (_, Toption inner_ty) -> (inner_ty, true) | _ -> (index_ty, false) in let (env, e1) = Typing_coercion.coerce_type ~coerce_for_op:true pos reason env ty_actual ty_expected @@ Typing_error.Callback.always base_error in let (ty_mismatch, e2) = match e1 with | None when is_option -> (Error (index_ty, ty_actual), Some (Typing_error.primary base_error)) | None -> (Ok index_ty, None) | Some _ -> (Error (index_ty, ty_arraykey), None) in Option.( iter ~f:(Typing_error_utils.add_typing_error ~env) @@ merge e1 e2 ~f:Typing_error.both); (env, ty_mismatch) ) else (env, Ok index_ty) let check_arraykey_index_read = let mk_err pos (container_pos, container_ty_name) (key_pos, key_ty_name) = Typing_error.Primary.Invalid_arraykey { pos; ctxt = `read; container_pos; container_ty_name; key_pos; key_ty_name; } in check_arraykey_index mk_err let check_arraykey_index_write = let mk_err pos (container_pos, container_ty_name) (key_pos, key_ty_name) = Typing_error.Primary.Invalid_arraykey { pos; ctxt = `write; container_pos; container_ty_name; key_pos; key_ty_name; } in check_arraykey_index mk_err let check_keyset_value = let mk_err pos (container_pos, container_ty_name) (value_pos, value_ty_name) = Typing_error.Primary.Invalid_keyset_value { pos; container_pos; container_ty_name; value_pos; value_ty_name } in check_arraykey_index mk_err let check_set_value = let mk_err pos (container_pos, container_ty_name) (value_pos, value_ty_name) = Typing_error.Primary.Invalid_set_value { pos; container_pos; container_ty_name; value_pos; value_ty_name } in check_arraykey_index mk_err let pessimise_type env ty = Typing_union.union env ty (MakeType.dynamic (get_reason ty)) let maybe_pessimise_type env ty = if TypecheckerOptions.pessimise_builtins (Env.get_tcopt env) then pessimise_type env ty else (env, ty) let pessimised_tup_assign p env arg_ty = let env = Env.open_tyvars env p in let (env, ty) = Env.fresh_type env p in let (env, pess_ty) = pessimise_type env ty in let env = Env.set_tyvar_variance env pess_ty in (* There can't be an error since the type variable is fresh *) let cb = Typing_error.Reasons_callback.unify_error_at p in let (env, ty_err_opt) = SubType.sub_type env arg_ty pess_ty (Some cb) in (* Enforce the invariant - this call should never give us an error *) if Option.is_some ty_err_opt then Errors.internal_error p "Subtype of fresh type variable"; let (env, ty_err_opt) = Typing_solver.close_tyvars_and_solve env in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (env, ty) (* Typing of array-get like expressions; [ty1] is the type of the expression into which we are indexing (the 'collection'), [e2] is the index expression and [ty2] is the type of that expression. We return: 1) the (modified) typing environment, 2) the type of the resulting expression (i.e. the type of the element we are 'getting') 3) the actual and expected type of the indexed expression, indicating a type mismatch (if any) 4) the actual and expected type of the indexing expression, indicating a type mismatch (if any) and an optional type mismatch giving the actual vs expected type of the The function has an error side-effect *) let rec array_get ~array_pos ~expr_pos ?(lhs_of_null_coalesce = false) is_lvalue env ty1 e2 ty2 = let ((env, ty_err1), ty1) = Typing_solver.expand_type_and_narrow env ~description_of_expected:"an array or collection" (widen_for_array_get ~lhs_of_null_coalesce ~expr_pos e2) array_pos ty1 in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err1; GenericRules.apply_rules_with_index_value_ty_mismatches ~ignore_type_structure:true ~preserve_supportdyn:true env ty1 (fun env ~supportdyn:_ ty1 -> let (r, ety1_) = deref ty1 in let dflt_arr_res = Ok ty1 in (* This is a little weird -- we enforce the right arity when you use certain * collections, even in partial mode (where normally completely omitting the * type parameter list is admitted). Basically the "omit type parameter" * hole was for compatibility with certain interfaces like Arrayaccess, not * for collections! But it's hard to go back on now, so since we've always * errored (with an inscrutable error message) when you try to actually use * a collection with omitted type parameters, we can continue to error and * give a more useful error message. *) let arity_error (_, name) = Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Array_get_arity { pos = expr_pos; name; decl_pos = Reason.to_pos r }) in let nullable_container_get env ty_actual ty = if lhs_of_null_coalesce || Tast.is_under_dynamic_assumptions env.Typing_env_types.checked (* Normally, we would not allow indexing into a nullable container, however, because the pattern shows up so frequently, we are allowing indexing into a nullable container as long as it is on the lhs of a null coalesce *) then array_get ~array_pos ~expr_pos ~lhs_of_null_coalesce is_lvalue env ty e2 ty2 else let arraykey = MakeType.arraykey Reason.none in let mixed = MakeType.mixed Reason.none in (* If our non-null type, ty, is a subtype of `KeyedContainer` use it in the hole, otherwise suggest KeyedContainer *) let (env, ty_expected) = if SubType.is_sub_type env ty (MakeType.keyed_container Reason.none arraykey mixed) then (env, ty) else let nothing = MakeType.nothing Reason.none in let (env, ty2) = Typing_intersection.intersect env ~r:Reason.Rnone arraykey ty2 in (env, MakeType.keyed_container Reason.none ty2 nothing) in Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Null_container { pos = expr_pos; null_witness = lazy (Reason.to_string "This is what makes me believe it can be `null`." r); }); let (env, ty) = err_witness env expr_pos in (env, (ty, Some (ty_actual, ty_expected), None)) in let type_index env p ty_have ty_expect reason = Typing_log.( log_with_level env "typing" ~level:1 (fun () -> log_types (Pos_or_decl.of_raw_pos p) env [ Log_head ( "array_get/type_index", [ Log_type ("ty_have", ty_have); Log_type ("ty_expect", ty_expect.et_type); ] ); ])); let (env, ty_err_opt) = Typing_coercion.coerce_type ~coerce_for_op:true p reason env ty_have ty_expect Typing_error.Callback.index_type_mismatch in let ty_mismatch = mk_ty_mismatch_res ty_have ty_expect.et_type ty_err_opt in ((env, ty_err_opt), ty_mismatch) in let got_dynamic () = let tv = MakeType.dynamic r in let (env, idx_ty_err_opt) = TUtils.supports_dynamic env ty2 @@ Some (Typing_error.Reasons_callback.unify_error_at expr_pos) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) idx_ty_err_opt; let idx_err_res = mk_ty_mismatch_res ty2 tv idx_ty_err_opt in (env, (tv, dflt_arr_res, idx_err_res)) in match ety1_ with | Tclass (((_, cn) as id), _, argl) when String.equal cn SN.Collections.cVector || String.equal cn SN.Collections.cVec -> let (env, ty) = match argl with | [ty] -> if String.equal cn SN.Collections.cVector then maybe_pessimise_type env ty else (env, ty) | _ -> arity_error id; err_witness env expr_pos in let (_, p2, _) = e2 in let ty1 = MakeType.enforced (MakeType.int (Reason.Ridx_vector p2)) in let ((env, ty_err_opt), idx_err_res) = type_index env expr_pos ty2 ty1 (Reason.index_class cn) in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); (env, (ty, dflt_arr_res, idx_err_res)) | Tclass (((_, cn) as id), _, argl) when cn = SN.Collections.cMap || cn = SN.Collections.cDict || cn = SN.Collections.cKeyset -> if cn = SN.Collections.cKeyset && is_lvalue then ( Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Keyset_set { pos = expr_pos; decl_pos = Reason.to_pos r }); let (env, ty) = err_witness env expr_pos in (env, (ty, Ok ty2, dflt_arr_res)) ) else let (k, (env, v)) = match argl with | [t] when String.equal cn SN.Collections.cKeyset -> (t, (env, t)) | [k; v] when String.equal cn SN.Collections.cDict -> (k, (env, v)) | [k; v] when String.( <> ) cn SN.Collections.cKeyset -> (k, maybe_pessimise_type env v) | _ -> arity_error id; let (env, ty) = err_witness env expr_pos in (ty, (env, ty)) in (* dict and keyset are covariant in the key type, so subsumption * lets you upcast the key type beyond ty2 to arraykey. * e.g. consider $d: dict<string,int> and $i:int * and $d[$i] should actually type check because * dict<string,int> <: dict<arraykey,int> *) let ((env, ty_err_opt), idx_err_res) = if String.equal cn SN.Collections.cMap then let (env, k) = Env.expand_type env k in let (env, k) = maybe_pessimise_type env k in type_index env expr_pos ty2 (MakeType.enforced k) (Reason.index_class cn) else let (env, res) = check_arraykey_index_read env expr_pos ty1 ty2 in ((env, None), res) in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); (env, (v, dflt_arr_res, idx_err_res)) (* Certain container/collection types are intended to be immutable/const, * thus they should never appear as a lvalue when indexing i.e. * * $x[0] = 100; // ERROR * $x[0]; // OK *) | Tclass (((_, cn) as id), _, argl) when String.equal cn SN.Collections.cConstMap || String.equal cn SN.Collections.cImmMap || String.equal cn SN.Collections.cKeyedContainer || String.equal cn SN.Collections.cAnyArray -> if is_lvalue then let (env, ty1) = error_const_mutation env expr_pos ty1 in let ty_nothing = MakeType.nothing Reason.none in (env, (ty1, Error (ty1, ty_nothing), Ok ty2)) else let (_k, (env, v)) = match argl with | [k; v] -> (k, maybe_pessimise_type env v) | _ -> arity_error id; let (env, ty) = err_witness env expr_pos in (ty, (env, ty)) in let (env, idx_err_res) = check_arraykey_index_read env expr_pos ty1 ty2 in (env, (v, dflt_arr_res, idx_err_res)) | Tclass (((_, cn) as id), _, argl) when (not is_lvalue) && (String.equal cn SN.Collections.cConstVector || String.equal cn SN.Collections.cImmVector) -> let (env, ty) = match argl with | [ty] -> maybe_pessimise_type env ty | _ -> arity_error id; err_witness env expr_pos in let (_, p2, _) = e2 in let ty1 = MakeType.enforced (MakeType.int (Reason.Ridx (p2, r))) in let ((env, ty_err1), idx_err_res) = type_index env expr_pos ty2 ty1 (Reason.index_class cn) in Option.iter ty_err1 ~f:(Typing_error_utils.add_typing_error ~env); (env, (ty, dflt_arr_res, idx_err_res)) | Tclass ((_, cn), _, tys) when is_lvalue && (String.equal cn SN.Collections.cConstVector || String.equal cn SN.Collections.cImmVector) -> let (env, ty1) = error_const_mutation env expr_pos ty1 in let ty_vector = MakeType.class_type Reason.none SN.Collections.cVector tys in (env, (ty1, Error (ty1, ty_vector), Ok ty2)) | Tvec_or_dict (_k, v) -> let (env, idx_err_res) = check_arraykey_index_read env expr_pos ty1 ty2 in let (env, tv) = maybe_pessimise_type env v in (env, (tv, dflt_arr_res, idx_err_res)) | Tvar _ when TUtils.is_tyvar_error env ty1 -> let (env, ty) = err_witness env expr_pos in (env, (ty, dflt_arr_res, Ok ty2)) | Tdynamic when Typing_env_types.( TypecheckerOptions.enable_sound_dynamic env.genv.tcopt) -> got_dynamic () | Tdynamic | Tany _ -> (env, (ty1, dflt_arr_res, Ok ty2)) | Tprim Tstring -> let ty = MakeType.string (Reason.Rwitness expr_pos) in let (_, p2, _) = e2 in let ty1 = MakeType.enforced (MakeType.int (Reason.Ridx (p2, r))) in let ((env, ty_err1), idx_err_res) = type_index env expr_pos ty2 ty1 Reason.index_array in Option.iter ty_err1 ~f:(Typing_error_utils.add_typing_error ~env); (env, (ty, dflt_arr_res, idx_err_res)) | Ttuple tyl -> (* requires integer literal *) (match e2 with | (_, p, Int n) -> let idx = int_of_string_opt n in (match Option.bind idx ~f:(List.nth tyl) with | Some nth -> (env, (nth, dflt_arr_res, Ok ty2)) | None -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Generic_unify { pos = p; msg = Reason.string_of_ureason Reason.index_tuple; }); let (env, ty) = err_witness env p in (env, (ty, dflt_arr_res, Ok ty2))) | (_, p, _) -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Generic_unify { pos = p; msg = Reason.string_of_ureason Reason.URtuple_access; }); let (env, ty) = err_witness env expr_pos in (env, (ty, dflt_arr_res, Error (ty2, MakeType.int Reason.none)))) | Tclass (((_, cn) as id), _, argl) when String.equal cn SN.Collections.cPair -> let (ty_fst, ty_snd) = match argl with | [ty_fst; ty_snd] -> (ty_fst, ty_snd) | _ -> arity_error id; let (_env, ty) = err_witness env expr_pos in (ty, ty) in (* requires integer literal *) (match e2 with | (_, p, Int n) -> let idx = int_of_string_opt n in (match Option.bind ~f:(List.nth [ty_fst; ty_snd]) idx with | Some nth -> (env, (nth, dflt_arr_res, Ok ty2)) | None -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Generic_unify { pos = p; msg = Reason.string_of_ureason (Reason.index_class cn); }); let (env, ty) = err_witness env p in (env, (ty, dflt_arr_res, Ok ty2))) | (_, p, _) -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Generic_unify { pos = p; msg = Reason.string_of_ureason Reason.URpair_access; }); let (env, ty) = err_witness env p in (env, (ty, dflt_arr_res, Error (ty2, MakeType.int Reason.none)))) | Tshape { s_fields = fdm; _ } -> let (_, p, _) = e2 in begin let (fld_opt, ty_err_opt) = TUtils.shape_field_name_with_ty_err env e2 in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; match fld_opt with | None -> (* there was already an error in shape_field name, don't report another one for a missing field *) let (env, ty) = err_witness env p in (env, (ty, dflt_arr_res, Ok ty2)) | Some field -> let field = TShapeField.of_ast Pos_or_decl.of_raw_pos field in if is_lvalue || lhs_of_null_coalesce then (* The expression $s['x'] ?? $y is semantically equivalent to Shapes::idx ($s, 'x') ?? $y. I.e., if $s['x'] occurs on the left of a coalesce operator, then for type checking it can be treated as if it evaluated to null instead of throwing an exception if the field 'x' doesn't exist in $s. *) let (env, ty) = Typing_shapes.idx_without_default env ty1 field ~expr_pos ~shape_pos:array_pos in (env, (ty, dflt_arr_res, Ok ty2)) else begin match TShapeMap.find_opt field fdm with | None -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Undefined_field { pos = p; name = TUtils.get_printable_shape_field_name field; decl_pos = Reason.to_pos r; }); let (env, ty) = err_witness env p in (env, (ty, dflt_arr_res, Ok ty2)) | Some { sft_optional; sft_ty } -> if sft_optional then ( let declared_field = List.find_exn ~f:(fun x -> TShapeField.equal field x) (TShapeMap.keys fdm) in Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Array_get_with_optional_field { recv_pos = array_pos; field_pos = p; field_name = TUtils.get_printable_shape_field_name field; decl_pos = Typing_defs.TShapeField.pos declared_field; }); let (env, ty) = err_witness env p in (env, (ty, dflt_arr_res, Ok ty2)) ) else (env, (sft_ty, dflt_arr_res, Ok ty2)) end end | Toption ty -> let (env, (ty, err_opt_arr, err_opt_idx)) = nullable_container_get env ty1 ty in let err_res_arr = Option.value_map err_opt_arr ~default:dflt_arr_res ~f:(fun (ty_have, ty_expect) -> Error (ty_have, ty_expect)) in let err_res_idx = Option.value_map err_opt_idx ~default:(Ok ty2) ~f:(fun (ty_have, ty_expect) -> Error (ty_have, ty_expect)) in (env, (ty, err_res_arr, err_res_idx)) | Tprim Tnull -> if Tast.is_under_dynamic_assumptions env.Typing_env_types.checked then got_dynamic () else let ty = MakeType.nothing Reason.Rnone in let (env, (ty, err_opt_arr, err_opt_idx)) = nullable_container_get env ty1 ty in let err_res_arr = Option.value_map err_opt_arr ~default:dflt_arr_res ~f:(fun (ty_have, ty_expect) -> Error (ty_have, ty_expect)) in let err_res_idx = Option.value_map err_opt_idx ~default:(Ok ty2) ~f:(fun (ty_have, ty_expect) -> Error (ty_have, ty_expect)) in (env, (ty, err_res_arr, err_res_idx)) | Tnewtype (cid, _, _bound) when String.equal cid SN.Classes.cSupportDyn -> (* We must be under_dynamic_assumptions because apply_rules_with_index_value_ty_mismatches otherwise descends into the newtype *) got_dynamic () | Tnewtype (ts, [ty], bound) -> begin match deref bound with | ( r, Tshape { s_origin = _; s_unknown_value = shape_kind; s_fields = fields } ) when String.equal ts SN.FB.cTypeStructure -> let (env, fields) = Typing_structure.transform_shapemap env array_pos ty fields in let ty = mk ( r, Tshape { s_origin = Missing_origin; s_unknown_value = shape_kind; s_fields = fields; } ) in let (env, (ty, err_opt_arr, err_opt_idx)) = array_get ~array_pos ~expr_pos ~lhs_of_null_coalesce is_lvalue env ty e2 ty2 in let err_res_idx = Option.value_map err_opt_idx ~default:(Ok ty2) ~f:(fun (ty_have, ty_expect) -> Error (ty_have, ty_expect)) in let err_res_arr = Option.value_map err_opt_arr ~default:dflt_arr_res ~f:(fun (ty_have, ty_expect) -> Error (ty_have, ty_expect)) in (env, (ty, err_res_arr, err_res_idx)) | _ -> error_array env expr_pos ty1; let (env, res_ty) = err_witness env expr_pos in let ty_nothing = MakeType.nothing Reason.none in let (env, ty_key) = MakeType.arraykey Reason.none |> Typing_intersection.intersect ~r:Reason.Rnone env ty2 in let ty_keyedcontainer = MakeType.(keyed_container Reason.none ty_key ty_nothing) in (env, (res_ty, Error (ty1, ty_keyedcontainer), Ok ty2)) end | Tunapplied_alias _ -> Typing_defs.error_Tunapplied_alias_in_illegal_context () | Tnonnull | Tprim _ | Tfun _ | Tclass _ | Tgeneric _ | Tnewtype _ | Tdependent _ | Tunion _ | Tintersection _ | Taccess _ | Tneg _ -> error_array env expr_pos ty1; let (env, res_ty) = err_witness env expr_pos in let ty_nothing = MakeType.nothing Reason.none in let (env, ty_key) = MakeType.arraykey Reason.none |> Typing_intersection.intersect ~r:Reason.Rnone env ty2 in let ty_keyedcontainer = MakeType.(keyed_container Reason.none ty_key ty_nothing) in (env, (res_ty, Error (ty1, ty_keyedcontainer), Ok ty2)) (* Type-check array access as though it is the method * array_get<Tk,Tv>(KeyedContainer<Tk,Tv> $array, Tk $key): Tv * (We can already force Tk to be the type of the key argument because * Tk does not appear in the result of the call) *) | Tvar _ -> let (env, value) = Env.fresh_type env expr_pos in let (env, ty_key) = MakeType.arraykey Reason.none |> Typing_intersection.intersect ~r:Reason.Rnone env ty2 in let keyed_container = MakeType.keyed_container r ty_key value in let (env, arr_ty_err_opt) = SubType.sub_type env ty1 keyed_container @@ Some (Typing_error.Reasons_callback.index_type_mismatch_at expr_pos) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) arr_ty_err_opt; let arr_res = mk_ty_mismatch_res ty1 keyed_container arr_ty_err_opt in (env, (value, arr_res, Ok ty2))) (* Given a type `ty` known to be a lower bound on the type of the array operand * to an array append operation, compute the largest upper bound on that type * that validates the get operation. For example, if `vec<string>` is a lower * bound, then `vec<#1>` is a suitable upper bound.` *) let widen_for_assign_array_append ~expr_pos env ty = match deref ty with (* dynamic is valid for array append *) | (_, Tdynamic) -> ((env, None), Some ty) | (r, Tclass (((_, cn) as id), _, tyl)) when String.equal cn SN.Collections.cVec || String.equal cn SN.Collections.cKeyset || String.equal cn SN.Collections.cVector || String.equal cn SN.Collections.cMap -> let (env, params) = List.map_env env tyl ~f:(fun env _ty -> Env.fresh_type_invariant env expr_pos) in let ty = mk (r, Tclass (id, nonexact, params)) in ((env, None), Some ty) | _ -> ((env, None), None) let assign_array_append ~array_pos ~expr_pos ur env ty1 ty2 = let ((env, ty_err1), ty1) = Typing_solver.expand_type_and_narrow ~description_of_expected:"an array or collection" env (widen_for_assign_array_append ~expr_pos) array_pos ty1 in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err1; GenericRules.apply_rules_with_index_value_ty_mismatches ~preserve_supportdyn:false env ty1 (fun env ~supportdyn ty1 -> (* In dynamic mode strip off nullable because we can always upcast to dynamic *) let ty1 = match get_node ty1 with | Toption ty when Tast.is_under_dynamic_assumptions env.Typing_env_types.checked -> ty | _ -> ty1 in let got_dynamic () = let tv = MakeType.dynamic (get_reason ty1) in let (env, val_ty_err_opt) = TUtils.supports_dynamic env ty2 @@ Some (Typing_error.Reasons_callback.unify_error_at expr_pos) in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) val_ty_err_opt; let val_err_res = mk_ty_mismatch_res ty2 tv val_ty_err_opt in (env, (tv, Ok tv, val_err_res)) in match deref ty1 with | (_, Tany _) -> (env, (ty1, Ok ty1, Ok ty2)) | (r, Tclass ((_, n), _, [tv])) when String.equal n SN.Collections.cVector -> let (env, tv) = maybe_make_supportdyn r env ~supportdyn tv in let (env, tv) = maybe_pessimise_type env tv in let (env, val_ty_err_opt) = Typing_ops.sub_type expr_pos ur env ty2 tv Typing_error.Callback.unify_error in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) val_ty_err_opt; let val_err_res = mk_ty_mismatch_res ty2 tv val_ty_err_opt in (env, (ty1, Ok ty1, val_err_res)) (* Handle the case where Vector or Set was used as a typehint without type parameters *) | (_, Tclass ((_, n), _, [])) when String.equal n SN.Collections.cVector -> (env, (ty1, Ok ty1, Ok ty2)) | (r, Tclass (((_, n) as id), e, [])) when String.equal n SN.Collections.cKeyset || String.equal n SN.Collections.cSet -> let (env, val_err_res) = if String.equal n SN.Collections.cKeyset then check_keyset_value env expr_pos ty1 ty2 else check_set_value env expr_pos ty1 ty2 in let ty = mk (r, Tclass (id, e, [ty2])) in (env, (ty, Ok ty, val_err_res)) | (r, Tclass (((_, n) as id), e, [tv])) when String.equal n SN.Collections.cVec -> let (env, tv) = maybe_make_supportdyn r env ~supportdyn tv in let (env, tv') = Typing_union.union env tv ty2 in let ty = mk (r, Tclass (id, e, [tv'])) in (env, (ty, Ok ty, Ok ty2)) | (r, Tclass (((_, n) as id), e, [tv])) when String.equal n SN.Collections.cKeyset -> let (env, err_res) = check_keyset_value env expr_pos ty1 ty2 in let (env, tk') = let r = Reason.Rkey_value_collection_key expr_pos in let ak_t = MakeType.arraykey r in let (env, ty2) = Typing_intersection.intersect env ~r ak_t ty2 in Typing_union.union env tv ty2 in let ty = mk (r, Tclass (id, e, [tk'])) in (env, (ty, Ok ty, err_res)) | (_, Tclass ((_, n), _, [tv])) when String.equal n SN.Collections.cSet -> let (env, err_res) = match check_set_value env expr_pos ty1 ty2 with | (_, Error _) as err_res -> err_res | (env, _) -> let (env, tv') = let ak_t = MakeType.arraykey (Reason.Ridx_vector expr_pos) in let (env, tv) = maybe_pessimise_type env tv in if TUtils.is_sub_type_for_union env ak_t tv then (* hhvm will enforce that the key is an arraykey, so if $x : Set<arraykey>, then it should be allowed to set $x[] = e where $d : dynamic. *) (env, MakeType.enforced tv) else (* It is unsound to allow $x[] = e if $x : Set<string> since the dynamic $d might be an int and hhvm wouldn't complain.*) (env, MakeType.unenforced tv) in let (env, ty_err_opt) = Typing_coercion.coerce_type ~coerce_for_op:true expr_pos ur env ty2 tv' Typing_error.Callback.unify_error in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let ty_mismatch = mk_ty_mismatch_res ty2 tv ty_err_opt in (env, ty_mismatch) in (env, (ty1, Ok ty1, err_res)) | (_, Tdynamic) when Typing_env_types.( TypecheckerOptions.enable_sound_dynamic env.genv.tcopt) -> got_dynamic () | (_, Tdynamic) -> (env, (ty1, Ok ty1, Ok ty2)) | (_, Tunapplied_alias _) -> Typing_defs.error_Tunapplied_alias_in_illegal_context () | (_, Tprim Tnull) when Tast.is_under_dynamic_assumptions env.Typing_env_types.checked -> got_dynamic () | (_, Tnewtype (cid, _, _bound)) when String.equal cid SN.Classes.cSupportDyn -> (* We must be under_dynamic_assumptions because apply_rules_with_index_value_ty_mismatches otherwise descends into the newtype. In this case we just accept the assignment because it's as though we applied an implicit upcast to dynamic *) got_dynamic () | ( r, ( Tnonnull | Tvec_or_dict _ | Toption _ | Tprim _ | Tvar _ | Tfun _ | Tclass _ | Ttuple _ | Tshape _ | Tunion _ | Tintersection _ | Tgeneric _ | Tnewtype _ | Tdependent _ | Taccess _ | Tneg _ ) ) -> let (env, ty) = error_assign_array_append env expr_pos ty1 in let (env, ty) = maybe_make_supportdyn r env ~supportdyn ty in let ty_nothing = MakeType.nothing Reason.none in (env, (ty, Error (ty, ty_nothing), Error (ty2, ty_nothing)))) let widen_for_assign_array_get ~expr_pos index_expr 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_assign_array_get", [Log_type ("ty", ty)])])); match deref ty with (* dynamic is valid for assign array get *) | (_, Tdynamic) -> ((env, None), Some ty) | (r, Ttuple tyl) -> begin (* requires integer literal *) match index_expr with (* Should freshen type variables *) | (_, _, Aast.Int _) -> let (env, params) = List.map_env env tyl ~f:(fun env _ty -> Env.fresh_type_invariant env expr_pos) in ((env, None), Some (mk (r, Ttuple params))) | _ -> ((env, None), None) end | _ -> ((env, None), None) (* Used for typing an assignment e1[key] = e2 * where e1 has type ty1, key has type tkey and e2 has type ty2. * Return the new array type *) let assign_array_get ~array_pos ~expr_pos ur env ty1 (key : Nast.expr) tkey ty2 = Typing_log.( log_with_level env "typing" ~level:1 (fun () -> log_types (Pos_or_decl.of_raw_pos expr_pos) env [ Log_head ( "assign_array_get", [Log_type ("ty1", ty1); Log_type ("ty2", ty2)] ); ])); let ((env, ty_err1), ety1) = Typing_solver.expand_type_and_narrow ~description_of_expected:"an array or collection" env (widen_for_assign_array_get ~expr_pos key) array_pos ty1 in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err1; GenericRules.apply_rules_with_array_index_value_ty_mismatches ~preserve_supportdyn:false env ety1 (fun env ~supportdyn ety1 -> let (r, ety1_) = deref ety1 in let arity_error (_, name) = Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Array_get_arity { pos = expr_pos; name; decl_pos = Reason.to_pos r }) in let type_index env p ty_have ty_expect reason = let (env, ty_err_opt) = Typing_coercion.coerce_type ~coerce_for_op:true p reason env ty_have ty_expect Typing_error.Callback.index_type_mismatch in let ty_mismatch = mk_ty_mismatch_res ty_have ty_expect.et_type ty_err_opt in ((env, ty_err_opt), ty_mismatch) in let got_dynamic () = let tv = MakeType.dynamic r in let (env, ty_err1) = TUtils.supports_dynamic env tkey @@ Some (Typing_error.Reasons_callback.unify_error_at expr_pos) in let idx_err_res = mk_ty_mismatch_res tkey tv ty_err1 in let (env, ty_err2) = TUtils.supports_dynamic env ty2 @@ Some (Typing_error.Reasons_callback.unify_error_at expr_pos) in let val_err_res = mk_ty_mismatch_res tkey tv ty_err2 in Option.( iter ~f:(Typing_error_utils.add_typing_error ~env) @@ merge ty_err1 ty_err2 ~f:Typing_error.both); (env, (tv, Ok tv, idx_err_res, val_err_res)) in match ety1_ with | Tclass (((_, cn) as id), _, argl) when String.equal cn SN.Collections.cVector -> let (env, tv) = match argl with | [tv] -> maybe_pessimise_type env tv | _ -> arity_error id; err_witness env expr_pos in let (env, tv) = maybe_make_supportdyn r env ~supportdyn tv in let (_, p, _) = key in let tk = MakeType.enforced (MakeType.int (Reason.Ridx_vector p)) in let ((env, ty_err1), idx_err) = type_index env expr_pos tkey tk (Reason.index_class cn) in let (env, ty_err2) = Typing_ops.sub_type expr_pos ur env ty2 tv Typing_error.Callback.unify_error in let err_res = mk_ty_mismatch_res ty2 tv ty_err2 in Option.( iter ~f:(Typing_error_utils.add_typing_error ~env) @@ merge ty_err1 ty_err2 ~f:Typing_error.both); (env, (ety1, Ok ety1, idx_err, err_res)) | Tclass (((_, cn) as id), e, argl) when String.equal cn SN.Collections.cVec -> let (env, tv) = match argl with | [tv] -> (env, tv) | _ -> arity_error id; err_witness env expr_pos in let (_, p, _) = key in let tk = MakeType.enforced (MakeType.int (Reason.Ridx_vector p)) in let ((env, ty_err1), idx_err) = type_index env expr_pos tkey tk (Reason.index_class cn) in let (env, tv) = maybe_make_supportdyn r env ~supportdyn tv in let (env, tv') = Typing_union.union env tv ty2 in let ty = mk (r, Tclass (id, e, [tv'])) in Option.iter ty_err1 ~f:(Typing_error_utils.add_typing_error ~env); (env, (ty, Ok ty, idx_err, Ok ty2)) | Tclass (((_, cn) as id), _, argl) when cn = SN.Collections.cMap -> let (env, idx_err1) = check_arraykey_index_write env expr_pos ety1 tkey in let (tk, (env, tv)) = match argl with | [tk; tv] -> (tk, maybe_pessimise_type env tv) | _ -> arity_error id; let (env, ty) = err_witness env expr_pos in (ty, (env, ty)) in let (env, tv) = maybe_make_supportdyn r env ~supportdyn tv in let (env, tk) = let (_, p, _) = key in let ak_t = MakeType.arraykey (Reason.Ridx_vector p) in let (env, tk) = maybe_pessimise_type env tk in if TUtils.is_sub_type_for_union env ak_t tk then (* hhvm will enforce that the key is an arraykey, so if $x : Map<arraykey, t>, then it should be allowed to set $x[$d] = e where $d : dynamic. NB above, we don't need to check that tk <: arraykey, because the Map ensures that. *) (env, MakeType.enforced tk) else (* It is unsound to allow $x[$d] = e if $x : Map<string, t> since the dynamic $d might be an int and hhvm wouldn't complain.*) (env, MakeType.unenforced tk) in let ((env, ty_err1), idx_err2) = type_index env expr_pos tkey tk (Reason.index_class cn) in let idx_err = match (idx_err1, idx_err2) with | (Error _, _) -> idx_err1 | _ -> idx_err2 in let (env, ty_err2) = Typing_ops.sub_type expr_pos ur env ty2 tv Typing_error.Callback.unify_error in let err_res = mk_ty_mismatch_res ty2 tv ty_err2 in Option.( iter ~f:(Typing_error_utils.add_typing_error ~env) @@ merge ty_err1 ty_err2 ~f:Typing_error.both); (env, (ety1, Ok ety1, idx_err, err_res)) | Tclass (((_, cn) as id), e, argl) when String.equal cn SN.Collections.cDict -> let (env, idx_err) = check_arraykey_index_write env expr_pos ety1 tkey in let (tk, tv) = match argl with | [tk; tv] -> (tk, tv) | _ -> arity_error id; let (_env, ty) = err_witness env expr_pos in (ty, ty) in let (env, tv) = maybe_make_supportdyn r env ~supportdyn tv in let (env, tk') = let (_, p, _) = key in let ak_t = MakeType.arraykey (Reason.Ridx_dict p) in match idx_err with | Ok _ -> let (env, tkey_new) = Typing_intersection.intersect env ~r:(Reason.Ridx_dict p) tkey ak_t in Typing_union.union env tk tkey_new | _ -> Typing_union.union env tk tkey in let (env, tv') = Typing_union.union env tv ty2 in let ty = mk (r, Tclass (id, e, [tk'; tv'])) in (env, (ty, Ok ty, idx_err, Ok ty2)) | Tclass ((_, cn), _, _) when String.equal cn SN.Collections.cKeyset -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Keyset_set { pos = expr_pos; decl_pos = Reason.to_pos r }); ( env, (ety1, Error (ety1, MakeType.nothing Reason.none), Ok tkey, Ok ty2) ) | Tclass ((_, cn), _, tys) when String.equal cn SN.Collections.cConstMap || String.equal cn SN.Collections.cImmMap -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Const_mutation { pos = expr_pos; decl_pos = Reason.to_pos r; ty_name = lazy (Typing_print.error env ety1); }); let ty_expect = MakeType.class_type Reason.none SN.Collections.cMap tys in (env, (ety1, Error (ety1, ty_expect), Ok tkey, Ok ty2)) | Tclass ((_, cn), _, tys) when String.equal cn SN.Collections.cConstVector || String.equal cn SN.Collections.cImmVector -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Const_mutation { pos = expr_pos; decl_pos = Reason.to_pos r; ty_name = lazy (Typing_print.error env ety1); }); let ty_expect = MakeType.class_type Reason.none SN.Collections.cVector tys in let (env, ety1) = maybe_make_supportdyn r env ~supportdyn ety1 in (env, (ety1, Error (ety1, ty_expect), Ok tkey, Ok ty2)) | Tclass ((_, cn), _, _) when String.equal cn SN.Collections.cAnyArray && Tast.is_under_dynamic_assumptions env.Typing_env_types.checked -> got_dynamic () | Tclass ((_, cn), _, _) when String.equal cn SN.Collections.cKeyedContainer || String.equal cn SN.Collections.cAnyArray || String.equal cn SN.Collections.cPair -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Const_mutation { pos = expr_pos; decl_pos = Reason.to_pos r; ty_name = lazy (Typing_print.error env ety1); }); let ty_expect = MakeType.nothing Reason.none in let (env, ety1) = maybe_make_supportdyn r env ~supportdyn ety1 in (env, (ety1, Error (ety1, ty_expect), Ok tkey, Ok ty2)) | Tvec_or_dict (tk, tv) -> let (env, idx_err) = check_arraykey_index_write env expr_pos ety1 tkey in let (env, tk') = Typing_union.union env tk tkey in let (env, tv) = maybe_make_supportdyn r env ~supportdyn tv in let (env, tv') = Typing_union.union env tv ty2 in let ty = mk (r, Tvec_or_dict (tk', tv')) in (env, (ty, Ok ty, idx_err, Ok ty2)) | Tvar _ when TUtils.is_tyvar_error env ety1 -> let (env, ty) = Env.fresh_type_error env expr_pos in let (env, ty) = maybe_make_supportdyn r env ~supportdyn ty in (env, (ty, Ok ty, Ok tkey, Ok ty2)) | Tdynamic when Typing_env_types.( TypecheckerOptions.enable_sound_dynamic env.genv.tcopt) -> got_dynamic () | Tdynamic -> (env, (ety1, Ok ety1, Ok tkey, Ok ty2)) | Tany _ -> (env, (ety1, Ok ety1, Ok tkey, Ok ty2)) | Tprim Tnull when Tast.is_under_dynamic_assumptions env.Typing_env_types.checked -> got_dynamic () | Tprim Tstring -> let (_, p, _) = key in let tk = MakeType.enforced (MakeType.int (Reason.Ridx (p, r))) in let tv = MakeType.string (Reason.Rwitness expr_pos) in let ((env, ty_err1), idx_err) = type_index env expr_pos tkey tk Reason.index_array in let (env, tv') = maybe_pessimise_type env tv in let (env, ty_err2) = Typing_ops.sub_type expr_pos ur env ty2 tv' Typing_error.Callback.unify_error in let err_res = mk_ty_mismatch_res ty2 tv ty_err2 in Option.( iter ~f:(Typing_error_utils.add_typing_error ~env) @@ merge ty_err1 ty_err2 ~f:Typing_error.both); (env, (ety1, Ok ety1, idx_err, err_res)) | Ttuple tyl -> let fail key_err reason = let (_, p, _) = key in Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Generic_unify { pos = p; msg = Reason.string_of_ureason reason }); (env, (ety1, Ok ety1, key_err, Ok ty2)) in begin match key with | (_, _, Int n) -> let idx = int_of_string_opt n in (match Option.map ~f:(List.split_n tyl) idx with | Some (tyl', _ :: tyl'') -> let ty = MakeType.tuple r (tyl' @ (ty2 :: tyl'')) in let (env, ty) = maybe_make_supportdyn r env ~supportdyn ty in (env, (ty, Ok ety1, Ok tkey, Ok ty2)) | _ -> fail (Ok tkey) Reason.index_tuple) | _ -> fail (Error (tkey, MakeType.int Reason.none)) Reason.URtuple_access end | Tshape { s_origin = _; s_unknown_value = shape_kind; s_fields = fdm } -> begin let (fld_opt, ty_err_opt) = TUtils.shape_field_name_with_ty_err env key in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; match fld_opt with | None -> let (env, ety1) = maybe_make_supportdyn r env ~supportdyn ety1 in (env, (ety1, Ok ety1, Ok tkey, Ok ty2)) | Some field -> let field = TShapeField.of_ast Pos_or_decl.of_raw_pos field in let (env, fdm) = if supportdyn then let f env _name { sft_optional; sft_ty } = let (env, sft_ty) = TUtils.make_supportdyn r env sft_ty in (env, { sft_optional; sft_ty }) in TShapeMap.map_env f env fdm else (env, fdm) in let fdm' = TShapeMap.add field { sft_optional = false; sft_ty = ty2 } fdm in let ty = mk ( r, Tshape { s_origin = Missing_origin; s_unknown_value = shape_kind; s_fields = fdm'; } ) in (env, (ty, Ok ty, Ok tkey, Ok ty2)) end | Tnewtype (cid, _, _bound) when String.equal cid SN.Classes.cSupportDyn -> (* We must be under_dynamic_assumptions because apply_rules_with_index_value_ty_mismatches otherwise descends into the newtype. In this case we just accept the assignment because it's as though we applied an implicit upcast to dynamic *) (env, (ety1, Ok ety1, Ok tkey, Ok ty2)) | Tunapplied_alias _ -> Typing_defs.error_Tunapplied_alias_in_illegal_context () | Toption _ | Tnonnull | Tprim _ | Tunion _ | Tintersection _ | Tgeneric _ | Tnewtype _ | Tdependent _ | Tvar _ | Tfun _ | Tclass _ | Taccess _ | Tneg _ -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Array_access { ctxt = `write; pos = expr_pos; decl_pos = Reason.to_pos r; ty_name = lazy (Typing_print.error env ety1); }); let ty_nothing = MakeType.nothing Reason.none in let (env, ety1) = maybe_make_supportdyn r env ~supportdyn ety1 in (env, (ety1, Error (ety1, ty_nothing), Ok tkey, Error (ty2, ty_nothing))))
OCaml Interface
hhvm/hphp/hack/src/typing/typing_array_access.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 Aast open Typing_defs val maybe_pessimise_type : Typing_env_types.env -> Typing_defs.locl_ty -> Typing_env_types.env * Typing_defs.locl_ty val pessimise_type : Typing_env_types.env -> Typing_defs.locl_ty -> Typing_env_types.env * Typing_defs.locl_ty val pessimised_tup_assign : pos -> Typing_env_types.env -> Typing_defs.locl_ty -> Typing_env_types.env * Typing_defs.locl_ty (* Typing of array-get like expressions; [ty1] is the type of the expression into which we are indexing (the 'collection'), [e2] is the index expression and [ty2] is the type of that expression. We return: 1) the (modified) typing environment, 2) the type of the resulting expression (i.e. the type of the element we are 'getting') 3) the actual and expected type of the indexed expression, indicating a type mismatch (if any) 4) the actual and expected type of the indexing expression, indicating a type mismatch (if any) and an optional type mismatch giving the actual vs expected type of the The function has an error side-effect *) val array_get : array_pos:pos -> expr_pos:pos -> ?lhs_of_null_coalesce:is_variadic -> is_variadic -> Typing_env_types.env -> locl_ty -> ('a, 'b) Aast.expr -> locl_ty -> Typing_env_types.env * (locl_ty * (locl_ty * locl_ty) option * (locl_ty * locl_ty) option) (* Check an array append expression returning the modified typing environment, the resulting type of the lhs expression, an optional subtyping errors for the lhs expression and an optional subtyping error for the expression to be appended *) val assign_array_append : array_pos:pos -> expr_pos:pos -> Reason.ureason -> Typing_env_types.env -> locl_ty -> locl_ty -> Typing_env_types.env * (locl_ty * (locl_ty * locl_ty) option * (locl_ty * locl_ty) option) (* Check an array append expression returning the modified typing environment, the resulting type of the lhs expression, an optional subtyping errors for the indexed expression, an optional subtyping error for the indexing expression , and an optional subtyping error for the rhs expression *) val assign_array_get : array_pos:pos -> expr_pos:pos -> Reason.ureason -> Typing_env_types.env -> locl_ty -> Nast.expr -> locl_ty -> locl_ty -> Typing_env_types.env * (locl_ty * (locl_ty * locl_ty) option * (locl_ty * locl_ty) option * (locl_ty * locl_ty) option)
OCaml
hhvm/hphp/hack/src/typing/typing_ast_print.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. * *) let print_tast_internal apply_to_ex_ty print_ex ctx tast = let dummy_filename = Relative_path.default in let env = Typing_env_types.empty ctx dummy_filename ~droot:None in let print_ex ex = apply_to_ex_ty (Typing_print.full_strip_ns env) ex |> print_ex in let pp_en fmt _ = Format.pp_print_string fmt "()" in let pp_ex fmt ex = Format.pp_print_string fmt (print_ex ex) in let formatter = Format.formatter_of_out_channel Stdlib.stdout in Format.pp_set_margin formatter 200; Aast.pp_program pp_ex pp_en formatter tast let print_tast ctx tast = let apply_to_ex_ty f ty = f ty in let print_pos_and_ty ty = Format.asprintf "(%s)" ty in print_tast_internal apply_to_ex_ty print_pos_and_ty ctx tast let print_tast_without_position ctx tast = let remove_pos = object inherit [_] Aast.map method! on_pos _ _pos = Pos.none method on_'ex _ ty = ty method on_'en _ en = en end in let tast = remove_pos#on_program () tast in let apply_to_ex_ty f ty = f ty in let print_pos_and_ty ty = Format.asprintf "%s" ty in print_tast_internal apply_to_ex_ty print_pos_and_ty ctx tast
OCaml Interface
hhvm/hphp/hack/src/typing/typing_ast_print.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 print_tast : Provider_context.t -> Tast.program -> unit val print_tast_without_position : Provider_context.t -> Tast.program -> unit
OCaml
hhvm/hphp/hack/src/typing/typing_async.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Typing_defs module Reason = Typing_reason module Type = Typing_ops module Env = Typing_env module TUtils = Typing_utils module MakeType = Typing_make_type (* If an expression e is of type `opt_ty_maybe`, then this function returns the type of `await e`. There is the special case that e : ?Awaitable<T> |- await e : ?T *) let overload_extract_from_awaitable_with_ty_err env ~p opt_ty_maybe = let r = Reason.Rwitness p in let rec extract_inner env opt_ty_maybe = let ((env, e1), e_opt_ty) = Typing_solver.expand_type_and_solve ~description_of_expected:"an Awaitable" env p opt_ty_maybe in match get_node e_opt_ty with | Tunion tyl -> let ((env, ty_errs), tyl) = List.fold_map ~init:(env, Option.to_list e1) ~f:(fun (env, ty_errs) ty -> match extract_inner env ty with | ((env, Some ty_err), ty) -> ((env, ty_err :: ty_errs), ty) | ((env, _), ty) -> ((env, ty_errs), ty)) tyl in let (env, ty) = TUtils.union_list env r tyl in ((env, Typing_error.multiple_opt ty_errs), ty) | Toption ty -> (* We want to try to avoid easy double nullables here, so we handle Toption * with some special logic. *) let ((env, e2), ty) = extract_inner env ty in let (env, ty) = TUtils.union env (MakeType.null r) ty in ((env, Option.merge e1 e2 ~f:Typing_error.both), ty) | Tintersection tyl -> let ((env, e2), rtyl) = TUtils.run_on_intersection_with_ty_err env tyl ~f:extract_inner in ( (env, Option.merge e1 e2 ~f:Typing_error.both), MakeType.intersection r rtyl ) | Tprim Aast.Tnull -> ((env, e1), e_opt_ty) | Tdynamic -> (* Awaiting a dynamic results in a new dynamic *) ((env, e1), MakeType.dynamic r) | Tunapplied_alias _ -> Typing_defs.error_Tunapplied_alias_in_illegal_context () | Tany _ | Tvec_or_dict _ | Tnonnull | Tprim _ | Tvar _ | Tfun _ | Tgeneric _ | Tnewtype _ | Tdependent _ | Tclass _ | Ttuple _ | Tshape _ | Taccess _ | Tneg _ -> let (env, type_var) = if TUtils.is_tyvar_error env e_opt_ty then Env.fresh_type_error env p else Env.fresh_type env p in let expected_type = MakeType.awaitable r type_var in let return_type = match get_node e_opt_ty with | Tany _ -> mk (r, Typing_defs.make_tany ()) | Tdynamic -> MakeType.dynamic r | Tunapplied_alias _ -> Typing_defs.error_Tunapplied_alias_in_illegal_context () | Tnonnull | Tvec_or_dict _ | Tprim _ | Tvar _ | Tfun _ | Tgeneric _ | Tnewtype _ | Tdependent _ | Tclass _ | Ttuple _ | Tintersection _ | Toption _ | Tunion _ | Tshape _ | Taccess _ | Tneg _ -> type_var in let (env, e2) = Type.sub_type p Reason.URawait env opt_ty_maybe expected_type Typing_error.Callback.unify_error in ((env, Option.merge e1 e2 ~f:Typing_error.both), return_type) in let env = Env.open_tyvars env p in let ((env, ty_err_opt), ty) = extract_inner env opt_ty_maybe in let (env, err) = Typing_solver.close_tyvars_and_solve env in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; ((env, err), ty) let overload_extract_from_awaitable env ~p opt_ty_maybe = let ((env, ty_err_opt), res) = overload_extract_from_awaitable_with_ty_err env ~p opt_ty_maybe in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (env, res) let overload_extract_from_awaitable_list_with_ty_err env p tyl = let (env, ty_errs, rtyl) = List.fold_right ~f:(fun ty (env, ty_errs, rtyl) -> let ((env, ty_err_opt), rty) = overload_extract_from_awaitable_with_ty_err env ~p ty in let ty_errs = Option.value_map ~default:ty_errs ~f:(fun e -> e :: ty_errs) ty_err_opt in (env, ty_errs, rty :: rtyl)) tyl ~init:(env, [], []) in ((env, Typing_error.multiple_opt ty_errs), rtyl) let overload_extract_from_awaitable_list env p tyl = let ((env, ty_err_opt), res) = overload_extract_from_awaitable_list_with_ty_err env p tyl in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (env, res) let overload_extract_from_awaitable_shape_with_ty_err env p fdm = TShapeMap.map_env_ty_err_opt (fun env _key (tk, tv) -> let (env, rtv) = overload_extract_from_awaitable_with_ty_err env ~p tv in (env, (tk, rtv))) ~combine_ty_errs:Typing_error.multiple_opt env fdm let overload_extract_from_awaitable_shape env p fdm = let ((env, ty_err_opt), res) = overload_extract_from_awaitable_shape_with_ty_err env p fdm in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; (env, res)
OCaml Interface
hhvm/hphp/hack/src/typing/typing_async.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 overload_extract_from_awaitable : Typing_env_types.env -> p:Pos.t -> Typing_defs.locl_ty -> Typing_env_types.env * Typing_defs.locl_ty val overload_extract_from_awaitable_list : Typing_env_types.env -> Pos.t -> Typing_defs.locl_ty list -> Typing_env_types.env * Typing_defs.locl_ty list val overload_extract_from_awaitable_shape : Typing_env_types.env -> Pos.t -> ('a * Typing_defs.locl_ty) Typing_defs.ShapeFieldMap.t -> Typing_env_types.env * ('a * Typing_defs.locl_ty) Typing_defs.ShapeFieldMap.t
OCaml
hhvm/hphp/hack/src/typing/typing_attributes.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_reason open Typing_env_types module SN = Naming_special_names module MakeType = Typing_make_type module Cls = Decl_provider.Class type attribute_interface_name = string type new_object_checker = Pos.t -> env -> Typing_defs.pos_string -> Nast.expr list -> env let check_implements (check_new_object : new_object_checker) (attr_interface : attribute_interface_name) ({ Aast.ua_name = (attr_pos, attr_name); ua_params = params } : Nast.user_attribute) (env : env) : env = let expr_kind = match SMap.find_opt attr_interface SN.AttributeKinds.plain_english_map with | Some ek -> ek | None -> "this expression" (* this case should never execute *) in let is_systemlib = TypecheckerOptions.is_systemlib (Typing_env.get_tcopt env) in if String.is_prefix attr_name ~prefix:"__" then (* Check against builtins *) let check_attr map = match SMap.find_opt attr_name map with | Some attr_info -> let check_locations = TypecheckerOptions.check_attribute_locations (Typing_env.get_tcopt env) in if check_locations && not @@ List.mem attr_info.SN.UserAttributes.contexts attr_interface ~equal:String.equal then Errors.add_error Nast_check_error.( to_user_error @@ Wrong_expression_kind_builtin_attribute { expr_kind; pos = attr_pos; attr_name }); true | None -> false in let () = if check_attr SN.UserAttributes.as_map || (is_systemlib && check_attr SN.UserAttributes.systemlib_map) then () else let all_valid_user_attributes = let bindings = SMap.bindings SN.UserAttributes.as_map in let filtered_bindings = List.filter ~f:(fun (_, attr_info) -> List.mem attr_info.SN.UserAttributes.contexts attr_interface ~equal:String.equal) bindings in List.map ~f:fst filtered_bindings in let closest_attr_name = Typing_env.most_similar attr_name all_valid_user_attributes (fun name -> name) in Errors.add_error Naming_error.( to_user_error @@ Unbound_attribute_name { pos = attr_pos; attr_name; closest_attr_name }) in env else match ( Typing_env.get_class env attr_name, Typing_env.get_class env attr_interface ) with | (Some attr_class, Some intf_class) -> (* Found matching class *) let attr_cid = (Cls.pos attr_class, Cls.name attr_class) in (* successful exit condition: attribute class is subtype of correct interface * and its args satisfy the attribute class constructor *) let attr_locl_ty : Typing_defs.locl_ty = MakeType.class_type (Rwitness_from_decl (Cls.pos attr_class)) (Cls.name attr_class) [] in let interface_locl_ty : Typing_defs.locl_ty = MakeType.class_type (Rwitness_from_decl (Cls.pos intf_class)) (Cls.name intf_class) [] in if not (Typing_subtype.is_sub_type env attr_locl_ty interface_locl_ty) then ( Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Wrong_expression_kind_attribute { expr_kind; pos = attr_pos; attr_name; attr_class_pos = Cls.pos attr_class; attr_class_name = Cls.name attr_class; intf_name = Cls.name intf_class; }); env ) else check_new_object attr_pos env attr_cid params | _ -> Errors.add_error Naming_error.( to_user_error @@ Unbound_attribute_name { pos = attr_pos; attr_name; closest_attr_name = None }); env let check_def env check_new_object (kind : attribute_interface_name) attributes = List.fold_right ~f:(check_implements check_new_object kind) attributes ~init:env (* TODO(coeffects) change to mixed after changing those constructors to pure *) let check_def env check_new_object (kind : attribute_interface_name) attributes = let defaults = MakeType.default_capability Pos_or_decl.none in let (env, _) = Typing_lenv.stash_and_do env (Typing_env.all_continuations env) (fun env -> let env = fst @@ Typing_coeffects.register_capabilities env defaults defaults in (check_def env check_new_object kind attributes, ())) in env
OCaml Interface
hhvm/hphp/hack/src/typing/typing_attributes.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 attribute_interface_name = string type new_object_checker = Pos.t -> Typing_env_types.env -> Typing_defs.pos_string -> Nast.expr list -> Typing_env_types.env (** Checks a list of user attributes: - checks that the attributes are on the proper kind of element, by checking subtyping of the attribute class with the provided attribute interface (e.g. FileAttribute, MethodAttribute, see Naming_special_names for a full list) - checks for unbound attribute names - runs the provided function, which checks creating an instance of the attribute class. *) val check_def : Typing_env_types.env -> new_object_checker -> attribute_interface_name -> Nast.user_attribute list -> Typing_env_types.env
OCaml
hhvm/hphp/hack/src/typing/typing_case_types.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. *These 'Unbound module' errors can be fixed... [read more](https://fburl.com/ocaml_hack_and_flow) *) open Hh_prelude open Typing_defs open Typing_env_types module Cls = Decl_provider.Class module Env = Typing_env module SN = Naming_special_names module DataType = struct (* Modelled after data types in HHVM. See hphp/runtime/base/datatype.h *) module Tag = struct type t = | DictData | VecData | KeysetData | StringData | ResourceData | BoolData | IntData | FloatData | NullData | ObjectData [@@deriving show, eq, ord] let name = function | DictData -> "dict" | VecData -> "vec" | KeysetData -> "keyset" | StringData -> "string" | ResourceData -> "resource" | BoolData -> "bool" | IntData -> "int" | FloatData -> "float" | NullData -> "null" | ObjectData -> "object" end module Map = struct include WrappedMap.Make (Tag) end module Set = struct include Caml.Set.Make (Tag) end type t = Set.t [@@deriving eq, ord] (** `mixed` should cover all possible data types. * Update if addition tags are added to [Tag.t] *) let mixed = Set.of_list [ Tag.DictData; Tag.VecData; Tag.KeysetData; Tag.StringData; Tag.ResourceData; Tag.BoolData; Tag.IntData; Tag.FloatData; Tag.NullData; Tag.ObjectData; ] let prim_to_datatypes (prim : Aast.tprim) : t = let open Aast in match prim with | Tint -> Set.singleton Tag.IntData | Tnull -> Set.singleton Tag.NullData | Tvoid -> Set.singleton Tag.NullData | Tbool -> Set.singleton Tag.BoolData | Tfloat -> Set.singleton Tag.FloatData | Tstring -> Set.singleton Tag.StringData | Tresource -> Set.singleton Tag.ResourceData | Tnum -> Set.of_list [Tag.IntData; Tag.FloatData] | Tarraykey -> Set.of_list [Tag.IntData; Tag.StringData] | Tnoreturn -> Set.empty module Class = struct (* Set of interfaces that contain non-object members *) let special_interfaces = SSet.of_list [ SN.Classes.cStringish; SN.Classes.cXHPChild; SN.Collections.cTraversable; SN.Collections.cKeyedTraversable; SN.Collections.cContainer; SN.Collections.cKeyedContainer; ] (** The [special_interfaces] contain additional data type tags beside [Tag.ObjectData]. These special interfaces are handled in [Typing_subtype]. To avoid duplicating the logic, we check if a certain tag should be included by doing a subtype test against the interface type. If the type corresponding to a tag is a subtype then it will be included in the list. *) let special_interface_to_datatypes env interface = let open Typing_make_type in let r = Typing_reason.none in let tag_to_type = [ (Tag.DictData, dict r (nothing r) (nothing r)); (Tag.VecData, vec r (nothing r)); (Tag.KeysetData, keyset r (nothing r)); (Tag.StringData, string r); (Tag.ResourceData, resource r); (Tag.BoolData, bool r); (Tag.IntData, int r); (Tag.FloatData, float r); (Tag.NullData, null r); ] in let (env, interface_ty) = match interface with | name when String.equal name SN.Collections.cTraversable || String.equal name SN.Collections.cContainer -> let (env, targ) = Env.fresh_type env Pos.none in let ty = Typing_make_type.class_type Reason.none name [targ] in (env, ty) | name when String.equal name SN.Collections.cKeyedTraversable || String.equal name SN.Collections.cKeyedContainer -> let (env, targ1) = Env.fresh_type env Pos.none in let (env, targ2) = Env.fresh_type env Pos.none in let ty = Typing_make_type.class_type Reason.none name [targ1; targ2] in (env, ty) | name when String.equal name SN.Classes.cStringish || String.equal name SN.Classes.cXHPChild -> (env, Typing_make_type.class_type Reason.none name []) | name -> failwithf "Unexpected special interface `%s` when determining data types" name () in List.fold tag_to_type ~init:Set.empty ~f: begin fun acc (tag, tag_ty) -> if Typing_utils.can_sub_type env tag_ty interface_ty then Set.add tag acc else acc end let special_interface_cache : t String.Table.t = String.Table.create () let to_datatypes (env : env) cls : t = match cls with | cls when String.equal cls SN.Collections.cDict -> Set.singleton Tag.DictData | cls when String.equal cls SN.Collections.cKeyset -> Set.singleton Tag.KeysetData | cls when String.equal cls SN.Collections.cVec -> Set.singleton Tag.VecData | cls when String.equal cls SN.Collections.cAnyArray -> Set.of_list [Tag.DictData; Tag.KeysetData; Tag.VecData] | cls when SSet.mem cls special_interfaces -> String.Table.find_or_add special_interface_cache cls ~default:(fun () -> let tags = special_interface_to_datatypes env cls in Set.add Tag.ObjectData tags) | _ -> Set.singleton Tag.ObjectData end let union (left : t) (right : t) : t = Set.union left right and intersect (left : t) (right : t) : t = Set.inter left right and minus (left : t) (right : t) : t = Set.diff left right let rec fromTy (env : env) (ty : locl_ty) : t = let (env, ty) = Env.expand_type env ty in match get_node ty with | Tprim prim -> prim_to_datatypes prim | Tnonnull -> minus mixed @@ Set.singleton Tag.NullData | Tdynamic -> mixed | Tany _ -> mixed | Toption ty -> fromTy env ty |> union @@ Set.singleton Tag.NullData (* For now say it has the same tags as `nonnull`. * We should be able to be more precise, but need to * validate what are all the data types that are valid callables *) | Tfun _ -> fromTy env (mk (get_reason ty, Tnonnull)) | Ttuple _ -> Set.singleton Tag.VecData | Tshape _ -> Set.singleton Tag.DictData | Tvar _ -> mixed | Tgeneric (name, tyl) -> let upper_bounds = Env.get_upper_bounds env name tyl in Typing_set.fold (fun ty acc -> intersect acc @@ fromTy env ty) upper_bounds mixed | Tunion tyl -> List.fold tyl ~init:Set.empty ~f:(fun acc ty -> union acc @@ fromTy env ty) | Tintersection tyl -> List.fold tyl ~init:mixed ~f:(fun acc ty -> intersect acc @@ fromTy env ty) | Tvec_or_dict _ -> Set.of_list [Tag.VecData; Tag.DictData] | Taccess (root_ty, id) -> let ety_env = empty_expand_env in let ((env, _), ty) = Typing_utils.expand_typeconst ety_env env root_ty id ~allow_abstract_tconst:true in fromTy env ty | Tdependent (_, ty) -> fromTy env ty | Tnewtype (name, tyl, ty) -> let (env, ty) = match Env.get_typedef env name with (* When determining the datatype associated with a type we should * expand the case type instead of looking at the upper bound. * If we do not expand, then we will over approximate the datatype. * Consider: * * case type Type1 = bool | int; * case type Type2 = Type1 | string; * * If we do not expand we will reject the definition of `Type2` * because we will believe the datatype for `Type1` contains `string`. * By expanding we can allow this definition. *) | Some { td_type = variants; td_vis = Aast.CaseType; td_tparams; _ } -> let ((env, _ty_err_opt), variants) = (* The this_ty does not need to be set because case types cannot * appear within classes thus cannot us the this type. * If we ever change that this could needs to be changed *) Typing_utils.localize ~ety_env: { empty_expand_env with substs = (if List.is_empty tyl then SMap.empty else Decl_subst.make_locl td_tparams tyl); } env variants in (env, variants) | _ -> (env, ty) in fromTy env ty | Tunapplied_alias _ -> Typing_defs.error_Tunapplied_alias_in_illegal_context () | Tclass ((_, cls), _, _) -> Class.to_datatypes env cls | Tneg n -> let right = match n with | Neg_prim prim -> prim_to_datatypes prim | Neg_class (_, cls) -> Class.to_datatypes env cls in minus mixed right end let mk_data_type_mapping env variants = let f map variant = let ((env, _), ty) = Decl_hint.hint env.decl_env variant |> Typing_utils.localize_no_subst env ~ignore_errors:true in let tags = DataType.fromTy env ty in DataType.Set.fold (fun tag acc -> DataType.Map.add ~combine:( @ ) tag [variant] acc) tags map in List.fold variants ~init:DataType.Map.empty ~f (** * Given the variants of a case type (encoded as a locl_ty) and another locl_ty [intersecting_ty] * produce a new locl_ty containing only the types in the variant that map to an intersecting * data type. For example: * Given * [variants] = int | vec<int> | Vector<int> * [intersecting_ty] = Container<string> * * This function will return the type `vec<int> | Vector<int>` because both `vec<int>` and * `Vector<int>` overlap with the tag associated with `Container<string>`. * * Note that this function only considers the data type associated to each type and not * the type itself. So even though `vec<int>` and `Container<string>` do not intersect at * the type level, they do intersect when considering only the runtime data types. *) let filter_variants_using_datatype env reason variants intersecting_ty = let tags = DataType.fromTy env intersecting_ty in let tyl = List.filter ~f:(fun ty -> let variant_tags = DataType.fromTy env ty in let refined_tags = DataType.intersect variant_tags tags in not @@ DataType.Set.is_empty refined_tags) variants in Typing_utils.union_list env reason tyl (** * Look up case type via [name]. If the case type exist returns the list of * variant types. If the case type doesn't exist, returns [None]. *) let get_variant_tys env name ty_args : Typing_env_types.env * locl_ty list option = match Env.get_typedef env name with | Some { td_type = variants; td_vis = Aast.CaseType; td_tparams; _ } -> let ((env, _ty_err_opt), variants) = Typing_utils.localize ~ety_env: { empty_expand_env with substs = (if List.is_empty ty_args then SMap.empty else Decl_subst.make_locl td_tparams ty_args); } env variants in let tyl = match get_node variants with | Tunion tyl -> tyl | _ -> [variants] in (env, Some tyl) | _ -> (env, None)
OCaml
hhvm/hphp/hack/src/typing/typing_check_job.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 (* #### The type checking service receives a list of files and their symbols as input and distributes the work to worker processes. In this file you will only find functions to process a single file at a time *) (*****************************************************************************) (* The job that will be run on the workers *) (*****************************************************************************) let handle_exn_as_error : type res. Pos.t -> (unit -> res option) -> res option = fun pos f -> try f () with | (WorkerCancel.Worker_should_exit | Deferred_decl.Defer) as exn -> (* Cancellation requests must be re-raised *) let e = Exception.wrap exn in Exception.reraise e | exn -> let e = Exception.wrap exn in Errors.exception_occurred pos e; None let type_fun (ctx : Provider_context.t) ~(full_ast : Nast.fun_def) : Tast.def Tast_with_dynamic.t option = let f = full_ast.Aast.fd_fun in handle_exn_as_error f.Aast.f_span (fun () -> let fun_ = Naming.fun_def ctx full_ast in Nast_check.def ctx (Aast.Fun fun_); let def_opt = Typing_toplevel.fun_def ctx fun_ |> Option.map ~f:(Tast_with_dynamic.map ~f:(fun f -> Aast.Fun f)) in (* Only do TAST check on normal TAST *) Option.iter def_opt ~f:(fun fs -> Tast_check.def ctx fs.Tast_with_dynamic.under_normal_assumptions); def_opt) let type_class (ctx : Provider_context.t) ~(full_ast : Nast.class_) : Tast.def Tast_with_dynamic.t option = handle_exn_as_error full_ast.Aast.c_span (fun () -> let class_ = Naming.class_ ctx full_ast in Nast_check.def ctx (Aast.Class class_); let def_opt = Typing_toplevel.class_def ctx class_ |> Option.map ~f:(Tast_with_dynamic.map ~f:(fun c -> Aast.Class c)) in (* Only do TAST check on normal TAST *) Option.iter def_opt ~f:(fun c -> Tast_check.def ctx c.Tast_with_dynamic.under_normal_assumptions); def_opt) let check_typedef (ctx : Provider_context.t) ~(full_ast : Nast.typedef) : Tast.def option = handle_exn_as_error Pos.none (fun () -> let typedef = Naming.typedef ctx full_ast in Nast_check.def ctx (Aast.Typedef typedef); let ret = Typing_toplevel.typedef_def ctx typedef in let def = Aast.Typedef ret in Tast_check.def ctx def; Some def) let check_const (ctx : Provider_context.t) ~(full_ast : Nast.gconst) : Tast.def option = handle_exn_as_error full_ast.Aast.cst_span (fun () -> let cst = Naming.global_const ctx full_ast in Nast_check.def ctx (Aast.Constant cst); let def = Aast.Constant (Typing_toplevel.gconst_def ctx cst) in Tast_check.def ctx def; Some def) let check_module (ctx : Provider_context.t) ~(full_ast : Nast.module_def) : Tast.def option = handle_exn_as_error (fst full_ast.Aast.md_name) (fun () -> let md = Naming.module_ ctx full_ast in Nast_check.def ctx (Aast.Module md); let def = Aast.Module (Typing_toplevel.module_def ctx md) in Tast_check.def ctx def; Some def) let calc_errors_and_tast ctx ?(drop_fixmed = true) fn ~full_ast : Errors.t * Tast.by_names = let { Nast.funs; classes; typedefs; constants; modules } = Nast.get_defs full_ast in let calc_tast (type def res) (typecheck : Provider_context.t -> full_ast:def -> res option) (defs : (FileInfo.id * def) list) : res SMap.t = (* List.map defs ~f:snd |> List.filter_map ~f:(fun full_ast -> f ctx ~full_ast) *) List.fold defs ~init:SMap.empty ~f:(fun acc (id, full_ast) -> typecheck ctx ~full_ast |> Option.fold ~init:acc ~f:(fun acc tast -> SMap.add (FileInfo.id_name id) tast acc)) in Errors.do_with_context ~drop_fixmed fn (fun () -> (* Some of our tests depend upon the order of [calc_tast] being exactly as follows, i.e. funs first, classes next, and so on. This is likely irrelevant to end user experience though, since user gets sorted errors. *) let fun_tasts = calc_tast type_fun funs in let class_tasts = calc_tast type_class classes in let typedef_tasts = calc_tast check_typedef typedefs in let gconst_tasts = calc_tast check_const constants in let module_tasts = calc_tast check_module modules in { Tast.fun_tasts; class_tasts; typedef_tasts; gconst_tasts; module_tasts }) let calc_errors_and_tast_for (type def res) (ctx : Provider_context.t) ?(drop_fixmed = true) (fn : Relative_path.t) (typecheck : Provider_context.t -> full_ast:def -> res option) ~(full_ast : def) (id : FileInfo.id) : Errors.t * res SMap.t = Errors.do_with_context ~drop_fixmed fn (fun () -> typecheck ctx ~full_ast |> Option.fold ~init:SMap.empty ~f:(fun acc tast -> SMap.add (FileInfo.id_name id) tast acc))
OCaml Interface
hhvm/hphp/hack/src/typing/typing_check_job.mli
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val type_fun : Provider_context.t -> full_ast:Nast.fun_def -> Tast.def Tast_with_dynamic.t option val type_class : Provider_context.t -> full_ast:Nast.class_ -> Tast.def Tast_with_dynamic.t option val check_typedef : Provider_context.t -> full_ast:Nast.typedef -> Tast.def option val check_const : Provider_context.t -> full_ast:Nast.gconst -> Tast.def option val check_module : Provider_context.t -> full_ast:Nast.module_def -> Tast.def option (** [type_file ctx fn ~full_ast] works as follows: 1. uses [fn] for the error context 2. iterates over the defs in [full_ast] 3. For each one runs them through [Naming], does [Nast_check], typechecks and obtains tast with [Typing_toplevel], does [Tast_check] It is unfortunate that this routine exists alongside [Typing_top_level.nast_to_tast] which does almost exactly the same thing, except it doesn't do [Naming], and there are minor differences in treatment of some toplevel nodes. *) val calc_errors_and_tast : Provider_context.t -> ?drop_fixmed:bool -> Relative_path.t -> full_ast:Nast.program -> Errors.t * Tast.by_names val calc_errors_and_tast_for : Provider_context.t -> ?drop_fixmed:bool -> Relative_path.t -> (Provider_context.t -> full_ast:'def -> 'res option) -> full_ast:'def -> FileInfo.id -> Errors.t * 'res SMap.t
OCaml
hhvm/hphp/hack/src/typing/typing_check_service.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module Hack_bucket = Bucket open Hh_prelude open Option.Monad_infix module Bucket = Hack_bucket open Typing_service_types (* #### The type checking service receives a list of files and their symbols as input and distributes the work to worker processes. A worker process's input is a subset of files. At the end of its work, it returns back to master the following progress report: - completed: a list of computations it completed - remaining: a list of computations which it didn't end up performing. For example, it may not have been able to get through the whole list of computations because it exceeded its worker memory cap - deferred: a list of computations which were discovered to be necessary to be performed before some of the computations in the input subset The deferred list needs further explanation, so read below. #### Here's how we actually plumb through the workitems and their individual results, via MultiWorker: * We have mutable state [ref files_to_process], a list of filenames still to be processed for the entire typecheck. * Datatype [progress] represents an input batch of work for a worker to do, and also an output indication of how it dispatched that batch * Datatype [typing_result] represents the accumulation of telemetry, errors, deps results from workers. Each individual worker is given an empty [typing_result] as input, and merges its own results into that empty input to give a per-worker output, and then we have a separate accumulator and we merge each per-worker's output into that accumulator. * next : () -> progress This mutates [files_to_process] by removing a bucket of filenames, and returns a degenerate progress {remaining=bucket; completed=[]; deferred=[]} which is basically just the bucket of work to be done by the job. * neutral : typing_result This value is just the empty typing_result {errors=Empty; deps=Empty; telemetry=Empty} * job : typing_result -> progress -> (typing_result', progress') MultiWorker will invoke this job. For input, it provides a copy of the degenerate [typing_result] that it got from [neutral], and it provides the degenerate [progress] i.e. just the bucket of work that it got from [next] The behavior of our job is to take items out of progress.remaining and typecheck them. It repeats this process until it either runs out of items or its heap grows too big. It returns a new progress' {remaining'; completed; deferred} to show the items still remaining, the ones it completed, and the ones it had to defer (see below). It returns a new typing_result' {errors; deps; telemetry} by merging its own newly discovered errors, deps, telemetry onto the (degenerate i.e. empty) typing_result it was given as input. * merge : (typing_result * progress) (accumulator : typing_result) -> typing_result The initial value of accumulator is the same [neutral] that was given to each job. After each job, MultiWorker calls [merge] to merge the results of that job into the accumulator. Our merge function looks at the progress {remaining;completed;deferred} that came out of the job, and mutates [files_to_process] by sticking back "remaining+deferred" into it. It then merges the typing_result {errors;deps;telemetry} that came out of the job with those in its accumulator. The type signatures for MultiWorker look like they'd allow a variety of implementations, e.g. having just a single accumulator that starts at "neutral" and feeds one by one into each job. But we don't do that. #### The normal computation kind for the type checking service is to type check all symbols in a file. The type checker would always be able to find a given symbol it needs to perform this job if all the declarations were computed for all the files in the repo before type checking begins. However, such eager declaration does not occur in the following scenarios: - When the server initialization strategy is Lazy: not having a declaration phase was the original meaning of lazy init - If the server initialized from a saved state: most decls would not be available because saved states only consist of one or more of the following: naming table, dependency graph, errors, and hot decls (a small subset of all possible decls) The decl heap module, when asked for a decl that is not yet in memory, can declare the decl's file lazily. Declaring a file means parsing the file and extracting the symbols declared in it, hence the term 'decl'. This lazy declaration strategy works reasonably well for most cases, but there's a case where it works poorly: if a particular file that is getting type checked requires a large number of symbols which have not yet been declared, the unlucky worker ends up serially declaring all the files that contain those symbols. In some cases, we observe type checking times on the order of minutes for a single file. Therefore, to account for the fact that we don't have the overall eager declaration phase in some initialization scenarios, the decl heap module is now capable of refusing to declare a file and instead adding the file to a list of deferments. The type checker worker is then able to return that list and the file which was being type checked when deferments occured back to the master process. The master process is then able to distribute the declaration of the files and the (re)checking of the original file to all of its workers, thus achieving parallelism and better type checking times overall. The deferment of declarations is adjustable: it works by using a threshold value that dictates the maximum number of lazy declarations allowed per file. If the threshold is not set, then there is no limit, and no declarations would be deferred. If the threshold is set at 1, then all declarations would be deferred. The idea behind deferring declarations is similar to the 2nd of the 4 build systems considered in the following paper (Make, Excel's calc engine, Shake, and Bazel): https://www.microsoft.com/en-us/research/uploads/prod/2018/03/build-systems-final.pdf The paper refers to this approach as "restarting", and further suggests that recording and reusing the chain of jobs could be used to minimize the number of restarts. *) type seconds_since_epoch = float type log_message = string let neutral : unit -> typing_result = Typing_service_types.make_typing_result let should_enable_deferring (file : check_file_workitem) = not file.was_already_deferred type process_file_results = { file_errors: Errors.t; file_map_reduce_data: Map_reduce.t; deferred_decls: Deferred_decl.deferment list; } let scrape_class_names (ast : Nast.program) : SSet.t = let names = ref SSet.empty in let visitor = object (* It would look less clumsy to use Aast.reduce, but would use set union which has higher complexity. *) inherit [_] Aast.iter method! on_class_name _ (_p, id) = names := SSet.add id !names end in visitor#on_program () ast; !names let process_file (ctx : Provider_context.t) (file : check_file_workitem) ~(log_errors : bool) ~(decl_cap_mb : int option) : process_file_results = let fn = file.path in let (file_errors, ast) = Ast_provider.get_ast_with_error ~full:true ctx fn in if not (Errors.is_empty file_errors) then { file_errors; deferred_decls = []; file_map_reduce_data = Map_reduce.empty; } else let opts = Provider_context.get_tcopt ctx in let ctx = Provider_context.map_tcopt ctx ~f:(fun _tcopt -> opts) in try let (result : (_, unit) result) = Deferred_decl.with_deferred_decls ~enable:(should_enable_deferring file) ~declaration_threshold_opt: (TypecheckerOptions.defer_class_declaration_threshold opts) ~memory_mb_threshold_opt:decl_cap_mb (fun () -> Typing_check_job.calc_errors_and_tast ctx fn ~drop_fixmed:false ~full_ast:ast) in match result with | Ok (file_errors, tasts) -> if log_errors then List.iter (Errors.get_error_list file_errors) ~f:(fun error -> let { User_error.claim; code; _ } = error in let (pos, msg) = claim in let (l1, l2, c1, c2) = Pos.info_pos_extended pos in Hh_logger.log "%s(%d:%d-%d:%d) [%d] %s" (Relative_path.suffix fn) l1 c1 l2 c2 code msg); { file_errors; deferred_decls = []; file_map_reduce_data = Map_reduce.map ctx fn tasts; } | Error () -> let deferred_decls = Errors.ignore_ (fun () -> Naming.program ctx ast) |> scrape_class_names |> SSet.elements |> List.filter_map ~f:(fun class_name -> Naming_provider.get_class_path ctx class_name >>| fun fn -> (fn, class_name)) in { file_errors = Errors.empty; deferred_decls; file_map_reduce_data = Map_reduce.empty; } with | WorkerCancel.Worker_should_exit as exn -> (* Cancellation requests must be re-raised *) let e = Exception.wrap exn in Exception.reraise e | exn -> let e = Exception.wrap exn in prerr_endline ("Exception on file " ^ Relative_path.S.to_string fn); Exception.reraise e module ProcessFilesTally = struct (** Counters for the [check_file_workitem] of each sort being processed *) type t = { decls: int; (** how many [Declare] items we performed *) checks_done: int; (** how many [Check] items we typechecked *) checks_deferred: int; (** how many [Check] items we deferred to later *) decls_deferred: int; (** how many [Declare] items we added for later *) exceeded_cap_count: int; (** how many times we exceeded the memory cap *) } let empty = { decls = 0; checks_done = 0; checks_deferred = 0; decls_deferred = 0; exceeded_cap_count = 0; } let incr_decls tally = { tally with decls = tally.decls + 1 } let record_caps ~workitem_ends_under_cap tally = if workitem_ends_under_cap then tally else { tally with exceeded_cap_count = tally.exceeded_cap_count + 1 } let incr_checks tally deferred_decls = if List.is_empty deferred_decls then { tally with checks_done = tally.checks_done + 1 } else { tally with checks_deferred = tally.checks_deferred + 1; decls_deferred = tally.decls_deferred + List.length deferred_decls; } let count tally = tally.checks_done + tally.checks_deferred + tally.decls let get_telemetry tally = Telemetry.create () |> Telemetry.int_ ~key:"decls" ~value:tally.decls |> Telemetry.int_ ~key:"checks_done" ~value:tally.checks_done |> Telemetry.int_ ~key:"checks_deferred" ~value:tally.checks_deferred |> Telemetry.int_ ~key:"decls_deferred" ~value:tally.decls_deferred |> Telemetry.int_ ~key:"exceeded_cap_count" ~value:tally.exceeded_cap_count end let get_stats ~include_slightly_costly_stats tally : HackEventLogger.ProfileTypeCheck.stats = let telemetry = Counters.get_counters () |> Telemetry.object_ ~key:"tally" ~value:(ProcessFilesTally.get_telemetry tally) in HackEventLogger.ProfileTypeCheck.get_stats ~include_current_process:true ~include_slightly_costly_stats ~shmem_heap_size:(SharedMem.SMTelemetry.heap_size ()) telemetry external hh_malloc_trim : unit -> unit = "hh_malloc_trim" type workitem_accumulator = { errors: Errors.t; map_reduce_data: Map_reduce.t; tally: ProcessFilesTally.t; stats: HackEventLogger.ProfileTypeCheck.stats; } let process_one_workitem ~ctx ~(check_info : check_info) ~batch_info ~memory_cap ~longlived_workers ~error_count_at_start_of_batch (fn : workitem) ({ errors; map_reduce_data; tally; stats } : workitem_accumulator) : TypingProgress.progress_outcome * workitem_accumulator = let decl_cap_mb = if check_info.use_max_typechecker_worker_memory_for_decl_deferral then memory_cap else None in let workitem_cap_mb = Option.value memory_cap ~default:Int.max_value in let type_check_twice = check_info.per_file_profiling .HackEventLogger.PerFileProfilingConfig.profile_type_check_twice in let ( file, decl, mid_stats, file_errors, map_reduce_data, deferred_workitems, tally ) = match fn with | Check file -> (* We'll show at least the first five errors in the project. Maybe more, if this file has more in it, or if other concurrent workers race to print the first five errors before us. *) let log_errors = check_info.log_errors && error_count_at_start_of_batch + Errors.count errors < 5 in let { file_errors; file_map_reduce_data; deferred_decls } = process_file ctx file ~decl_cap_mb ~log_errors in let map_reduce_data = Map_reduce.reduce map_reduce_data file_map_reduce_data in let mid_stats = if type_check_twice then Some (get_stats ~include_slightly_costly_stats:false tally) else None in begin if type_check_twice then let _ignored = process_file ctx file ~decl_cap_mb in () end; let tally = ProcessFilesTally.incr_checks tally deferred_decls in let deferred = if List.is_empty deferred_decls then [] else List.map deferred_decls ~f:(fun fn -> Declare fn) @ [Check { file with was_already_deferred = true }] in (Some file, None, mid_stats, file_errors, map_reduce_data, deferred, tally) | Declare (_path, class_name) -> let (_ : Decl_provider.class_decl option) = Decl_provider.get_class ctx class_name in ( None, Some class_name, None, Errors.empty, map_reduce_data, [], ProcessFilesTally.incr_decls tally ) in let errors = Errors.merge file_errors errors in let workitem_ends_under_cap = Gc_utils.get_heap_size () <= workitem_cap_mb in let final_stats = get_stats ~include_slightly_costly_stats: ((not longlived_workers) && not workitem_ends_under_cap) tally in let (workitem_end_stats, workitem_end_second_stats) = match mid_stats with | None -> (final_stats, None) | Some mid_stats -> (mid_stats, Some final_stats) in (* If the major heap has exceeded the bounds, we (1) first try and bring the size back down by flushing the parser cache and doing a major GC; (2) if this fails, we decline to typecheck the remaining files. We use [quick_stat] instead of [stat] in Gc_utils.get_heap_size in order to avoid walking the major heap, and we don't change the minor heap because it's small and fixed-size. This test is performed after we've processed at least one item, to ensure we make at least some progress. *) let tally = ProcessFilesTally.record_caps ~workitem_ends_under_cap tally in let workitem_ends_under_cap = if workitem_ends_under_cap || not longlived_workers then workitem_ends_under_cap else begin SharedMem.invalidate_local_caches (); HackEventLogger.flush (); Gc.compact (); hh_malloc_trim (); Gc_utils.get_heap_size () <= workitem_cap_mb end in HackEventLogger.ProfileTypeCheck.process_workitem ~batch_info ~workitem_index:(ProcessFilesTally.count tally) ~file:(Option.map file ~f:(fun file -> file.path)) ~file_was_already_deferred: (Option.map file ~f:(fun file -> file.was_already_deferred)) ~decl ~error_code:(Errors.choose_code_opt file_errors) ~workitem_ends_under_cap ~workitem_start_stats:stats ~workitem_end_stats ~workitem_end_second_stats; ( { TypingProgress.deferred_workitems; continue = workitem_ends_under_cap }, { errors; map_reduce_data; tally; stats = final_stats } ) let process_workitems (ctx : Provider_context.t) ({ errors; map_reduce_data; dep_edges; profiling_info } : typing_result) (progress : TypingProgress.t) ~(memory_cap : int option) ~(longlived_workers : bool) ~(check_info : check_info) ~(worker_id : string) ~(batch_number : int) ~(error_count_at_start_of_batch : int) ~(typecheck_info : HackEventLogger.ProfileTypeCheck.typecheck_info) : typing_result * TypingProgress.t = Decl_counters.set_mode check_info.per_file_profiling .HackEventLogger.PerFileProfilingConfig.profile_decling; let _prev_counters_state = Counters.reset () in let batch_info = HackEventLogger.ProfileTypeCheck.get_batch_info ~typecheck_info ~worker_id ~batch_number ~batch_size:(List.length (TypingProgress.remaining progress)) ~start_batch_stats: (get_stats ~include_slightly_costly_stats:true ProcessFilesTally.empty) in if not longlived_workers then SharedMem.invalidate_local_caches (); File_provider.local_changes_push_sharedmem_stack (); Ast_provider.local_changes_push_sharedmem_stack (); (* Process as many files as we can, and merge in their errors *) let (progress, { errors; map_reduce_data; tally = _; stats = _ }) = let init = { errors; map_reduce_data; tally = ProcessFilesTally.empty; stats = get_stats ~include_slightly_costly_stats:true ProcessFilesTally.empty; } in TypingProgress.progress_through ~init progress @@ process_one_workitem ~ctx ~check_info ~batch_info ~error_count_at_start_of_batch ~memory_cap ~longlived_workers in (* Update edges *) let new_dep_edges = Typing_deps.flush_ideps_batch (Provider_context.get_deps_mode ctx) in let dep_edges = Typing_deps.merge_dep_edges dep_edges new_dep_edges in if Provider_context.get_tcopt ctx |> TypecheckerOptions.record_fine_grained_dependencies then Typing_pessimisation_deps.finalize (Provider_context.get_deps_mode ctx); (* Gather up our various forms of telemetry... *) let end_heap_mb = Gc.((quick_stat ()).Stat.heap_words) * 8 / 1024 / 1024 in let this_batch_profiling_info = Telemetry.create () |> Telemetry.object_ ~key:"operations" ~value:(Counters.get_counters ()) |> Telemetry.int_ ~key:"end_heap_mb_sum" ~value:end_heap_mb |> Telemetry.int_ ~key:"batch_count" ~value:1 in let profiling_info = Telemetry.add profiling_info this_batch_profiling_info in TypingLogger.flush_buffers (); Ast_provider.local_changes_pop_sharedmem_stack (); File_provider.local_changes_pop_sharedmem_stack (); ({ errors; map_reduce_data; dep_edges; profiling_info }, progress) let load_and_process_workitems (ctx : Provider_context.t) (typing_result : typing_result) (progress : TypingProgress.t) ~(memory_cap : int option) ~(longlived_workers : bool) ~(check_info : check_info) ~(worker_id : string) ~(batch_number : int) ~(error_count_at_start_of_batch : int) ~(typecheck_info : HackEventLogger.ProfileTypeCheck.typecheck_info) : typing_result * TypingProgress.t = Option.iter check_info.memtrace_dir ~f:(fun temp_dir -> let file = Caml.Filename.temp_file ~temp_dir "memtrace.worker." ".ctf" in Daemon.start_memtracing file); (* When the type-checking worker receives SIGUSR1, display a position which corresponds approximately with the function/expression being checked. *) Sys_utils.set_signal Sys.sigusr1 (Sys.Signal_handle Typing.debug_print_last_pos); process_workitems ctx typing_result progress ~memory_cap ~longlived_workers ~check_info ~worker_id ~batch_number ~error_count_at_start_of_batch ~typecheck_info (*****************************************************************************) (* Let's go! That's where the action is *) (*****************************************************************************) let possibly_push_new_errors_to_lsp_client : progress:Typing_service_types.TypingProgress.t -> Errors.t -> Diagnostic_pusher.t option -> Diagnostic_pusher.t option * seconds_since_epoch option = fun ~progress new_errors diag -> match diag with | None -> (None, None) | Some diag -> let rechecked = TypingProgress.completed progress |> List.filter_map ~f:(function | Check { path; was_already_deferred = _ } -> Some path | Declare _ -> None) |> Relative_path.Set.of_list in let (diag, time_errors_pushed) = Diagnostic_pusher.push_new_errors diag ~rechecked new_errors in (Some diag, time_errors_pushed) (** Merge the results from multiple workers. We don't really care about which files are left unchecked since we use (gasp) mutation to track that, so combine the errors but always return an empty list for the list of unchecked files. *) let merge ~(batch_counts_by_worker_id : int SMap.t ref) ~(errors_so_far : int ref) ~(check_info : check_info) (workitems_to_process : workitem BigList.t ref) (workitems_initial_count : int) (workitems_in_progress : workitem Hash_set.t) (files_checked_count : int ref) (diagnostic_pusher : Diagnostic_pusher.t option ref) (time_first_error : seconds_since_epoch option ref) ( (worker_id : string), (produced_by_job : typing_result), ({ kind = progress_kind; progress : TypingProgress.t } : job_progress) ) (acc : typing_result) : typing_result = (* Update batch count *) begin match progress_kind with | Progress -> let prev_batch_count = SMap.find_opt worker_id !batch_counts_by_worker_id |> Option.value ~default:0 in batch_counts_by_worker_id := SMap.add worker_id (prev_batch_count + 1) !batch_counts_by_worker_id end; (* And error count *) errors_so_far := !errors_so_far + Errors.count produced_by_job.errors; workitems_to_process := BigList.append (TypingProgress.remaining progress) !workitems_to_process; (* Let's also prepend the deferred files! *) workitems_to_process := BigList.append (TypingProgress.deferred progress) !workitems_to_process; (* If workers can steal work from each other, then it's possible that some of the files that the current worker completed checking have already been removed from the in-progress set. Thus, we should keep track of how many type check computations we actually remove from the in-progress set. Note that we also skip counting Declare computations, since they are not relevant for computing how many files we've type checked. *) let completed_check_count = List.fold ~init:0 ~f:(fun acc workitem -> match Hash_set.Poly.strict_remove workitems_in_progress workitem with | Ok () -> begin match workitem with | Check _ -> acc + 1 | _ -> acc end | _ -> acc) (TypingProgress.completed progress) in (* Deferred type check computations should be subtracted from completed in order to produce an accurate count because they we requeued them, yet they were also included in the completed list. *) let is_check workitem = match workitem with | Check _ -> true | _ -> false in let deferred_check_count = List.count ~f:is_check (TypingProgress.deferred progress) in let completed_check_count = completed_check_count - deferred_check_count in files_checked_count := !files_checked_count + completed_check_count; ServerProgress.write_percentage ~operation:"typechecking" ~done_count:!files_checked_count ~total_count:workitems_initial_count ~unit:"files" ~extra:None; (* Handle errors paradigm (3) - push updates to errors-file as soon as their batch is finished *) if check_info.log_errors then ServerProgress.ErrorsWrite.report produced_by_job.errors; (* Handle errors paradigm (2) - push updates to lsp as well *) let (diag_pusher, time_errors_pushed) = possibly_push_new_errors_to_lsp_client ~progress produced_by_job.errors !diagnostic_pusher in diagnostic_pusher := diag_pusher; time_first_error := Option.first_some !time_first_error time_errors_pushed; Typing_deps.register_discovered_dep_edges produced_by_job.dep_edges; Typing_deps.register_discovered_dep_edges acc.dep_edges; let produced_by_job = { produced_by_job with dep_edges = Typing_deps.dep_edges_make () } in let acc = { acc with dep_edges = Typing_deps.dep_edges_make () } in accumulate_job_output produced_by_job acc let next (workers : MultiWorker.worker list option) (workitems_to_process : workitem BigList.t ref) (workitems_in_progress : workitem Hash_set.Poly.t) (record : Measure.record) : unit -> job_progress Bucket.bucket = let num_workers = match workers with | Some w -> List.length w | None -> 1 in let return_bucket_job (kind : progress_kind) ~current_bucket ~remaining_jobs = (* Update our shared mutable state, because hey: it's not like we're writing OCaml or anything. *) workitems_to_process := remaining_jobs; List.iter ~f:(Hash_set.Poly.add workitems_in_progress) current_bucket; Bucket.Job { kind; progress = TypingProgress.init current_bucket } in fun () -> Measure.time ~record "time" @@ fun () -> let workitems_to_process_length = BigList.length !workitems_to_process in (* WARNING: the following List.length is costly - for a full init, files_to_process starts out as the size of the entire repo, and we're traversing the entire list. *) match workitems_to_process_length with | 0 when Hash_set.Poly.is_empty workitems_in_progress -> Bucket.Done | 0 -> Bucket.Wait | _ -> let jobs = !workitems_to_process in begin match num_workers with (* When num_workers is zero, the execution mode is delegate-only, so we give an empty bucket to MultiWorker for execution. *) | 0 -> return_bucket_job Progress ~current_bucket:[] ~remaining_jobs:jobs | _ -> let bucket_size = Bucket.calculate_bucket_size ~num_jobs:workitems_to_process_length ~num_workers () in let (current_bucket, remaining_jobs) = BigList.split_n jobs bucket_size in return_bucket_job Progress ~current_bucket ~remaining_jobs end let on_cancelled (next : unit -> 'a Bucket.bucket) (files_to_process : 'b Hash_set.Poly.elt BigList.t ref) (files_in_progress : 'b Hash_set.Poly.t) : unit -> 'a list = fun () -> (* The size of [files_to_process] is bounded only by repo size, but [files_in_progress] is capped at [(worker count) * (max bucket size)]. *) files_to_process := BigList.append (Hash_set.Poly.to_list files_in_progress) !files_to_process; let rec add_next acc = match next () with | Bucket.Job j -> add_next (j :: acc) | Bucket.Wait | Bucket.Done -> acc in add_next [] let rec drain_events (done_count, total_count, handle, check_info) = match Hh_distc_ffi.recv handle with | Ok (Some (Hh_distc_types.Errors errors)) -> if check_info.log_errors then ServerProgress.ErrorsWrite.report errors; drain_events (done_count, total_count, handle, check_info) | Ok (Some (Hh_distc_types.TypingStart total_count)) -> drain_events (done_count, total_count, handle, check_info) | Ok (Some (Hh_distc_types.TypingProgress n)) -> let done_count = done_count + n in drain_events (done_count, total_count, handle, check_info) | Ok None -> Ok (done_count, total_count) | Error error -> Error error type 'env distc_outcome = | Success of Errors.t * Map_reduce.t * Typing_deps.dep_edges * 'env | DistCError of log_message | Cancel of 'env * MultiThreadedCall.cancel_reason (** This is the event loop that powers hh_distc. It keeps looping and calling select on a series of fds including ones from watchman, hh_distc, hh_client, etc. When one of the fds activate, the loops continues one iteration and decides what to do. Most of the time the main fd that will be selected is the hh_distc one as it reports progress events on a very frequent interval. We can then use these progress events to stream errors and report progress back to the user. *) let rec event_loop ~(done_count : int) ~(total_count : int) ~(interrupt : 'env MultiThreadedCall.interrupt_config) ~(handlers : (Unix.file_descr * 'env MultiThreadedCall.interrupt_handler) list) ~(fd_distc : Unix.file_descr) ~(handle : Hh_distc_ffi.handle) ~(check_info : check_info) ~(hhdg_path : string) : _ distc_outcome = let handler_fds = List.map handlers ~f:fst in (* hh_distc sends a byte each time new events are ready. *) let (ready_fds, _, _) = Sys_utils.select_non_intr (handler_fds @ [fd_distc]) [] [] (-1.) in if List.mem ~equal:Poly.( = ) ready_fds fd_distc then match Sys_utils.read_non_intr fd_distc 1 with | None -> ServerProgress.write "hh_distc done"; (match Hh_distc_ffi.join handle with | Ok (errors, map_reduce_data) -> (* TODO: Clear in memory deps. Doesn't effect correctness but can cause larger fanouts *) Typing_deps.replace (Typing_deps_mode.InMemoryMode (Some hhdg_path)); Success ( errors, Map_reduce.of_ffi map_reduce_data, Typing_deps.dep_edges_make (), interrupt.MultiThreadedCall.env ) | Error error -> DistCError error) | Some _ -> (match drain_events (done_count, total_count, handle, check_info) with | Ok (done_count, total_count) -> ServerProgress.write_percentage ~operation:"hh_distc checking" ~done_count ~total_count ~unit:"files" ~extra:None; event_loop ~done_count ~total_count ~interrupt ~handlers ~fd_distc ~handle ~check_info ~hhdg_path | Error error -> DistCError error) else let (env, decision, handlers) = List.fold handlers ~init: (interrupt.MultiThreadedCall.env, MultiThreadedCall.Continue, handlers) ~f:(fun (env, decision, handlers) (fd, handler) -> match (decision, not @@ List.mem ~equal:Poly.( = ) ready_fds fd) with | (_, false) -> (* skip handlers whose fd isn't ready *) (env, decision, handlers) | (MultiThreadedCall.Cancel _, _) -> (* if a previous handler has decided to cancel, skip further handlers *) (env, decision, handlers) | (MultiThreadedCall.Continue, true) -> let (env, decision) = handler env in (* running a handler could have changed the handlers, * so need to regenerate them based on new environment *) let handlers = interrupt.MultiThreadedCall.handlers interrupt.MultiThreadedCall.env in (env, decision, handlers)) in let interrupt = { interrupt with MultiThreadedCall.env } in match decision with | MultiThreadedCall.Cancel reason -> let () = Hh_distc_ffi.cancel handle in Cancel (interrupt.MultiThreadedCall.env, reason) | MultiThreadedCall.Continue -> event_loop ~done_count ~total_count ~interrupt ~handlers ~fd_distc ~handle ~check_info ~hhdg_path (** This is the main process function that triggers a full init via hh_distc. We FFI into rustland to activate hh_distc to get back an opaque handle. We can then use this handle to poll for progress and eventually join the handle to get all the errors we need to return to the user. This also works with the existing hh_server incrementality paradigm because after each typecheck, we generate a full dep graph, which we then use to replace the existing hh_server dep graph. We return a result where Ok represents a completed typecheck and Error represents a cancelled typecheck. Any errors from hh_distc are considered fatal and results in a call to failwith, which will terminate hh_server. *) let process_with_hh_distc ~(root : Path.t option) ~(interrupt : 'a MultiThreadedCall.interrupt_config) ~(check_info : check_info) ~(tcopt : TypecheckerOptions.t) : _ distc_outcome = (* We don't want to use with_tempdir because we need to keep the folder around for subseqent typechecks that will read the dep graph in the folder *) let root = Option.value_exn root in let ss_dir = Tempfile.mkdtemp ~skip_mocking:false in let hhdg_path = Path.(to_string @@ concat ss_dir "hh_mini_saved_state.hhdg") in let hh_distc_handle = Hh_distc_ffi.spawn ~root:(Path.to_string root) ~ss_dir:(Path.to_string ss_dir) ~hhdg_path tcopt |> Result.ok_or_failwith in let fd_distc = Hh_distc_ffi.get_fd hh_distc_handle in ServerProgress.write "hh_distc running"; let handlers = interrupt.MultiThreadedCall.handlers interrupt.MultiThreadedCall.env in event_loop ~done_count:0 ~total_count:0 ~interrupt ~handlers ~fd_distc ~handle:hh_distc_handle ~check_info ~hhdg_path (** `next` and `merge` both run in the master process and update mutable state in order to track work in progress and work remaining. `job` runs in each worker and does not have access to this mutable state. *) let process_in_parallel ?diagnostic_pusher (ctx : Provider_context.t) (workers : MultiWorker.worker list option) (telemetry : Telemetry.t) (workitems : workitem BigList.t) ~(interrupt : 'a MultiThreadedCall.interrupt_config) ~(memory_cap : int option) ~(longlived_workers : bool) ~(check_info : check_info) ~(typecheck_info : HackEventLogger.ProfileTypeCheck.typecheck_info) : typing_result * Telemetry.t * _ * (Relative_path.t list * MultiThreadedCall.cancel_reason) option * (Diagnostic_pusher.t option * seconds_since_epoch option) = let record = Measure.create () in (* [record] is used by [next] *) let workitems_to_process = ref workitems in let workitems_in_progress = Hash_set.Poly.create () in let workitems_initial_count = BigList.length workitems in let workitems_processed_count = ref 0 in let diagnostic_pusher = ref diagnostic_pusher in let time_first_error = ref None in let errors_so_far = ref 0 in let batch_counts_by_worker_id = ref SMap.empty in let next = next workers workitems_to_process workitems_in_progress record in (* The [job] lambda is marshalled, sent to the worker process, unmarshalled there, and executed. It is marshalled immediately before being executed. *) let job (typing_result : typing_result) (progress : job_progress) : string * typing_result * job_progress = let worker_id = Option.value ~default:"main" (Hh_logger.get_id ()) in let (typing_result, computation_progress) = match progress.kind with | Progress -> load_and_process_workitems ctx ~memory_cap ~longlived_workers ~check_info ~typecheck_info ~worker_id ~error_count_at_start_of_batch:!errors_so_far ~batch_number: (SMap.find_opt worker_id !batch_counts_by_worker_id |> Option.value ~default:0) typing_result progress.progress in (worker_id, typing_result, { progress with progress = computation_progress }) in let (typing_result, env, cancelled_results) = MultiWorker.call_with_interrupt workers ~job ~neutral:(neutral ()) ~merge: (merge ~batch_counts_by_worker_id ~errors_so_far ~check_info workitems_to_process workitems_initial_count workitems_in_progress workitems_processed_count diagnostic_pusher time_first_error) ~next ~on_cancelled: (on_cancelled next workitems_to_process workitems_in_progress) ~interrupt in let paths_of (unfinished : job_progress list) : Relative_path.t list = let paths_of (cancelled_progress : job_progress) = let cancelled_computations = TypingProgress.remaining cancelled_progress.progress in let paths_of paths (cancelled_workitem : workitem) = match cancelled_workitem with | Check { path; _ } -> path :: paths | _ -> paths in List.fold cancelled_computations ~init:[] ~f:paths_of in List.concat (List.map unfinished ~f:paths_of) in let cancelled_results = Option.map cancelled_results ~f:(fun (unfinished, reason) -> (paths_of unfinished, reason)) in ( typing_result, telemetry, env, cancelled_results, (!diagnostic_pusher, !time_first_error) ) type 'a job_result = 'a * (Relative_path.t list * MultiThreadedCall.cancel_reason) option module type Mocking_sig = sig val with_test_mocking : (* real job payload, that we can modify... *) workitem BigList.t -> ((* ... before passing it to the real job executor... *) workitem BigList.t -> 'a job_result) -> (* ... which output we can also modify. *) 'a job_result end module NoMocking = struct let with_test_mocking fnl f = f fnl end module TestMocking = struct let cancelled = ref Relative_path.Set.empty let set_is_cancelled x = cancelled := Relative_path.Set.add !cancelled x let is_cancelled x = Relative_path.Set.mem !cancelled x let with_test_mocking (fnl : workitem BigList.t) (f : workitem BigList.t -> 'a job_result) : 'a job_result = let (mock_cancelled, fnl) = List.partition_map (BigList.as_list fnl) ~f:(fun computation -> match computation with | Check { path; _ } -> if is_cancelled path then First path else Second computation | _ -> Second computation) in (* Only cancel once to avoid infinite loops *) cancelled := Relative_path.Set.empty; let (res, unfinished_and_reason) = f (BigList.create fnl) in let unfinished_and_reason = match unfinished_and_reason with | None when List.is_empty mock_cancelled -> None | None -> Some ( mock_cancelled, { MultiThreadedCall.user_message = "mock cancel"; log_message = "mock cancel"; timestamp = 0.0; } ) | Some (cancelled, reason) -> Some (mock_cancelled @ cancelled, reason) in (res, unfinished_and_reason) end module Mocking = (val if Injector_config.use_test_stubbing then (module TestMocking : Mocking_sig) else (module NoMocking : Mocking_sig)) type result = { errors: Errors.t; telemetry: Telemetry.t; diagnostic_pusher: Diagnostic_pusher.t option * seconds_since_epoch option; } let go_with_interrupt ?(diagnostic_pusher : Diagnostic_pusher.t option) (ctx : Provider_context.t) (workers : MultiWorker.worker list option) (telemetry : Telemetry.t) (fnl : Relative_path.t list) ~(root : Path.t option) ~(interrupt : 'a MultiThreadedCall.interrupt_config) ~(memory_cap : int option) ~(longlived_workers : bool) ~(use_hh_distc_instead_of_hulk : bool) ~(hh_distc_fanout_threshold : int option) ~(check_info : check_info) : (_ * result) job_result = let typecheck_info = HackEventLogger.ProfileTypeCheck.get_typecheck_info ~init_id:check_info.init_id ~check_reason:check_info.check_reason ~recheck_id:check_info.recheck_id ~start_hh_stats:(CgroupProfiler.get_initial_stats ()) ~start_typecheck_stats: (HackEventLogger.ProfileTypeCheck.get_stats ~include_current_process:false ~include_slightly_costly_stats:true ~shmem_heap_size:(SharedMem.SMTelemetry.heap_size ()) (Telemetry.create ())) ~config:check_info.per_file_profiling in let tcopt = Provider_context.get_tcopt ctx in let sample_rate = TypecheckerOptions.typecheck_sample_rate tcopt in let original_fnl = fnl in let fnl = BigList.create fnl in ServerProgress.write "typechecking %d files" (BigList.length fnl); let fnl = if Float.(sample_rate >= 1.0) then fnl else let result = BigList.filter ~f:(fun x -> Float.( float (Base.String.hash (Relative_path.suffix x) mod 1000000) <= sample_rate *. 1000000.0)) fnl in Hh_logger.log "Sampling %f percent of files: %d out of %d" sample_rate (BigList.length result) (BigList.length fnl); result in let fnl = BigList.map fnl ~f:(fun path -> Check { path; was_already_deferred = false }) in let num_workers = TypecheckerOptions.num_local_workers tcopt in let workers = match (workers, num_workers) with | (Some workers, Some num_local_workers) -> let (workers, _) = List.split_n workers num_local_workers in Some workers | (None, _) | (_, None) -> workers in Mocking.with_test_mocking fnl @@ fun fnl -> let ( typing_result, telemetry, env, cancelled_fnl_and_reason, diagnostic_pusher ) = let will_use_distc = use_hh_distc_instead_of_hulk && BigList.length fnl > Option.value_exn hh_distc_fanout_threshold in if check_info.log_errors then ServerProgress.ErrorsWrite.telemetry (Telemetry.create () |> Telemetry.bool_ ~key:"will_use_distc" ~value:will_use_distc); let results_via_distc = if will_use_distc then ( (* distc doesn't yet give any profiling_info about how its workers fared *) let profiling_info = Telemetry.create () in match process_with_hh_distc ~root ~interrupt ~check_info ~tcopt with | Success (errors, map_reduce_data, dep_edges, env) -> Some ( { errors; map_reduce_data; dep_edges; profiling_info }, telemetry, env, None, (None, None) ) | Cancel (env, reason) -> (* Typecheck is cancelled due to interrupt *) Some ( { errors = Errors.empty; map_reduce_data = Map_reduce.empty; dep_edges = Typing_deps.dep_edges_make (); profiling_info; }, telemetry, env, Some (original_fnl, reason), (None, None) ) | DistCError msg -> Hh_logger.log "Error with hh_distc: %s" msg; HackEventLogger.invariant_violation_bug "Unexpected hh_distc error" ~data:msg; None ) else None in (* None means either we didn't attempt distc, or we did but it failed and we'll fall back to parallel... *) match results_via_distc with | Some results -> results | None -> if check_info.log_errors then ServerProgress.ErrorsWrite.telemetry (Telemetry.create () |> Telemetry.bool_ ~key:"process_in_parallel" ~value:true); process_in_parallel ?diagnostic_pusher ctx workers telemetry fnl ~interrupt ~memory_cap ~longlived_workers ~check_info ~typecheck_info in let { errors; map_reduce_data; dep_edges; profiling_info } = typing_result in Typing_deps.register_discovered_dep_edges dep_edges; Map_reduce.finalize ~progress:(fun s -> ServerProgress.write "%s" s) ~init_id:check_info.init_id ~recheck_id:check_info.recheck_id map_reduce_data; let telemetry = telemetry |> Telemetry.object_ ~key:"profiling_info" ~value:profiling_info in ((env, { errors; telemetry; diagnostic_pusher }), cancelled_fnl_and_reason) let go (ctx : Provider_context.t) (workers : MultiWorker.worker list option) (telemetry : Telemetry.t) (fnl : Relative_path.t list) ~(root : Path.t option) ~(memory_cap : int option) ~(longlived_workers : bool) ~(use_hh_distc_instead_of_hulk : bool) ~(hh_distc_fanout_threshold : int option) ~(check_info : check_info) : result = let interrupt = MultiThreadedCall.no_interrupt () in let (((), result), unfinished_and_reason) = go_with_interrupt ?diagnostic_pusher:None ctx workers telemetry fnl ~root ~interrupt ~memory_cap ~longlived_workers ~use_hh_distc_instead_of_hulk ~hh_distc_fanout_threshold ~check_info in assert (Option.is_none unfinished_and_reason); result
OCaml Interface
hhvm/hphp/hack/src/typing/typing_check_service.mli
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type 'a job_result = 'a * (Relative_path.t list * MultiThreadedCall.cancel_reason) option type seconds_since_epoch = float type process_file_results = { file_errors: Errors.t; file_map_reduce_data: Map_reduce.t; deferred_decls: Deferred_decl.deferment list; } val should_enable_deferring : Typing_service_types.check_file_workitem -> bool val process_file : Provider_context.t -> Typing_service_types.check_file_workitem -> log_errors:bool -> decl_cap_mb:int option -> process_file_results type result = { errors: Errors.t; telemetry: Telemetry.t; diagnostic_pusher: Diagnostic_pusher.t option * seconds_since_epoch option; } val go : Provider_context.t -> MultiWorker.worker list option -> Telemetry.t -> Relative_path.t list -> root:Path.t option -> memory_cap:int option -> longlived_workers:bool -> use_hh_distc_instead_of_hulk:bool -> hh_distc_fanout_threshold:int option -> check_info:Typing_service_types.check_info -> result (** The last element returned, a list of paths, are the files which have not been processed fully or at all due to interrupts. *) val go_with_interrupt : ?diagnostic_pusher:Diagnostic_pusher.t -> Provider_context.t -> MultiWorker.worker list option -> Telemetry.t -> Relative_path.t list -> root:Path.t option -> interrupt:'env MultiWorker.interrupt_config -> memory_cap:int option -> longlived_workers:bool -> use_hh_distc_instead_of_hulk:bool -> hh_distc_fanout_threshold:int option -> check_info:Typing_service_types.check_info -> ('env * result) job_result module TestMocking : sig val set_is_cancelled : Relative_path.t -> unit end
OCaml
hhvm/hphp/hack/src/typing/typing_class.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 Common open Aast open Typing_defs open Typing_env_types open Typing_helpers module FunUtils = Decl_fun_utils module Reason = Typing_reason module Env = Typing_env module MakeType = Typing_make_type module Type = Typing_ops module Phase = Typing_phase module Subst = Decl_subst module EnvFromDef = Typing_env_from_def module TUtils = Typing_utils module TCO = TypecheckerOptions module Cls = Decl_provider.Class 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 method_dynamically_callable env cls m params_decl_ty return = let env = { env with checked = Tast.CUnderDynamicAssumptions } in let ret_locl_ty = return.Typing_env_return_info.return_type.et_type in (* Here the body of the method is typechecked again to ensure it is safe * to call it from a dynamic context (eg. under dyn..dyn->dyn assumptions). * The code below must be kept in sync with with the method_def checks. *) let make_dynamic pos = MakeType.dynamic (Reason.Rsupport_dynamic_type pos) in let dynamic_return_ty = make_dynamic (get_pos ret_locl_ty) in let dynamic_return_info = Typing_env_return_info. { return with return_type = MakeType.unenforced dynamic_return_ty } in let (env, param_tys) = Typing_param.make_param_local_tys ~dynamic_mode:true ~no_auto_likes:false env params_decl_ty m.m_params in let (env, dynamic_params) = Typing.bind_params ~no_auto_likes:false env m.m_ctxs param_tys m.m_params in let pos = fst m.m_name in let env = set_tyvars_variance_in_callable env dynamic_return_ty param_tys in let env = Typing_dynamic.add_require_dynamic_bounds env cls in let env = if Cls.get_support_dynamic_type cls then let this_local = Env.get_local env this in let this_ty = MakeType.intersection (Reason.Rsupport_dynamic_type Pos_or_decl.none) [this_local.Typing_local_types.ty; make_dynamic Pos_or_decl.none] in Env.set_local ~is_defined:true ~bound_ty:this_local.Typing_local_types.bound_ty env this this_ty Pos.none else env in let disable = Naming_attributes.mem SN.UserAttributes.uaDisableTypecheckerInternal m.m_user_attributes in let (env, dynamic_body) = Errors.try_with_result (fun () -> Typing.fun_ ~abstract:m.m_abstract ~native:(Typing_native.is_native_meth ~env m) ~disable env dynamic_return_info pos m.m_body m.m_fun_kind) (fun env_and_dynamic_body error -> if not @@ TCO.everything_sdt env.genv.tcopt then Errors.method_is_not_dynamically_callable pos (snd m.m_name) (Cls.name cls) (Env.get_support_dynamic_type env) None (Some error); env_and_dynamic_body) in (env, dynamic_params, dynamic_body, dynamic_return_ty) let method_return ~supportdyn env cls m ret_decl_ty = let hint_pos = match snd m.m_ret with | Some (hint_pos, _) -> hint_pos | None -> fst m.m_name in let default_ty = match ret_decl_ty with | None when String.equal (snd m.m_name) SN.Members.__construct -> Some (MakeType.void (Reason.Rwitness (fst m.m_name))) | _ -> None in let ety_env = empty_expand_env_with_on_error (Env.invalid_type_hint_assert_primary_pos_in_current_decl env) in let (env, ret_ty) = Typing_return.make_return_type ~ety_env ~this_class:(Some cls) env ~supportdyn ~hint_pos ~explicit:ret_decl_ty ~default:default_ty in let return = Typing_return.make_info hint_pos m.m_fun_kind m.m_user_attributes env ret_ty in (env, return) let method_def ~is_disposable env cls m = let tcopt = Env.get_tcopt env in Profile.measure_elapsed_time_and_report tcopt (Some env) m.m_name @@ fun () -> Errors.run_with_span m.m_span @@ fun () -> with_timeout env m.m_name @@ fun env -> let err_opt = FunUtils.check_params m.m_params in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) err_opt; let method_name = Ast_defs.get_id m.m_name in let is_ctor = String.equal method_name SN.Members.__construct in let env = if is_ctor then Env.env_with_constructor_droot_member env else Env.env_with_method_droot_member env method_name ~static:m.m_static in let initial_env = env in (* reset the expression dependent display ids for each method body *) Reason.expr_display_id_map := IMap.empty; let pos = fst m.m_name in let env = Env.open_tyvars env (fst m.m_name) in let env = Env.reinitialize_locals env in let env = Env.set_env_callable_pos env pos in let (env, user_attributes) = Typing.attributes_check_def env SN.AttributeKinds.mthd m.m_user_attributes in let env = if Naming_attributes.mem SN.UserAttributes.uaSupportDynamicType m.m_user_attributes then Env.set_support_dynamic_type env true else env in let no_auto_likes = Naming_attributes.mem SN.UserAttributes.uaNoAutoLikes m.m_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 m.m_user_attributes in let (env, cap_ty, unsafe_cap_ty) = Typing_coeffects.type_capability env m.m_ctxs m.m_unsafe_ctxs (fst m.m_name) in let (env, _) = Typing_coeffects.register_capabilities env cap_ty unsafe_cap_ty in let env = Env.set_fun_is_constructor env is_ctor in let (env, ty_err_opt) = Phase.localize_and_add_ast_generic_parameters_and_where_constraints env ~ignore_errors:false m.m_tparams m.m_where_constraints in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt; let env = match Env.get_self_ty env with | Some ty when not (Env.is_static env) -> (* The $this variable isn't a typed local, and so doesn't have a bound type. *) Env.set_local ~is_defined:true ~bound_ty:None env this (MakeType.this (get_reason ty)) Pos.none | _ -> env in let env = if is_disposable then Env.set_using_var env this else env in let env = Env.clear_params env in let (ret_decl_ty, params_decl_ty) = hint_fun_decl ~params:m.m_params ~ret:m.m_ret env in (* Is sound dynamic enabled, and the function not a constructor * and marked <<__SupportDynamicType>> explicitly or implicitly? *) let sdt_method = TCO.enable_sound_dynamic (Provider_context.get_tcopt (Env.get_ctx env)) && (not env.inside_constructor) && Env.get_support_dynamic_type env in (* Does the body of the method need to be checked again under * dynamic assumptions? Note that if there are generic parameters * then the check would be done under different assumptions for * generics from the normal check, so we play safe and require * the second check. *) let sdt_dynamic_check_required = sdt_method && not (List.is_empty (Cls.tparams cls) && Typing_dynamic.function_parameters_safe_for_dynamic ~this_class:(Some cls) env params_decl_ty) in let env = Env.set_fn_kind env m.m_fun_kind in let (env, return) = method_return ~supportdyn:(sdt_method && not sdt_dynamic_check_required) env cls m ret_decl_ty in let sound_dynamic_check_saved_env = env in let no_auto_likes = Naming_attributes.mem SN.UserAttributes.uaNoAutoLikes m.m_user_attributes in let (env, param_tys) = Typing_param.make_param_local_tys ~dynamic_mode:false ~no_auto_likes env params_decl_ty m.m_params in Typing_memoize.check_method env m; 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 m.m_ctxs param_tys m.m_params in let ret_locl_ty = return.Typing_env_return_info.return_type.et_type in let env = set_tyvars_variance_in_callable env ret_locl_ty param_tys in let local_tpenv = Env.get_tpenv env in let disable = Naming_attributes.mem SN.UserAttributes.uaDisableTypecheckerInternal m.m_user_attributes in let ((env, tb), had_errors) = Errors.run_and_check_for_errors (fun () -> Typing.fun_ ~abstract:m.m_abstract ~native:(Typing_native.is_native_meth ~env m) ~disable env return pos m.m_body m.m_fun_kind) in let type_hint' = match hint_of_type_hint m.m_ret with | None when String.equal method_name SN.Members.__construct -> Some (pos, Hprim Tvoid) | None -> Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.Expecting_return_type_hint pos); None | Some _ -> hint_of_type_hint m.m_ret in let m = { m with m_ret = (fst m.m_ret, type_hint') } in let (env, tparams) = List.map_env env m.m_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 return_hint = hint_of_type_hint m.m_ret in let under_normal_assumptions = { Aast.m_annotation = Env.save local_tpenv env; Aast.m_span = m.m_span; Aast.m_final = m.m_final; Aast.m_static = m.m_static; Aast.m_abstract = m.m_abstract; Aast.m_visibility = m.m_visibility; Aast.m_readonly_this = m.m_readonly_this; Aast.m_name = m.m_name; Aast.m_tparams = tparams; Aast.m_where_constraints = m.m_where_constraints; Aast.m_params = typed_params; Aast.m_ctxs = m.m_ctxs; Aast.m_unsafe_ctxs = m.m_unsafe_ctxs; Aast.m_fun_kind = m.m_fun_kind; Aast.m_user_attributes = user_attributes; Aast.m_readonly_ret = m.m_readonly_ret; Aast.m_ret = (ret_locl_ty, return_hint); Aast.m_body = { Aast.fb_ast = tb }; Aast.m_external = m.m_external; Aast.m_doc_comment = m.m_doc_comment; } in let sdt_dynamic_check_required = sdt_dynamic_check_required && (not had_errors) && not @@ (* Add `dynamic` lower and upper bound to any type parameters that are marked <<__RequireDynamic>> *) let env_with_require_dynamic = Typing_dynamic.add_require_dynamic_bounds sound_dynamic_check_saved_env cls in Typing_dynamic.sound_dynamic_interface_check ~this_class:(Some cls) env_with_require_dynamic params_decl_ty return.Typing_env_return_info.return_type.et_type in let method_def_of_dynamic (dynamic_env, dynamic_params, dynamic_body, dynamic_return_ty) = let open Aast in { under_normal_assumptions with m_annotation = Env.save local_tpenv dynamic_env; m_params = dynamic_params; m_body = { Aast.fb_ast = dynamic_body }; m_ret = (dynamic_return_ty, return_hint); } in let (env, under_normal_assumptions, under_dynamic_assumptions) = if sdt_dynamic_check_required && not (TCO.skip_check_under_dynamic tcopt) then let env = { env with checked = Tast.CUnderNormalAssumptions } in let under_normal_assumptions = Aast. { under_normal_assumptions with m_annotation = Env.save local_tpenv env; } in let dynamic_components = method_dynamically_callable sound_dynamic_check_saved_env cls m params_decl_ty return in ( env, under_normal_assumptions, Some (method_def_of_dynamic dynamic_components) ) else (env, under_normal_assumptions, None) in let _env = Env.log_env_change "method_def" initial_env env 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 } (** Checks that extending this parent is legal - e.g. it is not final and not const. *) let check_parent env class_def class_type = match Env.get_parent_class env with | Some parent_type -> let position = fst class_def.c_name in if Cls.const class_type && not (Cls.const parent_type) then Typing_error_utils.add_typing_error ~env Typing_error.(primary @@ Primary.Self_const_parent_not position); if Cls.final parent_type then Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Extend_final { pos = position; decl_pos = Cls.pos parent_type; name = Cls.name parent_type; }) | None -> () let sealed_subtype ctx (c : Nast.class_) ~is_enum ~hard_error ~env = let parent_name = snd c.c_name in let is_sealed (attr : Nast.user_attribute) = String.equal (snd attr.ua_name) SN.UserAttributes.uaSealed in match List.find c.c_user_attributes ~f:is_sealed with | None -> () | Some sealed_attr -> let iter_item ((_, pos, expr_) : Nast.expr) = match expr_ with | Class_const ((_, _, cid), _) -> let klass_name = Nast.class_id_to_str cid in let klass = Decl_provider.get_class ctx klass_name in (match klass with | None -> () | Some decl -> let includes_ancestor = if is_enum then match Cls.enum_type decl with | None -> true | Some enum_ty -> let check x = match get_node x with | Tapply ((_, name), _) -> String.equal name parent_name | _ -> true in List.exists enum_ty.te_includes ~f:check else Cls.has_ancestor decl parent_name in if not includes_ancestor then let parent_pos = pos in let child_pos = Cls.pos decl in let child_name = Cls.name decl in let class_kind = Cls.kind decl in let (child_kind, verb) = match class_kind with | Ast_defs.Cclass _ -> ("Class", "extend") | Ast_defs.Cinterface -> ("Interface", "implement") | Ast_defs.Ctrait -> ("Trait", "use") | Ast_defs.Cenum -> ("Enum", "use") | Ast_defs.Cenum_class _ -> ("Enum Class", "extend") in if hard_error then Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Sealed_not_subtype { pos = parent_pos; child_pos; name = parent_name; child_name; child_kind = class_kind; }) else Lint.sealed_not_subtype verb parent_pos parent_name child_name child_kind) (* unit below is fine because error cases are handled as Parsing[1002] *) | _ -> () in List.iter sealed_attr.ua_params ~f:iter_item let check_parent_sealed (child_pos, child_type) parent_type ~env = match Cls.sealed_whitelist parent_type with | None -> () | Some whitelist -> let parent_pos = Cls.pos parent_type in let parent_name = Cls.name parent_type in let child_name = Cls.name child_type in let check parent_kind verb = if not (SSet.mem child_name whitelist) then Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Extend_sealed { pos = child_pos; parent_pos; parent_name; parent_kind; verb }) in begin match (Cls.kind parent_type, Cls.kind child_type) with | (Ast_defs.Cinterface, Ast_defs.Cinterface) -> check `intf `extend | (Ast_defs.Cinterface, _) -> check `intf `implement | (Ast_defs.Ctrait, _) -> check `trait `use | (Ast_defs.Cclass _, _) -> check `class_ `extend | (Ast_defs.Cenum_class _, _) -> check `enum_class `extend | (Ast_defs.Cenum, _) -> check `enum `use end let check_parents_sealed env child_def child_type = let parents = match child_def.c_enum with | Some enum -> enum.e_includes | None -> child_def.c_extends in let parents = parents @ child_def.c_implements @ child_def.c_uses in List.iter parents ~f:(function | (_, Happly ((_, name), _)) -> begin match Env.get_class env name with | Some parent_type -> check_parent_sealed (fst child_def.c_name, child_type) parent_type ~env | None -> () end | _ -> ()) (* Reject multiple instantiations of the same generic interface * in extends and implements clauses. * e.g. disallow class C implements I<string>, I<int> * * O(n^2) but we don't expect number of instantiated interfaces to be large *) let rec check_implements_or_extends_unique impl ~env = match impl with | [] -> () | (hint, ty) :: rest -> (match get_node ty with | Tapply ((_, name), _ :: _) -> let (pos_list, rest) = List.partition_map rest ~f:(fun (h, ty) -> match get_node ty with | Tapply ((pos', name'), _) when String.equal name name' -> First pos' | _ -> Second (h, ty)) in if not (List.is_empty pos_list) then Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Duplicate_interface { pos = fst hint; name; others = pos_list }); check_implements_or_extends_unique rest ~env | _ -> check_implements_or_extends_unique rest ~env) (** Add a dependency to constructors or produce an error if not a Tapply. *) let check_is_tapply_add_constructor_extends_dep env ?(skip_constructor_dep = false) deps = List.iter deps ~f:(fun ((p, _dep_hint), dep) -> match get_node dep with | Tapply ((_, class_name), _) -> Env.add_parent_dep env ~skip_constructor_dep class_name | Tgeneric _ -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Expected_class { suffix = Some (lazy " or interface but got a generic"); pos = p; }) | _ -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Expected_class { suffix = Some (lazy " or interface"); pos = p })) (** For const classes, check that members from traits are all constant. *) let check_non_const_trait_members pos env use_list = let ((_, trait, _), err_opt) = Decl_utils.unwrap_class_hint use_list in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) err_opt; match Env.get_class env trait with | Some c when Ast_defs.is_c_trait (Cls.kind c) -> List.iter (Cls.props c) ~f:(fun (x, ce) -> if not (get_ce_const ce) then Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Trait_prop_const_class { pos; name = x })) | _ -> () let check_consistent_enum_inclusion included_cls ((dest_cls_pos, dest_cls) : Pos.t * Cls.t) ~env = let included_kind = Cls.kind included_cls in let dest_kind = Cls.kind dest_cls in match (Cls.enum_type included_cls, Cls.enum_type dest_cls) with | (Some included_e, Some dest_e) -> (* ensure that the base types are identical *) if not (Typing_defs.equal_decl_ty included_e.te_base dest_e.te_base) then Typing_error_utils.add_typing_error ~env Typing_error.( enum @@ Primary.Enum.Incompatible_enum_inclusion_base { pos = dest_cls_pos; classish_name = Cls.name dest_cls; src_classish_name = Cls.name included_cls; }); (* ensure that the visibility constraint are compatible *) (match (included_e.te_constraint, dest_e.te_constraint) with | (None, Some _) -> Typing_error_utils.add_typing_error ~env Typing_error.( enum @@ Primary.Enum.Incompatible_enum_inclusion_constraint { pos = dest_cls_pos; classish_name = Cls.name dest_cls; src_classish_name = Cls.name included_cls; }) | (_, _) -> ()); (* ensure normal enums can't include enum classes *) if Ast_defs.is_c_enum_class included_kind && not (Ast_defs.is_c_enum_class dest_kind) then Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Wrong_extend_kind { parent_pos = Cls.pos included_cls; parent_kind = included_kind; parent_name = Cls.name included_cls; pos = dest_cls_pos; kind = dest_kind; name = Cls.name dest_cls; }) | (None, _) -> Typing_error_utils.add_typing_error ~env Typing_error.( enum @@ Primary.Enum.Enum_inclusion_not_enum { pos = dest_cls_pos; classish_name = Cls.name dest_cls; src_classish_name = Cls.name included_cls; }) | (_, _) -> () let is_enum_or_enum_class k = Ast_defs.is_c_enum k || Ast_defs.is_c_enum_class k let check_enum_includes env cls = let is_abstract = function | CCAbstract has_default -> not has_default | CCConcrete -> false in (* checks that there are no duplicated enum-constants when folded-decls are enabled *) if is_enum_or_enum_class cls.c_kind then ( let (dest_class_pos, dest_class_name) = cls.c_name in let enum_constant_map = ref SMap.empty in (* prepopulate the map with the constants declared in cls *) List.iter cls.c_consts ~f:(fun cc -> enum_constant_map := SMap.add (snd cc.cc_id) (fst cc.cc_id, dest_class_name) !enum_constant_map); (* for all included enums *) let included_enums = Aast.enum_includes_map cls.c_enum ~f:(fun ce -> List.filter_map ce.e_includes ~f:(fun ie -> match snd ie with | Happly (sid, _) -> (match Env.get_class env (snd sid) with | None -> None | Some ie_cls -> Some (fst ie, ie_cls)) | _ -> None)) in List.iter included_enums ~f:(fun (ie_pos, ie_cls) -> let src_class_name = Cls.name ie_cls in (* 1. Check for consistency *) (match Env.get_class env dest_class_name with | None -> () | Some cls -> check_consistent_enum_inclusion ie_cls (ie_pos, cls) ~env); (* 2. Check for duplicates *) List.iter (Cls.consts ie_cls) ~f:(fun (const_name, class_const) -> (if String.equal const_name "class" then () (* TODO: Check with @fzn *) else if is_abstract class_const.cc_abstract then () else if SMap.mem const_name !enum_constant_map then (* distinguish between multiple inherit and redeclare *) let (origin_const_pos, origin_class_name) = SMap.find const_name !enum_constant_map in if String.equal origin_class_name dest_class_name then (* redeclare *) Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Redeclaring_classish_const { pos = dest_class_pos; classish_name = dest_class_name; redeclaration_pos = origin_const_pos; existing_const_origin = src_class_name; const_name; }) else if String.( <> ) origin_class_name class_const.cc_origin then (* check for diamond inclusion, if not raise an error about multiple inherit *) Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Reinheriting_classish_const { pos = dest_class_pos; classish_name = dest_class_name; src_pos = ie_pos; src_classish_name = src_class_name; existing_const_origin = origin_class_name; const_name; })); enum_constant_map := SMap.add const_name (dest_class_pos, class_const.cc_origin) !enum_constant_map)) ) let skip_hierarchy_checks (ctx : Provider_context.t) : bool = TCO.skip_hierarchy_checks (Provider_context.get_tcopt ctx) let class_type_param env ct = let (env, tparam_list) = List.map_env env ct ~f:Typing.type_param in (env, tparam_list) (** Check whether the type of a static property (class variable) contains any generic type parameters. Outside of traits, this is illegal as static * properties are shared across all generic instantiations. *) let check_no_generic_static_property env tc = if Ast_defs.is_c_trait (Cls.kind tc) then () else Cls.sprops tc |> List.iter ~f:(fun (_prop_name, prop) -> let (lazy ty) = prop.ce_type in let var_ty_pos = get_pos ty in let class_pos = Cls.pos tc in match TUtils.contains_generic_decl ty with | None -> () | Some generic_pos -> Option.iter (* If the static property is inherited from another trait, the position may be * in a different file. *) (Env.fill_in_pos_filename_if_in_current_decl env generic_pos) ~f:(fun generic_pos -> Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Static_prop_type_generic_param { class_pos; var_ty_pos; pos = generic_pos }))) let typeconst_def cls env { c_tconst_name = (pos, _) as id; c_tconst_kind; c_tconst_user_attributes; c_tconst_span; c_tconst_doc_comment; c_tconst_is_ctx; } = let tcopt = Env.get_tcopt env in Profile.measure_elapsed_time_and_report tcopt (Some env) id @@ fun () -> (if Ast_defs.is_c_enum cls.c_kind then let (class_pos, class_name) = cls.c_name in Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Cannot_declare_constant { pos; class_pos; class_name })); let name = snd cls.c_name ^ "::" ^ snd id in (* Check constraints and report cycles through the definition *) let (env, ty_err_opt) = match c_tconst_kind with | TCAbstract { c_atc_as_constraint; c_atc_super_constraint; c_atc_default = Some ty } -> let ((env, ty_err_opt1), ty) = Phase.localize_hint_no_subst ~ignore_errors:false ~report_cycle:(pos, name) env ty in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) ty_err_opt1; let (env, ty_err_opt2) = match c_atc_as_constraint with | Some as_ -> let ((env, ty_err_opt1), as_) = Phase.localize_hint_no_subst ~ignore_errors:false env as_ in let (env, ty_err_opt2) = Type.sub_type pos Reason.URtypeconst_cstr env ty as_ Typing_error.Callback.unify_error in (env, Option.merge ~f:Typing_error.both ty_err_opt1 ty_err_opt2) | None -> (env, None) in let (env, ty_err_opt3) = match c_atc_super_constraint with | Some super -> let ((env, te1), super) = Phase.localize_hint_no_subst ~ignore_errors:false env super in let (env, te2) = Type.sub_type pos Reason.URtypeconst_cstr env super ty Typing_error.Callback.unify_error in (env, Option.merge ~f:Typing_error.both te1 te2) | None -> (env, None) 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) | TCConcrete { c_tc_type = ty } -> let (env, _ty) = Phase.localize_hint_no_subst ~ignore_errors:false ~report_cycle:(pos, name) env ty in env | _ -> (env, None) in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); (* TODO(T88552052): should this check be happening for defaults * Does this belong here at all? *) let env = match c_tconst_kind with | TCConcrete { c_tc_type = (_, Hshape { nsi_field_map; _ }) } | TCAbstract { c_atc_default = Some (_, Hshape { 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.typeconst c_tconst_user_attributes in ( env, { Aast.c_tconst_name = id; Aast.c_tconst_kind; Aast.c_tconst_user_attributes = user_attributes; Aast.c_tconst_span; Aast.c_tconst_doc_comment; Aast.c_tconst_is_ctx; } ) let class_const_def ~in_enum_class c cls env cc = let tcopt = Env.get_tcopt env in Profile.measure_elapsed_time_and_report tcopt (Some env) cc.cc_id @@ fun () -> let { cc_type = h; cc_id = id; cc_kind = k; _ } = cc in let (env, hint_ty, opt_expected) = match h with | None -> begin match k with | CCAbstract _ when (not (is_enum_or_enum_class c.c_kind)) && TCO.require_types_class_consts tcopt > 0 -> Errors.add_error Naming_error.(to_user_error @@ Missing_typehint (fst id)) | _ when (not (is_enum_or_enum_class c.c_kind)) && TCO.require_types_class_consts tcopt > 1 -> Errors.add_error Naming_error.(to_user_error @@ Missing_typehint (fst id)) | CCAbstract None -> () | CCAbstract (Some e (* default *)) | CCConcrete e -> if (not (is_literal_with_trivially_inferable_type e)) && (not (is_enum_or_enum_class c.c_kind)) && not (Env.is_hhi env) then Errors.add_error Naming_error.(to_user_error @@ Missing_typehint (fst id)) end; let (env, ty) = Env.fresh_type env (fst id) in (env, MakeType.unenforced ty, None) | Some h -> let ty = Decl_hint.hint env.decl_env h in let ty = Typing_enforceability.compute_enforced_ty ~this_class:(Some cls) env ty in let ((env, ty_err_opt), ty) = Phase.localize_possibly_enforced_no_subst env ~ignore_errors:false ty in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); (* Removing the HH\MemberOf wrapper in case of enum classes so the * following call to expr_* has the right expected type *) let opt_ty = if in_enum_class then match get_node ty.et_type with | Tnewtype (memberof, [_; et_type], _) when String.equal memberof SN.Classes.cMemberOf -> { ty with et_type } | _ -> ty else ty in ( env, ty, Some (ExpectedTy.make_and_allow_coercion (fst id) Reason.URhint opt_ty) ) in let check env ty' = (* Lifted out to closure to illustrate which variables are captured *) Typing_coercion.coerce_type (fst id) Reason.URhint env ty' hint_ty Typing_error.Callback.class_constant_value_does_not_match_hint in let type_and_check env e = let (env, (te, ty')) = Typing.( expr_with_pure_coeffects ?expected:opt_expected env e |> triple_to_pair) in let env = check env ty' in (env, te, ty') in let ((env, ty_err_opt), kind, ty) = match k with | CCConcrete ((_, e_pos, _) as e) when in_enum_class -> let (env, cap, unsafe_cap) = (* Enum class constant initializers are restricted to be `write_props` *) let make_hint pos s = (pos, Aast.Happly ((pos, s), [])) in let enum_class_ctx = Some (e_pos, [make_hint e_pos SN.Capabilities.write_props]) in Typing_coeffects.type_capability env enum_class_ctx enum_class_ctx e_pos in let (env, (te, ty')) = Typing.( with_special_coeffects env cap unsafe_cap @@ fun env -> expr env ?expected:opt_expected e |> triple_to_pair) in let (te, ty') = match deref hint_ty.et_type with | (r, Tnewtype (memberof, [enum_name; _], _)) when String.equal memberof SN.Classes.cMemberOf -> let lift r ty = mk (r, Tnewtype (memberof, [enum_name; ty], ty)) in let (te_ty, p, te) = te in let te = (lift (get_reason te_ty) te_ty, p, te) in let ty' = lift r ty' in (te, ty') | _ -> (te, ty') in let env = check env ty' in (env, Aast.CCConcrete te, ty') | CCConcrete ((_, _, Omitted) as e) when Env.is_hhi env -> (* We don't require class 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 e in ((env, None), CCConcrete te, hint_ty.et_type) | CCConcrete e -> let (env, te, ty') = type_and_check env e in (env, Aast.CCConcrete te, ty') | CCAbstract (Some default) -> let (env, tdefault, ty') = type_and_check env default in (env, CCAbstract (Some tdefault), ty') | CCAbstract None -> ((env, None), CCAbstract None, hint_ty.et_type) in let (env, user_attributes) = if Ast_defs.is_c_class c.Aast.c_kind || Ast_defs.is_c_trait c.Aast.c_kind then Typing.attributes_check_def env SN.AttributeKinds.clscst cc.cc_user_attributes else begin assert (List.is_empty cc.cc_user_attributes); (env, []) end in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); ( env, ( { Aast.cc_type = cc.cc_type; Aast.cc_id = cc.cc_id; Aast.cc_kind = kind; Aast.cc_span = cc.cc_span; Aast.cc_doc_comment = cc.cc_doc_comment; Aast.cc_user_attributes = user_attributes; }, ty ) ) let class_constr_def ~is_disposable env cls constructor = let env = { env with inside_constructor = true } in Option.bind constructor ~f:(method_def ~is_disposable env cls) (** Type-check a property declaration, with optional initializer *) let class_var_def ~is_static ~is_noautodynamic cls env cv = let tcopt = Env.get_tcopt env in Profile.measure_elapsed_time_and_report tcopt (Some env) cv.cv_id @@ fun () -> (* First pick up and localize the hint if it exists *) let decl_cty = FunUtils.hint_to_type_opt env.decl_env (hint_of_type_hint cv.cv_type) in let no_auto_likes = Naming_attributes.mem SN.UserAttributes.uaNoAutoLikes cv.cv_user_attributes in let (env, expected) = match decl_cty with | None -> (env, None) | Some decl_cty -> let decl_cty = Typing_enforceability.compute_enforced_ty ~this_class:(Some cls) env decl_cty in let ((env, ty_err_opt), cty) = Phase.localize_possibly_enforced_no_subst env ~ignore_errors:false decl_cty in let cty = match cty.et_enforced with | Enforced when is_none cv.cv_xhp_attr -> cty | _ -> let add_like = (not is_noautodynamic) && not no_auto_likes in if TCO.everything_sdt env.genv.tcopt && add_like then { cty with et_type = TUtils.make_like env cty.et_type } else ( if add_like then Typing_log.log_pessimise_prop env (fst cv.cv_id) (snd cv.cv_id); cty ) in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let expected = Some (ExpectedTy.make_and_allow_coercion cv.cv_span Reason.URhint cty) in (env, expected) in (* Next check the expression, passing in expected type if present *) let ((env, ty_err_opt), typed_cv_expr) = match cv.cv_expr with | None -> ((env, None), None) | Some e -> let (env, te, ty) = Typing.expr_with_pure_coeffects env ?expected e in (* Check that the inferred type is a subtype of the expected type. * Eventually this will be the responsibility of `expr` *) let env = match expected with | None -> (env, None) | Some ExpectedTy.{ pos = p; reason = ur; ty = cty; coerce } -> Typing_coercion.coerce_type ~coerce p ur env ty cty Typing_error.Callback .class_property_initializer_type_does_not_match_hint in (env, Some te) in Option.iter ty_err_opt ~f:(Typing_error_utils.add_typing_error ~env); let (env, user_attributes) = Typing.attributes_check_def env (if is_static then SN.AttributeKinds.staticProperty else SN.AttributeKinds.instProperty) cv.cv_user_attributes in (if Option.is_none (hint_of_type_hint cv.cv_type) then let vis = match cv.cv_visibility with | Public -> Naming_error.Vpublic | Private -> Naming_error.Vprivate | Internal -> Naming_error.Vinternal | Protected -> Naming_error.Vprotected in let (pos, prop_name) = cv.cv_id in Errors.add_error Naming_error.( to_user_error @@ Prop_without_typehint { vis; pos; prop_name })); let ((cv_type_ty, _) as cv_type) = match expected with | Some expected -> (expected.ExpectedTy.ty.et_type, hint_of_type_hint cv.cv_type) | None -> Tast.dummy_type_hint (hint_of_type_hint cv.cv_type) in (* if the class implements dynamic, then check that the type of the property * is enforceable (for writing) and coerces to dynamic (for reading) *) if TCO.enable_sound_dynamic (Provider_context.get_tcopt (Env.get_ctx env)) && Cls.get_support_dynamic_type cls && not (Aast.equal_visibility cv.cv_visibility Private) then ( let env_with_require_dynamic = Typing_dynamic.add_require_dynamic_bounds env cls in Option.iter ~f:(Typing_error_utils.add_typing_error ~env) @@ Option.bind decl_cty ~f:(fun ty -> Typing_dynamic.check_property_sound_for_dynamic_write ~this_class:(Some cls) ~on_error:(fun pos prop_name class_name (prop_pos, prop_type) -> Typing_error.( primary @@ Primary.Property_is_not_enforceable { pos; prop_name; class_name; prop_pos; prop_type })) env_with_require_dynamic (Cls.name cls) cv.cv_id ty (Some cv_type_ty)); Option.iter ~f:(Typing_error_utils.add_typing_error ~env) @@ Typing_dynamic.check_property_sound_for_dynamic_read ~on_error:(fun pos prop_name class_name (prop_pos, prop_type) -> Typing_error.( primary @@ Primary.Property_is_not_dynamic { pos; prop_name; class_name; prop_pos; prop_type })) env_with_require_dynamic (Cls.name cls) cv.cv_id cv_type_ty ); ( env, { Aast.cv_final = cv.cv_final; Aast.cv_xhp_attr = cv.cv_xhp_attr; Aast.cv_abstract = cv.cv_abstract; Aast.cv_visibility = cv.cv_visibility; Aast.cv_type; Aast.cv_id = cv.cv_id; Aast.cv_expr = typed_cv_expr; Aast.cv_user_attributes = user_attributes; Aast.cv_is_promoted_variadic = cv.cv_is_promoted_variadic; Aast.cv_doc_comment = cv.cv_doc_comment; (* Can make None to save space *) Aast.cv_is_static = is_static; Aast.cv_span = cv.cv_span; Aast.cv_readonly = cv.cv_readonly; } ) (** Check the where constraints of the parents of a class *) let check_class_parents_where_constraints env pc impl = let check_where_constraints env ((p, _hint), decl_ty) = let ((env, ty_err_opt1), locl_ty) = Phase.localize_no_subst env ~ignore_errors:false decl_ty in Option.iter ty_err_opt1 ~f:(Typing_error_utils.add_typing_error ~env); match get_node (TUtils.get_base_type env locl_ty) with | Tclass (cls, _, tyl) -> (match Env.get_class env (snd cls) with | Some cls when not (List.is_empty (Cls.where_constraints cls)) -> let tc_tparams = Cls.tparams cls in let ety_env = { (empty_expand_env_with_on_error (Env.unify_error_assert_primary_pos_in_current_decl env)) with substs = Subst.make_locl tc_tparams tyl; } in let (env, ty_err_opt2) = Phase.check_where_constraints ~in_class:true ~use_pos:pc ~definition_pos:(Pos_or_decl.of_raw_pos p) ~ety_env env (Cls.where_constraints cls) in Option.iter ty_err_opt2 ~f:(Typing_error_utils.add_typing_error ~env); env | _ -> env) | _ -> env in List.fold impl ~init:env ~f:check_where_constraints let check_generic_class_with_SupportDynamicType env c parents = let (pc, c_name) = c.c_name in let check_support_dynamic_type = Naming_attributes.mem SN.UserAttributes.uaSupportDynamicType c.c_user_attributes in if TCO.enable_sound_dynamic (Provider_context.get_tcopt (Env.get_ctx env)) && check_support_dynamic_type then ( (* Any class that extends a class or implements an interface * that declares <<__SupportDynamicType>> must itself declare * <<__SupportDynamicType>>. This is checked elsewhere. But if any generic * parameters are marked <<__RequireDynamic>> then we must check that the * conditional support for dynamic is sound. * We require that * If t <: dynamic * and C<T1,..,Tn> extends t * then C<T1,...,Tn> <: dynamic *) let dynamic_ty = MakeType.supportdyn_mixed (Reason.Rdynamic_coercion (Reason.Rwitness pc)) in let (env, ty_errs) = List.fold parents ~init:(env, []) ~f:(fun (env, ty_errs) (_, ty) -> let ((env, ty_err_opt1), lty) = Phase.localize_no_subst env ~ignore_errors:true ty in let (env, ty_err_opt2) = match get_node lty with | Tclass ((_, name), _, _) -> begin match Env.get_class env name with | Some c when Cls.get_support_dynamic_type c -> let env_with_assumptions = Typing_subtype.add_constraint env Ast_defs.Constraint_as lty dynamic_ty @@ Some (Typing_error.Reasons_callback.unify_error_at pc) in begin match Env.get_self_ty env with | Some self_ty -> TUtils.supports_dynamic env_with_assumptions self_ty @@ Some (Typing_error.Reasons_callback .bad_conditional_support_dynamic pc ~child:c_name ~parent:name ~ty_name: (lazy (Typing_print.full_strip_ns_decl env ty)) ~self_ty_name: (lazy (Typing_print.full_strip_ns env self_ty))) | _ -> (env, None) end | _ -> (env, None) end | _ -> (env, None) in let ty_errs = Option.( value_map ~default:ty_errs ~f:(fun e -> e :: ty_errs) @@ merge ~f:Typing_error.both ty_err_opt1 ty_err_opt2) in (env, ty_errs)) in Option.( iter ~f:(Typing_error_utils.add_typing_error ~env) @@ Typing_error.multiple_opt ty_errs); env ) else env let check_SupportDynamicType env c tc = if TCO.enable_sound_dynamic (Provider_context.get_tcopt (Env.get_ctx env)) then let support_dynamic_type = Naming_attributes.mem SN.UserAttributes.uaSupportDynamicType c.c_user_attributes in let error_parent_support_dynamic_type parent child_support_dyn = Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Parent_support_dynamic_type { pos = fst c.c_name; child_name = snd c.c_name; child_kind = c.c_kind; parent_name = Cls.name parent; parent_kind = Cls.kind parent; child_support_dyn; }) in match c.c_kind with | Ast_defs.(Cenum | Cenum_class _) -> (* Avoid parent SDT check on things that cannot be SDT themselves *) () | Ast_defs.Cclass _ | Ast_defs.Cinterface | Ast_defs.Ctrait -> List.iter (Cls.all_ancestor_names tc) ~f:(fun name -> match Env.get_class env name with | Some parent_type -> begin match Cls.kind parent_type with | Ast_defs.Cclass _ | Ast_defs.Cinterface -> (* ensure that we implement dynamic if we are a subclass/subinterface of a class/interface * that implements dynamic. Upward well-formedness checks are performed in Typing_extends *) if Cls.get_support_dynamic_type parent_type && not support_dynamic_type then error_parent_support_dynamic_type parent_type support_dynamic_type | Ast_defs.(Cenum | Cenum_class _ | Ctrait) -> () end | None -> ()) (** Check methods with <<__Override>> have a corresponding overridden method. *) let check_override_has_parent (c : ('a, 'b) class_) (tc : Cls.t) ~env : unit = if not Ast_defs.(is_c_trait c.c_kind) then (* We don't want to check __Override on traits. __Override on traits asserts that the *using* class has an inherited method that we're overriding. *) List.iter c.c_methods ~f:(fun m -> let id = snd m.m_name in match Cls.get_any_method ~is_static:m.m_static tc id with | Some ce -> begin if get_ce_superfluous_override ce then Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Should_not_be_override { pos = fst m.m_name; class_id = snd c.c_name; id }) end | None -> ()) (** Check __Override on class methods included from traits. *) let check_used_methods_with_override env c (tc : Cls.t) : unit = let (class_pos, class_name) = c.c_name in let check_override ~is_static (meth_name, ce) = if get_ce_superfluous_override ce && not (String.equal ce.ce_origin class_name) then match Env.get_class env ce.ce_origin with | Some parent_class when Ast_defs.(is_c_trait (Cls.kind parent_class)) -> (* If we've included a method from a trait that has __Override, but there's no inherited method on this class that we're overridding, that's an error. *) Typing_error_utils.add_typing_error ~env Typing_error.( primary @@ Primary.Override_per_trait { pos = class_pos; class_name; meth_name; trait_name = ce.ce_origin; meth_pos = (let get_meth = if is_static then Decl_store.((get ()).get_static_method) else Decl_store.((get ()).get_method) in match get_meth (ce.ce_origin, meth_name) with | Some { fe_pos; _ } -> fe_pos | None -> Pos_or_decl.none); }) | _ -> () in if not Ast_defs.(is_c_trait c.c_kind) then ( List.iter (Cls.methods tc) ~f:(check_override ~is_static:false); List.iter (Cls.smethods tc) ~f:(check_override ~is_static:true) ) (** Check proper usage of the __Override attribute. *) let check_override_keyword env c tc = check_override_has_parent c tc ~env; check_used_methods_with_override env c tc let check_sealed env c = let hard_error = TCO.enforce_sealed_subclasses (Env.get_tcopt env) in let is_enum = is_enum_or_enum_class c.c_kind in sealed_subtype (Env.get_ctx env) c ~is_enum ~hard_error ~env let check_class_where_require_class_constraints env c tc = let (pc, _) = c.c_name in let req_class_constraints = List.filter_map c.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 let (env, ty_err_opt1) = Phase.localize_and_add_ast_generic_parameters_and_where_constraints env ~ignore_errors:false c.c_tparams (c.c_where_constraints @ req_class_constraints) in Option.iter ty_err_opt1 ~f:(Typing_error_utils.add_typing_error ~env); let (env, ty_err_opt2) = Phase.check_where_constraints ~in_class:true ~use_pos:pc ~definition_pos:(Pos_or_decl.of_raw_pos pc) ~ety_env: (empty_expand_env_with_on_error (Env.unify_error_assert_primary_pos_in_current_decl env)) env (Cls.where_constraints tc) in Option.iter ty_err_opt2 ~f:(Typing_error_utils.add_typing_error ~env); env type class_parents = { extends: (Aast.hint * decl_ty) list; implements: (Aast.hint * decl_ty) list; uses: (Aast.hint * decl_ty) list; req_extends: (Aast.hint * decl_ty) list; req_implements: (Aast.hint * decl_ty) list; req_class: (Aast.hint * decl_ty) list; enum_includes: (Aast.hint * decl_ty) list option; xhp_attr_uses: (Aast.hint * decl_ty) list; } let class_parents_hints_to_types env c : class_parents = let hints_and_decl_tys hints = List.map hints ~f:(fun hint -> (hint, Decl_hint.hint env.decl_env hint)) in let extends = hints_and_decl_tys c.c_extends in let implements = hints_and_decl_tys c.c_implements in let uses = hints_and_decl_tys c.c_uses in let (req_extends, req_implements, req_class) = split_reqs c.c_reqs in let req_extends = hints_and_decl_tys req_extends in let req_implements = hints_and_decl_tys req_implements in let req_class = hints_and_decl_tys req_class in let enum_includes = Option.map c.c_enum ~f:(fun e -> hints_and_decl_tys e.e_includes) in let xhp_attr_uses = hints_and_decl_tys c.c_xhp_attr_uses in { extends; implements; uses; req_extends; req_implements; req_class; enum_includes; xhp_attr_uses; } (** Add dependencies to parent constructors or produce errors if they're not a Tapply. *) let check_parents_are_tapply_add_constructor_deps env c (parents : class_parents) = let { extends; implements; uses; req_extends; req_implements; req_class; enum_includes; xhp_attr_uses; } = parents in check_is_tapply_add_constructor_extends_dep env extends; check_is_tapply_add_constructor_extends_dep env implements ~skip_constructor_dep: (not (Ast_defs.is_c_trait c.c_kind || Ast_defs.is_c_abstract c.c_kind)); check_is_tapply_add_constructor_extends_dep env uses; check_is_tapply_add_constructor_extends_dep env req_class; check_is_tapply_add_constructor_extends_dep env req_extends; check_is_tapply_add_constructor_extends_dep env req_implements; Option.iter enum_includes ~f:(check_is_tapply_add_constructor_extends_dep env); check_is_tapply_add_constructor_extends_dep env xhp_attr_uses ~skip_constructor_dep:true; () let check_class_attributes env ~cls = let (env, user_attributes) = let kind = if Ast_defs.is_c_enum cls.c_kind then SN.AttributeKinds.enum else if Ast_defs.is_c_enum_class cls.c_kind then SN.AttributeKinds.enumcls else SN.AttributeKinds.cls in Typing.attributes_check_def env kind cls.c_user_attributes in let (env, file_attrs) = Typing.file_attributes env cls.c_file_attributes in (env, (user_attributes, file_attrs)) (** Check type parameter definition, including variance, and add constraints to the environment. *) let check_class_type_parameters_add_constraints env c tc = let env = check_class_where_require_class_constraints env c tc in Typing_variance.class_def env c; env (** Check wellformedness of all type hints in the class. *) let check_hint_wellformedness_in_class env c parents = let { extends; implements; uses; _ } = parents in let (pc, _) = c.c_name in check_parents_are_tapply_add_constructor_deps env c parents; List.iter ~f:(Typing_error_utils.add_typing_error ~env) @@ Typing_type_wellformedness.class_ env c; let env = check_class_parents_where_constraints env pc (extends @ implements @ uses) in env (** Perform all class wellformedness checks which don't involve the hierarchy: - attributes - property initialization checks - type parameter checks - type hint wellformedness - generic static properties *) let class_wellformedness_checks env c tc (parents : class_parents) = (* Class and file level attributes are ran outside of the class context and thus should not have access to `self` in the environment, so we unset self while running these attribute checks. Note: This has the side effect of allowing internal classes to be referenced on class-level attributes that are applied to a public trait. This is intended and safe because class-level attributes are not copied to the use site of a trait.*) let (env, (user_attributes, file_attrs)) = Env.run_with_no_self env (check_class_attributes ~cls:c) in NastInitCheck.class_ env c; let env = check_class_type_parameters_add_constraints env c tc in let env = check_hint_wellformedness_in_class env c parents in check_no_generic_static_property env tc; (env, user_attributes, file_attrs) (** Perform all hierarchy checks, i.e. checking that making this class a child of its parents is legal: - requirements from `require` statements - duplicate parents - parents can have children (not final or const) - __Sealed attribute - dynamic-type related attributes w.r.t. parents - __Disposable attribute w.r.t. parents - individual member checks: - subtyping parent members - __Override attribute check - enum inclusions - abstract members in concrete class - non-const members in const class *) let class_hierarchy_checks env c tc (parents : class_parents) = if skip_hierarchy_checks (Env.get_ctx env) then env else let (pc, _) = c.c_name in let { extends; implements; uses; req_extends; req_implements; req_class = _; enum_includes = _; xhp_attr_uses = _; } = parents in let env = Typing_requirements.check_class env pc tc in check_override_keyword env c tc; check_enum_includes env c; check_implements_or_extends_unique implements ~env; check_implements_or_extends_unique extends ~env; check_parent env c tc; check_parents_sealed env c tc; check_sealed env c; let (_ : env) = check_generic_class_with_SupportDynamicType env c (extends @ implements) in if Cls.const tc then List.iter c.c_uses ~f:(check_non_const_trait_members pc env); let impl = extends @ implements @ uses in let impl = if TCO.require_extends_implements_ancestors (Env.get_tcopt env) then impl @ req_extends @ req_implements else impl in let env = Typing_extends.check_implements_extends_uses env ~implements:(List.map implements ~f:snd) ~parents:impl (c, tc) in if Typing_disposable.is_disposable_class env tc then List.iter (c.c_extends @ c.c_uses) ~f:(Typing_disposable.enforce_is_disposable env); env let check_class_members env c tc = let (static_vars, vars) = split_vars c.c_vars in let (constructor, static_methods, methods) = split_methods c.c_methods in let is_disposable = Typing_disposable.is_disposable_class env tc in let is_noautodynamic = Naming_attributes.mem SN.UserAttributes.uaNoAutoDynamic c.Aast.c_user_attributes in let (env, typed_vars) = List.map_env env vars ~f:(class_var_def ~is_static:false ~is_noautodynamic tc) in let typed_methods = List.filter_map methods ~f:(method_def ~is_disposable env tc) in let typed_methods = Tast_with_dynamic.collect typed_methods in let (env, typed_typeconsts) = List.map_env env c.c_typeconsts ~f:(typeconst_def c) in let in_enum_class = Env.is_enum_class env (snd c.c_name) in let (env, consts) = List.map_env env c.c_consts ~f:(class_const_def ~in_enum_class c tc) in let (typed_consts, const_types) = List.unzip consts in let env = Typing_enum.enum_class_check env tc c.c_consts const_types in let typed_constructor = class_constr_def ~is_disposable env tc constructor in let env = Env.set_static env in let (env, typed_static_vars) = List.map_env env static_vars ~f:(class_var_def ~is_static:true ~is_noautodynamic tc) in let typed_static_methods = List.filter_map static_methods ~f:(method_def ~is_disposable env tc) in let typed_static_methods = Tast_with_dynamic.collect typed_static_methods in let typed_methods = match typed_constructor with | None -> Tast_with_dynamic.append typed_static_methods typed_methods | Some ms -> Tast_with_dynamic.append (Tast_with_dynamic.cons ms typed_static_methods) typed_methods in let typed_members = ( typed_consts, typed_typeconsts, typed_vars, typed_static_vars, typed_methods ) in (env, typed_members) let class_def_ env c tc = let parents = class_parents_hints_to_types env c in let (env, user_attributes, file_attrs) = class_wellformedness_checks env c tc parents in let env = class_hierarchy_checks env c tc parents in let ( env, ( typed_consts, typed_typeconsts, typed_vars, typed_static_vars, typed_methods ) ) = check_class_members env c tc in let (env, tparams) = class_type_param env c.c_tparams in let (env, e1) = Typing_solver.solve_all_unsolved_tyvars env in check_SupportDynamicType env c tc; Option.iter ~f:(Typing_error_utils.add_typing_error ~env) e1; let mk_class_ typed_methods = { Aast.c_span = c.c_span; Aast.c_annotation = Env.save (Env.get_tpenv env) env; Aast.c_mode = c.c_mode; Aast.c_final = c.c_final; Aast.c_is_xhp = c.c_is_xhp; Aast.c_has_xhp_keyword = c.c_has_xhp_keyword; Aast.c_kind = c.c_kind; Aast.c_name = c.c_name; Aast.c_tparams = tparams; Aast.c_extends = c.c_extends; Aast.c_uses = c.c_uses; Aast.c_xhp_attr_uses = c.c_xhp_attr_uses; Aast.c_xhp_category = c.c_xhp_category; Aast.c_reqs = c.c_reqs; Aast.c_implements = c.c_implements; Aast.c_where_constraints = c.c_where_constraints; Aast.c_consts = typed_consts; Aast.c_typeconsts = typed_typeconsts; Aast.c_vars = typed_static_vars @ typed_vars; Aast.c_methods = typed_methods; Aast.c_file_attributes = file_attrs; Aast.c_user_attributes = user_attributes; Aast.c_namespace = c.c_namespace; Aast.c_enum = c.c_enum; Aast.c_doc_comment = c.c_doc_comment; Aast.c_xhp_children = c.c_xhp_children; Aast.c_xhp_attrs = []; Aast.c_emit_id = c.c_emit_id; Aast.c_internal = c.c_internal; Aast.c_module = c.c_module; Aast.c_docs_url = c.c_docs_url; } in { Tast_with_dynamic.under_normal_assumptions = mk_class_ typed_methods.Tast_with_dynamic.under_normal_assumptions; under_dynamic_assumptions = Option.map typed_methods.Tast_with_dynamic.under_dynamic_assumptions ~f:mk_class_; } let setup_env_for_class_def_check ctx c = let env = EnvFromDef.class_env ~origin:Decl_counters.TopLevel ctx c in let env = Env.set_current_module env c.c_module in let env = Env.set_internal env c.c_internal in let env = Env.set_support_dynamic_type env (Naming_attributes.mem SN.UserAttributes.uaSupportDynamicType c.c_user_attributes) in env let class_def ctx (c : _ class_) = let env = setup_env_for_class_def_check ctx c in match Env.get_class env (snd c.c_name) with | None -> HackEventLogger.decl_consistency_bug "Decl consistency: class_def, but can't find a decl" ~data:(snd c.c_name) ~pos:(Pos.to_relative_string (fst c.c_name) |> Pos.string); None | Some tc -> Env.make_depend_on_current_module env; Typing_helpers.add_decl_errors ~env (Cls.decl_errors tc); if not (TCO.saved_state_rollouts (Provider_context.get_tcopt ctx)) .Saved_state_rollouts.no_ancestor_edges then Env.make_depend_on_ancestors env tc; Some (class_def_ env c tc) type class_member_standalone_check_env = { cls: Cls.t; env: env; class_: Nast.class_; } let make_class_member_standalone_check_env ctx class_ = let env = setup_env_for_class_def_check ctx class_ in let name = Ast_defs.get_id class_.c_name in let open Option in Env.get_class env name >>| fun cls -> let env = check_class_type_parameters_add_constraints env class_ cls in (env, { env; cls; class_ }) let method_def_standalone standalone_env method_name = let open Option in let is_disposable = Typing_disposable.is_disposable_class standalone_env.env standalone_env.cls in List.find standalone_env.class_.Aast.c_methods ~f:(fun m -> String.equal (snd m.Aast.m_name) method_name) >>= fun method_ -> let env = if method_.m_static then Env.set_static standalone_env.env else standalone_env.env in method_def ~is_disposable env standalone_env.cls method_
OCaml Interface
hhvm/hphp/hack/src/typing/typing_class.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 class_member_standalone_check_env (** Create an environment from a class that can be used to subsequently type-check members of that class individually *) val make_class_member_standalone_check_env : Provider_context.t -> Nast.class_ -> (Typing_env_types.env * class_member_standalone_check_env) option (** Type-checks the given method of the class that was specific when creating the [class_member_standalone_check_env] *) val method_def_standalone : class_member_standalone_check_env -> string -> Tast.method_ Tast_with_dynamic.t option (** This is a helper for [Typing_toplevel.class_def]. Call that instead. Must only be called if [Decl_provider.get_class] for this class's name will return this class's decl. (which it might not, say, if there were duplicate definitions and this class was the loser). This function will return None if the condition isn't met. *) val class_def : Provider_context.t -> Nast.class_ -> Tast.class_ Tast_with_dynamic.t option
OCaml
hhvm/hphp/hack/src/typing/typing_classes_heap.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Typing_defs open Typing_class_types module SN = Naming_special_names type class_t = Typing_class_types.class_t [@@deriving show] let make_eager_class_decl decl = ( decl, { methods = String.Table.create (); static_methods = String.Table.create (); props = String.Table.create (); static_props = String.Table.create (); construct = ref None; } ) let make_eager_class_type ctx class_name declare_folded_class = match Decl_store.((get ()).get_class class_name) with | Some decl -> Some (make_eager_class_decl decl) | None -> begin match Naming_provider.get_type_kind ctx class_name with | None -> None | Some Naming_types.TTypedef -> None | Some Naming_types.TClass -> Deferred_decl.raise_if_should_defer (); (* declare_folded_class_in_file actual reads from Decl_heap.Classes.get * like what we do above, which makes our test redundant but cleaner. * It also writes into Decl_heap.Classes and other Decl_heaps. *) let (decl, _) = declare_folded_class ctx class_name in Some (make_eager_class_decl decl) end let get (ctx : Provider_context.t) (class_name : string) declare_folded_class : class_t option = make_eager_class_type ctx class_name declare_folded_class module ApiShallow = struct let abstract (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Abstract @@ fun () -> let (c, _) = t in c.Decl_defs.dc_abstract let final (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Final @@ fun () -> let (c, _) = t in c.Decl_defs.dc_final let const (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Const @@ fun () -> let (c, _) = t in c.Decl_defs.dc_const let kind (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Kind @@ fun () -> let (c, _) = t in c.Decl_defs.dc_kind let is_xhp (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Is_xhp @@ fun () -> let (c, _) = t in c.Decl_defs.dc_is_xhp let name (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Name @@ fun () -> let (c, _) = t in c.Decl_defs.dc_name let pos (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Pos @@ fun () -> let (c, _) = t in c.Decl_defs.dc_pos let tparams (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Tparams @@ fun () -> let (c, _) = t in c.Decl_defs.dc_tparams let where_constraints (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Where_constraints @@ fun () -> let (c, _) = t in c.Decl_defs.dc_where_constraints let enum_type (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Enum_type @@ fun () -> let (c, _) = t in c.Decl_defs.dc_enum_type let xhp_enum_values (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Xhp_enum_values @@ fun () -> let (c, _) = t in c.Decl_defs.dc_xhp_enum_values let xhp_marked_empty (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Xhp_marked_empty @@ fun () -> let (c, _) = t in c.Decl_defs.dc_xhp_marked_empty let sealed_whitelist (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Sealed_whitelist @@ fun () -> let (c, _) = t in c.Decl_defs.dc_sealed_whitelist let get_docs_url (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Docs_url @@ fun () -> let (c, _) = t in c.Decl_defs.dc_docs_url let get_module (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Module @@ fun () -> let (c, _) = t in Option.map c.Decl_defs.dc_module ~f:snd let internal (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Internal @@ fun () -> let (c, _) = t in c.Decl_defs.dc_internal let is_module_level_trait (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.IsModuleLevelTrait @@ fun () -> let (c, _) = t in c.Decl_defs.dc_is_module_level_trait let decl_errors (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Decl_errors @@ fun () -> let (c, _) = t in c.Decl_defs.dc_decl_errors let get_support_dynamic_type (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Support_dynamic_type @@ fun () -> let (c, _) = t in c.Decl_defs.dc_support_dynamic_type let all_where_constraints_on_this t = (* tally is already done by where_constraints *) List.filter ~f:(fun (l, _, r) -> match (get_node l, get_node r) with | (Tthis, _) | (_, Tthis) -> true | _ -> false) (where_constraints t) let upper_bounds_on_this_from_constraints t = (* tally is already done by where_constraints *) List.filter_map ~f:(fun (l, c, r) -> match (get_node l, c, get_node r) with | (Tthis, Ast_defs.Constraint_as, _) | (Tthis, Ast_defs.Constraint_eq, _) -> Some r | (_, Ast_defs.Constraint_eq, Tthis) | (_, Ast_defs.Constraint_super, Tthis) -> Some l | _ -> None) (where_constraints t) let has_upper_bounds_on_this_from_constraints t = (* tally is already done by upper_bounds_on_this *) not (List.is_empty (upper_bounds_on_this_from_constraints t)) (* get lower bounds on `this` from the where constraints *) let lower_bounds_on_this_from_constraints t = (* tally is already done by where_constraint *) List.filter_map ~f:(fun (l, c, r) -> match (get_node l, c, get_node r) with | (Tthis, Ast_defs.Constraint_super, _) | (Tthis, Ast_defs.Constraint_eq, _) -> Some r | (_, Ast_defs.Constraint_eq, Tthis) | (_, Ast_defs.Constraint_as, Tthis) -> Some l | _ -> None) (where_constraints t) let has_lower_bounds_on_this_from_constraints t = (* tally is already done by lower_bounds_on_this *) not (List.is_empty (lower_bounds_on_this_from_constraints t)) let lower_bounds_on_this t = (* tally is done inside the following method *) lower_bounds_on_this_from_constraints t end module ApiLazy = struct let construct (decl, t, ctx) = Decl_counters.count_subdecl decl Decl_counters.Construct @@ fun () -> let (cls, members) = t in match !(members.construct) with | Some x -> x | None -> let x = Decl_class.lookup_constructor_lazy ctx ~child_class_name:cls.Decl_defs.dc_name cls.Decl_defs.dc_substs cls.Decl_defs.dc_construct in members.construct := Some x; x let need_init (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Need_init @@ fun () -> let (c, _) = t in c.Decl_defs.dc_need_init let get_ancestor (decl, t, _ctx) ancestor = Decl_counters.count_subdecl decl (Decl_counters.Get_ancestor ancestor) @@ fun () -> let (c, _) = t in SMap.find_opt ancestor c.Decl_defs.dc_ancestors let has_ancestor (decl, t, _ctx) ancestor = Decl_counters.count_subdecl decl (Decl_counters.Has_ancestor ancestor) @@ fun () -> let (c, _) = t in SMap.mem ancestor c.Decl_defs.dc_ancestors let requires_ancestor (decl, t, _ctx) ancestor = Decl_counters.count_subdecl decl (Decl_counters.Requires_ancestor ancestor) @@ fun () -> let (c, _) = t in SSet.mem ancestor c.Decl_defs.dc_req_ancestors_extends let get_const (decl, t, _ctx) id = Decl_counters.count_subdecl decl (Decl_counters.Get_const id) @@ fun () -> let (c, _) = t in SMap.find_opt id c.Decl_defs.dc_consts let has_const (decl, t, _ctx) id = Decl_counters.count_subdecl decl (Decl_counters.Has_const id) @@ fun () -> let (c, _) = t in SMap.mem id c.Decl_defs.dc_consts let get_typeconst (decl, t, _ctx) id = Decl_counters.count_subdecl decl (Decl_counters.Get_typeconst id) @@ fun () -> let (c, _) = t in SMap.find_opt id c.Decl_defs.dc_typeconsts let has_typeconst (decl, t, _ctx) id = Decl_counters.count_subdecl decl (Decl_counters.Has_typeconst id) @@ fun () -> let (c, _) = t in SMap.mem id c.Decl_defs.dc_typeconsts let get_typeconst_enforceability (decl, t, _ctx) id = Decl_counters.count_subdecl decl (Decl_counters.Get_typeconst_enforceability id) @@ fun () -> let (c, _) = t in Option.map (SMap.find_opt id c.Decl_defs.dc_typeconsts) ~f:(fun t -> t.ttc_enforceable) let get_prop (decl, t, ctx) id = Decl_counters.count_subdecl decl (Decl_counters.Get_prop id) @@ fun () -> let (c, members) = t in match String.Table.find members.props id with | Some _ as elt_opt -> elt_opt | None -> (match SMap.find_opt id c.Decl_defs.dc_props with | None -> None | Some elt -> let elt = Decl_class.lookup_property_type_lazy ctx c id elt in String.Table.add_exn members.props ~key:id ~data:elt; Some elt) let has_prop (decl, t, _ctx) id = Decl_counters.count_subdecl decl (Decl_counters.Has_prop id) @@ fun () -> let (c, _) = t in SMap.mem id c.Decl_defs.dc_props let get_sprop (decl, t, ctx) id = Decl_counters.count_subdecl decl (Decl_counters.Get_sprop id) @@ fun () -> let (c, members) = t in match String.Table.find members.static_props id with | Some _ as elt_opt -> elt_opt | None -> (match SMap.find_opt id c.Decl_defs.dc_sprops with | None -> None | Some elt -> let elt = Decl_class.lookup_static_property_type_lazy ctx c id elt in String.Table.add_exn members.static_props ~key:id ~data:elt; Some elt) let has_sprop (decl, t, _ctx) id = Decl_counters.count_subdecl decl (Decl_counters.Has_sprop id) @@ fun () -> let (c, _) = t in SMap.mem id c.Decl_defs.dc_sprops let get_method (decl, t, ctx) id = Decl_counters.count_subdecl decl (Decl_counters.Get_method id) @@ fun () -> let (c, members) = t in match String.Table.find members.methods id with | Some _ as elt_opt -> elt_opt | None -> (match SMap.find_opt id c.Decl_defs.dc_methods with | None -> None | Some elt -> let elt = Decl_class.lookup_method_type_lazy ctx c id elt in String.Table.add_exn members.methods ~key:id ~data:elt; Some elt) let has_method (decl, t, _ctx) id = Decl_counters.count_subdecl decl (Decl_counters.Has_method id) @@ fun () -> let (c, _) = t in SMap.mem id c.Decl_defs.dc_methods let get_smethod (decl, t, ctx) id = Decl_counters.count_subdecl decl (Decl_counters.Get_smethod id) @@ fun () -> let (c, members) = t in match String.Table.find members.static_methods id with | Some _ as elt_opt -> elt_opt | None -> (match SMap.find_opt id c.Decl_defs.dc_smethods with | None -> None | Some elt -> let elt = Decl_class.lookup_static_method_type_lazy ctx c id elt in String.Table.add_exn members.static_methods ~key:id ~data:elt; Some elt) let has_smethod (decl, t, _ctx) id = Decl_counters.count_subdecl decl (Decl_counters.Has_smethod id) @@ fun () -> let (c, _) = t in SMap.mem id c.Decl_defs.dc_smethods let get_any_method ~is_static cls id = (* tally is already done inside the following three methods *) if String.equal id SN.Members.__construct then fst (construct cls) else if is_static then get_smethod cls id else get_method cls id end module ApiEager = struct let all_ancestor_req_names (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.All_ancestor_req_names @@ fun () -> (* The two below will traverse ancestors in different orders. But if the typechecker discovers errors in different order, no matter. *) let (c, _) = t in SSet.elements c.Decl_defs.dc_req_ancestors_extends let all_ancestors (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.All_ancestors @@ fun () -> let (c, _) = t in SMap.bindings c.Decl_defs.dc_ancestors let all_ancestor_names (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.All_ancestors @@ fun () -> let (c, _) = t in SMap.ordered_keys c.Decl_defs.dc_ancestors let all_ancestor_reqs (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.All_ancestor_reqs @@ fun () -> let (c, _) = t in c.Decl_defs.dc_req_ancestors let all_ancestor_req_class_requirements (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.All_ancestor_reqs @@ fun () -> let (c, _) = t in c.Decl_defs.dc_req_class_ancestors let upper_bounds_on_this t = (* tally is already done by all_ancestors and upper_bounds *) List.map ~f:(fun req -> snd req) (all_ancestor_reqs t) |> List.append (List.map ~f:snd (all_ancestor_req_class_requirements t)) |> List.append (ApiShallow.upper_bounds_on_this_from_constraints t) let consts (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Consts @@ fun () -> let (c, _) = t in SMap.bindings c.Decl_defs.dc_consts let typeconsts (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Typeconsts @@ fun () -> let (c, _) = t in SMap.bindings c.Decl_defs.dc_typeconsts let props (decl, t, ctx) = Decl_counters.count_subdecl decl Decl_counters.Props @@ fun () -> let (c, _) = t in SMap.bindings c.Decl_defs.dc_props |> List.map ~f:(fun (id, elt) -> (id, Decl_class.lookup_property_type_lazy ctx c id elt)) let sprops (decl, t, ctx) = Decl_counters.count_subdecl decl Decl_counters.SProps @@ fun () -> let (c, _) = t in SMap.bindings c.Decl_defs.dc_sprops |> List.map ~f:(fun (id, elt) -> (id, Decl_class.lookup_static_property_type_lazy ctx c id elt)) let methods (decl, t, ctx) = Decl_counters.count_subdecl decl Decl_counters.Methods @@ fun () -> let (c, _) = t in SMap.bindings c.Decl_defs.dc_methods |> List.map ~f:(fun (id, elt) -> (id, Decl_class.lookup_method_type_lazy ctx c id elt)) let smethods (decl, t, ctx) = Decl_counters.count_subdecl decl Decl_counters.SMethods @@ fun () -> let (c, _) = t in SMap.bindings c.Decl_defs.dc_smethods |> List.map ~f:(fun (id, elt) -> (id, Decl_class.lookup_static_method_type_lazy ctx c id elt)) let overridden_method (decl, t, ctx) ~method_name ~is_static ~get_class = let open Option.Monad_infix in Decl_counters.count_subdecl decl Decl_counters.Overridden_method @@ fun () -> ctx >>= fun ctx -> let get_method (ty : decl_ty) : class_elt option = let (_, (_, class_name), _) = Decl_utils.unwrap_class_type ty in get_class ctx class_name >>= fun cls -> ApiLazy.get_any_method ~is_static cls method_name in let (cls, _members) = t in Shallow_classes_provider.get ctx cls.Decl_defs.dc_name >>= Decl_inherit.find_overridden_method ~get_method end module Api = struct type t = (Decl_counters.decl option[@opaque]) * class_t * (Provider_context.t[@opaque]) option [@@deriving show] include ApiShallow include ApiLazy include ApiEager let deferred_init_members (decl, t, _ctx) = Decl_counters.count_subdecl decl Decl_counters.Deferred_init_members @@ fun () -> let (c, _) = t in c.Decl_defs.dc_deferred_init_members let valid_newable_class cls = if Ast_defs.is_c_class (kind cls) then final cls || not (equal_consistent_kind (snd (construct cls)) Inconsistent) (* There is currently a bug with interfaces that allows constructors to change * their signature, so they are not considered here. TODO: T41093452 *) else false end let get_class_with_cache ctx class_name decl_cache declare_folded_class = Provider_backend.Decl_cache.find_or_add decl_cache ~key:(Provider_backend.Decl_cache_entry.Class_decl class_name) ~default:(fun () -> get ctx class_name declare_folded_class)