diff --git a/analysis/reanalyze/src/exception.ml b/analysis/reanalyze/src/exception.ml index fb27cdfb82..a98c40c438 100644 --- a/analysis/reanalyze/src/exception.ml +++ b/analysis/reanalyze/src/exception.ml @@ -109,16 +109,17 @@ module Event = struct if config.Dce_config.cli.debug then ( Log_.item "@."; Log_.item "Events combine: #events %d@." (events |> List.length)); - let exn_table = Hashtbl.create 1 in + let exn_table = Exn.Table.create 1 in let extend_exn_table exn loc = - match Hashtbl.find_opt exn_table exn with - | Some loc_set -> Hashtbl.replace exn_table exn (Loc_set.add loc loc_set) - | None -> Hashtbl.replace exn_table exn (Loc_set.add loc Loc_set.empty) + match Exn.Table.find_opt exn_table exn with + | Some loc_set -> + Exn.Table.replace exn_table exn (Loc_set.add loc loc_set) + | None -> Exn.Table.replace exn_table exn (Loc_set.add loc Loc_set.empty) in let shrink_exn_table exn loc = - match Hashtbl.find_opt exn_table exn with + match Exn.Table.find_opt exn_table exn with | Some loc_set -> - Hashtbl.replace exn_table exn (Loc_set.remove loc loc_set) + Exn.Table.replace exn_table exn (Loc_set.remove loc loc_set) | None -> () in let rec loop exn_set events = @@ -188,6 +189,8 @@ and check = { loc: Location.t; loc_full: Location.t; module_name: string; + scope: string list; + (** The module the check's code is in, as [[File; M; N]] for [File.M.N] *) exn_name: string; exceptions: Exceptions.t; } @@ -195,21 +198,70 @@ and check = { let create_checks_builder () : checks_builder = ref [] let checks_builder_add (builder : checks_builder) ~events ~exceptions ~loc - ?(loc_full = loc) ~module_name exn_name = + ?(loc_full = loc) ~module_name ~scope exn_name = builder := - {events; exceptions; loc; loc_full; module_name; exn_name} :: !builder + {events; exceptions; loc; loc_full; module_name; scope; exn_name} + :: !builder let checks_builder_to_list (builder : checks_builder) : check list = !builder |> List.rev module Checks = struct let do_check ~(values_table : values_table) ~config - {events; exceptions; loc; loc_full; module_name; exn_name} = + {events; exceptions; loc; loc_full; module_name; scope; exn_name} = let throw_set, exn_table = events |> Event.combine ~values_table ~config ~module_name in let missing_annotations = Exceptions.diff throw_set exceptions in let redundant_annotations = Exceptions.diff exceptions throw_set in + (* The compiler names exceptions by their full path, as [Lib.M.E]. + Messages name them as the code they are about would: [E] in [Lib.M], + [M.E] elsewhere in [Lib]. *) + let prefixes = + let rec go rev_scope = + match rev_scope with + | [] -> [] + | _ :: outer -> + (String.concat "." (List.rev rev_scope) ^ ".") :: go outer + in + go (List.rev scope) + in + let shorten exn = + let name = Exn.to_string exn in + match + prefixes + |> List.find_opt (fun prefix -> String.starts_with ~prefix name) + with + | Some prefix -> + Exn.with_name + (String.sub name (String.length prefix) + (String.length name - String.length prefix)) + exn + | None -> exn + in + (* Two different exceptions, as [M.E] and an inner [M.N.E], keep their + names within the file when shortening would give them the same one. *) + let shortened = ref [] in + Exceptions.union throw_set exceptions + |> Exceptions.iter (fun exn -> + shortened := Exn.to_string (shorten exn) :: !shortened); + let relative exn = + let short = shorten exn in + let name = Exn.to_string short in + if List.length (List.filter (String.equal name) !shortened) > 1 then + let name = Exn.to_string exn in + let prefix = module_name ^ "." in + if String.starts_with ~prefix name then + Exn.with_name + (String.sub name (String.length prefix) + (String.length name - String.length prefix)) + exn + else exn + else short + in + let throw_set = Exceptions.map relative throw_set in + let missing_annotations = Exceptions.map relative missing_annotations in + let redundant_annotations = Exceptions.map relative redundant_annotations in (if not (Exceptions.is_empty missing_annotations) then let description = Issue.ExceptionAnalysisMissing @@ -263,8 +315,8 @@ let traverse_ast ~file ~values_builder ~checks_builder () = |> List.fold_left (fun acc desc -> match desc with - | Typedtree.Tpat_construct ({txt}, _, _) -> - Exceptions.add (Exn.from_lid txt) acc + | Typedtree.Tpat_construct ({txt}, cstr, _) -> + Exceptions.add (Exn.of_constructor txt cstr) acc | _ -> acc) Exceptions.empty in @@ -308,8 +360,8 @@ let traverse_ast ~file ~values_builder ~checks_builder () = in let throw_args args = match args with - | [(_, Some {Typedtree.exp_desc = Texp_construct ({txt}, _, _)})] -> - [Exn.from_lid txt] |> Exceptions.from_list + | [(_, Some {Typedtree.exp_desc = Texp_construct ({txt}, cstr, _)})] -> + [Exn.of_constructor txt cstr] |> Exceptions.from_list | [(_, Some {Typedtree.exp_desc = Texp_ident _})] -> [Exn.from_string "genericException"] |> Exceptions.from_list | _ -> [Exn.from_string "TODO_from_raise1"] |> Exceptions.from_list @@ -319,29 +371,13 @@ let traverse_ast ~file ~values_builder ~checks_builder () = |> Annotation.get_attribute_payload (fun s -> s = "doesNotThrow") <> None in - let get_exceptions_from_annotations attributes = - let throws_annotation_payload = - attributes |> Annotation.get_attribute_payload (fun s -> s = "throws") - in - let rec get_exceptions payload = - match payload with - | Annotation.StringPayload s -> - [Exn.from_string s] |> Exceptions.from_list - | Annotation.ConstructPayload s when s <> "::" -> - [Exn.from_string s] |> Exceptions.from_list - | Annotation.IdentPayload s -> - [Exn.from_string (s |> Longident.flatten |> String.concat ".")] - |> Exceptions.from_list - | Annotation.TuplePayload tuple -> - tuple - |> List.map (fun payload -> - payload |> get_exceptions |> Exceptions.to_list) - |> List.concat |> Exceptions.from_list - | _ -> Exceptions.empty - in - match throws_annotation_payload with - | None -> Exceptions.empty - | Some payload -> payload |> get_exceptions + (* The type checker resolves the names a [@throws] lists where they are + written, and records the exceptions with the declaration. *) + let exceptions_of_throws (throws : Types.throws list) = + throws + |> List.map (fun ({throws_name; throws_identity} : Types.throws) -> + Exn.make ~id:throws_identity ~name:throws_name) + |> Exceptions.from_list in let expr ~(module_path : Module_path.t) (self : Tast_mapper.mapper) (expr : Typedtree.expression) = @@ -369,7 +405,7 @@ let traverse_ast ~file ~values_builder ~checks_builder () = from other modules and packages. *) current_events := { - Event.exceptions = get_exceptions_from_annotations vd.val_attributes; + Event.exceptions = exceptions_of_throws vd.val_throws; loc; kind = Call {callee; module_path = module_path.path}; } @@ -447,8 +483,8 @@ let traverse_ast ~file ~values_builder ~checks_builder () = :: old_events); expr in - let toplevel_eval (self : Tast_mapper.mapper) (expr : Typedtree.expression) - attributes = + let toplevel_eval ~(module_path : Module_path.t) (self : Tast_mapper.mapper) + (expr : Typedtree.expression) throws = let old_id = !current_id in let old_events = !current_events in let name = "Toplevel expression" in @@ -457,8 +493,10 @@ let traverse_ast ~file ~values_builder ~checks_builder () = let module_name = file.File_context.module_name in self.expr self expr |> ignore; checks_builder_add checks_builder ~events:!current_events - ~exceptions:(get_exceptions_from_annotations attributes) - ~loc:expr.exp_loc ~module_name name; + ~exceptions:(exceptions_of_throws throws) + ~loc:expr.exp_loc ~module_name + ~scope:(module_name :: List.rev_map Name.to_string module_path.path) + name; current_id := old_id; current_events := old_events in @@ -475,9 +513,7 @@ let traverse_ast ~file ~values_builder ~checks_builder () = let process_binding name = current_id := name; current_events := []; - let exceptions_from_annotations = - get_exceptions_from_annotations vb.vb_attributes - in + let exceptions_from_annotations = exceptions_of_throws vb.vb_throws in values_builder_add values_builder ~module_path ~name exceptions_from_annotations; let res = super.value_binding self vb in @@ -488,8 +524,9 @@ let traverse_ast ~file ~values_builder ~checks_builder () = | Some exceptions -> exceptions | _ -> Exceptions.empty in + let scope = module_name :: List.rev_map Name.to_string module_path.path in checks_builder_add checks_builder ~events:!current_events ~exceptions - ~loc:vb.vb_pat.pat_loc ~loc_full:vb.vb_loc ~module_name name; + ~loc:vb.vb_pat.pat_loc ~loc_full:vb.vb_loc ~module_name ~scope name; current_id := old_id; current_events := old_events; res @@ -536,8 +573,8 @@ let traverse_ast ~file ~values_builder ~checks_builder () = let mapper = make_mapper mp in let mp' = match structure_item.str_desc with - | Tstr_eval (expr, attributes) -> - toplevel_eval mapper expr attributes; + | Tstr_eval (expr, _attributes, throws) -> + toplevel_eval ~module_path:mp mapper expr throws; mp | Tstr_module {mb_id; mb_loc; mb_expr} -> ( let name = mb_id |> Ident.name |> Name.create in diff --git a/analysis/reanalyze/src/exceptions.ml b/analysis/reanalyze/src/exceptions.ml index a5903143ad..fcd696e682 100644 --- a/analysis/reanalyze/src/exceptions.ml +++ b/analysis/reanalyze/src/exceptions.ml @@ -6,8 +6,8 @@ let add = Exn_set.add let diff = Exn_set.diff let empty = Exn_set.empty let from_list = Exn_set.of_list -let to_list = Exn_set.elements let is_empty = Exn_set.is_empty +let map = Exn_set.map let iter = Exn_set.iter let union = Exn_set.union @@ -19,7 +19,7 @@ let pp ~exn_table ppf exceptions = let name = Exn.to_string exn in match exn_table with | Some exn_table -> ( - match Hashtbl.find_opt exn_table exn with + match Exn.Table.find_opt exn_table exn with | Some loc_set -> let positions = loc_set |> Loc_set.elements diff --git a/analysis/reanalyze/src/exn.ml b/analysis/reanalyze/src/exn.ml index 145d47975c..1c38ee9581 100644 --- a/analysis/reanalyze/src/exn.ml +++ b/analysis/reanalyze/src/exn.ml @@ -1,7 +1,27 @@ -type t = string +(* An exception is its identity, which the type checker records on its + definition and on each [@throws] that names it (see [Throws_attribute]), + and a name to show in messages. So [Lib.E] and [E] after [open Lib] are + equal. *) +type t = {id: string; name: string} -let compare = String.compare -let match_failure = "Match_failure" -let from_lid lid = lid |> Longident.flatten |> String.concat "." -let from_string s = s -let to_string s = s +let compare a b = String.compare a.id b.id +let make ~id ~name = {id; name} +let from_string s = {id = s; name = s} +let match_failure = from_string "Match_failure" +let to_string e = e.name + +(* The exception a pattern or expression constructs, named as written *) +let of_constructor lid (cstr : Types.constructor_description) = + let name = lid |> Longident.flatten |> String.concat "." in + match Throws_attribute.identity cstr with + | Some id -> {id; name} + | None -> from_string name + +let with_name name e = {e with name} + +module Table = Hashtbl.Make (struct + type nonrec t = t + + let equal a b = String.equal a.id b.id + let hash a = Hashtbl.hash a.id +end) diff --git a/analysis/reanalyze/src/exn.mli b/analysis/reanalyze/src/exn.mli index 683440249e..2e7c6a3e48 100644 --- a/analysis/reanalyze/src/exn.mli +++ b/analysis/reanalyze/src/exn.mli @@ -1,7 +1,14 @@ type t val compare : t -> t -> int -val from_lid : Longident.t -> t +val make : id:string -> name:string -> t val from_string : string -> t val match_failure : t val to_string : t -> string + +val of_constructor : Longident.t -> Types.constructor_description -> t +(** The exception a pattern or expression constructs, named as written *) + +val with_name : string -> t -> t + +module Table : Hashtbl.S with type key = t diff --git a/analysis/reanalyze/src/issue.ml b/analysis/reanalyze/src/issue.ml index 767922a0fa..986eb3cf4b 100644 --- a/analysis/reanalyze/src/issue.ml +++ b/analysis/reanalyze/src/issue.ml @@ -6,7 +6,7 @@ module Exn_set = Set.Make (Exn) type missing_throw_info = { exn_name: string; - exn_table: (Exn.t, Loc_set.t) Hashtbl.t; + exn_table: Loc_set.t Exn.Table.t; loc_full: Location.t; missing_annotations: Exn_set.t; throw_set: Exn_set.t; diff --git a/changes/throws-names-are-dependencies.breaking.md b/changes/throws-names-are-dependencies.breaking.md new file mode 100644 index 0000000000..16b91fbaa5 --- /dev/null +++ b/changes/throws-names-are-dependencies.breaking.md @@ -0,0 +1 @@ +- A module named in `@throws` is now a dependency of the module that names it, so a dependency cycle through such a name is an error. Move the exception to a module of its own. diff --git a/changes/throws-resolved-in-type-checker.feature.md b/changes/throws-resolved-in-type-checker.feature.md new file mode 100644 index 0000000000..18301c1600 --- /dev/null +++ b/changes/throws-resolved-in-type-checker.feature.md @@ -0,0 +1 @@ +- The compiler resolves the exceptions a `@throws` names where it is written, so exception analysis matches them with catches through opens, aliases, includes and functors, and warns (warning 114) about a name that is not an exception in scope. diff --git a/compiler/typing/ctype.ml b/compiler/typing/ctype.ml index 7b0834be7e..0a6089d978 100644 --- a/compiler/typing/ctype.ml +++ b/compiler/typing/ctype.ml @@ -4633,6 +4633,7 @@ let nondep_extension_constructor env mid ext = ext_attributes = ext.ext_attributes; ext_loc = ext.ext_loc; ext_is_exception = ext.ext_is_exception; + ext_identity = ext.ext_identity; }) let same_constr env t1 t2 = diff --git a/compiler/typing/datarepr.ml b/compiler/typing/datarepr.ml index 8c7360f18b..7d505e981f 100644 --- a/compiler/typing/datarepr.ml +++ b/compiler/typing/datarepr.ml @@ -187,6 +187,7 @@ let constructor_descrs ty_path decl cstrs = cstr_loc = cd_loc; cstr_attributes = cd_attributes; cstr_inlined; + cstr_identity = None; } in (cd_id, cstr) :: descr_rem @@ -237,6 +238,7 @@ let extension_descr path_ext ext = cstr_loc = ext.ext_loc; cstr_attributes = ext.ext_attributes; cstr_inlined; + cstr_identity = ext.ext_identity; } let none = {desc = Ttuple []; level = -1; id = -1} diff --git a/compiler/typing/depend.ml b/compiler/typing/depend.ml index 19f9d659ff..72f55ab938 100644 --- a/compiler/typing/depend.ml +++ b/compiler/typing/depend.ml @@ -95,6 +95,15 @@ let add = add_parent let addmodule bv lid = add_path bv lid.txt +(* The type checker looks up the exceptions a [@throws] names, so their + modules are dependencies, as for any other use. *) +let add_throws bv (attributes : Parsetree.attributes) = + attributes + |> List.iter (fun (({txt}, payload) : Parsetree.attribute) -> + if txt = "throws" then + Throws_attribute.names payload + |> List.iter (fun (lid, loc) -> add bv {Location.txt = lid; loc})) + let handle_extension ext = match (fst ext).txt with | "error" -> @@ -370,6 +379,7 @@ and add_case bv {pc_lhs; pc_guard; pc_rhs} = add_expr bv pc_rhs and add_bindings recf bv pel = + List.iter (fun x -> add_throws bv x.pvb_attributes) pel; let bv' = List.fold_left (fun bv x -> add_pattern bv x.pvb_pat) bv pel in let bv = if recf = Recursive then bv' else bv in List.iter (fun x -> add_expr bv x.pvb_expr) pel; @@ -425,6 +435,7 @@ and add_sig_item (bv, m) item = match item.psig_desc with | Psig_value vd -> add_type bv vd.pval_type; + add_throws bv vd.pval_attributes; (bv, m) | Psig_type (_, dcls) -> List.iter (add_type_declaration bv) dcls; @@ -507,7 +518,8 @@ and add_structure_binding bv item_list = and add_struct_item (bv, m) item : _ String_map.t * _ String_map.t = match item.pstr_desc with - | Pstr_eval (e, _attrs) -> + | Pstr_eval (e, attrs) -> + add_throws bv attrs; add_expr bv e; (bv, m) | Pstr_value (rf, pel) -> @@ -515,6 +527,7 @@ and add_struct_item (bv, m) item : _ String_map.t * _ String_map.t = (bv, m) | Pstr_primitive vd -> add_type bv vd.pval_type; + add_throws bv vd.pval_attributes; (bv, m) | Pstr_type (_, dcls) -> List.iter (add_type_declaration bv) dcls; diff --git a/compiler/typing/predef.ml b/compiler/typing/predef.ml index 4dc58a5b74..34e3abac0e 100644 --- a/compiler/typing/predef.ml +++ b/compiler/typing/predef.ml @@ -406,6 +406,7 @@ let common_initial_env add_type add_extension empty_env = Parsetree.PStr [] ); ]; ext_is_exception = true; + ext_identity = None; } in empty_env diff --git a/compiler/typing/printtyped.ml b/compiler/typing/printtyped.ml index 7b44a52ac7..81b5b61a85 100644 --- a/compiler/typing/printtyped.ml +++ b/compiler/typing/printtyped.ml @@ -607,7 +607,7 @@ and structure_item i ppf x = line i ppf "structure_item %a\n" fmt_location x.str_loc; let i = i + 1 in match x.str_desc with - | Tstr_eval (e, attrs) -> + | Tstr_eval (e, attrs, _) -> line i ppf "Tstr_eval\n"; attributes i ppf attrs; expression i ppf e diff --git a/compiler/typing/rec_check.ml b/compiler/typing/rec_check.ml index 9744e66a23..5fa639fef8 100644 --- a/compiler/typing/rec_check.ml +++ b/compiler/typing/rec_check.ml @@ -386,7 +386,7 @@ and structure : Env.env -> Typedtree.structure -> Use.t = and structure_item : Env.env -> Typedtree.structure_item -> Env.env * Use.t = fun env s -> match s.str_desc with - | Tstr_eval (e, _) -> (Env.empty, expression env e) + | Tstr_eval (e, _, _) -> (Env.empty, expression env e) | Tstr_value (rec_flag, valbinds) -> value_bindings rec_flag env valbinds | Tstr_module {mb_id; mb_expr} -> let ty = modexp env mb_expr in diff --git a/compiler/typing/subst.ml b/compiler/typing/subst.ml index ee1f26d14d..6442dab52c 100644 --- a/compiler/typing/subst.ml +++ b/compiler/typing/subst.ml @@ -293,6 +293,7 @@ let value_description s descr = val_kind = descr.val_kind; val_loc = loc s descr.val_loc; val_attributes = attrs s descr.val_attributes; + val_throws = descr.val_throws; } let extension_constructor s ext = @@ -306,6 +307,7 @@ let extension_constructor s ext = ext_attributes = attrs s ext.ext_attributes; ext_loc = loc s ext.ext_loc; ext_is_exception = ext.ext_is_exception; + ext_identity = ext.ext_identity; }) let rec rename_bound_idents s idents = function diff --git a/compiler/typing/tast_iterator.ml b/compiler/typing/tast_iterator.ml index be2375b7ec..28383e8acd 100644 --- a/compiler/typing/tast_iterator.ml +++ b/compiler/typing/tast_iterator.ml @@ -60,7 +60,7 @@ let include_infos f {incl_mod; _} = f incl_mod let structure_item sub {str_desc; str_env; _} = sub.env sub str_env; match str_desc with - | Tstr_eval (exp, _) -> sub.expr sub exp + | Tstr_eval (exp, _, _) -> sub.expr sub exp | Tstr_value (rec_flag, list) -> sub.value_bindings sub (rec_flag, list) | Tstr_primitive v -> sub.value_description sub v | Tstr_type (rec_flag, list) -> sub.type_declarations sub (rec_flag, list) diff --git a/compiler/typing/tast_mapper.ml b/compiler/typing/tast_mapper.ml index 1da305bb24..5d6a9c3006 100644 --- a/compiler/typing/tast_mapper.ml +++ b/compiler/typing/tast_mapper.ml @@ -85,7 +85,8 @@ let structure_item sub {str_desc; str_loc; str_env} = let str_env = sub.env sub str_env in let str_desc = match str_desc with - | Tstr_eval (exp, attrs) -> Tstr_eval (sub.expr sub exp, attrs) + | Tstr_eval (exp, attrs, throws) -> + Tstr_eval (sub.expr sub exp, attrs, throws) | Tstr_value (rec_flag, list) -> let rec_flag, list = sub.value_bindings sub (rec_flag, list) in Tstr_value (rec_flag, list) diff --git a/compiler/typing/throws_attribute.ml b/compiler/typing/throws_attribute.ml new file mode 100644 index 0000000000..4b057ba670 --- /dev/null +++ b/compiler/typing/throws_attribute.ml @@ -0,0 +1,166 @@ +(* A [@throws([E, M.F])] attribute names exceptions as written, so only the + type checker knows which exceptions they are: the names depend on the + opens, aliases and includes in scope. [resolve] looks each name up there. + The result is stored in the declaration ([val_throws] and [vb_throws]), and + each exception's identity in its definition ([ext_identity]), so both reach + the .cmi, and reanalyze's exception analysis compares them with the + exceptions that callers catch. *) + +(* [Lib-Ns] is the module [Lib] of namespace [Ns]. *) +let without_namespace name = + match String.index_opt name '-' with + | Some i -> String.sub name 0 i + | None -> name + +(* Where the current file defines its modules and exceptions, as module paths + within the file ([M; N; E] for [E] in [M.N]), and the module being typed. + [Typemod] records them, so exceptions get an identity and messages can name + a file's own exceptions exactly. *) +type definitions = { + mutable current: string list; (** The module being typed, outermost first *) + defined: (Ident.t, string list) Hashtbl.t; + warned: (Location.t, unit) Hashtbl.t; + (** Names already warned about: a [let] that destructures a tuple + carries its attributes on every binding *) +} + +let definitions = + Request_local.new_key (fun () -> + {current = []; defined = Hashtbl.create 16; warned = Hashtbl.create 1}) + +(* Type the module [name] with [f], recording what it defines under [name]. *) +let in_module name f = + let d = Request_local.get definitions in + let outer = d.current in + d.current <- outer @ [name]; + Fun.protect ~finally:(fun () -> d.current <- outer) f + +(* Record that the module being typed defines [id]. *) +let define id = + let d = Request_local.get definitions in + Hashtbl.replace d.defined id (d.current @ [Ident.name id]) + +(* The identity of an exception [name] that the module being typed defines: + the compilation unit and module path, as [Lib.Inner.E]. A module's .res + and .resi give it the same identity. *) +let definition_identity name = + String.concat "." + ((Env.get_unit_name () :: (Request_local.get definitions).current) @ [name]) + +(* Whether [cstr] constructs an exception, rather than another extensible + variant *) +let is_exception (cstr : Types.constructor_description) = + match (Btype.repr cstr.cstr_res).desc with + | Tconstr (path, _, _) -> Path.same path Predef.path_exn + | _ -> false + +let identity (cstr : Types.constructor_description) = + match cstr.cstr_kind with + | Extension_constructor (Pident id) when Ident.is_predef_exn id -> + Some (Ident.name id) + | Extension_constructor _ when is_exception cstr -> ( + match cstr.cstr_identity with + | Some id -> Some id + | None -> Some ("#" ^ cstr.cstr_name)) + | Extension_constructor _ | Ordinary_constructor _ -> None + +(* A readable name for messages: [Lib.E] for another module's exception, + aliases resolved, and [Lib.M.E] for one that the current file [Lib] + defines in its module [M]. *) +let display_name env (cstr : Types.constructor_description) = + let unit = without_namespace (Env.get_unit_name ()) in + let local id = + match Hashtbl.find_opt (Request_local.get definitions).defined id with + | Some path -> unit :: path + | None -> [unit; Ident.name id] + in + match cstr.cstr_kind with + | Extension_constructor (Pident id) when Ident.is_predef_exn id -> + Ident.name id + | Extension_constructor (Pident id) -> String.concat "." (local id) + | Extension_constructor (Pdot (prefix, name, _)) -> ( + let prefix = Env.normalize_path None env prefix in + match Path.flatten prefix with + | `Ok (head, rest) -> + let head = + if Ident.persistent head then [without_namespace (Ident.name head)] + else local head + in + String.concat "." (head @ rest @ [name]) + | `Contains_apply -> Path.name prefix ^ "." ^ name) + | Extension_constructor (Papply _ as path) -> Path.name path + | Ordinary_constructor _ -> cstr.cstr_name + +(* The names a [@throws] payload lists: one name, as [E] or [M.E(_)], or + several in an array, a tuple or a [list{...}]. A payload-less [@throws] + lists none. *) +let names (payload : Parsetree.payload) = + let rec of_expr (e : Parsetree.expression) = + (* A string, also a template without interpolation, names an exception + as text; braces around a payload are dropped, as for other + attributes. *) + match Ast_payload.semantic_string_of_expression e with + | Some s -> [(Longident.parse (String.trim s), e.pexp_loc)] + | None -> ( + let e = Ast_payload.unwrap_braces e in + match e.pexp_desc with + | Pexp_construct ({txt = Lident "[]"}, {txt = []}) -> [] + | Pexp_construct ({txt = Lident "::"}, {txt = [head; tail]}) -> + of_expr head @ of_expr tail + | Pexp_construct ({txt; loc}, _) | Pexp_ident {txt; loc} -> [(txt, loc)] + | Pexp_tuple es | Pexp_array es -> List.concat_map of_expr es + | _ -> []) + in + match payload with + | PStr [{pstr_desc = Pstr_eval (e, _)}] -> + (* [""] or ["Lib."] names nothing *) + of_expr e |> List.filter (fun (lid, _) -> Longident.last lid <> "") + | _ -> [] + +(* The exceptions the [@throws] in [attributes] names, with their identities. + A name that is not an exception in [env] gets a warning and is listed as + written, as its own identity. *) +let resolve env (attributes : Parsetree.attributes) : Types.throws list = + match + List.find_opt + (fun (({txt}, _) : Parsetree.attribute) -> txt = "throws") + attributes + with + | None -> [] + | Some (_, payload) -> + names payload + |> List.map (fun (lid, loc) : Types.throws -> + (* The first exception of that name: a variant constructor declared + later may shadow it, as for [throw(E)]. *) + let found = + match Env.lookup_all_constructors ~loc lid env with + | constructors -> + constructors + |> List.find_map (fun (cstr, use) -> + match identity cstr with + | Some id -> + use (); + Some + { + Types.throws_name = display_name env cstr; + throws_identity = id; + } + | None -> None) + | exception (Not_found | Env.Error _) -> None + in + (* A lowercase name is never an exception, as reanalyze's + [genericException] for [throw(e)], so it is not warned about. *) + let is_value_name = + match (Longident.last lid).[0] with + | 'A' .. 'Z' -> false + | _ -> true + in + match found with + | Some throws -> throws + | None -> + let written = String.concat "." (Longident.flatten lid) in + let warned = (Request_local.get definitions).warned in + if (not is_value_name) && not (Hashtbl.mem warned loc) then ( + Hashtbl.replace warned loc (); + Loc_report.prerr_warning loc (Warnings.Throws_unbound written)); + {throws_name = written; throws_identity = written}) diff --git a/compiler/typing/translmod.ml b/compiler/typing/translmod.ml index 8c6b170f3e..656189b2f4 100644 --- a/compiler/typing/translmod.ml +++ b/compiler/typing/translmod.ml @@ -346,7 +346,7 @@ and transl_structure loc fields cc rootpath final_env = function | _ -> Misc.fatal_error "Translmod.transl_structure") | item :: rem -> ( match item.str_desc with - | Tstr_eval (expr, attrs) -> + | Tstr_eval (expr, attrs, _) -> let body, size = transl_structure loc fields cc rootpath final_env rem in let lam = Builtin_attributes.replay_warning_scope attrs (fun () -> diff --git a/compiler/typing/typecore.ml b/compiler/typing/typecore.ml index 4fde5f8812..cb9661f38c 100644 --- a/compiler/typing/typecore.ml +++ b/compiler/typing/typecore.ml @@ -1970,6 +1970,7 @@ let add_pattern_variables ?check ?check_as env = val_kind = Val_reg; Types.val_loc = loc; val_attributes = []; + val_throws = []; } env) pv env, @@ -3421,6 +3422,7 @@ and type_expect_ ?deprecated_context ~context ?(recarg = Rejected) { val_type = instance_def (Predef.type_int ()); val_attributes = []; + val_throws = []; val_kind = Val_reg; Types.val_loc = loc; } @@ -3479,6 +3481,7 @@ and type_expect_ ?deprecated_context ~context ?(recarg = Rejected) { val_type = ty_elem; val_attributes = []; + val_throws = []; val_kind = Val_reg; Types.val_loc = loc; } env ~check:(fun s -> Warnings.Unused_for_index s) @@ -3519,6 +3522,7 @@ and type_expect_ ?deprecated_context ~context ?(recarg = Rejected) { val_type = ty_elem; val_attributes = []; + val_throws = []; val_kind = Val_reg; Types.val_loc = loc; } env ~check:(fun s -> Warnings.Unused_for_index s) @@ -5150,6 +5154,11 @@ and type_let ~context ?(check = fun s -> Warnings.Unused_var s) vb_expr = e; (* As written, like a value description's in [Typedecl]. *) vb_attributes = Ast_helper.Vb.binding_attributes pvb; + vb_throws = + Builtin_attributes.replay_warning_scope pvb.pvb_attributes + (fun () -> + Throws_attribute.resolve env + (Ast_helper.Vb.binding_attributes pvb)); vb_loc = pvb.pvb_loc; }) l spat_sexp_list diff --git a/compiler/typing/typedecl.ml b/compiler/typing/typedecl.ml index 0378aa2c45..437bdfc983 100644 --- a/compiler/typing/typedecl.ml +++ b/compiler/typing/typedecl.ml @@ -1702,14 +1702,17 @@ let transl_type_decl env rec_flag sdecl_list = let transl_extension_constructor env type_path type_params typext_params priv sext = let id = Ident.create sext.pext_name.txt in - let args, ret_type, kind = + let args, ret_type, kind, identity = match sext.pext_kind with | Pext_decl (sargs, sret_type) -> let sargs = rewrite_optional_inline_record_fields sargs in let targs, tret_type, args, ret_type, _ = make_constructor env type_path typext_params sargs sret_type in - (args, ret_type, Text_decl (targs, tret_type)) + ( args, + ret_type, + Text_decl (targs, tret_type), + Some (Throws_attribute.definition_identity sext.pext_name.txt) ) | Pext_rebind lid -> let cdescr = Typetexp.find_constructor env lid.loc lid.txt in let usage = @@ -1785,7 +1788,7 @@ let transl_extension_constructor env type_path type_params typext_params priv in Types.Cstr_record lbls in - (args, ret_type, Text_rebind (path, lid)) + (args, ret_type, Text_rebind (path, lid), Throws_attribute.identity cdescr) in let is_exception = Path.same type_path Predef.path_exn in let ext = @@ -1798,6 +1801,9 @@ let transl_extension_constructor env type_path type_params typext_params priv ext_loc = sext.pext_loc; ext_attributes = sext.pext_attributes; ext_is_exception = is_exception; + (* For exception analysis; a rebound exception carries the identity of + the exception it rebinds. *) + ext_identity = (if is_exception then identity else None); } in { @@ -2057,6 +2063,7 @@ let transl_value_decl ?inline env loc valdecl = let attributes = Ast_helper.Val.description_attributes {valdecl with pval_attributes} in + let throws = Throws_attribute.resolve env attributes in let v = match prim with | None when Env.is_in_signature env -> @@ -2065,6 +2072,7 @@ let transl_value_decl ?inline env loc valdecl = val_kind = Val_reg; Types.val_loc = loc; val_attributes = attributes; + val_throws = throws; } | None -> (* unreachable: `pval_prim = None` outside a signature can only arise @@ -2105,6 +2113,7 @@ let transl_value_decl ?inline env loc valdecl = else Val_prim prim); Types.val_loc = loc; val_attributes = attributes; + val_throws = throws; } in let id, newenv = diff --git a/compiler/typing/typedtree.ml b/compiler/typing/typedtree.ml index 1a688c604c..4c6846ca3b 100644 --- a/compiler/typing/typedtree.ml +++ b/compiler/typing/typedtree.ml @@ -216,7 +216,7 @@ and structure_item = { } and structure_item_desc = - | Tstr_eval of expression * attributes + | Tstr_eval of expression * attributes * Types.throws list | Tstr_value of rec_flag * value_binding list | Tstr_primitive of value_description | Tstr_type of rec_flag * type_declaration list @@ -241,6 +241,7 @@ and value_binding = { vb_pat: pattern; vb_expr: expression; vb_attributes: attributes; + vb_throws: Types.throws list; (** The exceptions its [@throws] names *) vb_loc: Location.t; } diff --git a/compiler/typing/typedtree.mli b/compiler/typing/typedtree.mli index 558cc3821f..ad5d4d8ff2 100644 --- a/compiler/typing/typedtree.mli +++ b/compiler/typing/typedtree.mli @@ -345,7 +345,7 @@ and structure_item = { } and structure_item_desc = - | Tstr_eval of expression * attributes + | Tstr_eval of expression * attributes * Types.throws list | Tstr_value of rec_flag * value_binding list | Tstr_primitive of value_description | Tstr_type of rec_flag * type_declaration list @@ -370,6 +370,7 @@ and value_binding = { vb_pat: pattern; vb_expr: expression; vb_attributes: attributes; + vb_throws: Types.throws list; (** The exceptions its [@throws] names *) vb_loc: Location.t; } diff --git a/compiler/typing/typedtree_iter.ml b/compiler/typing/typedtree_iter.ml index 1820ab7f0f..d94ec04105 100644 --- a/compiler/typing/typedtree_iter.ml +++ b/compiler/typing/typedtree_iter.ml @@ -114,7 +114,7 @@ end = struct and iter_structure_item item = Iter.enter_structure_item item; (match item.str_desc with - | Tstr_eval (exp, _attrs) -> iter_expression exp + | Tstr_eval (exp, _attrs, _) -> iter_expression exp | Tstr_value (rec_flag, list) -> iter_bindings rec_flag list | Tstr_primitive vd -> iter_value_description vd | Tstr_type (rf, list) -> iter_type_declarations rf list diff --git a/compiler/typing/typemod.ml b/compiler/typing/typemod.ml index d0480a21cf..ecfb13b881 100644 --- a/compiler/typing/typemod.ml +++ b/compiler/typing/typemod.ml @@ -814,6 +814,10 @@ and transl_signature env sg = let tyext, newenv = Typedecl.transl_type_extension false env item.psig_loc styext in + List.iter + (fun (ext : Typedtree.extension_constructor) -> + Throws_attribute.define ext.ext_id) + tyext.tyext_constructors; let trem, rem, final_env = transl_sig newenv srem in let constructors = tyext.tyext_constructors in ( mksig (Tsig_typext tyext) env loc :: trem, @@ -824,6 +828,7 @@ and transl_signature env sg = | Psig_exception sext -> check_name check_typext names sext.pext_name; let ext, newenv = Typedecl.transl_exception env sext in + Throws_attribute.define ext.ext_id; let trem, rem, final_env = transl_sig newenv srem in ( mksig (Tsig_exception ext) env loc :: trem, Sig_typext (ext.ext_id, ext.ext_type, Text_exception) :: rem, @@ -831,9 +836,11 @@ and transl_signature env sg = | Psig_module pmd -> check_name check_module names pmd.pmd_name; let id = Ident.create pmd.pmd_name.txt in + Throws_attribute.define id; let tmty = Builtin_attributes.warning_scope pmd.pmd_attributes (fun () -> - transl_modtype env pmd.pmd_type) + Throws_attribute.in_module pmd.pmd_name.txt (fun () -> + transl_modtype env pmd.pmd_type)) in let md = { @@ -927,7 +934,10 @@ and transl_modtype_decl names env pmtd = and transl_modtype_decl_aux names env {pmtd_name; pmtd_type; pmtd_attributes; pmtd_loc} = check_name check_modtype names pmtd_name; - let tmty = Option.map (transl_modtype env) pmtd_type in + let tmty = + Throws_attribute.in_module pmtd_name.txt (fun () -> + Option.map (transl_modtype env) pmtd_type) + in let decl = { Types.mtd_type = Option.map (fun t -> t.mty_type) tmty; @@ -963,12 +973,14 @@ and transl_recmodule_modtypes env sdecls = (fun pmd (id, id_loc, _mty) -> let tmty = Builtin_attributes.warning_scope pmd.pmd_attributes (fun () -> - transl_modtype env_c pmd.pmd_type) + Throws_attribute.in_module pmd.pmd_name.txt (fun () -> + transl_modtype env_c pmd.pmd_type)) in (id, id_loc, tmty)) sdecls curr in let ids = List.map (fun x -> Ident.create x.pmd_name.txt) sdecls in + List.iter Throws_attribute.define ids; let approx_env = (* cf #5965 @@ -1429,11 +1441,12 @@ and type_structure funct_body anchor env sstr = let type_str_item env {pstr_loc = loc; pstr_desc = desc} = match desc with | Pstr_eval (sexpr, attrs) -> - let expr = + let expr, throws = Builtin_attributes.warning_scope attrs (fun () -> - Typecore.type_expression ~context:None env sexpr) + ( Typecore.type_expression ~context:None env sexpr, + Throws_attribute.resolve env attrs )) in - (Tstr_eval (expr, attrs), [], env) + (Tstr_eval (expr, attrs, throws), [], env) | Pstr_value (rec_flag, sdefs) -> ( match Ast_external_mk.inline_const_of_binding rec_flag sdefs with | Some (sdesc, inline) -> @@ -1484,21 +1497,25 @@ and type_structure funct_body anchor env sstr = (* The environment keeps let-bound values without attributes, so uses in this module do not warn. The signature carries their [deprecated] attributes, so uses from other modules do, and their [throws] - attributes, which reanalyze's exception analysis reads at calls - from other modules. Other attributes stay out: a doc comment in the - .cmi would make editing it recompile the module's dependents. *) + attributes and the exceptions these name, which reanalyze's + exception analysis reads at calls from other modules. Other + attributes stay out: a doc comment in the .cmi would make editing + it recompile the module's dependents. *) let signature_attributes = List.concat_map (fun (vb : value_binding) -> match - Builtin_attributes.deprecated_attributes vb.vb_attributes - @ List.filter - (fun ({txt}, _) -> txt = "throws") - vb.vb_attributes + ( Builtin_attributes.deprecated_attributes vb.vb_attributes + @ List.filter + (fun ({txt}, _) -> txt = "throws") + vb.vb_attributes, + vb.vb_throws ) with - | [] -> [] - | attrs -> - List.map (fun id -> (id, attrs)) (pat_bound_idents vb.vb_pat)) + | [], [] -> [] + | attrs, throws -> + List.map + (fun id -> (id, (attrs, throws))) + (pat_bound_idents vb.vb_pat)) defs in (* Note: Env.find_value does not trigger the value_used event. Values @@ -1514,8 +1531,12 @@ and type_structure funct_body anchor env sstr = signature_attributes with | None -> vd - | Some (_, attrs) -> - {vd with val_attributes = attrs @ vd.val_attributes} + | Some (_, (attrs, throws)) -> + { + vd with + val_attributes = attrs @ vd.val_attributes; + val_throws = throws; + } in Sig_value (id, vd)) (let_bound_idents defs), @@ -1594,6 +1615,10 @@ and type_structure funct_body anchor env sstr = (fun pext -> check_name check_typext names pext.pext_name) styext.ptyext_constructors; let tyext, newenv = Typedecl.transl_type_extension true env loc styext in + List.iter + (fun (ext : Typedtree.extension_constructor) -> + Throws_attribute.define ext.ext_id) + tyext.tyext_constructors; ( Tstr_typext tyext, map_ext (fun es ext -> Sig_typext (ext.ext_id, ext.ext_type, es)) @@ -1602,6 +1627,7 @@ and type_structure funct_body anchor env sstr = | Pstr_exception sext -> check_name check_typext names sext.pext_name; let ext, newenv = Typedecl.transl_exception env sext in + Throws_attribute.define ext.ext_id; ( Tstr_exception ext, [Sig_typext (ext.ext_id, ext.ext_type, Text_exception)], newenv ) @@ -1621,11 +1647,13 @@ and type_structure funct_body anchor env sstr = in Inline_not_stored.record_binding attrs (module_attributes smodl) (fun () -> [id]); + Throws_attribute.define id; let modl = Builtin_attributes.warning_scope attrs (fun () -> - type_module ~alias:true true funct_body - (anchor_submodule name.txt anchor) - env smodl) + Throws_attribute.in_module name.txt (fun () -> + type_module ~alias:true true funct_body + (anchor_submodule name.txt anchor) + env smodl)) in let md = { @@ -1692,7 +1720,9 @@ and type_structure funct_body anchor env sstr = (* [transl_recmodule_modtypes] reported these attributes *) let modl = Builtin_attributes.replay_warning_scope attrs (fun () -> - type_module true funct_body (anchor_recmodule id) newenv smodl) + Throws_attribute.in_module name.txt (fun () -> + type_module true funct_body (anchor_recmodule id) newenv + smodl)) in let mty' = enrich_module_type anchor (Ident.name id) modl.mod_type newenv diff --git a/compiler/typing/types.ml b/compiler/typing/types.ml index e466261ef3..171858e4c4 100644 --- a/compiler/typing/types.ml +++ b/compiler/typing/types.ml @@ -85,11 +85,16 @@ module Vars = Map.Make (Ordered_string) (* Value descriptions *) +(* An exception that a [@throws] names, as the type checker resolved it: + a name for messages, and the exception's identity (see [ext_identity]). *) +type throws = {throws_name: string; throws_identity: string} + type value_description = { val_type: type_expr; (* Type of the value *) val_kind: value_kind; val_loc: Location.t; val_attributes: Parsetree.attributes; + val_throws: throws list; (* The exceptions its [@throws] names *) } and value_kind = @@ -216,6 +221,10 @@ type extension_constructor = { ext_loc: Location.t; ext_attributes: Parsetree.attributes; ext_is_exception: bool; + ext_identity: string option; + (* For an exception, the unit and module path that define it, as + [Lib.Inner.E]; for a rebinding, the identity of the exception it + rebinds. Exception analysis compares these. *) } (* Type expressions for the class language *) @@ -278,6 +287,7 @@ type constructor_description = { cstr_loc: Location.t; cstr_attributes: Parsetree.attributes; cstr_inlined: type_declaration option; + cstr_identity: string option; (* The [ext_identity] of an exception *) } and constructor_kind = diff --git a/compiler/typing/types.mli b/compiler/typing/types.mli index 6f5e80a7b2..cedbae58fe 100644 --- a/compiler/typing/types.mli +++ b/compiler/typing/types.mli @@ -190,11 +190,16 @@ module Vars : Map.S with type key = string (* Value descriptions *) +(* An exception that a [@throws] names, as the type checker resolved it: + a name for messages, and the exception's identity (see [ext_identity]). *) +type throws = {throws_name: string; throws_identity: string} + type value_description = { val_type: type_expr; (* Type of the value *) val_kind: value_kind; val_loc: Location.t; val_attributes: Parsetree.attributes; + val_throws: throws list; (* The exceptions its [@throws] names *) } and value_kind = @@ -315,6 +320,10 @@ type extension_constructor = { ext_loc: Location.t; ext_attributes: Parsetree.attributes; ext_is_exception: bool; + ext_identity: string option; + (* For an exception, the unit and module path that define it, as + [Lib.Inner.E]; for a rebinding, the identity of the exception it + rebinds. Exception analysis compares these. *) } module Concr : Set.S with type elt = string @@ -375,6 +384,7 @@ type constructor_description = { cstr_loc: Location.t; cstr_attributes: Parsetree.attributes; cstr_inlined: type_declaration option; + cstr_identity: string option; (* The [ext_identity] of an exception *) } and constructor_kind = diff --git a/compiler/typing/warnings.ml b/compiler/typing/warnings.ml index 6d98ad2126..ca308aec92 100644 --- a/compiler/typing/warnings.ml +++ b/compiler/typing/warnings.ml @@ -76,6 +76,7 @@ type t = | Bs_private_record_mutation of string (* 111 *) | Bs_record_rest_optional_overlap of string list (* 112 *) | Inline_not_stored of string * string (* 113 *) + | Throws_unbound of string (* 114 *) (* If you remove a warning, leave a hole in the numbering. NEVER change the numbers of existing warnings. @@ -130,8 +131,9 @@ let number = function | Bs_private_record_mutation _ -> 111 | Bs_record_rest_optional_overlap _ -> 112 | Inline_not_stored _ -> 113 + | Throws_unbound _ -> 114 -let last_warning_number = 113 +let last_warning_number = 114 let letter_all = let rec loop i = if i = 0 then [] else i :: loop (i - 1) in @@ -471,6 +473,11 @@ let message = function ^ "." | Bs_private_record_mutation field_name -> Printf.sprintf "Mutation of private record field %S." field_name + | Throws_unbound name -> + Printf.sprintf + "@throws names %s, which is not an exception in scope here. Exception \ + analysis cannot match it with the exceptions callers catch." + name let sub_locs = function | Deprecated (_, def, use, _) -> @@ -570,6 +577,7 @@ let descriptions = (111, "Mutation of private record field"); (112, "Record rest pattern will always be empty"); (113, "@inline function inlined only in its own module"); + (114, "@throws names something that is not an exception in scope"); ] let help_warnings () = diff --git a/compiler/typing/warnings.mli b/compiler/typing/warnings.mli index 71d9e4c865..0dea70c781 100644 --- a/compiler/typing/warnings.mli +++ b/compiler/typing/warnings.mli @@ -69,6 +69,7 @@ type t = | Bs_private_record_mutation of string (* 111 *) | Bs_record_rest_optional_overlap of string list (* 112 *) | Inline_not_stored of string * string (* 113 *) + | Throws_unbound of string (* 114 *) val parse_options : bool -> string -> unit diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt b/tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt index 3901901800..96bd1c757a 100644 --- a/tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt +++ b/tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt @@ -203,5 +203,41 @@ Exception Analysis ThrowsDeclCalls.res:37:5-22 callViaLetIncluded might throw Not_found (ThrowsDeclCalls.res:37:30) and is not annotated with @throws(Not_found) + + Exception Analysis + ThrowsLibExnCalls.res:42:5-23 + catchUnrelatedLocal might throw ThrowsLibExn.E (ThrowsLibExnCalls.res:43:6) and is not annotated with @throws(ThrowsLibExn.E) + + Exception Analysis + ThrowsLibExnCalls.res:48:5-12 + uncaught might throw ThrowsLibExn.E (ThrowsLibExnCalls.res:48:20) and is not annotated with @throws(ThrowsLibExn.E) + + Exception Analysis + ThrowsLibExnCalls.res:110:5-18 + uncaughtNested might throw ThrowsLibExn.Inner.F (ThrowsLibExnCalls.res:110:26) and is not annotated with @throws(ThrowsLibExn.Inner.F) + + Exception Analysis + ThrowsLibExnCalls.res:112:5-17 + uncaughtLocal might throw Local.G (ThrowsLibExnCalls.res:112:25) and is not annotated with @throws(Local.G) + + Exception Analysis + ThrowsScopes.res:66:5-19 + catchOnlyOuterE might throw RecA.E (ThrowsScopes.res:67:6) and is not annotated with @throws(RecA.E) + + Exception Analysis + ThrowsScopes.res:106:5-20 + catchSealedPlain might throw SealedPlain.E (ThrowsScopes.res:107:6) and is not annotated with @throws(SealedPlain.E) + + Exception Analysis + ThrowsScopes.res:126:7-14 + uncaught might throw NestE (ThrowsScopes.res:126:23) and is not annotated with @throws(NestE) + + Exception Analysis + ThrowsScopes.res:141:3-5 + Toplevel expression might throw TopE (ThrowsScopes.res:141:2) and is not annotated with @throws(TopE) + + Exception Analysis + ThrowsScopes.res:158:9-12 + both might throw [Shadowing.E (ThrowsScopes.res:160:6), Shadowing.Inner.E (ThrowsScopes.res:159:6)] and is not annotated with @throws([Shadowing.E, Shadowing.Inner.E]) - Analysis reported 51 issues (Exception Analysis:51) + Analysis reported 60 issues (Exception Analysis:60) diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsAlias.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsAlias.res new file mode 100644 index 0000000000..4f7e46fb8b --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsAlias.res @@ -0,0 +1 @@ +module L = ThrowsLibExn diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsErrors.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsErrors.res new file mode 100644 index 0000000000..48e4679f14 --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsErrors.res @@ -0,0 +1,2 @@ +exception NotFound +exception Bad(string) diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsIfaceOpen.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsIfaceOpen.res new file mode 100644 index 0000000000..8b162746f4 --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsIfaceOpen.res @@ -0,0 +1,2 @@ +@throws(ThrowsErrors.NotFound) +let find = x => x > 0 ? x : throw(ThrowsErrors.NotFound) diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsIfaceOpen.resi b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsIfaceOpen.resi new file mode 100644 index 0000000000..f0b1cd1ed7 --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsIfaceOpen.resi @@ -0,0 +1,4 @@ +open ThrowsErrors + +@throws(NotFound) +let find: int => int diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExn.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExn.res new file mode 100644 index 0000000000..94d39a657d --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExn.res @@ -0,0 +1,24 @@ +exception E + +@throws(E) +external parse: string => int = "parseThrowing" + +@throws(E) +let viaLet = x => x > 0 ? x : throw(E) + +module Inner = { + exception F + + @throws(F) + external find: int => int = "findThrowing" +} + +module Outer = { + @throws(E) + external findOuter: int => int = "findOuterThrowing" +} + +module type S = { + @throws(E) + let get: int => int +} diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExnCalls.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExnCalls.res new file mode 100644 index 0000000000..b7a8f57a53 --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExnCalls.res @@ -0,0 +1,115 @@ +// Calls into ThrowsLibExn, which declares its own exceptions. A catch names +// an exception by where it is defined, however the source spells it. + +let catchExternal = s => + try ThrowsLibExn.parse(s) catch { + | ThrowsLibExn.E => 0 + } + +let catchViaLet = x => + try ThrowsLibExn.viaLet(x) catch { + | ThrowsLibExn.E => 0 + } + +let catchNested = x => + try ThrowsLibExn.Inner.find(x) catch { + | ThrowsLibExn.Inner.F => 0 + } + +// The declaration in ThrowsLibExn.Outer names the top-level E. +let catchOuter = x => + try ThrowsLibExn.Outer.findOuter(x) catch { + | ThrowsLibExn.E => 0 + } + +let catchOpen = s => { + open ThrowsLibExn + try parse(s) catch { + | E => 0 + } +} + +module L = ThrowsLibExn + +let catchAlias = s => + try L.parse(s) catch { + | L.E => 0 + } + +exception E + +// This file's own E is a different exception: reported. +let catchUnrelatedLocal = s => + try ThrowsLibExn.parse(s) catch { + | E => 0 + } + +// Not caught: reported with the qualified name. +let uncaught = s => ThrowsLibExn.parse(s) + +@throws(ThrowsLibExn.E) +let annotated = s => ThrowsLibExn.parse(s) + +// Same file: a nested module's exception, reached through open. +module Local = { + exception G + + @throws(G) + let find = x => x > 0 ? x : throw(G) +} + +let catchLocalOpen = x => { + open Local + try find(x) catch { + | G => 0 + } +} + +let catchLocalQualified = x => + try Local.find(x) catch { + | Local.G => 0 + } + +// Outer.findOuter's @throws(E) names ThrowsLibExn.E. +@throws(ThrowsLibExn.E) +let annotatedOuter = x => ThrowsLibExn.Outer.findOuter(x) + +// A rebound exception is the exception it rebinds, so catching Rebound +// catches ThrowsLibExn.E. +exception Rebound = ThrowsLibExn.E + +let catchRebound = s => + try ThrowsLibExn.parse(s) catch { + | Rebound => 0 + } + +let catchReexported = s => + try ThrowsReexport.parse(s) catch { + | ThrowsLibExn.E => 0 + } + +module LocalReexport = { + include ThrowsLibExn +} + +let catchLocalReexport = s => + try LocalReexport.parse(s) catch { + | ThrowsLibExn.E => 0 + } + +// X.get's @throws(E) is resolved where the module type S declares it, so it +// is ThrowsLibExn.E. +module UseS = (X: ThrowsLibExn.S) => { + let caught = x => + try X.get(x) catch { + | ThrowsLibExn.E => 0 + } +} + +// Reported with the exceptions' full names, which an annotation can use. +let uncaughtNested = x => ThrowsLibExn.Inner.find(x) + +let uncaughtLocal = x => Local.find(x) + +@throws(Local.G) +let annotatedLocal = x => Local.find(x) diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsReexport.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsReexport.res new file mode 100644 index 0000000000..199350e603 --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsReexport.res @@ -0,0 +1 @@ +include ThrowsLibExn diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsRepo.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsRepo.res new file mode 100644 index 0000000000..5c595a3aa3 --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsRepo.res @@ -0,0 +1,22 @@ +// Functions that throw exceptions defined in another module, ThrowsErrors. + +@throws(ThrowsErrors.NotFound) +let find = x => x > 0 ? x : throw(ThrowsErrors.NotFound) + +@throws(ThrowsErrors.NotFound) +external findExternal: int => int = "findExternal" + +module L = ThrowsErrors + +@throws(L.NotFound) +let viaAlias = x => x > 0 ? x : throw(L.NotFound) + +open ThrowsErrors + +@throws(Bad) +let viaOpen = x => x > 0 ? x : throw(Bad("negative")) + +let catchViaOpen = x => + try viaOpen(x) catch { + | Bad(_) => 0 + } diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsRepoCalls.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsRepoCalls.res new file mode 100644 index 0000000000..89773494e6 --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsRepoCalls.res @@ -0,0 +1,29 @@ +// Calls into ThrowsRepo, whose annotations name exceptions of ThrowsErrors. + +let catchFind = x => + try ThrowsRepo.find(x) catch { + | ThrowsErrors.NotFound => 0 + } + +let catchFindExternal = x => + try ThrowsRepo.findExternal(x) catch { + | ThrowsErrors.NotFound => 0 + } + +let catchViaAlias = x => + try ThrowsRepo.viaAlias(x) catch { + | ThrowsErrors.NotFound => 0 + } + +let catchViaOpen = x => + try ThrowsRepo.viaOpen(x) catch { + | ThrowsErrors.Bad(_) => 0 + } + +@throws(ThrowsErrors.NotFound) +let annotated = x => ThrowsRepo.find(x) + +open ThrowsErrors + +@throws(NotFound) +let annotatedViaOpen = x => ThrowsRepo.find(x) diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsScopes.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsScopes.res new file mode 100644 index 0000000000..688c5de676 --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsScopes.res @@ -0,0 +1,163 @@ +// An interface's @throws is resolved after the interface's own open. +let catchIfaceOpen = x => + try ThrowsIfaceOpen.find(x) catch { + | ThrowsErrors.NotFound => 0 + } + +// An alias of an alias in another file +module M = ThrowsAlias.L + +let catchAliasChain = s => + try M.parse(s) catch { + | M.E => 0 + } + +// An include of an include +module Twice = { + include ThrowsReexport +} + +let catchIncludedTwice = s => + try Twice.parse(s) catch { + | ThrowsLibExn.E => 0 + } + +// A functor body's own exception +module MakeThrower = (X: {}) => { + exception Inner + + @throws(Inner) + let throwInner = x => x > 0 ? x : throw(Inner) + + let catchInner = x => + try throwInner(x) catch { + | Inner => 0 + } +} + +// A list payload +@throws(list{ThrowsErrors.NotFound, Not_found}) +let listPayload = x => x > 0 ? throw(Not_found) : throw(ThrowsErrors.NotFound) + +// An exception of the runtime, whose .cmi keeps no locations +@throws(Lazy.Undefined) +let lazyUndefined = () => throw(Lazy.Undefined) + +let catchLazyUndefined = () => + try lazyUndefined() catch { + | Lazy.Undefined => 0 + } + +// A recursive module's own exception is not the file's E: reported. +exception E + +module rec RecA: { + exception E + + @throws(E) + let f: int => int +} = { + exception E + + @throws(E) + let f = x => x > 0 ? x : throw(E) +} + +let catchOnlyOuterE = x => + try RecA.f(x) catch { + | E => 0 + } + +// A module sealed with a module type whose let declares the @throws: the +// declaration's exception is the one callers catch. +module type SealedType = { + exception E + + @throws(E) + let f: unit => unit +} + +module Sealed: SealedType = { + exception E + + @throws(E) + let f = () => throw(E) +} + +let catchSealed = () => + try Sealed.f() catch { + | Sealed.E => () + } + +// Known limit: when only the implementation declares the @throws, its E is +// the implementation's own, while callers see the module type's E: reported. +module type SealedPlainType = { + exception E + let f: unit => unit +} + +module SealedPlain: SealedPlainType = { + exception E + + @throws(E) + let f = () => throw(E) +} + +let catchSealedPlain = () => + try SealedPlain.f() catch { + | SealedPlain.E => () + } + +// A variant constructor declared later does not hide the exception. +exception Shadow + +type shadowing = Shadow | Other + +@throws(Shadow) +let throwShadow = () => throw(Shadow) + +// Messages name an exception as the code they are about would. +module Nest = { + exception NestE + + @throws(NestE) + let f = () => throw(NestE) + + let uncaught = () => f() +} + +// A template string names an exception as a string does. +@throws(`Not_found`) +let templatePayload = () => throw(Not_found) + +// A top-level expression in a nested module: the message names TopE as the +// code there would. +module Top = { + exception TopE + + @throws(TopE) + let f = () => throw(TopE) + + f() +} + +// Two exceptions that shortening would give the same name keep their full +// names. +module Shadowing = { + exception E + + @throws(E) + let g = () => throw(E) + + module Inner = { + exception E + + @throws(E) + let f = () => throw(E) + + let both = () => { + f() + g() + } + } +} diff --git a/tests/build_tests/projects/throws_dependency/input.js b/tests/build_tests/projects/throws_dependency/input.js new file mode 100644 index 0000000000..f93196379f --- /dev/null +++ b/tests/build_tests/projects/throws_dependency/input.js @@ -0,0 +1,18 @@ +// @ts-check + +// A module named only in a @throws is a dependency: the type checker looks +// the exception up, so the module is built first and the name resolves. + +import * as assert from "node:assert"; +import { stripVTControlCharacters } from "node:util"; +import { setup } from "#dev/process"; + +const { execBuild, execClean } = setup(import.meta.dirname); + +await execClean(); +const output = await execBuild(); +const all = stripVTControlCharacters(output.stdout + output.stderr); + +assert.equal(output.status, 0, all); +assert.doesNotMatch(all, /Warning number 114/); +await execClean(); diff --git a/tests/build_tests/projects/throws_dependency/rescript.json b/tests/build_tests/projects/throws_dependency/rescript.json new file mode 100644 index 0000000000..338982f83d --- /dev/null +++ b/tests/build_tests/projects/throws_dependency/rescript.json @@ -0,0 +1,10 @@ +{ + "name": "throws_dependency", + "sources": ["src"], + "package-specs": { + "module": "esmodule", + "in-source": true + }, + "suffix": ".res.js", + "dependencies": [] +} diff --git a/tests/build_tests/projects/throws_dependency/src/A.res b/tests/build_tests/projects/throws_dependency/src/A.res new file mode 100644 index 0000000000..a8f4ed3379 --- /dev/null +++ b/tests/build_tests/projects/throws_dependency/src/A.res @@ -0,0 +1,4 @@ +// Z is named only in @throws. The type checker looks up Z.E, so Z must be +// built first. +@throws(Z.E) +external find: int => int = "find" diff --git a/tests/build_tests/projects/throws_dependency/src/Z.res b/tests/build_tests/projects/throws_dependency/src/Z.res new file mode 100644 index 0000000000..1c3424a79a --- /dev/null +++ b/tests/build_tests/projects/throws_dependency/src/Z.res @@ -0,0 +1 @@ +exception E diff --git a/tests/error_tests/single/expected/throws_unbound_warning.res.expected b/tests/error_tests/single/expected/throws_unbound_warning.res.expected new file mode 100644 index 0000000000..9ffc7a10aa --- /dev/null +++ b/tests/error_tests/single/expected/throws_unbound_warning.res.expected @@ -0,0 +1,47 @@ + + Warning number 114 + /.../fixtures/throws_unbound_warning.res:3:9-15 + + 1 │ type t = NotAnException + 2 │ + 3 │ @throws(Missing) + 4 │ let f = () => 1 + 5 │ + + @throws names Missing, which is not an exception in scope here. Exception analysis cannot match it with the exceptions callers catch. + + + Warning number 114 + /.../fixtures/throws_unbound_warning.res:6:21-34 + + 4 │ let f = () => 1 + 5 │ + 6 │ @throws([Not_found, NotAnException]) + 7 │ external g: int => int = "g" + 8 │ + + @throws names NotAnException, which is not an exception in scope here. Exception analysis cannot match it with the exceptions callers catch. + + + Warning number 114 + /.../fixtures/throws_unbound_warning.res:13:9-19 + + 11 │ + 12 │ // Warned once, though the pattern binds two names + 13 │ @throws(AlsoMissing) + 14 │ let (p, q) = (1, 2) + 15 │ + + @throws names AlsoMissing, which is not an exception in scope here. Exception analysis cannot match it with the exceptions callers catch. + + + Warning number 114 + /.../fixtures/throws_unbound_warning.res:27:9-11 + + 25 │ type ext += Ext + 26 │ + 27 │ @throws(Ext) + 28 │ let notExn = () => 5 + 29 │ + + @throws names Ext, which is not an exception in scope here. Exception analysis cannot match it with the exceptions callers catch. \ No newline at end of file diff --git a/tests/error_tests/single/fixtures/throws_unbound_warning.res b/tests/error_tests/single/fixtures/throws_unbound_warning.res new file mode 100644 index 0000000000..6dc373e623 --- /dev/null +++ b/tests/error_tests/single/fixtures/throws_unbound_warning.res @@ -0,0 +1,35 @@ +type t = NotAnException + +@throws(Missing) +let f = () => 1 + +@throws([Not_found, NotAnException]) +external g: int => int = "g" + +@throws +let h = () => 2 + +// Warned once, though the pattern binds two names +@throws(AlsoMissing) +let (p, q) = (1, 2) + +@warning("-114") @throws(Silenced) +let quiet = () => 3 + +// A lowercase name is never an exception: no warning +@throws(genericException) +let lower = () => 4 + +// An extensible variant's constructor is not an exception +type ext = .. +type ext += Ext + +@throws(Ext) +let notExn = () => 5 + +// An empty name names nothing: no crash, no warning +@throws("") +let empty = () => 6 + +@throws("Lib.") +let trailingDot = () => 7 diff --git a/tests/ounit_tests/ounit_deferred_signature_tests.ml b/tests/ounit_tests/ounit_deferred_signature_tests.ml index 1033f56576..b77e11ff03 100644 --- a/tests/ounit_tests/ounit_deferred_signature_tests.ml +++ b/tests/ounit_tests/ounit_deferred_signature_tests.ml @@ -140,6 +140,7 @@ let value name = val_kind = Val_reg; val_loc = Location.none; val_attributes = []; + val_throws = []; } ) let forged_crc = Digest.string "ounit_deferred_signature_tests forged crc" diff --git a/tests/ounit_tests/ounit_rec_check_tests.ml b/tests/ounit_tests/ounit_rec_check_tests.ml index 6f2f747492..6f82e566bf 100644 --- a/tests/ounit_tests/ounit_rec_check_tests.ml +++ b/tests/ounit_tests/ounit_rec_check_tests.ml @@ -4,7 +4,13 @@ let loc = Location.none let typ = Predef.type_unit () let val_desc = - {Types.val_type = typ; val_kind = Val_reg; val_loc = loc; val_attributes = []} + { + Types.val_type = typ; + val_kind = Val_reg; + val_loc = loc; + val_attributes = []; + val_throws = []; + } let ident_expr id = { @@ -41,7 +47,13 @@ let record_rest_pat rest_ident = } let value_binding ~pat ~expr = - {Typedtree.vb_pat = pat; vb_expr = expr; vb_attributes = []; vb_loc = loc} + { + Typedtree.vb_pat = pat; + vb_expr = expr; + vb_attributes = []; + vb_throws = []; + vb_loc = loc; + } let suites = __FILE__