Skip to content

Commit 9b3d665

Browse files
cknittclaude
andcommitted
Read @throws from library declarations in exception analysis
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. The type checker keeps a declaration's attributes in the `.cmi`, so an external or an interface `let` carries its `@throws` to calls in other modules and packages, through aliases, `open`, `include`, functors and first-class modules. The stdlib and Belt now declare what their throwing functions throw, and the table keeps only `Stdlib.panic` and `Stdlib.assertEqual`, whose `let`s in Stdlib.res (no interface) don't keep attributes in the signature, and the Yojson stub the tests use. 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`) when `f` is in the values table throws(`f`) = declared(`f`) ∪ table(`f`) otherwise 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: What happens to bs-json users? The bs-json entries are gone, so calls to `Json.Decode` functions are no longer reported until the library annotates them; no test covered those entries. Yojson stays because the tests use an unannotated stub of it. 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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Kbf3gGhHjzBTXqSo8Dckpb Signed-off-by: Christoph Knittel <ck@cca.io>
1 parent ac73578 commit 9b3d665

56 files changed

Lines changed: 441 additions & 224 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎analysis/reanalyze/src/exception.ml‎

Lines changed: 41 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -127,17 +127,21 @@ module Event = struct
127127
if config.Dce_config.cli.debug then Log_.item "%a@." print ev;
128128
exceptions |> Exceptions.iter (fun exn -> extend_exn_table exn loc);
129129
loop (Exceptions.union exn_set exceptions) rest
130-
| ({kind = Call {callee; module_path}; loc} as ev) :: rest ->
130+
| ({kind = Call {callee; module_path}; exceptions = declared; loc} as ev)
131+
:: rest ->
131132
if config.Dce_config.cli.debug then Log_.item "%a@." print ev;
133+
(* [declared] comes from the declaration's [@throws], the values table
134+
from the [@throws] of the implementation's binding. Both describe
135+
what the call can throw, so take both. *)
132136
let exceptions =
133137
match
134138
callee |> Values.find_path values_table ~module_name ~module_path
135139
with
136-
| Some exceptions -> exceptions
137-
| _ -> (
140+
| Some exceptions -> Exceptions.union declared exceptions
141+
| None -> (
138142
match Exn_lib.find callee with
139-
| Some exceptions -> exceptions
140-
| None -> Exceptions.empty)
143+
| Some exceptions -> Exceptions.union declared exceptions
144+
| None -> declared)
141145
in
142146
exceptions |> Exceptions.iter (fun exn -> extend_exn_table exn loc);
143147
loop (Exceptions.union exn_set exceptions) rest
@@ -280,7 +284,7 @@ let traverse_ast ~file ~values_builder ~checks_builder () =
280284
case.c_rhs |> iter_expr self)
281285
in
282286
let is_throw s = s = "Pervasives.raise" || s = "Pervasives.throw" in
283-
(* [/] and [mod] are listed in [Exn_lib] as throwing [Division_by_zero].
287+
(* [/] and [mod] are declared with [@throws(Division_by_zero)] in Pervasives.
284288
They cannot throw when the divisor is a non-zero literal, as in [x / 10]. *)
285289
let is_division s =
286290
s = "Pervasives./" || s = "Pervasives.mod" || s = "Stdlib./"
@@ -322,14 +326,40 @@ let traverse_ast ~file ~values_builder ~checks_builder () =
322326
| _ -> false)
323327
<> None
324328
in
329+
let get_exceptions_from_annotations attributes =
330+
let throws_annotation_payload =
331+
attributes
332+
|> Annotation.get_attribute_payload (fun s ->
333+
s = "throws" || s = "throw" || s = "raises" || s = "raise")
334+
in
335+
let rec get_exceptions payload =
336+
match payload with
337+
| Annotation.StringPayload s ->
338+
[Exn.from_string s] |> Exceptions.from_list
339+
| Annotation.ConstructPayload s when s <> "::" ->
340+
[Exn.from_string s] |> Exceptions.from_list
341+
| Annotation.IdentPayload s ->
342+
[Exn.from_string (s |> Longident.flatten |> String.concat ".")]
343+
|> Exceptions.from_list
344+
| Annotation.TuplePayload tuple ->
345+
tuple
346+
|> List.map (fun payload ->
347+
payload |> get_exceptions |> Exceptions.to_list)
348+
|> List.concat |> Exceptions.from_list
349+
| _ -> Exceptions.empty
350+
in
351+
match throws_annotation_payload with
352+
| None -> Exceptions.empty
353+
| Some payload -> payload |> get_exceptions
354+
in
325355
let expr ~(module_path : Module_path.t) (self : Tast_mapper.mapper)
326356
(expr : Typedtree.expression) =
327357
let loc = expr.exp_loc in
328358
let is_does_no_throw = expr.exp_attributes |> does_not_throw in
329359
let old_events = !current_events in
330360
if is_does_no_throw then current_events := [];
331361
(match expr.exp_desc with
332-
| Texp_ident (callee_, _, _) ->
362+
| Texp_ident (callee_, _, vd) ->
333363
let callee =
334364
callee_ |> Dce_path.from_path_t |> Module_path.resolve_alias module_path
335365
in
@@ -343,9 +373,12 @@ let traverse_ast ~file ~values_builder ~checks_builder () =
343373
"@{<info>%s@} can be analyzed only if called directly"
344374
(callee_name |> Name.to_string);
345375
});
376+
(* A [@throws] on the declaration (an external, a [let] in an
377+
interface, or a library's) is kept in the .cmi, so it reaches calls
378+
from other modules and packages. *)
346379
current_events :=
347380
{
348-
Event.exceptions = Exceptions.empty;
381+
Event.exceptions = get_exceptions_from_annotations vd.val_attributes;
349382
loc;
350383
kind = Call {callee; module_path = module_path.path};
351384
}
@@ -423,32 +456,6 @@ let traverse_ast ~file ~values_builder ~checks_builder () =
423456
:: old_events);
424457
expr
425458
in
426-
let get_exceptions_from_annotations attributes =
427-
let throws_annotation_payload =
428-
attributes
429-
|> Annotation.get_attribute_payload (fun s ->
430-
s = "throws" || s = "throw" || s = "raises" || s = "raise")
431-
in
432-
let rec get_exceptions payload =
433-
match payload with
434-
| Annotation.StringPayload s ->
435-
[Exn.from_string s] |> Exceptions.from_list
436-
| Annotation.ConstructPayload s when s <> "::" ->
437-
[Exn.from_string s] |> Exceptions.from_list
438-
| Annotation.IdentPayload s ->
439-
[Exn.from_string (s |> Longident.flatten |> String.concat ".")]
440-
|> Exceptions.from_list
441-
| Annotation.TuplePayload tuple ->
442-
tuple
443-
|> List.map (fun payload ->
444-
payload |> get_exceptions |> Exceptions.to_list)
445-
|> List.concat |> Exceptions.from_list
446-
| _ -> Exceptions.empty
447-
in
448-
match throws_annotation_payload with
449-
| None -> Exceptions.empty
450-
| Some payload -> payload |> get_exceptions
451-
in
452459
let toplevel_eval (self : Tast_mapper.mapper) (expr : Typedtree.expression)
453460
attributes =
454461
let old_id = !current_id in

‎analysis/reanalyze/src/exn.ml‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,8 @@
11
type t = string
22

33
let compare = String.compare
4-
let decode_error = "DecodeError"
5-
let assert_failure = "Assert_failure"
6-
let division_by_zero = "Division_by_zero"
7-
let invalid_argument = "Invalid_argument"
84
let js_exn = "JsExn"
95
let match_failure = "Match_failure"
10-
let not_found = "Not_found"
116
let from_lid lid = lid |> Longident.flatten |> String.concat "."
127
let from_string s = s
138
let to_string s = s

‎analysis/reanalyze/src/exn.mli‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,10 @@
11
type t
22

33
val compare : t -> t -> int
4-
val assert_failure : t
5-
val decode_error : t
6-
val division_by_zero : t
74
val from_lid : Longident.t -> t
85
val from_string : string -> t
9-
val invalid_argument : t
106
val js_exn : t
117
val match_failure : t
12-
val not_found : t
138
val to_string : t -> string
149
val yojson_json_error : t
1510
val yojson_type_error : t

‎analysis/reanalyze/src/exn_lib.ml‎

Lines changed: 7 additions & 165 deletions
Original file line numberDiff line numberDiff line change
@@ -1,99 +1,13 @@
1+
(* Library functions that throw but can't say so with a [@throws] on their
2+
declaration, which the analysis reads at each call site:
3+
- [Stdlib.panic] and [Stdlib.assertEqual] are [let]s in Stdlib.res, which
4+
has no interface, and the type checker doesn't keep the attributes of a
5+
[let] binding in the module's signature.
6+
- Yojson is an OCaml library, kept for the tests that use a stub of it. *)
17
let raises_lib_table : (Name.t, Exceptions.t) Hashtbl.t =
28
let table = Hashtbl.create 15 in
39
let open Exn in
4-
let belt_array =
5-
[
6-
("getExn", [assert_failure]);
7-
("getOrThrow", [assert_failure]);
8-
("setExn", [assert_failure]);
9-
("setOrThrow", [assert_failure]);
10-
]
11-
in
12-
let belt_list =
13-
[
14-
("getExn", [not_found]);
15-
("getOrThrow", [not_found]);
16-
("headExn", [not_found]);
17-
("headOrThrow", [not_found]);
18-
("tailExn", [not_found]);
19-
("tailOrThrow", [not_found]);
20-
]
21-
in
22-
let belt_map = [("getExn", [not_found]); ("getOrThrow", [not_found])] in
23-
let belt_mutable_map = belt_map in
24-
let belt_mutable_queue =
25-
[
26-
("peekExn", [not_found]);
27-
("peekOrThrow", [not_found]);
28-
("popExn", [not_found]);
29-
("popOrThrow", [not_found]);
30-
]
31-
in
32-
let belt_set = [("getExn", [not_found]); ("getOrThrow", [not_found])] in
33-
let belt_mutable_set = belt_set in
34-
let belt_option = [("getExn", [not_found]); ("getOrThrow", [not_found])] in
35-
let belt_result = [("getExn", [not_found]); ("getOrThrow", [not_found])] in
36-
let bs_json =
37-
(* bs-json *)
38-
[
39-
("bool", [decode_error]);
40-
("float", [decode_error]);
41-
("int", [decode_error]);
42-
("string", [decode_error]);
43-
("char", [decode_error]);
44-
("date", [decode_error]);
45-
("nullable", [decode_error]);
46-
("nullAs", [decode_error]);
47-
("array", [decode_error]);
48-
("list", [decode_error]);
49-
("pair", [decode_error]);
50-
("tuple2", [decode_error]);
51-
("tuple3", [decode_error]);
52-
("tuple4", [decode_error]);
53-
("dict", [decode_error]);
54-
("field", [decode_error]);
55-
("at", [decode_error; invalid_argument]);
56-
("oneOf", [decode_error]);
57-
("either", [decode_error]);
58-
]
59-
in
60-
let stdlib =
61-
[
62-
("panic", [js_exn]);
63-
("assertEqual", [js_exn]);
64-
("/", [division_by_zero]);
65-
("mod", [division_by_zero]);
66-
]
67-
in
68-
let stdlib_big_int =
69-
[("fromStringOrThrow", [js_exn]); ("fromFloatOrThrow", [js_exn])]
70-
in
71-
let stdlib_bool = [("fromStringOrThrow", [invalid_argument])] in
72-
let stdlib_js_error =
73-
[
74-
("EvalError.throwWithMessage", [js_exn]);
75-
("RangeError.throwWithMessage", [js_exn]);
76-
("ReferenceError.throwWithMessage", [js_exn]);
77-
("SyntaxError.throwWithMessage", [js_exn]);
78-
("TypeError.throwWithMessage", [js_exn]);
79-
("URIError.throwWithMessage", [js_exn]);
80-
("panic", [js_exn]);
81-
("throw", [js_exn]);
82-
("throwWithMessage", [js_exn]);
83-
]
84-
in
85-
let stdlib_json = [("parseOrThrow", [js_exn]); ("stringifyAny", [js_exn])] in
86-
let stdlib_list =
87-
[
88-
("headOrThrow", [not_found]);
89-
("tailOrThrow", [not_found]);
90-
("getOrThrow", [not_found]);
91-
]
92-
in
93-
let stdlib_null = [("getOrThrow", [invalid_argument])] in
94-
let stdlib_nullable = [("getOrThrow", [invalid_argument])] in
95-
let stdlib_option = [("getOrThrow", [js_exn])] in
96-
let stdlib_result = [("getOrThrow", [js_exn])] in
10+
let stdlib = [("panic", [js_exn]); ("assertEqual", [js_exn])] in
9711
let yojson_basic = [("from_string", [yojson_json_error])] in
9812
let yojson_basic_util =
9913
[
@@ -112,79 +26,7 @@ let raises_lib_table : (Name.t, Exceptions.t) Hashtbl.t =
11226
]
11327
in
11428
[
115-
("Belt.Array", belt_array);
116-
("Belt_Array", belt_array);
117-
("Belt.List", belt_list);
118-
("Belt_List", belt_list);
119-
("Belt.Map", belt_map);
120-
("Belt.Map.Int", belt_map);
121-
("Belt.Map.String", belt_map);
122-
("Belt_Map", belt_map);
123-
("Belt_Map.Int", belt_map);
124-
("Belt_Map.String", belt_map);
125-
("Belt_MapInt", belt_map);
126-
("Belt_MapString", belt_map);
127-
("Belt.MutableMap", belt_mutable_map);
128-
("Belt.MutableMap.Int", belt_mutable_map);
129-
("Belt.MutableMap.String", belt_mutable_map);
130-
("Belt_MutableMap", belt_mutable_map);
131-
("Belt_MutableMap.Int", belt_mutable_map);
132-
("Belt_MutableMap.String", belt_mutable_map);
133-
("Belt_MutableMapInt", belt_mutable_map);
134-
("Belt_MutableMapString", belt_mutable_map);
135-
("Belt.MutableQueue", belt_mutable_queue);
136-
("Belt_MutableQueue", belt_mutable_queue);
137-
("Belt_MutableSetInt", belt_mutable_set);
138-
("Belt_MutableSetString", belt_mutable_set);
139-
("Belt.MutableSet", belt_mutable_set);
140-
("Belt.MutableSet.Int", belt_mutable_set);
141-
("Belt.MutableSet.String", belt_mutable_set);
142-
("Belt.Option", belt_option);
143-
("Belt_Option", belt_option);
144-
("Belt.Result", belt_result);
145-
("Belt_Result", belt_result);
146-
("Belt.Set", belt_set);
147-
("Belt.Set.Int", belt_set);
148-
("Belt.Set.String", belt_set);
149-
("Belt_Set", belt_set);
150-
("Belt_Set.Int", belt_set);
151-
("Belt_Set.String", belt_set);
152-
("Belt_SetInt", belt_set);
153-
("Belt_SetString", belt_set);
154-
("BigInt", stdlib_big_int);
155-
("Bool", stdlib_bool);
156-
("JsError", stdlib_js_error);
157-
("JSON", stdlib_json);
158-
("Json_decode", bs_json);
159-
("Json.Decode", bs_json);
160-
("List", stdlib_list);
161-
("MutableSet", belt_mutable_set);
162-
("MutableSet.Int", belt_mutable_set);
163-
("MutableSet.String", belt_mutable_set);
164-
("Null", stdlib_null);
165-
("Nullable", stdlib_nullable);
166-
("Option", stdlib_option);
167-
("Pervasives", stdlib);
168-
("Result", stdlib_result);
16929
("Stdlib", stdlib);
170-
("Stdlib_BigInt", stdlib_big_int);
171-
("Stdlib.BigInt", stdlib_big_int);
172-
("Stdlib_Bool", stdlib_bool);
173-
("Stdlib.Bool", stdlib_bool);
174-
("Stdlib_JsError", stdlib_js_error);
175-
("Stdlib.JsError", stdlib_js_error);
176-
("Stdlib_JSON", stdlib_json);
177-
("Stdlib.JSON", stdlib_json);
178-
("Stdlib_List", stdlib_list);
179-
("Stdlib.List", stdlib_list);
180-
("Stdlib_Null", stdlib_null);
181-
("Stdlib.Null", stdlib_null);
182-
("Stdlib_Nullable", stdlib_nullable);
183-
("Stdlib.Nullable", stdlib_nullable);
184-
("Stdlib_Option", stdlib_option);
185-
("Stdlib.Option", stdlib_option);
186-
("Stdlib_Result", stdlib_result);
187-
("Stdlib.Result", stdlib_result);
18830
("Yojson.Basic", yojson_basic);
18931
("Yojson.Basic.Util", yojson_basic_util);
19032
]
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
- Exception analysis reads `@throws` from library and external declarations, including third-party ones, instead of a built-in list of stdlib and Belt functions, which now declare what they throw.

‎packages/@rescript/belt/src/Belt_Array.resi‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,14 @@ let get: (t<'a>, int) => option<'a>
4242
Throw an exception if `i` is out of range.
4343
Otherwise return the value at index `i` in `arr`.
4444
*/
45+
@throws(Assert_failure)
4546
let getExn: (t<'a>, int) => 'a
4647

4748
/**
4849
Throw an exception if `i` is out of range.
4950
Otherwise return the value at index `i` in `arr`.
5051
*/
52+
@throws(Assert_failure)
5153
let getOrThrow: (t<'a>, int) => 'a
5254

5355
/**
@@ -68,11 +70,13 @@ let set: (t<'a>, int, 'a) => bool
6870
/**
6971
`setExn(arr, i, x)` throw an exception if `i` is out of range.
7072
*/
73+
@throws(Assert_failure)
7174
let setExn: (t<'a>, int, 'a) => unit
7275

7376
/**
7477
`setOrThrow(arr, i, x)` throw an exception if `i` is out of range.
7578
*/
79+
@throws(Assert_failure)
7680
let setOrThrow: (t<'a>, int, 'a) => unit
7781

7882
external setUnsafe: (t<'a>, int, 'a) => unit = "%array_unsafe_set"

0 commit comments

Comments
 (0)