language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
Rust
hhvm/hphp/hack/src/naming/elab_ffi.rs
// Copyright (c) Meta Platforms, Inc. and affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use oxidized::ast; use oxidized::naming_phase_error::NamingPhaseError; use oxidized::nast; use oxidized::typechecker_options::TypecheckerOptions; use relative_path::RelativePath; ocamlrep_ocamlpool::ocaml_ffi! { fn hh_elab_program( tco: TypecheckerOptions, path: RelativePath, program: ast::Program, ) -> (nast::Program, Vec<NamingPhaseError>) { let mut program = program; let errs = elab::elaborate_program(&tco, &path, &mut program); (program, errs) } fn hh_elab_fun_def( tco: TypecheckerOptions, path: RelativePath, fd: ast::FunDef, ) -> (nast::FunDef, Vec<NamingPhaseError>) { let mut fd = fd; let errs = elab::elaborate_fun_def(&tco, &path, &mut fd); (fd, errs) } fn hh_elab_class_( tco: TypecheckerOptions, path: RelativePath, c: ast::Class_, ) -> (nast::Class_, Vec<NamingPhaseError>) { let mut c = c; let errs = elab::elaborate_class_(&tco, &path, &mut c); (c, errs) } fn hh_elab_module_def( tco: TypecheckerOptions, path: RelativePath, m: ast::ModuleDef, ) -> (nast::ModuleDef, Vec<NamingPhaseError>) { let mut m = m; let errs = elab::elaborate_module_def(&tco, &path, &mut m); (m, errs) } fn hh_elab_gconst( tco: TypecheckerOptions, path: RelativePath, cst: ast::Gconst, ) -> (nast::Gconst, Vec<NamingPhaseError>) { let mut cst = cst; let errs = elab::elaborate_gconst(&tco, &path, &mut cst); (cst, errs) } fn hh_elab_typedef( tco: TypecheckerOptions, path: RelativePath, td: ast::Typedef, ) -> (nast::Typedef, Vec<NamingPhaseError>) { let mut td = td; let errs = elab::elaborate_typedef(&tco, &path, &mut td); (td, errs) } }
OCaml
hhvm/hphp/hack/src/naming/name_context.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 t = | FunctionNamespace | ConstantNamespace | ModuleNamespace | PackageNamespace | TypeNamespace (** Classes, interfaces, traits, records and type aliases.*) (* The following are all subsets of TypeNamespace, used when we can give a more specific naming error. E.g. `use Foo;` only allows traits. *) | TraitContext | ClassContext let to_string = function | FunctionNamespace -> "function" | ConstantNamespace -> "constant" | TypeNamespace -> "type" | TraitContext -> "trait" | ClassContext -> "class" | ModuleNamespace -> "module" | PackageNamespace -> "package"
OCaml
hhvm/hphp/hack/src/naming/naming.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 "naming" a program. * * The naming phase consists in several things * 1- get all the global names * 2- transform all the local names into a unique identifier *) open Hh_prelude open Common module Env = Naming_phase_env (*****************************************************************************) (* Helpers *) (*****************************************************************************) let (on_error, reset_errors, get_errors) = let naming_errs = ref Naming_phase_error.empty in let reset_errors () = naming_errs := Naming_phase_error.empty and get_errors () = !naming_errs and on_error err = naming_errs := Naming_phase_error.add !naming_errs err in (on_error, reset_errors, get_errors) let invalid_expr_ = Naming_phase_error.invalid_expr_ let mk_env filename tcopt = let file_str = Relative_path.suffix filename in let is_hhi = String.is_suffix (Relative_path.suffix filename) ~suffix:".hhi" and is_systemlib = TypecheckerOptions.is_systemlib tcopt and allow_module_def = TypecheckerOptions.allow_all_files_for_module_declarations tcopt || List.exists ~f:(fun allowed_file -> let len = String.length allowed_file in if len > 0 then match allowed_file.[len - 1] with | '*' -> let allowed_dir = String.sub allowed_file ~pos:0 ~len:(len - 1) in String.is_prefix file_str ~prefix:allowed_dir | _ -> String.equal allowed_file file_str else false) (TypecheckerOptions.allowed_files_for_module_declarations tcopt) and everything_sdt = TypecheckerOptions.everything_sdt tcopt and supportdynamic_type_hint_enabled = TypecheckerOptions.experimental_feature_enabled tcopt TypecheckerOptions.experimental_supportdynamic_type_hint and hkt_enabled = TypecheckerOptions.higher_kinded_types tcopt and like_type_hints_enabled = TypecheckerOptions.like_type_hints tcopt and soft_as_like = TypecheckerOptions.interpret_soft_types_as_like_types tcopt and consistent_ctor_level = TypecheckerOptions.explicit_consistent_constructors tcopt in Env. { empty with is_hhi; is_systemlib; consistent_ctor_level; allow_module_def; everything_sdt; supportdynamic_type_hint_enabled; hkt_enabled; like_type_hints_enabled; soft_as_like; } let passes = [ (* Stop on `Invalid` expressions *) Naming_guard_invalid.pass; (* Canonicalization passes -------------------------------------------- *) (* Remove top-level file attributes, noop and markup statements *) Naming_elab_defs.pass; (* Remove function bodies when in hhi mode *) Naming_elab_func_body.pass; (* Flatten `Block` statements *) Naming_elab_block.pass; (* Strip `Hsoft` hints or replace with `Hlike` *) Naming_elab_soft.pass; (* Elaborate `Happly` to canonical representation, if any *) Naming_elab_happly_hint.pass on_error; (* Elaborate class identifier expressions (`CIexpr`) to canonical representation: `CIparent`, `CIself`, `CIstatic`, `CI` _or_ `CIexpr (_,_, Lvar _ | This )` *) Naming_elab_class_id.pass on_error; (* Strip type parameters from type parameters when HKTs are not enabled *) Naming_elab_hkt.pass on_error; (* Elaborate `Collection` to `ValCollection` or `KeyValCollection` *) Naming_elab_collection.pass on_error; (* Check that user attributes are well-formed *) Naming_elab_user_attributes.pass on_error; (* Replace import expressions with invalid expression marker *) Naming_elab_import.pass; (* Elaborate local variables to canonical representation *) Naming_elab_lvar.pass; (* Warn of explicit use of builtin enum classes; make subtyping of enum classes explicit*) Naming_elab_enum_class.pass on_error; (* Elaborate class members & xhp attributes *) Naming_elab_class_members.pass on_error; (* Elaborate special function calls to canonical representation, if any *) Naming_elab_call.top_down_pass; Naming_elab_call.bottom_up_pass on_error; (* Elaborate invariant calls to canonical representation *) Naming_elab_invariant.pass on_error; (* -- Mark invalid hints and expressions & miscellaneous validation --- *) (* Replace invalid uses of `void` and `noreturn` with `Herr` *) Naming_elab_retonly_hint.pass on_error; (* Replace invalid uses of wildcard hints with `Herr` *) Naming_elab_wildcard_hint.pass on_error; (* Replace uses to `self` in shape field names with referenced class *) Naming_elab_shape_field_name.top_down_pass; Naming_elab_shape_field_name.bottom_up_pass on_error; (* Replace invalid uses of `this` hints with `Herr` *) Naming_elab_this_hint.pass on_error; (* Replace invalid `Haccess` root hints with `Herr` *) Naming_elab_haccess_hint.pass on_error; (* Replace empty `Tuple`s with invalid expression marker *) Naming_elab_tuple.pass on_error; (* Validate / replace invalid uses of dynamic classes in `New` and `Class_get` expressions *) Naming_elab_dynamic_class_name.pass on_error; (* Replace non-constant class or global constant with invalid expression marker *) Naming_elab_const_expr.top_down_pass on_error; Naming_elab_const_expr.bottom_up_pass on_error; (* Replace malformed key / value bindings in as expressions with invalid local var markers *) Naming_elab_as_expr.pass on_error; (* Validate hints used in `Cast` expressions *) Naming_validate_cast_expr.pass on_error; (* Validate where `dynamic` can be used in a hint *) Naming_validate_dynamic_hint.pass on_error; (* Check for duplicate function parameter names *) Naming_validate_fun_params.pass on_error; (* Validate use of `require implements`, `require extends` and `require class` declarations for traits, interfaces and classes *) Naming_validate_class_req.pass on_error; (* Validation dealing with common xhp naming errors *) Naming_validate_xhp_name.pass on_error; (* -- Elaboration & validation under typechecker options -------------- *) (* Add `supportdyn` and `Like` wrappers everywhere - under `everything-sdt` typechecker option *) Naming_elab_everything_sdt.top_down_pass; Naming_elab_everything_sdt.bottom_up_pass; (* Validate use of `Hlike` hints - depends on `enable-like-type-hints` typechecker option *) Naming_validate_like_hint.pass on_error; (* Validate constructors under `consistent-explicit_consistent_constructors` typechecker option *) Naming_validate_consistent_construct.pass on_error; (* Validate use of `SupportDyn` class - depends on `enable-supportdyn` and `everything_sdt` typechecker options *) Naming_validate_supportdyn.pass on_error; (* Validate use of module definitions - depends on: - `allow_all_files_for_module_declarations` - `allowed_files_for_module_declarations` typechecker options *) Naming_validate_module.pass on_error; ] (* If we don't delegate to Rust, then all naming passes are done here in OCaml. *) let ( elab_core_program, elab_core_class, elab_core_fun_def, elab_core_module_def, elab_core_gconst, elab_core_typedef ) = Naming_phase_pass.mk_visitor passes let elab_elem elem ~elab_ns ~elab_capture ~elab_typed_locals ~elab_core = reset_errors (); let elem = elab_ns elem |> elab_capture |> elab_typed_locals |> elab_core in Naming_phase_error.emit @@ get_errors (); reset_errors (); elem let program_filename defs = let open Aast_defs in let rec aux = function | Fun fun_def :: _ -> Pos.filename fun_def.fd_fun.f_span | Class class_ :: _ -> Pos.filename class_.c_span | Stmt (pos, _) :: _ -> Pos.filename pos | Typedef typedef :: _ -> Pos.filename typedef.t_span | Constant gconst :: _ -> Pos.filename gconst.cst_span | Module module_def :: _ -> Pos.filename module_def.md_span | _ :: rest -> aux rest | _ -> Relative_path.default in aux defs (**************************************************************************) (* The entry points to CHECK the program, and transform the program *) (**************************************************************************) module Rust_elab_core = struct external elab_program : TypecheckerOptions.t -> Relative_path.t -> (unit, unit) Aast.program -> Nast.program * Naming_phase_error.t list = "hh_elab_program" external elab_fun_def : TypecheckerOptions.t -> Relative_path.t -> (unit, unit) Aast.fun_def -> Nast.fun_def * Naming_phase_error.t list = "hh_elab_fun_def" external elab_class_ : TypecheckerOptions.t -> Relative_path.t -> (unit, unit) Aast.class_ -> Nast.class_ * Naming_phase_error.t list = "hh_elab_class_" external elab_module_def : TypecheckerOptions.t -> Relative_path.t -> (unit, unit) Aast.module_def -> Nast.module_def * Naming_phase_error.t list = "hh_elab_module_def" external elab_gconst : TypecheckerOptions.t -> Relative_path.t -> (unit, unit) Aast.gconst -> Nast.gconst * Naming_phase_error.t list = "hh_elab_gconst" external elab_typedef : TypecheckerOptions.t -> Relative_path.t -> (unit, unit) Aast.typedef -> Nast.typedef * Naming_phase_error.t list = "hh_elab_typedef" let add_errors elab_x tcopt filename x = let (x, errs) = elab_x tcopt filename x in errs |> List.fold ~init:Naming_phase_error.empty ~f:Naming_phase_error.add |> Naming_phase_error.emit; x let elab_program = add_errors elab_program let elab_fun_def = add_errors elab_fun_def let elab_class_ = add_errors elab_class_ let elab_module_def = add_errors elab_module_def let elab_gconst = add_errors elab_gconst let elab_typedef = add_errors elab_typedef end let program ctx program = let tcopt = Provider_context.get_tcopt ctx in let filename = program_filename program in if TypecheckerOptions.rust_elab tcopt then Rust_elab_core.elab_program tcopt filename program else let elab_ns = Naming_elaborate_namespaces_endo.elaborate_program and elab_capture = Naming_captures.elab_program and elab_typed_locals = Naming_typed_locals.elab_program and elab_core = elab_core_program (mk_env filename tcopt) in elab_elem ~elab_ns ~elab_capture ~elab_typed_locals ~elab_core program let fun_def ctx fd = let tcopt = Provider_context.get_tcopt ctx in let filename = Pos.filename fd.Aast.fd_fun.Aast.f_span in if TypecheckerOptions.rust_elab tcopt then Rust_elab_core.elab_fun_def tcopt filename fd else let elab_ns = Naming_elaborate_namespaces_endo.elaborate_fun_def and elab_capture = Naming_captures.elab_fun_def and elab_typed_locals = Naming_typed_locals.elab_fun_def and elab_core = elab_core_fun_def (mk_env filename tcopt) in elab_elem ~elab_ns ~elab_capture ~elab_typed_locals ~elab_core fd let class_ ctx c = let tcopt = Provider_context.get_tcopt ctx in let filename = Pos.filename c.Aast.c_span in if TypecheckerOptions.rust_elab tcopt then Rust_elab_core.elab_class_ tcopt filename c else let elab_ns = Naming_elaborate_namespaces_endo.elaborate_class_ and elab_capture = Naming_captures.elab_class and elab_typed_locals = Naming_typed_locals.elab_class and elab_core = elab_core_class (mk_env filename tcopt) in elab_elem ~elab_ns ~elab_capture ~elab_typed_locals ~elab_core c let module_ ctx md = let tcopt = Provider_context.get_tcopt ctx in let filename = Pos.filename md.Aast.md_span in if TypecheckerOptions.rust_elab tcopt then Rust_elab_core.elab_module_def tcopt filename md else let elab_ns = Naming_elaborate_namespaces_endo.elaborate_module_def and elab_capture = Naming_captures.elab_module_def and elab_typed_locals x = x and elab_core = elab_core_module_def (mk_env filename tcopt) in elab_elem ~elab_ns ~elab_capture ~elab_typed_locals ~elab_core md let global_const ctx cst = let tcopt = Provider_context.get_tcopt ctx in let filename = Pos.filename cst.Aast.cst_span in if TypecheckerOptions.rust_elab tcopt then Rust_elab_core.elab_gconst tcopt filename cst else let elab_ns = Naming_elaborate_namespaces_endo.elaborate_gconst and elab_capture = Naming_captures.elab_gconst and elab_typed_locals x = x and elab_core = elab_core_gconst (mk_env filename tcopt) in elab_elem ~elab_ns ~elab_capture ~elab_typed_locals ~elab_core cst let typedef ctx td = let tcopt = Provider_context.get_tcopt ctx in let filename = Pos.filename @@ td.Aast.t_span in if TypecheckerOptions.rust_elab tcopt then Rust_elab_core.elab_typedef tcopt filename td else let elab_ns = Naming_elaborate_namespaces_endo.elaborate_typedef and elab_capture = Naming_captures.elab_typedef and elab_typed_locals x = x and elab_core = elab_core_typedef (mk_env filename tcopt) in elab_elem ~elab_ns ~elab_capture ~elab_typed_locals ~elab_core td
OCaml Interface
hhvm/hphp/hack/src/naming/naming.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 "naming" a program. * Transform all the local names into a unique identifier *) val program : Provider_context.t -> Nast.program -> Nast.program (* Solves the local names within a function *) val fun_def : Provider_context.t -> Nast.fun_def -> Nast.fun_def (* Solves the local names of a class *) val class_ : Provider_context.t -> Nast.class_ -> Nast.class_ (* Solves the local names in an typedef *) val typedef : Provider_context.t -> Nast.typedef -> Nast.typedef (* Solves the local names in a global constant definition *) val global_const : Provider_context.t -> Nast.gconst -> Nast.gconst val module_ : Provider_context.t -> Nast.module_def -> Nast.module_def val invalid_expr_ : ('ex, 'en) Aast.expr option -> ('ex, 'en) Aast.expr_
OCaml
hhvm/hphp/hack/src/naming/naming_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 pp_unit fmt () = Format.pp_print_string fmt "()" let print_nast_internal pp_ex nast = let pp_unit fmt () = Format.pp_print_string fmt "()" in let formatter = Format.formatter_of_out_channel Stdlib.stdout in Format.pp_set_margin formatter 200; Aast.pp_program pp_ex pp_unit formatter nast; Format.pp_print_newline formatter () let print_nast nast = print_nast_internal pp_unit nast let print_nast_without_position nast = let remove_pos = object inherit [_] Aast.map method! on_pos _ _pos = Pos.none method on_'ex _ _pos = () method on_'en _ en = en end in let nast = remove_pos#on_program () nast in print_nast_internal pp_unit nast
OCaml Interface
hhvm/hphp/hack/src/naming/naming_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_nast : Nast.program -> unit val print_nast_without_position : Nast.program -> unit
OCaml
hhvm/hphp/hack/src/naming/naming_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 Aast let mem x xs = List.exists xs ~f:(fun { ua_name; _ } -> String.equal x (snd ua_name)) let mem2 x1 x2 xs = List.exists xs ~f:(fun { ua_name = (_, n); _ } -> String.equal x1 n || String.equal x2 n) let find x xs = List.find xs ~f:(fun { ua_name; _ } -> String.equal x (snd ua_name)) let find2 x1 x2 xs = List.find xs ~f:(fun { ua_name = (_, n); _ } -> String.equal x1 n || String.equal x2 n) let mem_pos x xs = let attr = find x xs in match attr with | Some { ua_name = (pos, _); _ } -> Some pos | None -> None
Rust
hhvm/hphp/hack/src/naming/naming_attributes.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use oxidized::ast::*; pub fn mem(x: &str, xs: &[UserAttribute]) -> bool { xs.iter().any(|ua| ua.name.1 == x) }
OCaml
hhvm/hphp/hack/src/naming/naming_attributes_params.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 (* TODO: generalize the arity check / argument check here to handle attributes * in general, not just __Deprecated *) let deprecated ~kind (_, name) attrs = let attr = Naming_attributes.find SN.UserAttributes.uaDeprecated attrs in let open Aast in match attr with | Some { ua_name = _; ua_params = msg :: _ } -> begin match Nast_eval.static_string msg with | Ok msg -> let name = Utils.strip_ns name in let deprecated_prefix = Printf.sprintf "The %s %s is deprecated: " kind name in Some (deprecated_prefix ^ msg) | Error _ -> None end | _ -> None
OCaml
hhvm/hphp/hack/src/naming/naming_captures.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude type vars = { bound: Pos.t Local_id.Map.t; free: Pos.t Local_id.Map.t; } let empty = { bound = Local_id.Map.empty; free = Local_id.Map.empty } let add_local_def vars (pos, lid) : vars = { vars with bound = Local_id.Map.add lid pos vars.bound } let add_local_defs vars lvals : vars = List.fold lvals ~init:vars ~f:(fun acc ((), lval) -> add_local_def acc lval) let add_param vars param : vars = let lid = Local_id.make_unscoped param.Aast.param_name in add_local_def vars (param.Aast.param_pos, lid) let add_params vars f : vars = List.fold f.Aast.f_params ~init:vars ~f:add_param let lvalues (e : Nast.expr) : Nast.capture_lid list = let rec aux acc (_, _, e) = match e with | Aast.List lv -> List.fold_left ~init:acc ~f:aux lv | Aast.Lvar (pos, lid) -> ((), (pos, lid)) :: acc | _ -> acc in aux [] e let add_local_defs_from_lvalue vars e : vars = List.fold (lvalues e) ~init:vars ~f:(fun acc ((), lval) -> add_local_def acc lval) let add_local_ref vars (pos, lid) : vars = if Local_id.Map.mem lid vars.bound then vars else { vars with free = Local_id.Map.add lid pos vars.free } let vars = ref empty (* Walk this AAST, track free variables, and add them to capture lists in lambdas. A free variable is any local that isn't bound as a parameter or directly defined. ($a) ==> { $b = $a; $c; } In this example, only $c is free. *) let visitor = object inherit [_] Aast.endo as super method on_'ex () () = () method on_'en () () = () method! on_Lvar () e lv = vars := add_local_ref !vars lv; super#on_Lvar () e lv method! on_Binop () e (Aast.{ bop; lhs; _ } as binop) = (match bop with | Ast_defs.Eq None -> (* Introducing a new local variable. $x = ... *) vars := add_local_defs_from_lvalue !vars lhs | _ -> ()); super#on_Binop () e binop method! on_as_expr () ae = (* [as] inside a foreach loop introduces a new local variable. foreach(... as $x) { ... } *) (match ae with | Aast.As_v e | Aast.Await_as_v (_, e) -> vars := add_local_defs_from_lvalue !vars e | Aast.As_kv (k, v) | Aast.Await_as_kv (_, k, v) -> vars := add_local_defs_from_lvalue !vars k; vars := add_local_defs_from_lvalue !vars v); super#on_as_expr () ae method! on_Awaitall () s el block = (* [concurrent] blocks are desugared to a list of expressions, which can introduce new locals. concurrent { $x = await foo(); await bar(); } *) List.iter el ~f:(fun (e, _) -> match e with | Some lv -> vars := add_local_def !vars lv | None -> ()); super#on_Awaitall () s el block method! on_catch () (c_name, lv, block) = (* [catch] introduces a new local variable. try { ... } catch (Foo $x) { ... } *) vars := add_local_def !vars lv; super#on_catch () (c_name, lv, block) method! on_Efun () e efun = let outer_vars = !vars in let idl = efun.Aast.ef_use in (* We want to know about free variables inside the lambda, but we don't want its bound variables. *) vars := add_params empty efun.Aast.ef_fun; vars := add_local_defs !vars idl; let efun = match super#on_Efun () e efun with | Aast.Efun efun -> efun | _ -> assert false in vars := { outer_vars with free = Local_id.Map.union outer_vars.free !vars.free }; (* Efun syntax requires that the user specifies the captures. function() use($captured1, $captured2) { ... } We just check that they haven't tried to explicitly capture $this. *) let idl = List.filter idl ~f:(fun (_, (p, lid)) -> if String.equal (Local_id.to_string lid) Naming_special_names.SpecialIdents.this then ( Errors.add_error Naming_error.(to_user_error @@ This_as_lexical_variable p); false ) else true) in Aast.Efun { efun with Aast.ef_use = idl } method! on_Lfun () e f _ = let outer_vars = !vars in (* We want to know about free variables inside the lambda, but we don't want its bound variables. *) vars := add_params empty f; let f = match super#on_Lfun () e f [] with | Aast.Lfun (f, _) -> f | _ -> assert false in let idl = Local_id.Map.fold (fun lid pos acc -> ((), (pos, lid)) :: acc) !vars.free [] in vars := { outer_vars with free = Local_id.Map.union outer_vars.free !vars.free }; Aast.Lfun (f, idl) end (* Populate the capture list for all lambdas occurring in this top-level definition. ($x) ==> $x + $y; // $y is captured here *) let elab f elem = vars := empty; let elem = f () elem in vars := empty; elem let elab_fun_def elem = elab visitor#on_fun_def elem let elab_typedef elem = elab visitor#on_typedef elem let elab_module_def elem = elab visitor#on_module_def elem let elab_gconst elem = elab visitor#on_gconst elem let elab_class elem = elab visitor#on_class_ elem let elab_program elem = elab visitor#on_program elem let populate_fun_def (fd : Nast.fun_def) : Nast.fun_def = elab_fun_def fd let populate_class_ (c : Nast.class_) : Nast.class_ = elab_class c
OCaml Interface
hhvm/hphp/hack/src/naming/naming_captures.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 populate_fun_def : Nast.fun_def -> Nast.fun_def val populate_class_ : Nast.class_ -> Nast.class_ val elab_typedef : (unit, unit) Aast.typedef -> (unit, unit) Aast.typedef val elab_fun_def : (unit, unit) Aast.fun_def -> (unit, unit) Aast.fun_def val elab_module_def : (unit, unit) Aast.module_def -> (unit, unit) Aast.module_def val elab_gconst : (unit, unit) Aast.gconst -> (unit, unit) Aast.gconst val elab_class : (unit, unit) Aast.class_ -> (unit, unit) Aast.class_ val elab_program : (unit, unit) Aast.program -> (unit, unit) Aast.program
OCaml
hhvm/hphp/hack/src/naming/naming_elaborate_namespaces_endo.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. * *) (** * AAST visitor that elaborates the names in bodies * call_some_function($args); * -> * \CurrentNamespace\CurrentSubnamespace\call_some_function($args); * Both typechecking and codegen code expect that the AAST has been elaborated. * Currently, this assumes that the AAST has been run through * Namespaces.elaborate_toplevel_defs, which elaborates the names of toplevel * classes, functions, without elaborating the names in their bodies. * Elaboration is currently separated into these two passes based on the idea * that decl extraction does not need to do any work with function decls. * However, it should be viable to combine the two passes into a single pass. * See also: parser/namespaces.ml, parser/hh_autoimport.ml, * naming/naming_special_names.ml *) open Aast open Ast_defs open Hh_prelude module NS = Namespaces module SN = Naming_special_names type env = { namespace: Namespace_env.env; type_params: SSet.t; } let make_env namespace = { namespace; type_params = SSet.empty } (* While elaboration for codegen and typing is similar, there are currently a * couple differences between the two and are toggled by this flag (XHP). * It would be nice to eventually eliminate the discrepancies between the two. *) let in_codegen env = env.namespace.Namespace_env.ns_is_codegen let is_special_identifier = let special_identifiers = [ SN.Members.mClass; SN.Classes.cParent; SN.Classes.cSelf; SN.Classes.cStatic; SN.SpecialIdents.this; SN.SpecialIdents.dollardollar; SN.Typehints.wildcard; ] in fun name -> List.exists ~f:(fun ident -> String.equal ident name) special_identifiers let is_reserved_type_hint name = let base_name = Utils.strip_ns name in SN.Typehints.is_reserved_type_hint base_name let elaborate_type_name env ((_, name) as id) = if SSet.mem name env.type_params || is_special_identifier name || (String.length name <> 0 && Char.equal name.[0] '$') then id else NS.elaborate_id env.namespace NS.ElaborateClass id let extend_tparams env tparaml = let type_params = List.fold tparaml ~f:(fun acc tparam -> SSet.add (snd tparam.tp_name) acc) ~init:env.type_params in { env with type_params } (* `meth_caller` needs some fixup on the strings that are passed in *) let handle_meth_caller env call = match call with | Call ({ func = (_, _, Id (_, cn)); args = [(pk, (ty, p1, String cl)); meth]; _; } as call_expr) when String.equal cn SN.AutoimportedFunctions.meth_caller && (not @@ in_codegen env) -> let cl = Utils.add_ns cl in Call { call_expr with args = [(pk, (ty, p1, String cl)); meth] } | _ -> call let contexts_ns = Namespace_env. { empty_with_default with ns_name = Some (Utils.strip_ns SN.Coeffects.contexts); } let unsafe_contexts_ns = Namespace_env. { empty_with_default with ns_name = Some (Utils.strip_ns SN.Coeffects.unsafe_contexts); } class ['a, 'b, 'c, 'd] generic_elaborator = object (self) inherit [_] Aast.endo as super method on_'ex _ ex = ex method on_'en _ en = en (* Namespaces were already precomputed by ElaborateDefs * The following functions just set the namespace env correctly *) method! on_class_ env c = let env = { env with namespace = c.c_namespace } in let env = extend_tparams env c.c_tparams in super#on_class_ env c method! on_ctx_refinement env = function | CRexact h -> CRexact (self#on_ctx_hint_ns contexts_ns env h) | CRloose { cr_lower; cr_upper } -> CRloose { cr_lower = Option.map ~f:(self#on_ctx_hint_ns contexts_ns env) cr_lower; cr_upper = Option.map ~f:(self#on_ctx_hint_ns contexts_ns env) cr_upper; } method on_class_ctx_const env kind = match kind with | TCConcrete { c_tc_type } -> TCConcrete { c_tc_type = self#on_ctx_hint_ns contexts_ns env c_tc_type } | TCAbstract { c_atc_as_constraint = as_; c_atc_super_constraint = super; c_atc_default = default; } -> let as_ = Option.map ~f:(self#on_ctx_hint_ns contexts_ns env) as_ in let super = Option.map ~f:(self#on_ctx_hint_ns contexts_ns env) super in let default = Option.map ~f:(self#on_ctx_hint_ns contexts_ns env) default in TCAbstract { c_atc_as_constraint = as_; c_atc_super_constraint = super; c_atc_default = default; } method! on_class_typeconst_def env tc = if tc.c_tconst_is_ctx then let c_tconst_kind = self#on_class_ctx_const env tc.c_tconst_kind in super#on_class_typeconst_def env { tc with c_tconst_kind } else super#on_class_typeconst_def env tc method! on_typedef env td = let env = { env with namespace = td.t_namespace } in let env = extend_tparams env td.t_tparams in if td.t_is_ctx then let t_as_constraint = Option.map ~f:(self#on_ctx_hint_ns contexts_ns env) td.t_as_constraint in let t_super_constraint = Option.map ~f:(self#on_ctx_hint_ns contexts_ns env) td.t_super_constraint in let t_kind = self#on_ctx_hint_ns contexts_ns env td.t_kind in super#on_typedef env { td with t_as_constraint; t_super_constraint; t_kind } else super#on_typedef env td (* Difference between fun_def and fun_ is that fun_ is also lambdas *) method! on_fun_def env f = let env = { env with namespace = f.fd_namespace } in let env = extend_tparams env f.fd_tparams in super#on_fun_def env f method! on_fun_ env f = let f_ctxs = Option.map ~f:(self#on_contexts_ns contexts_ns env) f.f_ctxs in let f_unsafe_ctxs = Option.map ~f:(self#on_contexts_ns unsafe_contexts_ns env) f.f_unsafe_ctxs in { (super#on_fun_ env f) with f_ctxs; f_unsafe_ctxs } method! on_method_ env m = let env = extend_tparams env m.m_tparams in let m_ctxs = Option.map ~f:(self#on_contexts_ns contexts_ns env) m.m_ctxs in let m_unsafe_ctxs = Option.map ~f:(self#on_contexts_ns unsafe_contexts_ns env) m.m_unsafe_ctxs in { (super#on_method_ env m) with m_ctxs; m_unsafe_ctxs } method! on_tparam env tparam = (* Make sure that the nested tparams are in scope while traversing the rest of the tparam, in particular the constraints. See Naming.type_param for description of nested tparam scoping *) let env_with_nested = extend_tparams env tparam.tp_parameters in super#on_tparam env_with_nested tparam method! on_gconst env gc = let env = { env with namespace = gc.cst_namespace } in super#on_gconst env gc method! on_file_attribute env fa = let env = { env with namespace = fa.fa_namespace } in super#on_file_attribute env fa (* Sets let local env correctly *) method on_block_helper env b = let aux (env, stmts) stmt = (env, super#on_stmt env stmt :: stmts) in let (env, rev_stmts) = List.fold b ~f:aux ~init:(env, []) in (env, List.rev rev_stmts) method! on_block env b = let (_, stmts) = self#on_block_helper env b in stmts method! on_catch env (x1, x2, b) = let x1 = elaborate_type_name env x1 in let b = self#on_block env b in (x1, x2, b) method! on_stmt_ env stmt = match stmt with | Foreach (e, ae, b) -> let e = self#on_expr env e in let ae = self#on_as_expr env ae in let b = self#on_block env b in Foreach (e, ae, b) | For (e1, e2, e3, b) -> let on_expr_list env exprs = List.map exprs ~f:(self#on_expr env) in let e1 = on_expr_list env e1 in let e2 = match e2 with | Some e2 -> Some (self#on_expr env e2) | None -> None in let (env, b) = self#on_block_helper env b in let e3 = on_expr_list env e3 in For (e1, e2, e3, b) | Do (b, e) -> let (env, b) = self#on_block_helper env b in let e = self#on_expr env e in Do (b, e) | _ -> super#on_stmt_ env stmt (* The function that actually rewrites names *) method! on_expr_ env expr = let map_arg env_ (pk, e) = (self#on_param_kind env_ pk, self#on_expr env_ e) in match expr with | Collection (id, c_targ_opt, flds) -> let id = NS.elaborate_id env.namespace NS.ElaborateClass id and flds = super#on_list super#on_afield env flds and c_targ_opt = super#on_option super#on_collection_targ env c_targ_opt in Collection (id, c_targ_opt, flds) | Call { func = (ty, p, Id (p2, cn)); targs; args; unpacked_arg } when SN.SpecialFunctions.is_special_function cn -> Call { func = (ty, p, Id (p2, cn)); targs = List.map targs ~f:(self#on_targ env); args = List.map args ~f:(map_arg env); unpacked_arg = Option.map unpacked_arg ~f:(self#on_expr env); } | Call { func = (ty, p, Aast.Id id); targs; args; unpacked_arg } -> let new_id = NS.elaborate_id env.namespace NS.ElaborateFun id in let renamed_call = Call { func = (ty, p, Id new_id); targs = List.map targs ~f:(self#on_targ env); args = List.map args ~f:(map_arg env); unpacked_arg = Option.map unpacked_arg ~f:(self#on_expr env); } in handle_meth_caller env renamed_call | FunctionPointer (FP_id fn, targs) -> let fn = NS.elaborate_id env.namespace NS.ElaborateFun fn in let targs = List.map targs ~f:(self#on_targ env) in FunctionPointer (FP_id fn, targs) | FunctionPointer (FP_class_const (((), p1, CIexpr ((), p2, Id x1)), meth_name), targs) -> let name = elaborate_type_name env x1 in let targs = List.map targs ~f:(self#on_targ env) in FunctionPointer (FP_class_const (((), p1, CIexpr ((), p2, Id name)), meth_name), targs) | Obj_get (e1, (ty, p, Id x), null_safe, in_parens) -> Obj_get (self#on_expr env e1, (ty, p, Id x), null_safe, in_parens) | Id ((_, name) as sid) -> if (String.equal name "NAN" || String.equal name "INF") && in_codegen env then expr else Id (NS.elaborate_id env.namespace NS.ElaborateConst sid) | New (((), p1, CIexpr (ty, p2, Id x)), tal, el, unpacked_element, ex) -> let x = elaborate_type_name env x in New ( ((), p1, CIexpr (ty, p2, Id x)), List.map tal ~f:(self#on_targ env), List.map el ~f:(self#on_expr env), Option.map unpacked_element ~f:(self#on_expr env), ex ) | Class_const ((_, p1, CIexpr (ty, p2, Id x1)), pstr) -> let name = elaborate_type_name env x1 in Class_const (((), p1, CIexpr (ty, p2, Id name)), pstr) | Class_get ((_, p1, CIexpr (ty, p2, Id x1)), cge, in_parens) -> let x1 = elaborate_type_name env x1 in Class_get ( ((), p1, CIexpr (ty, p2, Id x1)), self#on_class_get_expr env cge, in_parens ) | Xml (id, al, el) -> let id = (* if XHP element mangling is disabled, namespaces are supported *) if in_codegen env && not env.namespace.Namespace_env.ns_disable_xhp_element_mangling then id else elaborate_type_name env id in Xml ( id, List.map al ~f:(self#on_xhp_attribute env), List.map el ~f:(self#on_expr env) ) | EnumClassLabel (Some sid, name) -> let sid = elaborate_type_name env sid in EnumClassLabel (Some sid, name) | _ -> super#on_expr_ env expr method! on_hint_ env h = let is_xhp_screwup name = String.equal name "Xhp" || String.equal name ":Xhp" || String.equal name "XHP" in match h with | Happly ((_, name), _) when is_xhp_screwup name -> super#on_hint_ env h | Happly ((_, name), _) when is_reserved_type_hint name && (not @@ in_codegen env) -> super#on_hint_ env h | Happly (x, hl) -> let x = elaborate_type_name env x in Happly (x, List.map hl ~f:(self#on_hint env)) | _ -> super#on_hint_ env h method! on_hint_fun env hf = let hf_ctxs = Option.map ~f:(self#on_contexts_ns contexts_ns env) hf.hf_ctxs in { (super#on_hint_fun env hf) with hf_ctxs } (* For contexts like cipp_of<T>, the type argument needs to be elaborated * in the standard namespace *) method private on_contexts_ns ctx_ns env ctxs = let (p, cs) = ctxs in let cs = List.map ~f:(self#on_ctx_hint_ns ctx_ns env) cs in (p, cs) method private on_ctx_hint_ns ctx_ns env h = let ctx_env = { env with namespace = ctx_ns } in let is_ctx_user_defined ctx = let tokens = Str.split (Str.regexp "\\") ctx in match List.last tokens with | Some ctx_name -> Char.equal ctx_name.[0] (Char.uppercase ctx_name.[0]) (* Char.is_uppercase does not work on unicode characters *) | None -> false in match h with | (p, Happly (((_, x) as ctx), hl)) when not (is_reserved_type_hint x) -> let ctx = if is_ctx_user_defined x then elaborate_type_name env ctx else elaborate_type_name ctx_env ctx in (p, Happly (ctx, List.map hl ~f:(self#on_hint env))) | (p, Hintersection ctxs) -> (p, Hintersection (List.map ctxs ~f:(self#on_ctx_hint_ns ctx_ns env))) | (p, Haccess (root, names)) -> (p, Haccess (self#on_hint env root, names)) | _ -> self#on_hint ctx_env h method! on_shape_field_name env sfn = match sfn with | SFclass_const (x, (pos, y)) -> let x = elaborate_type_name env x in SFclass_const (x, (pos, y)) | _ -> sfn method! on_user_attribute env ua = let ua_name = if SN.UserAttributes.is_reserved (snd ua.ua_name) then ua.ua_name else elaborate_type_name env ua.ua_name in { ua_name; ua_params = List.map ~f:(self#on_expr env) ua.ua_params } method! on_xhp_child env child = if in_codegen env then super#on_xhp_child env child else match child with | ChildName ((_, name) as sid) when (not @@ Naming_special_names.XHP.is_reserved name) && (not @@ Naming_special_names.XHP.is_xhp_category name) -> ChildName (elaborate_type_name env sid) | _ -> super#on_xhp_child env child method! on_program (env : env) (p : ('a, 'b) Aast.program) = let aux (env, defs) def = match def with | SetNamespaceEnv nsenv -> let env = { env with namespace = nsenv } in (env, def :: defs) | _ -> (env, super#on_def env def :: defs) in let (_, rev_defs) = List.fold p ~f:aux ~init:(env, []) in List.rev rev_defs end let elaborate_namespaces = new generic_elaborator let elaborate_program program = elaborate_namespaces#on_program (make_env Namespace_env.empty_with_default) program let elaborate_fun_def fd = elaborate_namespaces#on_fun_def (make_env fd.Aast.fd_namespace) fd let elaborate_class_ c = elaborate_namespaces#on_class_ (make_env c.Aast.c_namespace) c let elaborate_module_def m = elaborate_namespaces#on_module_def (make_env Namespace_env.empty_with_default) m let elaborate_gconst cst = elaborate_namespaces#on_gconst (make_env cst.Aast.cst_namespace) cst let elaborate_typedef td = elaborate_namespaces#on_typedef (make_env td.Aast.t_namespace) td
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elaborate_namespaces_endo.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 elaborate_program : (unit, unit) Aast.program -> Nast.program val elaborate_fun_def : (unit, unit) Aast.fun_def -> Nast.fun_def val elaborate_class_ : (unit, unit) Aast.class_ -> Nast.class_ val elaborate_module_def : (unit, unit) Aast.module_def -> Nast.module_def val elaborate_gconst : (unit, unit) Aast.gconst -> Nast.gconst val elaborate_typedef : (unit, unit) Aast.typedef -> Nast.typedef
OCaml
hhvm/hphp/hack/src/naming/naming_elab_as_expr.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 Err = Naming_phase_error let elab_value = function | (annot, pos, Aast.Id _) -> let err = Err.naming @@ Naming_error.Expected_variable pos in let ident = Local_id.make_unscoped "__internal_placeholder" in ((annot, pos, Aast.Lvar (pos, ident)), Some err) | expr -> (expr, None) let elab_key = function | (_, _, Aast.(Lvar _ | Lplaceholder _)) as expr -> (expr, None) | (annot, pos, _) -> let err = Err.naming @@ Naming_error.Expected_variable pos in let ident = Local_id.make_unscoped "__internal_placeholder" in ((annot, pos, Aast.Lvar (pos, ident)), Some err) let on_as_expr on_error as_expr ~ctx = match as_expr with | Aast.As_v e -> let (e, err_opt) = elab_value e in Option.iter ~f:on_error err_opt; (ctx, Ok (Aast.As_v e)) | Aast.Await_as_v (pos, e) -> let (e, err_opt) = elab_value e in Option.iter ~f:on_error err_opt; (ctx, Ok (Aast.Await_as_v (pos, e))) | Aast.As_kv (ke, ve) -> let (ke, key_err_opt) = elab_key ke in let (ve, val_err_opt) = elab_value ve in Option.iter ~f:on_error key_err_opt; Option.iter ~f:on_error val_err_opt; (ctx, Ok (Aast.As_kv (ke, ve))) | Aast.Await_as_kv (pos, ke, ve) -> let (ke, key_err_opt) = elab_key ke in let (ve, val_err_opt) = elab_value ve in Option.iter ~f:on_error key_err_opt; Option.iter ~f:on_error val_err_opt; (ctx, Ok (Aast.Await_as_kv (pos, ke, ve))) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.bottom_up Aast.Pass. { id with on_ty_as_expr = Some (fun elem ~ctx -> on_as_expr on_error elem ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_as_expr.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 pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_block.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 let rec concat_blocks stmts = match stmts with | [] -> [] | (_, Aast.Block b) :: rest -> concat_blocks (b @ rest) | next :: rest -> let rest = concat_blocks rest in next :: rest let on_block stmts ~ctx = (ctx, Ok (concat_blocks stmts)) let on_using_stmt us ~ctx = (ctx, Ok Aast.{ us with us_is_block_scoped = false }) let pass = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_block = Some on_block; on_ty_using_stmt = Some on_using_stmt; }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_block.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 pass : Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_call.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 SN = Naming_special_names module Env = struct let in_class t Aast.{ c_name; c_kind; c_final; _ } = Naming_phase_env. { t with elab_call = Elab_call.{ current_class = Some (c_name, c_kind, c_final) }; } end let on_expr on_error ((annot, pos, expr_) as expr) ~ctx = let (res, errs) = match expr_ with | Aast.(Call { func = (_, _, Id (_, fn_name)); unpacked_arg; _ } as call) when String.equal fn_name SN.SpecialFunctions.echo -> let errs = Option.to_list @@ Option.map ~f:(fun (_, pos, _) -> Naming_phase_error.naming @@ Naming_error.Too_few_arguments pos) unpacked_arg in (Ok call, errs) | Aast.(Call { func = (_, fn_expr_pos, Id (_, fn_name)); targs; args; _ }) when String.equal fn_name SN.StdlibFunctions.call_user_func -> let errs = [ Naming_phase_error.naming Naming_error.(Deprecated_use { pos = fn_expr_pos; fn_name }); ] in begin match args with | [] -> let args_err = Naming_phase_error.naming @@ Naming_error.Too_few_arguments fn_expr_pos in (Error fn_expr_pos, args_err :: errs) | (Ast_defs.Pnormal, fn_expr) :: fn_param_exprs -> (* TODO[mjt] why are we dropping the unpacked variadic arg here? *) ( Ok Aast.( Call { func = fn_expr; targs; args = fn_param_exprs; unpacked_arg = None; }), errs ) | (Ast_defs.Pinout pk_pos, fn_expr) :: fn_param_exprs -> let (_, fn_expr_pos, _) = fn_expr in let pos = Pos.merge pk_pos fn_expr_pos in let inout_err = Naming_phase_error.nast_check @@ Nast_check_error.Inout_in_transformed_pseudofunction { pos; fn_name = "call_user_func" } in (* TODO[mjt] why are we dropping the unpacked variadic arg here? *) ( Ok Aast.( Call { func = fn_expr; targs; args = fn_param_exprs; unpacked_arg = None; }), inout_err :: errs ) end | Aast.( Call { func = (_, fn_expr_pos, Id (_, fn_name)); args; unpacked_arg; _ }) when String.equal fn_name SN.AutoimportedFunctions.meth_caller -> (* TODO[mjt] targs is ignored entirely here - shouldn't we generate and error to say they are invalid for this function? *) let errs = Option.to_list @@ Option.map ~f:(fun (_, pos, _) -> Naming_phase_error.naming @@ Naming_error.Too_few_arguments pos) unpacked_arg in begin match args with | [] | [_] -> let args_err = Naming_phase_error.naming @@ Naming_error.Too_few_arguments fn_expr_pos in (Error fn_expr_pos, args_err :: errs) | [(Ast_defs.Pnormal, e1); (Ast_defs.Pnormal, e2)] -> begin match (e1, e2) with | Aast.((_, pc, String cl), (_, pm, String meth)) -> (Ok (Aast.Method_caller ((pc, cl), (pm, meth))), errs) | Aast. ( (_, _, Class_const ((_, _, CI cl), (_, mem))), (_, pm, String meth) ) when String.equal mem SN.Members.mClass -> (Ok (Aast.Method_caller (cl, (pm, meth))), errs) | ((_, p, _), _) -> let meth_err = Naming_phase_error.naming @@ Naming_error.Illegal_meth_caller p in (Error p, meth_err :: errs) end | [(Ast_defs.Pinout _, _); _] | [_; (Ast_defs.Pinout _, _)] -> let meth_err = Naming_phase_error.naming @@ Naming_error.Illegal_meth_caller fn_expr_pos in (Error fn_expr_pos, meth_err :: errs) | _ -> let args_err = Naming_phase_error.naming @@ Naming_error.Too_many_arguments fn_expr_pos in (Error fn_expr_pos, args_err :: errs) end | _ -> (Ok expr_, []) in List.iter ~f:on_error errs; match res with | Ok expr_ -> (ctx, Ok (annot, pos, expr_)) | Error _pos -> (ctx, Error (Naming_phase_error.invalid_expr expr)) let on_class_ c ~ctx = (Env.in_class ctx c, Ok c) let top_down_pass = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_class_ = Some (fun elem ~ctx -> on_class_ elem ~ctx) } let bottom_up_pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.bottom_up Aast.Pass. { id with on_ty_expr = Some (fun elem ~ctx -> on_expr on_error elem ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_call.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 top_down_pass : Naming_phase_env.t Naming_phase_pass.t val bottom_up_pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_class_id.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 Err = Naming_phase_error module SN = Naming_special_names module Env = struct let set_in_class t ~in_class = Naming_phase_env.{ t with elab_class_id = Elab_class_id.{ in_class } } let in_class Naming_phase_env.{ elab_class_id = Elab_class_id.{ in_class }; _ } = in_class end let on_class_ c ~ctx = (Env.set_in_class ctx ~in_class:true, Ok c) (* The attributes applied to a class exist outside the current class so references to `self` are invalid *) let on_class_c_user_attributes c_user_attributes ~ctx = (Env.set_in_class ctx ~in_class:false, Ok c_user_attributes) (* The lowerer will give us CIexpr (Id _ | Lvar _ ); here we: - convert CIexpr(_,_,Id _) to CIparent, CIself, CIstatic and CI. - convert CIexpr(_,_,Lvar $this) to CIexpr(_,_,This) If there is a CIexpr with anything other than an Lvar or This after this elaboration step, it is an error and will be raised in subsequent validation passes TODO[mjt] We're overriding `on_class` rather than `on_class_` since the legacy code mangles positions by using the inner `class_id_` position in the output `class_id` tuple. This looks to be erroneous. *) let on_class_id on_error class_id ~ctx = let in_class = Env.in_class ctx in let (class_id, err_opt) = match class_id with (* TODO[mjt] if we don't expect these from lowering should we refine the NAST repr? *) | (_, _, Aast.(CIparent | CIself | CIstatic | CI _)) -> (class_id, None) | (annot, _, Aast.(CIexpr (_, expr_pos, Id (id_pos, cname)))) -> if String.equal cname SN.Classes.cParent then if not in_class then ( (annot, expr_pos, Aast.CI (expr_pos, SN.Classes.cUnknown)), Some (Err.naming @@ Naming_error.Parent_outside_class id_pos) ) else ((annot, expr_pos, Aast.CIparent), None) else if String.equal cname SN.Classes.cSelf then if not in_class then ( (annot, expr_pos, Aast.CI (expr_pos, SN.Classes.cUnknown)), Some (Err.naming @@ Naming_error.Self_outside_class id_pos) ) else ((annot, expr_pos, Aast.CIself), None) else if String.equal cname SN.Classes.cStatic then if not in_class then ( (annot, expr_pos, Aast.CI (expr_pos, SN.Classes.cUnknown)), Some (Err.naming @@ Naming_error.Static_outside_class id_pos) ) else ((annot, expr_pos, Aast.CIstatic), None) else ((annot, expr_pos, Aast.CI (expr_pos, cname)), None) | (annot, _, Aast.(CIexpr (ci_annot, expr_pos, Lvar (lid_pos, lid)))) when String.equal (Local_id.to_string lid) SN.SpecialIdents.this -> (* TODO[mjt] why is `$this` valid outside a class? *) (Aast.(annot, expr_pos, CIexpr (ci_annot, lid_pos, This)), None) | (annot, _, (Aast.(CIexpr (_, expr_pos, _)) as class_id_)) -> ((annot, expr_pos, class_id_), None) in Option.iter ~f:on_error err_opt; (ctx, Ok class_id) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_class_ = Some on_class_; on_fld_class__c_user_attributes = Some on_class_c_user_attributes; on_ty_class_id = Some (fun elem ~ctx -> on_class_id on_error elem ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_class_id.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 pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_class_members.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. * *) (* * 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 SN = Naming_special_names module Env = struct let like_type_hints_enabled Naming_phase_env.{ like_type_hints_enabled; _ } = like_type_hints_enabled end let exists_both p1 p2 xs = let rec aux (b1, b2) = function | _ when b1 && b2 -> (b1, b2) | [] -> (b1, b2) | next :: rest -> aux (b1 || p1 next, b2 || p2 next) rest in aux (false, false) xs let xhp_attr_hint items = let is_int = function | (_, _, Aast.Int _) -> true | _ -> false and is_string = function | (_, _, Aast.(String _ | String2 _)) -> true | _ -> false in match exists_both is_int is_string items with | (true, false) -> Aast.(Hprim Tint) | (_, true) -> Aast.(Hprim Tstring) | _ -> Aast.Hmixed let strip_like = function | Aast.Hlike (_, hint_) -> hint_ | hint_ -> hint_ (* TODO[mjt] is there no other way of determining this? *) let is_xhp cv_name = try String.(sub cv_name ~pos:0 ~len:1 = ":") with | Invalid_argument _ -> false let elab_class_prop (Aast.{ cv_id = (_, cv_name); _ } as cv) = let cv_xhp_attr = if is_xhp cv_name then Some Aast.{ xai_like = None; xai_tag = None; xai_enum_values = [] } else None in Aast.{ cv with cv_xhp_attr } let elab_non_static_class_prop const_attr_opt (Aast.{ cv_user_attributes; _ } as cv) = let cv = elab_class_prop cv in let cv_user_attributes = match const_attr_opt with | Some ua when not @@ Naming_attributes.mem SN.UserAttributes.uaConst cv_user_attributes -> ua :: cv_user_attributes | _ -> cv_user_attributes in Aast.{ cv with cv_user_attributes } let elab_xhp_attr like_type_hints_enabled (type_hint, cv, xhp_attr_tag_opt, enum_opt) = let is_required = Option.is_some xhp_attr_tag_opt and has_default = Option.value_map ~default:false ~f:(function | (_, _, Aast.Null) -> false | _ -> true) cv.Aast.cv_expr in let (xai_like, xai_enum_values) = match cv.Aast.cv_xhp_attr with | Some xai -> (xai.Aast.xai_like, xai.Aast.xai_enum_values) | None -> (None, []) in let hint_opt = Option.value_map enum_opt ~default:(Aast.hint_of_type_hint type_hint) ~f:(fun (pos, items) -> Some (pos, xhp_attr_hint items)) in let (hint_opt, req_attr_err) = Option.value_map hint_opt ~default:(None, None) ~f:(fun ((pos, hint_) as hint) -> match strip_like hint_ with | Aast.Hoption _ -> let err = if is_required then Some (Naming_phase_error.naming @@ Naming_error.Xhp_optional_required_attr { pos; attr_name = snd @@ cv.Aast.cv_id }) else None in (Some hint, err) | Aast.Hmixed -> (Some hint, None) | _ when is_required || has_default -> (Some hint, None) | _ -> (Some (pos, Aast.Hoption hint), None)) in let (hint_opt, like_err) = Option.value ~default:(hint_opt, None) @@ Option.map2 hint_opt xai_like ~f:(fun hint pos -> ( Some (pos, Aast.Hlike hint), if like_type_hints_enabled then None else Some (Naming_phase_error.like_type pos) )) in let cv_type = (fst type_hint, hint_opt) and cv_xhp_attr = Some Aast.{ xai_like; xai_tag = xhp_attr_tag_opt; xai_enum_values } in let errs = List.filter_map ~f:Fn.id [req_attr_err; like_err] in (Aast.{ cv with cv_xhp_attr; cv_type; cv_user_attributes = [] }, errs) let on_class_ on_error (Aast.{ c_vars; c_xhp_attrs; c_methods; c_user_attributes; _ } as c) ~ctx = let (c, errs) = let (c_vars, err) = let (static_props, props) = Aast.split_vars c_vars in let const_attr_opt = Naming_attributes.find SN.UserAttributes.uaConst c_user_attributes in let static_props = List.map ~f:elab_class_prop static_props and props = List.map ~f:(elab_non_static_class_prop const_attr_opt) props and (xhp_attrs, xhp_attrs_err) = List.unzip @@ List.map ~f:(elab_xhp_attr (Env.like_type_hints_enabled ctx)) c_xhp_attrs in (static_props @ props @ xhp_attrs, List.concat xhp_attrs_err) in let c_methods = if Ast_defs.is_c_interface c.Aast.c_kind then List.map c_methods ~f:(fun m -> Aast.{ m with m_abstract = true }) else c_methods in (Aast.{ c with c_methods; c_vars; c_xhp_attrs = [] }, err) in List.iter ~f:on_error errs; (ctx, Ok c) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.bottom_up Aast.Pass. { id with on_ty_class_ = Some (fun elem ~ctx -> on_class_ on_error elem ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_class_members.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 pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_collection.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 Err = Naming_phase_error module SN = Naming_special_names let afield_value cname afield = match afield with | Aast.AFvalue e -> (e, None) | Aast.AFkvalue (((_, pos, _) as e), _) -> (e, Some (Err.naming @@ Naming_error.Unexpected_arrow { pos; cname })) let afield_key_value cname afield = match afield with | Aast.AFkvalue (ek, ev) -> ((ek, ev), None) | Aast.AFvalue ((annot, pos, _) as ek) -> let ev = ( annot, pos, Aast.Lvar (pos, Local_id.make_unscoped "__internal_placeholder") ) in ((ek, ev), Some (Err.naming @@ Naming_error.Missing_arrow { pos; cname })) let on_expr on_error ((annot, pos, expr_) as expr) ~ctx = let res = match expr_ with | Aast.Collection ((pos, cname), c_targ_opt, afields) when Nast.is_vc_kind cname -> let (targ_opt, targ_err_opt) = match c_targ_opt with | Some (Aast.CollectionTV tv) -> (Some tv, None) | Some (Aast.CollectionTKV _) -> (None, Some (Err.naming @@ Naming_error.Too_many_arguments pos)) | _ -> (None, None) in let (exprs, fields_err_opts) = List.unzip @@ List.map ~f:(afield_value cname) afields in let vc_kind = Nast.get_vc_kind cname in let err = List.filter_map ~f:Fn.id @@ (targ_err_opt :: fields_err_opts) in Ok (Aast.ValCollection ((pos, vc_kind), targ_opt, exprs), err) | Aast.Collection ((pos, cname), c_targ_opt, afields) when Nast.is_kvc_kind cname -> let (targs_opt, targ_err_opt) = match c_targ_opt with | Some (Aast.CollectionTKV (tk, tv)) -> (Some (tk, tv), None) | Some (Aast.CollectionTV _) -> (None, Some (Err.naming @@ Naming_error.Too_few_arguments pos)) | _ -> (None, None) in let (fields, fields_err_opts) = List.unzip @@ List.map ~f:(afield_key_value cname) afields in let kvc_kind = Nast.get_kvc_kind cname in let err = List.filter_map ~f:Fn.id @@ (targ_err_opt :: fields_err_opts) in Ok (Aast.KeyValCollection ((pos, kvc_kind), targs_opt, fields), err) | Aast.Collection ((pos, cname), _, []) when String.equal SN.Collections.cPair cname -> Error (pos, [Err.naming @@ Naming_error.Too_few_arguments pos]) | Aast.Collection ((pos, cname), c_targ_opt, [fst; snd]) when String.equal SN.Collections.cPair cname -> let (targs_opt, targ_err_opt) = match c_targ_opt with | Some (Aast.CollectionTKV (tk, tv)) -> (Some (tk, tv), None) | Some (Aast.CollectionTV _) -> (None, Some (Err.naming @@ Naming_error.Too_few_arguments pos)) | _ -> (None, None) in let (fst, fst_err_opt) = afield_value SN.Collections.cPair fst and (snd, snd_err_opt) = afield_value SN.Collections.cPair snd in let err = List.filter_map ~f:Fn.id [targ_err_opt; fst_err_opt; snd_err_opt] in Ok (Aast.Pair (targs_opt, fst, snd), err) | Aast.Collection ((pos, cname), _, _) when String.equal SN.Collections.cPair cname -> Error (pos, [Err.naming @@ Naming_error.Too_many_arguments pos]) | Aast.Collection ((pos, cname), _, _) -> Error (pos, [Err.naming @@ Naming_error.Expected_collection { pos; cname }]) | _ -> Ok (expr_, []) in match res with | Ok (expr_, errs) -> List.iter ~f:on_error errs; (ctx, Ok (annot, pos, expr_)) | Error (_pos, errs) -> List.iter ~f:on_error errs; (ctx, Error (Err.invalid_expr expr)) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_expr = Some (fun elem ~ctx -> on_expr on_error elem ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_collection.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 pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_const_expr.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 Err = Naming_phase_error module SN = Naming_special_names module Env = struct let in_mode Naming_phase_env.{ elab_const_expr = Elab_const_expr.{ in_mode; _ }; _ } = in_mode let in_enum_class Naming_phase_env. { elab_const_expr = Elab_const_expr.{ in_enum_class; _ }; _ } = in_enum_class let enforce_const_expr Naming_phase_env. { elab_const_expr = Elab_const_expr.{ enforce_const_expr; _ }; _ } = enforce_const_expr let set_mode t ~in_mode = Naming_phase_env. { t with elab_const_expr = Elab_const_expr.{ t.elab_const_expr with in_mode }; } let set_in_enum_class t ~in_enum_class = Naming_phase_env. { t with elab_const_expr = Elab_const_expr.{ t.elab_const_expr with in_enum_class }; } let set_enforce_const_expr t ~enforce_const_expr = Naming_phase_env. { t with elab_const_expr = Elab_const_expr.{ t.elab_const_expr with enforce_const_expr }; } end (* We can determine that certain expressions are invalid based on one-level pattern matching. We prefer to do this since we can stop the transformation early in these cases. For cases where we need to pattern match on the expression more deeply, we use the bottom-up pass *) let on_expr_top_down (on_error : Naming_phase_error.t -> unit) ((_annot, pos, expr_) as expr) ~ctx = if not @@ Env.enforce_const_expr ctx then (ctx, Ok expr) else begin match expr_ with (* -- Always valid ------------------------------------------------------ *) | Aast.( ( Id _ | Null | True | False | Int _ | Float _ | String _ | FunctionPointer _ | Eif _ | Darray _ | Varray _ | Tuple _ | Shape _ | Upcast _ | Package _ )) -> (ctx, Ok expr) (* -- Markers ----------------------------------------------------------- *) | Aast.(Invalid _ | Hole _) -> (ctx, Ok expr) (* -- Handled bottom up ------------------------------------------------- *) | Aast.(Class_const _) -> (ctx, Ok expr) (* -- Conditionally valid ----------------------------------------------- *) (* NB we can perform this top-down since the all valid hints are already in canonical *) | Aast.(As (_, (_, hint_), _)) -> begin match hint_ with | Aast.(Happly ((pos, _), _)) -> on_error (Err.naming @@ Naming_error.Illegal_constant pos); (ctx, Error (Err.invalid_expr expr)) | _ -> on_error (Err.naming @@ Naming_error.Illegal_constant pos); (ctx, Error (Err.invalid_expr expr)) end | Aast.(Unop (uop, _)) -> begin match uop with | Ast_defs.(Uplus | Uminus | Utild | Unot) -> (ctx, Ok expr) | _ -> on_error (Err.naming @@ Naming_error.Illegal_constant pos); (ctx, Error (Err.invalid_expr expr)) end | Aast.(Binop { bop; _ }) -> begin match bop with | Ast_defs.Eq _ -> on_error (Err.naming @@ Naming_error.Illegal_constant pos); (ctx, Error (Err.invalid_expr expr)) | _ -> (ctx, Ok expr) end | Aast.(ValCollection ((_, vc_kind), _, _)) -> begin match vc_kind with | Aast.(Vec | Keyset) -> (ctx, Ok expr) | _ -> on_error (Err.naming @@ Naming_error.Illegal_constant pos); (ctx, Error (Err.invalid_expr expr)) end | Aast.(KeyValCollection ((_, kvc_kind), _, _)) -> begin match kvc_kind with | Aast.Dict -> (ctx, Ok expr) | _ -> on_error (Err.naming @@ Naming_error.Illegal_constant pos); (ctx, Error (Err.invalid_expr expr)) end | Aast.(Call { func = (_, _, call_expr_); _ }) -> begin match call_expr_ with | Aast.(Id (_, nm)) when String.( nm = SN.StdlibFunctions.array_mark_legacy || nm = SN.PseudoFunctions.unsafe_cast || nm = SN.PseudoFunctions.unsafe_nonnull_cast) -> (ctx, Ok expr) | _ -> on_error (Err.naming @@ Naming_error.Illegal_constant pos); (ctx, Error (Err.invalid_expr expr)) end | Aast.Omitted -> begin match Env.in_mode ctx with | FileInfo.Mhhi -> (ctx, Ok expr) | _ -> on_error (Err.naming @@ Naming_error.Illegal_constant pos); (ctx, Error (Err.invalid_expr expr)) end (* -- Always invalid ---------------------------------------------------- *) | Aast.( ( This | Lvar _ | Lplaceholder _ | Array_get _ | Await _ | Cast _ | Class_get _ | Clone _ | Dollardollar _ | ET_Splice _ | Efun _ | EnumClassLabel _ | ExpressionTree _ | Is _ | Lfun _ | List _ | Method_caller _ | New _ | Obj_get _ | Pair _ | Pipe _ | PrefixedString _ | ReadonlyExpr _ | String2 _ | Yield _ | Xml _ )) -> on_error (Err.naming @@ Naming_error.Illegal_constant pos); (ctx, Error (Err.invalid_expr expr)) (* -- Unexpected expressions -------------------------------------------- *) | Aast.(Import _ | Collection _) -> raise (Err.UnexpectedExpr pos) end (* Handle non-constant expressions which require pattern matching on some element of the expression which is not yet transformed in the top-down pass *) let on_expr_bottom_up on_error ((_annot, pos, expr_) as expr) ~ctx = if not @@ Env.enforce_const_expr ctx then (ctx, Ok expr) else begin match expr_ with | Aast.(Class_const ((_, _, class_id_), _)) -> begin (* We have to handle this case bottom-up since the class identifier will not have been rewritten in the top-down pass *) match class_id_ with | Aast.CIstatic -> on_error (Err.naming @@ Naming_error.Illegal_constant pos); (ctx, Error (Err.invalid_expr expr)) | Aast.(CIparent | CIself | CI _) -> (ctx, Ok expr) | Aast.CIexpr (_, _, expr_) -> begin match expr_ with (* NB this relies on `class_id` elaboration having been applied, if it hasn't we would still have `CIstatic` represented as `CIexpr (_,_,Id(_,'static'))` *) | Aast.(This | Id _) -> (ctx, Ok expr) | _ -> on_error (Err.naming @@ Naming_error.Illegal_constant pos); (ctx, Error (Err.invalid_expr expr)) end end | _ -> (ctx, Ok expr) end let on_class_ c ~ctx = let in_enum_class = match c.Aast.c_kind with | Ast_defs.Cenum_class _ -> true | Ast_defs.(Cclass _ | Cinterface | Cenum | Ctrait) -> false in let ctx = Env.set_in_enum_class ~in_enum_class @@ Env.set_mode ~in_mode:c.Aast.c_mode ctx in (ctx, Ok c) let on_gconst cst ~ctx = let ctx = Env.set_mode ctx ~in_mode:cst.Aast.cst_mode in let ctx = Env.set_enforce_const_expr ctx ~enforce_const_expr:true in (ctx, Ok cst) let on_typedef t ~ctx = (Env.set_mode ctx ~in_mode:t.Aast.t_mode, Ok t) let on_fun_def fd ~ctx = (Env.set_mode ctx ~in_mode:fd.Aast.fd_mode, Ok fd) let on_module_def md ~ctx = (Env.set_mode ctx ~in_mode:md.Aast.md_mode, Ok md) let on_class_const_kind kind ~ctx = let enforce_const_expr = (not (Env.in_enum_class ctx)) && match kind with | Aast.CCConcrete _ -> true | Aast.CCAbstract _ -> false in let ctx = Env.set_enforce_const_expr ctx ~enforce_const_expr in (ctx, Ok kind) let top_down_pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_class_ = Some on_class_; on_ty_gconst = Some on_gconst; on_ty_typedef = Some on_typedef; on_ty_fun_def = Some on_fun_def; on_ty_module_def = Some on_module_def; on_ty_class_const_kind = Some on_class_const_kind; on_ty_expr = Some (fun expr ~ctx -> on_expr_top_down on_error expr ~ctx); } let bottom_up_pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.bottom_up Aast.Pass. { id with on_ty_expr = Some (fun expr ~ctx -> on_expr_bottom_up on_error expr ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_const_expr.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 top_down_pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t val bottom_up_pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_defs.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 (* TODO[mjt] - this will only remove top-level definititions so, for instance, we can't guarantee that `Noop` or `Markup` are not contained in say, a function body. We should either move these to top-level defs _or_ fully recurse to remove them *) let on_program program ~ctx = let rec aux acc def = match def with (* These are elaborated away in Namespaces.elaborate_toplevel_defs *) | Aast.FileAttributes _ | Aast.Stmt (_, Aast.Noop) | Aast.Stmt (_, Aast.Markup _) | Aast.NamespaceUse _ | Aast.SetNamespaceEnv _ -> acc | Aast.Stmt _ | Aast.Fun _ | Aast.Class _ | Aast.Typedef _ | Aast.Constant _ | Aast.Module _ | Aast.SetModule _ -> def :: acc | Aast.Namespace (_ns, aast) -> List.fold_left ~f:aux ~init:[] aast @ acc in let program = List.rev @@ List.fold_left ~f:aux ~init:[] program in (ctx, Ok program) let pass = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass.{ id with on_ty_program = Some on_program }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_defs.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 pass : Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_dynamic_class_name.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude module Err = Naming_phase_error module SN = Naming_special_names let is_dynamic = function | Aast.( ( CIparent | CIself | CIstatic | CI _ | CIexpr (_, _, (Lvar _ | This | Dollardollar _)) )) -> false | _ -> true let on_expr on_error ((ex, pos, expr_) as expr) ~ctx = let res = let open Aast in match expr_ with | Aast.(New ((annot, ci_pos, ci), targs, exprs, expr_opt, ann)) when is_dynamic ci -> let err = Err.naming @@ Naming_error.Dynamic_new_in_strict_mode ci_pos in let class_id = (annot, pos, Aast.CI (ci_pos, SN.Classes.cUnknown)) in let expr_ = Aast.New (class_id, targs, exprs, expr_opt, ann) in Ok (expr_, [err]) (* TODO[mjt] can we decompose this case further? This is considering both the class_id and the class_get_expr *) | Class_get ((_, _, ci), CGstring _, _prop_or_meth) when not @@ is_dynamic ci -> Ok (expr_, []) | Class_get ((_, _, ci), CGexpr (_, cg_expr_pos, _), Ast_defs.Is_method) when not @@ is_dynamic ci -> let err = Err.naming @@ Naming_error.Dynamic_method_access cg_expr_pos in Ok (expr_, [err]) | Class_get ( (_, _, CIexpr (_, ci_pos, _)), (CGstring _ | CGexpr (_, _, (Lvar _ | This))), _prop_or_meth ) -> let err = Err.naming @@ Naming_error.Dynamic_class_name_in_strict_mode ci_pos in Error [err] | Class_get ((_, _, CIexpr (_, ci_pos, _)), CGexpr (_, cg_pos, _), _prop_or_meth) -> let err1 = Err.naming @@ Naming_error.Dynamic_class_name_in_strict_mode ci_pos in (* TODO[mjt] this seems like the wrong error? Shouldn't this be `Dynamic_method_access` as in the case above? *) let err2 = Err.naming @@ Naming_error.Dynamic_class_name_in_strict_mode cg_pos in Error [err1; err2] | Class_get (_, Aast.CGexpr (_, cg_pos, _), _prop_or_meth) -> let err = Err.naming @@ Naming_error.Dynamic_class_name_in_strict_mode cg_pos in Error [err] | Aast.(FunctionPointer (FP_class_const ((_, _, ci), _), _)) when is_dynamic ci -> (* TODO[mjt] report error in strict mode *) Error [] | Aast.Class_const ((_, _, ci), _) when is_dynamic ci -> (* TODO[mjt] report error in strict mode *) Error [] | _ -> Ok (expr_, []) in match res with | Error errs -> List.iter ~f:on_error errs; (ctx, Error (Err.invalid_expr expr)) | Ok (expr_, errs) -> List.iter ~f:on_error errs; (ctx, Ok (ex, pos, expr_)) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.bottom_up Aast.Pass. { id with on_ty_expr = Some (fun elem ~ctx -> on_expr on_error elem ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_dynamic_class_name.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_enum_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 module SN = Naming_special_names module Err = Naming_phase_error module Env = struct let is_systemlib Naming_phase_env.{ is_systemlib; _ } = is_systemlib let is_hhi Naming_phase_env.{ is_hhi; _ } = is_hhi end let on_hint_ on_error hint_ ~ctx = let err_opt = if Env.is_systemlib ctx || Env.is_hhi ctx then None else match hint_ with | Aast.Happly ((pos, ty_name), _) when String.( equal ty_name SN.Classes.cHH_BuiltinEnum || equal ty_name SN.Classes.cHH_BuiltinEnumClass || equal ty_name SN.Classes.cHH_BuiltinAbstractEnumClass) -> Some (Err.naming @@ Naming_error.Using_internal_class { pos; class_name = Utils.strip_ns ty_name }) | _ -> None in Option.iter ~f:on_error err_opt; (ctx, Ok hint_) let on_class_ (Aast.{ c_kind; c_enum; c_name; _ } as c) ~ctx = let c = let pos = fst c_name in match c_enum with | Some Aast.{ e_base; _ } -> let enum_hint = (pos, Aast.Happly (c_name, [])) in let (cls_name, bounds) = match c_kind with | Ast_defs.(Cenum_class Concrete) -> (* Turn the base type of the enum class into MemberOf<E, base> *) let bounds = [ ( pos, Aast.Happly ((pos, SN.Classes.cMemberOf), [enum_hint; e_base]) ); ] in (SN.Classes.cHH_BuiltinEnumClass, bounds) | Ast_defs.(Cenum_class Abstract) -> (SN.Classes.cHH_BuiltinAbstractEnumClass, []) | _ -> (SN.Classes.cHH_BuiltinEnum, [enum_hint]) in let c_extends = (pos, Aast.Happly ((pos, cls_name), bounds)) :: c.Aast.c_extends in Aast.{ c with c_extends } | _ -> c in (ctx, Ok c) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.bottom_up Aast.Pass. { id with on_ty_hint_ = Some (on_hint_ on_error); on_ty_class_ = Some on_class_; }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_enum_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. * *) val pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_everything_sdt.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 SN = Naming_special_names module Env = struct let in_is_as Naming_phase_env. { elab_everything_sdt = Elab_everything_sdt.{ in_is_as; _ }; _ } = in_is_as let set_in_is_as t ~in_is_as = Naming_phase_env. { t with elab_everything_sdt = Elab_everything_sdt.{ t.elab_everything_sdt with in_is_as }; } let in_enum_class Naming_phase_env. { elab_everything_sdt = Elab_everything_sdt.{ in_enum_class; _ }; _ } = in_enum_class let set_in_enum_class t ~in_enum_class = Naming_phase_env. { t with elab_everything_sdt = Elab_everything_sdt.{ t.elab_everything_sdt with in_enum_class }; } let set_under_no_auto_dynamic t ~under_no_auto_dynamic = Naming_phase_env. { t with elab_everything_sdt = Elab_everything_sdt. { t.elab_everything_sdt with under_no_auto_dynamic }; } let set_under_no_auto_likes t ~under_no_auto_likes = Naming_phase_env. { t with elab_everything_sdt = Elab_everything_sdt.{ t.elab_everything_sdt with under_no_auto_likes }; } let everything_sdt Naming_phase_env.{ everything_sdt; _ } = everything_sdt let under_no_auto_dynamic Naming_phase_env. { elab_everything_sdt = Elab_everything_sdt.{ under_no_auto_dynamic; _ }; _; } = under_no_auto_dynamic let under_no_auto_likes Naming_phase_env. { elab_everything_sdt = Elab_everything_sdt.{ under_no_auto_likes; _ }; _; } = under_no_auto_likes let implicit_sdt env = everything_sdt env && not (under_no_auto_dynamic env) let everything_sdt Naming_phase_env.{ everything_sdt; _ } = everything_sdt end let no_auto_dynamic_attr ua = Naming_attributes.mem SN.UserAttributes.uaNoAutoDynamic ua let no_auto_likes_attr ua = Naming_attributes.mem SN.UserAttributes.uaNoAutoLikes ua let no_auto_bound_attr ua = Naming_attributes.mem SN.UserAttributes.uaNoAutoBound ua let wrap_supportdyn p h = Aast.Happly ((p, SN.Classes.cSupportDyn), [(p, h)]) let possibly_wrap_like env ((pos, _) as hint) = if Env.under_no_auto_likes env then hint else (pos, Aast.Hlike hint) let on_expr_ expr_ ~ctx = let ctx = match expr_ with | Aast.(Is _ | As _) -> Env.set_in_is_as ctx ~in_is_as:true | _ -> Env.set_in_is_as ctx ~in_is_as:false in (ctx, Ok expr_) let on_hint hint ~ctx = let hint = if Env.implicit_sdt ctx then match hint with | (pos, (Aast.(Hmixed | Hnonnull) as hint_)) when not @@ Env.in_is_as ctx -> (pos, wrap_supportdyn pos hint_) | ( pos, (Aast.Hshape Aast.{ nsi_allows_unknown_fields = true; _ } as hint_) ) -> (pos, wrap_supportdyn pos hint_) (* Return types and inout parameter types are pessimised *) | (pos, Aast.Hfun hint_fun) -> let hf_param_tys = match List.map2 hint_fun.Aast.hf_param_info hint_fun.Aast.hf_param_tys ~f:(fun p ty -> match p with | Some { Aast.hfparam_kind = Ast_defs.Pinout _; _ } -> possibly_wrap_like ctx ty | _ -> ty) with | List.Or_unequal_lengths.Ok res -> res (* Shouldn't happen *) | List.Or_unequal_lengths.Unequal_lengths -> hint_fun.Aast.hf_param_tys in let hf_return_ty = possibly_wrap_like ctx hint_fun.Aast.hf_return_ty in let hint_ = Aast.(Hfun { hint_fun with hf_return_ty; hf_param_tys }) in (pos, wrap_supportdyn pos hint_) | _ -> hint else hint in (ctx, Ok hint) let on_fun_def_top_down fd ~ctx = let ctx = Env.set_under_no_auto_dynamic ctx ~under_no_auto_dynamic: (no_auto_dynamic_attr Aast.(fd.fd_fun.f_user_attributes)) in let ctx = Env.set_under_no_auto_likes ctx ~under_no_auto_likes: (no_auto_likes_attr Aast.(fd.fd_fun.f_user_attributes)) in (ctx, Ok fd) let on_fun_def fd ~ctx = let ctx = Env.set_under_no_auto_dynamic ctx ~under_no_auto_dynamic: (no_auto_dynamic_attr Aast.(fd.fd_fun.f_user_attributes)) in let ctx = Env.set_under_no_auto_likes ctx ~under_no_auto_likes: (no_auto_likes_attr Aast.(fd.fd_fun.f_user_attributes)) in let fd_fun = fd.Aast.fd_fun in let fd_fun = if Env.implicit_sdt ctx then let (pos, _) = fd.Aast.fd_name in let f_user_attributes = Aast. { ua_name = (pos, SN.UserAttributes.uaSupportDynamicType); ua_params = []; } :: fd_fun.Aast.f_user_attributes in Aast.{ fd_fun with f_user_attributes } else fd_fun in let fd = Aast.{ fd with fd_fun } in (ctx, Ok fd) let on_tparam t ~ctx = let t = if Env.implicit_sdt ctx && not (no_auto_bound_attr t.Aast.tp_user_attributes) then let (pos, _) = t.Aast.tp_name in let tp_constraints = (Ast_defs.Constraint_as, (pos, wrap_supportdyn pos Aast.Hmixed)) :: t.Aast.tp_constraints in Aast.{ t with tp_constraints } else t in (ctx, Ok t) let on_typedef_top_down t ~ctx = let ctx = Env.set_under_no_auto_dynamic ctx ~under_no_auto_dynamic:(no_auto_dynamic_attr t.Aast.t_user_attributes) in let ctx = Env.set_under_no_auto_likes ctx ~under_no_auto_likes:(no_auto_likes_attr t.Aast.t_user_attributes) in (ctx, Ok t) let on_typedef t ~ctx = let ctx = Env.set_under_no_auto_dynamic ctx ~under_no_auto_dynamic:(no_auto_dynamic_attr t.Aast.t_user_attributes) in let ctx = Env.set_under_no_auto_likes ctx ~under_no_auto_likes:(no_auto_likes_attr t.Aast.t_user_attributes) in Aast_defs.( let (pos, _) = t.Aast.t_name in let t_as_constraint = if Env.implicit_sdt ctx then match t.t_as_constraint with | Some _ -> t.t_as_constraint | None -> begin (* If this isn't just a type alias then we need to add supportdyn<mixed> as upper bound *) match t.t_vis with | Transparent -> None | _ -> Some (pos, wrap_supportdyn pos Aast.Hmixed) end else t.t_as_constraint in (ctx, Ok Aast.{ t with t_as_constraint })) let on_class_top_down c ~ctx = let in_enum_class = match c.Aast.c_kind with | Ast_defs.Cenum_class _ -> true | _ -> false in let ctx = Env.set_in_enum_class ctx ~in_enum_class in let ctx = Env.set_under_no_auto_dynamic ctx ~under_no_auto_dynamic:(no_auto_dynamic_attr c.Aast.c_user_attributes) in (ctx, Ok c) let on_class_ c ~ctx = let ctx = Env.set_under_no_auto_dynamic ctx ~under_no_auto_dynamic:(no_auto_dynamic_attr c.Aast.c_user_attributes) in let c = if Env.implicit_sdt ctx then let (pos, _) = c.Aast.c_name in let c_user_attributes = match c.Aast.c_kind with | Ast_defs.(Cclass _ | Cinterface | Ctrait) -> Aast. { ua_name = (pos, SN.UserAttributes.uaSupportDynamicType); ua_params = []; } :: c.Aast.c_user_attributes | _ -> c.Aast.c_user_attributes in Aast.{ c with c_user_attributes } else c in (ctx, Ok c) let on_class_c_consts c_consts ~ctx = let c_consts = if Env.everything_sdt ctx && Env.in_enum_class ctx then let elab_hint = function | ( pos, Aast.( Happly ((p_member_of, c_member_of), [((p1, Happly _) as h1); h2])) ) when String.equal c_member_of SN.Classes.cMemberOf -> (pos, Aast.(Happly ((p_member_of, c_member_of), [h1; (p1, Hlike h2)]))) | hint -> hint in List.map ~f:(fun c_const -> Aast. { c_const with cc_type = Option.map ~f:elab_hint c_const.cc_type }) c_consts else c_consts in (ctx, Ok c_consts) let on_enum_ e ~ctx = let e = if Env.everything_sdt ctx && Env.in_enum_class ctx then let e_base = possibly_wrap_like ctx e.Aast.e_base in Aast.{ e with e_base } else e in (ctx, Ok e) let on_method_top_down m ~ctx = let ctx = Env.set_under_no_auto_dynamic ctx ~under_no_auto_dynamic: (no_auto_dynamic_attr m.Aast.m_user_attributes || Env.under_no_auto_dynamic ctx) in let ctx = Env.set_under_no_auto_likes ctx ~under_no_auto_likes:(no_auto_likes_attr m.Aast.m_user_attributes) in (ctx, Ok m) let top_down_pass = let id = Aast.Pass.identity () in Naming_phase_pass.( top_down Aast.Pass. { id with on_ty_fun_def = Some on_fun_def_top_down; on_ty_class_ = Some on_class_top_down; on_ty_method_ = Some on_method_top_down; on_ty_expr_ = Some on_expr_; on_ty_typedef = Some on_typedef_top_down; }) let bottom_up_pass = let id = Aast.Pass.identity () in Naming_phase_pass.bottom_up Aast.Pass. { id with on_ty_hint = Some on_hint; on_ty_fun_def = Some on_fun_def; on_ty_tparam = Some on_tparam; on_ty_class_ = Some on_class_; on_fld_class__c_consts = Some on_class_c_consts; on_ty_enum_ = Some on_enum_; on_ty_typedef = Some on_typedef; }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_everything_sdt.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. * *) (* This elaboration pass will: - pessimise return types; and - add `SupportDyn` attributes to classes; and - add upper bounds to type parameters. It is intended for use when the `--everything-sdt` typechecker option is set *) val top_down_pass : Naming_phase_env.t Naming_phase_pass.t val bottom_up_pass : Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_func_body.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. * *) (* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module Env = struct let in_mode Naming_phase_env.{ elab_func_body = Elab_func_body.{ in_mode }; _ } = in_mode let set_mode t ~in_mode = Naming_phase_env.{ t with elab_func_body = Elab_func_body.{ in_mode } } end let on_func_body func_body ~ctx = let func_body = if FileInfo.is_hhi @@ Env.in_mode ctx then Aast.{ fb_ast = [] } else func_body in (ctx, Ok func_body) let on_class_ c ~ctx = (Env.set_mode ctx ~in_mode:c.Aast.c_mode, Ok c) let on_typedef t ~ctx = (Env.set_mode ctx ~in_mode:t.Aast.t_mode, Ok t) let on_gconst cst ~ctx = (Env.set_mode ctx ~in_mode:cst.Aast.cst_mode, Ok cst) let on_fun_def fd ~ctx = (Env.set_mode ctx ~in_mode:fd.Aast.fd_mode, Ok fd) let on_module_def md ~ctx = (Env.set_mode ctx ~in_mode:md.Aast.md_mode, Ok md) let pass = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_func_body = Some on_func_body; on_ty_class_ = Some on_class_; on_ty_typedef = Some on_typedef; on_ty_gconst = Some on_gconst; on_ty_fun_def = Some on_fun_def; on_ty_module_def = Some on_module_def; }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_func_body.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. * *) (* Removes all statements from the `func_body` of `method_`s and `fun_`s. This pass is intended for use with .hhi files *) val pass : Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_haccess_hint.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 Err = Naming_phase_error module SN = Naming_special_names module Env = struct let in_class t Aast.{ c_name; c_kind; c_final; _ } = let elab_haccess_hint = t.Naming_phase_env.elab_haccess_hint in let elab_haccess_hint = Naming_phase_env.Elab_haccess_hint. { elab_haccess_hint with current_class = Some (c_name, c_kind, c_final); } in Naming_phase_env.{ t with elab_haccess_hint } let set_in_context t ~in_context = Naming_phase_env. { t with elab_haccess_hint = Elab_haccess_hint.{ t.elab_haccess_hint with in_context }; } let set_in_haccess t ~in_haccess = Naming_phase_env. { t with elab_haccess_hint = Elab_haccess_hint.{ t.elab_haccess_hint with in_haccess }; } let in_haccess Naming_phase_env. { elab_haccess_hint = Elab_haccess_hint.{ in_haccess; _ }; _ } = in_haccess let set_in_where_clause t ~in_where_clause = Naming_phase_env. { t with elab_haccess_hint = Elab_haccess_hint.{ t.elab_haccess_hint with in_where_clause }; } let in_where_clause Naming_phase_env. { elab_haccess_hint = Elab_haccess_hint.{ in_where_clause; _ }; _ } = in_where_clause let in_context Naming_phase_env. { elab_haccess_hint = Elab_haccess_hint.{ in_context; _ }; _ } = in_context let current_class Naming_phase_env. { elab_haccess_hint = Elab_haccess_hint.{ current_class; _ }; _ } = current_class end let on_class_ c ~ctx = (Env.in_class ctx c, Ok c) let on_where_constraint_hint cstr ~ctx = (Env.set_in_where_clause ctx ~in_where_clause:true, Ok cstr) let on_contexts ctxts ~ctx = (Env.set_in_context ctx ~in_context:true, Ok ctxts) let on_hint on_error hint ~ctx = let res = if Env.in_haccess ctx then match hint with (* TODO[mjt] we appear to be discarding type parameters on `Happly` here - should we change the representation of `Haccess` or handle erroneous type parameters? *) | (pos, Aast.Happly ((tycon_pos, tycon_name), _)) when String.equal tycon_name SN.Classes.cSelf -> begin match Env.current_class ctx with | Some (cid, _, _) -> Ok (pos, Aast.Happly (cid, [])) | _ -> Error ( (pos, Aast.Herr), Err.naming @@ Naming_error.Self_outside_class tycon_pos ) (* TODO[mjt] is this ever exercised? The cases is handles appear to be a parse errors *) end | (pos, Aast.Happly ((tycon_pos, tycon_name), _)) when String.( equal tycon_name SN.Classes.cStatic || equal tycon_name SN.Classes.cParent) -> Error ( (pos, Aast.Herr), Err.naming @@ Naming_error.Invalid_type_access_root { pos = tycon_pos; id = Some tycon_name } ) | (_, Aast.(Hthis | Happly _)) -> Ok hint | (_, Aast.Habstr _) when Env.in_where_clause ctx || Env.in_context ctx -> Ok hint (* TODO[mjt] why are we allow `Hvar`? *) | (_, Aast.Hvar _) -> Ok hint | (pos, _) -> Error ( (pos, Aast.Herr), Err.naming @@ Naming_error.Invalid_type_access_root { pos; id = None } ) else Ok hint in let ctx = match hint with | (_, Aast.Haccess _) -> Env.set_in_haccess ctx ~in_haccess:true | _ -> Env.set_in_haccess ctx ~in_haccess:false in match res with | Error (hint, err) -> on_error err; (ctx, Error hint) | Ok hint -> (ctx, Ok hint) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_class_ = Some on_class_; on_ty_where_constraint_hint = Some on_where_constraint_hint; on_ty_contexts = Some on_contexts; on_ty_hint = Some (on_hint on_error); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_haccess_hint.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. * *) (* Validates the hint at the root of a type access replacing it with `Herr` and raising an error if it is invalid *) val pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_happly_hint.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 module Err = Naming_phase_error module SN = Naming_special_names module Env = struct let tparams Naming_phase_env.{ elab_happly_hint = Elab_happly_hint.{ tparams; _ }; _ } = tparams let add_tparams ps init = List.fold ps ~f:(fun acc Aast.{ tp_name = (_, nm); _ } -> SSet.add nm acc) ~init let extend_tparams t ps = let elab_happly_hint = t.Naming_phase_env.elab_happly_hint in let tparams = add_tparams ps elab_happly_hint.Naming_phase_env.Elab_happly_hint.tparams in let elab_happly_hint = Naming_phase_env.Elab_happly_hint.{ tparams } in Naming_phase_env.{ t with elab_happly_hint } let in_class t Aast.{ c_tparams; _ } = let elab_happly_hint = Naming_phase_env.Elab_happly_hint. { tparams = add_tparams c_tparams SSet.empty } in Naming_phase_env.{ t with elab_happly_hint } let in_fun_def t Aast.{ fd_tparams; _ } = let elab_happly_hint = Naming_phase_env.Elab_happly_hint. { tparams = add_tparams fd_tparams SSet.empty } in Naming_phase_env.{ t with elab_happly_hint } let in_typedef t Aast.{ t_tparams; _ } = let elab_happly_hint = Naming_phase_env.Elab_happly_hint. { tparams = add_tparams t_tparams SSet.empty } in Naming_phase_env.{ t with elab_happly_hint } let in_gconst t = let elab_happly_hint = Naming_phase_env.Elab_happly_hint.{ tparams = SSet.empty } in Naming_phase_env.{ t with elab_happly_hint } let in_module_def t = let elab_happly_hint = Naming_phase_env.Elab_happly_hint.{ tparams = SSet.empty } in Naming_phase_env.{ t with elab_happly_hint } end type canon_result = | Concrete of Aast.hint | This of Pos.t | Classname of Pos.t | Tycon of Pos.t * string | Typaram of string | Varray of Pos.t | Darray of Pos.t | Vec_or_dict of Pos.t | CanonErr of Naming_error.t (* A number of hints are represented by `Happly` after lowering; we elaborate to the canonical representation here taking care to separate the result so we can apply subsequent validation of the hint based on where it appeared *) let canonical_tycon typarams (pos, name) = if String.equal name SN.Typehints.int then Concrete (pos, Aast.(Hprim Tint)) else if String.equal name SN.Typehints.bool then Concrete (pos, Aast.(Hprim Tbool)) else if String.equal name SN.Typehints.float then Concrete (pos, Aast.(Hprim Tfloat)) else if String.equal name SN.Typehints.string then Concrete (pos, Aast.(Hprim Tstring)) else if String.equal name SN.Typehints.darray then Darray pos else if String.equal name SN.Typehints.varray then Varray pos (* TODO[mjt] `vec_or_dict` is currently special cased since the canonical representation requires us to have no arity mismatches or throw away info. We do not use that repr here to avoid having to do so. Ultimately, we should remove that special case *) else if String.( equal name SN.Typehints.varray_or_darray || equal name SN.Typehints.vec_or_dict) then Vec_or_dict pos else if String.equal name SN.Typehints.void then Concrete (pos, Aast.(Hprim Tvoid)) else if String.equal name SN.Typehints.noreturn then Concrete (pos, Aast.(Hprim Tnoreturn)) else if String.equal name SN.Typehints.null then Concrete (pos, Aast.(Hprim Tnull)) else if String.equal name SN.Typehints.num then Concrete (pos, Aast.(Hprim Tnum)) else if String.equal name SN.Typehints.resource then Concrete (pos, Aast.(Hprim Tresource)) else if String.equal name SN.Typehints.arraykey then Concrete (pos, Aast.(Hprim Tarraykey)) else if String.equal name SN.Typehints.mixed then Concrete (pos, Aast.Hmixed) else if String.equal name SN.Typehints.nonnull then Concrete (pos, Aast.Hnonnull) else if String.equal name SN.Typehints.nothing then Concrete (pos, Aast.Hnothing) else if String.equal name SN.Typehints.dynamic then Concrete (pos, Aast.Hdynamic) else if String.equal name SN.Typehints.this then This pos else if String.( equal name ("\\" ^ SN.Typehints.void) || equal name ("\\" ^ SN.Typehints.null) || equal name ("\\" ^ SN.Typehints.noreturn) || equal name ("\\" ^ SN.Typehints.int) || equal name ("\\" ^ SN.Typehints.bool) || equal name ("\\" ^ SN.Typehints.float) || equal name ("\\" ^ SN.Typehints.num) || equal name ("\\" ^ SN.Typehints.string) || equal name ("\\" ^ SN.Typehints.resource) || equal name ("\\" ^ SN.Typehints.mixed) || equal name ("\\" ^ SN.Typehints.nonnull) || equal name ("\\" ^ SN.Typehints.arraykey) || equal name ("\\" ^ SN.Typehints.nothing)) then CanonErr (Naming_error.Primitive_top_level pos) (* TODO[mjt] why wouldn't be have a fully qualified name here? *) else if String.(equal name SN.Classes.cClassname || equal name "classname") then Classname pos else if SSet.mem name typarams then Typaram name else Tycon (pos, name) (* TODO[mjt] should we really be special casing `darray`? *) let canonicalise_darray hint_pos pos hints = match hints with | [] | [_] -> let err = Some (Err.naming @@ Naming_error.Too_few_type_arguments hint_pos) in let any = (pos, Aast.Hany) in Ok ((hint_pos, Aast.Happly ((pos, SN.Collections.cDict), [any; any])), err) | [key_hint; val_hint] -> Ok ( ( hint_pos, Aast.Happly ((pos, SN.Collections.cDict), [key_hint; val_hint]) ), None ) | _ -> let err = Err.naming @@ Naming_error.Too_many_type_arguments hint_pos in Error ((hint_pos, Aast.Hany), err) (* TODO[mjt] should we really be special casing `varray`? *) let canonicalise_varray hint_pos pos hints = match hints with | [] -> let err = Some (Err.naming @@ Naming_error.Too_few_type_arguments hint_pos) in let any = (pos, Aast.Hany) in Ok ((hint_pos, Aast.Happly ((pos, SN.Collections.cVec), [any])), err) | [val_hint] -> Ok ((hint_pos, Aast.Happly ((pos, SN.Collections.cVec), [val_hint])), None) | _ -> let err = Err.naming @@ Naming_error.Too_many_type_arguments hint_pos in Error ((hint_pos, Aast.Hany), err) (* TODO[mjt] should we really be special casing `vec_or_dict` both in its representation and error handling? *) let canonicalise_vec_or_dict hint_pos pos hints = match hints with | [] -> let err = Some (Err.naming @@ Naming_error.Too_few_type_arguments hint_pos) in let any = (pos, Aast.Hany) in Ok ((hint_pos, Aast.Hvec_or_dict (None, any)), err) | [val_hint] -> Ok ((hint_pos, Aast.Hvec_or_dict (None, val_hint)), None) | [key_hint; val_hint] -> Ok ((hint_pos, Aast.Hvec_or_dict (Some key_hint, val_hint)), None) | _ -> let err = Err.naming @@ Naming_error.Too_many_type_arguments hint_pos in Error ((hint_pos, Aast.Hany), err) (* After lowering many hints are represented as `Happly(...,...)`. Here we canonicalise the representation of type constructor then handle errors and further elaboration *) let canonicalize_happly tparams hint_pos tycon hints = match canonical_tycon tparams tycon with (* The hint was malformed *) | CanonErr err -> Error ((hint_pos, Aast.Herr), Err.naming err) (* The type constructors canonical representation is a concrete type *) | Concrete (pos, hint_) -> (* We can't represent a concrete type applied to other types so we raise an error here *) let err_opt = if not @@ List.is_empty hints then Some (Err.naming @@ Naming_error.Unexpected_type_arguments pos) else None in Ok ((hint_pos, hint_), err_opt) (* The type constructors corresponds to an in-scope type parameter *) | Typaram name -> let hint_ = Aast.Habstr (name, hints) in Ok ((hint_pos, hint_), None) (* The type constructors canonical representation is `Happly` but additional elaboration / validation is required *) | This pos -> let err_opt = if not @@ List.is_empty hints then Some (Err.naming @@ Naming_error.This_no_argument hint_pos) else None in Ok ((pos, Aast.Hthis), err_opt) | Classname pos -> (* TODO[mjt] currently if `classname` is not applied to exactly one type parameter, it canonicalizes to `Hprim Tstring`. Investigate why this happens and if we can delay treatment to typing *) (match hints with | [_] -> let hint_ = Aast.Happly ((pos, SN.Classes.cClassname), hints) in Ok ((hint_pos, hint_), None) | _ -> Ok ( (hint_pos, Aast.(Hprim Tstring)), Some (Err.naming @@ Naming_error.Classname_param pos) )) | Darray pos -> canonicalise_darray hint_pos pos hints | Varray pos -> canonicalise_varray hint_pos pos hints | Vec_or_dict pos -> canonicalise_vec_or_dict hint_pos pos hints (* The type constructors canonical representation is `Happly` *) | Tycon (pos, tycon) -> let hint_ = Aast.Happly ((pos, tycon), hints) in Ok ((hint_pos, hint_), None) let on_typedef t ~ctx = (Env.in_typedef ctx t, Ok t) let on_gconst cst ~ctx = (Env.in_gconst ctx, Ok cst) let on_fun_def fd ~ctx = (Env.in_fun_def ctx fd, Ok fd) let on_module_def md ~ctx = (Env.in_module_def ctx, Ok md) let on_class_ c ~ctx = (Env.in_class ctx c, Ok c) let on_method_ m ~ctx = let ctx = Env.extend_tparams ctx m.Aast.m_tparams in (ctx, Ok m) let on_tparam tp ~ctx = (* TODO[mjt] do we want to maintain the HKT code? *) let ctx = Env.extend_tparams ctx tp.Aast.tp_parameters in (ctx, Ok tp) let on_hint on_error hint ~ctx = match hint with | (hint_pos, Aast.Happly (tycon, hints)) -> (match canonicalize_happly (Env.tparams ctx) hint_pos tycon hints with | Ok (hint, err_opt) -> Option.iter ~f:on_error err_opt; (ctx, Ok hint) | Error (hint, err) -> on_error err; (ctx, Error hint)) | _ -> (ctx, Ok hint) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_typedef = Some on_typedef; on_ty_gconst = Some on_gconst; on_ty_fun_def = Some on_fun_def; on_ty_module_def = Some on_module_def; on_ty_class_ = Some on_class_; on_ty_method_ = Some on_method_; on_ty_tparam = Some on_tparam; on_ty_hint = Some (on_hint on_error); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_happly_hint.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. * *) (* Elaborates `Happly` hints received from the lowerer to their canonical representation *) val pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_hkt.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 Err = Naming_phase_error module Env = struct let hkt_enabled Naming_phase_env.{ hkt_enabled; _ } = hkt_enabled end let on_hint on_error hint ~ctx = match hint with | (pos, Aast.Habstr (name, _ :: _)) when not @@ Env.hkt_enabled ctx -> on_error (Err.naming @@ Naming_error.Tparam_applied_to_type { pos; tparam_name = name }); (ctx, Ok (pos, Aast.Habstr (name, []))) | _ -> (ctx, Ok hint) let on_tparam on_error (Aast.{ tp_parameters; tp_name = (pos, tparam_name); _ } as tparam) ~ctx = match tp_parameters with | _ :: _ when not @@ Env.hkt_enabled ctx -> on_error (Err.naming @@ Naming_error.Tparam_with_tparam { pos; tparam_name }); (ctx, Ok Aast.{ tparam with tp_parameters = [] }) | _ -> (ctx, Ok tparam) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_hint = Some (on_hint on_error); on_ty_tparam = Some (fun elem ~ctx -> on_tparam on_error elem ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_hkt.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. * *) (* This combined elaboration and validation pass will remove the type arguments to `Habstr(_,_)` and raise an error It is intended for use when the `--higher-kinded-types` typechecker option is _not_ set, *) val pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_import.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) let on_expr expr ~ctx = match expr with | (_, _, Aast.Import _) -> (ctx, Error (Naming_phase_error.invalid_expr expr)) | _ -> (ctx, Ok expr) let pass = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass.{ id with on_ty_expr = Some on_expr }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_import.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 pass : Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_invariant.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 Err = Naming_phase_error module SN = Naming_special_names let on_stmt on_error stmt ~ctx = let res = match stmt with | ( pos, Aast.( Expr ( annot, expr_pos, Call ({ func = (fn_annot, fn_expr_pos, Id (fn_name_pos, fn_name)); args; _; } as call_expr) )) ) when String.equal fn_name SN.AutoimportedFunctions.invariant -> (match args with | [] -> let err = Err.naming @@ Naming_error.Too_few_arguments fn_expr_pos in let expr = (annot, fn_expr_pos, Err.invalid_expr_ None) in Error ((pos, Aast.Expr expr), err) | [(_, expr)] -> let err = Err.naming @@ Naming_error.Too_few_arguments fn_expr_pos in let expr = Err.invalid_expr expr in Error ((pos, Aast.Expr expr), err) | (pk, (cond_annot, cond_pos, cond)) :: exprs -> let err_opt = match pk with | Ast_defs.Pnormal -> None | Ast_defs.Pinout pk_p -> Some (Err.nast_check @@ Nast_check_error.Inout_in_transformed_pseudofunction { pos = Pos.merge pk_p fn_expr_pos; fn_name = "invariant" }) in let id_expr = Aast.Id (fn_name_pos, SN.AutoimportedFunctions.invariant_violation) in let fn_expr = (fn_annot, fn_expr_pos, id_expr) in let violation = ( annot, expr_pos, Aast.(Call { call_expr with func = fn_expr; args = exprs }) ) in (match cond with | Aast.False -> (* a false <condition> means unconditional invariant_violation *) Ok ((pos, Aast.Expr violation), err_opt) | _ -> let (b1, b2) = ([(expr_pos, Aast.Expr violation)], [(Pos.none, Aast.Noop)]) in let cond = ( cond_annot, cond_pos, Aast.Unop (Ast_defs.Unot, (cond_annot, cond_pos, cond)) ) in Ok ((pos, Aast.If (cond, b1, b2)), err_opt))) | _ -> Ok (stmt, None) in match res with | Ok (stmt, err_opt) -> Option.iter ~f:on_error err_opt; (ctx, Ok stmt) | Error (stmt, err) -> on_error err; (ctx, Error stmt) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.bottom_up Aast.Pass. { id with on_ty_stmt = Some (fun elem ~ctx -> on_stmt on_error elem ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_invariant.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. * *) (* invariant is subject to a source-code transform in the HHVM * runtime: the arguments to invariant are lazily evaluated only in * the case in which the invariant condition does not hold. So: * * invariant_violation(<condition>, <format>, <format_args...>) * * ... is rewritten as: * * if (!<condition>) { * invariant_violation(<format>, <format_args...>); * } *) val pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_lvar.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module SN = Naming_special_names let on_expr_ expr_ ~ctx = let expr_ = match expr_ with | Aast.Lvar (pos, local_id) -> let lid_str = Local_id.to_string local_id in if String.equal lid_str SN.SpecialIdents.this then Aast.This else if String.equal lid_str SN.SpecialIdents.dollardollar then Aast.Dollardollar (pos, Local_id.make_unscoped SN.SpecialIdents.dollardollar) else if String.equal lid_str SN.SpecialIdents.placeholder then Aast.Lplaceholder pos else expr_ | Aast.Pipe ((pos, _), e1, e2) -> let lid = (pos, Local_id.make_unscoped SN.SpecialIdents.dollardollar) in Aast.Pipe (lid, e1, e2) | _ -> expr_ in (ctx, Ok expr_) let pass = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass.{ id with on_ty_expr_ = Some on_expr_ }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_lvar.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. * *) (* Elaborates `$$`, `$this` and `$_` to `Dollardollar`, `This` and `Lplaceholder` *) val pass : Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_retonly_hint.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude module Env = struct let allow_retonly Naming_phase_env. { elab_retonly_hint = Elab_retonly_hint.{ allow_retonly }; _ } = allow_retonly let set_allow_retonly t ~allow_retonly = Naming_phase_env. { t with elab_retonly_hint = Elab_retonly_hint.{ allow_retonly } } end let on_targ targ ~ctx = let ctx = Env.set_allow_retonly ctx ~allow_retonly:true in (ctx, Ok targ) let on_hint_fun_hf_return_ty t ~ctx = let ctx = Env.set_allow_retonly ctx ~allow_retonly:true in (ctx, Ok t) let on_fun_f_ret f ~ctx = let ctx = Env.set_allow_retonly ctx ~allow_retonly:true in (ctx, Ok f) let on_method_m_ret m ~ctx = let ctx = Env.set_allow_retonly ctx ~allow_retonly:true in (ctx, Ok m) let on_hint_ hint_ ~ctx = match hint_ with | Aast.(Happly _ | Habstr _) -> let ctx = Env.set_allow_retonly ctx ~allow_retonly:true in (ctx, Ok hint_) | _ -> (ctx, Ok hint_) let on_hint on_error hint ~ctx = let allow_retonly = Env.allow_retonly ctx in match hint with | (pos, Aast.(Hprim Tvoid)) when not allow_retonly -> on_error (Naming_phase_error.naming Naming_error.(Return_only_typehint { pos; kind = Hvoid })); (ctx, Error (pos, Aast.Herr)) | (pos, Aast.(Hprim Tnoreturn)) when not allow_retonly -> on_error (Naming_phase_error.naming Naming_error.(Return_only_typehint { pos; kind = Hnoreturn })); (ctx, Error (pos, Aast.Herr)) | _ -> (ctx, Ok hint) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_hint_ = Some on_hint_; on_ty_targ = Some on_targ; on_fld_hint_fun_hf_return_ty = Some on_hint_fun_hf_return_ty; on_fld_fun__f_ret = Some on_fun_f_ret; on_fld_method__m_ret = Some on_method_m_ret; on_ty_hint = Some (on_hint on_error); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_retonly_hint.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 pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_shape_field_name.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude module SN = Naming_special_names module Env = struct let in_class t Aast.{ c_name; c_kind; c_final; _ } = Naming_phase_env. { t with elab_shape_field_name = Elab_shape_field_name. { current_class = Some (c_name, c_kind, c_final) }; } let current_class Naming_phase_env. { elab_shape_field_name = Elab_shape_field_name.{ current_class }; _ } = current_class end let on_class_ c ~ctx = (Env.in_class ctx c, Ok c) (* We permit class constants to be used as shape field names. Here we replace uses of `self` with the class to which they refer or `unknown` if the shape is not defined within the context of a class *) let canonical_shape_name current_class sfld = match sfld with | Ast_defs.SFclass_const ((class_pos, class_name), cst) when String.equal class_name SN.Classes.cSelf -> (match current_class with | Some ((_, class_name), _, _) -> Ok (Ast_defs.SFclass_const ((class_pos, class_name), cst)) | None -> let err = Naming_phase_error.naming @@ Naming_error.Self_outside_class class_pos in Error (Ast_defs.SFclass_const ((class_pos, SN.Classes.cUnknown), cst), err)) | _ -> Ok sfld let on_expr_ on_error expr_ ~ctx = let (expr_, errs) = match expr_ with | Aast.Shape fdl -> let (fdl, err_opts) = List.unzip @@ List.map fdl ~f:(fun (nm, v) -> let (nm, err_opt) = match canonical_shape_name (Env.current_class ctx) nm with | Ok nm -> (nm, None) | Error (nm, err) -> (nm, Some err) in ((nm, v), err_opt)) in let err = List.fold_right err_opts ~init:[] ~f:(fun err_opt acc -> Option.value_map err_opt ~default:acc ~f:(fun err -> err :: acc)) in (Aast.Shape fdl, err) | _ -> (expr_, []) in List.iter ~f:on_error errs; (ctx, Ok expr_) let on_shape_field_info on_error (Aast.{ sfi_name; _ } as sfi) ~ctx = match canonical_shape_name (Env.current_class ctx) sfi_name with | Ok sfi_name -> (ctx, Ok Aast.{ sfi with sfi_name }) | Error (sfi_name, err) -> on_error err; (ctx, Error Aast.{ sfi with sfi_name }) let top_down_pass = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass.{ id with on_ty_class_ = Some on_class_ } let bottom_up_pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.bottom_up Aast.Pass. { id with on_ty_expr_ = Some (fun elem ~ctx -> on_expr_ on_error elem ~ctx); on_ty_shape_field_info = Some (on_shape_field_info on_error); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_shape_field_name.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (* We permit class constants to be used as shape field names. Here we replace uses of `self` with the class to which they refer or `unknown` if the shape is not defined within the context of a class *) val top_down_pass : Naming_phase_env.t Naming_phase_pass.t val bottom_up_pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_soft.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module Env = struct let soft_as_like Naming_phase_env.{ soft_as_like; _ } = soft_as_like end let on_hint hint ~ctx = match hint with | (pos, Aast.Hsoft hint) when Env.soft_as_like ctx -> (ctx, Ok (pos, Aast.Hlike hint)) | (pos, Aast.Hsoft (_, hint_)) -> (ctx, Ok (pos, hint_)) | _ -> (ctx, Ok hint) let pass = let id = Aast.Pass.identity () in Naming_phase_pass.bottom_up Aast.Pass.{ id with on_ty_hint = Some on_hint }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_soft.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. * *) (* This elaboration pass will replace Hsoft(_)` hints, with either - the inner hint to which the constructor is applied; OR - `Hlike`, when the `--interpret-soft-types-as-like-types` typechecker option is enabled *) val pass : Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_this_hint.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 SN = Naming_special_names module Env = struct let forbid_this Naming_phase_env.{ elab_this_hint = Elab_this_hint.{ forbid_this; _ }; _ } = forbid_this let lsb Naming_phase_env.{ elab_this_hint = Elab_this_hint.{ lsb; _ }; _ } = lsb let in_req_extends Naming_phase_env. { elab_this_hint = Elab_this_hint.{ in_req_extends; _ }; _ } = in_req_extends let in_extends Naming_phase_env.{ elab_this_hint = Elab_this_hint.{ in_extends; _ }; _ } = in_extends let is_top_level_haccess_root Naming_phase_env. { elab_this_hint = Elab_this_hint.{ is_top_level_haccess_root; _ }; _ } = is_top_level_haccess_root let in_interface Naming_phase_env. { elab_this_hint = Elab_this_hint.{ in_interface; _ }; _ } = in_interface let in_invariant_final Naming_phase_env. { elab_this_hint = Elab_this_hint.{ in_invariant_final; _ }; _ } = in_invariant_final let set_forbid_this t ~forbid_this = let elab_this_hint = t.Naming_phase_env.elab_this_hint in let elab_this_hint = Naming_phase_env.Elab_this_hint.{ elab_this_hint with forbid_this } in Naming_phase_env.{ t with elab_this_hint } let set_lsb t ~lsb = let elab_this_hint = t.Naming_phase_env.elab_this_hint in let elab_this_hint = Naming_phase_env.Elab_this_hint.{ elab_this_hint with lsb } in Naming_phase_env.{ t with elab_this_hint } let set_in_req_extends t ~in_req_extends = let elab_this_hint = t.Naming_phase_env.elab_this_hint in let elab_this_hint = Naming_phase_env.Elab_this_hint.{ elab_this_hint with in_req_extends } in Naming_phase_env.{ t with elab_this_hint } let set_in_extends t ~in_extends = let elab_this_hint = t.Naming_phase_env.elab_this_hint in let elab_this_hint = Naming_phase_env.Elab_this_hint.{ elab_this_hint with in_extends } in Naming_phase_env.{ t with elab_this_hint } let set_is_top_level_haccess_root t ~is_top_level_haccess_root = let elab_this_hint = t.Naming_phase_env.elab_this_hint in let elab_this_hint = Naming_phase_env.Elab_this_hint. { elab_this_hint with is_top_level_haccess_root } in Naming_phase_env.{ t with elab_this_hint } let set_in_interface t ~in_interface = let elab_this_hint = t.Naming_phase_env.elab_this_hint in let elab_this_hint = Naming_phase_env.Elab_this_hint.{ elab_this_hint with in_interface } in Naming_phase_env.{ t with elab_this_hint } let set_in_invariant_final t ~in_invariant_final = let elab_this_hint = t.Naming_phase_env.elab_this_hint in let elab_this_hint = Naming_phase_env.Elab_this_hint.{ elab_this_hint with in_invariant_final } in Naming_phase_env.{ t with elab_this_hint } end let on_class_ c ~ctx = let in_interface = match c.Aast.c_kind with | Ast_defs.Cinterface -> true | _ -> false in let in_invariant_final = if c.Aast.c_final then match c.Aast.c_tparams with | [] -> true | tps -> let f Aast.{ tp_variance; _ } = match tp_variance with | Ast_defs.Invariant -> true | _ -> false in List.for_all ~f tps else false in let ctx = Env.set_in_invariant_final ~in_invariant_final @@ Env.set_in_interface ~in_interface ctx in (ctx, Ok c) let on_class_c_tparams c_tparams ~ctx = let ctx = Env.set_forbid_this ctx ~forbid_this:true in (ctx, Ok c_tparams) let on_class_c_extends c_extends ~ctx = let ctx = Env.set_in_extends ~in_extends:true ctx in (ctx, Ok c_extends) let on_class_c_uses c_uses ~ctx = let ctx = Env.set_forbid_this ctx ~forbid_this:false in (ctx, Ok c_uses) let on_class_c_xhp_attrs c_xhp_attrs ~ctx = let ctx = Env.set_forbid_this ctx ~forbid_this:false in (ctx, Ok c_xhp_attrs) let on_class_c_xhp_attr_uses c_xhp_attr_uses ~ctx = let ctx = Env.set_forbid_this ctx ~forbid_this:false in (ctx, Ok c_xhp_attr_uses) let on_class_c_reqs c_reqs ~ctx = let ctx = Env.set_forbid_this ctx ~forbid_this:false in (ctx, Ok c_reqs) let on_class_req ((_, require_kind) as elem) ~ctx = let in_req_extends = match require_kind with | Aast.RequireExtends -> true | _ -> false in let ctx = Env.set_in_req_extends ~in_req_extends ctx in (ctx, Ok elem) let on_class_c_implements c_implements ~ctx = let ctx = Env.set_forbid_this ctx ~forbid_this:false in (ctx, Ok c_implements) let on_class_var (Aast.{ cv_is_static; cv_user_attributes; _ } as cv) ~ctx = let lsb = if cv_is_static then Some (not @@ Naming_attributes.mem SN.UserAttributes.uaLSB cv_user_attributes) else None in let ctx = Env.set_lsb ctx ~lsb in (ctx, Ok cv) let on_class_var_cv_type cv_type ~ctx = let forbid_this = Option.value ~default:false @@ Env.lsb ctx in let ctx = Env.set_lsb ~lsb:None @@ Env.set_forbid_this ~forbid_this ctx in (ctx, Ok cv_type) let on_fun_f_ret f_ret ~ctx = let ctx = Env.set_forbid_this ~forbid_this:false @@ Env.set_lsb ~lsb:None ctx in (ctx, Ok f_ret) let on_expr_ expr_ ~ctx = let ctx = match expr_ with | Aast.(Cast _ | Is _ | As _ | Upcast _) -> Env.set_forbid_this ~forbid_this:false @@ Env.set_lsb ~lsb:None ctx | _ -> ctx in (ctx, Ok expr_) (* We want to disallow `this` hints in: - _class_ and _abstract class_ type parameters - non-late static bound class_var - `extends` and `require extends` clauses _unless_ it appears as the top-level root of a type access *) let on_hint on_error hint ~ctx = let forbid_in_extends = (Env.in_req_extends ctx || Env.in_extends ctx) && (not @@ Env.in_interface ctx) && (not @@ Env.is_top_level_haccess_root ctx) && (not @@ Env.in_invariant_final ctx) in match hint with | (pos, Aast.Hthis) when Env.forbid_this ctx || forbid_in_extends -> on_error @@ Naming_phase_error.naming @@ Naming_error.This_type_forbidden { pos; in_extends = Env.in_extends ctx; in_req_extends = Env.in_req_extends ctx; }; (ctx, Ok (pos, Aast.Herr)) | (_, Aast.Haccess _) -> let ctx = Env.set_is_top_level_haccess_root ~is_top_level_haccess_root:true ctx in (ctx, Ok hint) | _ -> let ctx = Env.set_is_top_level_haccess_root ~is_top_level_haccess_root:false ctx in (ctx, Ok hint) let on_shape_field_info sfi ~ctx = let ctx = Env.set_forbid_this ~forbid_this:false @@ Env.set_lsb ~lsb:None ctx in (ctx, Ok sfi) let on_hint_fun_hf_return_ty hf_return_ty ~ctx = let ctx = Env.set_forbid_this ~forbid_this:false @@ Env.set_lsb ~lsb:None ctx in (ctx, Ok hf_return_ty) let on_targ targ ~ctx = let ctx = Env.set_forbid_this ~forbid_this:false @@ Env.set_lsb ~lsb:None ctx in (ctx, Ok targ) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_class_ = Some on_class_; on_fld_class__c_tparams = Some on_class_c_tparams; on_fld_class__c_extends = Some on_class_c_extends; on_fld_class__c_uses = Some on_class_c_uses; on_fld_class__c_xhp_attrs = Some on_class_c_xhp_attrs; on_fld_class__c_xhp_attr_uses = Some on_class_c_xhp_attr_uses; on_fld_class__c_reqs = Some on_class_c_reqs; on_ty_class_req = Some on_class_req; on_fld_class__c_implements = Some on_class_c_implements; on_ty_class_var = Some on_class_var; on_fld_class_var_cv_type = Some on_class_var_cv_type; on_fld_fun__f_ret = Some on_fun_f_ret; on_ty_expr_ = Some on_expr_; on_ty_hint = Some (on_hint on_error); on_ty_shape_field_info = Some on_shape_field_info; on_fld_hint_fun_hf_return_ty = Some on_hint_fun_hf_return_ty; on_ty_targ = Some on_targ; }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_this_hint.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. * *) (* This combined elaboration and validation pass will: - Canonicalise `Happly(...)` hints coming from the lowerer - Canonicalise `varray`, `darray` and `varray_or_darray` type hints - Replace invalid hints with `Herr` and raise errors - Validate use of `self`, `this`, `parent` and `static` type hints - Elaborate missing type parameters to builtin collections to `Hany` - Validate the arity of certain builtin collections *) val pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_tuple.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 Err = Naming_phase_error let on_expr on_error expr ~ctx = match expr with | (_, pos, Aast.Tuple []) -> on_error (Err.naming @@ Naming_error.Too_few_arguments pos); (ctx, Error (Err.invalid_expr expr)) | _ -> (ctx, Ok expr) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_expr = Some (fun elem ~ctx -> on_expr on_error elem ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_tuple.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. * *) (* This combined elaboration and validation pass will replace empty tuples with the `invalid_expr_` and raise an error *) val pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_user_attributes.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast let on_user_attributes on_error us ~ctx = (* Complain on duplicates, e.g. <<Foo, Bar, Foo>>. *) let seen = Caml.Hashtbl.create 0 in let dedup (attrs, err_acc) (Aast.{ ua_name = (pos, attr_name); _ } as attr) = match Caml.Hashtbl.find_opt seen attr_name with | Some prev_pos -> let err = Naming_phase_error.naming @@ Naming_error.Duplicate_user_attribute { pos; prev_pos; attr_name } in (attrs, err :: err_acc) | _ -> Caml.Hashtbl.add seen attr_name pos; (attr :: attrs, err_acc) in let (us, errs) = Tuple2.map_fst ~f:List.rev @@ List.fold_left us ~init:([], []) ~f:dedup in List.iter ~f:on_error errs; (* Fully qualify arguments to __Memoize with enum class syntax. E.g. <<__Memoize(#KeyedByIC)>> becomes <<__Memoize(\HH\MemoizeOption#KeyedByIC)>> *) let us = List.map ~f:(fun ({ ua_name = (_, attr_name); ua_params } as attr) -> if String.equal attr_name Naming_special_names.UserAttributes.uaMemoize || String.equal attr_name Naming_special_names.UserAttributes.uaMemoizeLSB then let ua_params = List.map ua_params ~f:(fun e -> let (ex, pos, e_) = e in let e_ = match e_ with | EnumClassLabel (None, label) -> EnumClassLabel ( Some (Pos.none, Naming_special_names.HH.memoizeOption), label ) | EnumClassLabel (Some cid, label) -> let (class_pos, class_name) = cid in if not (String.equal class_name Naming_special_names.HH.memoizeOption) then on_error (Naming_phase_error.naming @@ Naming_error.Invalid_memoize_label { pos = class_pos; attr_name }); EnumClassLabel (Some cid, label) | _ -> e_ in (ex, pos, e_)) in { attr with ua_params } else attr) us in (ctx, Ok us) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_user_attributes = Some (fun elem ~ctx -> on_user_attributes on_error elem ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_user_attributes.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. * *) (* This combined elaboration and validation pass will deduplicate user attributes and raise errors for each duplicate *) val pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_elab_wildcard_hint.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude module Env = struct let incr_tp_depth t = let elab_wildcard_hint = t.Naming_phase_env.elab_wildcard_hint in let elab_wildcard_hint = Naming_phase_env.Elab_wildcard_hint. { elab_wildcard_hint with tp_depth = elab_wildcard_hint.tp_depth + 1 } in Naming_phase_env.{ t with elab_wildcard_hint } let reset_tp_depth t = let elab_wildcard_hint = t.Naming_phase_env.elab_wildcard_hint in let elab_wildcard_hint = Naming_phase_env.Elab_wildcard_hint. { elab_wildcard_hint with tp_depth = 0 } in Naming_phase_env.{ t with elab_wildcard_hint } let allow_wildcard Naming_phase_env. { elab_wildcard_hint = Elab_wildcard_hint.{ allow_wildcard; _ }; _ } = allow_wildcard let set_allow_wildcard t ~allow_wildcard = let elab_wildcard_hint = t.Naming_phase_env.elab_wildcard_hint in let elab_wildcard_hint = Naming_phase_env.Elab_wildcard_hint. { elab_wildcard_hint with allow_wildcard } in Naming_phase_env.{ t with elab_wildcard_hint } let tp_depth Naming_phase_env. { elab_wildcard_hint = Elab_wildcard_hint.{ tp_depth; _ }; _ } = tp_depth end let on_expr_ expr_ ~ctx = let ctx = match expr_ with | Aast.Cast _ -> Env.incr_tp_depth ctx | Aast.(Is _ | As _) -> Env.set_allow_wildcard ctx ~allow_wildcard:true | Aast.Upcast _ -> Env.set_allow_wildcard ctx ~allow_wildcard:false | _ -> ctx in (ctx, Ok expr_) let on_targ targ ~ctx = (Env.set_allow_wildcard ~allow_wildcard:true @@ Env.incr_tp_depth ctx, Ok targ) let on_hint_ hint_ ~ctx = let ctx = match hint_ with | Aast.( ( Hunion _ | Hintersection _ | Hoption _ | Hlike _ | Hsoft _ | Hrefinement _ )) -> Env.reset_tp_depth ctx | Aast.(Htuple _ | Happly _ | Habstr _ | Hvec_or_dict _) -> Env.incr_tp_depth ctx | _ -> ctx in (ctx, Ok hint_) let on_shape_field_info sfi ~ctx = (Env.incr_tp_depth ctx, Ok sfi) let on_context on_error hint ~ctx = match hint with | (pos, Aast.Hwildcard) -> on_error (Naming_phase_error.naming @@ Naming_error.Invalid_wildcard_context pos); (ctx, Error (pos, Aast.Herr)) | _ -> (ctx, Ok hint) let on_hint on_error hint ~ctx = match hint with | (pos, Aast.Hwildcard) -> if Env.(allow_wildcard ctx && tp_depth ctx >= 1) (* prevents 3 as _ *) then (ctx, Ok hint) else let err = Naming_phase_error.naming @@ Naming_error.Wildcard_hint_disallowed pos in on_error err; (ctx, Ok (pos, Aast.Herr)) | _ -> (ctx, Ok hint) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_expr_ = Some on_expr_; on_ty_shape_field_info = Some on_shape_field_info; on_ty_targ = Some on_targ; on_ty_context = Some (fun elem ~ctx -> on_context on_error elem ~ctx); on_ty_hint_ = Some on_hint_; on_ty_hint = Some (fun elem ~ctx -> on_hint on_error elem ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_elab_wildcard_hint.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 pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_error.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude module Error_code = Error_codes.Naming type visibility = | Vprivate | Vpublic | Vinternal | Vprotected type return_only_hint = | Hvoid | Hnoreturn type unsupported_feature = | Ft_where_constraints | Ft_constraints | Ft_reification | Ft_user_attrs | Ft_variance let visibility_to_string = function | Vpublic -> "public" | Vprivate -> "private" | Vinternal -> "internal" | Vprotected -> "protected" type t = | Unsupported_trait_use_as of Pos.t | Unsupported_instead_of of Pos.t | Unexpected_arrow of { pos: Pos.t; cname: string; } | Missing_arrow of { pos: Pos.t; cname: string; } | Disallowed_xhp_type of { pos: Pos.t; ty_name: string; } | Name_is_reserved of { pos: Pos.t; name: string; } | Dollardollar_unused of Pos.t | Method_name_already_bound of { pos: Pos.t; meth_name: string; } | Error_name_already_bound of { pos: Pos.t; name: string; prev_pos: Pos.t; } | Unbound_name of { pos: Pos.t; name: string; kind: Name_context.t; } | Invalid_fun_pointer of { pos: Pos.t; name: string; } | Undefined of { pos: Pos.t; var_name: string; did_you_mean: (string * Pos.t) option; } | Undefined_in_expr_tree of { pos: Pos.t; var_name: string; dsl: string option; did_you_mean: (string * Pos.t) option; } | This_reserved of Pos.t | Start_with_T of Pos.t | Already_bound of { pos: Pos.t; name: string; } | Unexpected_typedef of { pos: Pos.t; decl_pos: Pos.t; expected_kind: Name_context.t; } | Field_name_already_bound of Pos.t | Primitive_top_level of Pos.t | Primitive_invalid_alias of { pos: Pos.t; ty_name_used: string; ty_name_canon: string; } | Dynamic_new_in_strict_mode of Pos.t | Invalid_type_access_root of { pos: Pos.t; id: string option; } | Duplicate_user_attribute of { pos: Pos.t; attr_name: string; prev_pos: Pos.t; } | Invalid_memoize_label of { pos: Pos.t; attr_name: string; } | Unbound_attribute_name of { pos: Pos.t; attr_name: string; closest_attr_name: string option; } | This_no_argument of Pos.t | Object_cast of Pos.t | This_hint_outside_class of Pos.t | Parent_outside_class of Pos.t | Self_outside_class of Pos.t | Static_outside_class of Pos.t | This_type_forbidden of { pos: Pos.t; in_extends: bool; in_req_extends: bool; } | Nonstatic_property_with_lsb of Pos.t | Lowercase_this of { pos: Pos.t; ty_name: string; } | Classname_param of Pos.t | Tparam_applied_to_type of { pos: Pos.t; tparam_name: string; } | Tparam_with_tparam of { pos: Pos.t; tparam_name: string; } | Shadowed_tparam of { pos: Pos.t; tparam_name: string; prev_pos: Pos.t; } | Missing_typehint of Pos.t | Expected_variable of Pos.t | Too_many_arguments of Pos.t | Too_few_arguments of Pos.t | Expected_collection of { pos: Pos.t; cname: string; } | Illegal_CLASS of Pos.t | Illegal_TRAIT of Pos.t | Illegal_fun of Pos.t | Illegal_member_variable_class of Pos.t | Illegal_meth_fun of Pos.t | Illegal_inst_meth of Pos.t | Illegal_meth_caller of Pos.t | Illegal_class_meth of Pos.t | Lvar_in_obj_get of { pos: Pos.t; lvar_pos: Pos.t; lvar_name: string; } | Class_meth_non_final_self of { pos: Pos.t; class_name: string; } | Class_meth_non_final_CLASS of { pos: Pos.t; class_name: string; is_trait: bool; } | Const_without_typehint of { pos: Pos.t; const_name: string; ty_name: string; } | Prop_without_typehint of { pos: Pos.t; prop_name: string; vis: visibility; } | Illegal_constant of Pos.t | Invalid_require_implements of Pos.t | Invalid_require_extends of Pos.t | Invalid_require_class of Pos.t | Did_you_mean of { pos: Pos.t; name: string; suggest_pos: Pos.t; suggest_name: string; } | Using_internal_class of { pos: Pos.t; class_name: string; } | Too_few_type_arguments of Pos.t | Dynamic_class_name_in_strict_mode of Pos.t | Xhp_optional_required_attr of { pos: Pos.t; attr_name: string; } | Xhp_required_with_default of { pos: Pos.t; attr_name: string; } | Array_typehints_disallowed of Pos.t | Wildcard_hint_disallowed of Pos.t | Wildcard_tparam_disallowed of Pos.t | Illegal_use_of_dynamically_callable of { attr_pos: Pos.t; meth_pos: Pos.t; vis: visibility; } | Parent_in_function_pointer of { pos: Pos.t; meth_name: string; parent_name: string option; } | Self_in_non_final_function_pointer of { pos: Pos.t; meth_name: string; class_name: string option; } | Invalid_wildcard_context of Pos.t | Return_only_typehint of { pos: Pos.t; kind: return_only_hint; } | Unexpected_type_arguments of Pos.t | Too_many_type_arguments of Pos.t | This_as_lexical_variable of Pos.t | HKT_unsupported_feature of { pos: Pos.t; because_nested: bool; var_name: string; feature: unsupported_feature; } | HKT_partial_application of { pos: Pos.t; count: int; } | HKT_wildcard of Pos.t | HKT_implicit_argument of { pos: Pos.t; decl_pos: Pos_or_decl.t; param_name: string; } | HKT_class_with_constraints_used of { pos: Pos.t; class_name: string; } | HKT_alias_with_implicit_constraints of { pos: Pos.t; typedef_pos: Pos_or_decl.t; used_class_in_def_pos: Pos_or_decl.t; typedef_name: string; typedef_tparam_name: string; used_class_in_def_name: string; used_class_tparam_name: string; } | Explicit_consistent_constructor of { pos: Pos.t; classish_kind: Ast_defs.classish_kind; } | Module_declaration_outside_allowed_files of Pos.t | Dynamic_method_access of Pos.t | Deprecated_use of { pos: Pos.t; fn_name: string; } | Unnecessary_attribute of { pos: Pos.t; attr: string; class_pos: Pos.t; class_name: string; suggestion: string option; } | Tparam_non_shadowing_reuse of { pos: Pos.t; tparam_name: string; } | Dynamic_hint_disallowed of Pos.t | Illegal_typed_local of { join: bool; id_pos: Pos.t; id_name: string; def_pos: Pos.t; } let const_without_typehint pos name type_ = let name = Utils.strip_all_ns name in let msg = Printf.sprintf "Please add a type hint `const SomeType %s`" name in let (title, new_text) = match type_ with | "string" -> ("Add string type annotation", "string " ^ name) | "int" -> ("Add integer type annotation", "int " ^ name) | "float" -> ("Add float type annotation", "float " ^ name) | _ -> ("Add mixed type annotation", "mixed " ^ name) in User_error.make Error_code.(to_enum AddATypehint) ~quickfixes:[Quickfix.make ~title ~new_text pos] (pos, msg) [] let prop_without_typehint pos name vis = let visibility = visibility_to_string vis in let msg = Printf.sprintf "Please add a type hint `%s SomeType $%s`" visibility name in User_error.make Error_code.(to_enum AddATypehint) (pos, msg) [] let illegal_constant pos = User_error.make Error_code.(to_enum IllegalConstant) (pos, "Illegal constant value") [] let invalid_req_implements pos = User_error.make Error_code.(to_enum InvalidReqImplements) (pos, "Only traits may use `require implements`") [] let invalid_req_extends pos = User_error.make Error_code.(to_enum InvalidReqExtends) (pos, "Only traits and interfaces may use `require extends`") [] let invalid_req_class pos = User_error.make Error_code.(to_enum InvalidReqClass) (pos, "Only traits may use `require class`") [] let did_you_mean_naming pos name suggest_pos suggest_name = let name = Render.strip_ns name in let suggest_name = Render.strip_ns suggest_name in let quickfixes = [ Quickfix.make ~title:("Change to " ^ suggest_name) ~new_text:suggest_name pos; ] in User_error.make Error_code.(to_enum DidYouMeanNaming) ~quickfixes (pos, "Could not find " ^ Markdown_lite.md_codify name ^ ".") [ Render.suggestion_message name suggest_name (Pos_or_decl.of_raw_pos suggest_pos); ] let using_internal_class pos name = User_error.make Error_code.(to_enum UsingInternalClass) ( pos, Markdown_lite.md_codify name ^ " is an implementation internal class that cannot be used directly" ) [] let too_few_type_arguments p = User_error.make Error_code.(to_enum TooFewTypeArguments) (p, "Too few type arguments for this type") [] let dynamic_class_name_in_strict_mode pos = User_error.make Error_code.(to_enum DynamicClassNameInStrictMode) (pos, "Cannot use dynamic class or method name in strict mode") [] let xhp_optional_required_attr pos id = User_error.make Error_code.(to_enum XhpOptionalRequiredAttr) ( pos, "XHP attribute " ^ Markdown_lite.md_codify id ^ " cannot be marked as nullable and `@required`" ) [] let xhp_required_with_default pos id = User_error.make Error_code.(to_enum XhpRequiredWithDefault) ( pos, "XHP attribute " ^ Markdown_lite.md_codify id ^ " cannot be marked `@required` and provide a default" ) [] let array_typehints_disallowed pos = User_error.make Error_code.(to_enum ArrayTypehintsDisallowed) ( pos, "Array typehints are no longer legal; use `varray` or `darray` instead" ) [] let wildcard_hint_disallowed pos = User_error.make Error_code.(to_enum WildcardHintDisallowed) (pos, "Wildcard typehints are not allowed in this position") [] let dynamic_hint_disallowed pos = User_error.make Error_code.(to_enum DynamicHintDisallowed) (pos, "dynamic typehints are not allowed in this position") [] let illegal_typed_local ~join id_pos name def_pos = let desc = if join then "It is assigned in another branch. Consider moving the definition to an enclosing block." else "It is already defined. Typed locals must have their type declared before they can be assigned." in User_error.make Error_code.(to_enum IllegalTypedLocal) (id_pos, "Illegal definition of typed local variable " ^ name ^ ".") [(def_pos, desc)] let wildcard_param_disallowed pos = User_error.make Error_code.(to_enum WildcardTypeParamDisallowed) (pos, "Cannot use anonymous type parameter in this position.") [] let illegal_use_of_dynamically_callable attr_pos meth_pos vis = let visibility = visibility_to_string vis in User_error.make Error_code.(to_enum IllegalUseOfDynamicallyCallable) (attr_pos, "`__DynamicallyCallable` can only be used on public methods") [ ( Pos_or_decl.of_raw_pos meth_pos, sprintf "But this method is %s" (Markdown_lite.md_codify visibility) ); ] let unsupported_trait_use_as pos = User_error.make Error_code.(to_enum UnsupportedTraitUseAs) ( pos, "Aliasing with `as` within a trait `use` is a PHP feature that is unsupported in Hack" ) [] let unsupported_instead_of pos = User_error.make Error_code.(to_enum UnsupportedInsteadOf) (pos, "`insteadof` is a PHP feature that is unsupported in Hack") [] let unexpected_arrow pos cname = User_error.make Error_code.(to_enum UnexpectedArrow) ( pos, Format.sprintf {|Keys may not be specified for %s initialization|} cname ) [] let parent_in_function_pointer pos meth_name parent_name = let msg = match parent_name with | None -> "Cannot use `parent::` in a function pointer due to class context ambiguity. Consider using the name of the parent class explicitly." | Some id -> let name = Markdown_lite.md_codify (Render.strip_ns id ^ "::" ^ meth_name) in Format.sprintf "Cannot use `parent::` in a function pointer due to class context ambiguity. Consider using %s instead" name in User_error.make Error_code.(to_enum ParentInFunctionPointer) (pos, msg) [] let missing_arrow pos cname = User_error.make Error_code.(to_enum MissingArrow) ( pos, Format.sprintf {|Keys must be specified for %s initialization|} @@ Markdown_lite.md_codify cname ) [] let disallowed_xhp_type pos ty_name = User_error.make Error_code.(to_enum DisallowedXhpType) ( pos, Format.sprintf {|%s is not a valid type. Use `:xhp` or `XHPChild`.|} @@ Markdown_lite.md_codify ty_name ) [] let name_is_reserved pos name = User_error.make Error_code.(to_enum NameIsReserved) ( pos, Format.sprintf {|%s cannot be used as it is reserved.|} @@ Markdown_lite.md_codify @@ Utils.strip_all_ns name ) [] let dollardollar_unused pos = User_error.make Error_code.(to_enum DollardollarUnused) ( pos, "This expression does not contain a " ^ "usage of the special pipe variable. Did you forget to use the `$$` " ^ "variable?" ) [] let already_bound pos name = User_error.make Error_code.(to_enum NameAlreadyBound) ( pos, Format.sprintf "Argument already bound: %s" @@ Markdown_lite.md_codify name ) [] let method_name_already_bound pos meth_name = User_error.make Error_code.(to_enum MethodNameAlreadyBound) ( pos, Format.sprintf "Method name already bound: %s" @@ Markdown_lite.md_codify meth_name ) [] let error_name_already_bound pos name prev_pos = let name = Render.strip_ns name in let hhi_msg = "This appears to be defined in an hhi file included in your project " ^ "root. The hhi files for the standard library are now a part of the " ^ "typechecker and must be removed from your project. Typically, you can " ^ "do this by deleting the \"hhi\" directory you copied into your " ^ "project when first starting with Hack." in let suffix = if Relative_path.(is_hhi (prefix (Pos.filename pos))) then [(Pos_or_decl.of_raw_pos prev_pos, hhi_msg)] else if Pos.is_hhi prev_pos then [(Pos_or_decl.of_raw_pos pos, hhi_msg)] else [] in let reasons = [(Pos_or_decl.of_raw_pos prev_pos, "Previous definition is here")] @ suffix in User_error.make Error_code.(to_enum ErrorNameAlreadyBound) ( pos, Format.sprintf "Name already bound: %s" @@ Markdown_lite.md_codify @@ Render.strip_ns name ) reasons let invalid_fun_pointer pos name = User_error.make Error_code.(to_enum InvalidFunPointer) ( pos, Format.sprintf "Unbound global function: %s is not a valid name for fun()" @@ Markdown_lite.md_codify @@ Render.strip_ns name ) [] let undefined pos var_name did_you_mean = let (reasons, quickfixes) = Option.value_map ~default:([], []) did_you_mean ~f:(fun (did_you_mean, did_you_mean_pos) -> ( [ Render.( suggestion_message var_name did_you_mean did_you_mean_pos |> Tuple2.map_fst ~f:Pos_or_decl.of_raw_pos); ], [ Quickfix.make ~title:("Change to " ^ did_you_mean) ~new_text:did_you_mean pos; ] )) in User_error.make Error_code.(to_enum Undefined) ( pos, Format.sprintf "Variable %s is undefined, or not always defined." @@ Markdown_lite.md_codify var_name ) reasons ~quickfixes let undefined_in_expr_tree pos var_name dsl did_you_mean = let (reasons, quickfixes) = Option.value_map ~default:([], []) did_you_mean ~f:(fun (did_you_mean, did_you_mean_pos) -> ( [ ( Pos_or_decl.of_raw_pos did_you_mean_pos, Printf.sprintf "Did you forget to splice in `%s`?" did_you_mean ); ], [ Quickfix.make ~title:("Splice in " ^ did_you_mean) ~new_text:(Printf.sprintf "${%s}" did_you_mean) pos; ] )) in let dsl = match dsl with | Some dsl -> Printf.sprintf "`%s` expression tree" @@ Utils.strip_ns dsl | None -> "expression tree" in User_error.make Error_code.(to_enum Undefined) ( pos, Format.sprintf "Variable %s is undefined in this %s." (Markdown_lite.md_codify var_name) dsl ) reasons ~quickfixes let this_reserved pos = User_error.make Error_code.(to_enum ThisReserved) (pos, "The type parameter `this` is reserved") [] let start_with_T pos = User_error.make Error_code.(to_enum StartWith_T) (pos, "Please make your type parameter start with the letter `T` (capital)") [] let unexpected_typedef pos expected_kind decl_pos = User_error.make Error_code.(to_enum UnexpectedTypedef) ( pos, Printf.sprintf "Expected a %s but got a type alias." @@ Markdown_lite.md_codify @@ Name_context.to_string expected_kind ) [(Pos_or_decl.of_raw_pos decl_pos, "Alias definition is here.")] let field_name_already_bound pos = User_error.make Error_code.(to_enum FdNameAlreadyBound) (pos, "Field name already bound") [] let primitive_top_level pos = User_error.make Error_code.(to_enum PrimitiveToplevel) ( pos, "Primitive type annotations are always available and may no longer be referred to in the toplevel namespace." ) [] let primitive_invalid_alias pos ty_name_used ty_name_canon = User_error.make Error_code.(to_enum PrimitiveInvalidAlias) ( pos, Format.sprintf "Invalid Hack type. Using %s in Hack is considered an error. Use %s instead, to keep the codebase consistent." (Markdown_lite.md_codify ty_name_used) (Markdown_lite.md_codify ty_name_canon) ) [] let dynamic_new_in_strict_mode pos = User_error.make Error_code.(to_enum DynamicNewInStrictMode) (pos, "Cannot use dynamic `new`.") [] let invalid_type_access_root pos id_opt = let msg = match id_opt with | Some id -> Format.sprintf "%s must be an identifier for a class, `self`, or `this`" @@ Markdown_lite.md_codify id | _ -> Format.sprintf "Type access is only valid for a class, `self`, or `this`" in User_error.make Error_code.(to_enum InvalidTypeAccessRoot) (pos, msg) [] let duplicate_user_attribute attr_name prev_pos pos = User_error.make Error_code.(to_enum DuplicateUserAttribute) ( pos, Format.sprintf "You cannot reuse the attribute %s" @@ Markdown_lite.md_codify attr_name ) [ ( Pos_or_decl.of_raw_pos prev_pos, Markdown_lite.md_codify attr_name ^ " was already used here" ); ] let invalid_memoize_label attr_name pos = User_error.make Error_code.(to_enum InvalidMemoizeLabel) ( pos, Format.sprintf "%s can only be used with items from MemoizeOption." (Markdown_lite.md_codify attr_name) ) [] let unbound_name pos name kind = let kind_str = match kind with | Name_context.ConstantNamespace -> " (a global constant)" | Name_context.FunctionNamespace -> " (a global function)" | Name_context.TypeNamespace -> "" | Name_context.ClassContext -> " (an object type)" | Name_context.TraitContext -> " (a trait)" | Name_context.ModuleNamespace -> " (a module)" | Name_context.PackageNamespace -> " (a package)" in User_error.make Error_code.(to_enum UnboundName) ( pos, "Unbound name: " ^ Markdown_lite.md_codify (Render.strip_ns name) ^ kind_str ) [] let unbound_attribute_name pos attr_name closest_attr_name = let reason = if String.is_prefix attr_name ~prefix:"__" then "starts with __ but is not a standard attribute" else "does not have a class. Please declare a class for the attribute." in let quickfixes = if String.is_prefix attr_name ~prefix:"__" then match closest_attr_name with | None -> [] | Some close_name -> [ Quickfix.make ~title:("Change to " ^ Markdown_lite.md_codify close_name) ~new_text:close_name pos; ] else [] in User_error.make Error_code.(to_enum UnboundName) ~quickfixes ( pos, Format.sprintf "Unrecognized user attribute: %s %s" (Render.strip_ns attr_name |> Markdown_lite.md_codify) reason ) [] let this_no_argument pos = User_error.make Error_code.(to_enum ThisNoArgument) (pos, "`this` expects no arguments") [] let object_cast pos = User_error.make Error_code.(to_enum ObjectCast) (pos, "Casts are only supported for `bool`, `int`, `float` and `string`.") [] let this_hint_outside_class pos = User_error.make Error_code.(to_enum ThisHintOutsideClass) (pos, "Cannot use `this` outside of a class") [] let parent_outside_class pos = User_error.make Error_codes.Typing.(to_enum ParentOutsideClass) (pos, "`parent` is undefined outside of a class") [] let self_outside_class pos = User_error.make Error_codes.Typing.(to_enum SelfOutsideClass) (pos, "`self` is undefined outside of a class") [] let static_outside_class pos = User_error.make Error_codes.Typing.(to_enum StaticOutsideClass) (pos, "`static` is undefined outside of a class") [] let this_type_forbidden pos in_extends in_req_extends = let msg = if in_extends then "This type `this` cannot be used in an `extends` clause" else if in_req_extends then "This type `this` cannot be used in an `require extends` clause`" else "The type `this` cannot be used as a constraint on a class generic, or as the type of a static member variable" in User_error.make Error_code.(to_enum ThisMustBeReturn) (pos, msg) [] let nonstatic_property_with_lsb pos = User_error.make Error_code.(to_enum NonstaticPropertyWithLSB) (pos, "`__LSB` attribute may only be used on static properties") [] let lowercase_this pos ty_name = User_error.make Error_code.(to_enum LowercaseThis) ( pos, Format.sprintf "Invalid Hack type %s. Use `this` instead." @@ Markdown_lite.md_codify ty_name ) [] let classname_param pos = User_error.make Error_code.(to_enum ClassnameParam) ( pos, "Missing type parameter to `classname`; `classname` is entirely" ^ " meaningless without one" ) [] let tparam_applied_to_type pos tparam_name = User_error.make Error_code.(to_enum HigherKindedTypesUnsupportedFeature) ( pos, Printf.sprintf "`%s` is a type parameter. Type parameters cannot take type arguments (e.g. `%s<int>` isn't allowed)" tparam_name tparam_name ) [] let tparam_with_tparam pos tparam_name = User_error.make Error_code.(to_enum HigherKindedTypesUnsupportedFeature) ( pos, if String.equal tparam_name "_" then "Type parameters cannot themselves have type parameters" else Format.sprintf "%s is a type parameter. Type parameters cannot themselves have type parameters" @@ Markdown_lite.md_codify tparam_name ) [] let shadowed_tparam prev_pos tparam_name pos = User_error.make Error_code.(to_enum ShadowedTypeParam) ( pos, Printf.sprintf "You cannot re-bind the type parameter %s" (Markdown_lite.md_codify tparam_name) ) [ ( Pos_or_decl.of_raw_pos prev_pos, Printf.sprintf "%s is already bound here" (Markdown_lite.md_codify tparam_name) ); ] let missing_typehint pos = User_error.make Error_code.(to_enum MissingTypehint) (pos, "Please add a type hint") [] let expected_variable pos = User_error.make Error_code.(to_enum ExpectedVariable) (pos, "Was expecting a variable name") [] let too_many_arguments pos = User_error.make Error_code.(to_enum NamingTooManyArguments) (pos, "Too many arguments") [] let too_few_arguments pos = User_error.make Error_code.(to_enum NamingTooFewArguments) (pos, "Too few arguments") [] let expected_collection pos cname = User_error.make Error_code.(to_enum ExpectedCollection) ( pos, Format.sprintf "Unexpected collection type %s" (Render.strip_ns cname |> Markdown_lite.md_codify) ) [] let illegal_CLASS pos = User_error.make Error_code.(to_enum IllegalClass) (pos, "Using `__CLASS__` outside a class or trait") [] let illegal_TRAIT pos = User_error.make Error_code.(to_enum IllegalTrait) (pos, "Using `__TRAIT__` outside a trait") [] let illegal_fun pos = User_error.make Error_code.(to_enum IllegalFun) ( pos, "The argument to `fun()` must be a single-quoted, constant " ^ "literal string representing a valid function name." ) [] let illegal_member_variable_class pos = User_error.make Error_code.(to_enum IllegalMemberVariableClass) ( pos, "Cannot declare a constant named `class`. The name `class` is reserved for the class constant that represents the name of the class" ) [] let illegal_meth_fun pos = User_error.make Error_code.(to_enum IllegalMethFun) ( pos, "String argument to `fun()` contains `:`;" ^ " for static class methods, use" ^ " `class_meth(Cls::class, 'method_name')`, not `fun('Cls::method_name')`" ) [] let illegal_inst_meth pos = User_error.make Error_code.(to_enum IllegalInstMeth) ( pos, "The argument to `inst_meth()` must be an expression and a " ^ "constant literal string representing a valid method name." ) [] let illegal_meth_caller pos = User_error.make Error_code.(to_enum IllegalMethCaller) ( pos, "The two arguments to `meth_caller()` must be:" ^ "\n - first: `ClassOrInterface::class`" ^ "\n - second: a single-quoted string literal containing the name" ^ " of a non-static method of that class" ) [] let illegal_class_meth pos = User_error.make Error_code.(to_enum IllegalClassMeth) ( pos, "The two arguments to `class_meth()` must be:" ^ "\n - first: `ValidClassname::class`" ^ "\n - second: a single-quoted string literal containing the name" ^ " of a static method of that class" ) [] let illegal_constant pos = illegal_constant pos let lvar_in_obj_get pos lvar_pos lvar_name = let lvar_no_dollar = String.chop_prefix_if_exists lvar_name ~prefix:"$" in let suggestion = Printf.sprintf "->%s" lvar_no_dollar in let suggestion_message = Printf.sprintf "Did you mean %s instead?" (Markdown_lite.md_codify suggestion) in let quickfixes = [ Quickfix.make ~title:("Change to " ^ suggestion) ~new_text:lvar_no_dollar pos; ] in User_error.make Error_code.(to_enum LvarInObjGet) ~quickfixes ( pos, "Dynamic access of properties and methods is only permitted on values of type `dynamic`." ) [(Pos_or_decl.of_raw_pos lvar_pos, suggestion_message)] let dynamic_method_access pos = User_error.make Error_code.(to_enum DynamicMethodAccess) ( pos, "Dynamic method access is not allowed. Please use the method name directly, for example `::myMethodName()`" ) [] let class_meth_non_final_self pos class_name = User_error.make Error_code.(to_enum ClassMethNonFinalSelf) ( pos, Format.sprintf "`class_meth` with `self::class` does not preserve class calling context.\nUse `static::class`, or `%s::class` explicitly" @@ Render.strip_ns class_name ) [] let class_meth_non_final_CLASS pos class_name is_trait = User_error.make Error_code.(to_enum ClassMethNonFinalCLASS) ( pos, if is_trait then "`class_meth` with `__CLASS__` in non-final classes is not allowed.\n" else Format.sprintf "`class_meth` with `__CLASS__` in non-final classes is not allowed.\nUse `%s::class` explicitly" @@ Render.strip_ns class_name ) [] let self_in_non_final_function_pointer pos class_name meth_name = let suggestion = match class_name with | None -> "" | Some id -> let name = Markdown_lite.md_codify (Render.strip_ns id ^ "::" ^ meth_name) in "Consider using " ^ name ^ " instead" in User_error.make Error_code.(to_enum SelfInNonFinalFunctionPointer) ( pos, "Cannot use `self::` in a function pointer in a non-final class due to class context ambiguity. " ^ suggestion ) [] let invalid_wildcard_context pos = User_error.make Error_code.(to_enum InvalidWildcardContext) ( pos, "A wildcard can only be used as a context when it is the sole context of a callable parameter in a higher-order function. The parameter must also be referenced with `ctx` in the higher-order function's context list, e.g. `function hof((function ()[_]: void) $f)[ctx $f]: void {}`" ) [] let return_only_typehint pos kind = let kstr = Markdown_lite.md_codify @@ match kind with | Hvoid -> "void" | Hnoreturn -> "noreturn" in User_error.make Error_code.(to_enum ReturnOnlyTypehint) ( pos, Format.sprintf "You can only use the %s type as the return type of a function or method" kstr ) [] let unexpected_type_arguments pos = User_error.make Error_code.(to_enum UnexpectedTypeArguments) (pos, "Type arguments are not expected for this type") [] let too_many_type_arguments pos = User_error.make Error_code.(to_enum TooManyTypeArguments) (pos, "Too many type arguments for this type") [] let this_as_lexical_variable pos = User_error.make Error_code.(to_enum ThisAsLexicalVariable) (pos, "Cannot use `$this` as lexical variable") [] let hkt_unsupported_feature pos because_nested var_name feature = let var_name = Markdown_lite.md_codify var_name in let var_desc = Format.sprintf (if because_nested then {|%s is a generic parameter of another (higher-kinded) generic parameter.|} else {|%s is a higher-kinded type parameter, standing for a type that has type parameters itself.|}) var_name in let feature_desc = match feature with | Ft_where_constraints -> "where constraints mentioning" | Ft_constraints -> "constraints on" | Ft_reification -> "reification of" | Ft_user_attrs -> "user attributes on" | Ft_variance -> "variance other than invariant for" in User_error.make Error_code.(to_enum HigherKindedTypesUnsupportedFeature) ( pos, Format.sprintf {|%s We don't support %s parameters like %s.|} var_desc feature_desc var_name ) [] let hkt_partial_application pos count = User_error.make Error_code.(to_enum HigherKindedTypesUnsupportedFeature) ( pos, Format.sprintf {|A higher-kinded type is expected here. We do not not support partial applications to yield higher-kinded types, but you are providing %n type argument(s).|} count ) [] let hkt_wildcard pos = User_error.make Error_code.(to_enum HigherKindedTypesUnsupportedFeature) ( pos, "You are supplying _ where a higher-kinded type is expected." ^ " We cannot infer higher-kinded type arguments at this time, please state the actual type." ) [] let hkt_implicit_argument decl_pos param_name pos = let param_desc = (* This should be Naming_special_names.Typehints.wildcard, but its not available in this module *) if String.equal param_name "_" then "the anonymous generic parameter" else "the generic parameter " ^ param_name in User_error.make Error_code.(to_enum HigherKindedTypesUnsupportedFeature) ( pos, "You left out the type arguments here such that they may be inferred." ^ " However, a higher-kinded type is expected in place of " ^ param_desc ^ ", meaning that the type arguments cannot be inferred." ^ " Please provide the type arguments explicitly." ) [ ( decl_pos, Format.sprintf {|%s was declared to be higher-kinded here.|} param_desc ); ] let hkt_class_with_constraints_used pos class_name = User_error.make Error_code.(to_enum HigherKindedTypesUnsupportedFeature) ( pos, Format.sprintf "The class %s imposes constraints on some of its type parameters. Classes that do this cannot be used as higher-kinded types at this time." @@ Render.strip_ns class_name ) [] let hkt_alias_with_implicit_constraints typedef_pos typedef_name used_class_in_def_pos used_class_in_def_name used_class_tparam_name typedef_tparam_name pos = let typedef_name = Render.strip_ns typedef_name and used_class_in_def_name = Render.strip_ns used_class_in_def_name and used_class_tparam_name = Render.strip_ns used_class_tparam_name in User_error.make Error_code.(to_enum HigherKindedTypesUnsupportedFeature) ( pos, Format.sprintf "The type %s implicitly imposes constraints on its type parameters. Therefore, it cannot be used as a higher-kinded type at this time." typedef_name ) [ (typedef_pos, "The definition of " ^ typedef_name ^ " is here."); ( used_class_in_def_pos, "The definition of " ^ typedef_name ^ " relies on " ^ used_class_in_def_name ^ " and the constraints that " ^ used_class_in_def_name ^ " imposes on its type parameter " ^ used_class_tparam_name ^ " then become implicit constraints on the type parameter " ^ typedef_tparam_name ^ " of " ^ typedef_name ^ "." ); ] let explicit_consistent_constructor ck pos = let classish_kind = match ck with | Ast_defs.Cclass _ -> "class " | Ast_defs.Ctrait -> "trait " | Ast_defs.Cinterface -> "interface " | Ast_defs.Cenum_class _ -> "enum class " | Ast_defs.Cenum -> "enum " in User_error.make Error_code.(to_enum ExplicitConsistentConstructor) ( pos, "This " ^ classish_kind ^ "is marked <<__ConsistentConstruct>>, so it must declare a constructor explicitly" ) [] let module_declaration_outside_allowed_files pos = User_error.make Error_code.(to_enum ModuleDeclarationOutsideAllowedFiles) ( pos, "This module declaration exists in an unapproved file. " ^ "The set of approved files is in .hhconfig" ) [] let deprecated_use pos fn_name = let msg = "The builtin " ^ Markdown_lite.md_codify (Render.strip_ns fn_name) ^ " is deprecated." in User_error.make Error_codes.Typing.(to_enum DeprecatedUse) (pos, msg) [] let unnecessary_attribute pos ~attr ~class_pos ~class_name ~suggestion = let class_name = Render.strip_ns class_name in let (reason_pos, reason_msg) = (class_pos, sprintf "the class `%s` is final" class_name) in let reason = let suggestion = match suggestion with | None -> "Try deleting this attribute" | Some s -> s in [ ( Pos_or_decl.of_raw_pos reason_pos, "It is unnecessary because " ^ reason_msg ); (Pos_or_decl.of_raw_pos pos, suggestion); ] in User_error.make Error_codes.Typing.(to_enum UnnecessaryAttribute) (pos, sprintf "The attribute `%s` is unnecessary" @@ Render.strip_ns attr) reason let tparam_non_shadowing_reuse pos var_name = User_error.make Error_codes.Typing.(to_enum TypeParameterNameAlreadyUsedNonShadow) ( pos, "The name " ^ Markdown_lite.md_codify var_name ^ " was already used for another generic parameter. Please use a different name to avoid confusion." ) [] let to_user_error = function | Unsupported_trait_use_as pos -> unsupported_trait_use_as pos | Unsupported_instead_of pos -> unsupported_instead_of pos | Unexpected_arrow { pos; cname } -> unexpected_arrow pos cname | Missing_arrow { pos; cname } -> missing_arrow pos cname | Disallowed_xhp_type { pos; ty_name } -> disallowed_xhp_type pos ty_name | Name_is_reserved { pos; name } -> name_is_reserved pos name | Dollardollar_unused pos -> dollardollar_unused pos | Already_bound { pos; name } -> already_bound pos name | Method_name_already_bound { pos; meth_name } -> method_name_already_bound pos meth_name | Error_name_already_bound { pos; name; prev_pos } -> error_name_already_bound pos name prev_pos | Invalid_fun_pointer { pos; name } -> invalid_fun_pointer pos name | Undefined { pos; var_name; did_you_mean } -> undefined pos var_name did_you_mean | This_reserved pos -> this_reserved pos | Start_with_T pos -> start_with_T pos | Unexpected_typedef { pos; expected_kind; decl_pos } -> unexpected_typedef pos expected_kind decl_pos | Field_name_already_bound pos -> field_name_already_bound pos | Primitive_top_level pos -> primitive_top_level pos | Primitive_invalid_alias { pos; ty_name_used; ty_name_canon } -> primitive_invalid_alias pos ty_name_used ty_name_canon | Dynamic_new_in_strict_mode pos -> dynamic_new_in_strict_mode pos | Invalid_type_access_root { pos; id } -> invalid_type_access_root pos id | Duplicate_user_attribute { attr_name; prev_pos; pos } -> duplicate_user_attribute attr_name prev_pos pos | Invalid_memoize_label { attr_name; pos } -> invalid_memoize_label attr_name pos | Unbound_name { pos; name; kind } -> unbound_name pos name kind | Unbound_attribute_name { pos; attr_name; closest_attr_name } -> unbound_attribute_name pos attr_name closest_attr_name | This_no_argument pos -> this_no_argument pos | Object_cast pos -> object_cast pos | This_hint_outside_class pos -> this_hint_outside_class pos | Parent_outside_class pos -> parent_outside_class pos | Self_outside_class pos -> self_outside_class pos | Static_outside_class pos -> static_outside_class pos | This_type_forbidden { pos; in_extends; in_req_extends } -> this_type_forbidden pos in_extends in_req_extends | Nonstatic_property_with_lsb pos -> nonstatic_property_with_lsb pos | Lowercase_this { pos; ty_name } -> lowercase_this pos ty_name | Classname_param pos -> classname_param pos | Tparam_applied_to_type { pos; tparam_name } -> tparam_applied_to_type pos tparam_name | Tparam_with_tparam { pos; tparam_name } -> tparam_with_tparam pos tparam_name | Shadowed_tparam { prev_pos; tparam_name; pos } -> shadowed_tparam prev_pos tparam_name pos | Missing_typehint pos -> missing_typehint pos | Expected_variable pos -> expected_variable pos | Too_many_arguments pos -> too_many_arguments pos | Too_few_arguments pos -> too_few_arguments pos | Expected_collection { pos; cname } -> expected_collection pos cname | Illegal_CLASS pos -> illegal_CLASS pos | Illegal_TRAIT pos -> illegal_TRAIT pos | Illegal_fun pos -> illegal_fun pos | Illegal_member_variable_class pos -> illegal_member_variable_class pos | Illegal_meth_fun pos -> illegal_meth_fun pos | Illegal_inst_meth pos -> illegal_inst_meth pos | Illegal_meth_caller pos -> illegal_meth_caller pos | Illegal_class_meth pos -> illegal_class_meth pos | Illegal_constant pos -> illegal_constant pos | Lvar_in_obj_get { pos; lvar_pos; lvar_name } -> lvar_in_obj_get pos lvar_pos lvar_name | Class_meth_non_final_self { pos; class_name } -> class_meth_non_final_self pos class_name | Class_meth_non_final_CLASS { pos; class_name; is_trait } -> class_meth_non_final_CLASS pos class_name is_trait | Const_without_typehint { pos; const_name; ty_name } -> const_without_typehint pos const_name ty_name | Prop_without_typehint { pos; prop_name; vis } -> prop_without_typehint pos prop_name vis | Invalid_require_implements pos -> invalid_req_implements pos | Invalid_require_extends pos -> invalid_req_extends pos | Invalid_require_class pos -> invalid_req_class pos | Invalid_wildcard_context pos -> invalid_wildcard_context pos | Did_you_mean { name; suggest_pos; suggest_name; pos } -> did_you_mean_naming pos name suggest_pos suggest_name | Using_internal_class { pos; class_name } -> using_internal_class pos class_name | Too_few_type_arguments pos -> too_few_type_arguments pos | Dynamic_class_name_in_strict_mode pos -> dynamic_class_name_in_strict_mode pos | Xhp_optional_required_attr { pos; attr_name } -> xhp_optional_required_attr pos attr_name | Xhp_required_with_default { pos; attr_name } -> xhp_required_with_default pos attr_name | Array_typehints_disallowed pos -> array_typehints_disallowed pos | Wildcard_hint_disallowed pos -> wildcard_hint_disallowed pos | Wildcard_tparam_disallowed pos -> wildcard_param_disallowed pos | Illegal_use_of_dynamically_callable { meth_pos; vis; attr_pos } -> illegal_use_of_dynamically_callable attr_pos meth_pos vis | Parent_in_function_pointer { pos; meth_name; parent_name } -> parent_in_function_pointer pos meth_name parent_name | Self_in_non_final_function_pointer { pos; class_name; meth_name } -> self_in_non_final_function_pointer pos class_name meth_name | Return_only_typehint { pos; kind } -> return_only_typehint pos kind | Unexpected_type_arguments pos -> unexpected_type_arguments pos | Too_many_type_arguments pos -> too_many_type_arguments pos | This_as_lexical_variable pos -> this_as_lexical_variable pos | HKT_unsupported_feature { pos; because_nested; var_name; feature } -> hkt_unsupported_feature pos because_nested var_name feature | HKT_partial_application { pos; count } -> hkt_partial_application pos count | HKT_wildcard pos -> hkt_wildcard pos | HKT_implicit_argument { decl_pos; param_name; pos } -> hkt_implicit_argument decl_pos param_name pos | HKT_class_with_constraints_used { pos; class_name } -> hkt_class_with_constraints_used pos class_name | HKT_alias_with_implicit_constraints { typedef_pos; typedef_name; used_class_in_def_pos; used_class_in_def_name; used_class_tparam_name; typedef_tparam_name; pos; } -> hkt_alias_with_implicit_constraints typedef_pos typedef_name used_class_in_def_pos used_class_in_def_name used_class_tparam_name typedef_tparam_name pos | Explicit_consistent_constructor { pos; classish_kind } -> explicit_consistent_constructor classish_kind pos | Module_declaration_outside_allowed_files pos -> module_declaration_outside_allowed_files pos | Dynamic_method_access pos -> dynamic_method_access pos | Deprecated_use { pos; fn_name } -> deprecated_use pos fn_name | Unnecessary_attribute { pos; attr; class_pos; class_name; suggestion } -> unnecessary_attribute pos ~attr ~class_pos ~class_name ~suggestion | Tparam_non_shadowing_reuse { pos; tparam_name } -> tparam_non_shadowing_reuse pos tparam_name | Undefined_in_expr_tree { pos; var_name; dsl; did_you_mean } -> undefined_in_expr_tree pos var_name dsl did_you_mean | Dynamic_hint_disallowed pos -> dynamic_hint_disallowed pos | Illegal_typed_local { join; id_pos; id_name; def_pos } -> illegal_typed_local ~join id_pos id_name (Pos_or_decl.of_raw_pos def_pos)
OCaml Interface
hhvm/hphp/hack/src/naming/naming_error.mli
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module Error_code : sig type t end type visibility = | Vprivate | Vpublic | Vinternal | Vprotected type return_only_hint = | Hvoid | Hnoreturn type unsupported_feature = | Ft_where_constraints | Ft_constraints | Ft_reification | Ft_user_attrs | Ft_variance type t = | Unsupported_trait_use_as of Pos.t | Unsupported_instead_of of Pos.t | Unexpected_arrow of { pos: Pos.t; cname: string; } | Missing_arrow of { pos: Pos.t; cname: string; } | Disallowed_xhp_type of { pos: Pos.t; ty_name: string; } | Name_is_reserved of { pos: Pos.t; name: string; } | Dollardollar_unused of Pos.t | Method_name_already_bound of { pos: Pos.t; meth_name: string; } | Error_name_already_bound of { pos: Pos.t; name: string; prev_pos: Pos.t; } | Unbound_name of { pos: Pos.t; name: string; kind: Name_context.t; } | Invalid_fun_pointer of { pos: Pos.t; name: string; } | Undefined of { pos: Pos.t; var_name: string; did_you_mean: (string * Pos.t) option; } | Undefined_in_expr_tree of { pos: Pos.t; var_name: string; dsl: string option; did_you_mean: (string * Pos.t) option; } | This_reserved of Pos.t | Start_with_T of Pos.t | Already_bound of { pos: Pos.t; name: string; } | Unexpected_typedef of { pos: Pos.t; decl_pos: Pos.t; expected_kind: Name_context.t; } | Field_name_already_bound of Pos.t | Primitive_top_level of Pos.t | Primitive_invalid_alias of { pos: Pos.t; ty_name_used: string; ty_name_canon: string; } | Dynamic_new_in_strict_mode of Pos.t | Invalid_type_access_root of { pos: Pos.t; id: string option; } | Duplicate_user_attribute of { pos: Pos.t; attr_name: string; prev_pos: Pos.t; } | Invalid_memoize_label of { pos: Pos.t; attr_name: string; } | Unbound_attribute_name of { pos: Pos.t; attr_name: string; closest_attr_name: string option; } | This_no_argument of Pos.t | Object_cast of Pos.t | This_hint_outside_class of Pos.t | Parent_outside_class of Pos.t | Self_outside_class of Pos.t | Static_outside_class of Pos.t | This_type_forbidden of { pos: Pos.t; in_extends: bool; in_req_extends: bool; } | Nonstatic_property_with_lsb of Pos.t | Lowercase_this of { pos: Pos.t; ty_name: string; } | Classname_param of Pos.t | Tparam_applied_to_type of { pos: Pos.t; tparam_name: string; } | Tparam_with_tparam of { pos: Pos.t; tparam_name: string; } | Shadowed_tparam of { pos: Pos.t; tparam_name: string; prev_pos: Pos.t; } | Missing_typehint of Pos.t | Expected_variable of Pos.t | Too_many_arguments of Pos.t | Too_few_arguments of Pos.t | Expected_collection of { pos: Pos.t; cname: string; } | Illegal_CLASS of Pos.t | Illegal_TRAIT of Pos.t | Illegal_fun of Pos.t | Illegal_member_variable_class of Pos.t | Illegal_meth_fun of Pos.t | Illegal_inst_meth of Pos.t | Illegal_meth_caller of Pos.t | Illegal_class_meth of Pos.t | Lvar_in_obj_get of { pos: Pos.t; lvar_pos: Pos.t; lvar_name: string; } | Class_meth_non_final_self of { pos: Pos.t; class_name: string; } | Class_meth_non_final_CLASS of { pos: Pos.t; class_name: string; is_trait: bool; } | Const_without_typehint of { pos: Pos.t; const_name: string; ty_name: string; } | Prop_without_typehint of { pos: Pos.t; prop_name: string; vis: visibility; } | Illegal_constant of Pos.t | Invalid_require_implements of Pos.t | Invalid_require_extends of Pos.t | Invalid_require_class of Pos.t | Did_you_mean of { pos: Pos.t; name: string; suggest_pos: Pos.t; suggest_name: string; } | Using_internal_class of { pos: Pos.t; class_name: string; } | Too_few_type_arguments of Pos.t | Dynamic_class_name_in_strict_mode of Pos.t | Xhp_optional_required_attr of { pos: Pos.t; attr_name: string; } | Xhp_required_with_default of { pos: Pos.t; attr_name: string; } | Array_typehints_disallowed of Pos.t | Wildcard_hint_disallowed of Pos.t | Wildcard_tparam_disallowed of Pos.t | Illegal_use_of_dynamically_callable of { attr_pos: Pos.t; meth_pos: Pos.t; vis: visibility; } | Parent_in_function_pointer of { pos: Pos.t; meth_name: string; parent_name: string option; } | Self_in_non_final_function_pointer of { pos: Pos.t; meth_name: string; class_name: string option; } | Invalid_wildcard_context of Pos.t | Return_only_typehint of { pos: Pos.t; kind: return_only_hint; } | Unexpected_type_arguments of Pos.t | Too_many_type_arguments of Pos.t | This_as_lexical_variable of Pos.t | HKT_unsupported_feature of { pos: Pos.t; because_nested: bool; var_name: string; feature: unsupported_feature; } | HKT_partial_application of { pos: Pos.t; count: int; } | HKT_wildcard of Pos.t | HKT_implicit_argument of { pos: Pos.t; decl_pos: Pos_or_decl.t; param_name: string; } | HKT_class_with_constraints_used of { pos: Pos.t; class_name: string; } | HKT_alias_with_implicit_constraints of { pos: Pos.t; typedef_pos: Pos_or_decl.t; used_class_in_def_pos: Pos_or_decl.t; typedef_name: string; typedef_tparam_name: string; used_class_in_def_name: string; used_class_tparam_name: string; } | Explicit_consistent_constructor of { pos: Pos.t; classish_kind: Ast_defs.classish_kind; } | Module_declaration_outside_allowed_files of Pos.t | Dynamic_method_access of Pos.t | Deprecated_use of { pos: Pos.t; fn_name: string; } | Unnecessary_attribute of { pos: Pos.t; attr: string; class_pos: Pos.t; class_name: string; suggestion: string option; } | Tparam_non_shadowing_reuse of { pos: Pos.t; tparam_name: string; } | Dynamic_hint_disallowed of Pos.t | Illegal_typed_local of { join: bool; id_pos: Pos.t; id_name: string; def_pos: Pos.t; } val to_user_error : t -> (Pos.t, Pos_or_decl.t) User_error.t
OCaml
hhvm/hphp/hack/src/naming/naming_global.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 "naming" a program. * * The naming phase consists in several things * 1- get all the global names * 2- transform all the local names into a unique identifier *) open Hh_prelude (*****************************************************************************) (* The types *) (*****************************************************************************) let category = "naming_global" module GEnv = struct (** This function logs and error and raises an exception, ultimately causing the typechecker to terminate. Why? We looked for a file in the file heap, but it was deleted before we could get it. This occurs with highest probability when we have multiple large rebases in quick succession, and the typechecker doesn't get updates from watchman while checking. For now, we restart gracefully, but in future versions we'll be restarting the server on large rebases anyhow, so this is sufficient behavior. TODO(jjwu): optimize this. Instead of forcing a server restart, catch the exception in the recheck look and start another recheck cycle by adding more files to the unprocessed/partially-processed set in the previous loop. *) let file_disappeared_under_our_feet (pos, name) = let fn = FileInfo.get_pos_filename pos in Hh_logger.log "File missing: %s" (Relative_path.to_absolute fn); Hh_logger.log "Name missing: %s" name; raise File_provider.File_provider_stale let get_fun_full_pos ctx (pos, name) = match Naming_provider.get_fun_full_pos_by_parsing_file ctx (pos, name) with | Some pos -> (pos, name) | None -> file_disappeared_under_our_feet (pos, name) let get_type_full_pos ctx (pos, name) = match Naming_provider.get_type_full_pos_by_parsing_file ctx (pos, name) with | Some pos -> (pos, name) | None -> file_disappeared_under_our_feet (pos, name) let get_const_full_pos ctx (pos, name) = match Naming_provider.get_const_full_pos_by_parsing_file ctx (pos, name) with | Some pos -> (pos, name) | None -> file_disappeared_under_our_feet (pos, name) let get_module_full_pos ctx (pos, name) = match Naming_provider.get_module_full_pos_by_parsing_file ctx (pos, name) with | Some pos -> (pos, name) | None -> file_disappeared_under_our_feet (pos, name) let type_pos ctx name = match Naming_provider.get_type_pos ctx name with | Some pos -> let (p, _) = get_type_full_pos ctx (pos, name) in Some p | None -> None let type_info ctx name = match Naming_provider.get_type_pos_and_kind ctx name with | Some (pos, ((Naming_types.TClass | Naming_types.TTypedef) as kind)) -> let (p, _) = get_type_full_pos ctx (pos, name) in Some (p, kind) | None -> None let fun_pos ctx name = match Naming_provider.get_fun_pos ctx name with | Some pos -> let (p, _) = get_fun_full_pos ctx (pos, name) in Some p | None -> None let typedef_pos ctx name = match Naming_provider.get_type_pos_and_kind ctx name with | Some (pos, Naming_types.TTypedef) -> let (p, _) = get_type_full_pos ctx (pos, name) in Some p | Some (_, Naming_types.TClass) | None -> None let gconst_pos ctx name = match Naming_provider.get_const_pos ctx name with | Some pos -> let (p, _) = get_const_full_pos ctx (pos, name) in Some p | None -> None let module_pos ctx name = match Naming_provider.get_module_pos ctx name with | Some pos -> Some (fst @@ get_module_full_pos ctx (pos, name)) | None -> None end (** Given name-and-position [id], compared to the [canonical_id] name-and-position, this judges whether we should report [id] as "already bound". This is surprising. Notionally you'd expect that the mere existence of a canonical_id means that we should report [id] as already-bound. But this function has some historical quirks: - The function was written to support [id] being a file-only position. But in practice it's always a full position that comes from parsing. If we encounter a file-only position, we log this anomalous path. - The function was written so that if you declare [id], but it's in the exact same file+position as [canonical_id], then you must be declaring the same name and hence shouldn't report it as already-bound. This path should never arise (since a file's previous names all get removed before we decl that file); we log this anomalous path. - From the way this function is invoked, [canonical_id] should always be either in a different file (meaning that the user declared a symbol in the currently-being-declared file which conflicts with another file), or in the same file (meaning that the user declared two conflicting symbols in the same file). The parameter [current_file_symbols_acc] gathers all the symbol positions we've declared so far from the current file. If we encounter a [canonical_id] that's in the same file but not already in [current_file_symbols_acc], that's anomalous, and we log it. *) let should_report_duplicate (ctx : Provider_context.t) (fi : FileInfo.t) (current_file_symbols_acc : FileInfo.pos list) ~(id : FileInfo.id) ~(canonical_id : FileInfo.id) : bool = let open FileInfo in let (p, name, _) = id in let (pc, canonical, _) = canonical_id in (* helper, for the various paths below which want to log a bug *) let bug ~(desc : string) : unit = let () = Hh_logger.log "INVARIANT_VIOLATION_BUG [%s] %s %s" desc name (FileInfo.show_pos p) in Printf.eprintf "%s\n%!" (Exception.get_current_callstack_string 99 |> Exception.clean_stack); HackEventLogger.invariant_violation_bug desc ~path:(FileInfo.get_pos_filename p) ~telemetry: (Telemetry.create () |> Telemetry.string_ ~key:"name" ~value:name |> Telemetry.string_ ~key:"canonical_name" ~value:canonical |> Telemetry.string_ ~key:"canonical_path" ~value:(FileInfo.get_pos_filename pc |> Relative_path.to_absolute) |> Telemetry.string_ ~key:"fileinfo" ~value:(FileInfo.show fi)) in (* Detect anomaly where we're given a file-only [id] *) begin match p with | Full _ -> () | File _ -> bug ~desc:"naming_duplicate_file_only_p" end; let is_same_pos = match (pc, p) with | (Full a, Full b) -> Pos.compare a b = 0 | ((File (Fun, _) as a), Full b) | (Full b, (File (Fun, _) as a)) -> let a = fst (GEnv.get_fun_full_pos ctx (a, canonical)) in Pos.compare a b = 0 | ((File (Const, _) as a), Full b) | (Full b, (File (Const, _) as a)) -> let a = fst (GEnv.get_const_full_pos ctx (a, canonical)) in Pos.compare a b = 0 | ((File ((Class | Typedef), _) as a), Full b) | (Full b, (File ((Class | Typedef), _) as a)) -> let a = fst (GEnv.get_type_full_pos ctx (a, canonical)) in Pos.compare a b = 0 | ((File (Module, _) as a), Full b) | (Full b, (File (Module, _) as a)) -> let a = fst (GEnv.get_module_full_pos ctx (a, canonical)) in Pos.compare a b = 0 | (File (a, fna), File (b, fnb)) -> Relative_path.equal fna fnb && equal_name_type a b in (* Detect anomaly if [id] and [canonical_id] are identical positions *) if is_same_pos then bug ~desc:"naming_duplicate_same"; (* Detect anomaly where [canonical_id] is in the same file but not found in [current_file_symbols_acc] *) if (not is_same_pos) && Relative_path.equal (FileInfo.get_pos_filename pc) (FileInfo.get_pos_filename p) && not (List.mem current_file_symbols_acc pc ~equal:FileInfo.equal_pos) then bug ~desc:"naming_duplicate_same_file_not_acc"; (* Finally, should we report duplicates? Generally yes, except in that same anomalous case! *) not is_same_pos (* The primitives to manipulate the naming environment *) module Env = struct let new_fun_skip_if_already_bound ctx fn (_p, name, _) = match Naming_provider.get_fun_canon_name ctx name with | Some _ -> () | None -> let backend = Provider_context.get_backend ctx in Naming_provider.add_fun backend name (FileInfo.File (FileInfo.Fun, fn)) let new_type_skip_if_already_bound ctx fn ~kind (_p, name, _) = let name_type = Naming_types.type_kind_to_name_type kind in match Naming_provider.get_type_canon_name ctx name with | Some _ -> () | None -> let backend = Provider_context.get_backend ctx in (* We store redundant info in this case, but if the position is a *) (* Full position, we don't store the kind, so this is necessary *) Naming_provider.add_type backend name (FileInfo.File (name_type, fn)) kind let new_global_const_skip_if_already_bound ctx fn (_p, name, _) = let backend = Provider_context.get_backend ctx in Naming_provider.add_const backend name (FileInfo.File (FileInfo.Const, fn)) let new_fun_error_if_already_bound (ctx : Provider_context.t) (fi : FileInfo.t) ((current_file_symbols_acc, is_okay_acc) : FileInfo.pos list * bool) (id : FileInfo.id) : FileInfo.pos list * bool = let (p, name, _) = id in match Naming_provider.get_fun_canon_name ctx name with | Some canonical -> let pc = Option.value_exn (Naming_provider.get_fun_pos ctx canonical) in let is_error = should_report_duplicate ctx fi current_file_symbols_acc ~id ~canonical_id:(pc, canonical, None) in (current_file_symbols_acc, is_okay_acc && not is_error) | None -> let backend = Provider_context.get_backend ctx in Naming_provider.add_fun backend name p; (p :: current_file_symbols_acc, is_okay_acc) let new_type_error_if_already_bound (ctx : Provider_context.t) (fi : FileInfo.t) ~(kind : Naming_types.kind_of_type) ((current_file_symbols_acc, is_okay_acc) : FileInfo.pos list * bool) (id : FileInfo.id) : FileInfo.pos list * bool = let (p, name, _) = id in match Naming_provider.get_type_canon_name ctx name with | Some canonical -> let pc = Option.value_exn (Naming_provider.get_type_pos ctx canonical) in let is_error = should_report_duplicate ctx fi current_file_symbols_acc ~id ~canonical_id:(pc, canonical, None) in (current_file_symbols_acc, is_okay_acc && not is_error) | None -> let backend = Provider_context.get_backend ctx in Naming_provider.add_type backend name p kind; (p :: current_file_symbols_acc, is_okay_acc) let new_global_const_error_if_already_bound (ctx : Provider_context.t) (fi : FileInfo.t) ((current_file_symbols_acc, is_okay_acc) : FileInfo.pos list * bool) (id : FileInfo.id) : FileInfo.pos list * bool = let (p, name, _) = id in match Naming_provider.get_const_pos ctx name with | Some pc -> let is_error = should_report_duplicate ctx fi current_file_symbols_acc ~id ~canonical_id:(pc, name, None) in (current_file_symbols_acc, is_okay_acc && not is_error) | None -> let backend = Provider_context.get_backend ctx in Naming_provider.add_const backend name p; (p :: current_file_symbols_acc, is_okay_acc) let new_module_skip_if_already_bound ctx fn (_p, name, _) = let backend = Provider_context.get_backend ctx in Naming_provider.add_module backend name (FileInfo.File (FileInfo.Module, fn)) let new_module_error_if_already_bound (ctx : Provider_context.t) (fi : FileInfo.t) ((current_file_symbols_acc, is_okay_acc) : FileInfo.pos list * bool) (id : FileInfo.id) : FileInfo.pos list * bool = let (p, name, _) = id in match Naming_provider.get_module_pos ctx name with | Some pc -> let is_error = should_report_duplicate ctx fi current_file_symbols_acc ~id ~canonical_id:(pc, name, None) in (current_file_symbols_acc, is_okay_acc && not is_error) | None -> let backend = Provider_context.get_backend ctx in Naming_provider.add_module backend name p; (p :: current_file_symbols_acc, is_okay_acc) end (*****************************************************************************) (* Updating the environment *) (*****************************************************************************) let remove_decls ~backend ~funs ~classes ~typedefs ~consts ~modules = Naming_provider.remove_type_batch backend (typedefs @ classes); Naming_provider.remove_fun_batch backend funs; Naming_provider.remove_const_batch backend consts; Naming_provider.remove_module_batch backend modules let remove_decls_using_file_info backend file_info = let open FileInfo in remove_decls ~backend ~funs:(List.map ~f:id_name file_info.funs) ~classes:(List.map ~f:id_name file_info.classes) ~typedefs:(List.map ~f:id_name file_info.typedefs) ~consts:(List.map ~f:id_name file_info.consts) ~modules:(List.map ~f:id_name file_info.modules) (*****************************************************************************) (* The entry point to build the naming environment *) (*****************************************************************************) (** return true if no names were already bound; returns false if some were *) let make_env_and_check_not_already_bound ctx fileinfo = let is_okay = true in (* funs *) let (_, is_okay) = List.fold fileinfo.FileInfo.funs ~init:([], is_okay) ~f:(Env.new_fun_error_if_already_bound ctx fileinfo) in (* types *) let (current_file_symbols_acc, is_okay) = List.fold fileinfo.FileInfo.classes ~init:([], is_okay) ~f: (Env.new_type_error_if_already_bound ctx fileinfo ~kind:Naming_types.TClass) in let (_, is_okay) = List.fold fileinfo.FileInfo.typedefs ~init:(current_file_symbols_acc, is_okay) ~f: (Env.new_type_error_if_already_bound ctx fileinfo ~kind:Naming_types.TTypedef) in (* consts *) let (_, is_okay) = List.fold fileinfo.FileInfo.consts ~init:([], is_okay) ~f:(Env.new_global_const_error_if_already_bound ctx fileinfo) in (* modules *) let (_, is_okay) = List.fold fileinfo.FileInfo.modules ~init:([], is_okay) ~f:(Env.new_module_error_if_already_bound ctx fileinfo) in is_okay let make_env_skip_if_already_bound ctx fn fileinfo = List.iter fileinfo.FileInfo.funs ~f:(Env.new_fun_skip_if_already_bound ctx fn); List.iter fileinfo.FileInfo.classes ~f:(Env.new_type_skip_if_already_bound ctx fn ~kind:Naming_types.TClass); List.iter fileinfo.FileInfo.typedefs ~f:(Env.new_type_skip_if_already_bound ctx fn ~kind:Naming_types.TTypedef); List.iter fileinfo.FileInfo.consts ~f:(Env.new_global_const_skip_if_already_bound ctx fn); List.iter fileinfo.FileInfo.modules ~f:(Env.new_module_skip_if_already_bound ctx fn); () (*****************************************************************************) (* Declaring the names in a list of files *) (*****************************************************************************) let add_files_to_rename failed defl defs_in_env = List.fold_left ~f: begin fun failed (_, def, _) -> match defs_in_env def with | None -> failed | Some previous_definition_position -> let filename = Pos.filename previous_definition_position in Relative_path.Set.add failed filename end ~init:failed defl let ndecl_file_skip_if_already_bound ctx fn fileinfo = make_env_skip_if_already_bound ctx fn fileinfo let ndecl_file_and_get_conflict_files ctx fn fileinfo = Hh_logger.debug ~category "Naming decl: %s" (Relative_path.to_absolute fn); let is_okay = make_env_and_check_not_already_bound ctx fileinfo in if is_okay then Relative_path.Set.empty else (* IMPORTANT: * If a file has name collisions, we MUST add the list of files that * were previously defining the type to the set of "failed" files. * If we fail to do so, we will be in a phony state, where a name could * be missing. * * Example: * A.php defines class A * B.php defines class B * Save the state, now let's introduce a new file (foo.php): * foo.php defines class A and class B. * * 2 things happen (cf serverTypeCheck.ml): * We remove the names A and B from the global environment. * We report the error. * * But this is clearly not enough. If the user removes the file foo.php, * both class A and class B are now missing from the naming environment. * If the user has a file using class A (in strict), he now gets the * error "Unbound name class A". * * The solution consist in adding all the files that were previously * defining the same things as foo.php to the set of files to recheck. * * This way, when the user removes foo.php, A.php and B.php are recomputed * and the naming environment is in a sane state. * * XXX (jezng): we can probably be less conservative about this -- instead * of adding all the declarations in the file, why not just add those that * were actually duplicates? *) let type_canon_pos name = Naming_provider.get_type_canon_name ctx name |> Option.bind ~f:(GEnv.type_pos ctx) in let fun_canon_pos name = Naming_provider.get_fun_canon_name ctx name |> Option.bind ~f:(GEnv.fun_pos ctx) in let failed = Relative_path.Set.singleton fn in let failed = add_files_to_rename failed fileinfo.FileInfo.funs fun_canon_pos in let failed = add_files_to_rename failed fileinfo.FileInfo.classes type_canon_pos in let failed = add_files_to_rename failed fileinfo.FileInfo.typedefs type_canon_pos in let failed = add_files_to_rename failed fileinfo.FileInfo.consts (GEnv.gconst_pos ctx) in let failed = add_files_to_rename failed fileinfo.FileInfo.modules (GEnv.module_pos ctx) in failed
OCaml Interface
hhvm/hphp/hack/src/naming/naming_global.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. * *) (** GEnv is solely a set of thin wrappers around Naming_provider. *) module GEnv : sig val get_fun_full_pos : Provider_context.t -> FileInfo.pos * string -> Pos.t * string val get_type_full_pos : Provider_context.t -> FileInfo.pos * string -> Pos.t * string val get_const_full_pos : Provider_context.t -> FileInfo.pos * string -> Pos.t * string val type_pos : Provider_context.t -> string -> Pos.t option val type_info : Provider_context.t -> string -> (Pos.t * Naming_types.kind_of_type) option val fun_pos : Provider_context.t -> string -> Pos.t option val typedef_pos : Provider_context.t -> string -> Pos.t option val gconst_pos : Provider_context.t -> string -> Pos.t option end (* Removing declarations *) val remove_decls : backend:Provider_backend.t -> funs:string list -> classes:string list -> typedefs:string list -> consts:string list -> modules:string list -> unit (* Same as remove_decls but extracts definition identifiers from the file_info *) val remove_decls_using_file_info : Provider_backend.t -> FileInfo.t -> unit (** This function "declares" top-level names, i.e. adds them into the naming-table provider (which is a wrapper for the reverse naming table). As for duplicate name definitions, they are a joint responsibility between the reverse-naming-table and [env.failed_naming]; this function is responsible for maintaining the invariant... - The invariant is that if there are duplicate names, then [env.failed_naming] contains all filenames that declare those duplicate names (both winners and losers). - If any symbol from the FileInfo.t is already defined in a different file (with or without the same case), that other file is deemed to have the "winner" definition of the symbol; this function leaves the reverse-naming-table for the conflicting name as it is, and also returns the winner's filename plus this filename. - If any symbol from the FileInfo.t is defined twice within the FileInfo.t (with or without the same case), then the first occurrence is deemed to be the "winner" definition of the symbol; this function ends with the first occurrence in the reverse-naming-table, and returns this filename. - Actually, the way serverTypeCheck works is that whenever it is asked to do a typecheck, then it already first calls [Naming_global.remove_decls] on ALL [env.failed_naming] in addition to all modified files, and then calls this function [Naming_global.ndecl_file_and_get_conflict_files] on the same list of files. In this way, despite the precisely phrased bullet points above, the net effect of serverTypeCheck is that the winners end up being defined just by the order in which files get sent to this function, which is in fact [Relative_path.Map.fold], which ends up as an implementation detail being defined by [Relative_path.compare]. Returns: - This function returns a set of all "conflict files" discovered: if you call [ndecl_file_and_get_conflict_files ctx fn file_info], and no symbol in [file_info] conflicts with any existing entries in the reverse naming table, then it returns an empty set; but for all symbols that do conflict then it returns [fn] as well as the filename that defines the winner for that symbol. There are expectations of the caller: - This function doesn't touch the forward naming table; that's left to the caller. - The caller is expected to ensure that all names from the specified file have already been removed from the naming-table provider prior to calling this function. - The caller is expected to provide "full" positions in its FileInfo.t. *) val ndecl_file_and_get_conflict_files : Provider_context.t -> Relative_path.t -> FileInfo.t -> Relative_path.Set.t (** This function "declares" top-level names, i.e. adds them into the naming-table provider. This caller is expected to ensure that there are no naming-collisons and no case-insensitive naming collisions. *) val ndecl_file_skip_if_already_bound : Provider_context.t -> Relative_path.t -> FileInfo.t -> unit
OCaml
hhvm/hphp/hack/src/naming/naming_guard_invalid.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) let on_expr_ expr_ ~ctx = match expr_ with | Aast.Invalid _ -> (ctx, Error expr_) | _ -> (ctx, Ok expr_) let pass = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass.{ id with on_ty_expr_ = Some on_expr_ }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_guard_invalid.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 pass : Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_heap.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude type blocked_entry = Blocked (** Gets an entry from shared memory, or falls back to SQLite if necessary. If data is returned by SQLite, we also cache it back to shared memory. @param map_result function that maps from the SQLite fallback value to the actual value type we want to cache and return. @param get_func function that retrieves a key from shared memory. @param check_block_func function that checks if a key is blocked from falling back to SQLite. @param fallback_get_func function to get a fallback value from SQLite. @param add_func function to cache a value back into shared memory. @param measure_name the name of the measure to use for tracking fallback stats. We write a 1.0 if the request could be resolved entirely from shared memory, and 0.0 if we had to go to SQLite. @param key the key to request. *) let get_and_cache ~(map_result : 'fallback_value -> 'value option) ~(get_func : 'key -> 'value option) ~(check_block_func : 'key -> blocked_entry option) ~(fallback_get_func_opt : ('key -> 'fallback_value option) option) ~(cache_func : 'key -> 'value -> unit) ~(key : 'key) : _ option = match (get_func key, fallback_get_func_opt) with | (Some v, _) -> Some v | (None, None) -> None | (None, Some fallback_get_func) -> (match check_block_func key with | Some Blocked -> None | None -> begin match fallback_get_func key with | Some res -> begin match map_result res with | Some pos -> cache_func key pos; Some pos | None -> None end | None -> None end) module type ReverseNamingTable = sig type pos module Position : SharedMem.Value with type t = pos module CanonName : SharedMem.Value with type t = string val add : string -> pos -> unit val get_pos : Naming_sqlite.db_path option -> string -> pos option val remove_batch : Naming_sqlite.db_path option -> string list -> unit val get_canon_name : Provider_context.t -> string -> string option val hash : string -> Typing_deps.Dep.t val canon_hash : string -> Typing_deps.Dep.t end (* The Types module records both class names and typedefs since they live in the * same namespace. That is, one cannot both define a class Foo and a typedef Foo * (or FOO or fOo, due to case insensitivity). *) module Types = struct type pos = FileInfo.pos * Naming_types.kind_of_type module Position = struct type t = pos let description = "Naming_TypePos" end module CanonName = struct type t = string let description = "Naming_TypeCanon" end module TypePosHeap = SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.NonEvictable)) (Typing_deps.DepHashKey) (Position) (struct let capacity = 1000 end) module TypeCanonHeap = SharedMem.Heap (SharedMem.ImmediateBackend (SharedMem.NonEvictable)) (Typing_deps.DepHashKey) (CanonName) module BlockedEntries = SharedMem.HeapWithLocalCache (SharedMem.ImmediateBackend (SharedMem.NonEvictable)) (Typing_deps.DepHashKey) (struct type t = blocked_entry let description = "Naming_TypeBlocked" end) (struct let capacity = 1000 end) let hash name = Typing_deps.Dep.Type name |> Typing_deps.Dep.make let canon_hash name = Typing_deps.Dep.Type (Naming_sqlite.to_canon_name_key name) |> Typing_deps.Dep.make let add id pos = TypePosHeap.write_around (hash id) pos; TypeCanonHeap.add (canon_hash id) id; () let get_pos db_path_opt id = let map_result (path, kind_of_type) = let name_type = Naming_types.type_kind_to_name_type kind_of_type in Some (FileInfo.File (name_type, path), kind_of_type) in let fallback_get_func_opt = Option.map db_path_opt ~f:(fun db_path hash -> match Naming_sqlite.get_path_by_64bit_dep db_path hash with | None -> None | Some (file, Naming_types.Type_kind type_kind) -> Some (file, type_kind) | Some (_, _) -> failwith "passed in Type dephash, but got non-type out") in get_and_cache ~map_result ~get_func:TypePosHeap.get ~check_block_func:BlockedEntries.get ~fallback_get_func_opt ~cache_func:TypePosHeap.write_around ~key:(hash id) let get_canon_name ctx id = let map_result (path, entry_type) = let path_str = Relative_path.S.to_string path in match entry_type with | Naming_types.TClass -> begin match Ast_provider.find_iclass_in_file ctx path id with | Some cls -> Some (snd cls.Aast.c_name) | None -> Hh_logger.log "Failed to get canonical name for %s in file %s" id path_str; None end | Naming_types.TTypedef -> begin match Ast_provider.find_itypedef_in_file ctx path id with | Some typedef -> Some (snd typedef.Aast.t_name) | None -> Hh_logger.log "Failed to get canonical name for %s in file %s" id path_str; None end in let db_path_opt = Db_path_provider.get_naming_db_path (Provider_context.get_backend ctx) in let fallback_get_func_opt = Option.map db_path_opt ~f:(fun db_path _canon_hash -> Naming_sqlite.get_itype_path_by_name db_path id) in get_and_cache ~map_result ~get_func:TypeCanonHeap.get ~check_block_func:BlockedEntries.get ~fallback_get_func_opt ~cache_func:TypeCanonHeap.add ~key:(canon_hash id) let remove_batch db_path_opt types = let hashes = types |> List.map ~f:hash in let canon_hashes = types |> List.map ~f:canon_hash in TypeCanonHeap.remove_batch (TypeCanonHeap.KeySet.of_list canon_hashes); TypePosHeap.remove_batch (TypePosHeap.KeySet.of_list hashes); match db_path_opt with | None -> () | Some _ -> List.iter hashes ~f:(fun hash -> BlockedEntries.add hash Blocked); List.iter canon_hashes ~f:(fun canon_hash -> BlockedEntries.add canon_hash Blocked); () end module Funs = struct type pos = FileInfo.pos module Position = struct type t = pos let description = "Naming_FunPos" end module CanonName = struct type t = string let description = "Naming_FunCanon" end module FunPosHeap = SharedMem.Heap (SharedMem.ImmediateBackend (SharedMem.NonEvictable)) (Typing_deps.DepHashKey) (Position) module FunCanonHeap = SharedMem.Heap (SharedMem.ImmediateBackend (SharedMem.NonEvictable)) (Typing_deps.DepHashKey) (CanonName) module BlockedEntries = SharedMem.Heap (SharedMem.ImmediateBackend (SharedMem.NonEvictable)) (Typing_deps.DepHashKey) (struct type t = blocked_entry let description = "Naming_FunBlocked" end) let hash name = Typing_deps.Dep.Fun name |> Typing_deps.Dep.make let canon_hash name = Typing_deps.Dep.Fun (Naming_sqlite.to_canon_name_key name) |> Typing_deps.Dep.make let add id pos = FunCanonHeap.add (canon_hash id) id; FunPosHeap.add (hash id) pos; () let get_pos db_path_opt (id : string) = let map_result path = Some (FileInfo.File (FileInfo.Fun, path)) in let fallback_get_func_opt = Option.map db_path_opt ~f:(fun db_path dep -> Naming_sqlite.get_path_by_64bit_dep db_path dep |> Option.map ~f:fst) in get_and_cache ~map_result ~get_func:FunPosHeap.get ~check_block_func:BlockedEntries.get ~fallback_get_func_opt ~cache_func:FunPosHeap.add ~key:(hash id) let get_canon_name ctx name = let map_result path = match Ast_provider.find_ifun_in_file ctx path name with | Some f -> Some (snd f.Aast.fd_name) | None -> let path_str = Relative_path.S.to_string path in Hh_logger.log "Failed to get canonical name for %s in file %s" name path_str; None in let db_path_opt = Db_path_provider.get_naming_db_path (Provider_context.get_backend ctx) in let fallback_get_func_opt = Option.map db_path_opt ~f:(fun db_path _canon_hash -> Naming_sqlite.get_ifun_path_by_name db_path name) in get_and_cache ~map_result ~get_func:FunCanonHeap.get ~check_block_func:BlockedEntries.get ~fallback_get_func_opt ~cache_func:FunCanonHeap.add ~key:(canon_hash name) let remove_batch db_path_opt funs = let hashes = funs |> List.map ~f:hash in let canon_hashes = funs |> List.map ~f:canon_hash in FunCanonHeap.remove_batch (FunCanonHeap.KeySet.of_list canon_hashes); FunPosHeap.remove_batch (FunPosHeap.KeySet.of_list hashes); match db_path_opt with | None -> () | Some _ -> List.iter hashes ~f:(fun hash -> BlockedEntries.add hash Blocked); List.iter canon_hashes ~f:(fun canon_hash -> BlockedEntries.add canon_hash Blocked); () end module Consts = struct type pos = FileInfo.pos module Position = struct type t = pos let description = "Naming_ConstPos" end (** This module isn't actually used. It's here only for uniformity with the other ReverseNamingTables. *) module CanonName = struct type t = string let description = "Naming_ConstCanon" end module ConstPosHeap = SharedMem.Heap (SharedMem.ImmediateBackend (SharedMem.NonEvictable)) (Typing_deps.DepHashKey) (Position) module BlockedEntries = SharedMem.Heap (SharedMem.ImmediateBackend (SharedMem.NonEvictable)) (Typing_deps.DepHashKey) (struct type t = blocked_entry let description = "Naming_ConstBlocked" end) let hash name = Typing_deps.Dep.GConst name |> Typing_deps.Dep.make let canon_hash name = Typing_deps.Dep.GConst (Naming_sqlite.to_canon_name_key name) |> Typing_deps.Dep.make let add id pos = ConstPosHeap.add (hash id) pos let get_pos db_path_opt id = let map_result path = Some (FileInfo.File (FileInfo.Const, path)) in let fallback_get_func_opt = Option.map db_path_opt ~f:(fun db_path hash -> Naming_sqlite.get_path_by_64bit_dep db_path hash |> Option.map ~f:fst) in get_and_cache ~map_result ~get_func:ConstPosHeap.get ~check_block_func:BlockedEntries.get ~fallback_get_func_opt ~cache_func:ConstPosHeap.add ~key:(hash id) (* This function isn't even used, because the only callers who wish to obtain canonical names are "class fOo isn't defined; did you mean Foo?" and "error class Foobar differs from class FooBar only in capitalization", and they don't do their checks for constants. Nevertheless, we maintain consistent behavior: get_canon_name only returns a name if that name is defined in the repository. *) let get_canon_name ctx name = let db_path_opt = Db_path_provider.get_naming_db_path (Provider_context.get_backend ctx) in match get_pos db_path_opt name with | Some _ -> Some name | None -> None let remove_batch db_path_opt consts = let hashes = consts |> List.map ~f:hash in ConstPosHeap.remove_batch (ConstPosHeap.KeySet.of_list hashes); match db_path_opt with | None -> () | Some _ -> List.iter hashes ~f:(fun hash -> BlockedEntries.add hash Blocked); () end module Modules = struct type pos = FileInfo.pos module Position = struct type t = pos let description = "Naming_ModulePos" end (** This module isn't actually used. It's here only for uniformity with the other ReverseNamingTables. *) module CanonName = struct type t = string let description = "Naming_ModuleCanon" end module ModulePosHeap = SharedMem.Heap (SharedMem.ImmediateBackend (SharedMem.NonEvictable)) (Typing_deps.DepHashKey) (Position) module BlockedEntries = SharedMem.Heap (SharedMem.ImmediateBackend (SharedMem.NonEvictable)) (Typing_deps.DepHashKey) (struct type t = blocked_entry let description = "Naming_ModuleBlocked" end) let hash name = Typing_deps.Dep.Module name |> Typing_deps.Dep.make let canon_hash name = Typing_deps.Dep.Module (Naming_sqlite.to_canon_name_key name) |> Typing_deps.Dep.make let add id pos = ModulePosHeap.add (hash id) pos let get_pos db_path_opt id = let map_result path = Some (FileInfo.File (FileInfo.Module, path)) in let fallback_get_func_opt = Option.map db_path_opt ~f:(fun db_path hash -> Naming_sqlite.get_path_by_64bit_dep db_path hash |> Option.map ~f:fst) in get_and_cache ~map_result ~get_func:ModulePosHeap.get ~check_block_func:BlockedEntries.get ~fallback_get_func_opt ~cache_func:ModulePosHeap.add ~key:(hash id) let get_canon_name ctx name = let db_path_opt = Db_path_provider.get_naming_db_path (Provider_context.get_backend ctx) in match get_pos db_path_opt name with | Some _ -> Some name | None -> None let remove_batch db_path_opt consts = let hashes = consts |> List.map ~f:hash in ModulePosHeap.remove_batch (ModulePosHeap.KeySet.of_list hashes); match db_path_opt with | None -> () | Some _ -> List.iter hashes ~f:(fun hash -> BlockedEntries.add hash Blocked); () end let get_filename_by_hash (db_path_opt : Naming_sqlite.db_path option) (hash : Typing_deps.Dep.t) : Relative_path.t option = (* This function embodies the complicated storage we have for names: 1. If the name's in TypePosHeap/FunPosHeap/ConstPosHeap, that reflects either that we've cached it from sqlite or we're storing an authoritative delta; 2. Otherwise, if it's in BlockedEntries, then the authoritative delta says that it was removed; 3. Otherwise, see what sqlite says. The complication is that there are three separate BlockedEntries heaps, one for each name_kind (Types/Funs/Consts), so we'll actually query sqlite first to discover the name_kind and only afterwards check the BlockedEntries heap. All this logic is complicated enought that we just won't bother writing our sqlite-reads into the TypePosHeap/FunPosHeap/ConstPosHeap caches, like the normal reads do. *) let pos = match Types.TypePosHeap.get hash with | Some (pos, _type_kind) -> Some pos | None -> (match Funs.FunPosHeap.get hash with | Some pos -> Some pos | None -> Consts.ConstPosHeap.get hash) in match (pos, db_path_opt) with | (Some pos, _) -> Some (FileInfo.get_pos_filename pos) | (None, None) -> None | (None, Some db_path) -> (match Naming_sqlite.get_path_by_64bit_dep db_path hash with | None -> None | Some (file, name_kind) -> let is_blocked = match name_kind with | Naming_types.Type_kind _ -> Types.BlockedEntries.get hash | Naming_types.Fun_kind -> Funs.BlockedEntries.get hash | Naming_types.Const_kind -> Consts.BlockedEntries.get hash | Naming_types.Module_kind -> Modules.BlockedEntries.get hash in (match is_blocked with | Some Blocked -> None | None -> Some file)) let get_filenames_by_hash (db_path_opt : Naming_sqlite.db_path option) (hashes : Typing_deps.DepSet.t) : Relative_path.Set.t = Typing_deps.DepSet.fold hashes ~init:Relative_path.Set.empty ~f:(fun hash files -> match get_filename_by_hash db_path_opt hash with | None -> files | Some file -> Relative_path.Set.add files file) let push_local_changes () = Types.TypePosHeap.LocalChanges.push_stack (); Types.TypeCanonHeap.LocalChanges.push_stack (); Types.BlockedEntries.LocalChanges.push_stack (); Funs.FunPosHeap.LocalChanges.push_stack (); Funs.FunCanonHeap.LocalChanges.push_stack (); Funs.BlockedEntries.LocalChanges.push_stack (); Consts.ConstPosHeap.LocalChanges.push_stack (); Consts.BlockedEntries.LocalChanges.push_stack (); Modules.ModulePosHeap.LocalChanges.push_stack (); Modules.BlockedEntries.LocalChanges.push_stack (); () let pop_local_changes () = Types.TypePosHeap.LocalChanges.pop_stack (); Types.TypeCanonHeap.LocalChanges.pop_stack (); Types.BlockedEntries.LocalChanges.pop_stack (); Funs.FunPosHeap.LocalChanges.pop_stack (); Funs.FunCanonHeap.LocalChanges.pop_stack (); Funs.BlockedEntries.LocalChanges.pop_stack (); Consts.ConstPosHeap.LocalChanges.pop_stack (); Consts.BlockedEntries.LocalChanges.pop_stack (); Modules.ModulePosHeap.LocalChanges.pop_stack (); Modules.BlockedEntries.LocalChanges.pop_stack (); ()
OCaml Interface
hhvm/hphp/hack/src/naming/naming_heap.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. * *) (** Naming_heap is an internal implementation detail of Naming_provider used for the shared-mem backend. Its job is to (1) store deltas to the reverse naming table in shared-mem, (2) cache in sharedmem the results of lookups in sqlite table. *) module type ReverseNamingTable = sig type pos module Position : SharedMem.Value with type t = pos module CanonName : SharedMem.Value with type t = string val add : string -> pos -> unit val get_pos : Naming_sqlite.db_path option -> string -> pos option val remove_batch : Naming_sqlite.db_path option -> string list -> unit val get_canon_name : Provider_context.t -> string -> string option val hash : string -> Typing_deps.Dep.t val canon_hash : string -> Typing_deps.Dep.t end module Types : sig module TypeCanonHeap : SharedMem.Heap with type key = Typing_deps.Dep.t module TypePosHeap : SharedMem.Heap with type key = Typing_deps.Dep.t include ReverseNamingTable with type pos = FileInfo.pos * Naming_types.kind_of_type end module Funs : sig module FunCanonHeap : SharedMem.Heap with type key = Typing_deps.Dep.t module FunPosHeap : SharedMem.Heap with type key = Typing_deps.Dep.t include ReverseNamingTable with type pos = FileInfo.pos end module Consts : sig module ConstPosHeap : SharedMem.Heap with type key = Typing_deps.Dep.t include ReverseNamingTable with type pos = FileInfo.pos end module Modules : sig module ModulePosHeap : SharedMem.Heap with type key = Typing_deps.Dep.t include ReverseNamingTable with type pos = FileInfo.pos end (** This function searches all three namespaces (types, funs, consts) to find which one contains each Dep.t. The earlier functions in this module only search one specified namespace. Note: this function doesn't use the sharedmem cache of names - doesn't benefit from it, doesn't write into it. *) val get_filenames_by_hash : Naming_sqlite.db_path option -> Typing_deps.DepSet.t -> Relative_path.Set.t val push_local_changes : unit -> unit val pop_local_changes : unit -> unit
OCaml
hhvm/hphp/hack/src/naming/naming_phase_env.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module Elab_happly_hint = struct type t = { tparams: SSet.t } let empty = { tparams = SSet.empty } end module Elab_func_body = struct type t = { in_mode: FileInfo.mode } let empty = { in_mode = FileInfo.Mstrict } end module Elab_haccess_hint = struct type t = { current_class: (Ast_defs.id * Ast_defs.classish_kind * bool) option; in_where_clause: bool; in_context: bool; in_haccess: bool; } let empty = { current_class = None; in_where_clause = false; in_context = false; in_haccess = false; } end module Elab_this_hint = struct type t = { (* `this` is forbidden as a hint in this context *) forbid_this: bool; lsb: bool option; in_interface: bool; in_req_extends: bool; in_extends: bool; is_top_level_haccess_root: bool; in_invariant_final: bool; } let empty = { forbid_this = false; lsb = None; in_interface = false; in_req_extends = false; in_extends = false; is_top_level_haccess_root = false; in_invariant_final = false; } end module Elab_call = struct type t = { current_class: (Ast_defs.id * Ast_defs.classish_kind * bool) option; } let empty = { current_class = None } end module Elab_class_id = struct type t = { in_class: bool } let empty = { in_class = false } end module Elab_const_expr = struct type t = { enforce_const_expr: bool; in_enum_class: bool; in_mode: FileInfo.mode; } let empty = { enforce_const_expr = false; in_enum_class = false; in_mode = FileInfo.Mstrict; } end module Elab_everything_sdt = struct type t = { in_is_as: bool; in_enum_class: bool; under_no_auto_dynamic: bool; under_no_auto_likes: bool; } let empty = { in_is_as = false; in_enum_class = false; under_no_auto_dynamic = false; under_no_auto_likes = false; } end module Elab_wildcard_hint = struct type t = { allow_wildcard: bool; tp_depth: int; } let empty = { allow_wildcard = false; tp_depth = 0 } end module Elab_shape_field_name = struct type t = { current_class: (Ast_defs.id * Ast_defs.classish_kind * bool) option; } let empty = { current_class = None } end module Elab_retonly_hint = struct type t = { allow_retonly: bool } let empty = { allow_retonly = false } end type t = { elab_happly_hint: Elab_happly_hint.t; elab_haccess_hint: Elab_haccess_hint.t; elab_class_id: Elab_class_id.t; elab_this_hint: Elab_this_hint.t; elab_call: Elab_call.t; elab_const_expr: Elab_const_expr.t; elab_everything_sdt: Elab_everything_sdt.t; elab_func_body: Elab_func_body.t; elab_retonly_hint: Elab_retonly_hint.t; elab_wildcard_hint: Elab_wildcard_hint.t; elab_shape_field_name: Elab_shape_field_name.t; everything_sdt: bool; soft_as_like: bool; consistent_ctor_level: int; hkt_enabled: bool; like_type_hints_enabled: bool; supportdynamic_type_hint_enabled: bool; is_systemlib: bool; is_hhi: bool; allow_module_def: bool; } let empty = { elab_happly_hint = Elab_happly_hint.empty; elab_haccess_hint = Elab_haccess_hint.empty; elab_class_id = Elab_class_id.empty; elab_this_hint = Elab_this_hint.empty; elab_call = Elab_call.empty; elab_const_expr = Elab_const_expr.empty; elab_everything_sdt = Elab_everything_sdt.empty; elab_func_body = Elab_func_body.empty; elab_retonly_hint = Elab_retonly_hint.empty; elab_wildcard_hint = Elab_wildcard_hint.empty; elab_shape_field_name = Elab_shape_field_name.empty; everything_sdt = false; soft_as_like = false; consistent_ctor_level = 0; hkt_enabled = false; like_type_hints_enabled = false; supportdynamic_type_hint_enabled = false; is_systemlib = false; is_hhi = false; allow_module_def = false; }
OCaml
hhvm/hphp/hack/src/naming/naming_phase_error.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude exception UnexpectedExpr of Pos.t type experimental_feature = | Like_type of Pos.t | Supportdyn of Pos.t (* We use these constructors in Rust elaboration *) | Const_attr of Pos.t [@warning "-37"] | Const_static_prop of Pos.t [@warning "-37"] | IFC_infer_flows of Pos.t [@warning "-37"] [@@ocaml.warning "-37"] type t = | Naming of Naming_error.t | Nast_check of Nast_check_error.t | Unexpected_hint of Pos.t | Malformed_access of Pos.t | Experimental_feature of experimental_feature (* We use this constructor (or at least the [Xhp_parsing_error] ctor) in Rust elaboration *) | Parsing of Parsing_error.t [@warning "-37"] [@@ocaml.warning "-37"] let naming err = Naming err let parsing err = Parsing err let nast_check err = Nast_check err let like_type pos = Experimental_feature (Like_type pos) let unexpected_hint pos = Unexpected_hint pos let malformed_access pos = Malformed_access pos let supportdyn pos = Experimental_feature (Supportdyn pos) type agg = { naming: Naming_error.t list; (* TODO[mjt] either these errors shouldn't be raised in naming or they aren't really typing errors *) (* TODO[mjt] as above, either these should be naming errors or we should be raising in NAST checks *) nast_check: Nast_check_error.t list; (* TODO[mjt] these errors are not represented by any of our conventional phase errors; presumably they should all be naming errors? *) unexpected_hints: Pos.t list; malformed_accesses: Pos.t list; experimental_features: experimental_feature list; parsing: Parsing_error.t list; } let empty = { naming = []; nast_check = []; unexpected_hints = []; malformed_accesses = []; experimental_features = []; parsing = []; } let add t = function | Naming err -> { t with naming = err :: t.naming } | Nast_check err -> { t with nast_check = err :: t.nast_check } | Unexpected_hint err -> { t with unexpected_hints = err :: t.unexpected_hints } | Malformed_access err -> { t with malformed_accesses = err :: t.malformed_accesses } | Experimental_feature err -> { t with experimental_features = err :: t.experimental_features } | Parsing err -> { t with parsing = err :: t.parsing } let emit_experimental_feature = function | Like_type pos -> Errors.experimental_feature pos "like-types" | Supportdyn pos -> Errors.experimental_feature pos "supportdyn type hint" | Const_attr pos -> Errors.experimental_feature pos "The __Const attribute is not supported." | Const_static_prop pos -> Errors.experimental_feature pos "Const properties cannot be static." | IFC_infer_flows pos -> Errors.experimental_feature pos "IFC InferFlows" let emit { naming; nast_check; unexpected_hints; malformed_accesses; experimental_features; parsing; } = List.iter ~f:(fun err -> Errors.add_error @@ Naming_error.to_user_error err) naming; List.iter ~f:(fun err -> Errors.add_error @@ Nast_check_error.to_user_error err) nast_check; List.iter ~f:(fun pos -> Errors.internal_error pos "Unexpected hint not present on legacy AST") unexpected_hints; List.iter ~f:(fun pos -> Errors.internal_error pos "Malformed hint: expected Haccess (Happly ...) from ast_to_nast") malformed_accesses; List.iter ~f:emit_experimental_feature experimental_features; List.iter ~f:(fun err -> Errors.add_error @@ Parsing_error.to_user_error err) parsing (* Helper for constructing expression to be substituted for invalid expressions TODO[mjt] this probably belongs with the AAST defs *) let invalid_expr_ expr_opt = Aast.Invalid expr_opt let invalid_expr ((annot, pos, _) as expr) = (annot, pos, Aast.Invalid (Some expr))
OCaml Interface
hhvm/hphp/hack/src/naming/naming_phase_error.mli
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type t type agg exception UnexpectedExpr of Pos.t val naming : Naming_error.t -> t val parsing : Parsing_error.t -> t val nast_check : Nast_check_error.t -> t val like_type : Pos.t -> t val unexpected_hint : Pos.t -> t val malformed_access : Pos.t -> t val supportdyn : Pos.t -> t val invalid_expr_ : ('ex, 'en) Aast.expr option -> ('ex, 'en) Aast.expr_ val invalid_expr : ('ex, 'en) Aast.expr -> ('ex, 'en) Aast.expr val add : agg -> t -> agg val emit : agg -> unit val empty : agg
OCaml
hhvm/hphp/hack/src/naming/naming_phase_pass.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 Common type 'ctx t = | Top_down of 'ctx Aast_defs.Pass.t | Bottom_up of 'ctx Aast_defs.Pass.t let combine ts = let id = Aast_defs.Pass.identity () in List.fold_left ts ~init:(id, id) ~f:(fun (td_acc, bu_acc) t -> match t with | Top_down td -> (Aast_defs.Pass.combine td_acc td, bu_acc) | Bottom_up bu -> (td_acc, Aast_defs.Pass.combine bu_acc bu)) let top_down pass = Top_down pass let bottom_up pass = Bottom_up pass let mk_visitor passes = let (top_down, bottom_up) = combine passes in Aast_defs. ( (fun ctx elem -> transform_ty_program elem ~ctx ~top_down ~bottom_up), (fun ctx elem -> transform_ty_class_ elem ~ctx ~top_down ~bottom_up), (fun ctx elem -> transform_ty_fun_def elem ~ctx ~top_down ~bottom_up), (fun ctx elem -> transform_ty_module_def elem ~ctx ~top_down ~bottom_up), (fun ctx elem -> transform_ty_gconst elem ~ctx ~top_down ~bottom_up), (fun ctx elem -> transform_ty_typedef elem ~ctx ~top_down ~bottom_up) )
OCaml Interface
hhvm/hphp/hack/src/naming/naming_phase_pass.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. * *) open Aast type 'ctx t val top_down : 'ctx Aast_defs.Pass.t -> 'ctx t val bottom_up : 'ctx Aast_defs.Pass.t -> 'ctx t val mk_visitor : 'ctx t list -> ('ctx -> (unit, unit) program -> (unit, unit) program) * ('ctx -> (unit, unit) class_ -> (unit, unit) class_) * ('ctx -> (unit, unit) fun_def -> (unit, unit) fun_def) * ('ctx -> (unit, unit) module_def -> (unit, unit) module_def) * ('ctx -> (unit, unit) gconst -> (unit, unit) gconst) * ('ctx -> (unit, unit) typedef -> (unit, unit) typedef)
OCaml
hhvm/hphp/hack/src/naming/naming_special_names.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude (** Module consisting of the special names known to the typechecker *) module Classes = struct let cParent = "parent" let cStatic = "static" let cSelf = "self" let cUnknown = "\\*Unknown*" (* Used for dynamic classnames, e.g. new $foo(); *) let cAwaitable = "\\HH\\Awaitable" let cGenerator = "\\Generator" let cAsyncGenerator = "\\HH\\AsyncGenerator" let cHHFormatString = "\\HH\\FormatString" let is_format_string x = String.equal x cHHFormatString let cHH_BuiltinEnum = "\\HH\\BuiltinEnum" let cHH_BuiltinEnumClass = "\\HH\\BuiltinEnumClass" let cHH_BuiltinAbstractEnumClass = "\\HH\\BuiltinAbstractEnumClass" let cThrowable = "\\Throwable" let cStdClass = "\\stdClass" let cDateTime = "\\DateTime" let cDateTimeImmutable = "\\DateTimeImmutable" let cAsyncIterator = "\\HH\\AsyncIterator" let cAsyncKeyedIterator = "\\HH\\AsyncKeyedIterator" let cStringish = "\\Stringish" let cStringishObject = "\\StringishObject" let cXHPChild = "\\XHPChild" let cIMemoizeParam = "\\HH\\IMemoizeParam" let cUNSAFESingletonMemoizeParam = "\\HH\\UNSAFESingletonMemoizeParam" let cClassname = "\\HH\\classname" let cTypename = "\\HH\\typename" let cIDisposable = "\\IDisposable" let cIAsyncDisposable = "\\IAsyncDisposable" let cMemberOf = "\\HH\\MemberOf" let cEnumClassLabel = "\\HH\\EnumClass\\Label" (* Classes that can be spliced into ExpressionTrees *) let cSpliceable = "\\Spliceable" let cSupportDyn = "\\HH\\supportdyn" end module Collections = struct (* concrete classes *) let cVector = "\\HH\\Vector" let cMutableVector = "\\MutableVector" let cImmVector = "\\HH\\ImmVector" let cSet = "\\HH\\Set" let cConstSet = "\\ConstSet" let cMutableSet = "\\MutableSet" let cImmSet = "\\HH\\ImmSet" let cMap = "\\HH\\Map" let cMutableMap = "\\MutableMap" let cImmMap = "\\HH\\ImmMap" let cPair = "\\HH\\Pair" (* interfaces *) let cContainer = "\\HH\\Container" let cKeyedContainer = "\\HH\\KeyedContainer" let cTraversable = "\\HH\\Traversable" let cKeyedTraversable = "\\HH\\KeyedTraversable" let cCollection = "\\Collection" let cConstVector = "\\ConstVector" let cConstMap = "\\ConstMap" let cConstCollection = "\\ConstCollection" let cAnyArray = "\\HH\\AnyArray" let cDict = "\\HH\\dict" let cVec = "\\HH\\vec" let cKeyset = "\\HH\\keyset" end module Members = struct let mGetInstanceKey = "getInstanceKey" let mClass = "class" let __construct = "__construct" let __destruct = "__destruct" let __call = "__call" let __callStatic = "__callStatic" let __clone = "__clone" let __debugInfo = "__debugInfo" let __dispose = "__dispose" let __disposeAsync = "__disposeAsync" let __get = "__get" let __invoke = "__invoke" let __isset = "__isset" let __set = "__set" let __set_state = "__set_state" let __sleep = "__sleep" let __toString = "__toString" let __unset = "__unset" let __wakeup = "__wakeup" let as_set = List.fold_right ~f:SSet.add ~init:SSet.empty [ __construct; __destruct; __call; __callStatic; __clone; __debugInfo; __dispose; __disposeAsync; __get; __invoke; __isset; __set; __set_state; __sleep; __toString; __unset; __wakeup; ] let as_lowercase_set = SSet.map String.lowercase as_set (* Any data- or aria- attribute is always valid, even if it is not declared * for a given XHP element *) let is_special_xhp_attribute s = String.is_prefix s ~prefix:":data-" || String.is_prefix s ~prefix:":aria-" end module AttributeKinds = struct let cls = "\\HH\\ClassAttribute" let clscst = "\\HH\\ClassConstantAttribute" let enum = "\\HH\\EnumAttribute" let typealias = "\\HH\\TypeAliasAttribute" let fn = "\\HH\\FunctionAttribute" let mthd = "\\HH\\MethodAttribute" let instProperty = "\\HH\\InstancePropertyAttribute" let staticProperty = "\\HH\\StaticPropertyAttribute" let parameter = "\\HH\\ParameterAttribute" let typeparam = "\\HH\\TypeParameterAttribute" let file = "\\HH\\FileAttribute" let typeconst = "\\HH\\TypeConstantAttribute" let lambda = "\\HH\\LambdaAttribute" let enumcls = "\\HH\\EnumClassAttribute" let module_ = "\\HH\\ModuleAttribute" let plain_english_map = List.fold_left ~init:SMap.empty ~f:(fun acc (k, v) -> SMap.add k v acc) [ (cls, "a class"); (clscst, "a constant of a class"); (enum, "an enum"); (typealias, "a typealias"); (fn, "a function"); (mthd, "a method"); (instProperty, "an instance property"); (staticProperty, "a static property"); (parameter, "a parameter"); (typeparam, "a type parameter"); (file, "a file"); (typeconst, "a type constant"); (lambda, "a lambda expression"); (enumcls, "an enum class"); (module_, "a module"); ] end module UserAttributes = struct let uaOverride = "__Override" let uaConsistentConstruct = "__ConsistentConstruct" let uaConst = "__Const" let uaDeprecated = "__Deprecated" let uaDocs = "__Docs" let uaEntryPoint = "__EntryPoint" let uaMemoize = "__Memoize" let uaMemoizeLSB = "__MemoizeLSB" let uaPHPStdLib = "__PHPStdLib" let uaAcceptDisposable = "__AcceptDisposable" let uaReturnDisposable = "__ReturnDisposable" let uaLSB = "__LSB" let uaSealed = "__Sealed" let uaLateInit = "__LateInit" let uaNewable = "__Newable" let uaEnforceable = "__Enforceable" let uaExplicit = "__Explicit" let uaNonDisjoint = "__NonDisjoint" let uaSoft = "__Soft" let uaWarn = "__Warn" let uaMockClass = "__MockClass" let uaProvenanceSkipFrame = "__ProvenanceSkipFrame" let uaDynamicallyCallable = "__DynamicallyCallable" let uaDynamicallyConstructible = "__DynamicallyConstructible" let uaReifiable = "__Reifiable" let uaNeverInline = "__NEVER_INLINE" let uaDisableTypecheckerInternal = "__DisableTypecheckerInternal" let uaHasTopLevelCode = "__HasTopLevelCode" let uaIsFoldable = "__IsFoldable" let uaNative = "__Native" let uaNativeData = "__NativeData" let uaEagerVMSync = "__EagerVMSync" let uaOutOnly = "__OutOnly" let uaAlwaysInline = "__ALWAYS_INLINE" let uaEnableUnstableFeatures = "__EnableUnstableFeatures" let uaEnumClass = "__EnumClass" let uaPolicied = "__Policied" let uaInferFlows = "__InferFlows" let uaExternal = "__External" let uaCanCall = "__CanCall" let uaSupportDynamicType = "__SupportDynamicType" let uaNoAutoDynamic = "__NoAutoDynamic" let uaNoAutoLikes = "__NoAutoLikes" let uaNoAutoBound = "__NoAutoBound" let uaRequireDynamic = "__RequireDynamic" let uaEnableMethodTraitDiamond = "__EnableMethodTraitDiamond" let uaIgnoreReadonlyLocalErrors = "__IgnoreReadonlyLocalErrors" let uaIgnoreCoeffectLocalErrors = "__IgnoreCoeffectLocalErrors" let uaReified = "__Reified" let uaHasReifiedParent = "__HasReifiedParent" let uaSoftInternal = "__SoftInternal" let uaNoFlatten = "__NoFlatten" let uaCrossPackage = "__CrossPackage" (* <<__SafeForGlobalAccessCheck>> marks global variables as safe from mutations. This attribute merely ensures that the global_access_check does NOT raise errors/warnings from writing to the annotated global variable, and it has NO runtime/semantic implication. *) let uaSafeGlobalVariable = "__SafeForGlobalAccessCheck" let uaModuleLevelTrait = "__ModuleLevelTrait" type attr_info = { contexts: string list; doc: string; autocomplete: bool; } let as_map : attr_info SMap.t = AttributeKinds.( SMap.of_list [ ( uaOverride, { contexts = [mthd]; autocomplete = true; doc = "Ensures there's a parent method being overridden."; } ); ( uaConsistentConstruct, { contexts = [cls]; autocomplete = true; doc = "Requires all child classes to have the same constructor signature. " ^ " This allows `new static(...)` and `new $the_class_name(...)`."; } ); ( uaConst, { contexts = [cls; instProperty; parameter; staticProperty]; autocomplete = false; doc = "Marks a class or property as immutable." ^ " When applied to a class, all the properties are considered `__Const`." ^ " `__Const` properties can only be set in the constructor."; } ); ( uaDeprecated, { contexts = [fn; mthd]; autocomplete = true; doc = "Mark a function/method as deprecated. " ^ " The type checker will show an error at call sites, and a runtime notice is raised if this function/method is called." ^ "\n\nThe optional second argument specifies a sampling rate for raising notices at runtime." ^ " If the sampling rate is 100, a notice is only raised every 1/100 calls. If omitted, the default sampling rate is 1 (i.e. all calls raise notices)." ^ " To disable runtime notices, use a sampling rate of 0."; } ); ( uaDocs, { contexts = [cls; enum; enumcls; typealias]; autocomplete = true; doc = "Shows the linked URL when hovering over this type."; } ); ( uaEntryPoint, { contexts = [fn]; autocomplete = true; doc = "Execution of the program will start here." ^ Printf.sprintf " This only applies in the first file executed, `%s` in required or autoloaded files has no effect." uaEntryPoint; } ); ( uaMemoize, { contexts = [fn; mthd]; autocomplete = true; doc = "Cache the return values from this function/method." ^ " Calls with the same arguments will return the cached value." ^ "\n\nCaching is per-request and shared between subclasses (see also `__MemoizeLSB`)."; } ); ( uaMemoizeLSB, { contexts = [mthd]; autocomplete = true; doc = "Cache the return values from this method." ^ " Calls with the same arguments will return the cached value." ^ "\n\nCaching is per-request and has Late Static Binding, so subclasses do not share the cache."; } ); ( uaPHPStdLib, { contexts = [cls; fn; mthd]; autocomplete = false; doc = "Ignore this built-in function or class, so the type checker errors if code uses it." ^ " This only applies to code in .hhi files by default, but can apply everywhere with `deregister_php_stdlib`."; } ); ( uaAcceptDisposable, { contexts = [parameter]; autocomplete = true; doc = "Allows passing values that implement `IDisposable` or `IAsyncDisposable`." ^ " Normally these values cannot be passed to functions." ^ "\n\nYou cannot save references to `__AcceptDisposable` parameters, to ensure they are disposed at the end of their using block."; } ); ( uaReturnDisposable, { contexts = [fn; mthd; lambda]; autocomplete = true; doc = "Allows a function/method to return a value that implements `IDisposable` or `IAsyncDisposable`." ^ " The function must return a fresh disposable value by either instantiating a class or " ^ " returning a value from another method/function marked `__ReturnDisposable`."; } ); ( uaLSB, { contexts = [staticProperty]; autocomplete = true; doc = "Marks this property as implicitly redeclared on all subclasses." ^ " This ensures each subclass has its own value for the property."; } ); ( uaSealed, { contexts = [cls; enumcls; enum]; autocomplete = true; doc = "Only the named classes can extend this class or interface." ^ " Child classes may still be extended unless they are marked `final`."; } ); ( uaLateInit, { contexts = [instProperty; staticProperty]; autocomplete = true; doc = "Marks a property as late initialized." ^ " Normally properties are required to be initialized in the constructor."; } ); ( uaNewable, { contexts = [typeparam]; autocomplete = true; doc = "Ensures the class can be constructed." ^ "\n\nThis forbids abstract classes, and ensures that the constructor has a consistent signature." ^ " Classes must use `__ConsistentConstruct` or be final."; } ); ( uaEnforceable, { contexts = [typeconst; typeparam]; autocomplete = true; doc = "Ensures that this type is enforceable." ^ " Enforceable types can be used with `is` and `as`." ^ " This forbids usage of function types and erased (not reified) generics."; } ); ( uaExplicit, { contexts = [typeparam]; autocomplete = true; doc = "Requires callers to explicitly specify this type." ^ "\n\nNormally Hack allows generics to be inferred at the call site."; } ); ( uaSoft, { contexts = [instProperty; parameter; staticProperty; typeparam]; autocomplete = true; doc = "A runtime type mismatch on this parameter/property will not throw a TypeError/Error." ^ " This is useful for migrating partial code where you're unsure about the type." ^ "\n\nThe type checker will ignore this attribute, so your code will still get type checked." ^ " If the type is wrong at runtime, a warning will be logged and code execution will continue."; } ); ( uaWarn, { contexts = [typeparam]; autocomplete = true; doc = "Ensures that incorrect reified types are a warning rather than error." ^ "\n\nThis is intended to help gradually migrate code to reified types."; } ); ( uaMockClass, { contexts = [cls]; autocomplete = false; doc = "Allows subclasses of final classes and overriding of final methods." ^ " This is useful for writing mock classes." ^ "\n\nYou cannot use this to subclass `vec`, `keyset`, `dict`, `Vector`, `Map` or `Set`."; } ); ( uaProvenanceSkipFrame, { contexts = [fn; mthd; lambda]; autocomplete = false; doc = "Don't track Hack arrays created by this function." ^ " This is useful when migrating code from PHP arrays to Hack arrays."; } ); ( uaDynamicallyCallable, { contexts = [fn; mthd]; autocomplete = true; doc = "Allows this function/method to be called dynamically, based on a string of its name. " ^ " HHVM will warn or error (depending on settings) on dynamic calls to functions without this attribute." ^ "\n\nSee also `HH\\dynamic_fun()` and `HH\\dynamic_class_meth()`."; } ); ( uaDynamicallyConstructible, { contexts = [cls]; autocomplete = true; doc = "Allows this class to be instantiated dynamically, based on a string of its name." ^ " HHVM will warn or error (depending on settings) on dynamic instantiations without this attribute."; } ); ( uaReifiable, { contexts = [typeconst]; autocomplete = true; doc = "Requires this type to be reifiable." ^ " This bans PHP arrays (varray and darray)."; } ); ( uaNeverInline, { contexts = [fn; mthd]; autocomplete = false; doc = "Instructs HHVM to never inline this function." ^ " Only used for testing HHVM." ^ "\n\nSee also `__ALWAYS_INLINE`."; } ); ( uaReified, { contexts = []; autocomplete = false; doc = "Marks a function as taking reified generics." ^ " This is an internal attribute used for byte compilation, and is banned in user code."; } ); ( uaHasReifiedParent, { contexts = []; autocomplete = false; doc = "Marks a class as extending a class that uses reified generics." ^ " This is an internal attribute used for byte compilation, and is banned in user code."; } ); ( uaNoFlatten, { contexts = []; autocomplete = false; doc = "Instructs hhbbc to never inline this trait into classes that use it." ^ " Used for testing hhbbc optimizations."; } ); ( uaNativeData, { contexts = [cls]; autocomplete = false; doc = "Associates this class with a native data type (usually a C++ class)." ^ " When instantiating this class, the corresponding native object will also be allocated."; } ); ( uaNonDisjoint, { contexts = [typeparam]; autocomplete = true; doc = "Requires this type parameter to have some overlap with the other `<<__NonDisjoint>>` type parameters." ^ "\n\nThis prevents Hack inferring completely unrelated types." ^ " For example, this allows the typechecker to warn on `C\\contains(vec[1], \"foo\")`."; } ); ( uaDisableTypecheckerInternal, { contexts = [fn; mthd]; autocomplete = false; doc = "Disables type checking of a function body or method. This is only useful for debugging typechecker performance." ^ " The typechecker will discard the body and immediately report an internal error."; } ); ( uaEnableUnstableFeatures, { contexts = [file]; autocomplete = true; doc = "Enables unstable or preview features of Hack." ^ "\n\nUnstable features can only run when HHVM has `Hack.Lang.AllowUnstableFeatures` set. This allows local experimentation without using the feature in production." ^ "\n\nWhen a feature enters preview, `__EnableUnstableFeatures` is still required but HHVM will allow the code to run."; } ); ( uaEnumClass, { contexts = [cls; enumcls]; autocomplete = false; doc = "Allows initializing class constants with class instances (not just constant expressions). Used when desugaring `enum class`."; } ); ( uaPolicied, { contexts = [fn; mthd; instProperty; parameter]; autocomplete = false; doc = "Associate a definition with a policy. Used for information flow control, requires `<<file:__EnableUnstableFeatures('ifc')>>`."; } ); ( uaInferFlows, { contexts = [fn; mthd]; autocomplete = false; doc = "Used for IFC, requires `<<file:__EnableUnstableFeatures('ifc')>>`."; } ); ( uaExternal, { contexts = [parameter]; autocomplete = false; doc = "Used for IFC, requires `<<file:__EnableUnstableFeatures('ifc')>>`."; } ); ( uaCanCall, { contexts = [parameter]; autocomplete = false; doc = "Used for IFC, requires `<<file:__EnableUnstableFeatures('ifc')>>`."; } ); ( uaSupportDynamicType, { contexts = [fn; cls; mthd; lambda; enumcls]; autocomplete = false; doc = "Marks methods and functions that can be called on a receiver of type `dynamic` with `dynamic` arguments. Requires the enable_sound_dynamic_type typechecking flag."; } ); ( uaNoAutoDynamic, { contexts = [fn; cls; mthd; typealias]; autocomplete = false; doc = "Locally disable implicit pessimisation."; } ); ( uaNoAutoLikes, { contexts = [fn; mthd; staticProperty; instProperty; parameter; lambda]; autocomplete = false; doc = "Locally disable addition of ~ types."; } ); ( uaNoAutoBound, { contexts = [typeparam]; autocomplete = false; doc = "Locally disable addition of supportdyn<mixed> bound."; } ); ( uaRequireDynamic, { contexts = [typeparam]; autocomplete = false; doc = "Marks this type parameter as required to be `dynamic`. Requires the enable_sound_dynamic_type typechecking flag."; } ); ( uaEnableMethodTraitDiamond, { contexts = [cls]; autocomplete = true; doc = "Allows a trait to be `use`d more than once. " ^ "This is useful in large class hierarchies, where you can end up using the same trait on via multiple paths, producing 'diamond inheritance'." ^ "\n\nThis requires methods to unambiguous: each method definition must occur in exactly one trait."; } ); ( uaSafeGlobalVariable, { contexts = [staticProperty]; autocomplete = false; doc = "Marks this global variable as safe from mutation." ^ " This ensures the global_access_check does NOT raise errors/warnings from writing to this global variable."; } ); ( uaModuleLevelTrait, { contexts = [cls]; autocomplete = false; doc = "Consider the trait to belong to the module where it is defined, " ^ "rather than to the module of the class that uses it."; } ); ( uaSoftInternal, { (* Parameters are for constructor promotion: if someone tries to use it on a parameter without internal, they'll encounter a nast check error *) contexts = [ fn; cls; mthd; instProperty; staticProperty; parameter; enum; enumcls; ]; autocomplete = false; doc = "Instead of throwing an exception upon a module boundary violation at this symbol, logs a warning instead."; } ); ( uaCrossPackage, { contexts = [fn; mthd]; autocomplete = true; doc = "Enables access to elements from other package(s), requires `<<file:__EnableUnstableFeatures('package')>>`"; } ); ]) (* These are names which are allowed in the systemlib but not in normal programs *) let systemlib_map = AttributeKinds.( SMap.of_list [ ( uaAlwaysInline, { contexts = [fn; mthd]; autocomplete = false; doc = "Instructs HHVM to always inline this function." ^ " Only used for testing HHVM." ^ "\n\nSee also `__NEVER_INLINE`."; } ); ( uaIsFoldable, { contexts = [fn; mthd]; autocomplete = false; doc = "Marks that this function can be constant-folded if all arguments are constants." ^ " Used by hhbbc."; } ); ( uaNative, { contexts = [fn; mthd]; autocomplete = false; doc = "Declares a native function." ^ " This declares the signature, the implementation will be in an HHVM extension (usually C++)."; } ); ( uaEagerVMSync, { contexts = [fn; mthd]; autocomplete = false; doc = "Declares that runtime will eagerly sync vm registers for this function."; } ); ( uaOutOnly, { contexts = [parameter]; autocomplete = false; doc = "Declares that an `inout` parameter is written but never read."; } ); ( uaIgnoreReadonlyLocalErrors, { contexts = [fn; mthd]; autocomplete = false; doc = "Disables `readonly` compiler checks (systemlib only)."; } ); ( uaIgnoreCoeffectLocalErrors, { contexts = [fn; mthd]; autocomplete = false; doc = "Disables context/capability runtime checks (systemlib only)."; } ); ]) let is_reserved name = String.is_prefix name ~prefix:"__" end (* Tested before \\-prepending name-canonicalization *) module SpecialFunctions = struct let echo = "echo" (* pseudo-function *) let is_special_function = let all_special_functions = HashSet.of_list [echo] in (fun x -> HashSet.mem all_special_functions x) end (* There are a number of functions that are automatically imported into the * namespace. The full list can be found in hh_autoimport.ml. *) module AutoimportedFunctions = struct let invariant_violation = "\\HH\\invariant_violation" let invariant = "\\HH\\invariant" let meth_caller = "\\HH\\meth_caller" end module SpecialIdents = struct let this = "$this" let placeholder = "$_" let dollardollar = "$$" (* Intentionally using an invalid variable name to ensure it's translated *) let tmp_var_prefix = "__tmp$" let is_tmp_var name = String.length name > 6 && String.(sub name ~pos:0 ~len:6 = tmp_var_prefix) let assert_tmp_var name = assert (is_tmp_var name) end (* PseudoFunctions are functions (or items that are parsed like functions) * that are treated like builtins that do not have a public HHI or interface. *) module PseudoFunctions = struct let isset = "\\isset" let unset = "\\unset" let hh_show = "\\hh_show" let hh_expect = "\\hh_expect" let hh_expect_equivalent = "\\hh_expect_equivalent" let hh_show_env = "\\hh_show_env" let hh_log_level = "\\hh_log_level" let hh_force_solve = "\\hh_force_solve" let hh_loop_forever = "\\hh_loop_forever" let hh_time = "\\hh_time" let echo = "\\echo" let empty = "\\empty" let exit = "\\exit" let die = "\\die" let unsafe_cast = "\\HH\\FIXME\\UNSAFE_CAST" let unsafe_nonnull_cast = "\\HH\\FIXME\\UNSAFE_NONNULL_CAST" let enforced_cast = "\\HH\\FIXME\\ENFORCED_CAST" let all_pseudo_functions = HashSet.of_list [ isset; unset; hh_show; hh_expect; hh_expect_equivalent; hh_show_env; hh_log_level; hh_force_solve; hh_loop_forever; echo; empty; exit; die; unsafe_cast; unsafe_nonnull_cast; ] let is_pseudo_function x = HashSet.mem all_pseudo_functions x end module StdlibFunctions = struct let is_array = "\\is_array" let is_null = "\\is_null" let get_class = "\\get_class" let array_filter = "\\array_filter" let call_user_func = "\\call_user_func" let type_structure = "\\HH\\type_structure" let array_mark_legacy = "\\HH\\array_mark_legacy" let array_unmark_legacy = "\\HH\\array_unmark_legacy" let is_any_array = "\\HH\\is_any_array" let is_dict_or_darray = "\\HH\\is_dict_or_darray" let is_vec_or_varray = "\\HH\\is_vec_or_varray" (* All Id funcions that Typing.dispatch_call handles specially *) let special_dispatch = String.Hash_set.of_list ~growth_allowed:false [ SpecialFunctions.echo; PseudoFunctions.isset; PseudoFunctions.unset; type_structure; PseudoFunctions.unsafe_cast; PseudoFunctions.unsafe_nonnull_cast; ] let needs_special_dispatch x = Hash_set.mem special_dispatch x end module Typehints = struct let null = "null" let void = "void" let resource = "resource" let num = "num" let arraykey = "arraykey" let noreturn = "noreturn" let mixed = "mixed" let nonnull = "nonnull" let this = "this" let dynamic = "dynamic" let nothing = "nothing" let int = "int" let bool = "bool" let float = "float" let string = "string" let darray = "darray" let varray = "varray" let varray_or_darray = "varray_or_darray" let vec_or_dict = "vec_or_dict" let callable = "callable" let wildcard = "_" let is_reserved_type_hint = let reserved_typehints = HashSet.of_list [ null; void; resource; num; arraykey; noreturn; mixed; nonnull; this; dynamic; nothing; int; bool; float; string; darray; varray; varray_or_darray; vec_or_dict; callable; wildcard; ] in (fun x -> HashSet.mem reserved_typehints x) let is_reserved_global_name x = String.equal x callable || String.equal x Classes.cSelf || String.equal x Classes.cParent let is_reserved_hh_name x = String.equal x void || String.equal x noreturn || String.equal x int || String.equal x bool || String.equal x float || String.equal x num || String.equal x string || String.equal x resource || String.equal x mixed || String.equal x arraykey || String.equal x dynamic || String.equal x wildcard || String.equal x null || String.equal x nonnull || String.equal x nothing || String.equal x this let is_namespace_with_reserved_hh_name x = let unqualify qualified_name = let as_list = Str.split (Str.regexp "\\") qualified_name in let as_list = List.filter as_list ~f:(fun s -> not (String.equal s "")) in match List.rev as_list with | name :: qualifiers -> (List.rev qualifiers, name) | [] -> ([], qualified_name) in let is_HH qualifier = match qualifier with | [qual] -> String.equal qual "HH" | _ -> false in let (qualifier, name) = unqualify x in name |> is_reserved_hh_name && (not (List.is_empty qualifier)) && not (qualifier |> is_HH) end module PseudoConsts = struct let g__LINE__ = "\\__LINE__" let g__CLASS__ = "\\__CLASS__" let g__TRAIT__ = "\\__TRAIT__" let g__FILE__ = "\\__FILE__" let g__DIR__ = "\\__DIR__" let g__FUNCTION__ = "\\__FUNCTION__" let g__METHOD__ = "\\__METHOD__" let g__NAMESPACE__ = "\\__NAMESPACE__" let g__COMPILER_FRONTEND__ = "\\__COMPILER_FRONTEND__" let g__FUNCTION_CREDENTIAL__ = "\\__FUNCTION_CREDENTIAL__" (* exit and die are not pseudo consts, but they are currently parsed as such. * Would be more correct to parse them as special statements like return *) let exit = "\\exit" let die = "\\die" let all_pseudo_consts = HashSet.of_list [ g__LINE__; g__CLASS__; g__TRAIT__; g__FILE__; g__DIR__; g__FUNCTION__; g__METHOD__; g__NAMESPACE__; g__COMPILER_FRONTEND__; g__FUNCTION_CREDENTIAL__; exit; die; ] let is_pseudo_const x = HashSet.mem all_pseudo_consts x end module FB = struct let cEnum = "\\Enum" let tInner = "TInner" let idx = "\\HH\\idx" let cTypeStructure = "\\HH\\TypeStructure" end module HH = struct let memoizeOption = "\\HH\\MemoizeOption" let contains = "\\HH\\Lib\\C\\contains" let contains_key = "\\HH\\Lib\\C\\contains_key" module FIXME = struct let tTanyMarker = "\\HH\\FIXME\\TANY_MARKER" let tPoisonMarker = "\\HH\\FIXME\\POISON_MARKER" end end module Shapes = struct let cShapes = "\\HH\\Shapes" let cReadonlyShapes = "\\HH\\Readonly\\Shapes" let idx = "idx" let at = "at" let keyExists = "keyExists" let removeKey = "removeKey" let toArray = "toArray" let toDict = "toDict" end module Hips = struct let inspect = "\\inspect" end module Superglobals = struct let globals = "$GLOBALS" let is_superglobal = let superglobals = HashSet.of_list [ "$_SERVER"; "$_GET"; "$_POST"; "$_FILES"; "$_COOKIE"; "$_REQUEST"; "$_ENV"; ] in (fun x -> HashSet.mem superglobals x) end module Regex = struct let tPattern = "\\HH\\Lib\\Regex\\Pattern" end (* These are functions treated by the emitter specially. They are not * autoimported (see hh_autoimport.ml) nor are they consider PseudoFunctions * so they can be overridden by namespacing (at least currently) *) module EmitterSpecialFunctions = struct let eval = "\\eval" let set_frame_metadata = "\\HH\\set_frame_metadata" let systemlib_reified_generics = "\\__systemlib_reified_generics" end module XHP = struct let pcdata = "pcdata" let any = "any" let empty = "empty" let is_reserved name = String.equal name pcdata || String.equal name any || String.equal name empty let is_xhp_category name = String.is_prefix name ~prefix:"%" end (* This should be a subset of rust_parser_errors::UnstableFeatures that is relevant * to the typechecker *) module UnstableFeatures = struct let coeffects_provisional = "coeffects_provisional" let ifc = "ifc" let readonly = "readonly" let expression_trees = "expression_trees" let modules = "modules" end module Coeffects = struct let capability = "$#capability" let local_capability = "$#local_capability" let contexts = "\\HH\\Contexts" let unsafe_contexts = contexts ^ "\\Unsafe" let generated_generic_prefix = "T/" let is_generated_generic = String.is_prefix ~prefix:generated_generic_prefix (** "T/[ctx $foo]" to "ctx $foo". *) let unwrap_generated_generic name = name |> String.chop_prefix_if_exists ~prefix:"T/[" |> String.chop_suffix_if_exists ~suffix:"]" end module Readonly = struct let prefix = "\\HH\\Readonly\\" let idx = "\\HH\\idx_readonly" let as_mut = prefix ^ "as_mut" end module Capabilities = struct let defaults = Coeffects.contexts ^ "\\defaults" let write_props = Coeffects.contexts ^ "\\write_props" let prefix = "\\HH\\Capabilities\\" let writeProperty = prefix ^ "WriteProperty" let accessGlobals = prefix ^ "AccessGlobals" let readGlobals = prefix ^ "ReadGlobals" let systemLocal = prefix ^ "SystemLocal" let implicitPolicy = prefix ^ "ImplicitPolicy" let implicitPolicyLocal = prefix ^ "ImplicitPolicyLocal" let io = prefix ^ "IO" let rx = prefix ^ "Rx" let rxLocal = rx ^ "Local" end module ExpressionTrees = struct let makeTree = "makeTree" let intType = "intType" let floatType = "floatType" let boolType = "boolType" let stringType = "stringType" let nullType = "nullType" let voidType = "voidType" let symbolType = "symbolType" let visitInt = "visitInt" let visitFloat = "visitFloat" let visitBool = "visitBool" let visitString = "visitString" let visitNull = "visitNull" let visitBinop = "visitBinop" let visitUnop = "visitUnop" let visitLocal = "visitLocal" let visitLambda = "visitLambda" let visitGlobalFunction = "visitGlobalFunction" let visitStaticMethod = "visitStaticMethod" let visitCall = "visitCall" let visitAssign = "visitAssign" let visitTernary = "visitTernary" let visitIf = "visitIf" let visitWhile = "visitWhile" let visitReturn = "visitReturn" let visitFor = "visitFor" let visitBreak = "visitBreak" let visitContinue = "visitContinue" let splice = "splice" let dollardollarTmpVar = "$0dollardollar" end
Rust
hhvm/hphp/hack/src/naming/naming_special_names.rs
/* * 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 consisting of the special names known to the typechecker */ pub mod classes { pub const PARENT: &str = "parent"; pub const STATIC: &str = "static"; pub const SELF: &str = "self"; pub const UNKNOWN: &str = "\\*Unknown*"; /* Used for dynamic classnames, e.g. new $foo(); */ pub const AWAITABLE: &str = "\\HH\\Awaitable"; pub const GENERATOR: &str = "\\Generator"; pub const ASYNC_GENERATOR: &str = "\\HH\\AsyncGenerator"; pub const HH_FORMAT_STRING: &str = "\\HH\\FormatString"; pub fn is_format_string(x: &str) -> bool { match x { HH_FORMAT_STRING => true, _ => false, } } pub const HH_BUILTIN_ENUM: &str = "\\HH\\BuiltinEnum"; pub const HH_BUILTIN_ENUM_CLASS: &str = "\\HH\\BuiltinEnumClass"; pub const HH_BUILTIN_ABSTRACT_ENUM_CLASS: &str = "\\HH\\BuiltinAbstractEnumClass"; pub const THROWABLE: &str = "\\Throwable"; pub const STD_CLASS: &str = "\\stdClass"; pub const DATE_TIME: &str = "\\DateTime"; pub const DATE_TIME_IMMUTABLE: &str = "\\DateTimeImmutable"; pub const ASYNC_ITERATOR: &str = "\\HH\\AsyncIterator"; pub const ASYNC_KEYED_ITERATOR: &str = "\\HH\\AsyncKeyedIterator"; pub const STRINGISH: &str = "\\Stringish"; pub const STRINGISH_OBJECT: &str = "\\StringishObject"; pub const XHP_CHILD: &str = "\\XHPChild"; pub const IMEMOIZE_PARAM: &str = "\\HH\\IMemoizeParam"; pub const UNSAFE_SINGLETON_MEMOIZE_PARAM: &str = "\\HH\\UNSAFESingletonMemoizeParam"; pub const CLASS_NAME: &str = "\\HH\\classname"; pub const TYPE_NAME: &str = "\\HH\\typename"; pub const IDISPOSABLE: &str = "\\IDisposable"; pub const IASYNC_DISPOSABLE: &str = "\\IAsyncDisposable"; pub const MEMBER_OF: &str = "\\HH\\MemberOf"; pub const ENUM_CLASS_LABEL: &str = "\\HH\\EnumClass\\Label"; /// Classes that can be spliced into ExpressionTrees pub const SPLICEABLE: &str = "\\Spliceable"; pub const SUPPORT_DYN: &str = "\\HH\\supportdyn"; } pub mod collections { /* concrete classes */ pub const VECTOR: &str = "\\HH\\Vector"; pub const MUTABLE_VECTOR: &str = "\\MutableVector"; pub const IMM_VECTOR: &str = "\\HH\\ImmVector"; pub const SET: &str = "\\HH\\Set"; pub const CONST_SET: &str = "\\ConstSet"; pub const MUTABLE_SET: &str = "\\MutableSet"; pub const IMM_SET: &str = "\\HH\\ImmSet"; pub const MAP: &str = "\\HH\\Map"; pub const MUTABLE_MAP: &str = "\\MutableMap"; pub const IMM_MAP: &str = "\\HH\\ImmMap"; pub const PAIR: &str = "\\HH\\Pair"; /* interfaces */ pub const CONTAINER: &str = "\\HH\\Container"; pub const KEYED_CONTAINER: &str = "\\HH\\KeyedContainer"; pub const TRAVERSABLE: &str = "\\HH\\Traversable"; pub const KEYED_TRAVERSABLE: &str = "\\HH\\KeyedTraversable"; pub const COLLECTION: &str = "\\Collection"; pub const CONST_VECTOR: &str = "\\ConstVector"; pub const CONST_MAP: &str = "\\ConstMap"; pub const CONST_COLLECTION: &str = "\\ConstCollection"; pub const ANY_ARRAY: &str = "\\HH\\AnyArray"; pub const DICT: &str = "\\HH\\dict"; pub const VEC: &str = "\\HH\\vec"; pub const KEYSET: &str = "\\HH\\keyset"; } pub mod members { use hash::HashMap; use hash::HashSet; use lazy_static::lazy_static; pub const M_GET_INSTANCE_KEY: &str = "getInstanceKey"; pub const M_CLASS: &str = "class"; pub const __CONSTRUCT: &str = "__construct"; pub const __DESTRUCT: &str = "__destruct"; pub const __CALL: &str = "__call"; pub const __CALL_STATIC: &str = "__callStatic"; pub const __CLONE: &str = "__clone"; pub const __DEBUG_INFO: &str = "__debugInfo"; pub const __DISPOSE: &str = "__dispose"; pub const __DISPOSE_ASYNC: &str = "__disposeAsync"; pub const __GET: &str = "__get"; pub const __INVOKE: &str = "__invoke"; pub const __ISSET: &str = "__isset"; pub const __SET: &str = "__set"; pub const __SET_STATE: &str = "__set_state"; pub const __SLEEP: &str = "__sleep"; pub const __TO_STRING: &str = "__toString"; pub const __UNSET: &str = "__unset"; pub const __WAKEUP: &str = "__wakeup"; lazy_static! { static ref AS_SET: HashSet<&'static str> = vec![ __CONSTRUCT, __DESTRUCT, __CALL, __CALL_STATIC, __CLONE, __DEBUG_INFO, __DISPOSE, __DISPOSE_ASYNC, __GET, __INVOKE, __ISSET, __SET, __SET_STATE, __SLEEP, __TO_STRING, __UNSET, __WAKEUP ] .into_iter() .collect(); pub static ref AS_LOWERCASE_SET: HashSet<String> = { AS_SET .iter() .fold(HashSet::<String>::default(), |mut set, special_name| { set.insert(special_name.to_ascii_lowercase()); set }) }; pub static ref UNSUPPORTED_MAP: HashMap<String, &'static str> = { vec![__CALL, __CALL_STATIC, __GET, __ISSET, __SET, __UNSET] .iter() .fold( HashMap::<String, &'static str>::default(), |mut set, special_name| { set.insert(special_name.to_ascii_lowercase(), special_name); set }, ) }; } /* Any data- or aria- attribute is always valid, even if it is not declared * for a given XHP element */ pub fn is_special_xhp_attribute(s: &str) -> bool { s.len() >= 6 && match &s[..6] { ":data-" | ":aria-" => true, _ => false, } } } pub mod user_attributes { pub const OVERRIDE: &str = "__Override"; pub const CONSISTENT_CONSTRUCT: &str = "__ConsistentConstruct"; pub const CONST: &str = "__Const"; pub const DEPRECATED: &str = "__Deprecated"; pub const DOCS: &str = "__Docs"; pub const ENTRY_POINT: &str = "__EntryPoint"; pub const MEMOIZE: &str = "__Memoize"; pub const MEMOIZE_LSB: &str = "__MemoizeLSB"; pub const PHP_STD_LIB: &str = "__PHPStdLib"; pub const ACCEPT_DISPOSABLE: &str = "__AcceptDisposable"; pub const RETURN_DISPOSABLE: &str = "__ReturnDisposable"; pub const LSB: &str = "__LSB"; pub const SEALED: &str = "__Sealed"; pub const LATE_INIT: &str = "__LateInit"; pub const NEWABLE: &str = "__Newable"; pub const ENFORCEABLE: &str = "__Enforceable"; pub const EXPLICIT: &str = "__Explicit"; pub const NON_DISJOINT: &str = "__NonDisjoint"; pub const SOFT: &str = "__Soft"; pub const SOFT_INTERNAL: &str = "__SoftInternal"; pub const WARN: &str = "__Warn"; pub const MOCK_CLASS: &str = "__MockClass"; pub const PROVENANCE_SKIP_FRAME: &str = "__ProvenanceSkipFrame"; pub const DYNAMICALLY_CALLABLE: &str = "__DynamicallyCallable"; pub const DYNAMICALLY_CONSTRUCTIBLE: &str = "__DynamicallyConstructible"; pub const REIFIABLE: &str = "__Reifiable"; pub const NEVER_INLINE: &str = "__NEVER_INLINE"; pub const DISABLE_TYPECHECKER_INTERNAL: &str = "__DisableTypecheckerInternal"; pub const HAS_TOP_LEVEL_CODE: &str = "__HasTopLevelCode"; pub const IS_FOLDABLE: &str = "__IsFoldable"; pub const NATIVE: &str = "__Native"; pub const OUT_ONLY: &str = "__OutOnly"; pub const ALWAYS_INLINE: &str = "__ALWAYS_INLINE"; pub const ENABLE_UNSTABLE_FEATURES: &str = "__EnableUnstableFeatures"; pub const ENUM_CLASS: &str = "__EnumClass"; pub const POLICIED: &str = "__Policied"; pub const INFERFLOWS: &str = "__InferFlows"; pub const EXTERNAL: &str = "__External"; pub const CAN_CALL: &str = "__CanCall"; pub const SUPPORT_DYNAMIC_TYPE: &str = "__SupportDynamicType"; pub const NO_AUTO_DYNAMIC: &str = "__NoAutoDynamic"; pub const NO_AUTO_LIKES: &str = "__NoAutoLikes"; pub const NO_AUTO_BOUND: &str = "__NoAutoBound"; pub const REQUIRE_DYNAMIC: &str = "__RequireDynamic"; pub const ENABLE_METHOD_TRAIT_DIAMOND: &str = "__EnableMethodTraitDiamond"; pub const IGNORE_READONLY_LOCAL_ERRORS: &str = "__IgnoreReadonlyLocalErrors"; pub const IGNORE_COEFFECT_LOCAL_ERRORS: &str = "__IgnoreCoeffectLocalErrors"; pub const CROSS_PACKAGE: &str = "__CrossPackage"; pub const MODULE_LEVEL_TRAIT: &str = "__ModuleLevelTrait"; pub fn is_memoized(name: &str) -> bool { name == MEMOIZE || name == MEMOIZE_LSB } // TODO(hrust) these should probably be added to the above map/fields, too // These attributes are only valid in systemlib, and therefore are not passed to the typechecker // or hhi files pub fn is_native(name: &str) -> bool { name == "__Native" } pub fn ignore_coeffect_local_errors(name: &str) -> bool { name == "__IgnoreCoeffectLocalErrors" } pub fn ignore_readonly_local_errors(name: &str) -> bool { name == "__IgnoreReadonlyLocalErrors" } pub fn is_foldable(name: &str) -> bool { name == "__IsFoldable" } pub fn is_meth_caller(name: &str) -> bool { name == "__MethCaller" } pub fn is_reserved(name: &str) -> bool { name.starts_with("__") } pub fn is_soft(name: &str) -> bool { name == SOFT } pub fn is_ifc(name: &str) -> bool { name == POLICIED || name == INFERFLOWS || name == EXTERNAL } pub fn is_cross_package(name: &str) -> bool { name == CROSS_PACKAGE } } pub mod memoize_option { use hash::HashSet; use lazy_static::lazy_static; pub const KEYED_BY_IC: &str = "KeyedByIC"; pub const MAKE_IC_INACCESSSIBLE: &str = "MakeICInaccessible"; pub const SOFT_MAKE_IC_INACCESSSIBLE: &str = "SoftMakeICInaccessible"; pub const UNCATEGORIZED: &str = "Uncategorized"; pub static _ALL: &[&str] = &[ KEYED_BY_IC, MAKE_IC_INACCESSSIBLE, SOFT_MAKE_IC_INACCESSSIBLE, UNCATEGORIZED, ]; lazy_static! { static ref VALID_SET: HashSet<&'static str> = _ALL.iter().copied().collect(); } pub fn is_valid(x: &str) -> bool { VALID_SET.contains(x) } } pub mod attribute_kinds { use hash::HashMap; use lazy_static::lazy_static; pub const CLS: &str = "\\HH\\ClassAttribute"; pub const CLS_CST: &str = "\\HH\\ClassConstantAttribute"; pub const ENUM: &str = "\\HH\\EnumAttribute"; pub const TYPE_ALIAS: &str = "\\HH\\TypeAliasAttribute"; pub const FN: &str = "\\HH\\FunctionAttribute"; pub const MTHD: &str = "\\HH\\MethodAttribute"; pub const INST_PROPERTY: &str = "\\HH\\InstancePropertyAttribute"; pub const STATIC_PROPERTY: &str = "\\HH\\StaticPropertyAttribute"; pub const PARAMETER: &str = "\\HH\\ParameterAttribute"; pub const TYPE_PARAM: &str = "\\HH\\TypeParameterAttribute"; pub const FILE: &str = "\\HH\\FileAttribute"; pub const TYPE_CONST: &str = "\\HH\\TypeConstantAttribute"; pub const LAMBDA: &str = "\\HH\\LambdaAttribute"; pub const ENUM_CLS: &str = "\\HH\\EnumClassAttribute"; pub static PLAIN_ENGLISH: &[(&str, &str)] = &[ (CLS, "a class"), (CLS_CST, "a constant of a class"), (ENUM, "an enum"), (TYPE_ALIAS, "a typealias"), (FN, "a function"), (MTHD, "a method"), (INST_PROPERTY, "an instance property"), (STATIC_PROPERTY, "a static property"), (PARAMETER, "a parameter"), (TYPE_PARAM, "a type parameter"), (FILE, "a file"), (TYPE_CONST, "a type constant"), (LAMBDA, "a lambda expression"), (ENUM_CLS, "an enum class"), ]; lazy_static! { pub static ref PLAIN_ENGLISH_MAP: HashMap<&'static str, &'static str> = PLAIN_ENGLISH.iter().copied().collect(); } } /* Tested before \\-prepending name-canonicalization */ pub mod special_functions { use lazy_static::lazy_static; pub const ECHO: &str = "echo"; /* pseudo-function */ pub fn is_special_function(x: &str) -> bool { lazy_static! { static ref ALL_SPECIAL_FUNCTIONS: Vec<&'static str> = vec![ECHO].into_iter().collect(); } ALL_SPECIAL_FUNCTIONS.contains(&x) } } pub mod autoimported_functions { pub const INVARIANT: &str = "\\HH\\invariant"; pub const INVARIANT_VIOLATION: &str = "\\HH\\invariant_violation"; pub const METH_CALLER: &str = "\\HH\\meth_caller"; } pub mod special_idents { pub const THIS: &str = "$this"; pub const PLACEHOLDER: &str = "$_"; pub const DOLLAR_DOLLAR: &str = "$$"; /* Intentionally using an invalid variable name to ensure it's translated */ pub const TMP_VAR_PREFIX: &str = "__tmp$"; pub fn is_tmp_var(name: &str) -> bool { name.len() > TMP_VAR_PREFIX.len() && name.starts_with(TMP_VAR_PREFIX) } pub fn assert_tmp_var(name: &str) { assert!(is_tmp_var(name)) } } pub mod pseudo_functions { use hash::HashSet; use lazy_static::lazy_static; pub const ISSET: &str = "\\isset"; pub const UNSET: &str = "\\unset"; pub const HH_SHOW: &str = "\\hh_show"; pub const HH_EXPECT: &str = "\\hh_expect"; pub const HH_EXPECT_EQUIVALENT: &str = "\\hh_expect_equivalent"; pub const HH_SHOW_ENV: &str = "\\hh_show_env"; pub const HH_LOG_LEVEL: &str = "\\hh_log_level"; pub const HH_FORCE_SOLVE: &str = "\\hh_force_solve"; pub const HH_LOOP_FOREVER: &str = "\\hh_loop_forever"; pub const ECHO: &str = "\\echo"; pub const ECHO_NO_NS: &str = "echo"; pub const EMPTY: &str = "\\empty"; pub const EXIT: &str = "\\exit"; pub const DIE: &str = "\\die"; pub const UNSAFE_CAST: &str = "\\HH\\FIXME\\UNSAFE_CAST"; pub const UNSAFE_NONNULL_CAST: &str = "\\HH\\FIXME\\UNSAFE_NONNULL_CAST"; pub const ENFORCED_CAST: &str = "\\HH\\FIXME\\ENFORCED_CAST"; pub const PACKAGE_EXISTS: &str = "\\HH\\package_exists"; pub static ALL_PSEUDO_FUNCTIONS: &[&str] = &[ ISSET, UNSET, HH_SHOW, HH_EXPECT, HH_EXPECT_EQUIVALENT, HH_SHOW_ENV, HH_LOG_LEVEL, HH_FORCE_SOLVE, HH_LOOP_FOREVER, ECHO, EMPTY, EXIT, DIE, UNSAFE_CAST, UNSAFE_NONNULL_CAST, PACKAGE_EXISTS, ]; lazy_static! { static ref PSEUDO_SET: HashSet<&'static str> = ALL_PSEUDO_FUNCTIONS.iter().copied().collect(); } pub fn is_pseudo_function(x: &str) -> bool { PSEUDO_SET.contains(x) } } pub mod std_lib_functions { pub const IS_ARRAY: &str = "\\is_array"; pub const IS_NULL: &str = "\\is_null"; pub const GET_CLASS: &str = "\\get_class"; pub const ARRAY_FILTER: &str = "\\array_filter"; pub const CALL_USER_FUNC: &str = "\\call_user_func"; pub const TYPE_STRUCTURE: &str = "\\HH\\type_structure"; pub const ARRAY_MARK_LEGACY: &str = "\\HH\\array_mark_legacy"; pub const ARRAY_UNMARK_LEGACY: &str = "\\HH\\array_unmark_legacy"; pub const IS_PHP_ARRAY: &str = "\\HH\\is_php_array"; pub const IS_ANY_ARRAY: &str = "\\HH\\is_any_array"; pub const IS_DICT_OR_DARRAY: &str = "\\HH\\is_dict_or_darray"; pub const IS_VEC_OR_VARRAY: &str = "\\HH\\is_vec_or_varray"; } pub mod typehints { use hash::HashSet; use lazy_static::lazy_static; pub const NULL: &str = "null"; pub const HH_NULL: &str = "\\HH\\null"; pub const VOID: &str = "void"; pub const HH_VOID: &str = "\\HH\\void"; pub const RESOURCE: &str = "resource"; pub const HH_RESOURCE: &str = "\\HH\\resource"; pub const NUM: &str = "num"; pub const HH_NUM: &str = "\\HH\\num"; pub const ARRAYKEY: &str = "arraykey"; pub const HH_ARRAYKEY: &str = "\\HH\\arraykey"; pub const NORETURN: &str = "noreturn"; pub const HH_NORETURN: &str = "\\HH\\noreturn"; pub const MIXED: &str = "mixed"; pub const NONNULL: &str = "nonnull"; pub const HH_NONNULL: &str = "\\HH\\nonnull"; pub const THIS: &str = "this"; pub const HH_THIS: &str = "\\HH\\this"; pub const DYNAMIC: &str = "dynamic"; pub const NOTHING: &str = "nothing"; pub const HH_NOTHING: &str = "\\HH\\nothing"; pub const INT: &str = "int"; pub const HH_INT: &str = "\\HH\\int"; pub const BOOL: &str = "bool"; pub const HH_BOOL: &str = "\\HH\\bool"; pub const FLOAT: &str = "float"; pub const HH_FLOAT: &str = "\\HH\\float"; pub const STRING: &str = "string"; pub const HH_STRING: &str = "\\HH\\string"; pub const DARRAY: &str = "darray"; pub const HH_DARRAY: &str = "\\HH\\darray"; pub const VARRAY: &str = "varray"; pub const HH_VARRAY: &str = "\\HH\\varray"; pub const VARRAY_OR_DARRAY: &str = "varray_or_darray"; pub const HH_VARRAY_OR_DARRAY: &str = "\\HH\\varray_or_darray"; pub const VEC_OR_DICT: &str = "vec_or_dict"; pub const HH_VEC_OR_DICT: &str = "\\HH\\vec_or_dict"; pub const CALLABLE: &str = "callable"; pub const OBJECT_CAST: &str = "object"; pub const SUPPORTDYN: &str = "supportdyn"; pub const HH_SUPPORTDYN: &str = "\\HH\\supportdyn"; pub const TANY_MARKER: &str = "\\HH\\FIXME\\TANY_MARKER"; pub const POISON_MARKER: &str = "\\HH\\FIXME\\POISON_MARKER"; pub const WILDCARD: &str = "_"; lazy_static! { // matches definition in Tprim pub static ref PRIMITIVE_TYPEHINTS: HashSet<&'static str> = vec![ NULL, VOID, INT, BOOL, FLOAT, STRING, RESOURCE, NUM, ARRAYKEY, NORETURN ] .into_iter() .collect(); } pub fn is_reserved_type_hint(x: &str) -> bool { lazy_static! { static ref RESERVED_TYPEHINTS: HashSet<&'static str> = vec![ NULL, VOID, RESOURCE, NUM, ARRAYKEY, NORETURN, MIXED, NONNULL, THIS, DYNAMIC, NOTHING, INT, BOOL, FLOAT, STRING, DARRAY, VARRAY, VARRAY_OR_DARRAY, VEC_OR_DICT, CALLABLE, WILDCARD, ] .into_iter() .collect(); } RESERVED_TYPEHINTS.contains(x) } lazy_static! { static ref RESERVED_GLOBAL_NAMES: HashSet<&'static str> = vec![CALLABLE, crate::classes::SELF, crate::classes::PARENT] .into_iter() .collect(); } pub fn is_reserved_global_name(x: &str) -> bool { RESERVED_GLOBAL_NAMES.contains(x) } lazy_static! { static ref RESERVED_HH_NAMES: HashSet<&'static str> = vec![ VOID, NORETURN, INT, BOOL, FLOAT, NUM, STRING, RESOURCE, MIXED, ARRAYKEY, DYNAMIC, WILDCARD, NULL, NONNULL, NOTHING, THIS ] .into_iter() .collect(); } pub fn is_reserved_hh_name(x: &str) -> bool { RESERVED_HH_NAMES.contains(x) } // This function checks if this is a namespace of the "(not HH)\\(...)*\\(reserved_name)" pub fn is_namespace_with_reserved_hh_name(x: &str) -> bool { // This splits the string into its namespaces fn unqualify(x: &str) -> (Vec<&str>, &str) { let mut as_list = x.split('\\').collect::<Vec<&str>>(); // Retain if not empty as_list.retain(|&split| match split { "" => false, _ => true, }); let last_split = match as_list.pop() { None => "", Some(x) => x, }; (as_list, last_split) } // This returns a bool whether or not the list is just the string "HH" fn is_hh(qualifier: &[&str]) -> bool { match qualifier.len() { 1 => qualifier[0] == "HH", _ => false, } } let (qualifier, name) = unqualify(x); !is_hh(&qualifier) && !qualifier.is_empty() && is_reserved_hh_name(name) } } pub mod literal { pub const TRUE: &str = "true"; pub const FALSE: &str = "false"; pub const NULL: &str = "null"; } pub mod pseudo_consts { use hash::HashSet; use lazy_static::lazy_static; pub const G__LINE__: &str = "\\__LINE__"; pub const G__CLASS__: &str = "\\__CLASS__"; pub const G__TRAIT__: &str = "\\__TRAIT__"; pub const G__FILE__: &str = "\\__FILE__"; pub const G__DIR__: &str = "\\__DIR__"; pub const G__FUNCTION__: &str = "\\__FUNCTION__"; pub const G__METHOD__: &str = "\\__METHOD__"; pub const G__NAMESPACE__: &str = "\\__NAMESPACE__"; pub const G__COMPILER_FRONTEND__: &str = "\\__COMPILER_FRONTEND__"; pub const G__FUNCTION_CREDENTIAL__: &str = "\\__FUNCTION_CREDENTIAL__"; pub const DIE: &str = "\\die"; pub const EXIT: &str = "\\exit"; pub static ALL_PSEUDO_CONSTS: &[&str] = &[ G__LINE__, G__CLASS__, G__TRAIT__, G__FILE__, G__DIR__, G__FUNCTION__, G__METHOD__, G__NAMESPACE__, G__COMPILER_FRONTEND__, G__FUNCTION_CREDENTIAL__, DIE, EXIT, ]; lazy_static! { static ref PSEUDO_SET: HashSet<&'static str> = ALL_PSEUDO_CONSTS.iter().copied().collect(); } pub fn is_pseudo_const(x: &str) -> bool { PSEUDO_SET.contains(x) } } pub mod fb { pub const ENUM: &str = "\\Enum"; pub const INNER: &str = "TInner"; pub const IDX: &str = "\\HH\\idx"; pub const IDXREADONLY: &str = "\\HH\\idx_readonly"; pub const TYPE_STRUCTURE: &str = "\\HH\\TypeStructure"; } pub mod hh { pub const MEMOIZE_OPTION: &str = "\\HH\\MemoizeOption"; pub const CONTAINS: &str = "\\HH\\Lib\\C\\contains"; pub const CONTAINS_KEY: &str = "\\HH\\Lib\\C\\contains_key"; } pub mod readonly { pub const IDX: &str = "\\HH\\idx_readonly"; pub const AS_MUT: &str = "\\HH\\Readonly\\as_mut"; } pub mod coeffects { use std::fmt; use hash::HashSet; use lazy_static::lazy_static; use serde::Serialize; pub const DEFAULTS: &str = "defaults"; pub const RX_LOCAL: &str = "rx_local"; pub const RX_SHALLOW: &str = "rx_shallow"; pub const RX: &str = "rx"; pub const WRITE_THIS_PROPS: &str = "write_this_props"; pub const WRITE_PROPS: &str = "write_props"; pub const LEAK_SAFE_LOCAL: &str = "leak_safe_local"; pub const LEAK_SAFE_SHALLOW: &str = "leak_safe_shallow"; pub const LEAK_SAFE: &str = "leak_safe"; pub const ZONED_LOCAL: &str = "zoned_local"; pub const ZONED_SHALLOW: &str = "zoned_shallow"; pub const ZONED: &str = "zoned"; pub const ZONED_WITH: &str = "zoned_with"; pub const PURE: &str = "pure"; pub const READ_GLOBALS: &str = "read_globals"; pub const GLOBALS: &str = "globals"; pub const BACKDOOR: &str = "86backdoor"; pub const BACKDOOR_GLOBALS_LEAK_SAFE: &str = "86backdoor_globals_leak_safe"; pub const CONTEXTS: &str = "HH\\Contexts"; pub const UNSAFE_CONTEXTS: &str = "HH\\Contexts\\Unsafe"; pub const CAPABILITIES: &str = "HH\\Capabilities"; pub fn is_any_zoned(x: &str) -> bool { lazy_static! { static ref ZONED_SET: HashSet<&'static str> = vec![ZONED, ZONED_WITH].into_iter().collect(); } ZONED_SET.contains(x) } pub fn is_any_zoned_or_defaults(x: &str) -> bool { lazy_static! { static ref ZONED_SET: HashSet<&'static str> = vec![ZONED, ZONED_WITH, ZONED_LOCAL, ZONED_SHALLOW, DEFAULTS] .into_iter() .collect(); } ZONED_SET.contains(x) } // context does not provide the capability to fetch the IC even indirectly pub fn is_any_without_implicit_policy_or_unsafe(x: &str) -> bool { lazy_static! { static ref LEAK_SAFE_GLOBALS_SET: HashSet<&'static str> = vec![LEAK_SAFE, GLOBALS, READ_GLOBALS, WRITE_PROPS] .into_iter() .collect(); } LEAK_SAFE_GLOBALS_SET.contains(x) } #[derive(PartialEq, Eq, Hash, Debug, Copy, Clone, Serialize)] #[repr(C)] pub enum Ctx { Defaults, // Shared WriteThisProps, WriteProps, // Rx hierarchy RxLocal, RxShallow, Rx, // Zoned hierarchy ZonedWith, ZonedLocal, ZonedShallow, Zoned, LeakSafeLocal, LeakSafeShallow, LeakSafe, ReadGlobals, Globals, // Pure Pure, } impl fmt::Display for Ctx { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use Ctx::*; match self { Defaults => write!(f, "{}", DEFAULTS), Pure => write!(f, "{}", PURE), RxLocal => write!(f, "{}", RX_LOCAL), RxShallow => write!(f, "{}", RX_SHALLOW), Rx => write!(f, "{}", RX), WriteThisProps => write!(f, "{}", WRITE_THIS_PROPS), WriteProps => write!(f, "{}", WRITE_PROPS), ZonedWith => write!(f, "{}", ZONED_WITH), ZonedLocal => write!(f, "{}", ZONED_LOCAL), ZonedShallow => write!(f, "{}", ZONED_SHALLOW), Zoned => write!(f, "{}", ZONED), LeakSafeLocal => write!(f, "{}", LEAK_SAFE_LOCAL), LeakSafeShallow => write!(f, "{}", LEAK_SAFE_SHALLOW), LeakSafe => write!(f, "{}", LEAK_SAFE), ReadGlobals => write!(f, "{}", READ_GLOBALS), Globals => write!(f, "{}", GLOBALS), } } } write_bytes::display_bytes_using_display!(Ctx); pub fn ctx_str_to_enum(s: &str) -> Option<Ctx> { match s { DEFAULTS => Some(Ctx::Defaults), PURE => Some(Ctx::Pure), RX_LOCAL => Some(Ctx::RxLocal), RX_SHALLOW => Some(Ctx::RxShallow), RX => Some(Ctx::Rx), WRITE_THIS_PROPS => Some(Ctx::WriteThisProps), WRITE_PROPS => Some(Ctx::WriteProps), ZONED_WITH => Some(Ctx::ZonedWith), ZONED_LOCAL => Some(Ctx::ZonedLocal), ZONED_SHALLOW => Some(Ctx::ZonedShallow), ZONED => Some(Ctx::Zoned), LEAK_SAFE_LOCAL => Some(Ctx::LeakSafeLocal), LEAK_SAFE_SHALLOW => Some(Ctx::LeakSafeShallow), LEAK_SAFE => Some(Ctx::LeakSafe), GLOBALS => Some(Ctx::Globals), READ_GLOBALS => Some(Ctx::ReadGlobals), _ => None, } } pub fn capability_matches_name(c: &Ctx, name: &Ctx) -> bool { // Either the capability we are searching for matches exactly, is a subtype // of, or is contained in the capability/context we are visiting if c == name || self::capability_contained_in_ctx(c, name) || self::capability_is_subtype_of_capability(c, name) { return true; } false } pub fn capability_contained_in_ctx(c: &Ctx, ctx: &Ctx) -> bool { match ctx { Ctx::Defaults => self::capability_in_defaults_ctx(c), Ctx::Rx | Ctx::RxLocal | Ctx::RxShallow => self::capability_in_rx_ctx(c), Ctx::LeakSafe | Ctx::LeakSafeLocal | Ctx::LeakSafeShallow => { self::capability_in_controlled_ctx(c) } Ctx::Zoned | Ctx::ZonedLocal | Ctx::ZonedShallow | Ctx::ZonedWith => { self::capability_in_policied_ctx(c) } // By definition, granular capabilities are not contexts and cannot // contain other capabilities. Also included in the fall through here // are pure, namespaced, polymorphic, and encapsulated contexts; oldrx related // contexts; and illformed symbols (e.g. primitive type used as a context) _ => false, } } pub fn capability_is_subtype_of_capability(s: &Ctx, c: &Ctx) -> bool { match c { Ctx::WriteProps => *s == Ctx::WriteThisProps, Ctx::Globals => *s == Ctx::ReadGlobals, // By definition, contexts which contain multiple capabilities are not // themselves granular capabilities and therefore not subject to this // logic. Also included in the fall through here are capabilities which do // not have "subtype" capabilities and illformed symbols (e.g. primitive // type used as a context) _ => false, } } pub fn capability_in_defaults_ctx(c: &Ctx) -> bool { lazy_static! { static ref DEFAULTS_SET: HashSet<Ctx> = vec![Ctx::WriteProps, Ctx::Globals,].into_iter().collect(); } DEFAULTS_SET.contains(c) } pub fn capability_in_policied_ctx(c: &Ctx) -> bool { lazy_static! { static ref POLICIED_SET: HashSet<Ctx> = vec![Ctx::WriteProps, Ctx::ReadGlobals,] .into_iter() .collect(); } POLICIED_SET.contains(c) } pub fn capability_in_rx_ctx(c: &Ctx) -> bool { lazy_static! { static ref RX_SET: HashSet<Ctx> = vec![Ctx::WriteProps,].into_iter().collect(); } RX_SET.contains(c) } pub fn capability_in_controlled_ctx(c: &Ctx) -> bool { lazy_static! { static ref CONTROLLED_SET: HashSet<Ctx> = vec![Ctx::WriteProps, Ctx::ReadGlobals,] .into_iter() .collect(); } CONTROLLED_SET.contains(c) } } pub mod shapes { pub const SHAPES: &str = "\\HH\\Shapes"; pub const IDX: &str = "idx"; pub const AT: &str = "at"; pub const KEY_EXISTS: &str = "keyExists"; pub const REMOVE_KEY: &str = "removeKey"; pub const TO_ARRAY: &str = "toArray"; pub const TO_DICT: &str = "toDict"; } pub mod superglobals { use hash::HashSet; use lazy_static::lazy_static; pub const GLOBALS: &str = "$GLOBALS"; pub static SUPERGLOBALS: &[&str] = &[ "$_SERVER", "$_GET", "$_POST", "$_FILES", "$_COOKIE", "$_REQUEST", "$_ENV", ]; lazy_static! { static ref SUPERGLOBALS_SET: HashSet<&'static str> = SUPERGLOBALS.iter().copied().collect(); } pub fn is_superglobal(x: &str) -> bool { SUPERGLOBALS_SET.contains(x) } pub fn is_any_global(x: &str) -> bool { is_superglobal(x) || x == GLOBALS } } pub mod xhp { pub const PCDATA: &str = "pcdata"; pub const ANY: &str = "any"; pub const EMPTY: &str = "empty"; pub fn is_reserved(x: &str) -> bool { x == PCDATA || x == ANY || x == EMPTY } pub fn is_xhp_category(x: &str) -> bool { x.starts_with('%') } } pub mod unstable_features { pub const COEFFECTS_PROVISIONAL: &str = "coeffects_provisional"; pub const IFC: &str = "ifc"; pub const READONLY: &str = "readonly"; pub const EXPRESSION_TREES: &str = "expression_trees"; pub const MODULES: &str = "modules"; pub const MODULE_REFERENCES: &str = "module_references"; pub const PACKAGE: &str = "package"; } pub mod regex { pub const T_PATTERN: &str = "\\HH\\Lib\\Regex\\Pattern"; } pub mod emitter_special_functions { pub const EVAL: &str = "\\eval"; pub const SET_FRAME_METADATA: &str = "\\HH\\set_frame_metadata"; pub const SET_PRODUCT_ATTRIBUTION_ID: &str = "\\HH\\set_product_attribution_id"; pub const SET_PRODUCT_ATTRIBUTION_ID_DEFERRED: &str = "\\HH\\set_product_attribution_id_deferred"; pub const SYSTEMLIB_REIFIED_GENERICS: &str = "\\__systemlib_reified_generics"; pub const GENA: &str = "gena"; } pub mod math { pub const NAN: &str = "NAN"; pub const INF: &str = "INF"; pub const NEG_INF: &str = "-INF"; } pub mod expression_trees { pub const MAKE_TREE: &str = "makeTree"; pub const INT_TYPE: &str = "intType"; pub const FLOAT_TYPE: &str = "floatType"; pub const BOOL_TYPE: &str = "boolType"; pub const STRING_TYPE: &str = "stringType"; pub const NULL_TYPE: &str = "nullType"; pub const VOID_TYPE: &str = "voidType"; pub const SYMBOL_TYPE: &str = "symbolType"; pub const LAMBDA_TYPE: &str = "lambdaType"; pub const VISIT_INT: &str = "visitInt"; pub const VISIT_FLOAT: &str = "visitFloat"; pub const VISIT_BOOL: &str = "visitBool"; pub const VISIT_STRING: &str = "visitString"; pub const VISIT_NULL: &str = "visitNull"; pub const VISIT_BINOP: &str = "visitBinop"; pub const VISIT_UNOP: &str = "visitUnop"; pub const VISIT_LOCAL: &str = "visitLocal"; pub const VISIT_LAMBDA: &str = "visitLambda"; pub const VISIT_GLOBAL_FUNCTION: &str = "visitGlobalFunction"; pub const VISIT_STATIC_METHOD: &str = "visitStaticMethod"; pub const VISIT_CALL: &str = "visitCall"; pub const VISIT_ASSIGN: &str = "visitAssign"; pub const VISIT_TERNARY: &str = "visitTernary"; pub const VISIT_IF: &str = "visitIf"; pub const VISIT_WHILE: &str = "visitWhile"; pub const VISIT_RETURN: &str = "visitReturn"; pub const VISIT_FOR: &str = "visitFor"; pub const VISIT_BREAK: &str = "visitBreak"; pub const VISIT_CONTINUE: &str = "visitContinue"; pub const VISIT_PROPERTY_ACCESS: &str = "visitPropertyAccess"; pub const VISIT_XHP: &str = "visitXhp"; pub const SPLICE: &str = "splice"; pub const DOLLARDOLLAR_TMP_VAR: &str = "$0dollardollar"; } #[cfg(test)] mod test { use crate::members::is_special_xhp_attribute; use crate::members::AS_LOWERCASE_SET; use crate::members::UNSUPPORTED_MAP; use crate::special_idents::is_tmp_var; use crate::typehints::is_namespace_with_reserved_hh_name; #[test] fn test_special_idents_is_tmp_var() { assert!(!is_tmp_var("_tmp$Blah")); assert!(!is_tmp_var("__tmp$")); assert!(!is_tmp_var("О БОЖЕ")); assert!(is_tmp_var("__tmp$Blah")); } #[test] fn test_members_as_lowercase_set() { assert!(AS_LOWERCASE_SET.contains("__tostring")); assert!(!AS_LOWERCASE_SET.contains("__toString")); } #[test] fn test_members_unsupported_map() { assert_eq!(UNSUPPORTED_MAP.get("__callstatic"), Some(&"__callStatic")); assert!(!UNSUPPORTED_MAP.contains_key("__callStatic")); } #[test] fn test_members_is_special_xhp_attribute() { assert!(is_special_xhp_attribute(":data-blahblah")); assert!(is_special_xhp_attribute(":aria-blahblah")); assert!(!is_special_xhp_attribute(":arla-blahblah")); assert!(!is_special_xhp_attribute(":aria")); } #[test] fn test_typehint_is_namespace_with_reserved_hh_name() { assert!(!is_namespace_with_reserved_hh_name("HH\\void")); assert!(!is_namespace_with_reserved_hh_name("void")); assert!(!is_namespace_with_reserved_hh_name("ReturnType\\Lloyd")); assert!(!is_namespace_with_reserved_hh_name("Lloyd")); assert!(is_namespace_with_reserved_hh_name("Anything\\Else\\void")); } }
Rust
hhvm/hphp/hack/src/naming/naming_special_names_ffi_cbindgen.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. /// This definition exists for ffi_cbindgen C++ header generation. Any /// attempt to call this function will result in an intentional /// unresolved symbol at link time. #[no_mangle] pub extern "C" fn no_call_compile_only_USED_TYPES_naming_special_names(_: Ctx) { unimplemented!() }
OCaml
hhvm/hphp/hack/src/naming/naming_sqlite.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 Sqlite_utils type db_path = Db_path of string [@@deriving eq, show] type insertion_error = { canon_hash: Int64.t; hash: Int64.t; name_kind: Naming_types.name_kind; name: string; origin_exception: Exception.t; [@printer (fun fmt e -> fprintf fmt "%s" (Exception.get_ctor_string e))] } [@@deriving show] type save_result = { files_added: int; symbols_added: int; errors: insertion_error list; checksum: Int64.t; } [@@deriving show] let empty_save_result ~(checksum : Int64.t) = { files_added = 0; symbols_added = 0; errors = []; checksum } let insert_safe ~name ~name_kind ~hash ~canon_hash f : (unit, insertion_error) result = try Ok (f ()) with | e -> let origin_exception = Exception.wrap e in Error { canon_hash; hash; name_kind; name; origin_exception } type 'a forward_naming_table_delta = | Modified of 'a | Deleted [@@deriving show] type file_deltas = FileInfo.t forward_naming_table_delta Relative_path.Map.t type blob_format = FileInfo.saved forward_naming_table_delta Relative_path.Map.t let pp_file_deltas = Relative_path.Map.make_pp Relative_path.pp (pp_forward_naming_table_delta FileInfo.pp) type local_changes = { file_deltas: file_deltas; base_content_version: string; } [@@deriving show] type symbol_and_decl_hash = { symbol: Int64.t; (** the HASH column of NAMING_SYMBOLS *) decl_hash: Int64.t; (** the DECL_HASH column of NAMING_SYMBOLS *) } external checksum_addremove : Int64.t -> symbol:Int64.t -> decl_hash:Int64.t -> path:Relative_path.t -> Int64.t = "checksum_addremove_ffi" let _ = show_forward_naming_table_delta let _ = show_local_changes let make_relative_path ~prefix_int ~suffix = let prefix = let open Option in value_exn (Int64.to_int prefix_int >>= Relative_path.prefix_of_enum) in let full_suffix = Filename.concat (Relative_path.path_of_prefix prefix) suffix in Relative_path.create prefix full_suffix let to_canon_name_key = Caml.String.lowercase_ascii let fold_sqlite stmt ~f ~init = let rec helper acc = match Sqlite3.step stmt with | Sqlite3.Rc.DONE -> acc | Sqlite3.Rc.ROW -> helper (f stmt acc) | rc -> failwith (Printf.sprintf "SQLite operation failed: %s" (Sqlite3.Rc.to_string rc)) in helper init (* It's kind of weird to just dump this into the SQLite database, but removing * entries one at a time during a normal incremental update leads to too many * table scans, and I don't want to put this in a separate file because then * the naming table and dep table in a given SQLite database might not agree * with each other, and that just feels weird. *) module LocalChanges = struct let table_name = "NAMING_LOCAL_CHANGES" let create_table_sqlite = Printf.sprintf " CREATE TABLE IF NOT EXISTS %s( ID INTEGER PRIMARY KEY, LOCAL_CHANGES BLOB NOT NULL, BASE_CONTENT_VERSION TEXT ); " table_name let insert_sqlite = Printf.sprintf " INSERT INTO %s (ID, LOCAL_CHANGES, BASE_CONTENT_VERSION) VALUES (0, ?, ?); " table_name let get_sqlite = Printf.sprintf " SELECT LOCAL_CHANGES, BASE_CONTENT_VERSION FROM %s; " table_name let prime db stmt_cache base_content_version = let insert_stmt = StatementCache.make_stmt stmt_cache insert_sqlite in let (blob : blob_format) = Relative_path.Map.empty in let empty = Marshal.to_string blob [Marshal.No_sharing] in Sqlite3.bind insert_stmt 1 (Sqlite3.Data.BLOB empty) |> check_rc db; Sqlite3.bind insert_stmt 2 (Sqlite3.Data.TEXT base_content_version) |> check_rc db; Sqlite3.step insert_stmt |> check_rc db let get stmt_cache = let get_stmt = StatementCache.make_stmt stmt_cache get_sqlite in match Sqlite3.step get_stmt with (* We don't include Sqlite3.Rc.DONE in this match because we always expect * exactly one row. *) | Sqlite3.Rc.ROW -> let local_changes_blob = column_blob get_stmt 0 in let (local_changes_saved : blob_format) = Marshal.from_string local_changes_blob 0 in let base_content_version = column_str get_stmt 1 in let file_deltas = Relative_path.Map.mapi local_changes_saved ~f:(fun path delta -> match delta with | Modified saved -> Modified (FileInfo.from_saved path saved) | Deleted -> Deleted) in if Relative_path.Map.cardinal file_deltas > 0 then HackEventLogger.naming_sqlite_local_changes_nonempty "get"; { base_content_version; file_deltas } | rc -> failwith (Printf.sprintf "Failure retrieving row: %s" (Sqlite3.Rc.to_string rc)) end module ChecksumTable = struct let create_table_sqlite = "CREATE TABLE IF NOT EXISTS CHECKSUM (ID INTEGER PRIMARY KEY, CHECKSUM_VALUE INTEGER NOT NULL);" let set db stmt_cache (checksum : Int64.t) : unit = let stmt = StatementCache.make_stmt stmt_cache "REPLACE INTO CHECKSUM (ID, CHECKSUM_VALUE) VALUES (0, ?);" in Sqlite3.bind stmt 1 (Sqlite3.Data.INT checksum) |> check_rc db; Sqlite3.step stmt |> check_rc db; () let get stmt_cache : Int64.t = let stmt = StatementCache.make_stmt stmt_cache "SELECT CHECKSUM_VALUE FROM CHECKSUM;" in match Sqlite3.step stmt with | Sqlite3.Rc.ROW -> column_int64 stmt 0 | rc -> failwith (Sqlite3.Rc.to_string rc) end (* These are just done as modules to keep the SQLite for related tables close together. *) module FileInfoTable = struct let table_name = "NAMING_FILE_INFO" let create_table_sqlite = Printf.sprintf " CREATE TABLE IF NOT EXISTS %s( FILE_INFO_ID INTEGER PRIMARY KEY AUTOINCREMENT, FILE_DIGEST TEXT, PATH_PREFIX_TYPE INTEGER NOT NULL, PATH_SUFFIX TEXT NOT NULL, TYPE_CHECKER_MODE INTEGER, DECL_HASH INTEGER, CLASSES TEXT, CONSTS TEXT, FUNS TEXT, TYPEDEFS TEXT, MODULES TEXT ); " table_name let create_index_sqlite = Printf.sprintf " CREATE UNIQUE INDEX IF NOT EXISTS FILE_INFO_PATH_IDX ON %s (PATH_SUFFIX, PATH_PREFIX_TYPE); " table_name let insert_sqlite = Printf.sprintf " INSERT INTO %s( PATH_PREFIX_TYPE, PATH_SUFFIX, TYPE_CHECKER_MODE, DECL_HASH, CLASSES, CONSTS, FUNS, TYPEDEFS, MODULES ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?); " table_name let delete_sqlite = Printf.sprintf " DELETE FROM %s WHERE PATH_PREFIX_TYPE = ? AND PATH_SUFFIX = ? " table_name let get_file_info_id_sqlite = Printf.sprintf " SELECT FILE_INFO_ID FROM %s WHERE PATH_PREFIX_TYPE = ? AND PATH_SUFFIX = ? " table_name let get_sqlite = Printf.sprintf " SELECT TYPE_CHECKER_MODE, DECL_HASH, CLASSES, CONSTS, FUNS, TYPEDEFS, MODULES FROM %s WHERE PATH_PREFIX_TYPE = ? AND PATH_SUFFIX = ?; " table_name let iter_sqlite = Printf.sprintf " SELECT PATH_PREFIX_TYPE, PATH_SUFFIX, TYPE_CHECKER_MODE, DECL_HASH, CLASSES, CONSTS, FUNS, TYPEDEFS, MODULES FROM %s ORDER BY PATH_PREFIX_TYPE, PATH_SUFFIX; " table_name let delete db stmt_cache relative_path = let prefix_type = Sqlite3.Data.INT (Int64.of_int (Relative_path.prefix_to_enum (Relative_path.prefix relative_path))) in let suffix = Sqlite3.Data.TEXT (Relative_path.suffix relative_path) in let delete_stmt = StatementCache.make_stmt stmt_cache delete_sqlite in Sqlite3.bind delete_stmt 1 prefix_type |> check_rc db; Sqlite3.bind delete_stmt 2 suffix |> check_rc db; Sqlite3.step delete_stmt |> check_rc db let insert db stmt_cache relative_path ~(type_checker_mode : FileInfo.mode option) ~(file_decls_hash : Int64.t option) ~(classes : FileInfo.id list) ~(consts : FileInfo.id list) ~(funs : FileInfo.id list) ~(typedefs : FileInfo.id list) ~(modules : FileInfo.id list) = let prefix_type = Sqlite3.Data.INT (Int64.of_int (Relative_path.prefix_to_enum (Relative_path.prefix relative_path))) in let suffix = Sqlite3.Data.TEXT (Relative_path.suffix relative_path) in let type_checker_mode = match type_checker_mode with | Some type_checker_mode -> Sqlite3.Data.INT (Int64.of_int (FileInfo.mode_to_enum type_checker_mode)) | None -> Sqlite3.Data.NULL in let file_decls_hash = match file_decls_hash with | Some file_decls_hash -> Sqlite3.Data.INT file_decls_hash | None -> Sqlite3.Data.NULL in let names_to_data_type names = let open Core in let names = String.concat ~sep:"|" (List.map names ~f:(fun (_, x, _) -> x)) in match String.length names with | 0 -> Sqlite3.Data.NULL | _ -> Sqlite3.Data.TEXT names in let insert_stmt = StatementCache.make_stmt stmt_cache insert_sqlite in Sqlite3.bind insert_stmt 1 prefix_type |> check_rc db; Sqlite3.bind insert_stmt 2 suffix |> check_rc db; Sqlite3.bind insert_stmt 3 type_checker_mode |> check_rc db; Sqlite3.bind insert_stmt 4 file_decls_hash |> check_rc db; Sqlite3.bind insert_stmt 5 (names_to_data_type classes) |> check_rc db; Sqlite3.bind insert_stmt 6 (names_to_data_type consts) |> check_rc db; Sqlite3.bind insert_stmt 7 (names_to_data_type funs) |> check_rc db; Sqlite3.bind insert_stmt 8 (names_to_data_type typedefs) |> check_rc db; Sqlite3.bind insert_stmt 9 (names_to_data_type modules) |> check_rc db; Sqlite3.step insert_stmt |> check_rc db let read_row ~stmt ~path ~base_index = let file_mode = let open Option in Int64.to_int (column_int64 stmt base_index) >>= FileInfo.mode_of_enum in let hash = Some (column_int64 stmt (base_index + 1)) in let to_ids ~value ~name_type = match value with | Sqlite3.Data.TEXT s -> Core.( List.map (String.split s ~on:'|') ~f:(fun name -> (FileInfo.File (name_type, path), name, None))) | Sqlite3.Data.NULL -> [] | _ -> failwith "Unexpected column type when retrieving names" in let classes = to_ids ~value:(Sqlite3.column stmt (base_index + 2)) ~name_type:FileInfo.Class in let consts = to_ids ~value:(Sqlite3.column stmt (base_index + 3)) ~name_type:FileInfo.Const in let funs = to_ids ~value:(Sqlite3.column stmt (base_index + 4)) ~name_type:FileInfo.Fun in let typedefs = to_ids ~value:(Sqlite3.column stmt (base_index + 5)) ~name_type:FileInfo.Typedef in let modules = to_ids ~value:(Sqlite3.column stmt (base_index + 6)) ~name_type:FileInfo.Module in FileInfo. { hash; file_mode; funs; classes; typedefs; consts; modules; comments = None; } let get_file_info db stmt_cache path = let get_stmt = StatementCache.make_stmt stmt_cache get_sqlite in let prefix_type = Relative_path.prefix_to_enum (Relative_path.prefix path) in let suffix = Relative_path.suffix path in Sqlite3.bind get_stmt 1 (Sqlite3.Data.INT (Int64.of_int prefix_type)) |> check_rc db; Sqlite3.bind get_stmt 2 (Sqlite3.Data.TEXT suffix) |> check_rc db; match Sqlite3.step get_stmt with | Sqlite3.Rc.DONE -> None | Sqlite3.Rc.ROW -> Some (read_row ~stmt:get_stmt ~path ~base_index:0) | rc -> failwith (Printf.sprintf "Failure retrieving row: %s" (Sqlite3.Rc.to_string rc)) let get_file_info_id db stmt_cache path = let get_stmt = StatementCache.make_stmt stmt_cache get_file_info_id_sqlite in let prefix_type = Relative_path.prefix_to_enum (Relative_path.prefix path) in let suffix = Relative_path.suffix path in Sqlite3.bind get_stmt 1 (Sqlite3.Data.INT (Int64.of_int prefix_type)) |> check_rc db; Sqlite3.bind get_stmt 2 (Sqlite3.Data.TEXT suffix) |> check_rc db; match Sqlite3.step get_stmt with | Sqlite3.Rc.DONE -> None | Sqlite3.Rc.ROW -> Some (column_int64 get_stmt 0) | rc -> failwith (Printf.sprintf "Failure retrieving row: %s" (Sqlite3.Rc.to_string rc)) let fold stmt_cache ~init ~f = let iter_stmt = StatementCache.make_stmt stmt_cache iter_sqlite in let f iter_stmt acc = let prefix_int = column_int64 iter_stmt 0 in let suffix = column_str iter_stmt 1 in let path = make_relative_path ~prefix_int ~suffix in let fi = read_row ~stmt:iter_stmt ~path ~base_index:2 in f path fi acc in fold_sqlite iter_stmt ~f ~init end module SymbolTable = struct let table_name = "NAMING_SYMBOLS" let create_table_sqlite = (* CANON_HASH is the hash of the lowercase form of the name (even for consts which don't need it) *) (* FLAGS comes from Naming_types.name_kind *) Printf.sprintf " CREATE TABLE IF NOT EXISTS %s( HASH INTEGER PRIMARY KEY NOT NULL, CANON_HASH INTEGER NOT NULL, DECL_HASH INTEGER NOT NULL, FLAGS INTEGER NOT NULL, FILE_INFO_ID INTEGER NOT NULL ); " table_name let create_index_sqlite = Printf.sprintf " CREATE INDEX IF NOT EXISTS TYPES_CANON ON %s (CANON_HASH); " table_name let create_temporary_index_sqlite = Printf.sprintf " CREATE INDEX IF NOT EXISTS SYMBOLS_FILE_INFO_ID ON %s (FILE_INFO_ID); " table_name let drop_temporary_index_sqlite = Printf.sprintf " DROP INDEX SYMBOLS_FILE_INFO_ID; " let insert_sqlite = Printf.sprintf " INSERT INTO %s( HASH, CANON_HASH, DECL_HASH, FLAGS, FILE_INFO_ID) VALUES (?, ?, ?, ?, ?); " table_name let delete_sqlite = Printf.sprintf " DELETE FROM %s WHERE FILE_INFO_ID = ? " table_name let (get_sqlite, get_sqlite_case_insensitive) = let base = Str.global_replace (Str.regexp "{table_name}") table_name " SELECT NAMING_FILE_INFO.PATH_PREFIX_TYPE, NAMING_FILE_INFO.PATH_SUFFIX, {table_name}.FLAGS, {table_name}.DECL_HASH FROM {table_name} LEFT JOIN NAMING_FILE_INFO ON {table_name}.FILE_INFO_ID = NAMING_FILE_INFO.FILE_INFO_ID WHERE {table_name}.{hash} = ?" in ( Str.global_replace (Str.regexp "{hash}") "HASH" base, Str.global_replace (Str.regexp "{hash}") "CANON_HASH" base ) let delete db stmt_cache file_info_id = let delete_stmt = StatementCache.make_stmt stmt_cache delete_sqlite in Sqlite3.bind delete_stmt 1 (Sqlite3.Data.INT file_info_id) |> check_rc db; Sqlite3.step delete_stmt |> check_rc db (** Note: name parameter is used solely for debugging; it's only the hash and canon_hash that get inserted. *) let insert db stmt_cache ~name ~hash ~canon_hash ~name_kind ~file_info_id ~decl_hash : (unit, insertion_error) result = insert_safe ~name ~name_kind ~hash ~canon_hash @@ fun () -> let flags = name_kind |> Naming_types.name_kind_to_enum |> Int64.of_int in let insert_stmt = StatementCache.make_stmt stmt_cache insert_sqlite in Sqlite3.bind insert_stmt 1 (Sqlite3.Data.INT hash) |> check_rc db; Sqlite3.bind insert_stmt 2 (Sqlite3.Data.INT canon_hash) |> check_rc db; Sqlite3.bind insert_stmt 3 (Sqlite3.Data.INT decl_hash) |> check_rc db; Sqlite3.bind insert_stmt 4 (Sqlite3.Data.INT flags) |> check_rc db; Sqlite3.bind insert_stmt 5 (Sqlite3.Data.INT file_info_id) |> check_rc db; Sqlite3.step insert_stmt |> check_rc db let get db stmt_cache dep stmt = let hash = dep |> Typing_deps.Dep.to_int64 in let get_stmt = StatementCache.make_stmt stmt_cache stmt in Sqlite3.bind get_stmt 1 (Sqlite3.Data.INT hash) |> check_rc db; match Sqlite3.step get_stmt with | Sqlite3.Rc.DONE -> None | Sqlite3.Rc.ROW -> let prefix_type = column_int64 get_stmt 0 in let suffix = column_str get_stmt 1 in let flag = Option.value_exn (column_int64 get_stmt 2 |> Int64.to_int) in let decl_hash = column_int64 get_stmt 3 |> Int64.to_string in let name_kind = Option.value_exn (flag |> Naming_types.name_kind_of_enum) in Some ( make_relative_path ~prefix_int:prefix_type ~suffix, name_kind, decl_hash ) | rc -> failwith (Printf.sprintf "Failure retrieving row: %s" (Sqlite3.Rc.to_string rc)) let get_symbols_and_decl_hashes_for_file_id db stmt_cache (file_info_id : Int64.t) : symbol_and_decl_hash list = let sqlite = Printf.sprintf "SELECT HASH, DECL_HASH FROM %s WHERE FILE_INFO_ID = ?" table_name in let stmt = StatementCache.make_stmt stmt_cache sqlite in Sqlite3.bind stmt 1 (Sqlite3.Data.INT file_info_id) |> check_rc db; fold_sqlite stmt ~init:[] ~f:(fun iter_stmt acc -> let symbol = column_int64 iter_stmt 0 in let decl_hash = column_int64 iter_stmt 1 in { symbol; decl_hash } :: acc) end let db_cache : [ `Not_yet_cached | `Cached of (db_path * Sqlite3.db * StatementCache.t) option ] ref = ref `Not_yet_cached let open_db (Db_path path) : Sqlite3.db = let db = Sqlite3.db_open path in Sqlite3.exec db "PRAGMA synchronous = OFF;" |> check_rc db; Sqlite3.exec db "PRAGMA journal_mode = MEMORY;" |> check_rc db; db let get_db_and_stmt_cache (path : db_path) : Sqlite3.db * StatementCache.t = match !db_cache with | `Cached (Some (existing_path, db, stmt_cache)) when equal_db_path path existing_path -> (db, stmt_cache) | _ -> let db = open_db path in let stmt_cache = StatementCache.make ~db in db_cache := `Cached (Some (path, db, stmt_cache)); (db, stmt_cache) let validate_can_open_db (db_path : db_path) : unit = (* sqlite is entirely happy opening a non-existent file; all it does is touches the file (giving it zero size) and reports that the file doesn't contain any tables. Here we catch the zero-size case as well as the file-not-found case, so we're robust against accidental sqlite touching prior to this function. *) let (Db_path path) = db_path in let exists = try (Unix.stat path).Unix.st_size > 0 with | exn -> Hh_logger.log "opening naming-table sqlite: %s" (Exn.to_string exn); false in if not exists then failwith "naming-table sqlite absent or empty"; let (_ : Sqlite3.db * StatementCache.t) = get_db_and_stmt_cache db_path in () let free_db_cache () : unit = db_cache := `Not_yet_cached let save_file_info db stmt_cache relative_path checksum file_info : save_result = let open Core in FileInfoTable.insert db stmt_cache relative_path ~type_checker_mode:file_info.FileInfo.file_mode ~file_decls_hash:file_info.FileInfo.hash ~consts:file_info.FileInfo.consts ~classes:file_info.FileInfo.classes ~funs:file_info.FileInfo.funs ~typedefs:file_info.FileInfo.typedefs ~modules:file_info.FileInfo.modules; let file_info_id = ref None in Sqlite3.exec_not_null_no_headers db "SELECT last_insert_rowid()" ~cb:(fun row -> match row with | [| row_id |] -> file_info_id := Some (Int64.of_string row_id) | [||] -> failwith "Got no columns when querying last inserted row ID" | _ -> failwith "Got too many columns when querying last inserted row ID") |> check_rc db; let file_info_id = match !file_info_id with | Some id -> id | None -> failwith "Could not get last inserted row ID" in let insert ~name_kind ~dep_ctor (symbols_inserted, errors, checksum) (_pos, name, decl_hash) = let decl_hash = Option.value decl_hash ~default:Int64.zero in let hash = name |> dep_ctor |> Typing_deps.Dep.make |> Typing_deps.Dep.to_int64 in let canon_hash = name |> to_canon_name_key |> dep_ctor |> Typing_deps.Dep.make |> Typing_deps.Dep.to_int64 in let checksum : Int64.t = checksum_addremove checksum ~symbol:hash ~decl_hash ~path:relative_path in match SymbolTable.insert db stmt_cache ~name ~name_kind ~hash ~canon_hash ~file_info_id ~decl_hash with | Ok () -> (symbols_inserted + 1, errors, checksum) | Error error -> (symbols_inserted, error :: errors, checksum) in let results = (0, [], checksum) in let results = List.fold file_info.FileInfo.funs ~init:results ~f: (insert ~name_kind:Naming_types.Fun_kind ~dep_ctor:(fun name -> Typing_deps.Dep.Fun name)) in let results = List.fold file_info.FileInfo.classes ~init:results ~f: (insert ~name_kind:Naming_types.(Type_kind TClass) ~dep_ctor:(fun name -> Typing_deps.Dep.Type name)) in let results = List.fold file_info.FileInfo.typedefs ~init:results ~f: (insert ~name_kind:Naming_types.(Type_kind TTypedef) ~dep_ctor:(fun name -> Typing_deps.Dep.Type name)) in let results = List.fold file_info.FileInfo.consts ~init:results ~f: (insert ~name_kind:Naming_types.Const_kind ~dep_ctor:(fun name -> Typing_deps.Dep.GConst name)) in let results = List.fold file_info.FileInfo.modules ~init:results ~f: (insert ~name_kind:Naming_types.Module_kind ~dep_ctor:(fun name -> Typing_deps.Dep.Module name)) in let (symbols_added, errors, checksum) = results in { files_added = 1; symbols_added; errors; checksum } let save_file_infos db_name file_info_map ~base_content_version = let db = Sqlite3.db_open db_name in let stmt_cache = StatementCache.make ~db in Sqlite3.exec db "BEGIN TRANSACTION;" |> check_rc db; try Sqlite3.exec db LocalChanges.create_table_sqlite |> check_rc db; Sqlite3.exec db FileInfoTable.create_table_sqlite |> check_rc db; Sqlite3.exec db SymbolTable.create_table_sqlite |> check_rc db; Sqlite3.exec db ChecksumTable.create_table_sqlite |> check_rc db; (* Incremental updates only update the single row in this table, so we need * to write in some dummy data to start. *) LocalChanges.prime db stmt_cache base_content_version; let save_result = Relative_path.Map.fold file_info_map ~init:(empty_save_result ~checksum:Int64.zero) ~f:(fun path file_info acc -> let per_file = save_file_info db stmt_cache path acc.checksum file_info in { files_added = acc.files_added + per_file.files_added; symbols_added = acc.symbols_added + per_file.symbols_added; errors = List.rev_append acc.errors per_file.errors; checksum = per_file.checksum; }) in ChecksumTable.set db stmt_cache save_result.checksum; Sqlite3.exec db FileInfoTable.create_index_sqlite |> check_rc db; Sqlite3.exec db SymbolTable.create_index_sqlite |> check_rc db; Sqlite3.exec db "END TRANSACTION;" |> check_rc db; StatementCache.close stmt_cache; if not @@ Sqlite3.db_close db then failwith @@ Printf.sprintf "Could not close database at %s" db_name; save_result with | exn -> let e = Exception.wrap exn in Sqlite3.exec db "END TRANSACTION;" |> check_rc db; Exception.reraise e let copy_and_update ~(existing_db : db_path) ~(new_db : db_path) (local_changes : local_changes) : save_result = let (Db_path existing_path, Db_path new_path) = (existing_db, new_db) in FileUtil.cp ~force:(FileUtil.Ask (fun _ -> false)) [existing_path] new_path; let new_db = open_db new_db in let stmt_cache = StatementCache.make ~db:new_db in Sqlite3.exec new_db "BEGIN TRANSACTION;" |> check_rc new_db; Sqlite3.exec new_db SymbolTable.create_temporary_index_sqlite |> check_rc new_db; (* Our update plan is to use two phases: (1) go through every single file that has been changed in any way and delete the old entries, (2) go through every file and add the updated entries if any. First step is to gather from the database the FILE_INFO_ID of every old file... *) let old_files : (Relative_path.t * Int64.t) list = List.filter_map (Relative_path.Map.elements local_changes.file_deltas) ~f:(fun (path, _delta) -> match FileInfoTable.get_file_info_id new_db stmt_cache path with | None -> None | Some file_info_id -> Some (path, file_info_id)) in (* Checksum: phase 1 is to remove from the checksum every item which used to be there in the old entries. We've read the forward-naming-table to read which symbols used to be there, and now we read the reverse-naming-table to read what decl-hashes they used to have. This has to be done before any of those old symbols have yet been removed! *) let checksum = ChecksumTable.get stmt_cache in let checksum = List.fold old_files ~init:checksum ~f:(fun checksum (path, file_info_id) -> let symbols_and_decl_hashes = SymbolTable.get_symbols_and_decl_hashes_for_file_id new_db stmt_cache file_info_id in let checksum = List.fold symbols_and_decl_hashes ~init:checksum ~f:(fun checksum { symbol; decl_hash } -> checksum_addremove checksum ~symbol ~decl_hash ~path) in checksum) in (* Symbols: phase 1 is to remove from forward and reverse naming table every symbol which used to be there. Our strategy here is to read the forward-naming-table to learn the FILE_INFO_ID, and then bulk delete all entries from the reverse-naming-table which have this same FILE_INFO_ID. (The reverse table isn't indexed by FILE_INFO_ID, which is why we had to create a temporary index for it. It would have been more efficient to get ToplevelSymbolHash from the forward naming table and remove by that, since the reverse naming table is already indexed by ToplevelSymbolHash. *) List.iter old_files ~f:(fun (path, file_info_id) -> SymbolTable.delete new_db stmt_cache file_info_id; FileInfoTable.delete new_db stmt_cache path; ()); (* Symbols: phase 2 is to add forward and reverse entries for every item in file_deltas. Note: if we tried to combine phases 1 and 2, then in the case of symbol X being moved from b.php to a.php, we might have done local-change b.php first and tried to add X->b.php, even before X->a.php had been deleted. That would have lead to a duplicate primary key violation. By doing it in two phases we avoid that problem. (Of course if someone adds a duplicate entry then that truly will result in a duplicate primary key violation.) Checksum: phase 2 is to add to the checksum every symbol in file_deltas. This would give incorrect answers in case of duplicate symbol definitions (since the checksum is only meant to include the winner) but symbols phase 2 would already have already raised a sqlite duplicate violation if there were any duplicate symbol definitions. *) let result = Relative_path.Map.fold local_changes.file_deltas ~init:(empty_save_result ~checksum) ~f:(fun path file_info acc -> match file_info with | Deleted -> acc | Modified file_info -> let per_file = save_file_info new_db stmt_cache path acc.checksum file_info in { files_added = acc.files_added + per_file.files_added; symbols_added = acc.symbols_added + per_file.symbols_added; errors = List.rev_append acc.errors per_file.errors; checksum = per_file.checksum; }) in ChecksumTable.set new_db stmt_cache result.checksum; Sqlite3.exec new_db "END TRANSACTION;" |> check_rc new_db; StatementCache.close stmt_cache; Sqlite3.exec new_db SymbolTable.drop_temporary_index_sqlite |> check_rc new_db; (* This reclaims space after deleting the index *) Sqlite3.exec new_db "VACUUM;" |> check_rc new_db; result let get_local_changes (db_path : db_path) : local_changes = let (_db, stmt_cache) = get_db_and_stmt_cache db_path in LocalChanges.get stmt_cache let fold ?(warn_on_naming_costly_iter = true) ~(db_path : db_path) ~init ~f ~file_deltas = let start_t = Unix.gettimeofday () in (* We depend on [Relative_path.Map.bindings] returning results in increasing * order here. *) let sorted_changes = Relative_path.Map.bindings file_deltas in (* This function looks kind of funky, but it's not too terrible when * explained. We essentially have two major inputs: * 1. a path and file info that we got from SQLite. In order for this * function to work properly, we require that consecutive invocations * of this function within the same [fold] call have paths that are * strictly increasing. * 2. the list of local changes. This list is also required to be in * increasing sorted order. * In order to make sure that we a) return results in sorted order, and * b) properly handle files that have been added (and therefore will never * show up in the [path] and [fi] args), we essentially walk both lists in * sorted order (walking the SQLite list through successive invocations and * walking the local changes list through recursion), at each step folding * over whichever entry has the lowest sort order. If both paths are * identical, we use the one from our local changes. In this way we get O(n) * iteration while handling additions, modifications, and deletions * properly (again, given our input sorting restraints). *) let rec consume_sorted_changes path fi (sorted_changes, acc) = match sorted_changes with | hd :: tl when Relative_path.compare (fst hd) path < 0 -> begin match snd hd with | Modified local_fi -> consume_sorted_changes path fi (tl, f (fst hd) local_fi acc) | Deleted -> consume_sorted_changes path fi (tl, acc) end | hd :: tl when Relative_path.equal (fst hd) path -> begin match snd hd with | Modified fi -> (tl, f path fi acc) | Deleted -> (tl, acc) end | _ -> (sorted_changes, f path fi acc) in let (_db, stmt_cache) = get_db_and_stmt_cache db_path in let (remaining_changes, acc) = FileInfoTable.fold stmt_cache ~init:(sorted_changes, init) ~f:consume_sorted_changes in let acc = List.fold_left ~f: begin fun acc (path, delta) -> match delta with | Modified fi -> f path fi acc | Deleted -> (* This probably shouldn't happen? *) acc end ~init:acc remaining_changes in if warn_on_naming_costly_iter then begin Hh_logger.log "NAMING_COSTLY_ITER\n%s" (Exception.get_current_callstack_string 99 |> Exception.clean_stack); HackEventLogger.naming_costly_iter ~start_t end; acc let get_file_info (db_path : db_path) path = let (db, stmt_cache) = get_db_and_stmt_cache db_path in FileInfoTable.get_file_info db stmt_cache path (* Same as `get_db_and_stmt_cache` but with logging for when opening the database fails. *) let sqlite_exn_wrapped_get_db_and_stmt_cache db_path name = try get_db_and_stmt_cache db_path with | Sqlite3.Error _ as exn -> let e = Exception.wrap exn in Hh_logger.info "Sqlite_db_open_bug: couldn't open the DB at `%s` while getting the position of `%s`" (show_db_path db_path) name; Exception.reraise e let get_type_wrapper (result : (Relative_path.t * Naming_types.name_kind * string) option) : (Relative_path.t * Naming_types.kind_of_type) option = match result with | None -> None | Some (filename, Naming_types.Type_kind kind_of_type, _) -> Some (filename, kind_of_type) | Some (_, _, _) -> failwith "wrong symbol kind" let get_fun_wrapper (result : (Relative_path.t * Naming_types.name_kind * string) option) : Relative_path.t option = match result with | None -> None | Some (filename, Naming_types.Fun_kind, _) -> Some filename | Some (_, _, _) -> failwith "wrong symbol kind" let get_const_wrapper (result : (Relative_path.t * Naming_types.name_kind * string) option) : Relative_path.t option = match result with | None -> None | Some (filename, Naming_types.Const_kind, _) -> Some filename | Some (_, _, _) -> failwith "wrong symbol kind" let get_module_wrapper (result : (Relative_path.t * Naming_types.name_kind * string) option) : Relative_path.t option = match result with | None -> None | Some (filename, Naming_types.Module_kind, _) -> Some filename | Some (_, _, _) -> failwith "wrong symbol kind" let get_decl_hash_wrapper (result : (Relative_path.t * Naming_types.name_kind * string) option) : string option = match result with | None -> None | Some (_, _, decl_hash) -> Some decl_hash let get_type_path_by_name (db_path : db_path) name = let (db, stmt_cache) = sqlite_exn_wrapped_get_db_and_stmt_cache db_path name in SymbolTable.get db stmt_cache (Typing_deps.Dep.Type name |> Typing_deps.Dep.make) SymbolTable.get_sqlite |> get_type_wrapper let get_itype_path_by_name (db_path : db_path) name = let (db, stmt_cache) = sqlite_exn_wrapped_get_db_and_stmt_cache db_path name in SymbolTable.get db stmt_cache (Typing_deps.Dep.Type (Caml.String.lowercase_ascii name) |> Typing_deps.Dep.make) SymbolTable.get_sqlite_case_insensitive |> get_type_wrapper let get_fun_path_by_name (db_path : db_path) name = let (db, stmt_cache) = get_db_and_stmt_cache db_path in SymbolTable.get db stmt_cache (Typing_deps.Dep.Fun name |> Typing_deps.Dep.make) SymbolTable.get_sqlite |> get_fun_wrapper let get_ifun_path_by_name (db_path : db_path) name = let (db, stmt_cache) = get_db_and_stmt_cache db_path in SymbolTable.get db stmt_cache (Typing_deps.Dep.Fun (Caml.String.lowercase_ascii name) |> Typing_deps.Dep.make) SymbolTable.get_sqlite_case_insensitive |> get_fun_wrapper let get_const_path_by_name (db_path : db_path) name = let (db, stmt_cache) = get_db_and_stmt_cache db_path in SymbolTable.get db stmt_cache (Typing_deps.Dep.GConst name |> Typing_deps.Dep.make) SymbolTable.get_sqlite |> get_const_wrapper let get_module_path_by_name (db_path : db_path) name = let (db, stmt_cache) = get_db_and_stmt_cache db_path in SymbolTable.get db stmt_cache (Typing_deps.Dep.Module name |> Typing_deps.Dep.make) SymbolTable.get_sqlite |> get_module_wrapper let get_path_by_64bit_dep (db_path : db_path) (dep : Typing_deps.Dep.t) = let (db, stmt_cache) = get_db_and_stmt_cache db_path in SymbolTable.get db stmt_cache dep SymbolTable.get_sqlite |> Option.map ~f:(function (first, second, _) -> (first, second)) let get_decl_hash_by_64bit_dep (db_path : db_path) (dep : Typing_deps.Dep.t) = let (db, stmt_cache) = get_db_and_stmt_cache db_path in SymbolTable.get db stmt_cache dep SymbolTable.get_sqlite |> get_decl_hash_wrapper
OCaml Interface
hhvm/hphp/hack/src/naming/naming_sqlite.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 db_path = Db_path of string [@@deriving show] type insertion_error = { canon_hash: Int64.t; hash: Int64.t; name_kind: Naming_types.name_kind; name: string; origin_exception: Exception.t; [@printer (fun fmt e -> fprintf fmt "%s" (Exception.get_ctor_string e))] } [@@deriving show] type save_result = { files_added: int; symbols_added: int; errors: insertion_error list; checksum: Int64.t; } [@@deriving show] type 'a forward_naming_table_delta = | Modified of 'a | Deleted [@@deriving show] type file_deltas = FileInfo.t forward_naming_table_delta Relative_path.Map.t type local_changes = { file_deltas: file_deltas; base_content_version: string; } [@@deriving show] val validate_can_open_db : db_path -> unit val free_db_cache : unit -> unit val save_file_infos : string -> FileInfo.t Relative_path.Map.t -> base_content_version:string -> save_result val copy_and_update : existing_db:db_path -> new_db:db_path -> local_changes -> save_result val get_local_changes : db_path -> local_changes val fold : ?warn_on_naming_costly_iter:bool -> db_path:db_path -> init:'a -> f:(Relative_path.t -> FileInfo.t -> 'a -> 'a) -> file_deltas:file_deltas -> 'a val get_file_info : db_path -> Relative_path.t -> FileInfo.t option val get_path_by_64bit_dep : db_path -> Typing_deps.Dep.t -> (Relative_path.t * Naming_types.name_kind) option val get_decl_hash_by_64bit_dep : db_path -> Typing_deps.Dep.t -> string option val get_type_path_by_name : db_path -> string -> (Relative_path.t * Naming_types.kind_of_type) option val get_itype_path_by_name : db_path -> string -> (Relative_path.t * Naming_types.kind_of_type) option val get_fun_path_by_name : db_path -> string -> Relative_path.t option val get_ifun_path_by_name : db_path -> string -> Relative_path.t option val get_const_path_by_name : db_path -> string -> Relative_path.t option val get_module_path_by_name : db_path -> string -> Relative_path.t option (** The canonical name (and assorted *Canon heaps) store the canonical name for a symbol, keyed off of the lowercase version of its name. We use the canon heaps to check for symbols which are redefined using different capitalizations so we can throw proper Hack errors for them. *) val to_canon_name_key : string -> string
OCaml
hhvm/hphp/hack/src/naming/naming_table.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude (** +---------------------------------+ | Let's talk about naming tables! | +---------------------------------+ Every typechecker or compiler that's more complicated than a toy project needs some way to look up the location of a given symbol, especially one that operates at the same scale as Hack and double especially as Hack moves towards generating data lazily on demand instead of generating all of the data up front during strictly defined typechecking phases. In Hack, the data structures that map from symbols to filenames and from filenames to symbol names are referred to as the "naming table," with the "forward naming table" mapping from filenames to symbol names and the "reverse naming table" mapping from symbol names to file names. We store the forward naming table as a standard OCaml map since we only read and write it from the main process, and we store the reverse naming table in shared memory since we want to allow rapid reads and writes from worker processes. So, to recap: - Forward naming table: OCaml map, maps filename -> symbols in file - Reverse naming table: shared memory, maps symbol name to filename it's defined in Seems simple enough, right? Unfortunately, this is where the real world and all of its attendant complexity comes in. The naming table (forward + reverse) is big. And not only is it big, its size is on the order of O(repo). This conflicts with our goal of making Hack use a flat amount of memory regardless of the amount of code we're actually typechecking, so it needs to go. In this case, we've chosen to use our existing saved state infrastructure and dump the naming table to a SQLite file which we can use to serve queries without having to store anything in memory other than just the differences between what's in the saved state and what's on disk. Right now, only the reverse naming table supports falling back to SQLite, so let's go through each operation that the reverse naming table supports and cover how it handles falling back to SQLite. +---------------------------------+ | Reverse naming table operations | +---------------------------------+ The reverse naming table supports three operations: [put], [get], and [delete]. [Put] is pretty simple, conceptually, but there's some trickiness with [delete] that would benefit from being covered in more detail, and that trickiness bleeds into how [get] works as well. One important consideration is that *the SQLite database is read-only.* The general idea of these operations is that shared memory stores only entries that have changed. PUT: [Put] is simple. Since the SQLite database is read-only and we use shared memory for storing any changes, we just put the value in shared memory. +------------------+ +------------+ | | | | | Naming Heap | | SQLite | | | | | [put key value] -----> [put key value] | | | | | | | +------------------+ +------------+ DELETE: We're going to cover [delete] next because it's the only reason that [get] has any complexity beyond "look for the value in shared memory and if it's not there look for it in SQLite." At first glance, [delete] doesn't seem too difficult. Just delete the entry from shared memory, right? Well, that's fine... unless that key also exists in SQLite. If the value is in SQLite, then all that deleting it from shared memory does is make us start returning the stored SQLite value! This is bad, because if we just deleted a key of course we want [get] operations for it to return [None]. But okay, we can work around that. Instead of storing direct values in shared memory, we'll store an enum of [[Added of 'a | Deleted]]. Easy peasy! ...except what do we do if we want to delete a value in the main process, then add it again in a worker process? That would require changing a key's value in shared memory, which is something that we don't support due to data integrity concerns with multiple writers and readers. We could remove and re-add, except removal can only be done by master because of the same integrity concerns. So master would somehow need to know which entries will be added and prematurely remove the [Deleted] sentinel from them. This is difficult enough as to be effectively impossible. So what we're left needing is some way to delete values which can be undone by child processes, which means that undeleting a value needs to consist only of [add] operations to shared memory, and have no dependency on [remove]. Enter: the blocked entries heap. For each of the reverse naming table heaps (types, functions, and constants) we also create a heap that only stores values of a single-case enum: [Blocked]. The crucial difference between [Blocked] and [[Added of 'a | Deleted]] is that *we only check for [Blocked] if the value is not in the shared memory naming heap.* This means that we can effectively undelete an entry by using an only an [add] operation. Exactly what we need! Thus, [delete] becomes: +-----------------+ +---------------------+ +------------+ | | | | | | | Naming Heap | | Blocked Entries | | SQLite | | | | | | | [delete key] --+-----> [delete key] | | | | | | | | | | | | +----------------------------> [add key Blocked] | | | | | | | | | +-----------------+ +---------------------+ +------------+ GET: Wow, what a ride, huh? Now that we know how to add and remove entries, let's make this actually useful and talk about how to read them! The general idea is that we first check to see if the value is in the shared memory naming heap. If so, we can return that immediately. If it's not in the naming heap, then we check to see if it's blocked. If it is, we immediately return [None]. If it's not in the naming heap, and it's not in the blocked entries, then and only then do we read the value from SQLite: +-----------------+ +---------------------+ +------------------+ | | | | | | | Naming Heap | | Blocked Entries | | SQLite | | | | | | | [get key] -----------> [get key] is: | | | | | [Some value] <---------- [Some value] | | | | | | [None] -------+ | | | | | | \ | | | | | | +--> [get key] is: | | | [None] <--------------------------------------- [Some Blocked] | | | | | | [None] -----------+ | | | | | | \ | | | | | | +--> [get key] is: | [Some value] <------------------------------------------------------------ [Some value] | [None] <------------------------------------------------------------------ [None] | | | | | | | +-----------------+ +---------------------+ +------------------+ And we're done! I hope this was easy to understand and as fun to read as it was to write :) MINUTIAE: Q: When do we delete entries from the Blocked Entries heaps? A: Never! Once an entry has been removed at least once we never want to retrieve the SQLite version for the rest of the program execution. Q: Won't we just end up with a heap full of [Blocked] entries now? A: Not really. We only have to do deletions once to remove entries for dirty files, and after that it's not a concern. Plus [Blocked] entries are incredibly small in shared memory (although they do still occupy a hash slot). *) (* Changes since baseline can be None if there was no baseline to begin with. The scenario where we apply changes since baseline instead of relying on the packaged local changes in the LOCAL_CHANGES table is this: 1) Load the naming table baseline (may include local changes if it was incrementally updated at some point - not currently done in practice, but possible and likely to happen in the future) 2) Load the changes since baseline that include naming changes processed at another time (perhaps, on another host) In the scenario where the naming table is saved to SQLite from an Unbacked naming table, there is no baseline to speak of *) type changes_since_baseline = Naming_sqlite.local_changes option type t = | Unbacked of FileInfo.t Relative_path.Map.t | Backed of Naming_sqlite.local_changes * Naming_sqlite.db_path [@@deriving show] type defs_per_file = FileInfo.names Relative_path.Map.t [@@deriving show] type saved_state_info = FileInfo.saved Relative_path.Map.t (*****************************************************************************) (* Forward naming table functions *) (*****************************************************************************) let empty = Unbacked Relative_path.Map.empty let filter a ~f = match a with | Unbacked a -> Unbacked (Relative_path.Map.filter a ~f) | Backed (local_changes, db_path) -> let file_deltas = local_changes.Naming_sqlite.file_deltas in Backed ( { local_changes with Naming_sqlite.file_deltas = Naming_sqlite.fold ~warn_on_naming_costly_iter:true ~db_path ~init:file_deltas ~f: begin fun path fi acc -> if f path fi then acc else Relative_path.Map.add acc ~key:path ~data:Naming_sqlite.Deleted end ~file_deltas; }, db_path ) let fold ?(warn_on_naming_costly_iter = true) a ~init ~f = match a with | Unbacked a -> Relative_path.Map.fold a ~init ~f | Backed (local_changes, db_path) -> Naming_sqlite.fold ~warn_on_naming_costly_iter ~db_path ~init ~f ~file_deltas:local_changes.Naming_sqlite.file_deltas let get_files a = match a with | Unbacked a -> Relative_path.Map.keys a | Backed (local_changes, db_path) -> (* Reverse at the end to preserve ascending sort order. *) Naming_sqlite.fold ~warn_on_naming_costly_iter:true ~db_path ~init:[] ~f:(fun path _ acc -> path :: acc) ~file_deltas:local_changes.Naming_sqlite.file_deltas |> List.rev let get_files_changed_since_baseline (changes_since_baseline : changes_since_baseline) : Relative_path.t list = match changes_since_baseline with | Some changes_since_baseline -> Relative_path.Map.keys changes_since_baseline.Naming_sqlite.file_deltas | None -> [] let get_file_info a key = match a with | Unbacked a -> Relative_path.Map.find_opt a key | Backed (local_changes, db_path) -> (match Relative_path.Map.find_opt local_changes.Naming_sqlite.file_deltas key with | Some (Naming_sqlite.Modified fi) -> Some fi | Some Naming_sqlite.Deleted -> None | None -> Naming_sqlite.get_file_info db_path key) exception File_info_not_found let get_file_info_unsafe a key = match get_file_info a key with | Some info -> info | None -> raise File_info_not_found let get_64bit_dep_set_files (naming_table : t) (deps : Typing_deps.DepSet.t) : Relative_path.Set.t = match naming_table with | Unbacked _ -> failwith "get_64bit_dep_set_files not supported for unbacked naming tables. Use Typing_deps.get_ifiles instead." | Backed (local_changes, db_path) -> let base_results = Typing_deps.DepSet.fold deps ~init:Relative_path.Set.empty ~f:(fun dep acc -> match Naming_sqlite.get_path_by_64bit_dep db_path dep with | None -> acc | Some (file, _namekind) -> Relative_path.Set.add acc file) in Relative_path.Map.fold local_changes.Naming_sqlite.file_deltas ~init:base_results ~f:(fun path file_info acc -> match file_info with | Naming_sqlite.Deleted -> Relative_path.Set.remove acc path | Naming_sqlite.Modified file_info -> let file_deps = Typing_deps.deps_of_file_info file_info |> Typing_deps.DepSet.of_list in if not (Typing_deps.DepSet.is_empty (Typing_deps.DepSet.inter deps file_deps)) then Relative_path.Set.add acc path else (* If this file happened to be present in the base changes, it would be permissible to include it since we can return an overestimate, but we may as well remove it. *) Relative_path.Set.remove acc path) let has_file a key = match get_file_info a key with | Some _ -> true | None -> false let iter a ~f = match a with | Unbacked a -> Relative_path.Map.iter a ~f | Backed (local_changes, db_path) -> Naming_sqlite.fold ~warn_on_naming_costly_iter:true ~db_path ~init:() ~f:(fun path fi () -> f path fi) ~file_deltas:local_changes.Naming_sqlite.file_deltas let remove a key = match a with | Unbacked a -> Unbacked (Relative_path.Map.remove a key) | Backed (local_changes, db_path) -> Backed ( { local_changes with Naming_sqlite.file_deltas = Relative_path.Map.add local_changes.Naming_sqlite.file_deltas ~key ~data:Naming_sqlite.Deleted; }, db_path ) let update a key data = match a with | Unbacked a -> Unbacked (Relative_path.Map.add a ~key ~data) | Backed (local_changes, db_path) -> Backed ( { local_changes with Naming_sqlite.file_deltas = Relative_path.Map.add local_changes.Naming_sqlite.file_deltas ~key ~data:(Naming_sqlite.Modified data); }, db_path ) let update_many a updates = match a with | Unbacked a -> (* Reverse the order because union always takes the first value. *) Unbacked (Relative_path.Map.union updates a) | Backed (local_changes, db_path) -> let local_updates = Relative_path.Map.map updates ~f:(fun data -> Naming_sqlite.Modified data) in Backed ( { local_changes with Naming_sqlite.file_deltas = Relative_path.Map.union local_updates local_changes.Naming_sqlite.file_deltas; }, db_path ) let update_from_deltas a file_deltas = match a with | Unbacked file_infos -> let file_infos = Relative_path.Map.fold file_deltas ~init:file_infos ~f:(fun path file_delta acc -> match file_delta with | Naming_sqlite.Modified file_info -> Relative_path.Map.add acc ~key:path ~data:file_info | Naming_sqlite.Deleted -> Relative_path.Map.remove acc path) in Unbacked file_infos | Backed (local_changes, db_path) -> let file_deltas = (* Reverse the order because union always takes the first value. *) Relative_path.Map.union file_deltas local_changes.Naming_sqlite.file_deltas in Backed ({ local_changes with Naming_sqlite.file_deltas }, db_path) let combine a b = match b with | Unbacked b -> update_many a b | _ -> failwith "SQLite-backed naming tables cannot be the second argument to combine." (** This function saves the local changes structure as a binary blob. Local changes represents the (forward) naming table changes since the SQLite naming table baseline. Therefore, this function is most meaningful when the naming table is backed by SQLite. If the naming table is NOT backed by SQLite, meaning that it was computed from scratch by parsing the whole repo, then this baseline-to-current difference is an empty set. The resulting snapshot can be applied when loading a SQLite naming table. *) let save_changes_since_baseline naming_table ~destination_path = let snapshot = match naming_table with | Unbacked _ -> None | Backed (local_changes, _db_path) -> Some local_changes in let contents = Marshal.to_string snapshot [Marshal.No_sharing] in Disk.write_file ~file:destination_path ~contents let save naming_table db_name = match naming_table with | Unbacked naming_table -> let t = Unix.gettimeofday () in (* Ideally, we would have a commit hash, which would result in the same content version given the same version of source files. However, using a unique version every time we save the naming table from scratch is good enough to enable us to check that the local changes diff provided as an argument to load_from_sqlite_with_changes_since_baseline is compatible with the underlying SQLite table. *) let base_content_version = Printf.sprintf "%d-%s" (int_of_float t) (Random_id.short_string ()) in let save_result = Naming_sqlite.save_file_infos db_name naming_table ~base_content_version in Naming_sqlite.free_db_cache (); let (_ : float) = let open Naming_sqlite in Hh_logger.log_duration (Printf.sprintf "Inserted %d symbols from %d files" save_result.symbols_added save_result.files_added) t in save_result | Backed (local_changes, db_path) -> let t = Unix.gettimeofday () in let save_result = Naming_sqlite.copy_and_update ~existing_db:db_path ~new_db:(Naming_sqlite.Db_path db_name) local_changes in Naming_sqlite.free_db_cache (); let (_ : float) = let open Naming_sqlite in Hh_logger.log_duration (Printf.sprintf "Inserted %d symbols from %d files" save_result.symbols_added save_result.files_added) t in save_result (*****************************************************************************) (* Conversion functions *) (*****************************************************************************) let from_saved saved = Hh_logger.log "Loading naming table from marshalled blob..."; let t = Unix.gettimeofday () in let naming_table = Unbacked (Relative_path.Map.fold saved ~init:Relative_path.Map.empty ~f:(fun fn saved acc -> let file_info = FileInfo.from_saved fn saved in Relative_path.Map.add acc ~key:fn ~data:file_info)) in let _t = Hh_logger.log_duration "Loaded naming table from blob" t in naming_table let to_saved a = match a with | Unbacked a -> Relative_path.Map.map a ~f:FileInfo.to_saved | Backed _ -> fold a ~init:Relative_path.Map.empty ~f:(fun path fi acc -> Relative_path.Map.add acc ~key:path ~data:(FileInfo.to_saved fi)) let to_defs_per_file ?(warn_on_naming_costly_iter = true) a = match a with | Unbacked a -> Relative_path.Map.map a ~f:FileInfo.simplify | Backed _ -> fold a ~warn_on_naming_costly_iter ~init:Relative_path.Map.empty ~f:(fun path fi acc -> Relative_path.Map.add acc ~key:path ~data:(FileInfo.simplify fi)) let saved_to_defs_per_file saved = Relative_path.Map.map saved ~f:FileInfo.saved_to_names (*****************************************************************************) (* Forward naming table creation functions *) (*****************************************************************************) let create a = Unbacked a (* Helper function to apply new files info to reverse naming table *) let update_reverse_entries_helper (ctx : Provider_context.t) (changed_file_infos : (Relative_path.t * FileInfo.t option) list) : unit = let backend = Provider_context.get_backend ctx in let db_path_opt = Db_path_provider.get_naming_db_path backend in (* Remove all old file symbols first *) List.iter ~f:(fun (path, _file_info) -> let fi_opt = Option.bind db_path_opt ~f:(fun db_path -> Naming_sqlite.get_file_info db_path path) in match fi_opt with | Some fi -> Naming_provider.remove_type_batch backend (fi.FileInfo.classes |> List.map ~f:(fun (_, x, _) -> x)); Naming_provider.remove_type_batch backend (fi.FileInfo.typedefs |> List.map ~f:(fun (_, x, _) -> x)); Naming_provider.remove_fun_batch backend (fi.FileInfo.funs |> List.map ~f:(fun (_, x, _) -> x)); Naming_provider.remove_const_batch backend (fi.FileInfo.consts |> List.map ~f:(fun (_, x, _) -> x)); Naming_provider.remove_module_batch backend (fi.FileInfo.modules |> List.map ~f:(fun (_, x, _) -> x)) | None -> ()) changed_file_infos; (* Add new file symbols after removing old files symbols *) List.iter ~f:(fun (_path, new_file_info) -> match new_file_info with | Some fi -> List.iter ~f:(fun (pos, name, _) -> Naming_provider.add_class backend name pos) fi.FileInfo.classes; List.iter ~f:(fun (pos, name, _) -> Naming_provider.add_typedef backend name pos) fi.FileInfo.typedefs; List.iter ~f:(fun (pos, name, _) -> Naming_provider.add_fun backend name pos) fi.FileInfo.funs; List.iter ~f:(fun (pos, name, _) -> Naming_provider.add_const backend name pos) fi.FileInfo.consts; List.iter ~f:(fun (pos, name, _) -> Naming_provider.add_module backend name pos) fi.FileInfo.modules | None -> ()) changed_file_infos let update_reverse_entries ctx file_deltas = let file_delta_list = Relative_path.Map.bindings file_deltas in let changed_files_info = List.map ~f:(fun (path, file_delta) -> match file_delta with | Naming_sqlite.Modified fi -> (path, Some fi) | Naming_sqlite.Deleted -> (path, None)) file_delta_list in update_reverse_entries_helper ctx changed_files_info let choose_local_changes ~local_changes ~changes_since_baseline = match changes_since_baseline with | None -> local_changes | Some changes_since_baseline -> if String.equal changes_since_baseline.Naming_sqlite.base_content_version local_changes.Naming_sqlite.base_content_version then changes_since_baseline else failwith (Printf.sprintf "%s\nSQLite content version: %s\nLocal changes content version: %s" "Incompatible local changes diff supplied." local_changes.Naming_sqlite.base_content_version changes_since_baseline.Naming_sqlite.base_content_version) (** Loads the naming table from a SQLite database. The optional custom local changes represents the naming table changes that occurred since the original SQLite database was created. To recap, the SQLite-based naming table, once loaded, is not mutated. All the forward naming table changes are kept in an in-memory map. When we save an update to a naming table that is backed by SQLite, we store the changes since the baseline as a blob is a separate table and we rehydrate those changes into an in-memory map when we load the updated naming table later. The custom local changes is an alternative to the changes serialized as a blob into the SQLite table. This enables scenarios that require repeatedly loading the same base SQLite naming table with different versions of the local changes. *) let load_from_sqlite_for_type_checking ~(changes_since_baseline : Naming_sqlite.local_changes option) (ctx : Provider_context.t) (db_path : string) : t = Hh_logger.log "Loading naming table from SQLite..."; let t = Unix.gettimeofday () in let db_path = Naming_sqlite.Db_path db_path in Naming_sqlite.validate_can_open_db db_path; (* throw in master if anything's wrong *) Db_path_provider.set_naming_db_path (Provider_context.get_backend ctx) (Some db_path); (* I believe that changes_since_baseline is never used. I want to check... *) if Option.is_some changes_since_baseline then HackEventLogger.naming_sqlite_has_changes_since_baseline (); let local_changes = choose_local_changes ~local_changes:(Naming_sqlite.get_local_changes db_path) ~changes_since_baseline in let t = Hh_logger.log_duration "Loaded local naming table changes" t in update_reverse_entries ctx local_changes.Naming_sqlite.file_deltas; let _t = Hh_logger.log_duration "Updated reverse naming table entries" t in Backed (local_changes, db_path) let load_from_sqlite_with_changed_file_infos (ctx : Provider_context.t) (changed_file_infos : (Relative_path.t * FileInfo.t option) list) (db_path : string) : t = Hh_logger.log "Loading naming table from SQLite..."; let db_path = Naming_sqlite.Db_path db_path in Naming_sqlite.validate_can_open_db db_path; (* throw in master if anything's wrong *) Db_path_provider.set_naming_db_path (Provider_context.get_backend ctx) (Some db_path); let t = Unix.gettimeofday () in (* Get changed files delta from file info *) let changed_file_deltas = List.fold_left ~f:(fun acc_files_delta (path, changed_file_info_opt) -> let file_delta = match changed_file_info_opt with | Some file_info -> Naming_sqlite.Modified file_info | None -> Naming_sqlite.Deleted in Relative_path.Map.add acc_files_delta ~key:path ~data:file_delta) ~init:Relative_path.Map.empty changed_file_infos in let base_local_changes = Naming_sqlite.get_local_changes db_path in let local_changes = Naming_sqlite. { file_deltas = changed_file_deltas; base_content_version = base_local_changes.Naming_sqlite.base_content_version; } in let t = Hh_logger.log_duration "Calculate changed files delta" t in update_reverse_entries_helper ctx changed_file_infos; let _t = Hh_logger.log_duration "Updated reverse naming table entries" t in Backed (local_changes, db_path) let load_from_sqlite_with_changes_since_baseline (ctx : Provider_context.t) (changes_since_baseline : Naming_sqlite.local_changes option) (db_path : string) : t = load_from_sqlite_for_type_checking ~changes_since_baseline ctx db_path let load_from_sqlite (ctx : Provider_context.t) (db_path : string) : t = load_from_sqlite_for_type_checking ~changes_since_baseline:None ctx db_path let get_forward_naming_fallback_path a : string option = match a with | Unbacked _ -> None | Backed (_, Naming_sqlite.Db_path db_path) -> Some db_path module SaveAsync = struct (* The input record that gets passed from the main process to the daemon process *) type input = { blob_path: string; destination_path: string; init_id: string; root: string; } (* The main entry point of the daemon process that saves the naming table from a blob to the SQLite format. *) let save { blob_path; destination_path; root; init_id } : unit = HackEventLogger.init_batch_tool ~init_id ~root:(Path.make root) ~time:(Unix.gettimeofday ()); let chan = In_channel.create ~binary:true blob_path in let (naming_table : t) = Marshal.from_channel chan in Sys_utils.close_in_no_fail blob_path chan; Sys_utils.rm_dir_tree (Filename.dirname blob_path); let (_save_result : Naming_sqlite.save_result) = save naming_table destination_path in (* The intention here is to force the daemon process to exit with an failed exit code so that the main process can detect the condition and log the outcome. *) assert (Disk.file_exists destination_path) (* The daemon entry registration - used by the main process *) let save_entry = Process.register_entry_point "naming_table_save_async_entry" save end let save_async naming_table ~init_id ~root ~destination_path = Hh_logger.log "Saving naming table to %s" destination_path; let blob_dir = Tempfile.mkdtemp_with_dir (Path.make GlobalConfig.tmp_dir) in let blob_path = Path.(to_string (concat blob_dir "naming_bin")) in let chan = Stdlib.open_out_bin blob_path in Marshal.to_channel chan naming_table []; Stdlib.close_out chan; let open SaveAsync in FutureProcess.make (Process.run_entry Process_types.Default save_entry { blob_path; destination_path; init_id; root }) (fun output -> Hh_logger.log "Output from out-of-proc: %s" output) (*****************************************************************************) (* Testing functions *) (*****************************************************************************) let get_backed_delta_TEST_ONLY (t : t) : Naming_sqlite.local_changes option = match t with | Backed (local_changes, _) -> Some local_changes | Unbacked _ -> None
OCaml Interface
hhvm/hphp/hack/src/naming/naming_table.mli
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) (** * This module holds all the operations that can be performed on forward and * reverse naming tables. Forward naming tables map from filenames to the * symbols in that file, while the reverse naming table maps from symbols to the * file that they're defined in. *) type t [@@deriving show] type changes_since_baseline type defs_per_file = FileInfo.names Relative_path.Map.t [@@deriving show] type saved_state_info = FileInfo.saved Relative_path.Map.t (* Querying and updating forward naming tables. *) val combine : t -> t -> t val empty : t (** [filter] is implemented using tombstones on SQLite-backed naming tables, so * if your naming table is backed by SQLite you should try to avoid removing * more than half the table by filtering (otherwise it would be best to just * make a new empty one and add elements to it). On non-SQLite backed tables * we remove entries, so it's no more or less efficient depending on how many * are removed. *) val filter : t -> f:(Relative_path.t -> FileInfo.t -> bool) -> t val fold : ?warn_on_naming_costly_iter:bool -> t -> init:'b -> f:(Relative_path.t -> FileInfo.t -> 'b -> 'b) -> 'b val get_files : t -> Relative_path.t list val get_files_changed_since_baseline : changes_since_baseline -> Relative_path.t list val get_file_info : t -> Relative_path.t -> FileInfo.t option exception File_info_not_found (** Might raise {!File_info_not_found} *) val get_file_info_unsafe : t -> Relative_path.t -> FileInfo.t (** Look up the files declaring the symbols provided in the given set of dependency hashes. Only works for backed naming tables, and 64bit dep_sets *) val get_64bit_dep_set_files : t -> Typing_deps.DepSet.t -> Relative_path.Set.t val has_file : t -> Relative_path.t -> bool val iter : t -> f:(Relative_path.t -> FileInfo.t -> unit) -> unit val remove : t -> Relative_path.t -> t val update : t -> Relative_path.t -> FileInfo.t -> t val update_many : t -> FileInfo.t Relative_path.Map.t -> t val update_from_deltas : t -> Naming_sqlite.file_deltas -> t val save : t -> string -> Naming_sqlite.save_result (* Creation functions. *) val create : FileInfo.t Relative_path.Map.t -> t (* The common path for loading a save state from a SQLite database *) val load_from_sqlite : Provider_context.t -> string -> t (* This function is intended for applying naming changes relative to the source code version on which the naming table was first created. For the additional naming changes to be compatible with a SQLite-backed naming table originally created on source code version X, they must be snapshotted by loading a naming table originally created on X and, at a later time, calling `save_changes_since_baseline`. The scenario where this can be useful is thus: 1) In process A - load a SQLite-backed naming table for source code version N - user makes changes, resulting in source code version N + 1 - save changes since baseline as C1 2) In process B - load the naming table for N + C1 - do some work 3) In process A - user makes changes, resulting in source code version N + 2 - save changes since baseline as C2 4) In process B - load the naming table for N + C2 - do some work This avoids having to send the naming table version N to process B more than once. After B gets naming table N, it only needs the changes C1 and C2 to restore the state as process A sees it. This is more relevant if A and B are not on the same host, and the cost of sending the naming table is not negligible. *) val load_from_sqlite_with_changes_since_baseline : Provider_context.t -> changes_since_baseline -> string -> t (** The same as load_from_sqlite_with_changes_since_baseline but accepting a list of changed file infos since naming table base. *) val load_from_sqlite_with_changed_file_infos : Provider_context.t -> (Relative_path.t * FileInfo.t option) list -> string -> t (* The path to the table's SQLite database mapping filenames to symbol names, if any *) val get_forward_naming_fallback_path : t -> string option (* Converting between different types of forward naming tables. *) val from_saved : saved_state_info -> t val to_saved : t -> saved_state_info val to_defs_per_file : ?warn_on_naming_costly_iter:bool -> t -> defs_per_file val saved_to_defs_per_file : saved_state_info -> defs_per_file val save_changes_since_baseline : t -> destination_path:string -> unit val save_async : t -> init_id:string -> root:string -> destination_path:string -> unit Future.t (** Test function; do not use. *) val get_backed_delta_TEST_ONLY : t -> Naming_sqlite.local_changes option
OCaml
hhvm/hphp/hack/src/naming/naming_typed_locals.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Aast module Map = Local_id.Map module Set = Local_id.Set type typed_local_env = { locals: Pos.t Map.t; declared_ids: Set.t; assigned_ids: Set.t; } let empty = { locals = Map.empty; declared_ids = Set.empty; assigned_ids = Set.empty } let add_local env id pos = { env with locals = Map.add id pos env.locals } let add_declared_id env id = { env with declared_ids = Set.add id env.declared_ids } let add_assigned_id env id = { env with assigned_ids = Set.add id env.assigned_ids } let get_local env id = Map.find_opt id env.locals let get_local_pos env id = match get_local env id with | Some pos -> pos | None -> Pos.none let restrict_env env uses = List.fold_left uses ~init:empty ~f:(fun new_env (_, (_, id)) -> let new_env = match get_local env id with | None -> new_env | Some pos -> add_local new_env id pos in let new_env = if Set.mem id env.declared_ids then add_declared_id new_env id else new_env in if Set.mem id env.assigned_ids then add_assigned_id new_env id else new_env) let extend_error_map error_map env1 env2 clashes = Set.fold (fun id error_map -> Map.add id (get_local_pos env1 id, get_local_pos env2 id) error_map) clashes error_map let join2 error_map env1 env2 = let two_declare = Set.inter env1.assigned_ids env2.declared_ids in let error_map = extend_error_map error_map env2 env1 two_declare in let one_declare = Set.inter env1.declared_ids env2.assigned_ids in let error_map = extend_error_map error_map env1 env2 one_declare in let both_declare = Set.inter env1.declared_ids env2.declared_ids in let error_map = extend_error_map error_map env1 env2 both_declare in let locals = Set.fold (fun id locals -> Map.add id (Map.find id env1.locals) locals) (Set.union env1.declared_ids (Set.diff env1.assigned_ids env2.declared_ids)) env2.locals in let declared_ids = Set.union env1.declared_ids env2.declared_ids in let assigned_ids = Set.diff (Set.union env1.assigned_ids env2.assigned_ids) (Set.union one_declare two_declare) in ({ locals; assigned_ids; declared_ids }, error_map) let join envs before_env = let (env, error_map) = List.fold_right envs ~init:({ empty with locals = before_env.locals }, Map.empty) ~f:(fun env1 (env2, error_map) -> join2 error_map env1 env2) in Map.iter (fun id (id_pos, def_pos) -> Errors.add_error Naming_error.( to_user_error (Illegal_typed_local { join = true; id_pos; id_name = Local_id.to_string id; def_pos }))) error_map; { env with declared_ids = Set.union env.declared_ids before_env.declared_ids; assigned_ids = Set.union env.assigned_ids before_env.assigned_ids; } let rec check_assign_lval on_expr env (((), pos, expr_) as expr) = on_expr env expr; match expr_ with | Lvar lid -> let name = snd lid in (match get_local env name with | None -> let env = add_local env name pos in add_assigned_id env name | Some _ -> env) | List exprs -> List.fold_left exprs ~init:env ~f:(check_assign_lval on_expr) | _ -> env let check_assign_expr on_expr env (((), _pos, expr_) as expr) = on_expr env expr; match expr_ with | Binop { bop = Ast_defs.Eq _; lhs = ((), pos, lval); rhs = _ } -> (match lval with | Lvar lid -> let name = snd lid in (match get_local env name with | None -> let env = add_local env name pos in add_assigned_id env name | Some _ -> env) | List exprs -> List.fold_left exprs ~init:env ~f:(check_assign_lval on_expr) | _ -> env) | _ -> env let rec check_stmt on_expr env (id_pos, stmt_) = let check_block = check_block on_expr in match stmt_ with | Declare_local (id, _hint, init) -> Option.iter ~f:(on_expr env) init; let name = snd id in (match get_local env name with | None -> let env = add_local env name id_pos in let env = add_declared_id env name in env | Some def_pos -> Errors.add_error Naming_error.( to_user_error (Illegal_typed_local { join = false; id_pos; id_name = Local_id.to_string name; def_pos; })); env) | Expr expr -> check_assign_expr on_expr env expr | If (cond, then_block, else_block) -> on_expr env cond; let new_env = { empty with locals = env.locals } in let then_env = check_block new_env then_block in let else_env = check_block new_env else_block in join [then_env; else_env] env | For (init_exprs, cond, update_exprs, body) -> let env = List.fold_left init_exprs ~init:env ~f:(check_assign_expr on_expr) in Option.iter ~f:(on_expr env) cond; let env = check_block env body in List.fold_left update_exprs ~init:env ~f:(check_assign_expr on_expr) | Switch (expr, cases, default) -> on_expr env expr; let new_env = { empty with locals = env.locals } in let envs = List.map ~f:(check_case on_expr new_env) cases in let default_env = match default with | None -> empty | Some (_, block) -> check_block new_env block in join (envs @ [default_env]) env | Match { sm_expr; sm_arms } -> on_expr env sm_expr; let new_env = { empty with locals = env.locals } in let envs = List.map ~f:(check_stmt_match_arm on_expr new_env) sm_arms in join envs env | Do (block, cond) -> let env = check_block env block in on_expr env cond; env | While (cond, block) -> on_expr env cond; check_block env block | Awaitall (inits, block) -> List.iter ~f:(fun (_, e) -> on_expr env e) inits; check_block env block | Block block -> check_block env block | Return (Some expr) | Throw expr -> on_expr env expr; env | Foreach (expr, as_expr, block) -> on_expr env expr; let env = match as_expr with | As_v e | Await_as_v (_, e) -> check_assign_lval on_expr env e | As_kv (e1, e2) | Await_as_kv (_, e1, e2) -> let env = check_assign_lval on_expr env e1 in check_assign_lval on_expr env e2 in check_block env block | Try (try_block, catches, finally_block) -> let env = check_block env try_block in let env = check_catches on_expr env catches in let env = check_block env finally_block in env | Using { us_is_block_scoped = _; us_has_await = _; us_exprs = (_, exprs); us_block = block; } -> let env = List.fold_left exprs ~init:env ~f:(check_assign_expr on_expr) in check_block env block | Return None | Fallthrough | Break | Continue | Yield_break | Noop | Markup _ | AssertEnv _ -> env and check_block on_expr env block = match block with | [] -> env | stmt :: stmts -> let env = check_stmt on_expr env stmt in let env = check_block on_expr env stmts in env and check_catch on_expr env (_cn, (pos, name), block) = let env = match get_local env name with | None -> let env = add_local env name pos in add_assigned_id env name | Some _ -> env in check_block on_expr env block and check_catches on_expr env catches = let new_env = { empty with locals = env.locals } in let envs = List.map ~f:(check_catch on_expr new_env) catches in join envs env and check_case on_expr env (expr, block) = on_expr env expr; check_block on_expr env block and check_stmt_match_arm on_expr env { sma_pat = _; sma_body } = check_block on_expr env sma_body let ignorefn f x y = ignore (f x y) let visitor = object (s) inherit [_] Aast.endo as super method on_'ex (_ : typed_local_env) () = () method on_'en (_ : typed_local_env) () = () method! on_stmt env stmt = let _env = check_stmt (ignorefn super#on_expr) env stmt in stmt method! on_block env block = let _env = check_block (ignorefn super#on_expr) env block in block method! on_fun_ env fun_ = let env = List.fold_left fun_.f_params ~init:env ~f:(fun env param -> let local_id = Local_id.make_unscoped param.param_name in let env = add_local env local_id param.param_pos in add_assigned_id env local_id) in let _env = check_block (ignorefn super#on_expr) env fun_.f_body.fb_ast in fun_ method! on_efun env efun = let env = restrict_env env efun.ef_use in let _fun_ = s#on_fun_ env efun.ef_fun in efun method! on_fun_def _env fun_def = let _fun_ = s#on_fun_ empty fun_def.fd_fun in fun_def method! on_method_ _env method_ = let env = List.fold_left method_.m_params ~init:empty ~f:(fun env param -> let local_id = Local_id.make_unscoped param.param_name in let env = add_local env local_id param.param_pos in add_assigned_id env local_id) in let _env = check_block (ignorefn super#on_expr) env method_.m_body.fb_ast in method_ end let elab_fun_def elem = visitor#on_fun_def empty elem let elab_class elem = visitor#on_class_ empty elem let elab_program elem = visitor#on_program empty elem
OCaml Interface
hhvm/hphp/hack/src/naming/naming_typed_locals.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 elab_fun_def : (unit, unit) Aast.fun_def -> (unit, unit) Aast.fun_def val elab_class : (unit, unit) Aast.class_ -> (unit, unit) Aast.class_ val elab_program : (unit, unit) Aast.program -> (unit, unit) Aast.program
OCaml
hhvm/hphp/hack/src/naming/naming_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 kind_of_type = | TClass | TTypedef [@@deriving show, eq] type name_kind = | Type_kind of kind_of_type | Fun_kind | Const_kind | Module_kind [@@deriving show, eq] let type_kind_to_name_type (kind_of_type : kind_of_type) : FileInfo.name_type = match kind_of_type with | TClass -> FileInfo.Class | TTypedef -> FileInfo.Typedef let name_kind_to_name_type (name_kind : name_kind) : FileInfo.name_type = match name_kind with | Type_kind type_kind -> type_kind_to_name_type type_kind | Fun_kind -> FileInfo.Fun | Const_kind -> FileInfo.Const | Module_kind -> FileInfo.Module let name_kind_of_name_type (name_type : FileInfo.name_type) : name_kind = match name_type with | FileInfo.Class -> Type_kind TClass | FileInfo.Typedef -> Type_kind TTypedef | FileInfo.Fun -> Fun_kind | FileInfo.Const -> Const_kind | FileInfo.Module -> Module_kind let type_kind_of_name_type (name_type : FileInfo.name_type) : kind_of_type option = match name_type with | FileInfo.Class -> Some TClass | FileInfo.Typedef -> Some TTypedef | FileInfo.Fun | FileInfo.Const | FileInfo.Module -> None let name_kind_to_enum (name_kind : name_kind) : int = (* These values are stored in the naming table database, and must match [flag_of_enum] and naming_types_impl.rs We happen for convenience to use the same numerical values as FileInfo.name_type. *) name_kind |> name_kind_to_name_type |> FileInfo.name_type_to_enum let name_kind_of_enum (i : int) : name_kind option = (* These values are stored in the naming table database, and must match [flag_to_enum] and naming_types_impl.rs *) i |> FileInfo.name_type_of_enum |> Option.map name_kind_of_name_type
OCaml Interface
hhvm/hphp/hack/src/naming/naming_types.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. * *) (** In the naming table, global constants and global functions can be syntactically disambiguated at their use-site, and therefore can live in separate namespaces. However, types (such as classes) cannot be syntactically disambiguated, and they live in the same namespace. So in the naming table, we also have to store what kind of type that symbol was. *) type kind_of_type = | TClass | TTypedef [@@deriving show, eq] type name_kind = | Type_kind of kind_of_type | Fun_kind | Const_kind | Module_kind [@@deriving show, eq] val name_kind_to_enum : name_kind -> int val name_kind_of_enum : int -> name_kind option (* The types in this file duplicate what's in FileInfo.name_type, but with more structure. It'd be nice to unify them. *) val name_kind_to_name_type : name_kind -> FileInfo.name_type val type_kind_to_name_type : kind_of_type -> FileInfo.name_type val name_kind_of_name_type : FileInfo.name_type -> name_kind val type_kind_of_name_type : FileInfo.name_type -> kind_of_type option
OCaml
hhvm/hphp/hack/src/naming/naming_validate_cast_expr.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 SN = Naming_special_names let on_expr_ on_error expr_ ~ctx = let err_opt = match expr_ with | Aast.(Cast ((_, Hprim (Tint | Tbool | Tfloat | Tstring)), _)) -> None | Aast.(Cast ((_, Happly ((_, tycon_nm), _)), _)) when String.( equal tycon_nm SN.Collections.cDict || equal tycon_nm SN.Collections.cVec) -> None | Aast.(Cast ((_, Aast.Hvec_or_dict (_, _)), _)) -> None | Aast.(Cast ((_, Aast.Hany), _)) -> (* We end up with a `Hany` when we have an arity error for dict/vec - we don't error on this case to preserve behaviour *) None | Aast.(Cast ((pos, _), _)) -> Some (Naming_phase_error.naming @@ Naming_error.Object_cast pos) | _ -> None in Option.iter ~f:on_error err_opt; (ctx, Ok expr_) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.bottom_up Aast.Pass. { id with on_ty_expr_ = Some (fun elem ~ctx -> on_expr_ on_error elem ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_validate_cast_expr.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. * *) (* Ensures that the hint inside a `Cast` expression is valid *) val pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_validate_class_req.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 let on_class_ on_error (Aast.{ c_reqs; c_kind; _ } as c) ~ctx = let (c_req_extends, c_req_implements, c_req_class) = Aast.split_reqs c_reqs in let is_trait = Ast_defs.is_c_trait c_kind and is_interface = Ast_defs.is_c_interface c_kind in let err_req_impl = match c_req_implements with | (pos, _) :: _ when not is_trait -> Some (Naming_phase_error.naming @@ Naming_error.Invalid_require_implements pos) | _ -> None and err_req_class = match c_req_class with | (pos, _) :: _ when not is_trait -> Some (Naming_phase_error.naming @@ Naming_error.Invalid_require_class pos) | _ -> None and err_req_extends = match c_req_extends with | (pos, _) :: _ when not (is_trait || is_interface) -> Some (Naming_phase_error.naming @@ Naming_error.Invalid_require_extends pos) | _ -> None in Option.iter ~f:on_error err_req_impl; Option.iter ~f:on_error err_req_class; Option.iter ~f:on_error err_req_extends; (ctx, Ok c) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_class_ = Some (fun elem ~ctx -> on_class_ on_error elem ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_validate_class_req.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 pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_validate_consistent_construct.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 SN = Naming_special_names module Env = struct let consistent_ctor_level Naming_phase_env.{ consistent_ctor_level; _ } = consistent_ctor_level end let on_class_ on_error (Aast.{ c_methods; c_user_attributes; c_kind; _ } as c) ~ctx = let err_opt = if Env.consistent_ctor_level ctx > 0 then let attr_pos_opt = Naming_attributes.mem_pos SN.UserAttributes.uaConsistentConstruct c_user_attributes in let ctor_opt = List.find c_methods ~f:(fun Aast.{ m_name = (_, nm); _ } -> if String.equal nm "__construct" then true else false) in match (attr_pos_opt, ctor_opt) with | (Some pos, None) when Ast_defs.is_c_trait c_kind || Env.consistent_ctor_level ctx > 1 -> if Option.is_none ctor_opt then Some (Naming_phase_error.naming @@ Naming_error.Explicit_consistent_constructor { classish_kind = c_kind; pos }) else None | _ -> None else None in Option.iter ~f:on_error err_opt; (ctx, Ok c) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_class_ = Some (fun elem ~ctx -> on_class_ on_error elem ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_validate_consistent_construct.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 pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_validate_dynamic_hint.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 let on_expr_ on_error expr_ ~ctx = let err_opt = match expr_ with | Aast.(Is (_, (pos, Hdynamic))) -> Some (Naming_phase_error.naming @@ Naming_error.Dynamic_hint_disallowed pos) | _ -> None in Option.iter ~f:on_error err_opt; (ctx, Ok expr_) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.bottom_up Aast.Pass. { id with on_ty_expr_ = Some (fun elem ~ctx -> on_expr_ on_error elem ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_validate_dynamic_hint.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. * *) (* Ensures that the hint inside an `Is` expression isn't just `dynamic` *) val pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_validate_fun_params.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 Err = Naming_phase_error module SN = Naming_special_names let validate_fun_params params = snd @@ List.fold_left params ~init:(SSet.empty, []) ~f:(fun (seen, errs) Aast.{ param_name; param_pos; _ } -> if String.equal SN.SpecialIdents.placeholder param_name then (seen, errs) else if SSet.mem param_name seen then let err = Err.naming @@ Naming_error.Already_bound { pos = param_pos; name = param_name } in (seen, err :: errs) else (SSet.add param_name seen, errs)) let on_method_ on_error m ~ctx = List.iter ~f:on_error @@ validate_fun_params m.Aast.m_params; (ctx, Ok m) let on_fun_ on_error f ~ctx = List.iter ~f:on_error @@ validate_fun_params f.Aast.f_params; (ctx, Ok f) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_method_ = Some (fun elem ~ctx -> on_method_ on_error elem ~ctx); on_ty_fun_ = Some (fun elem ~ctx -> on_fun_ on_error elem ~ctx); }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_validate_fun_params.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 pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_validate_like_hint.ml
(* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude module Env = struct let like_type_hints_enabled Naming_phase_env.{ like_type_hints_enabled; _ } = like_type_hints_enabled end let on_hint on_error hint ~ctx = let (err_opt, ctx) = match hint with | (pos, Aast.Hlike _) when not (Env.like_type_hints_enabled ctx) -> (Some (Naming_phase_error.like_type pos), ctx) | _ -> (None, ctx) in Option.iter ~f:on_error err_opt; (ctx, Ok hint) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass.{ id with on_ty_hint = Some (on_hint on_error) }
OCaml Interface
hhvm/hphp/hack/src/naming/naming_validate_like_hint.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 pass : (Naming_phase_error.t -> unit) -> Naming_phase_env.t Naming_phase_pass.t
OCaml
hhvm/hphp/hack/src/naming/naming_validate_module.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 Err = Naming_phase_error module Env = struct let allow_module_def Naming_phase_env.{ allow_module_def; _ } = allow_module_def end let on_module_def on_error (Aast.{ md_span; _ } as md) ~ctx = let err_opt = if Env.allow_module_def ctx then None else Some (Err.naming @@ Naming_error.Module_declaration_outside_allowed_files md_span) in Option.iter ~f:on_error err_opt; (ctx, Ok md) let pass on_error = let id = Aast.Pass.identity () in Naming_phase_pass.top_down Aast.Pass. { id with on_ty_module_def = Some (fun elem ~ctx -> on_module_def on_error elem ~ctx); }