Skip to content

Commit 629ea53

Browse files
cknittclaude
andcommitted
Make modules named in @throws dependencies and name nested exceptions exactly
Why: Review of #9198: the type checker loads the module a @throws names, but the dependency scanner skipped attributes. A module named only there was built in any order, so the name resolved or got warning 113 depending on the build, and a later edit could fail with "inconsistent assumptions". Messages also named an exception defined in a nested module without that module, so the annotation they suggested did not resolve. And a library built with -no-keep-locs recorded its own exceptions with its file, while its users see them without one. `Depend` now adds the modules a @throws names, like any other use, so they are built first. A module that is both named in @throws and depends on the annotating module now gives a dependency cycle error. `Typemod` records which module of the current file defines each exception and module, so a file's own exception is named `Lib.Inner.F`. Under -no-keep-locs a file's own exceptions are identified by name alone also while it is compiled. Warning 113 is shown once for a `let` that destructures a tuple. Diagnostic modified (an exception of a nested module): Example: // ThrowsLibExn.res module Inner = { exception F @throws(F) external find: int => int = "findThrowing" } // ThrowsLibExnCalls.res let uncaughtNested = x => ThrowsLibExn.Inner.find(x) Before (reanalyze): tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExnCalls.res Exception Analysis ThrowsLibExnCalls.res:110:5-18 uncaughtNested might throw ThrowsLibExn.F (ThrowsLibExnCalls.res:110:26) and is not annotated with @throws(ThrowsLibExn.F) After (reanalyze): tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExnCalls.res Exception Analysis ThrowsLibExnCalls.res:110:5-18 uncaughtNested might throw ThrowsLibExn.Inner.F (ThrowsLibExnCalls.res:110:26) and is not annotated with @throws(ThrowsLibExn.Inner.F) Diagnostic modified (a module named only in @throws, tests/build_tests/throws_dependency): Example: // A.res @throws(Z.E) external find: int => int = "find" // Z.res exception E Before (diagnostic): A.res built before Z.res Warning number 113 @throws names Z.E, which is not an exception in scope here. Exception analysis cannot match it with the exceptions callers catch. After (diagnostic): Z.res built first, no warning Breaking: A module named in @throws that itself depends on the annotating module is now a dependency cycle. Move the exception to a module of its own. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Kbf3gHA54VKxsXvCQyC2vw Signed-off-by: Christoph Knittel <ck@cca.io>
1 parent 60f3830 commit 629ea53

12 files changed

Lines changed: 165 additions & 25 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
- A module named in `@throws` is now a dependency of the module that names it, so a dependency cycle through such a name is an error. Move the exception to a module of its own.

‎compiler/typing/depend.ml‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,15 @@ let add = add_parent
9595

9696
let addmodule bv lid = add_path bv lid.txt
9797

98+
(* The type checker looks up the exceptions a [@throws] names, so their
99+
modules are dependencies, as for any other use. *)
100+
let add_throws bv (attributes : Parsetree.attributes) =
101+
attributes
102+
|> List.iter (fun (({txt}, payload) : Parsetree.attribute) ->
103+
if txt = "throws" then
104+
Throws_attribute.names payload
105+
|> List.iter (fun (lid, loc) -> add bv {Location.txt = lid; loc}))
106+
98107
let handle_extension ext =
99108
match (fst ext).txt with
100109
| "error" ->
@@ -370,6 +379,7 @@ and add_case bv {pc_lhs; pc_guard; pc_rhs} =
370379
add_expr bv pc_rhs
371380

372381
and add_bindings recf bv pel =
382+
List.iter (fun x -> add_throws bv x.pvb_attributes) pel;
373383
let bv' = List.fold_left (fun bv x -> add_pattern bv x.pvb_pat) bv pel in
374384
let bv = if recf = Recursive then bv' else bv in
375385
List.iter (fun x -> add_expr bv x.pvb_expr) pel;
@@ -425,6 +435,7 @@ and add_sig_item (bv, m) item =
425435
match item.psig_desc with
426436
| Psig_value vd ->
427437
add_type bv vd.pval_type;
438+
add_throws bv vd.pval_attributes;
428439
(bv, m)
429440
| Psig_type (_, dcls) ->
430441
List.iter (add_type_declaration bv) dcls;
@@ -507,14 +518,16 @@ and add_structure_binding bv item_list =
507518

508519
and add_struct_item (bv, m) item : _ String_map.t * _ String_map.t =
509520
match item.pstr_desc with
510-
| Pstr_eval (e, _attrs) ->
521+
| Pstr_eval (e, attrs) ->
522+
add_throws bv attrs;
511523
add_expr bv e;
512524
(bv, m)
513525
| Pstr_value (rf, pel) ->
514526
let bv = add_bindings rf bv pel in
515527
(bv, m)
516528
| Pstr_primitive vd ->
517529
add_type bv vd.pval_type;
530+
add_throws bv vd.pval_attributes;
518531
(bv, m)
519532
| Pstr_type (_, dcls) ->
520533
List.iter (add_type_declaration bv) dcls;

‎compiler/typing/throws_attribute.ml‎

Lines changed: 58 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,26 @@
88

99
let generated = "res.throws"
1010

11-
(* An exception's identity: the source file that defines it, without its
12-
extension, and its name, as [src/Lib#E]. A module's .res and .resi share it,
13-
and it does not change when the definition moves within the file. Two
14-
exceptions of the same name in one file share it. Rebinding with
15-
[exception E = Lib.F] defines a new identity. A .cmi built with
16-
[-no-keep-locs], as the runtime's and Belt's are, has no locations, so
17-
its exceptions are identified by their name alone, as [#Undefined]. *)
11+
(* An exception's identity: the path of the source file that defines it, as
12+
the compiler was given it, without the extension, and its name, as
13+
[src/Lib#E]. A module's .res and .resi share it, and it does not change when
14+
the definition moves within the file. Exceptions of the same name in one
15+
file share it, as do the exceptions of two applications of one functor.
16+
Rebinding with [exception E = Lib.F] defines a new identity. A file
17+
compiled with [-no-keep-locs], as the runtime and Belt are, keeps no
18+
locations in its .cmi, so its exceptions are identified by their name
19+
alone, as [#Undefined], also while that file itself is compiled. *)
1820
let identity (cstr : Types.constructor_description) =
1921
match cstr.cstr_kind with
2022
| Extension_constructor (Pident id) when Ident.is_predef_exn id ->
2123
Some (Ident.name id)
2224
| Extension_constructor _ ->
2325
let file = cstr.cstr_loc.loc_start.pos_fname in
2426
let file =
25-
if file = Location.none.loc_start.pos_fname then ""
27+
if
28+
file = Location.none.loc_start.pos_fname
29+
|| not !((Clflags.current ()).keep_locs)
30+
then ""
2631
else Filename.remove_extension file
2732
in
2833
Some (file ^ "#" ^ cstr.cstr_name)
@@ -34,25 +39,58 @@ let without_namespace name =
3439
| Some i -> String.sub name 0 i
3540
| None -> name
3641

42+
(* Where the current file defines its modules and exceptions, as module paths
43+
within the file ([M; N; E] for [E] in [M.N]), and the module being typed.
44+
[Typemod] records them, so messages can name a file's own exceptions
45+
exactly. *)
46+
type definitions = {
47+
mutable current: string list; (** The module being typed, outermost first *)
48+
defined: (Ident.t, string list) Hashtbl.t;
49+
warned: (Location.t, unit) Hashtbl.t;
50+
(** Names already warned about: a [let] that destructures a tuple
51+
carries its attributes on every binding *)
52+
}
53+
54+
let definitions =
55+
Request_local.new_key (fun () ->
56+
{current = []; defined = Hashtbl.create 16; warned = Hashtbl.create 1})
57+
58+
(* Type the module [name] with [f], recording what it defines under [name]. *)
59+
let in_module name f =
60+
let d = Request_local.get definitions in
61+
let outer = d.current in
62+
d.current <- outer @ [name];
63+
Fun.protect ~finally:(fun () -> d.current <- outer) f
64+
65+
(* Record that the module being typed defines [id]. *)
66+
let define id =
67+
let d = Request_local.get definitions in
68+
Hashtbl.replace d.defined id (d.current @ [Ident.name id])
69+
3770
(* A readable name for messages: [Lib.E] for another module's exception,
38-
aliases resolved, and the current module's name in front of its own. *)
71+
aliases resolved, and [Lib.M.E] for one that the current file [Lib]
72+
defines in its module [M]. *)
3973
let display_name env (cstr : Types.constructor_description) =
74+
let unit = without_namespace (Env.get_unit_name ()) in
75+
let local id =
76+
match Hashtbl.find_opt (Request_local.get definitions).defined id with
77+
| Some path -> unit :: path
78+
| None -> [unit; Ident.name id]
79+
in
4080
match cstr.cstr_kind with
4181
| Extension_constructor (Pident id) when Ident.is_predef_exn id ->
4282
Ident.name id
83+
| Extension_constructor (Pident id) -> String.concat "." (local id)
4384
| Extension_constructor (Pdot (prefix, name, _)) -> (
4485
let prefix = Env.normalize_path None env prefix in
4586
match Path.flatten prefix with
4687
| `Ok (head, rest) ->
47-
let names = (without_namespace (Ident.name head) :: rest) @ [name] in
48-
let names =
49-
if Ident.persistent head then names
50-
else without_namespace (Env.get_unit_name ()) :: names
88+
let head =
89+
if Ident.persistent head then [without_namespace (Ident.name head)]
90+
else local head
5191
in
52-
String.concat "." names
92+
String.concat "." (head @ rest @ [name])
5393
| `Contains_apply -> Path.name prefix ^ "." ^ name)
54-
| Extension_constructor (Pident id) ->
55-
without_namespace (Env.get_unit_name ()) ^ "." ^ Ident.name id
5694
| Extension_constructor (Papply _ as path) -> Path.name path
5795
| Ordinary_constructor _ -> cstr.cstr_name
5896

@@ -101,7 +139,10 @@ let resolve env (attributes : Parsetree.attributes) =
101139
| Some entry -> entry
102140
| None ->
103141
let written = String.concat "." (Longident.flatten lid) in
104-
Loc_report.prerr_warning loc (Warnings.Bs_throws_unbound written);
142+
let warned = (Request_local.get definitions).warned in
143+
if not (Hashtbl.mem warned loc) then (
144+
Hashtbl.replace warned loc ();
145+
Loc_report.prerr_warning loc (Warnings.Bs_throws_unbound written));
105146
(written, written))
106147
in
107148
match resolved with

‎compiler/typing/typemod.ml‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -814,6 +814,10 @@ and transl_signature env sg =
814814
let tyext, newenv =
815815
Typedecl.transl_type_extension false env item.psig_loc styext
816816
in
817+
List.iter
818+
(fun (ext : Typedtree.extension_constructor) ->
819+
Throws_attribute.define ext.ext_id)
820+
tyext.tyext_constructors;
817821
let trem, rem, final_env = transl_sig newenv srem in
818822
let constructors = tyext.tyext_constructors in
819823
( mksig (Tsig_typext tyext) env loc :: trem,
@@ -824,16 +828,19 @@ and transl_signature env sg =
824828
| Psig_exception sext ->
825829
check_name check_typext names sext.pext_name;
826830
let ext, newenv = Typedecl.transl_exception env sext in
831+
Throws_attribute.define ext.ext_id;
827832
let trem, rem, final_env = transl_sig newenv srem in
828833
( mksig (Tsig_exception ext) env loc :: trem,
829834
Sig_typext (ext.ext_id, ext.ext_type, Text_exception) :: rem,
830835
final_env )
831836
| Psig_module pmd ->
832837
check_name check_module names pmd.pmd_name;
833838
let id = Ident.create pmd.pmd_name.txt in
839+
Throws_attribute.define id;
834840
let tmty =
835841
Builtin_attributes.warning_scope pmd.pmd_attributes (fun () ->
836-
transl_modtype env pmd.pmd_type)
842+
Throws_attribute.in_module pmd.pmd_name.txt (fun () ->
843+
transl_modtype env pmd.pmd_type))
837844
in
838845
let md =
839846
{
@@ -927,7 +934,10 @@ and transl_modtype_decl names env pmtd =
927934
and transl_modtype_decl_aux names env
928935
{pmtd_name; pmtd_type; pmtd_attributes; pmtd_loc} =
929936
check_name check_modtype names pmtd_name;
930-
let tmty = Option.map (transl_modtype env) pmtd_type in
937+
let tmty =
938+
Throws_attribute.in_module pmtd_name.txt (fun () ->
939+
Option.map (transl_modtype env) pmtd_type)
940+
in
931941
let decl =
932942
{
933943
Types.mtd_type = Option.map (fun t -> t.mty_type) tmty;
@@ -1546,6 +1556,10 @@ and type_structure funct_body anchor env sstr =
15461556
(fun pext -> check_name check_typext names pext.pext_name)
15471557
styext.ptyext_constructors;
15481558
let tyext, newenv = Typedecl.transl_type_extension true env loc styext in
1559+
List.iter
1560+
(fun (ext : Typedtree.extension_constructor) ->
1561+
Throws_attribute.define ext.ext_id)
1562+
tyext.tyext_constructors;
15491563
( Tstr_typext tyext,
15501564
map_ext
15511565
(fun es ext -> Sig_typext (ext.ext_id, ext.ext_type, es))
@@ -1554,6 +1568,7 @@ and type_structure funct_body anchor env sstr =
15541568
| Pstr_exception sext ->
15551569
check_name check_typext names sext.pext_name;
15561570
let ext, newenv = Typedecl.transl_exception env sext in
1571+
Throws_attribute.define ext.ext_id;
15571572
( Tstr_exception ext,
15581573
[Sig_typext (ext.ext_id, ext.ext_type, Text_exception)],
15591574
newenv )
@@ -1562,11 +1577,13 @@ and type_structure funct_body anchor env sstr =
15621577
check_name check_module names name;
15631578
let id = Ident.create name.txt in
15641579
(* create early for PR#6752 *)
1580+
Throws_attribute.define id;
15651581
let modl =
15661582
Builtin_attributes.warning_scope attrs (fun () ->
1567-
type_module ~alias:true true funct_body
1568-
(anchor_submodule name.txt anchor)
1569-
env smodl)
1583+
Throws_attribute.in_module name.txt (fun () ->
1584+
type_module ~alias:true true funct_body
1585+
(anchor_submodule name.txt anchor)
1586+
env smodl))
15701587
in
15711588
let md =
15721589
{

‎tests/analysis_tests/tests-reanalyze/deadcode/expected/exception.txt‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,5 +215,13 @@
215215
Exception Analysis
216216
ThrowsLibExnCalls.res:81:5-16
217217
catchRebound might throw ThrowsLibExn.E (ThrowsLibExnCalls.res:82:6) and is not annotated with @throws(ThrowsLibExn.E)
218+
219+
Exception Analysis
220+
ThrowsLibExnCalls.res:110:5-18
221+
uncaughtNested might throw ThrowsLibExn.Inner.F (ThrowsLibExnCalls.res:110:26) and is not annotated with @throws(ThrowsLibExn.Inner.F)
222+
223+
Exception Analysis
224+
ThrowsLibExnCalls.res:112:5-17
225+
uncaughtLocal might throw Local.G (ThrowsLibExnCalls.res:112:25) and is not annotated with @throws(Local.G)
218226

219-
Analysis reported 54 issues (Exception Analysis:54)
227+
Analysis reported 56 issues (Exception Analysis:56)

‎tests/analysis_tests/tests-reanalyze/deadcode/src/exception/ThrowsLibExnCalls.res‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,11 @@ module UseS = (X: ThrowsLibExn.S) => {
105105
| ThrowsLibExn.E => 0
106106
}
107107
}
108+
109+
// Reported with the exceptions' full names, which an annotation can use.
110+
let uncaughtNested = x => ThrowsLibExn.Inner.find(x)
111+
112+
let uncaughtLocal = x => Local.find(x)
113+
114+
@throws(Local.G)
115+
let annotatedLocal = x => Local.find(x)

‎tests/build_tests/super_errors/expected/throws_unbound_warning.res.expected‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,16 @@
2020
7 │ external g: int => int = "g"
2121
8 │
2222

23-
@throws names NotAnException, which is not an exception in scope here. Exception analysis cannot match it with the exceptions callers catch.
23+
@throws names NotAnException, which is not an exception in scope here. Exception analysis cannot match it with the exceptions callers catch.
24+
25+
26+
Warning number 113
27+
/.../fixtures/throws_unbound_warning.res:13:9-19
28+
29+
11 │
30+
12 │ // Warned once, though the pattern binds two names
31+
13 │ @throws(AlsoMissing)
32+
14 │ let (p, q) = (1, 2)
33+
15 │
34+
35+
@throws names AlsoMissing, which is not an exception in scope here. Exception analysis cannot match it with the exceptions callers catch.

‎tests/build_tests/super_errors/fixtures/throws_unbound_warning.res‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,10 @@ external g: int => int = "g"
88

99
@throws
1010
let h = () => 2
11+
12+
// Warned once, though the pattern binds two names
13+
@throws(AlsoMissing)
14+
let (p, q) = (1, 2)
15+
16+
@warning("-113") @throws(Silenced)
17+
let quiet = () => 3
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// @ts-check
2+
3+
// A module named only in a @throws is a dependency: the type checker looks
4+
// the exception up, so the module is built first and the name resolves.
5+
6+
import * as assert from "node:assert";
7+
import { stripVTControlCharacters } from "node:util";
8+
import { setup } from "#dev/process";
9+
10+
const { execBuild, execClean } = setup(import.meta.dirname);
11+
12+
await execClean();
13+
const output = await execBuild();
14+
const all = stripVTControlCharacters(output.stdout + output.stderr);
15+
16+
assert.equal(output.status, 0, all);
17+
assert.doesNotMatch(all, /Warning number 113/);
18+
await execClean();
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"name": "throws_dependency",
3+
"sources": ["src"],
4+
"package-specs": {
5+
"module": "esmodule",
6+
"in-source": true
7+
},
8+
"suffix": ".res.js",
9+
"dependencies": []
10+
}

0 commit comments

Comments
 (0)