From 18ed1905f268d32a97fa9ede6f3861ebbad00a8c Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 3 Nov 2026 18:23:54 +0000 Subject: [PATCH 1/4] Read @throws from library declarations in exception analysis MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why: The exception analysis knew what library functions throw only from a table kept by hand in exn_lib.ml. The table drifted: the Temporal `fromStringOrThrow` functions were never added (#9182), and neither were a few Intl and Belt ones. Third-party libraries and a project's own externals had no way to say what they throw. A call now takes the exceptions named by the `@throws` on the declaration of the value it calls, and the table is gone. The `.cmi` keeps the attributes of externals and interface declarations, so their `@throws` reaches calls in other modules and packages, through aliases, `open`, `include`, functors and first-class modules. For a `let` in a module without an interface, the type checker now copies the binding's `@throws` into the inferred signature, as it already did for `@deprecated`. The stdlib and Belt declare what their throwing functions throw, and a guard in the reanalyze tests fails when a stdlib or Belt `*OrThrow` or `*Exn` declaration has no `@throws(...)`. Analysis modified (exceptions of a call to `f`, `Exception.Event` loop): Before (rule): throws(`f`) = values(`f`) when `f` is in the values table throws(`f`) = table(`f`) otherwise After (rule): throws(`f`) = declared(`f`) ∪ values(`f`) Signature modified (inferred signature of a module without an interface, `Typemod.type_structure`): Example: /** Finds the value. */ @throws(Not_found) let find = x => x > 0 ? x : throw(Not_found) Before (rescript): the signature in the .cmi let find: int => int After (rescript): @throws(Not_found) let find: int => int Reanalyze modified (calls to annotated externals): Example: // Lib.res @throws(JsExn) external parse: string => int = "parseInt" // App.res let parse = s => Lib.parse(s) @throws(JsExn) let parseAnnotated = s => Lib.parse(s) let date = () => Temporal.PlainDate.fromStringOrThrow("x") Before (reanalyze): Exception Analysis App.res:4:5-18 parseAnnotated throws nothing and is annotated with redundant @throws(JsExn) Analysis reported 1 issues (Exception Analysis:1) After (reanalyze): Exception Analysis App.res:1:5-9 parse might throw JsExn (App.res:1:17) and is not annotated with @throws(JsExn) Exception Analysis App.res:6:5-8 date might throw JsExn (App.res:6:17) and is not annotated with @throws(JsExn) Analysis reported 2 issues (Exception Analysis:2) Review: Why the union of the declaration and the values table, rather than one winning? The values table holds the `@throws` on the implementation's binding, the declaration the one in its interface. Either can be the only one written, as with an annotated `.resi` `let` whose `.res` isn't annotated, so the call can throw what either names. Review: Why does the inferred signature take only the `@throws` family and `@deprecated`, and not every attribute? A doc comment is an attribute too: in the `.cmi` it would make editing a comment recompile the module's dependents. A module with a `.resi` is unchanged, since its `.cmi` holds the interface's declarations. Review: What does a `@throws` without a payload mean? Nothing, as on a binding. The guard requires a payload, and the stdlib's two payload-less `@throws` in Stdlib_JSON.res now name `JsExn`. Fixes #9182 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gGhHjzBTXqSo8Dckpb Signed-off-by: Christoph Knittel --- analysis/reanalyze/src/exception.ml | 74 ++++--- analysis/reanalyze/src/exn.ml | 8 - analysis/reanalyze/src/exn.mli | 8 - analysis/reanalyze/src/exn_lib.ml | 200 ------------------ ...nalyze-throws-from-declarations.feature.md | 1 + compiler/ml/typemod.ml | 17 +- packages/@rescript/belt/src/Belt_Array.resi | 4 + packages/@rescript/belt/src/Belt_List.resi | 6 + packages/@rescript/belt/src/Belt_Map.resi | 2 + packages/@rescript/belt/src/Belt_MapDict.resi | 2 + packages/@rescript/belt/src/Belt_MapInt.resi | 2 + .../@rescript/belt/src/Belt_MapString.resi | 2 + .../@rescript/belt/src/Belt_MutableMap.resi | 4 + .../belt/src/Belt_MutableMapInt.resi | 4 + .../belt/src/Belt_MutableMapString.resi | 4 + .../@rescript/belt/src/Belt_MutableQueue.resi | 4 + .../@rescript/belt/src/Belt_MutableSet.resi | 2 + .../belt/src/Belt_MutableSetInt.resi | 4 + .../belt/src/Belt_MutableSetString.resi | 4 + .../@rescript/belt/src/Belt_MutableStack.resi | 3 + packages/@rescript/belt/src/Belt_Option.resi | 2 + packages/@rescript/belt/src/Belt_Result.resi | 2 + packages/@rescript/belt/src/Belt_Set.resi | 2 + packages/@rescript/belt/src/Belt_SetDict.resi | 2 + packages/@rescript/belt/src/Belt_SetInt.resi | 2 + .../@rescript/belt/src/Belt_SetString.resi | 2 + .../belt/src/Belt_internalAVLset.resi | 2 + .../belt/src/Belt_internalAVLtree.resi | 2 + .../belt/src/Belt_internalMapInt.res | 1 + .../belt/src/Belt_internalMapString.res | 1 + .../belt/src/Belt_internalSetInt.res | 1 + .../belt/src/Belt_internalSetString.res | 1 + packages/@rescript/runtime/Pervasives.res | 6 + packages/@rescript/runtime/Stdlib.res | 2 + packages/@rescript/runtime/Stdlib_BigInt.resi | 4 +- packages/@rescript/runtime/Stdlib_Bool.resi | 1 + packages/@rescript/runtime/Stdlib_Intl.res | 3 + packages/@rescript/runtime/Stdlib_JSON.res | 5 +- packages/@rescript/runtime/Stdlib_JSON.resi | 4 +- .../@rescript/runtime/Stdlib_JsError.resi | 9 + packages/@rescript/runtime/Stdlib_List.resi | 3 + packages/@rescript/runtime/Stdlib_Null.resi | 1 + .../@rescript/runtime/Stdlib_Nullable.resi | 1 + packages/@rescript/runtime/Stdlib_Option.resi | 1 + packages/@rescript/runtime/Stdlib_Result.resi | 1 + .../runtime/Stdlib_Temporal_Duration.res | 2 +- .../runtime/Stdlib_Temporal_Instant.res | 2 +- .../runtime/Stdlib_Temporal_PlainDate.res | 2 +- .../runtime/Stdlib_Temporal_PlainDateTime.res | 2 +- .../runtime/Stdlib_Temporal_PlainMonthDay.res | 2 +- .../runtime/Stdlib_Temporal_PlainTime.res | 2 +- .../Stdlib_Temporal_PlainYearMonth.res | 2 +- .../runtime/Stdlib_Temporal_ZonedDateTime.res | 2 +- packages/@rescript/runtime/lib/es6/Stdlib.mjs | 2 +- packages/@rescript/runtime/lib/js/Stdlib.cjs | 2 +- .../checkThrowsAnnotations.mjs | 66 ++++++ .../deadcode/expected/exception.txt | 54 ++++- .../deadcode/src/exception/BeltTest.res | 33 +++ .../deadcode/src/exception/BsJson.res | 0 .../src/exception/ExnPayloadGuard.res | 15 ++ .../deadcode/src/exception/StdlibTest.res | 74 +++++++ .../deadcode/src/exception/TestYojson.res | 17 -- .../deadcode/src/exception/ThrowsDecl.res | 19 ++ .../src/exception/ThrowsDeclCalls.res | 43 ++++ .../deadcode/src/exception/ThrowsIface.res | 5 + .../deadcode/src/exception/ThrowsIface.resi | 8 + .../deadcode/src/exception/Yojson.res | 19 -- .../tests-reanalyze/deadcode/test.sh | 3 + 68 files changed, 484 insertions(+), 308 deletions(-) delete mode 100644 analysis/reanalyze/src/exn_lib.ml create mode 100644 changes/reanalyze-throws-from-declarations.feature.md create mode 100644 tests/analysis_tests/tests-reanalyze/checkThrowsAnnotations.mjs delete mode 100644 tests/analysis_tests/tests-reanalyze/deadcode/src/exception/BsJson.res create mode 100644 tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ExnPayloadGuard.res delete mode 100644 tests/analysis_tests/tests-reanalyze/deadcode/src/exception/TestYojson.res create mode 100644 tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsDecl.res create mode 100644 tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsDeclCalls.res create mode 100644 tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsIface.res create mode 100644 tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsIface.resi delete mode 100644 tests/analysis_tests/tests-reanalyze/deadcode/src/exception/Yojson.res diff --git a/analysis/reanalyze/src/exception.ml b/analysis/reanalyze/src/exception.ml index 13fdc5d4b7e..41e40a405e6 100644 --- a/analysis/reanalyze/src/exception.ml +++ b/analysis/reanalyze/src/exception.ml @@ -127,17 +127,18 @@ module Event = struct if config.Dce_config.cli.debug then Log_.item "%a@." print ev; exceptions |> Exceptions.iter (fun exn -> extend_exn_table exn loc); loop (Exceptions.union exn_set exceptions) rest - | ({kind = Call {callee; module_path}; loc} as ev) :: rest -> + | ({kind = Call {callee; module_path}; exceptions = declared; loc} as ev) + :: rest -> if config.Dce_config.cli.debug then Log_.item "%a@." print ev; + (* [declared] comes from the declaration's [@throws], the values table + from the [@throws] of the implementation's binding. Both describe + what the call can throw, so take both. *) let exceptions = match callee |> Values.find_path values_table ~module_name ~module_path with - | Some exceptions -> exceptions - | _ -> ( - match Exn_lib.find callee with - | Some exceptions -> exceptions - | None -> Exceptions.empty) + | Some exceptions -> Exceptions.union declared exceptions + | None -> declared in exceptions |> Exceptions.iter (fun exn -> extend_exn_table exn loc); loop (Exceptions.union exn_set exceptions) rest @@ -280,7 +281,7 @@ let traverse_ast ~file ~values_builder ~checks_builder () = case.c_rhs |> iter_expr self) in let is_throw s = s = "Pervasives.raise" || s = "Pervasives.throw" in - (* [/] and [mod] are listed in [Exn_lib] as throwing [Division_by_zero]. + (* [/] and [mod] are declared with [@throws(Division_by_zero)] in Pervasives. They cannot throw when the divisor is a non-zero literal, as in [x / 10]. *) let is_division s = s = "Pervasives./" || s = "Pervasives.mod" || s = "Stdlib./" @@ -322,6 +323,32 @@ let traverse_ast ~file ~values_builder ~checks_builder () = | _ -> false) <> None in + let get_exceptions_from_annotations attributes = + let throws_annotation_payload = + attributes + |> Annotation.get_attribute_payload (fun s -> + s = "throws" || s = "throw" || s = "raises" || s = "raise") + 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 + in let expr ~(module_path : Module_path.t) (self : Tast_mapper.mapper) (expr : Typedtree.expression) = let loc = expr.exp_loc in @@ -329,7 +356,7 @@ let traverse_ast ~file ~values_builder ~checks_builder () = let old_events = !current_events in if is_does_no_throw then current_events := []; (match expr.exp_desc with - | Texp_ident (callee_, _, _) -> + | Texp_ident (callee_, _, vd) -> let callee = callee_ |> Dce_path.from_path_t |> Module_path.resolve_alias module_path in @@ -343,9 +370,12 @@ let traverse_ast ~file ~values_builder ~checks_builder () = "@{%s@} can be analyzed only if called directly" (callee_name |> Name.to_string); }); + (* A [@throws] on the declaration (an external, a [let] in an + interface, or a library's) is kept in the .cmi, so it reaches calls + from other modules and packages. *) current_events := { - Event.exceptions = Exceptions.empty; + Event.exceptions = get_exceptions_from_annotations vd.val_attributes; loc; kind = Call {callee; module_path = module_path.path}; } @@ -423,32 +453,6 @@ let traverse_ast ~file ~values_builder ~checks_builder () = :: old_events); expr in - let get_exceptions_from_annotations attributes = - let throws_annotation_payload = - attributes - |> Annotation.get_attribute_payload (fun s -> - s = "throws" || s = "throw" || s = "raises" || s = "raise") - 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 - in let toplevel_eval (self : Tast_mapper.mapper) (expr : Typedtree.expression) attributes = let old_id = !current_id in diff --git a/analysis/reanalyze/src/exn.ml b/analysis/reanalyze/src/exn.ml index 47b64705cea..145d47975c5 100644 --- a/analysis/reanalyze/src/exn.ml +++ b/analysis/reanalyze/src/exn.ml @@ -1,15 +1,7 @@ type t = string let compare = String.compare -let decode_error = "DecodeError" -let assert_failure = "Assert_failure" -let division_by_zero = "Division_by_zero" -let invalid_argument = "Invalid_argument" -let js_exn = "JsExn" let match_failure = "Match_failure" -let not_found = "Not_found" let from_lid lid = lid |> Longident.flatten |> String.concat "." let from_string s = s let to_string s = s -let yojson_json_error = "Yojson.Json_error" -let yojson_type_error = "Yojson.Basic.Util.Type_error" diff --git a/analysis/reanalyze/src/exn.mli b/analysis/reanalyze/src/exn.mli index 21eb9f90cc5..683440249eb 100644 --- a/analysis/reanalyze/src/exn.mli +++ b/analysis/reanalyze/src/exn.mli @@ -1,15 +1,7 @@ type t val compare : t -> t -> int -val assert_failure : t -val decode_error : t -val division_by_zero : t val from_lid : Longident.t -> t val from_string : string -> t -val invalid_argument : t -val js_exn : t val match_failure : t -val not_found : t val to_string : t -> string -val yojson_json_error : t -val yojson_type_error : t diff --git a/analysis/reanalyze/src/exn_lib.ml b/analysis/reanalyze/src/exn_lib.ml deleted file mode 100644 index 2fe0d9a5849..00000000000 --- a/analysis/reanalyze/src/exn_lib.ml +++ /dev/null @@ -1,200 +0,0 @@ -let raises_lib_table : (Name.t, Exceptions.t) Hashtbl.t = - let table = Hashtbl.create 15 in - let open Exn in - let belt_array = - [ - ("getExn", [assert_failure]); - ("getOrThrow", [assert_failure]); - ("setExn", [assert_failure]); - ("setOrThrow", [assert_failure]); - ] - in - let belt_list = - [ - ("getExn", [not_found]); - ("getOrThrow", [not_found]); - ("headExn", [not_found]); - ("headOrThrow", [not_found]); - ("tailExn", [not_found]); - ("tailOrThrow", [not_found]); - ] - in - let belt_map = [("getExn", [not_found]); ("getOrThrow", [not_found])] in - let belt_mutable_map = belt_map in - let belt_mutable_queue = - [ - ("peekExn", [not_found]); - ("peekOrThrow", [not_found]); - ("popExn", [not_found]); - ("popOrThrow", [not_found]); - ] - in - let belt_set = [("getExn", [not_found]); ("getOrThrow", [not_found])] in - let belt_mutable_set = belt_set in - let belt_option = [("getExn", [not_found]); ("getOrThrow", [not_found])] in - let belt_result = [("getExn", [not_found]); ("getOrThrow", [not_found])] in - let bs_json = - (* bs-json *) - [ - ("bool", [decode_error]); - ("float", [decode_error]); - ("int", [decode_error]); - ("string", [decode_error]); - ("char", [decode_error]); - ("date", [decode_error]); - ("nullable", [decode_error]); - ("nullAs", [decode_error]); - ("array", [decode_error]); - ("list", [decode_error]); - ("pair", [decode_error]); - ("tuple2", [decode_error]); - ("tuple3", [decode_error]); - ("tuple4", [decode_error]); - ("dict", [decode_error]); - ("field", [decode_error]); - ("at", [decode_error; invalid_argument]); - ("oneOf", [decode_error]); - ("either", [decode_error]); - ] - in - let stdlib = - [ - ("panic", [js_exn]); - ("assertEqual", [js_exn]); - ("/", [division_by_zero]); - ("mod", [division_by_zero]); - ] - in - let stdlib_big_int = - [("fromStringOrThrow", [js_exn]); ("fromFloatOrThrow", [js_exn])] - in - let stdlib_bool = [("fromStringOrThrow", [invalid_argument])] in - let stdlib_js_error = - [ - ("EvalError.throwWithMessage", [js_exn]); - ("RangeError.throwWithMessage", [js_exn]); - ("ReferenceError.throwWithMessage", [js_exn]); - ("SyntaxError.throwWithMessage", [js_exn]); - ("TypeError.throwWithMessage", [js_exn]); - ("URIError.throwWithMessage", [js_exn]); - ("panic", [js_exn]); - ("throw", [js_exn]); - ("throwWithMessage", [js_exn]); - ] - in - let stdlib_json = [("parseOrThrow", [js_exn]); ("stringifyAny", [js_exn])] in - let stdlib_list = - [ - ("headOrThrow", [not_found]); - ("tailOrThrow", [not_found]); - ("getOrThrow", [not_found]); - ] - in - let stdlib_null = [("getOrThrow", [invalid_argument])] in - let stdlib_nullable = [("getOrThrow", [invalid_argument])] in - let stdlib_option = [("getOrThrow", [js_exn])] in - let stdlib_result = [("getOrThrow", [js_exn])] in - let yojson_basic = [("from_string", [yojson_json_error])] in - let yojson_basic_util = - [ - ("member", [yojson_type_error]); - ("to_assoc", [yojson_type_error]); - ("to_bool", [yojson_type_error]); - ("to_bool_option", [yojson_type_error]); - ("to_float", [yojson_type_error]); - ("to_float_option", [yojson_type_error]); - ("to_int", [yojson_type_error]); - ("to_list", [yojson_type_error]); - ("to_number", [yojson_type_error]); - ("to_number_option", [yojson_type_error]); - ("to_string", [yojson_type_error]); - ("to_string_option", [yojson_type_error]); - ] - in - [ - ("Belt.Array", belt_array); - ("Belt_Array", belt_array); - ("Belt.List", belt_list); - ("Belt_List", belt_list); - ("Belt.Map", belt_map); - ("Belt.Map.Int", belt_map); - ("Belt.Map.String", belt_map); - ("Belt_Map", belt_map); - ("Belt_Map.Int", belt_map); - ("Belt_Map.String", belt_map); - ("Belt_MapInt", belt_map); - ("Belt_MapString", belt_map); - ("Belt.MutableMap", belt_mutable_map); - ("Belt.MutableMap.Int", belt_mutable_map); - ("Belt.MutableMap.String", belt_mutable_map); - ("Belt_MutableMap", belt_mutable_map); - ("Belt_MutableMap.Int", belt_mutable_map); - ("Belt_MutableMap.String", belt_mutable_map); - ("Belt_MutableMapInt", belt_mutable_map); - ("Belt_MutableMapString", belt_mutable_map); - ("Belt.MutableQueue", belt_mutable_queue); - ("Belt_MutableQueue", belt_mutable_queue); - ("Belt_MutableSetInt", belt_mutable_set); - ("Belt_MutableSetString", belt_mutable_set); - ("Belt.MutableSet", belt_mutable_set); - ("Belt.MutableSet.Int", belt_mutable_set); - ("Belt.MutableSet.String", belt_mutable_set); - ("Belt.Option", belt_option); - ("Belt_Option", belt_option); - ("Belt.Result", belt_result); - ("Belt_Result", belt_result); - ("Belt.Set", belt_set); - ("Belt.Set.Int", belt_set); - ("Belt.Set.String", belt_set); - ("Belt_Set", belt_set); - ("Belt_Set.Int", belt_set); - ("Belt_Set.String", belt_set); - ("Belt_SetInt", belt_set); - ("Belt_SetString", belt_set); - ("BigInt", stdlib_big_int); - ("Bool", stdlib_bool); - ("JsError", stdlib_js_error); - ("JSON", stdlib_json); - ("Json_decode", bs_json); - ("Json.Decode", bs_json); - ("List", stdlib_list); - ("MutableSet", belt_mutable_set); - ("MutableSet.Int", belt_mutable_set); - ("MutableSet.String", belt_mutable_set); - ("Null", stdlib_null); - ("Nullable", stdlib_nullable); - ("Option", stdlib_option); - ("Pervasives", stdlib); - ("Result", stdlib_result); - ("Stdlib", stdlib); - ("Stdlib_BigInt", stdlib_big_int); - ("Stdlib.BigInt", stdlib_big_int); - ("Stdlib_Bool", stdlib_bool); - ("Stdlib.Bool", stdlib_bool); - ("Stdlib_JsError", stdlib_js_error); - ("Stdlib.JsError", stdlib_js_error); - ("Stdlib_JSON", stdlib_json); - ("Stdlib.JSON", stdlib_json); - ("Stdlib_List", stdlib_list); - ("Stdlib.List", stdlib_list); - ("Stdlib_Null", stdlib_null); - ("Stdlib.Null", stdlib_null); - ("Stdlib_Nullable", stdlib_nullable); - ("Stdlib.Nullable", stdlib_nullable); - ("Stdlib_Option", stdlib_option); - ("Stdlib.Option", stdlib_option); - ("Stdlib_Result", stdlib_result); - ("Stdlib.Result", stdlib_result); - ("Yojson.Basic", yojson_basic); - ("Yojson.Basic.Util", yojson_basic_util); - ] - |> List.iter (fun (name, group) -> - group - |> List.iter (fun (s, e) -> - Hashtbl.add table - (name ^ "." ^ s |> Name.create) - (e |> Exceptions.from_list))); - table - -let find (path : Dce_path.t) = - Hashtbl.find_opt raises_lib_table (path |> Dce_path.to_name) diff --git a/changes/reanalyze-throws-from-declarations.feature.md b/changes/reanalyze-throws-from-declarations.feature.md new file mode 100644 index 00000000000..48bdbe454e4 --- /dev/null +++ b/changes/reanalyze-throws-from-declarations.feature.md @@ -0,0 +1 @@ +- Exception analysis reads `@throws` from library and external declarations, including third-party ones, instead of a built-in list, and a `@throws` on a `let` now reaches other modules even without an interface. diff --git a/compiler/ml/typemod.ml b/compiler/ml/typemod.ml index 4fe073a2f10..7e185e0f6f7 100644 --- a/compiler/ml/typemod.ml +++ b/compiler/ml/typemod.ml @@ -1442,11 +1442,18 @@ and type_structure funct_body anchor env sstr = in (* 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. *) - let 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. *) + let signature_attributes (attrs : Parsetree.attributes) = + Builtin_attributes.deprecated_attributes attrs + @ List.filter (fun ({txt}, _) -> txt = "throws") attrs + in + let kept_attributes = List.concat_map (fun (vb : value_binding) -> - match Builtin_attributes.deprecated_attributes vb.vb_attributes with + match signature_attributes vb.vb_attributes with | [] -> [] | attrs -> List.map (fun id -> (id, attrs)) (pat_bound_idents vb.vb_pat)) @@ -1460,7 +1467,9 @@ and type_structure funct_body anchor env sstr = let vd = Env.find_value (Pident id) newenv in let vd = match - List.find_opt (fun (id', _) -> Ident.same id id') deprecated + List.find_opt + (fun (id', _) -> Ident.same id id') + kept_attributes with | None -> vd | Some (_, attrs) -> diff --git a/packages/@rescript/belt/src/Belt_Array.resi b/packages/@rescript/belt/src/Belt_Array.resi index 745f357c113..035925fce9e 100644 --- a/packages/@rescript/belt/src/Belt_Array.resi +++ b/packages/@rescript/belt/src/Belt_Array.resi @@ -42,12 +42,14 @@ let get: (t<'a>, int) => option<'a> Throw an exception if `i` is out of range. Otherwise return the value at index `i` in `arr`. */ +@throws(Assert_failure) let getExn: (t<'a>, int) => 'a /** Throw an exception if `i` is out of range. Otherwise return the value at index `i` in `arr`. */ +@throws(Assert_failure) let getOrThrow: (t<'a>, int) => 'a /** @@ -68,11 +70,13 @@ let set: (t<'a>, int, 'a) => bool /** `setExn(arr, i, x)` throw an exception if `i` is out of range. */ +@throws(Assert_failure) let setExn: (t<'a>, int, 'a) => unit /** `setOrThrow(arr, i, x)` throw an exception if `i` is out of range. */ +@throws(Assert_failure) let setOrThrow: (t<'a>, int, 'a) => unit external setUnsafe: (t<'a>, int, 'a) => unit = "%array_unsafe_set" diff --git a/packages/@rescript/belt/src/Belt_List.resi b/packages/@rescript/belt/src/Belt_List.resi index f8a9db85045..281041251af 100644 --- a/packages/@rescript/belt/src/Belt_List.resi +++ b/packages/@rescript/belt/src/Belt_List.resi @@ -60,6 +60,7 @@ switch Belt.List.headExn(list{}) { } ``` */ +@throws(Not_found) let headExn: t<'a> => 'a /** @@ -78,6 +79,7 @@ switch Belt.List.headOrThrow(list{}) { } ``` */ +@throws(Not_found) let headOrThrow: t<'a> => 'a /** @@ -110,6 +112,7 @@ switch Belt.List.tailExn(list{}) { } ``` */ +@throws(Not_found) let tailExn: t<'a> => t<'a> /** @@ -128,6 +131,7 @@ switch Belt.List.tailOrThrow(list{}) { } ``` */ +@throws(Not_found) let tailOrThrow: t<'a> => t<'a> /** @@ -177,6 +181,7 @@ switch abc->Belt.List.getExn(4) { } ``` */ +@throws(Not_found) let getExn: (t<'a>, int) => 'a /** @@ -197,6 +202,7 @@ switch abc->Belt.List.getOrThrow(4) { } ``` */ +@throws(Not_found) let getOrThrow: (t<'a>, int) => 'a /** diff --git a/packages/@rescript/belt/src/Belt_Map.resi b/packages/@rescript/belt/src/Belt_Map.resi index 2ff36890c4e..c2cbbb96b82 100644 --- a/packages/@rescript/belt/src/Belt_Map.resi +++ b/packages/@rescript/belt/src/Belt_Map.resi @@ -345,6 +345,7 @@ See `Belt.Map.get` throw when `k` not exist */ +@throws(Not_found) let getExn: (t<'k, 'v, 'id>, 'k) => 'v /** @@ -354,6 +355,7 @@ See `Belt.Map.get` throw when `k` not exist */ +@throws(Not_found) let getOrThrow: (t<'k, 'v, 'id>, 'k) => 'v /* ************************************************************************** */ diff --git a/packages/@rescript/belt/src/Belt_MapDict.resi b/packages/@rescript/belt/src/Belt_MapDict.resi index 22d08d1ff6b..2d68f38d8cc 100644 --- a/packages/@rescript/belt/src/Belt_MapDict.resi +++ b/packages/@rescript/belt/src/Belt_MapDict.resi @@ -132,8 +132,10 @@ let get: (t<'k, 'a, 'id>, 'k, ~cmp: cmp<'k, 'id>) => option<'a> let getWithDefault: (t<'k, 'a, 'id>, 'k, 'a, ~cmp: cmp<'k, 'id>) => 'a +@throws(Not_found) let getExn: (t<'k, 'a, 'id>, 'k, ~cmp: cmp<'k, 'id>) => 'a +@throws(Not_found) let getOrThrow: (t<'k, 'a, 'id>, 'k, ~cmp: cmp<'k, 'id>) => 'a let checkInvariantInternal: t<_> => unit diff --git a/packages/@rescript/belt/src/Belt_MapInt.resi b/packages/@rescript/belt/src/Belt_MapInt.resi index da86440d10c..58e447fc094 100644 --- a/packages/@rescript/belt/src/Belt_MapInt.resi +++ b/packages/@rescript/belt/src/Belt_MapInt.resi @@ -103,8 +103,10 @@ let get: (t<'v>, key) => option<'v> let getWithDefault: (t<'v>, key, 'v) => 'v +@throws(Not_found) let getExn: (t<'v>, key) => 'v +@throws(Not_found) let getOrThrow: (t<'v>, key) => 'v /** diff --git a/packages/@rescript/belt/src/Belt_MapString.resi b/packages/@rescript/belt/src/Belt_MapString.resi index c4fed2ad113..aa14e9fab2c 100644 --- a/packages/@rescript/belt/src/Belt_MapString.resi +++ b/packages/@rescript/belt/src/Belt_MapString.resi @@ -103,8 +103,10 @@ let get: (t<'v>, key) => option<'v> let getWithDefault: (t<'v>, key, 'v) => 'v +@throws(Not_found) let getExn: (t<'v>, key) => 'v +@throws(Not_found) let getOrThrow: (t<'v>, key) => 'v /** diff --git a/packages/@rescript/belt/src/Belt_MutableMap.resi b/packages/@rescript/belt/src/Belt_MutableMap.resi index 8b48c48a88e..68e3de5f8fb 100644 --- a/packages/@rescript/belt/src/Belt_MutableMap.resi +++ b/packages/@rescript/belt/src/Belt_MutableMap.resi @@ -103,7 +103,11 @@ let minimum: t<'k, 'a, _> => option<('k, 'a)> let maximum: t<'k, 'a, _> => option<('k, 'a)> let get: (t<'k, 'a, 'id>, 'k) => option<'a> let getWithDefault: (t<'k, 'a, 'id>, 'k, 'a) => 'a + +@throws(Not_found) let getExn: (t<'k, 'a, 'id>, 'k) => 'a + +@throws(Not_found) let getOrThrow: (t<'k, 'a, 'id>, 'k) => 'a /** Throw when invariant is not held. */ diff --git a/packages/@rescript/belt/src/Belt_MutableMapInt.resi b/packages/@rescript/belt/src/Belt_MutableMapInt.resi index d2a68170910..dc9cac42f9f 100644 --- a/packages/@rescript/belt/src/Belt_MutableMapInt.resi +++ b/packages/@rescript/belt/src/Belt_MutableMapInt.resi @@ -82,7 +82,11 @@ let minimum: t<'a> => option<(key, 'a)> let maximum: t<'a> => option<(key, 'a)> let get: (t<'a>, key) => option<'a> let getWithDefault: (t<'a>, key, 'a) => 'a + +@throws(Not_found) let getExn: (t<'a>, key) => 'a + +@throws(Not_found) let getOrThrow: (t<'a>, key) => 'a /** diff --git a/packages/@rescript/belt/src/Belt_MutableMapString.resi b/packages/@rescript/belt/src/Belt_MutableMapString.resi index b221010f967..eb05d1d8000 100644 --- a/packages/@rescript/belt/src/Belt_MutableMapString.resi +++ b/packages/@rescript/belt/src/Belt_MutableMapString.resi @@ -82,7 +82,11 @@ let minimum: t<'a> => option<(key, 'a)> let maximum: t<'a> => option<(key, 'a)> let get: (t<'a>, key) => option<'a> let getWithDefault: (t<'a>, key, 'a) => 'a + +@throws(Not_found) let getExn: (t<'a>, key) => 'a + +@throws(Not_found) let getOrThrow: (t<'a>, key) => 'a /** diff --git a/packages/@rescript/belt/src/Belt_MutableQueue.resi b/packages/@rescript/belt/src/Belt_MutableQueue.resi index fe5d8d38e36..c8ed5c7b235 100644 --- a/packages/@rescript/belt/src/Belt_MutableQueue.resi +++ b/packages/@rescript/belt/src/Belt_MutableQueue.resi @@ -46,11 +46,13 @@ let peek: t<'a> => option<'a> /** `peekExn(q)` throws an exception if `q` is empty. */ +@throws(Not_found) let peekExn: t<'a> => 'a /** `peekOrThrow(q)` throws an exception if `q` is empty. */ +@throws(Not_found) let peekOrThrow: t<'a> => 'a /** @@ -61,11 +63,13 @@ let pop: t<'a> => option<'a> /** `popExn(q)` throw an exception if q is empty. */ +@throws(Not_found) let popExn: t<'a> => 'a /** `popOrThrow(q)` throw an exception if q is empty. */ +@throws(Not_found) let popOrThrow: t<'a> => 'a /** diff --git a/packages/@rescript/belt/src/Belt_MutableSet.resi b/packages/@rescript/belt/src/Belt_MutableSet.resi index d4c12d19bfa..074679551b8 100644 --- a/packages/@rescript/belt/src/Belt_MutableSet.resi +++ b/packages/@rescript/belt/src/Belt_MutableSet.resi @@ -573,11 +573,13 @@ let get: (t<'value, 'id>, 'value) => option<'value> /** Same as `Belt.MutableSet.get` but throw when element does not exist. */ +@throws(Not_found) let getExn: (t<'value, 'id>, 'value) => 'value /** Same as `Belt.MutableSet.get` but throw when element does not exist. */ +@throws(Not_found) let getOrThrow: (t<'value, 'id>, 'value) => 'value /** diff --git a/packages/@rescript/belt/src/Belt_MutableSetInt.resi b/packages/@rescript/belt/src/Belt_MutableSetInt.resi index d64bf370448..981be1cfef9 100644 --- a/packages/@rescript/belt/src/Belt_MutableSetInt.resi +++ b/packages/@rescript/belt/src/Belt_MutableSetInt.resi @@ -103,7 +103,11 @@ let minimum: t => option let maximum: t => option let get: (t, value) => option + +@throws(Not_found) let getExn: (t, value) => value + +@throws(Not_found) let getOrThrow: (t, value) => value /** diff --git a/packages/@rescript/belt/src/Belt_MutableSetString.resi b/packages/@rescript/belt/src/Belt_MutableSetString.resi index 94381f493ce..cf2629db91e 100644 --- a/packages/@rescript/belt/src/Belt_MutableSetString.resi +++ b/packages/@rescript/belt/src/Belt_MutableSetString.resi @@ -103,7 +103,11 @@ let minimum: t => option let maximum: t => option let get: (t, value) => option + +@throws(Not_found) let getExn: (t, value) => value + +@throws(Not_found) let getOrThrow: (t, value) => value /** diff --git a/packages/@rescript/belt/src/Belt_MutableStack.resi b/packages/@rescript/belt/src/Belt_MutableStack.resi index 984020d5f3e..8061cf8101e 100644 --- a/packages/@rescript/belt/src/Belt_MutableStack.resi +++ b/packages/@rescript/belt/src/Belt_MutableStack.resi @@ -28,7 +28,10 @@ let copy: t<'a> => t<'a> let push: (t<'a>, 'a) => unit let pop: t<'a> => option<'a> + +@throws(Not_found) let popOrThrow: t<'a> => 'a + let top: t<'a> => option<'a> let isEmpty: t<'a> => bool let size: t<'a> => int diff --git a/packages/@rescript/belt/src/Belt_Option.resi b/packages/@rescript/belt/src/Belt_Option.resi index 1fad05201fd..9f6791121b9 100644 --- a/packages/@rescript/belt/src/Belt_Option.resi +++ b/packages/@rescript/belt/src/Belt_Option.resi @@ -70,6 +70,7 @@ switch Belt.Option.getExn(None) { } ``` */ +@throws(Not_found) let getExn: option<'a> => 'a /** @@ -87,6 +88,7 @@ switch Belt.Option.getOrThrow(None) { } ``` */ +@throws(Not_found) let getOrThrow: option<'a> => 'a /** diff --git a/packages/@rescript/belt/src/Belt_Result.resi b/packages/@rescript/belt/src/Belt_Result.resi index faf0b18593d..12af906f5f6 100644 --- a/packages/@rescript/belt/src/Belt_Result.resi +++ b/packages/@rescript/belt/src/Belt_Result.resi @@ -30,6 +30,7 @@ switch Belt.Result.getExn(Belt.Result.Error("Invalid data")) { } ``` */ +@throws(Not_found) let getExn: t<'a, 'b> => 'a /** @@ -47,6 +48,7 @@ switch Belt.Result.getOrThrow(Belt.Result.Error("Invalid data")) { } ``` */ +@throws(Not_found) let getOrThrow: t<'a, 'b> => 'a @deprecated("Use `mapWithDefault` instead") diff --git a/packages/@rescript/belt/src/Belt_Set.resi b/packages/@rescript/belt/src/Belt_Set.resi index 8d71784b8d4..9c4d9522a06 100644 --- a/packages/@rescript/belt/src/Belt_Set.resi +++ b/packages/@rescript/belt/src/Belt_Set.resi @@ -610,11 +610,13 @@ let get: (t<'value, 'id>, 'value) => option<'value> /** Same as [get](#get) but throw when element does not exist. */ +@throws(Not_found) let getExn: (t<'value, 'id>, 'value) => 'value /** Same as [get](#get) but throw when element does not exist. */ +@throws(Not_found) let getOrThrow: (t<'value, 'id>, 'value) => 'value /** diff --git a/packages/@rescript/belt/src/Belt_SetDict.resi b/packages/@rescript/belt/src/Belt_SetDict.resi index c2a5354a6c7..e3547c43abb 100644 --- a/packages/@rescript/belt/src/Belt_SetDict.resi +++ b/packages/@rescript/belt/src/Belt_SetDict.resi @@ -542,11 +542,13 @@ let get: (t<'value, 'id>, 'value, ~cmp: cmp<'value, 'id>) => option<'value> /** Same as [get](#get) but throw when element does not exist. */ +@throws(Not_found) let getExn: (t<'value, 'id>, 'value, ~cmp: cmp<'value, 'id>) => 'value /** Same as [get](#get) but throw when element does not exist. */ +@throws(Not_found) let getOrThrow: (t<'value, 'id>, 'value, ~cmp: cmp<'value, 'id>) => 'value /** diff --git a/packages/@rescript/belt/src/Belt_SetInt.resi b/packages/@rescript/belt/src/Belt_SetInt.resi index 590576256de..5e5b7b73c97 100644 --- a/packages/@rescript/belt/src/Belt_SetInt.resi +++ b/packages/@rescript/belt/src/Belt_SetInt.resi @@ -128,8 +128,10 @@ let maximum: t => option let get: (t, value) => option +@throws(Not_found) let getExn: (t, value) => value +@throws(Not_found) let getOrThrow: (t, value) => value /** diff --git a/packages/@rescript/belt/src/Belt_SetString.resi b/packages/@rescript/belt/src/Belt_SetString.resi index ec0f8cb375f..c7275a36554 100644 --- a/packages/@rescript/belt/src/Belt_SetString.resi +++ b/packages/@rescript/belt/src/Belt_SetString.resi @@ -128,8 +128,10 @@ let maximum: t => option let get: (t, value) => option +@throws(Not_found) let getExn: (t, value) => value +@throws(Not_found) let getOrThrow: (t, value) => value /** diff --git a/packages/@rescript/belt/src/Belt_internalAVLset.resi b/packages/@rescript/belt/src/Belt_internalAVLset.resi index e9ce7c88b1c..069125a25c0 100644 --- a/packages/@rescript/belt/src/Belt_internalAVLset.resi +++ b/packages/@rescript/belt/src/Belt_internalAVLset.resi @@ -74,6 +74,8 @@ let cmp: (t<'a>, t<'a>, ~cmp: cmp<'a, 'b>) => int let eq: (t<'a>, t<'a>, ~cmp: cmp<'a, 'b>) => bool let subset: (t<'a>, t<'a>, ~cmp: cmp<'a, 'b>) => bool let get: (t<'a>, 'a, ~cmp: cmp<'a, 'b>) => option<'a> + +@throws(Not_found) let getOrThrow: (t<'a>, 'a, ~cmp: cmp<'a, 'b>) => 'a let fromArray: (array<'a>, ~cmp: cmp<'a, 'b>) => t<'a> diff --git a/packages/@rescript/belt/src/Belt_internalAVLtree.resi b/packages/@rescript/belt/src/Belt_internalAVLtree.resi index 7fccf7020e9..fb18a5f9369 100644 --- a/packages/@rescript/belt/src/Belt_internalAVLtree.resi +++ b/packages/@rescript/belt/src/Belt_internalAVLtree.resi @@ -91,6 +91,8 @@ let eq: (t<'a, 'b>, t<'a, 'c>, ~kcmp: cmp<'a, _>, ~veq: ('b, 'c) => bool) => boo let get: (t<'a, 'b>, 'a, ~cmp: cmp<'a, _>) => option<'b> let getWithDefault: (t<'a, 'b>, 'a, 'b, ~cmp: cmp<'a, _>) => 'b + +@throws(Not_found) let getOrThrow: (t<'a, 'b>, 'a, ~cmp: cmp<'a, _>) => 'b let has: (t<'a, 'b>, 'a, ~cmp: cmp<'a, _>) => bool diff --git a/packages/@rescript/belt/src/Belt_internalMapInt.res b/packages/@rescript/belt/src/Belt_internalMapInt.res index 219879e90d4..d8770ad9cc6 100644 --- a/packages/@rescript/belt/src/Belt_internalMapInt.res +++ b/packages/@rescript/belt/src/Belt_internalMapInt.res @@ -44,6 +44,7 @@ let rec get = (n, x: key) => } } +@throws(Not_found) let rec getOrThrow = (n, x: key) => switch n { | None => throw(Not_found) diff --git a/packages/@rescript/belt/src/Belt_internalMapString.res b/packages/@rescript/belt/src/Belt_internalMapString.res index 880228823d9..9a515843390 100644 --- a/packages/@rescript/belt/src/Belt_internalMapString.res +++ b/packages/@rescript/belt/src/Belt_internalMapString.res @@ -44,6 +44,7 @@ let rec get = (n, x: key) => } } +@throws(Not_found) let rec getOrThrow = (n, x: key) => switch n { | None => throw(Not_found) diff --git a/packages/@rescript/belt/src/Belt_internalSetInt.res b/packages/@rescript/belt/src/Belt_internalSetInt.res index 55029c22473..f981c4b568c 100644 --- a/packages/@rescript/belt/src/Belt_internalSetInt.res +++ b/packages/@rescript/belt/src/Belt_internalSetInt.res @@ -85,6 +85,7 @@ let rec get = (n: t, x: value) => } } +@throws(Not_found) let rec getOrThrow = (n: t, x: value) => switch n { | None => throw(Not_found) diff --git a/packages/@rescript/belt/src/Belt_internalSetString.res b/packages/@rescript/belt/src/Belt_internalSetString.res index 910a1d0aaf9..216e54f96dc 100644 --- a/packages/@rescript/belt/src/Belt_internalSetString.res +++ b/packages/@rescript/belt/src/Belt_internalSetString.res @@ -85,6 +85,7 @@ let rec get = (n: t, x: value) => } } +@throws(Not_found) let rec getOrThrow = (n: t, x: value) => switch n { | None => throw(Not_found) diff --git a/packages/@rescript/runtime/Pervasives.res b/packages/@rescript/runtime/Pervasives.res index 2a51bfe1482..43d1b6f6455 100644 --- a/packages/@rescript/runtime/Pervasives.res +++ b/packages/@rescript/runtime/Pervasives.res @@ -56,10 +56,16 @@ external \"~-": 'a => 'a = "%neg" external \"+": ('a, 'a) => 'a = "%add" external \"-": ('a, 'a) => 'a = "%sub" external \"*": ('a, 'a) => 'a = "%mul" + +@throws(Division_by_zero) external \"/": ('a, 'a) => 'a = "%div" + external \"%": ('a, 'a) => 'a = "%mod" external \"<<": ('a, 'a) => 'a = "%lsl" + +@throws(Division_by_zero) external mod: ('a, 'a) => 'a = "%mod" + external \"**": ('a, 'a) => 'a = "%pow" external \"~~~": 'a => 'a = "%bitnot" diff --git a/packages/@rescript/runtime/Stdlib.res b/packages/@rescript/runtime/Stdlib.res index 303bff50169..aad73164c10 100644 --- a/packages/@rescript/runtime/Stdlib.res +++ b/packages/@rescript/runtime/Stdlib.res @@ -142,6 +142,7 @@ let caught = try panic("Invariant violated") catch { caught == "Panic! Invariant violated" ``` */ +@throws(JsExn) let panic = JsError.panic /** @@ -153,6 +154,7 @@ let panic = JsError.panic list{1, 2}->List.tailOrThrow == list{2} ``` */ +@throws(Assert_failure) let assertEqual = (a, b) => { if a != b { assert(false) diff --git a/packages/@rescript/runtime/Stdlib_BigInt.resi b/packages/@rescript/runtime/Stdlib_BigInt.resi index 231b853659b..142c8a6a2b0 100644 --- a/packages/@rescript/runtime/Stdlib_BigInt.resi +++ b/packages/@rescript/runtime/Stdlib_BigInt.resi @@ -55,7 +55,7 @@ switch BigInt.fromStringOrThrow("a") { } ``` */ -@val +@val @throws(JsExn) external fromStringOrThrow: string => bigint = "BigInt" /** @@ -113,7 +113,7 @@ switch BigInt.fromFloatOrThrow(123.5) { } ``` */ -@val +@val @throws(JsExn) external fromFloatOrThrow: float => bigint = "BigInt" /** diff --git a/packages/@rescript/runtime/Stdlib_Bool.resi b/packages/@rescript/runtime/Stdlib_Bool.resi index 1a28996cc66..77a6da7f98c 100644 --- a/packages/@rescript/runtime/Stdlib_Bool.resi +++ b/packages/@rescript/runtime/Stdlib_Bool.resi @@ -45,6 +45,7 @@ switch Bool.fromStringOrThrow("notAValidBoolean") { } ``` */ +@throws(Invalid_argument) let fromStringOrThrow: string => bool /** diff --git a/packages/@rescript/runtime/Stdlib_Intl.res b/packages/@rescript/runtime/Stdlib_Intl.res index 8717929d389..abb247210b6 100644 --- a/packages/@rescript/runtime/Stdlib_Intl.res +++ b/packages/@rescript/runtime/Stdlib_Intl.res @@ -22,6 +22,7 @@ See [`Intl.getCanonicalLocales`](https://developer.mozilla.org/en-US/docs/Web/Ja Intl.getCanonicalLocalesExn("EN-US") == ["en-US"] ``` */ +@throws(JsExn) external getCanonicalLocalesExn: string => array = "Intl.getCanonicalLocales" /** @@ -37,6 +38,7 @@ See [`Intl.getCanonicalLocales`](https://developer.mozilla.org/en-US/docs/Web/Ja Intl.getCanonicalLocalesManyExn(["EN-US", "fr"]) == ["en-US", "fr"] ``` */ +@throws(JsExn) external getCanonicalLocalesManyExn: array => array = "Intl.getCanonicalLocales" /** @@ -52,4 +54,5 @@ See [`Intl.supportedValuesOf`](https://developer.mozilla.org/en-US/docs/Web/Java Intl.supportedValuesOfExn("calendar")->Array.includes("gregory") == true ``` */ +@throws(JsExn) external supportedValuesOfExn: string => array = "Intl.supportedValuesOf" diff --git a/packages/@rescript/runtime/Stdlib_JSON.res b/packages/@rescript/runtime/Stdlib_JSON.res index a6aaa0fb7af..1f389c8f385 100644 --- a/packages/@rescript/runtime/Stdlib_JSON.res +++ b/packages/@rescript/runtime/Stdlib_JSON.res @@ -10,11 +10,12 @@ type rec t = @unboxed type replacer = Keys(array) | Replacer((string, t) => t) -@throws @val external parseOrThrow: (string, ~reviver: (string, t) => t=?) => t = "JSON.parse" +@throws(JsExn) @val +external parseOrThrow: (string, ~reviver: (string, t) => t=?) => t = "JSON.parse" @val external stringify: (t, ~replacer: replacer=?, ~space: int=?) => string = "JSON.stringify" -@throws @val +@throws(JsExn) @val external stringifyAny: ('a, ~replacer: replacer=?, ~space: int=?) => option = "JSON.stringify" diff --git a/packages/@rescript/runtime/Stdlib_JSON.resi b/packages/@rescript/runtime/Stdlib_JSON.resi index 429c2ffcc12..672b6237c91 100644 --- a/packages/@rescript/runtime/Stdlib_JSON.resi +++ b/packages/@rescript/runtime/Stdlib_JSON.resi @@ -60,7 +60,7 @@ try { - Throws a SyntaxError (JsExn.t) if the string isn't valid JSON. */ -@val +@val @throws(JsExn) external parseOrThrow: (string, ~reviver: (string, t) => t=?) => t = "JSON.parse" /** @@ -174,7 +174,7 @@ switch BigInt.fromInt(0)->JSON.stringifyAny { - Throws a TypeError if the value contains circular references. - Throws a TypeError if the value contains `BigInt`s. */ -@val +@val @throws(JsExn) external stringifyAny: ('a, ~replacer: replacer=?, ~space: int=?) => option = "JSON.stringify" diff --git a/packages/@rescript/runtime/Stdlib_JsError.resi b/packages/@rescript/runtime/Stdlib_JsError.resi index ef4a489cc61..237c3a659de 100644 --- a/packages/@rescript/runtime/Stdlib_JsError.resi +++ b/packages/@rescript/runtime/Stdlib_JsError.resi @@ -89,6 +89,7 @@ module EvalError: { See [`EvalError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError) on MDN. */ + @throws(JsExn) let throwWithMessage: string => 'a } @@ -108,6 +109,7 @@ module RangeError: { See [`RangeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError) on MDN. */ + @throws(JsExn) let throwWithMessage: string => 'a } @@ -127,6 +129,7 @@ module ReferenceError: { See [`ReferenceError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError) on MDN. */ + @throws(JsExn) let throwWithMessage: string => 'a } @@ -146,6 +149,7 @@ module SyntaxError: { See [`SyntaxError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError) on MDN. */ + @throws(JsExn) let throwWithMessage: string => 'a } @@ -165,6 +169,7 @@ module TypeError: { See [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) on MDN. */ + @throws(JsExn) let throwWithMessage: string => 'a } @@ -184,6 +189,7 @@ module URIError: { See [`URIError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError) on MDN. */ + @throws(JsExn) let throwWithMessage: string => 'a } @@ -202,6 +208,7 @@ if 5 > 10 { } ``` */ +@throws(JsExn) external throw: t => 'a = "%raise" /** @@ -209,6 +216,7 @@ Creates a new `Error` with the provided `message` and throws it. `JsError.throwWithMessage("message")` is equivalent to `JsError.make("message")->JsError.throw`. */ +@throws(JsExn) let throwWithMessage: string => 'a /** @@ -233,6 +241,7 @@ try { } ``` */ +@throws(JsExn) let panic: string => 'a /** diff --git a/packages/@rescript/runtime/Stdlib_List.resi b/packages/@rescript/runtime/Stdlib_List.resi index 2de11bfbd03..a18f5dd7106 100644 --- a/packages/@rescript/runtime/Stdlib_List.resi +++ b/packages/@rescript/runtime/Stdlib_List.resi @@ -71,6 +71,7 @@ switch List.headOrThrow(list{}) { - Throws an Error if list is empty. */ +@throws(Not_found) let headOrThrow: list<'a> => 'a /** @@ -105,6 +106,7 @@ switch List.tailOrThrow(list{}) { - Throws an Error if list is empty. */ +@throws(Not_found) let tailOrThrow: list<'a> => list<'a> /** @@ -156,6 +158,7 @@ switch abc->List.getOrThrow(4) { - Throws an Error if `index` is larger than the length of list. */ +@throws(Not_found) let getOrThrow: (list<'a>, int) => 'a /** diff --git a/packages/@rescript/runtime/Stdlib_Null.resi b/packages/@rescript/runtime/Stdlib_Null.resi index 6726c2c0c29..c0fe10bc79e 100644 --- a/packages/@rescript/runtime/Stdlib_Null.resi +++ b/packages/@rescript/runtime/Stdlib_Null.resi @@ -154,6 +154,7 @@ switch Null.getOrThrow(%raw("null")) { - Throws `Invalid_argument` if `value` is `null` */ +@throws(Invalid_argument) let getOrThrow: t<'a> => 'a /** diff --git a/packages/@rescript/runtime/Stdlib_Nullable.resi b/packages/@rescript/runtime/Stdlib_Nullable.resi index 0fca9f47eca..d18a8f89fe1 100644 --- a/packages/@rescript/runtime/Stdlib_Nullable.resi +++ b/packages/@rescript/runtime/Stdlib_Nullable.resi @@ -154,6 +154,7 @@ switch Nullable.getOrThrow(%raw("undefined")) { - Throws `Invalid_argument` if `value` is `null` or `undefined` */ +@throws(Invalid_argument) let getOrThrow: t<'a> => 'a /** diff --git a/packages/@rescript/runtime/Stdlib_Option.resi b/packages/@rescript/runtime/Stdlib_Option.resi index 39e0e755b9c..9d5989c5871 100644 --- a/packages/@rescript/runtime/Stdlib_Option.resi +++ b/packages/@rescript/runtime/Stdlib_Option.resi @@ -73,6 +73,7 @@ switch Option.getOrThrow(None, ~message="was None!") { - Throws an error if `opt` is `None` */ +@throws(JsExn) let getOrThrow: (option<'a>, ~message: string=?) => 'a /** diff --git a/packages/@rescript/runtime/Stdlib_Result.resi b/packages/@rescript/runtime/Stdlib_Result.resi index 9ca4b71d06a..6fe8a67f14b 100644 --- a/packages/@rescript/runtime/Stdlib_Result.resi +++ b/packages/@rescript/runtime/Stdlib_Result.resi @@ -46,6 +46,7 @@ type t<'res, 'err> = result<'res, 'err> = Ok('res) | Error('err) } == true ``` */ +@throws(JsExn) let getOrThrow: (result<'a, 'b>, ~message: string=?) => 'a /** diff --git a/packages/@rescript/runtime/Stdlib_Temporal_Duration.res b/packages/@rescript/runtime/Stdlib_Temporal_Duration.res index 9806001fc12..146782208cb 100644 --- a/packages/@rescript/runtime/Stdlib_Temporal_Duration.res +++ b/packages/@rescript/runtime/Stdlib_Temporal_Duration.res @@ -82,7 +82,7 @@ See [`Temporal.Duration.from`](https://developer.mozilla.org/en-US/docs/Web/Java Temporal.Duration.fromStringOrThrow("PT1H30M")->Temporal.Duration.minutes == 30. ``` */ -@val +@val @throws(JsExn) external fromStringOrThrow: string => t = "Temporal.Duration.from" /** diff --git a/packages/@rescript/runtime/Stdlib_Temporal_Instant.res b/packages/@rescript/runtime/Stdlib_Temporal_Instant.res index 79ccdd77edb..c67e23e9a38 100644 --- a/packages/@rescript/runtime/Stdlib_Temporal_Instant.res +++ b/packages/@rescript/runtime/Stdlib_Temporal_Instant.res @@ -30,7 +30,7 @@ Temporal.Instant.fromStringOrThrow("2024-01-01T00:00:00Z")->Temporal.Instant.epo 1704067200000. ``` */ -@val +@val @throws(JsExn) external fromStringOrThrow: string => t = "Temporal.Instant.from" /** diff --git a/packages/@rescript/runtime/Stdlib_Temporal_PlainDate.res b/packages/@rescript/runtime/Stdlib_Temporal_PlainDate.res index 830606c3e58..36e06c8fbcf 100644 --- a/packages/@rescript/runtime/Stdlib_Temporal_PlainDate.res +++ b/packages/@rescript/runtime/Stdlib_Temporal_PlainDate.res @@ -51,7 +51,7 @@ See [`Temporal.PlainDate.from`](https://developer.mozilla.org/en-US/docs/Web/Jav Temporal.PlainDate.fromStringOrThrow("2024-02-29")->Temporal.PlainDate.day == 29 ``` */ -@val +@val @throws(JsExn) external fromStringOrThrow: string => t = "Temporal.PlainDate.from" /** diff --git a/packages/@rescript/runtime/Stdlib_Temporal_PlainDateTime.res b/packages/@rescript/runtime/Stdlib_Temporal_PlainDateTime.res index 8dd2e2ec0ae..46c48dfd2a4 100644 --- a/packages/@rescript/runtime/Stdlib_Temporal_PlainDateTime.res +++ b/packages/@rescript/runtime/Stdlib_Temporal_PlainDateTime.res @@ -62,7 +62,7 @@ See [`Temporal.PlainDateTime.from`](https://developer.mozilla.org/en-US/docs/Web Temporal.PlainDateTime.fromStringOrThrow("2024-02-29T09:30")->Temporal.PlainDateTime.hour == 9 ``` */ -@val +@val @throws(JsExn) external fromStringOrThrow: string => t = "Temporal.PlainDateTime.from" /** diff --git a/packages/@rescript/runtime/Stdlib_Temporal_PlainMonthDay.res b/packages/@rescript/runtime/Stdlib_Temporal_PlainMonthDay.res index 32b6c640d65..1ef4a7295f3 100644 --- a/packages/@rescript/runtime/Stdlib_Temporal_PlainMonthDay.res +++ b/packages/@rescript/runtime/Stdlib_Temporal_PlainMonthDay.res @@ -57,7 +57,7 @@ See [`Temporal.PlainMonthDay.from`](https://developer.mozilla.org/en-US/docs/Web Temporal.PlainMonthDay.fromStringOrThrow("12-25")->Temporal.PlainMonthDay.day == 25 ``` */ -@val +@val @throws(JsExn) external fromStringOrThrow: string => t = "Temporal.PlainMonthDay.from" /** diff --git a/packages/@rescript/runtime/Stdlib_Temporal_PlainTime.res b/packages/@rescript/runtime/Stdlib_Temporal_PlainTime.res index 8d40304278f..34c5e802956 100644 --- a/packages/@rescript/runtime/Stdlib_Temporal_PlainTime.res +++ b/packages/@rescript/runtime/Stdlib_Temporal_PlainTime.res @@ -47,7 +47,7 @@ See [`Temporal.PlainTime.from`](https://developer.mozilla.org/en-US/docs/Web/Jav Temporal.PlainTime.fromStringOrThrow("09:30")->Temporal.PlainTime.minute == 30 ``` */ -@val +@val @throws(JsExn) external fromStringOrThrow: string => t = "Temporal.PlainTime.from" /** diff --git a/packages/@rescript/runtime/Stdlib_Temporal_PlainYearMonth.res b/packages/@rescript/runtime/Stdlib_Temporal_PlainYearMonth.res index 0493d78e6db..fba8511fd3c 100644 --- a/packages/@rescript/runtime/Stdlib_Temporal_PlainYearMonth.res +++ b/packages/@rescript/runtime/Stdlib_Temporal_PlainYearMonth.res @@ -77,7 +77,7 @@ See [`Temporal.PlainYearMonth.from`](https://developer.mozilla.org/en-US/docs/We Temporal.PlainYearMonth.fromStringOrThrow("2024-02")->Temporal.PlainYearMonth.daysInMonth == 29 ``` */ -@val +@val @throws(JsExn) external fromStringOrThrow: string => t = "Temporal.PlainYearMonth.from" /** diff --git a/packages/@rescript/runtime/Stdlib_Temporal_ZonedDateTime.res b/packages/@rescript/runtime/Stdlib_Temporal_ZonedDateTime.res index 73256f9e00a..85a0075333b 100644 --- a/packages/@rescript/runtime/Stdlib_Temporal_ZonedDateTime.res +++ b/packages/@rescript/runtime/Stdlib_Temporal_ZonedDateTime.res @@ -88,7 +88,7 @@ Temporal.ZonedDateTime.fromStringOrThrow( )->Temporal.ZonedDateTime.timeZoneId == "Asia/Seoul" ``` */ -@val +@val @throws(JsExn) external fromStringOrThrow: (string, ~options: fromOptions=?) => t = "Temporal.ZonedDateTime.from" /** diff --git a/packages/@rescript/runtime/lib/es6/Stdlib.mjs b/packages/@rescript/runtime/lib/es6/Stdlib.mjs index 904294e9755..17a914df037 100644 --- a/packages/@rescript/runtime/lib/es6/Stdlib.mjs +++ b/packages/@rescript/runtime/lib/es6/Stdlib.mjs @@ -12,7 +12,7 @@ function assertEqual(a, b) { RE_EXN_ID: "Assert_failure", _1: [ "Stdlib.res", - 158, + 160, 4 ], Error: new Error() diff --git a/packages/@rescript/runtime/lib/js/Stdlib.cjs b/packages/@rescript/runtime/lib/js/Stdlib.cjs index ffb9f6ffb59..a76b3ec2c0f 100644 --- a/packages/@rescript/runtime/lib/js/Stdlib.cjs +++ b/packages/@rescript/runtime/lib/js/Stdlib.cjs @@ -12,7 +12,7 @@ function assertEqual(a, b) { RE_EXN_ID: "Assert_failure", _1: [ "Stdlib.res", - 158, + 160, 4 ], Error: new Error() diff --git a/tests/analysis_tests/tests-reanalyze/checkThrowsAnnotations.mjs b/tests/analysis_tests/tests-reanalyze/checkThrowsAnnotations.mjs new file mode 100644 index 00000000000..93d46ac902e --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/checkThrowsAnnotations.mjs @@ -0,0 +1,66 @@ +// Checks that every stdlib and Belt value named `*OrThrow` or `*Exn` declares +// what it throws with `@throws(...)`. The exception analysis reads that +// attribute from the declaration at each call site, so a missing one makes +// calls to the function look as if they throw nothing. +// +// A module's declarations are read from its .resi, or from its .res when it +// has no interface; the compiler copies a binding's `@throws` into the +// signature it infers. + +import fs from "node:fs"; +import path from "node:path"; + +const root = path.resolve(import.meta.dirname, "../../.."); +const dirs = ["packages/@rescript/runtime", "packages/@rescript/belt/src"]; + +// Names that end in `Exn` without throwing. +const allowed = new Set(["Stdlib_JsError.toJsExn"]); + +const declaration = + /^\s*(?:let|external)\s+(?:rec\s+)?([A-Za-z_][A-Za-z0-9_']*)\s*[:=]/; +const throwsWithPayload = /@throws\(/; + +const missing = []; + +for (const dir of dirs) { + const files = fs.readdirSync(path.join(root, dir)); + for (const file of files) { + const match = /^(.*)\.(resi?)$/.exec(file); + if (match === null) continue; + const [, module, ext] = match; + if (ext === "res" && files.includes(`${module}.resi`)) continue; + const lines = fs + .readFileSync(path.join(root, dir, file), "utf8") + .split("\n"); + let commentDepth = 0; + lines.forEach((line, i) => { + const inComment = commentDepth > 0; + commentDepth += + (line.match(/\/\*/g) ?? []).length - (line.match(/\*\//g) ?? []).length; + if (inComment) return; + const decl = declaration.exec(line); + if (decl === null) return; + const name = decl[1]; + if (!/(OrThrow|Exn)$/.test(name)) return; + if (allowed.has(`${module}.${name}`)) return; + // The attributes of a declaration are on its line and the lines above + // it, up to a blank line or the end of its doc comment. + let annotated = throwsWithPayload.test(line); + for (let j = i - 1; !annotated && j >= 0; j--) { + const above = lines[j].trim(); + if (above === "" || above.endsWith("*/")) break; + annotated = throwsWithPayload.test(above); + } + if (!annotated) missing.push(`${dir}/${file}:${i + 1}: ${name}`); + }); + } +} + +if (missing.length > 0) { + console.error( + "These declarations need a @throws(...) naming what they throw:", + ); + for (const m of missing) console.error(` ${m}`); + process.exit(1); +} +console.log("✅ Every *OrThrow and *Exn declaration has a @throws."); diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt b/tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt index 1c9b93d1877..5526549b570 100644 --- a/tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt +++ b/tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt @@ -123,5 +123,57 @@ Exception Analysis ExternalTest.res:7:5-24 bigIntFromStringExn2 might throw JsExn (ExternalTest.res:7:35) and is not annotated with @throws(JsExn) + + Exception Analysis + StdlibTest.res:67:5-34 + plainDateFromStringUnannotated might throw JsExn (StdlibTest.res:67:42) and is not annotated with @throws(JsExn) + + Exception Analysis + ThrowsDeclCalls.res:1:5-16 + callExternal might throw JsExn (ThrowsDeclCalls.res:1:24) and is not annotated with @throws(JsExn) + + Exception Analysis + ThrowsDeclCalls.res:3:5-20 + callExternalPipe might throw JsExn (ThrowsDeclCalls.res:3:31) and is not annotated with @throws(JsExn) + + Exception Analysis + ThrowsDeclCalls.res:5:5-14 + callNested might throw Not_found (ThrowsDeclCalls.res:5:22) and is not annotated with @throws(Not_found) + + Exception Analysis + ThrowsDeclCalls.res:7:5-16 + callIfaceLet might throw Not_found (ThrowsDeclCalls.res:7:24) and is not annotated with @throws(Not_found) + + Exception Analysis + ThrowsDeclCalls.res:9:5-21 + callIfaceExternal might throw JsExn (ThrowsDeclCalls.res:9:29) and is not annotated with @throws(JsExn) + + Exception Analysis + ThrowsDeclCalls.res:12:5-13 + callAlias might throw JsExn (ThrowsDeclCalls.res:12:21) and is not annotated with @throws(JsExn) + + Exception Analysis + ThrowsDeclCalls.res:14:5-12 + callOpen might throw JsExn (ThrowsDeclCalls.res:16:2) and is not annotated with @throws(JsExn) + + Exception Analysis + ThrowsDeclCalls.res:23:5-15 + callInclude might throw JsExn (ThrowsDeclCalls.res:23:23) and is not annotated with @throws(JsExn) + + Exception Analysis + ThrowsDeclCalls.res:26:5-15 + callFunctor might throw Not_found (ThrowsDeclCalls.res:26:23) and is not annotated with @throws(Not_found) + + Exception Analysis + ThrowsDeclCalls.res:28:5-18 + callFirstClass might throw Not_found (ThrowsDeclCalls.res:30:2) and is not annotated with @throws(Not_found) + + Exception Analysis + ThrowsDeclCalls.res:36:5-14 + callViaLet might throw Not_found (ThrowsDeclCalls.res:36:22) and is not annotated with @throws(Not_found) + + Exception Analysis + ThrowsDeclCalls.res:37:5-22 + callViaLetIncluded might throw Not_found (ThrowsDeclCalls.res:37:30) and is not annotated with @throws(Not_found) - Analysis reported 31 issues (Exception Analysis:31) + Analysis reported 44 issues (Exception Analysis:44) diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/BeltTest.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/BeltTest.res index 0a8910c486e..81b41844484 100644 --- a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/BeltTest.res +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/BeltTest.res @@ -29,3 +29,36 @@ let mapGetExn7 = (s, k) => s->Belt.Map.getExn(k) @throws(Not_found) let mapGetExn8 = (s, k) => s->Belt_Map.getExn(k) + +@throws(Not_found) +let stackPopOrThrow = s => Belt.MutableStack.popOrThrow(s) + +@throws(Not_found) +let directStackPopOrThrow = s => Belt_MutableStack.popOrThrow(s) + +@throws(Not_found) +let mapDictGetOrThrow = (m, k, ~cmp) => Belt.Map.Dict.getOrThrow(m, k, ~cmp) + +@throws(Not_found) +let mapDictGetExn = (m, k, ~cmp) => Belt.Map.Dict.getExn(m, k, ~cmp) + +@throws(Not_found) +let directMapDictGetOrThrow = (m, k, ~cmp) => Belt_MapDict.getOrThrow(m, k, ~cmp) + +@throws(Not_found) +let setDictGetOrThrow = (s, v, ~cmp) => Belt.Set.Dict.getOrThrow(s, v, ~cmp) + +@throws(Not_found) +let directSetDictGetOrThrow = (s, v, ~cmp) => Belt_SetDict.getOrThrow(s, v, ~cmp) + +@throws(Not_found) +let directMutableSetGetOrThrow = (s, v) => Belt_MutableSet.getOrThrow(s, v) + +@throws(Not_found) +let directMutableSetIntGetOrThrow = (s, v) => Belt_MutableSet.Int.getOrThrow(s, v) + +@throws(Assert_failure) +let arrayGetExn = (a, i) => Belt.Array.getExn(a, i) + +@throws(Not_found) +let queuePopOrThrow = q => Belt.MutableQueue.popOrThrow(q) diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/BsJson.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/BsJson.res deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ExnPayloadGuard.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ExnPayloadGuard.res new file mode 100644 index 00000000000..a618aac833c --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ExnPayloadGuard.res @@ -0,0 +1,15 @@ +exception Type_error(string, int) + +module Util = { + @throws(Type_error) + let member = (s, j) => s == "" ? throw(Type_error(s, j)) : j +} + +let bar = (str, json) => + switch { + open Util + member(str, json) + } { + | j => j + | exception Type_error("a", d) if d == json => json + } diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/StdlibTest.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/StdlibTest.res index 63868d7a7e8..c641633f24f 100644 --- a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/StdlibTest.res +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/StdlibTest.res @@ -12,3 +12,77 @@ let bigIntFromStringExn = s => s->BigInt.fromStringOrThrow @throws(JsExn) let jsonParseExn = s => s->JSON.parseOrThrow + +@throws(JsExn) +let durationFromStringOrThrow = s => Temporal.Duration.fromStringOrThrow(s) + +@throws(JsExn) +let instantFromStringOrThrow = s => Temporal.Instant.fromStringOrThrow(s) + +@throws(JsExn) +let plainDateFromStringOrThrow = s => Temporal.PlainDate.fromStringOrThrow(s) + +@throws(JsExn) +let plainDateTimeFromStringOrThrow = s => Temporal.PlainDateTime.fromStringOrThrow(s) + +@throws(JsExn) +let plainMonthDayFromStringOrThrow = s => Temporal.PlainMonthDay.fromStringOrThrow(s) + +@throws(JsExn) +let plainTimeFromStringOrThrow = s => Temporal.PlainTime.fromStringOrThrow(s) + +@throws(JsExn) +let plainYearMonthFromStringOrThrow = s => Temporal.PlainYearMonth.fromStringOrThrow(s) + +@throws(JsExn) +let zonedDateTimeFromStringOrThrow = s => Temporal.ZonedDateTime.fromStringOrThrow(s) + +@throws(JsExn) +let stdlibPlainDateFromStringOrThrow = s => Stdlib.Temporal.PlainDate.fromStringOrThrow(s) + +@throws(JsExn) +let openedPlainDateFromStringOrThrow = s => { + open Temporal + PlainDate.fromStringOrThrow(s) +} + +@throws(JsExn) +let directPlainDateFromStringOrThrow = s => Stdlib_Temporal_PlainDate.fromStringOrThrow(s) + +@throws(JsExn) +let aliasPlainDateFromStringOrThrow = s => Stdlib_Temporal.PlainDate.fromStringOrThrow(s) + +@throws(JsExn) +let canonicalLocales = s => Intl.getCanonicalLocalesExn(s) + +@throws(JsExn) +let canonicalLocalesMany = s => Intl.getCanonicalLocalesManyExn(s) + +@throws(JsExn) +let supportedValuesOf = s => Intl.supportedValuesOfExn(s) + +@throws(JsExn) +let stdlibCanonicalLocales = s => Stdlib.Intl.getCanonicalLocalesExn(s) + +let plainDateFromStringUnannotated = s => Temporal.PlainDate.fromStringOrThrow(s) + +@throws(JsExn) +let callPanic = () => panic("x") + +@throws(Assert_failure) +let callAssertEqual = (a, b) => assertEqual(a, b) + +@throws(JsExn) +let rangeError = () => JsError.RangeError.throwWithMessage("x") + +@throws(Not_found) +let listHead = l => List.headOrThrow(l) + +@throws(Invalid_argument) +let boolFromString = s => Bool.fromStringOrThrow(s) + +@throws(Invalid_argument) +let nullableGetOrThrow = n => Nullable.getOrThrow(n) + +@throws(JsExn) +let stringifyAny = x => JSON.stringifyAny(x) diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/TestYojson.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/TestYojson.res deleted file mode 100644 index 6dda239e927..00000000000 --- a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/TestYojson.res +++ /dev/null @@ -1,17 +0,0 @@ -@throws(Yojson.Json_error) -let foo = x => Yojson.Basic.from_string(x) - -let bar = (str, json) => - switch { - open Yojson.Basic.Util - member(str, json) - } { - | j => j - | exception Yojson.Basic.Util.Type_error("a", d) when d == json => json - } - -@throws(Yojson.Basic.Util.Type_error) -let toString = x => Yojson.Basic.Util.to_string(x) - -@throws(Yojson.Basic.Util.Type_error) -let toInt = x => Yojson.Basic.Util.to_int(x) diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsDecl.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsDecl.res new file mode 100644 index 00000000000..d1414ba9971 --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsDecl.res @@ -0,0 +1,19 @@ +@throws(JsExn) +external parse: string => int = "parseThrowing" + +module Inner = { + @throws(Not_found) + external find: int => int = "findThrowing" +} + +module type S = { + @throws(Not_found) + let get: int => int +} + +module Make = (X: {}): S => { + let get = x => x +} + +@throws(Not_found) +let viaLet = x => x > 0 ? x : throw(Not_found) diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsDeclCalls.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsDeclCalls.res new file mode 100644 index 00000000000..0378c4b8a78 --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsDeclCalls.res @@ -0,0 +1,43 @@ +let callExternal = s => ThrowsDecl.parse(s) + +let callExternalPipe = s => s->ThrowsDecl.parse + +let callNested = x => ThrowsDecl.Inner.find(x) + +let callIfaceLet = x => ThrowsIface.lookup(x) + +let callIfaceExternal = s => ThrowsIface.parseIface(s) + +module Alias = ThrowsDecl +let callAlias = s => Alias.parse(s) + +let callOpen = s => { + open ThrowsDecl + parse(s) +} + +module Included = { + include ThrowsDecl +} + +let callInclude = s => Included.parse(s) + +module Applied = ThrowsDecl.Make() +let callFunctor = x => Applied.get(x) + +let callFirstClass = (m: module(ThrowsDecl.S), x) => { + module M = unpack(m) + M.get(x) +} + +@throws(JsExn) +let callExternalAnnotated = s => ThrowsDecl.parse(s) + +let callViaLet = x => ThrowsDecl.viaLet(x) +let callViaLetIncluded = x => Included.viaLet(x) + +module IfaceIncluded = { + include ThrowsIface +} + +let callImplOnlyIncluded = x => IfaceIncluded.implOnly(x) diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsIface.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsIface.res new file mode 100644 index 00000000000..648adc80bfd --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsIface.res @@ -0,0 +1,5 @@ +let lookup = x => x +external parseIface: string => int = "parseThrowing" + +@throws(Not_found) +let implOnly = x => x > 0 ? x : throw(Not_found) diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsIface.resi b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsIface.resi new file mode 100644 index 00000000000..1cee1377c61 --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsIface.resi @@ -0,0 +1,8 @@ +@throws(Not_found) +let lookup: int => int + +@throws(JsExn) +external parseIface: string => int = "parseThrowing" + +// The interface has no @throws, and it is what the .cmi holds. +let implOnly: int => int diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/Yojson.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/Yojson.res deleted file mode 100644 index 85dfbcc18e5..00000000000 --- a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/Yojson.res +++ /dev/null @@ -1,19 +0,0 @@ -exception Json_error(string) - -module Basic = { - type t - - @throws(Json_error) - let from_string: string => t = _ => throw(Json_error("Basic.from_string")) - - module Util = { - exception Type_error(string, t) - - @throws(Type_error) - let member: (string, t) => t = (_s, j) => throw(Type_error("Basic.Util.member", j)) - - let to_int: t => int = _ => 34 - - let to_string: t => string = _ => "" - } -} diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/test.sh b/tests/analysis_tests/tests-reanalyze/deadcode/test.sh index a408b9da0a2..32f653fb4d6 100755 --- a/tests/analysis_tests/tests-reanalyze/deadcode/test.sh +++ b/tests/analysis_tests/tests-reanalyze/deadcode/test.sh @@ -1,5 +1,8 @@ DEBUG_FLAG="-debug" +# The exception analysis reads @throws from library declarations. +node ../checkThrowsAnnotations.mjs || exit 1 + if [ "$RUNNER_OS" == "Windows" ]; then exclude_dirs="src\exception" suppress="src\ToSuppress.res" From 33d29b0c160eb537c6d9dcaaa72ff1d2620fbe72 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 10 Nov 2026 17:30:38 +0000 Subject: [PATCH 2/4] Drop the empty BsJson module from the deadcode debug snapshot Why: Since #9245 every .cmt lands in the flat lib/rescript, so the empty src/exception/BsJson.res logged "Implementation 0" in the deadcode debug output. This PR deletes that file, so the line goes away. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gHi59ptFC3WWfiDQH4 Signed-off-by: Christoph Knittel --- .../tests-reanalyze/deadcode/expected/deadcode.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/expected/deadcode.txt b/tests/analysis_tests/tests-reanalyze/deadcode/expected/deadcode.txt index d523b404733..9822ce80203 100644 --- a/tests/analysis_tests/tests-reanalyze/deadcode/expected/deadcode.txt +++ b/tests/analysis_tests/tests-reanalyze/deadcode/expected/deadcode.txt @@ -8,7 +8,6 @@ addDeclaration_ VariantCase R2 AutoAnnotate.res:14:2 path:+AutoAnnotate.annotatedVariant addDeclaration_ VariantCase R4 AutoAnnotate.res:15:2 path:+AutoAnnotate.annotatedVariant Scanning BootloaderResource.cmt Source:BootloaderResource.res - Implementation 0 Scanning BucklescriptAnnotations.cmt Source:BucklescriptAnnotations.res addDeclaration_ Value +bar BucklescriptAnnotations.res:22:4 path:+BucklescriptAnnotations addDeclaration_ Value +f BucklescriptAnnotations.res:23:6 path:+BucklescriptAnnotations From 81ce8eb26cf09e395f3bd76f741a0a04f5776c67 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 17 Nov 2026 20:17:07 +0000 Subject: [PATCH 3/4] Resolve @throws names in the declaration's scope in exception analysis Why: Review finding on #9198: a library's `@throws(E)` reached the caller as the bare name `E`, while a catch was compared by its spelling, `Lib.E`. So a correct catch still reported the exception, and a caller's own `E` could hide the library's. Now a catch or throw names an exception by its constructor's path: `Lib.E` whether it is written `Lib.E`, `E` after `open Lib` or `L.E` for `module L = Lib`. A callee's `@throws` names are resolved in the callee's scope (`Lib.Inner.E`, then `Lib.E`), picking the first one the project catches or throws. For a callee in another file the bare name is not a candidate. Predefined exceptions such as `Not_found` and `JsExn` keep their bare names. The same applies to the values table, so an annotated `let` in another file without an interface is fixed too. That case is older than this PR. Reanalyze modified (cross-module exception names): Example: // ThrowsLibExn.res 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" } // ThrowsLibExnCalls.res 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 } exception E let catchUnrelatedLocal = s => try ThrowsLibExn.parse(s) catch { | E => 0 } Before (reanalyze): Exception Analysis ThrowsLibExnCalls.res:1:5-17 catchExternal might throw E (ThrowsLibExnCalls.res:2:6) and is not annotated with @throws(E) Exception Analysis ThrowsLibExnCalls.res:6:5-15 catchViaLet might throw E (ThrowsLibExnCalls.res:7:6) and is not annotated with @throws(E) Exception Analysis ThrowsLibExnCalls.res:11:5-15 catchNested might throw F (ThrowsLibExnCalls.res:12:6) and is not annotated with @throws(F) After (reanalyze): Exception Analysis ThrowsLibExnCalls.res:18:5-23 catchUnrelatedLocal might throw ThrowsLibExn.E (ThrowsLibExnCalls.res:19:6) and is not annotated with @throws(ThrowsLibExn.E) Review: Where do the candidate names come from, without the declaration's environment? The .cmt keeps no environments, so a name is resolved against the exceptions the project's files catch or throw. A catch can only match one of those, so the choice matters for matching. When none is known, the innermost candidate is used, which only affects the message. Review: What does a caller now write in its own annotation? The qualified name, `@throws(ThrowsLibExn.E)`, which the message suggests. A bare `E` after `open ThrowsLibExn` no longer matches. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gHA54VKxsXvCQyC2vw Signed-off-by: Christoph Knittel --- analysis/reanalyze/src/exception.ml | 180 ++++++++++++++---- analysis/reanalyze/src/exceptions.ml | 2 + .../deadcode/expected/exception.txt | 10 +- .../deadcode/src/exception/ThrowsLibExn.res | 19 ++ .../src/exception/ThrowsLibExnCalls.res | 71 +++++++ 5 files changed, 246 insertions(+), 36 deletions(-) create mode 100644 tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExn.res create mode 100644 tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExnCalls.res diff --git a/analysis/reanalyze/src/exception.ml b/analysis/reanalyze/src/exception.ml index 41e40a405e6..c9a00355c49 100644 --- a/analysis/reanalyze/src/exception.ml +++ b/analysis/reanalyze/src/exception.ml @@ -66,10 +66,44 @@ module Values = struct | Some exceptions -> Some exceptions end +(* Where a callee's [@throws] names are resolved. A catch or a throw names an + exception by its constructor's path, as [Lib.E] or, defined in the same + file, as [E] or [M.E]. A [@throws(E)] on a declaration in [Lib.Inner] means + [Lib.Inner.E] or [Lib.E], whichever exists. *) +type scope = { + prefixes: string list; + (** Candidate prefixes for a name, innermost first. [""] stands for the + bare name, which is a candidate only for a callee in the same file: + a bare [E] there is the caller's own [E]. *) + fallback: string; (** The prefix to use when no candidate is known. *) +} + +let predef_exceptions = + Predef.builtin_idents + |> List.filter_map (fun (name, id) -> + if Ident.is_predef_exn id then Some name else None) + +(* [known] holds the exceptions caught or thrown somewhere in the project, so + it holds every exception that a catch could match. *) +let resolve_declared ~known ~(scope : scope) exn = + let name = Exn.to_string exn in + if List.mem name predef_exceptions then exn + else + let qualify prefix = + Exn.from_string (if prefix = "" then name else prefix ^ "." ^ name) + in + match + scope.prefixes + |> List.find_opt (fun prefix -> Exceptions.mem (qualify prefix) known) + with + | Some prefix -> qualify prefix + | None -> qualify scope.fallback + module Event = struct type kind = | Catches of t list (* with | E => ... *) - | Call of {callee: Dce_path.t; module_path: Dce_path.t} (* foo() *) + | Call of {callee: Dce_path.t; module_path: Dce_path.t; scope: scope} + (* foo() *) | DoesNotThrow of t list (* DoesNotThrow(events) where events come from an expression *) | Throws (** throw E *) @@ -105,7 +139,8 @@ module Event = struct nested_events |> List.iter (fun e -> Format.fprintf ppf "%a " print e)) () - let combine ~(values_table : values_table) ~config ~module_name events = + let combine ~(values_table : values_table) ~known ~config ~module_name events + = if config.Dce_config.cli.debug then ( Log_.item "@."; Log_.item "Events combine: #events %d@." (events |> List.length)); @@ -127,18 +162,21 @@ module Event = struct if config.Dce_config.cli.debug then Log_.item "%a@." print ev; exceptions |> Exceptions.iter (fun exn -> extend_exn_table exn loc); loop (Exceptions.union exn_set exceptions) rest - | ({kind = Call {callee; module_path}; exceptions = declared; loc} as ev) + | ({kind = Call {callee; module_path; scope}; exceptions = declared; loc} + as ev) :: rest -> if config.Dce_config.cli.debug then Log_.item "%a@." print ev; (* [declared] comes from the declaration's [@throws], the values table from the [@throws] of the implementation's binding. Both describe - what the call can throw, so take both. *) + what the call can throw, so take both. Both name exceptions as + written at the declaration, so resolve them in its scope. *) let exceptions = - match - callee |> Values.find_path values_table ~module_name ~module_path - with - | Some exceptions -> Exceptions.union declared exceptions - | None -> declared + (match + callee |> Values.find_path values_table ~module_name ~module_path + with + | Some exceptions -> Exceptions.union declared exceptions + | None -> declared) + |> Exceptions.map (resolve_declared ~known ~scope) in exceptions |> Exceptions.iter (fun exn -> extend_exn_table exn loc); loop (Exceptions.union exn_set exceptions) rest @@ -201,10 +239,10 @@ let checks_builder_to_list (builder : checks_builder) : check list = !builder |> List.rev module Checks = struct - let do_check ~(values_table : values_table) ~config + let do_check ~(values_table : values_table) ~known ~config {events; exceptions; loc; loc_full; module_name; exn_name} = let throw_set, exn_table = - events |> Event.combine ~values_table ~config ~module_name + events |> Event.combine ~values_table ~known ~config ~module_name in let missing_annotations = Exceptions.diff throw_set exceptions in let redundant_annotations = Exceptions.diff exceptions throw_set in @@ -234,14 +272,17 @@ module Checks = struct redundant_annotations); }) - let do_checks ~values_table ~config (checks : check list) = - checks |> List.iter (do_check ~values_table ~config) + let do_checks ~values_table ~known ~config (checks : check list) = + checks |> List.iter (do_check ~values_table ~known ~config) end -let traverse_ast ~file ~values_builder ~checks_builder () = +let traverse_ast ~file ~values_builder ~checks_builder ~seen_exceptions () = let super = Tast_mapper.default in let current_id = ref "" in let current_events = ref [] in + (* Compilation units that the file's module aliases point into. A call + through such an alias is a call into another file. *) + let alias_units = Hashtbl.create 1 in (* For local lookups during AST processing, we look up in the current file's builder *) let find_local_exceptions ~module_path path = let name = path @ module_path |> Dce_path.to_name in @@ -256,16 +297,62 @@ let traverse_ast ~file ~values_builder ~checks_builder () = | _ :: rest_module_path -> path |> find_local_path ~module_path:rest_module_path) in - let exceptions_of_patterns patterns = + (* Name an exception by its constructor's path rather than by how the source + spells it, so [Lib.E], [E] after [open Lib] and [L.E] for [module L = Lib] + are the same exception, and a file's own [E] is not [Lib.E]. *) + let exn_of_constructor ~(module_path : Module_path.t) lid + (cstr : Types.constructor_description) = + let exn = + match cstr.cstr_kind with + | Extension_constructor (Pident id) when Ident.is_predef_exn id -> + Exn.from_string (Ident.name id) + | Extension_constructor path -> ( + match path |> Dce_path.from_path_t with + | [] -> Exn.from_lid lid + | dce_path -> + dce_path + |> Module_path.resolve_alias module_path + |> Dce_path.to_string |> Exn.from_string) + | Ordinary_constructor _ -> Exn.from_lid lid + in + seen_exceptions := Exceptions.add exn !seen_exceptions; + exn + in + let exceptions_of_patterns ~module_path patterns = patterns |> 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 ~module_path txt cstr) acc | _ -> acc) Exceptions.empty in + (* The scope of a callee's declaration, from the callee's path. A call into + another file never resolves a name to a bare one. *) + let scope_of_callee ~(callee_path : Path.t) (callee : Dce_path.t) = + let modules = + match callee with + | _ :: modules -> modules + | [] -> [] + in + let rec prefixes modules = + match modules with + | [] -> [] + | _ :: outer -> Dce_path.to_string modules :: prefixes outer + in + let other_file = + Ident.persistent (Path.head callee_path) + || + match List.rev modules with + | root :: _ -> Hashtbl.mem alias_units (Name.to_string root) + | [] -> false + in + match prefixes modules with + | innermost :: _ as prefixes when other_file -> + {prefixes; fallback = innermost} + | prefixes -> {prefixes = prefixes @ [""]; fallback = ""} + in let iter_expr self e = self.Tast_mapper.expr self e |> ignore in let iter_expr_opt self eo = match eo with @@ -304,10 +391,10 @@ let traverse_ast ~file ~values_builder ~checks_builder () = is_non_zero_constant c | _ -> false in - let throw_args args = + let throw_args ~module_path 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 ~module_path 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 @@ -377,7 +464,13 @@ let traverse_ast ~file ~values_builder ~checks_builder () = { Event.exceptions = get_exceptions_from_annotations vd.val_attributes; loc; - kind = Call {callee; module_path = module_path.path}; + kind = + Call + { + callee; + module_path = module_path.path; + scope = scope_of_callee ~callee_path:callee_ callee; + }; } :: !current_events | Texp_apply @@ -388,14 +481,14 @@ let traverse_ast ~file ~values_builder ~checks_builder () = when (* raise @@ Exn(...) *) atat |> Path.name = "Pervasives.@@" && callee |> Path.name |> is_throw -> - let exceptions = [arg] |> throw_args in + let exceptions = [arg] |> throw_args ~module_path in current_events := {Event.exceptions; loc; kind = Throws} :: !current_events; arg |> snd |> iter_expr_opt self | Texp_apply {funct = {exp_desc = Texp_ident (callee, _, _)} as e; args} -> let callee_name = Path.name callee in if callee_name |> is_throw then - let exceptions = args |> throw_args in + let exceptions = args |> throw_args ~module_path in current_events := {Event.exceptions; loc; kind = Throws} :: !current_events else if not (is_division callee_name && divides_by_non_zero_constant args) @@ -407,7 +500,9 @@ let traverse_ast ~file ~values_builder ~checks_builder () = cases_exn |> List.map (fun (case : Typedtree.case) -> case.c_lhs.pat_desc) in - let exceptions = exception_patterns |> exceptions_of_patterns in + let exceptions = + exception_patterns |> exceptions_of_patterns ~module_path + in if exception_patterns <> [] then ( let old_events = !current_events in current_events := []; @@ -431,7 +526,7 @@ let traverse_ast ~file ~values_builder ~checks_builder () = let exceptions = cases |> List.map (fun case -> case.Typedtree.c_lhs.pat_desc) - |> exceptions_of_patterns + |> exceptions_of_patterns ~module_path in let old_events = !current_events in current_events := []; @@ -513,6 +608,12 @@ let traverse_ast ~file ~values_builder ~checks_builder () = process_binding (id |> Ident.name) | _ -> super.value_binding self vb in + let add_alias module_path ~name path = + let head = Path.head path in + if Ident.persistent head then + Hashtbl.replace alias_units (Ident.name head) (); + Module_path.add_alias module_path ~name ~path:(path |> Dce_path.from_path_t) + in let make_mapper (module_path : Module_path.t) : Tast_mapper.mapper = let open Tast_mapper in { @@ -550,9 +651,7 @@ let traverse_ast ~file ~values_builder ~checks_builder () = let mp_inside = Module_path.enter_module mp ~name ~loc:mb_loc in process_module_expr mp_inside mb_expr; match mb_expr.mod_desc with - | Tmod_ident (path_, _lid) -> - Module_path.add_alias mp ~name - ~path:(path_ |> Dce_path.from_path_t) + | Tmod_ident (path_, _lid) -> add_alias mp ~name path_ | _ -> mp) | Tstr_recmodule mbs -> (* Process each module in the recursive group in the current scope; aliases are collected in the current scope too. *) @@ -564,9 +663,7 @@ let traverse_ast ~file ~values_builder ~checks_builder () = in process_module_expr mp_inside mb_expr; match mb_expr.mod_desc with - | Tmod_ident (path_, _lid) -> - Module_path.add_alias acc ~name - ~path:(path_ |> Dce_path.from_path_t) + | Tmod_ident (path_, _lid) -> add_alias acc ~name path_ | _ -> acc) mp mbs | _ -> @@ -584,12 +681,16 @@ type file_result = { module_name: string; values_builder: values_builder; checks: check list; + seen_exceptions: Exceptions.t; + (** The exceptions the file catches or throws, by constructor path *) } (** Result of processing a single file *) -let process_structure ~file ~values_builder ~checks_builder +let process_structure ~file ~values_builder ~checks_builder ~seen_exceptions (structure : Typedtree.structure) = - let process = traverse_ast ~file ~values_builder ~checks_builder () in + let process = + traverse_ast ~file ~values_builder ~checks_builder ~seen_exceptions () + in process structure let process_cmt ~file (cmt_infos : Cmt_format.cmt_infos) : file_result option = @@ -598,12 +699,15 @@ let process_cmt ~file (cmt_infos : Cmt_format.cmt_infos) : file_result option = | Implementation structure -> let values_builder = create_values_builder () in let checks_builder = create_checks_builder () in - structure |> process_structure ~file ~values_builder ~checks_builder; + let seen_exceptions = ref Exceptions.empty in + structure + |> process_structure ~file ~values_builder ~checks_builder ~seen_exceptions; Some { module_name = file.File_context.module_name; values_builder; checks = checks_builder_to_list checks_builder; + seen_exceptions = !seen_exceptions; } | _ -> None @@ -617,5 +721,11 @@ let run_checks ~config (all_results : file_result list) = in (* Collect all checks *) let all_checks = all_results |> List.concat_map (fun r -> r.checks) in + let known = + all_results + |> List.fold_left + (fun acc r -> Exceptions.union acc r.seen_exceptions) + Exceptions.empty + in (* Run checks with merged table *) - Checks.do_checks ~values_table ~config all_checks + Checks.do_checks ~values_table ~known ~config all_checks diff --git a/analysis/reanalyze/src/exceptions.ml b/analysis/reanalyze/src/exceptions.ml index a5903143ad4..b3a75661ea7 100644 --- a/analysis/reanalyze/src/exceptions.ml +++ b/analysis/reanalyze/src/exceptions.ml @@ -8,6 +8,8 @@ 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 mem = Exn_set.mem +let map = Exn_set.map let iter = Exn_set.iter let union = Exn_set.union diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt b/tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt index 5526549b570..ab551124047 100644 --- a/tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt +++ b/tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt @@ -175,5 +175,13 @@ 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) - Analysis reported 44 issues (Exception Analysis:44) + Analysis reported 46 issues (Exception Analysis:46) 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 00000000000..45e7fcd19de --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExn.res @@ -0,0 +1,19 @@ +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" +} 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 00000000000..04ede4d0aa1 --- /dev/null +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExnCalls.res @@ -0,0 +1,71 @@ +// 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 + } From bd4a72228a6230b57fb366e6ca855471decbaeb1 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Wed, 18 Nov 2026 19:30:20 +0000 Subject: [PATCH 4/4] Name exceptions by where they are defined in exception analysis MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why: A review of 81ce8eb26c found that it broke common code. A @throws naming another module's exception got the callee's module put in front (`ThrowsRepo.ThrowsErrors.NotFound`). A binding's own @throws was still compared as written, so `@throws(Bad)` after `open ThrowsErrors`, an alias, or any name in a namespaced project warned twice. And how a name resolved depended on whether some other file caught it. Every exception now has one name: where it is defined. A file's own exceptions are named with the file and module (`File.M.E`), a namespace is left out, and `exception E = Lib.F` is `Lib.F`. Every @throws name is resolved in the scope it was written in: the module and the modules around it, what they include, and the file's opens and module aliases. The first candidate the project defines, catches or throws wins. A binding's own @throws is resolved the same way. Messages leave out the current file's name, so existing warnings read as before. A namespaced callee path now drops the namespace (`Ns.Lib.f` is `Lib.f`), so calls in namespaced projects find the binding's @throws. A functor parameter's declarations are still named after the parameter: `X.get`'s `@throws(E)` is `X.E`. A fixture shows this limit. Reanalyze modified (names from another module, open and alias): Example: // ThrowsErrors.res exception NotFound exception Bad(string) // ThrowsRepo.res @throws(ThrowsErrors.NotFound) let find = x => x > 0 ? x : throw(ThrowsErrors.NotFound) open ThrowsErrors @throws(Bad) let viaOpen = x => x > 0 ? x : throw(Bad("negative")) // ThrowsRepoCalls.res let catchFind = x => try ThrowsRepo.find(x) catch { | ThrowsErrors.NotFound => 0 } Before (reanalyze): tests/analysis_tests/tests-reanalyze/deadcode/src/exception Exception Analysis ThrowsRepo.res:17:5-11 viaOpen might throw ThrowsErrors.Bad (ThrowsRepo.res:17:31) and is annotated with redundant @throws(Bad) Exception Analysis ThrowsRepoCalls.res:3:5-13 catchFind might throw ThrowsRepo.ThrowsErrors.NotFound (ThrowsRepoCalls.res:4:6) and is not annotated with @throws(ThrowsRepo.ThrowsErrors.NotFound) Exception Analysis ThrowsRepoCalls.res:24:5-13 annotated might throw ThrowsRepo.ThrowsErrors.NotFound (ThrowsRepoCalls.res:24:21) and is annotated with redundant @throws(ThrowsErrors.NotFound) … Analysis reported 63 issues (Exception Analysis:63) After (reanalyze): tests/analysis_tests/tests-reanalyze/deadcode/src/exception Exception Analysis ThrowsLibExnCalls.res:101:7-12 caught might throw X.E (ThrowsLibExnCalls.res:102:8) and is not annotated with @throws(X.E) Analysis reported 47 issues (Exception Analysis:47) Review: Why not resolve @throws in the type checker, which has the environment? That would be exact, and would also handle functor parameters, but it is a much bigger compiler change. The .cmt keeps no environments, so reanalyze rebuilds the scope it needs from the file. Review: Can a guess pick the wrong exception? Only when two candidates both exist, as a module's own E and an E it opens. The module's own name is tried first, then what it includes, then the outer modules, then the opens, which can differ from the language's shadowing order. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gHA54VKxsXvCQyC2vw Signed-off-by: Christoph Knittel --- analysis/reanalyze/src/exception.ml | 545 ++++++++++++------ .../deadcode/expected/exception.txt | 6 +- .../deadcode/src/exception/ThrowsErrors.res | 2 + .../deadcode/src/exception/ThrowsLibExn.res | 5 + .../src/exception/ThrowsLibExnCalls.res | 34 ++ .../deadcode/src/exception/ThrowsReexport.res | 1 + .../deadcode/src/exception/ThrowsRepo.res | 22 + .../src/exception/ThrowsRepoCalls.res | 29 + 8 files changed, 468 insertions(+), 176 deletions(-) create mode 100644 tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsErrors.res create mode 100644 tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsReexport.res create mode 100644 tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsRepo.res create mode 100644 tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsRepoCalls.res diff --git a/analysis/reanalyze/src/exception.ml b/analysis/reanalyze/src/exception.ml index c9a00355c49..60dd87f220e 100644 --- a/analysis/reanalyze/src/exception.ml +++ b/analysis/reanalyze/src/exception.ml @@ -1,17 +1,24 @@ open Dead_common -type values_builder = (Name.t, Exceptions.t) Hashtbl.t -(** Per-file mutable builder for exception values during AST processing *) +(* Exceptions are named by where they are defined: [Lib.E], [Lib.Inner.F], + or [File.E] for one defined in the file [File]. A [@throws] payload is a + name as written at the annotation, so it is resolved against a scope: the + candidate prefixes, in priority order, that the name may be relative to. *) +type scope = string list -type values_table = (string, (Name.t, Exceptions.t) Hashtbl.t) Hashtbl.t +type values_builder = (Name.t, Exceptions.t * scope) Hashtbl.t +(** Per-file mutable builder for exception values during AST processing: a + binding's [@throws] as written, with the scope it was written in *) + +type values_table = (string, values_builder) Hashtbl.t (** Merged immutable table for cross-file lookups *) let create_values_builder () : values_builder = Hashtbl.create 15 -let values_builder_add (builder : values_builder) ~module_path ~name exceptions - = +let values_builder_add (builder : values_builder) ~module_path ~name ~scope + exceptions = let path = (name |> Name.create) :: module_path.Module_path.path in - Hashtbl.replace builder (path |> Dce_path.to_name) exceptions + Hashtbl.replace builder (path |> Dce_path.to_name) (exceptions, scope) (** Merge all per-file builders into a single lookup table *) let merge_values_builders (builders : (string * values_builder) list) : @@ -66,16 +73,14 @@ module Values = struct | Some exceptions -> Some exceptions end -(* Where a callee's [@throws] names are resolved. A catch or a throw names an - exception by its constructor's path, as [Lib.E] or, defined in the same - file, as [E] or [M.E]. A [@throws(E)] on a declaration in [Lib.Inner] means - [Lib.Inner.E] or [Lib.E], whichever exists. *) -type scope = { - prefixes: string list; - (** Candidate prefixes for a name, innermost first. [""] stands for the - bare name, which is a candidate only for a callee in the same file: - a bare [E] there is the caller's own [E]. *) - fallback: string; (** The prefix to use when no candidate is known. *) +type names = { + known: Exceptions.t; + (** The exceptions the project's files define, catch or throw *) + aliases: (string, string) Hashtbl.t; + (** Module aliases by their qualified name, as [File.L] for + [module L = Lib] in [File], to the module they name *) + includes: (string, string list) Hashtbl.t; + (** The modules each module includes, by qualified name *) } let predef_exceptions = @@ -83,21 +88,67 @@ let predef_exceptions = |> List.filter_map (fun (name, id) -> if Ident.is_predef_exn id then Some name else None) -(* [known] holds the exceptions caught or thrown somewhere in the project, so - it holds every exception that a catch could match. *) -let resolve_declared ~known ~(scope : scope) exn = +(* Replace the longest prefix of [name] that is a module alias by the module + it names: [File.L.E] becomes [Lib.E]. *) +let resolve_aliases ~aliases name = + let components = String.split_on_char '.' name in + let rec split n prefix rest = + if n = 0 then Some (List.rev prefix, rest) + else + match rest with + | [] -> None + | c :: rest -> split (n - 1) (c :: prefix) rest + in + let rec try_prefix n = + if n = 0 then name + else + match split n [] components with + | Some (prefix, rest) -> ( + match Hashtbl.find_opt aliases (String.concat "." prefix) with + | Some target -> String.concat "." (target :: rest) + | None -> try_prefix (n - 1)) + | None -> try_prefix (n - 1) + in + try_prefix (List.length components - 1) + +(* Resolve a [@throws] name written in [scope]: the first candidate that the + project defines, catches or throws. Otherwise a predefined exception, or a + qualified name, stands for itself, and a bare name is taken to be defined + in the innermost scope. *) +let resolve ~names ~(scope : scope) exn = let name = Exn.to_string exn in - if List.mem name predef_exceptions then exn - else - let qualify prefix = - Exn.from_string (if prefix = "" then name else prefix ^ "." ^ name) - in - match - scope.prefixes - |> List.find_opt (fun prefix -> Exceptions.mem (qualify prefix) known) - with - | Some prefix -> qualify prefix - | None -> qualify scope.fallback + let normalize s = resolve_aliases ~aliases:names.aliases s in + let with_includes prefix = + prefix + :: (Hashtbl.find_opt names.includes prefix |> Option.value ~default:[]) + in + let candidates = + (scope + |> List.concat_map with_includes + |> List.map (fun prefix -> normalize (prefix ^ "." ^ name))) + @ [normalize name] + in + match + candidates + |> List.find_opt (fun c -> Exceptions.mem (Exn.from_string c) names.known) + with + | Some c -> Exn.from_string c + | None -> ( + if List.mem name predef_exceptions || String.contains name '.' then + Exn.from_string (normalize name) + else + match scope with + | prefix :: _ -> Exn.from_string (normalize (prefix ^ "." ^ name)) + | [] -> exn) + +(* The module [A.B.C] and the modules around it: [A.B.C], [A.B], [A] *) +let prefixes components : scope = + let rec go rev_components = + match rev_components with + | [] -> [] + | _ :: outer -> String.concat "." (List.rev rev_components) :: go outer + in + go (List.rev components) module Event = struct type kind = @@ -139,7 +190,7 @@ module Event = struct nested_events |> List.iter (fun e -> Format.fprintf ppf "%a " print e)) () - let combine ~(values_table : values_table) ~known ~config ~module_name events + let combine ~(values_table : values_table) ~names ~config ~module_name events = if config.Dce_config.cli.debug then ( Log_.item "@."; @@ -168,15 +219,20 @@ module Event = struct if config.Dce_config.cli.debug then Log_.item "%a@." print ev; (* [declared] comes from the declaration's [@throws], the values table from the [@throws] of the implementation's binding. Both describe - what the call can throw, so take both. Both name exceptions as - written at the declaration, so resolve them in its scope. *) + what the call can throw, so take both, each resolved in the scope + it was written in. *) let exceptions = - (match - callee |> Values.find_path values_table ~module_name ~module_path - with - | Some exceptions -> Exceptions.union declared exceptions - | None -> declared) - |> Exceptions.map (resolve_declared ~known ~scope) + match + callee |> Values.find_path values_table ~module_name ~module_path + with + | Some (exceptions, binding_scope) -> + (* The binding's scope also knows the opens of its file, which the + declaration (often a copy of the binding's [@throws] in the + inferred signature) was written among. *) + let scope = binding_scope @ scope in + Exceptions.union declared exceptions + |> Exceptions.map (resolve ~names ~scope) + | None -> declared |> Exceptions.map (resolve ~names ~scope) in exceptions |> Exceptions.iter (fun exn -> extend_exn_table exn loc); loop (Exceptions.union exn_set exceptions) rest @@ -226,26 +282,57 @@ and check = { module_name: string; exn_name: string; exceptions: Exceptions.t; + scope: scope; (** The scope the binding's [@throws] is written in *) } let create_checks_builder () : checks_builder = ref [] -let checks_builder_add (builder : checks_builder) ~events ~exceptions ~loc - ?(loc_full = loc) ~module_name exn_name = +let checks_builder_add (builder : checks_builder) ~events ~exceptions ~scope + ~loc ?(loc_full = loc) ~module_name exn_name = builder := - {events; exceptions; loc; loc_full; module_name; exn_name} :: !builder + {events; exceptions; scope; loc; loc_full; module_name; 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) ~known ~config - {events; exceptions; loc; loc_full; module_name; exn_name} = + let do_check ~(values_table : values_table) ~names ~config + {events; exceptions; scope; loc; loc_full; module_name; exn_name} = let throw_set, exn_table = - events |> Event.combine ~values_table ~known ~config ~module_name + events |> Event.combine ~values_table ~names ~config ~module_name in + let exceptions = exceptions |> Exceptions.map (resolve ~names ~scope) in let missing_annotations = Exceptions.diff throw_set exceptions in let redundant_annotations = Exceptions.diff exceptions throw_set in + (* Messages name the file's own exceptions without the file's name. *) + let prefix = module_name ^ "." in + let relative exn = + let s = Exn.to_string exn in + if String.starts_with ~prefix s then + Exn.from_string + (String.sub s (String.length prefix) + (String.length s - String.length prefix)) + else exn + in + let throw_set = throw_set |> Exceptions.map relative in + let missing_annotations = missing_annotations |> Exceptions.map relative in + let redundant_annotations = + redundant_annotations |> Exceptions.map relative + in + let exn_table = + let table = Hashtbl.create (Hashtbl.length exn_table) in + exn_table + |> Hashtbl.iter (fun exn loc_set -> + let exn = relative exn in + let loc_set = + match Hashtbl.find_opt table exn with + | Some other -> Loc_set.union loc_set other + | None -> loc_set + in + Hashtbl.replace table exn loc_set); + table + in (if not (Exceptions.is_empty missing_annotations) then let description = Issue.ExceptionAnalysisMissing @@ -272,17 +359,58 @@ module Checks = struct redundant_annotations); }) - let do_checks ~values_table ~known ~config (checks : check list) = - checks |> List.iter (do_check ~values_table ~known ~config) + let do_checks ~values_table ~names ~config (checks : check list) = + checks |> List.iter (do_check ~values_table ~names ~config) end -let traverse_ast ~file ~values_builder ~checks_builder ~seen_exceptions () = +(* What a file contributes to [names] *) +type file_names = { + mutable file_known: Exceptions.t; + file_aliases: (string, string) Hashtbl.t; + file_includes: (string, string list) Hashtbl.t; +} + +let traverse_ast ~file ~namespace ~values_builder ~checks_builder + ~(file_names : file_names) () = let super = Tast_mapper.default in let current_id = ref "" in let current_events = ref [] in - (* Compilation units that the file's module aliases point into. A call - through such an alias is a call into another file. *) - let alias_units = Hashtbl.create 1 in + let module_name = file.File_context.module_name in + (* The qualified name of each module and exception the file defines, by + its identifier: [File.M] for [module M], [File.M.E] for [exception E] + in [M], the aliased module for [module L = Lib], and the rebound + exception for [exception E = Lib.F]. *) + let local_idents : (Ident.t, string list) Hashtbl.t = Hashtbl.create 16 in + let rec canonical_path (path : Path.t) = + match path with + | Pident id -> ( + match Hashtbl.find_opt local_idents id with + | Some components -> components + | None when Ident.persistent id -> + (* [Lib-Ns] is the file [Lib] of namespace [Ns]; the namespace + module itself is left out, as reanalyze names files without + it. *) + let name = + match String.index_opt (Ident.name id) '-' with + | Some i -> String.sub (Ident.name id) 0 i + | None -> Ident.name id + in + if Some name = namespace then [] else [name] + | None -> [Ident.name id]) + | Pdot (p, s, _) -> canonical_path p @ [s] + | Papply _ -> [Path.name path] + in + let qualified (module_path : Module_path.t) = + module_name :: List.rev_map Name.to_string module_path.path + in + let add_known exn = + file_names.file_known <- Exceptions.add exn file_names.file_known + in + (* The scope of code in [module_path] with [opens] (the modules opened or + included there, latest first) *) + let scope_at ~module_path ~opens : scope = + prefixes (qualified module_path) @ opens + in (* For local lookups during AST processing, we look up in the current file's builder *) let find_local_exceptions ~module_path path = let name = path @ module_path |> Dce_path.to_name in @@ -297,61 +425,35 @@ let traverse_ast ~file ~values_builder ~checks_builder ~seen_exceptions () = | _ :: rest_module_path -> path |> find_local_path ~module_path:rest_module_path) in - (* Name an exception by its constructor's path rather than by how the source + (* Name an exception by where it is defined rather than by how the source spells it, so [Lib.E], [E] after [open Lib] and [L.E] for [module L = Lib] are the same exception, and a file's own [E] is not [Lib.E]. *) - let exn_of_constructor ~(module_path : Module_path.t) lid - (cstr : Types.constructor_description) = + let exn_of_constructor lid (cstr : Types.constructor_description) = let exn = match cstr.cstr_kind with - | Extension_constructor (Pident id) when Ident.is_predef_exn id -> - Exn.from_string (Ident.name id) - | Extension_constructor path -> ( - match path |> Dce_path.from_path_t with - | [] -> Exn.from_lid lid - | dce_path -> - dce_path - |> Module_path.resolve_alias module_path - |> Dce_path.to_string |> Exn.from_string) + | Extension_constructor path -> + path |> canonical_path |> String.concat "." |> Exn.from_string | Ordinary_constructor _ -> Exn.from_lid lid in - seen_exceptions := Exceptions.add exn !seen_exceptions; + add_known exn; exn in - let exceptions_of_patterns ~module_path patterns = + let exceptions_of_patterns patterns = patterns |> List.fold_left (fun acc desc -> match desc with | Typedtree.Tpat_construct ({txt}, cstr, _) -> - Exceptions.add (exn_of_constructor ~module_path txt cstr) acc + Exceptions.add (exn_of_constructor txt cstr) acc | _ -> acc) Exceptions.empty in - (* The scope of a callee's declaration, from the callee's path. A call into - another file never resolves a name to a bare one. *) - let scope_of_callee ~(callee_path : Path.t) (callee : Dce_path.t) = - let modules = - match callee with - | _ :: modules -> modules - | [] -> [] - in - let rec prefixes modules = - match modules with - | [] -> [] - | _ :: outer -> Dce_path.to_string modules :: prefixes outer - in - let other_file = - Ident.persistent (Path.head callee_path) - || - match List.rev modules with - | root :: _ -> Hashtbl.mem alias_units (Name.to_string root) - | [] -> false - in - match prefixes modules with - | innermost :: _ as prefixes when other_file -> - {prefixes; fallback = innermost} - | prefixes -> {prefixes = prefixes @ [""]; fallback = ""} + (* The scope of a callee's declaration: the module it is in and the modules + around it, or the caller's own scope for a value defined there. *) + let scope_of_callee ~scope (callee_path : Path.t) : scope = + match callee_path with + | Pdot (module_path, _, _) -> prefixes (canonical_path module_path) + | Pident _ | Papply _ -> scope in let iter_expr self e = self.Tast_mapper.expr self e |> ignore in let iter_expr_opt self eo = @@ -391,13 +493,20 @@ let traverse_ast ~file ~values_builder ~checks_builder ~seen_exceptions () = is_non_zero_constant c | _ -> false in - let throw_args ~module_path args = + let throw_args args = match args with | [(_, Some {Typedtree.exp_desc = Texp_construct ({txt}, cstr, _)})] -> - [exn_of_constructor ~module_path 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 + [exn_of_constructor txt cstr] |> Exceptions.from_list + | _ -> + (* A stand-in name, which an annotation can name as it is *) + let exn = + match args with + | [(_, Some {Typedtree.exp_desc = Texp_ident _})] -> + Exn.from_string "genericException" + | _ -> Exn.from_string "TODO_from_raise1" + in + add_known exn; + [exn] |> Exceptions.from_list in let does_not_throw attributes = attributes @@ -436,8 +545,8 @@ let traverse_ast ~file ~values_builder ~checks_builder ~seen_exceptions () = | None -> Exceptions.empty | Some payload -> payload |> get_exceptions in - let expr ~(module_path : Module_path.t) (self : Tast_mapper.mapper) - (expr : Typedtree.expression) = + let expr ~(module_path : Module_path.t) ~(scope : scope) + (self : Tast_mapper.mapper) (expr : Typedtree.expression) = let loc = expr.exp_loc in let is_does_no_throw = expr.exp_attributes |> does_not_throw in let old_events = !current_events in @@ -445,7 +554,16 @@ let traverse_ast ~file ~values_builder ~checks_builder ~seen_exceptions () = (match expr.exp_desc with | Texp_ident (callee_, _, vd) -> let callee = - callee_ |> Dce_path.from_path_t |> Module_path.resolve_alias module_path + let callee = + callee_ |> Dce_path.from_path_t + |> Module_path.resolve_alias module_path + in + (* [Ns.Lib.f] is [Lib.f] of this file's namespace [Ns]. *) + match List.rev callee with + | root :: (_ :: _ as rest) when Some (Name.to_string root) = namespace + -> + List.rev rest + | _ -> callee in let callee_name = callee |> Dce_path.to_name in if callee_name |> Name.to_string |> is_throw then @@ -469,7 +587,7 @@ let traverse_ast ~file ~values_builder ~checks_builder ~seen_exceptions () = { callee; module_path = module_path.path; - scope = scope_of_callee ~callee_path:callee_ callee; + scope = scope_of_callee ~scope callee_; }; } :: !current_events @@ -481,14 +599,14 @@ let traverse_ast ~file ~values_builder ~checks_builder ~seen_exceptions () = when (* raise @@ Exn(...) *) atat |> Path.name = "Pervasives.@@" && callee |> Path.name |> is_throw -> - let exceptions = [arg] |> throw_args ~module_path in + let exceptions = [arg] |> throw_args in current_events := {Event.exceptions; loc; kind = Throws} :: !current_events; arg |> snd |> iter_expr_opt self | Texp_apply {funct = {exp_desc = Texp_ident (callee, _, _)} as e; args} -> let callee_name = Path.name callee in if callee_name |> is_throw then - let exceptions = args |> throw_args ~module_path in + let exceptions = args |> throw_args in current_events := {Event.exceptions; loc; kind = Throws} :: !current_events else if not (is_division callee_name && divides_by_non_zero_constant args) @@ -500,9 +618,7 @@ let traverse_ast ~file ~values_builder ~checks_builder ~seen_exceptions () = cases_exn |> List.map (fun (case : Typedtree.case) -> case.c_lhs.pat_desc) in - let exceptions = - exception_patterns |> exceptions_of_patterns ~module_path - in + let exceptions = exception_patterns |> exceptions_of_patterns in if exception_patterns <> [] then ( let old_events = !current_events in current_events := []; @@ -526,7 +642,7 @@ let traverse_ast ~file ~values_builder ~checks_builder ~seen_exceptions () = let exceptions = cases |> List.map (fun case -> case.Typedtree.c_lhs.pat_desc) - |> exceptions_of_patterns ~module_path + |> exceptions_of_patterns in let old_events = !current_events in current_events := []; @@ -548,23 +664,22 @@ let traverse_ast ~file ~values_builder ~checks_builder ~seen_exceptions () = :: old_events); expr in - let toplevel_eval (self : Tast_mapper.mapper) (expr : Typedtree.expression) - attributes = + let toplevel_eval ~scope (self : Tast_mapper.mapper) + (expr : Typedtree.expression) attributes = let old_id = !current_id in let old_events = !current_events in let name = "Toplevel expression" in current_id := name; current_events := []; - 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; + ~scope ~loc:expr.exp_loc ~module_name name; current_id := old_id; current_events := old_events in - let value_binding ~(module_path : Module_path.t) (self : Tast_mapper.mapper) - (vb : Typedtree.value_binding) = + let value_binding ~(module_path : Module_path.t) ~(scope : scope) + (self : Tast_mapper.mapper) (vb : Typedtree.value_binding) = let old_id = !current_id in let old_events = !current_events in let is_function = @@ -579,18 +694,17 @@ let traverse_ast ~file ~values_builder ~checks_builder ~seen_exceptions () = let exceptions_from_annotations = get_exceptions_from_annotations vb.vb_attributes in - values_builder_add values_builder ~module_path ~name + values_builder_add values_builder ~module_path ~name ~scope exceptions_from_annotations; let res = super.value_binding self vb in - let module_name = file.File_context.module_name in let path = [name |> Name.create] in - let exceptions = + let exceptions, scope = match path |> find_local_path ~module_path:module_path.path with - | Some exceptions -> exceptions - | _ -> Exceptions.empty + | Some found -> found + | None -> (Exceptions.empty, scope) in checks_builder_add checks_builder ~events:!current_events ~exceptions - ~loc:vb.vb_pat.pat_loc ~loc_full:vb.vb_loc ~module_name name; + ~scope ~loc:vb.vb_pat.pat_loc ~loc_full:vb.vb_loc ~module_name name; current_id := old_id; current_events := old_events; res @@ -608,106 +722,176 @@ let traverse_ast ~file ~values_builder ~checks_builder ~seen_exceptions () = process_binding (id |> Ident.name) | _ -> super.value_binding self vb in - let add_alias module_path ~name path = - let head = Path.head path in - if Ident.persistent head then - Hashtbl.replace alias_units (Ident.name head) (); - Module_path.add_alias module_path ~name ~path:(path |> Dce_path.from_path_t) + (* The module a module expression names, as in [include Lib], also when the + compiler wraps it in a coercion *) + let rec module_ident (me : Typedtree.module_expr) = + match me.mod_desc with + | Tmod_ident (path, _) -> Some path + | Tmod_constraint (me, _, _, _) -> module_ident me + | Tmod_structure _ | Tmod_functor _ | Tmod_apply _ | Tmod_unpack _ -> None + in + (* Record a module the file defines, under its qualified name, or the module + an alias names. *) + let add_module (mp : Module_path.t) ~mb_id (mb_expr : Typedtree.module_expr) = + let name = mb_id |> Ident.name |> Name.create in + let own = qualified mp @ [Ident.name mb_id] in + match mb_expr.mod_desc with + | Tmod_ident (path_, _lid) -> + let target = canonical_path path_ in + Hashtbl.replace local_idents mb_id target; + Hashtbl.replace file_names.file_aliases (String.concat "." own) + (String.concat "." target); + Module_path.add_alias mp ~name ~path:(path_ |> Dce_path.from_path_t) + | _ -> + Hashtbl.replace local_idents mb_id own; + mp in - let make_mapper (module_path : Module_path.t) : Tast_mapper.mapper = + (* Record an exception (or other extension constructor) the file defines. *) + let add_extension_constructor (mp : Module_path.t) + (ext : Typedtree.extension_constructor) = + match ext.ext_kind with + | Text_rebind (path, _) -> + Hashtbl.replace local_idents ext.ext_id (canonical_path path) + | Text_decl _ -> + let own = qualified mp @ [Ident.name ext.ext_id] in + Hashtbl.replace local_idents ext.ext_id own; + add_known (Exn.from_string (String.concat "." own)) + in + let make_mapper (module_path : Module_path.t) ~scope : Tast_mapper.mapper = let open Tast_mapper in { super with - expr = expr ~module_path; - value_binding = value_binding ~module_path; + expr = expr ~module_path ~scope; + value_binding = value_binding ~module_path ~scope; } in - let rec process_module_expr (module_path : Module_path.t) + let rec process_module_expr (module_path : Module_path.t) ~opens (me : Typedtree.module_expr) = match me.mod_desc with - | Tmod_structure structure -> process_structure module_path structure + | Tmod_structure structure -> process_structure module_path ~opens structure | Tmod_constraint (me1, _mty, _mtc, _coercion) -> - process_module_expr module_path me1 + process_module_expr module_path ~opens me1 | Tmod_apply (me1, me2, _) -> - process_module_expr module_path me1; - process_module_expr module_path me2 + process_module_expr module_path ~opens me1; + process_module_expr module_path ~opens me2 | _ -> - let mapper = make_mapper module_path in + let mapper = + make_mapper module_path ~scope:(scope_at ~module_path ~opens) + in super.module_expr mapper me |> ignore - and process_structure (module_path : Module_path.t) + and process_structure (module_path : Module_path.t) ~opens (structure : Typedtree.structure) = - let rec loop (mp : Module_path.t) (items : Typedtree.structure_item list) = + let rec loop (mp : Module_path.t) opens + (items : Typedtree.structure_item list) = match items with | [] -> () | structure_item :: rest -> - let mapper = make_mapper mp in - let mp' = + let mapper = make_mapper mp ~scope:(scope_at ~module_path:mp ~opens) in + let default () = super.structure_item mapper structure_item |> ignore in + let mp', opens' = match structure_item.str_desc with | Tstr_eval (expr, attributes) -> - toplevel_eval mapper expr attributes; - mp - | Tstr_module {mb_id; mb_loc; mb_expr} -> ( + toplevel_eval + ~scope:(scope_at ~module_path:mp ~opens) + mapper expr attributes; + (mp, opens) + | Tstr_module {mb_id; mb_loc; mb_expr} -> let name = mb_id |> Ident.name |> Name.create in let mp_inside = Module_path.enter_module mp ~name ~loc:mb_loc in - process_module_expr mp_inside mb_expr; - match mb_expr.mod_desc with - | Tmod_ident (path_, _lid) -> add_alias mp ~name path_ - | _ -> mp) + process_module_expr mp_inside ~opens mb_expr; + (add_module mp ~mb_id mb_expr, opens) | Tstr_recmodule mbs -> (* Process each module in the recursive group in the current scope; aliases are collected in the current scope too. *) - List.fold_left - (fun acc {Typedtree.mb_id; mb_loc; mb_expr} -> - let name = mb_id |> Ident.name |> Name.create in - let mp_inside = - Module_path.enter_module acc ~name ~loc:mb_loc - in - process_module_expr mp_inside mb_expr; - match mb_expr.mod_desc with - | Tmod_ident (path_, _lid) -> add_alias acc ~name path_ - | _ -> acc) - mp mbs + ( List.fold_left + (fun acc {Typedtree.mb_id; mb_loc; mb_expr} -> + let name = mb_id |> Ident.name |> Name.create in + let mp_inside = + Module_path.enter_module acc ~name ~loc:mb_loc + in + process_module_expr mp_inside ~opens mb_expr; + add_module acc ~mb_id mb_expr) + mp mbs, + opens ) + | Tstr_exception ext -> + add_extension_constructor mp ext; + default (); + (mp, opens) + | Tstr_typext {tyext_constructors} -> + tyext_constructors |> List.iter (add_extension_constructor mp); + default (); + (mp, opens) + | Tstr_open {open_path} -> + (mp, String.concat "." (canonical_path open_path) :: opens) + | Tstr_include {incl_mod} when module_ident incl_mod <> None -> + let path = Option.get (module_ident incl_mod) in + default (); + let included = String.concat "." (canonical_path path) in + let key = String.concat "." (qualified mp) in + Hashtbl.replace file_names.file_includes key + ((Hashtbl.find_opt file_names.file_includes key + |> Option.value ~default:[]) + @ [included]); + (mp, included :: opens) | _ -> - super.structure_item mapper structure_item |> ignore; - mp + default (); + (mp, opens) in - loop mp' rest + loop mp' opens' rest in - loop module_path structure.str_items + loop module_path opens structure.str_items in fun (structure : Typedtree.structure) -> - process_structure Module_path.initial structure + process_structure Module_path.initial ~opens:[] structure type file_result = { module_name: string; values_builder: values_builder; checks: check list; - seen_exceptions: Exceptions.t; - (** The exceptions the file catches or throws, by constructor path *) + known: Exceptions.t; + (** The exceptions the file defines, catches or throws *) + aliases: (string * string) list; + (** The file's module aliases, by qualified name *) + includes: (string * string list) list; + (** The modules the file's modules include, by qualified name *) } (** Result of processing a single file *) -let process_structure ~file ~values_builder ~checks_builder ~seen_exceptions - (structure : Typedtree.structure) = - let process = - traverse_ast ~file ~values_builder ~checks_builder ~seen_exceptions () - in - process structure - let process_cmt ~file (cmt_infos : Cmt_format.cmt_infos) : file_result option = match cmt_infos.cmt_annots with | Interface _ -> None | Implementation structure -> let values_builder = create_values_builder () in let checks_builder = create_checks_builder () in - let seen_exceptions = ref Exceptions.empty in + let file_names = + { + file_known = Exceptions.empty; + file_aliases = Hashtbl.create 1; + file_includes = Hashtbl.create 1; + } + in + let namespace = + match String.index_opt cmt_infos.cmt_modname '-' with + | Some i -> + Some + (String.sub cmt_infos.cmt_modname (i + 1) + (String.length cmt_infos.cmt_modname - i - 1)) + | None -> None + in structure - |> process_structure ~file ~values_builder ~checks_builder ~seen_exceptions; + |> traverse_ast ~file ~namespace ~values_builder ~checks_builder ~file_names + (); Some { module_name = file.File_context.module_name; values_builder; checks = checks_builder_to_list checks_builder; - seen_exceptions = !seen_exceptions; + known = file_names.file_known; + aliases = + Hashtbl.fold (fun k v acc -> (k, v) :: acc) file_names.file_aliases []; + includes = + Hashtbl.fold + (fun k v acc -> (k, v) :: acc) + file_names.file_includes []; } | _ -> None @@ -721,11 +905,22 @@ let run_checks ~config (all_results : file_result list) = in (* Collect all checks *) let all_checks = all_results |> List.concat_map (fun r -> r.checks) in - let known = + let names = + let aliases = Hashtbl.create 16 in + let includes = Hashtbl.create 16 in all_results - |> List.fold_left - (fun acc r -> Exceptions.union acc r.seen_exceptions) - Exceptions.empty + |> List.iter (fun r -> + r.aliases |> List.iter (fun (k, v) -> Hashtbl.replace aliases k v); + r.includes |> List.iter (fun (k, v) -> Hashtbl.replace includes k v)); + { + includes; + known = + all_results + |> List.fold_left + (fun acc r -> Exceptions.union acc r.known) + Exceptions.empty; + aliases; + } in (* Run checks with merged table *) - Checks.do_checks ~values_table ~known ~config all_checks + Checks.do_checks ~values_table ~names ~config all_checks diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt b/tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt index ab551124047..4e943994052 100644 --- a/tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt +++ b/tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt @@ -183,5 +183,9 @@ 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:101:7-12 + caught might throw X.E (ThrowsLibExnCalls.res:102:8) and is not annotated with @throws(X.E) - Analysis reported 46 issues (Exception Analysis:46) + Analysis reported 47 issues (Exception Analysis:47) 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 00000000000..48e4679f14a --- /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/ThrowsLibExn.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExn.res index 45e7fcd19de..94d39a657db 100644 --- a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExn.res +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExn.res @@ -17,3 +17,8 @@ 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 index 04ede4d0aa1..5da7dd6d08c 100644 --- a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExnCalls.res +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExnCalls.res @@ -69,3 +69,37 @@ 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) + +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 + } + +// Known limit: a functor parameter's declarations are named after the +// parameter, so X.get's E is not resolved to ThrowsLibExn.E. +module UseS = (X: ThrowsLibExn.S) => { + let caught = x => + try X.get(x) catch { + | ThrowsLibExn.E => 0 + } +} 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 00000000000..199350e6035 --- /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 00000000000..5c595a3aa36 --- /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 00000000000..89773494e6e --- /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)